blob: 922ef0a4fd4cf1b5f4a7517324d64d2f7b43eb80 [file] [log] [blame]
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001/*
2**
3** Copyright 2018, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17#define LOG_TAG "keymaster_worker"
18
19#include "keymaster_worker.h"
20
21#include "keystore_utils.h"
22
23#include <android-base/logging.h>
24
25#include "KeyStore.h"
26#include "keymaster_enforcement.h"
27
28#include "key_proto_handler.h"
29#include "keystore_utils.h"
30
31namespace keystore {
32
33constexpr size_t kMaxOperations = 15;
34
35using AndroidKeymasterArguments = android::security::keymaster::KeymasterArguments;
36using android::security::keymaster::ExportResult;
37using android::security::keymaster::operationFailed;
38using android::security::keymaster::OperationResult;
39
Janis Danisevskis5ec4c2a2018-11-12 10:39:48 -080040Worker::Worker() {}
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070041Worker::~Worker() {
Janis Danisevskis5ec4c2a2018-11-12 10:39:48 -080042 std::unique_lock<std::mutex> lock(pending_requests_mutex_);
43 pending_requests_cond_var_.wait(lock, [this] { return pending_requests_.empty(); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070044}
45void Worker::addRequest(WorkerTask request) {
46 std::unique_lock<std::mutex> lock(pending_requests_mutex_);
Janis Danisevskis5ec4c2a2018-11-12 10:39:48 -080047 bool start_thread = pending_requests_.empty();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070048 pending_requests_.push(std::move(request));
49 lock.unlock();
Janis Danisevskis5ec4c2a2018-11-12 10:39:48 -080050 if (start_thread) {
51 auto worker = std::thread([this] {
52 std::unique_lock<std::mutex> lock(pending_requests_mutex_);
53 running_ = true;
54 while (!pending_requests_.empty()) {
55 auto request = std::move(pending_requests_.front());
56 lock.unlock();
57 request();
58 lock.lock();
59 pending_requests_.pop();
60 pending_requests_cond_var_.notify_all();
61 }
62 });
63 worker.detach();
64 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070065}
66
67KeymasterWorker::KeymasterWorker(sp<Keymaster> keymasterDevice, KeyStore* keyStore)
68 : keymasterDevice_(std::move(keymasterDevice)), operationMap_(keyStore), keyStore_(keyStore) {
69 // make sure that hal version is cached.
70 if (keymasterDevice_) keymasterDevice_->halVersion();
71}
72
Janis Danisevskisa359c672019-03-14 17:15:06 -070073void KeymasterWorker::logIfKeymasterVendorError(ErrorCode ec) const {
74 keymasterDevice_->logIfKeymasterVendorError(ec);
75}
76
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070077std::tuple<KeyStoreServiceReturnCode, Blob>
78KeymasterWorker::upgradeKeyBlob(const LockedKeyBlobEntry& lockedEntry,
79 const AuthorizationSet& params) {
80 LOG(INFO) << "upgradeKeyBlob " << lockedEntry->alias() << " " << (uint32_t)lockedEntry->uid();
81
82 std::tuple<KeyStoreServiceReturnCode, Blob> result;
83
84 auto userState = keyStore_->getUserStateDB().getUserStateByUid(lockedEntry->uid());
85
86 Blob& blob = std::get<1>(result);
87 KeyStoreServiceReturnCode& error = std::get<0>(result);
88
89 Blob charBlob;
90 ResponseCode rc;
91
92 std::tie(rc, blob, charBlob) =
93 lockedEntry.readBlobs(userState->getEncryptionKey(), userState->getState());
94
Janis Danisevskis265435f2018-11-16 14:10:46 -080095 userState = {};
96
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070097 if (rc != ResponseCode::NO_ERROR) {
98 return error = rc, result;
99 }
100
101 auto hidlKey = blob2hidlVec(blob);
102 auto& dev = keymasterDevice_;
103
104 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& upgradedKeyBlob) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700105 dev->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700106 error = ret;
107 if (!error.isOk()) {
108 if (error == ErrorCode::INVALID_KEY_BLOB) {
109 log_key_integrity_violation(lockedEntry->alias().c_str(), lockedEntry->uid());
110 }
111 return;
112 }
113
114 error = keyStore_->del(lockedEntry);
115 if (!error.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800116 ALOGI("upgradeKeyBlob keystore->del failed %d", error.getErrorCode());
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700117 return;
118 }
119
120 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
121 0 /* infoLength */, ::TYPE_KEYMASTER_10);
122 newBlob.setSecurityLevel(blob.getSecurityLevel());
123 newBlob.setEncrypted(blob.isEncrypted());
124 newBlob.setSuperEncrypted(blob.isSuperEncrypted());
125 newBlob.setCriticalToDeviceEncryption(blob.isCriticalToDeviceEncryption());
126
127 error = keyStore_->put(lockedEntry, newBlob, charBlob);
128 if (!error.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800129 ALOGI("upgradeKeyBlob keystore->put failed %d", error.getErrorCode());
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700130 return;
131 }
132 blob = std::move(newBlob);
133 };
134
135 KeyStoreServiceReturnCode error2;
Janis Danisevskisa359c672019-03-14 17:15:06 -0700136 error2 = KS_HANDLE_HIDL_ERROR(dev, dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700137 if (!error2.isOk()) {
138 return error = error2, result;
139 }
140
141 return result;
142}
143
144std::tuple<KeyStoreServiceReturnCode, KeyCharacteristics, Blob, Blob>
145KeymasterWorker::createKeyCharacteristicsCache(const LockedKeyBlobEntry& lockedEntry,
146 const hidl_vec<uint8_t>& clientId,
147 const hidl_vec<uint8_t>& appData, Blob keyBlob,
148 Blob charBlob) {
149 std::tuple<KeyStoreServiceReturnCode, KeyCharacteristics, Blob, Blob> result;
150
151#if __cplusplus == 201703L
152 auto& [rc, resultCharacteristics, outBlob, charOutBlob] = result;
153#else
154 KeyStoreServiceReturnCode& rc = std::get<0>(result);
155 KeyCharacteristics& resultCharacteristics = std::get<1>(result);
156 Blob& outBlob = std::get<2>(result);
157 Blob& charOutBlob = std::get<3>(result);
158#endif
159
160 rc = ResponseCode::SYSTEM_ERROR;
161 if (!keyBlob) return result;
162 auto hidlKeyBlob = blob2hidlVec(keyBlob);
163 auto& dev = keymasterDevice_;
164
165 KeyStoreServiceReturnCode error;
166
167 AuthorizationSet hwEnforced, swEnforced;
168 bool success = true;
169
170 if (charBlob) {
171 std::tie(success, hwEnforced, swEnforced) = charBlob.getKeyCharacteristics();
172 }
173 if (!success) {
174 LOG(ERROR) << "Failed to read cached key characteristics";
175 return rc = ResponseCode::SYSTEM_ERROR, result;
176 }
177
178 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700179 dev->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700180 error = ret;
181 if (!error.isOk()) {
182 if (error == ErrorCode::INVALID_KEY_BLOB) {
183 log_key_integrity_violation(lockedEntry->alias().c_str(), lockedEntry->uid());
184 }
185 return;
186 }
187
188 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
189 AuthorizationSet softwareEnforced = keyCharacteristics.softwareEnforced;
190 hwEnforced = keyCharacteristics.hardwareEnforced;
191 swEnforced.Union(softwareEnforced);
192 softwareEnforced.Subtract(hwEnforced);
193
194 // We only get the characteristics from keymaster if there was no cache file or the
195 // the chach file was a legacy cache file. So lets write a new cache file for the next time.
196 Blob newCharBlob;
197 success = newCharBlob.putKeyCharacteristics(hwEnforced, swEnforced);
198 if (!success) {
199 error = ResponseCode::SYSTEM_ERROR;
200 LOG(ERROR) << "Failed to serialize cached key characteristics";
201 return;
202 }
203
204 error = keyStore_->put(lockedEntry, {}, newCharBlob);
205 if (!error.isOk()) {
206 ALOGE("Failed to write key characteristics cache");
207 return;
208 }
209 charBlob = std::move(newCharBlob);
210 };
211
212 if (!charBlob || charBlob.getType() == TYPE_KEY_CHARACTERISTICS) {
213 // this updates the key characteristics cache file to the new format or creates one in
214 // in the first place
215 rc = KS_HANDLE_HIDL_ERROR(
Janis Danisevskisa359c672019-03-14 17:15:06 -0700216 dev, dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700217 if (!rc.isOk()) {
218 return result;
219 }
220
221 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
222 AuthorizationSet upgradeParams;
223 if (clientId.size()) {
224 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
225 }
226 if (appData.size()) {
227 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
228 }
229 std::tie(rc, keyBlob) = upgradeKeyBlob(lockedEntry, upgradeParams);
230 if (!rc.isOk()) {
231 return result;
232 }
233
234 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
235
236 rc = KS_HANDLE_HIDL_ERROR(
Janis Danisevskisa359c672019-03-14 17:15:06 -0700237 dev, dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700238 if (!rc.isOk()) {
239 return result;
240 }
241 }
242 }
243
244 resultCharacteristics.hardwareEnforced = hwEnforced.hidl_data();
245 resultCharacteristics.softwareEnforced = swEnforced.hidl_data();
246
247 outBlob = std::move(keyBlob);
248 charOutBlob = std::move(charBlob);
249 rc = error;
250 return result;
251}
252
253/**
254 * Get the auth token for this operation from the auth token table.
255 *
256 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
257 * ::OP_AUTH_NEEDED if it is a per op authorization, no
258 * authorization token exists for that operation and
259 * failOnTokenMissing is false.
260 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
261 * token for the operation
262 */
263std::pair<KeyStoreServiceReturnCode, HardwareAuthToken>
264KeymasterWorker::getAuthToken(const KeyCharacteristics& characteristics, uint64_t handle,
265 KeyPurpose purpose, bool failOnTokenMissing) {
266
267 AuthorizationSet allCharacteristics(characteristics.softwareEnforced);
268 allCharacteristics.append(characteristics.hardwareEnforced.begin(),
269 characteristics.hardwareEnforced.end());
270
271 HardwareAuthToken authToken;
272 AuthTokenTable::Error err;
273 std::tie(err, authToken) = keyStore_->getAuthTokenTable().FindAuthorization(
274 allCharacteristics, static_cast<KeyPurpose>(purpose), handle);
275
276 KeyStoreServiceReturnCode rc;
277
278 switch (err) {
279 case AuthTokenTable::OK:
280 case AuthTokenTable::AUTH_NOT_REQUIRED:
281 rc = ResponseCode::NO_ERROR;
282 break;
283
284 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
285 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
286 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
287 ALOGE("getAuthToken failed: %d", err); // STOPSHIP: debug only, to be removed
288 rc = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
289 break;
290
291 case AuthTokenTable::OP_HANDLE_REQUIRED:
292 rc = failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
293 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
294 break;
295
296 default:
297 ALOGE("Unexpected FindAuthorization return value %d", err);
298 rc = ErrorCode::INVALID_ARGUMENT;
299 }
300
301 return {rc, std::move(authToken)};
302}
303
304KeyStoreServiceReturnCode KeymasterWorker::abort(const sp<IBinder>& token) {
305 auto op = operationMap_.removeOperation(token, false /* wasOpSuccessful */);
306 if (op) {
307 keyStore_->getAuthTokenTable().MarkCompleted(op->handle);
Janis Danisevskisa359c672019-03-14 17:15:06 -0700308 return KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->abort(op->handle));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700309 } else {
310 return ErrorCode::INVALID_OPERATION_HANDLE;
311 }
312}
313
314/**
315 * Prune the oldest pruneable operation.
316 */
317bool KeymasterWorker::pruneOperation() {
318 sp<IBinder> oldest = operationMap_.getOldestPruneableOperation();
319 ALOGD("Trying to prune operation %p", oldest.get());
320 size_t op_count_before_abort = operationMap_.getOperationCount();
321 // We mostly ignore errors from abort() because all we care about is whether at least
322 // one operation has been removed.
323 auto rc = abort(oldest);
324 if (operationMap_.getOperationCount() >= op_count_before_abort) {
Branden Archer70080742018-11-20 11:04:11 -0800325 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), rc.getErrorCode());
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700326 return false;
327 }
328 return true;
329}
330
331// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
332// It should never be redefined by a build system though.
333#ifndef CAPTURE_MOVE
334#define CAPTURE_MOVE(x) x = std::move(x)
335#endif
336
337void KeymasterWorker::begin(LockedKeyBlobEntry lockedEntry, sp<IBinder> appToken, Blob keyBlob,
338 Blob charBlob, bool pruneable, KeyPurpose purpose,
339 AuthorizationSet opParams, hidl_vec<uint8_t> entropy,
340 worker_begin_cb worker_cb) {
341
342 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), CAPTURE_MOVE(appToken),
343 CAPTURE_MOVE(keyBlob), CAPTURE_MOVE(charBlob), pruneable, purpose,
344 CAPTURE_MOVE(opParams), CAPTURE_MOVE(entropy),
345 CAPTURE_MOVE(worker_cb)]() mutable {
346 // Concurrently executed
347
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700348 auto& dev = keymasterDevice_;
349
350 KeyCharacteristics characteristics;
351
352 {
353 hidl_vec<uint8_t> clientId;
354 hidl_vec<uint8_t> appData;
Chih-Hung Hsiehb3bfdb02018-12-12 14:43:33 -0800355 for (const auto& param : opParams) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700356 if (param.tag == Tag::APPLICATION_ID) {
357 clientId = authorizationValue(TAG_APPLICATION_ID, param).value();
358 } else if (param.tag == Tag::APPLICATION_DATA) {
359 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
360 }
361 }
362 KeyStoreServiceReturnCode error;
363 std::tie(error, characteristics, keyBlob, charBlob) = createKeyCharacteristicsCache(
364 lockedEntry, clientId, appData, std::move(keyBlob), std::move(charBlob));
365 if (!error.isOk()) {
366 worker_cb(operationFailed(error));
367 return;
368 }
369 }
370
371 KeyStoreServiceReturnCode rc, authRc;
372 HardwareAuthToken authToken;
373 std::tie(authRc, authToken) = getAuthToken(characteristics, 0 /* no challenge */, purpose,
374 /*failOnTokenMissing*/ false);
375
376 // If per-operation auth is needed we need to begin the operation and
377 // the client will need to authorize that operation before calling
378 // update. Any other auth issues stop here.
379 if (!authRc.isOk() && authRc != ResponseCode::OP_AUTH_NEEDED) {
380 return worker_cb(operationFailed(authRc));
381 }
382
383 // Add entropy to the device first.
384 if (entropy.size()) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700385 rc = KS_HANDLE_HIDL_ERROR(dev, dev->addRngEntropy(entropy));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700386 if (!rc.isOk()) {
387 return worker_cb(operationFailed(rc));
388 }
389 }
390
391 // Create a keyid for this key.
Janis Danisevskis64eb3eb2018-11-27 20:41:52 -0800392 auto keyid = KeymasterEnforcement::CreateKeyId(blob2hidlVec(keyBlob));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700393 if (!keyid) {
394 ALOGE("Failed to create a key ID for authorization checking.");
395 return worker_cb(operationFailed(ErrorCode::UNKNOWN_ERROR));
396 }
397
398 // Check that all key authorization policy requirements are met.
399 AuthorizationSet key_auths = characteristics.hardwareEnforced;
400 key_auths.append(characteristics.softwareEnforced.begin(),
401 characteristics.softwareEnforced.end());
402
403 rc = keyStore_->getEnforcementPolicy().AuthorizeOperation(
404 purpose, *keyid, key_auths, opParams, authToken, 0 /* op_handle */,
405 true /* is_begin_operation */);
406 if (!rc.isOk()) {
407 return worker_cb(operationFailed(rc));
408 }
409
410 // If there are more than kMaxOperations, abort the oldest operation that was started as
411 // pruneable.
412 while (operationMap_.getOperationCount() >= kMaxOperations) {
413 ALOGD("Reached or exceeded concurrent operations limit");
414 if (!pruneOperation()) {
415 break;
416 }
417 }
418
419 android::security::keymaster::OperationResult result;
420
421 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
422 uint64_t operationHandle) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700423 dev->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700424 result.resultCode = ret;
425 if (!result.resultCode.isOk()) {
426 if (result.resultCode == ErrorCode::INVALID_KEY_BLOB) {
427 log_key_integrity_violation(lockedEntry->alias().c_str(), lockedEntry->uid());
428 }
429 return;
430 }
431 result.handle = operationHandle;
432 result.outParams = outParams;
433 };
434
435 do {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700436 rc = KS_HANDLE_HIDL_ERROR(dev, dev->begin(purpose, blob2hidlVec(keyBlob),
437 opParams.hidl_data(), authToken, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700438 if (!rc.isOk()) {
439 LOG(ERROR) << "Got error " << rc << " from begin()";
440 return worker_cb(operationFailed(ResponseCode::SYSTEM_ERROR));
441 }
Janis Danisevskis64eb3eb2018-11-27 20:41:52 -0800442
443 if (result.resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
444 std::tie(rc, keyBlob) = upgradeKeyBlob(lockedEntry, opParams);
445 if (!rc.isOk()) {
446 return worker_cb(operationFailed(rc));
447 }
448
Janis Danisevskisa359c672019-03-14 17:15:06 -0700449 rc = KS_HANDLE_HIDL_ERROR(dev, dev->begin(purpose, blob2hidlVec(keyBlob),
450 opParams.hidl_data(), authToken, hidlCb));
Janis Danisevskis64eb3eb2018-11-27 20:41:52 -0800451 if (!rc.isOk()) {
452 LOG(ERROR) << "Got error " << rc << " from begin()";
453 return worker_cb(operationFailed(ResponseCode::SYSTEM_ERROR));
454 }
455 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700456 // If there are too many operations abort the oldest operation that was
457 // started as pruneable and try again.
458 } while (result.resultCode == ErrorCode::TOO_MANY_OPERATIONS && pruneOperation());
459
460 rc = result.resultCode;
461 if (!rc.isOk()) {
462 return worker_cb(operationFailed(rc));
463 }
464
465 // Note: The operation map takes possession of the contents of "characteristics".
466 // It is safe to use characteristics after the following line but it will be empty.
467 sp<IBinder> operationToken =
468 operationMap_.addOperation(result.handle, *keyid, purpose, dev, appToken,
469 std::move(characteristics), opParams.hidl_data(), pruneable);
470 assert(characteristics.hardwareEnforced.size() == 0);
471 assert(characteristics.softwareEnforced.size() == 0);
472 result.token = operationToken;
473
474 auto operation = operationMap_.getOperation(operationToken);
475 if (!operation) {
476 return worker_cb(operationFailed(ResponseCode::SYSTEM_ERROR));
477 }
478
479 if (authRc.isOk() && authToken.mac.size() &&
480 dev->halVersion().securityLevel == SecurityLevel::STRONGBOX) {
481 operation->authTokenFuture = operation->authTokenPromise.get_future();
482 std::weak_ptr<Operation> weak_operation = operation;
483
484 auto verifyTokenCB = [weak_operation](KeyStoreServiceReturnCode rc,
485 HardwareAuthToken authToken,
486 VerificationToken verificationToken) {
487 auto operation = weak_operation.lock();
488 if (!operation) {
489 // operation aborted, nothing to do
490 return;
491 }
492 if (rc.isOk()) {
493 operation->authToken = std::move(authToken);
494 operation->verificationToken = std::move(verificationToken);
495 }
496 operation->authTokenPromise.set_value(rc);
497 };
498 auto teeKmDevice = keyStore_->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
499 teeKmDevice->verifyAuthorization(result.handle, {}, std::move(authToken),
500 std::move(verifyTokenCB));
501 }
502
503 // Return the authentication lookup result. If this is a per operation
504 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
505 // application should get an auth token using the handle before the
506 // first call to update, which will fail if keystore hasn't received the
507 // auth token.
508 if (result.resultCode.isOk()) {
509 result.resultCode = authRc;
510 }
511 return worker_cb(result);
512 });
513}
514
515KeyStoreServiceReturnCode
516KeymasterWorker::getOperationAuthTokenIfNeeded(std::shared_ptr<Operation> op) {
517 if (!op) return ErrorCode::INVALID_OPERATION_HANDLE;
518
519 if (op->authTokenFuture.valid()) {
520 LOG(INFO) << "Waiting for verification token";
521 op->authTokenFuture.wait();
522 auto rc = op->authTokenFuture.get();
523 if (!rc.isOk()) {
524 return rc;
525 }
526 op->authTokenFuture = {};
527 } else if (!op->hasAuthToken()) {
528 KeyStoreServiceReturnCode rc;
529 HardwareAuthToken found;
530 std::tie(rc, found) = getAuthToken(op->characteristics, op->handle, op->purpose);
531 if (!rc.isOk()) return rc;
532 op->authToken = std::move(found);
533 }
534
535 return ResponseCode::NO_ERROR;
536}
537
538namespace {
539
540class Finalize {
541 private:
542 std::function<void()> f_;
543
544 public:
Chih-Hung Hsieh4fa39ef2019-01-04 13:34:17 -0800545 explicit Finalize(std::function<void()> f) : f_(f) {}
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700546 ~Finalize() {
547 if (f_) f_();
548 }
549 void release() { f_ = {}; }
550};
551
552} // namespace
553
554void KeymasterWorker::update(sp<IBinder> token, AuthorizationSet params, hidl_vec<uint8_t> data,
555 update_cb worker_cb) {
556 Worker::addRequest([this, CAPTURE_MOVE(token), CAPTURE_MOVE(params), CAPTURE_MOVE(data),
557 CAPTURE_MOVE(worker_cb)]() {
558 KeyStoreServiceReturnCode rc;
559 auto op = operationMap_.getOperation(token);
560 if (!op) {
561 return worker_cb(operationFailed(ErrorCode::INVALID_OPERATION_HANDLE));
562 }
563
564 Finalize abort_operation_in_case_of_error([&] {
565 operationMap_.removeOperation(token, false);
566 keyStore_->getAuthTokenTable().MarkCompleted(op->handle);
Janis Danisevskisa359c672019-03-14 17:15:06 -0700567 KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->abort(op->handle));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700568 });
569
570 rc = getOperationAuthTokenIfNeeded(op);
571 if (!rc.isOk()) return worker_cb(operationFailed(rc));
572
573 // Check that all key authorization policy requirements are met.
574 AuthorizationSet key_auths(op->characteristics.hardwareEnforced);
575 key_auths.append(op->characteristics.softwareEnforced.begin(),
576 op->characteristics.softwareEnforced.end());
577
578 rc = keyStore_->getEnforcementPolicy().AuthorizeOperation(op->purpose, op->keyid, key_auths,
579 params, op->authToken, op->handle,
580 false /* is_begin_operation */);
581 if (!rc.isOk()) return worker_cb(operationFailed(rc));
582
583 OperationResult result;
584 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
585 const hidl_vec<KeyParameter>& outParams,
586 const ::std::vector<uint8_t>& output) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700587 op->device->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700588 result.resultCode = ret;
589 if (result.resultCode.isOk()) {
590 result.inputConsumed = inputConsumed;
591 result.outParams = outParams;
592 result.data = output;
593 }
594 };
595
Janis Danisevskisa359c672019-03-14 17:15:06 -0700596 rc = KS_HANDLE_HIDL_ERROR(op->device,
597 op->device->update(op->handle, params.hidl_data(), data,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700598 op->authToken, op->verificationToken, hidlCb));
599
600 // just a reminder: on success result->resultCode was set in the callback. So we only
601 // overwrite it if there was a communication error indicated by the ErrorCode.
602 if (!rc.isOk()) result.resultCode = rc;
603 if (result.resultCode.isOk()) {
604 // if everything went well we don't abort the operation.
605 abort_operation_in_case_of_error.release();
606 }
607 return worker_cb(std::move(result));
608 });
609}
610
611/**
612 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
613 * adds itself should be disallowed here.
614 */
615template <typename ParamsIter>
616static bool checkAllowedOperationParams(ParamsIter begin, const ParamsIter end) {
617 while (begin != end) {
618 switch (begin->tag) {
619 case Tag::ATTESTATION_APPLICATION_ID:
620 case Tag::RESET_SINCE_ID_ROTATION:
621 return false;
622 default:
623 break;
624 }
625 ++begin;
626 }
627 return true;
628}
629
630void KeymasterWorker::finish(sp<IBinder> token, AuthorizationSet params, hidl_vec<uint8_t> input,
631 hidl_vec<uint8_t> signature, hidl_vec<uint8_t> entropy,
632 finish_cb worker_cb) {
633 Worker::addRequest([this, CAPTURE_MOVE(token), CAPTURE_MOVE(params), CAPTURE_MOVE(input),
634 CAPTURE_MOVE(signature), CAPTURE_MOVE(entropy),
635 CAPTURE_MOVE(worker_cb)]() mutable {
636 KeyStoreServiceReturnCode rc;
637 auto op = operationMap_.getOperation(token);
638 if (!op) {
639 return worker_cb(operationFailed(ErrorCode::INVALID_OPERATION_HANDLE));
640 }
641
642 bool finished = false;
643 Finalize abort_operation_in_case_of_error([&] {
644 operationMap_.removeOperation(token, finished && rc.isOk());
645 keyStore_->getAuthTokenTable().MarkCompleted(op->handle);
Janis Danisevskisa359c672019-03-14 17:15:06 -0700646 if (!finished)
647 KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->abort(op->handle));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700648 });
649
650 if (!checkAllowedOperationParams(params.begin(), params.end())) {
651 return worker_cb(operationFailed(ErrorCode::INVALID_ARGUMENT));
652 }
653
654 rc = getOperationAuthTokenIfNeeded(op);
655 if (!rc.isOk()) return worker_cb(operationFailed(rc));
656
657 // Check that all key authorization policy requirements are met.
658 AuthorizationSet key_auths(op->characteristics.hardwareEnforced);
659 key_auths.append(op->characteristics.softwareEnforced.begin(),
660 op->characteristics.softwareEnforced.end());
661
662 if (key_auths.Contains(Tag::TRUSTED_CONFIRMATION_REQUIRED)) {
663 hidl_vec<uint8_t> confirmationToken =
664 keyStore_->getConfirmationManager().getLatestConfirmationToken();
665 if (confirmationToken.size() == 0) {
666 LOG(ERROR) << "Confirmation token required but none found";
667 return worker_cb(operationFailed(ErrorCode::NO_USER_CONFIRMATION));
668 }
669 params.push_back(keymaster::TAG_CONFIRMATION_TOKEN, std::move(confirmationToken));
670 }
671
672 rc = keyStore_->getEnforcementPolicy().AuthorizeOperation(op->purpose, op->keyid, key_auths,
673 params, op->authToken, op->handle,
674 false /* is_begin_operation */);
675 if (!rc.isOk()) return worker_cb(operationFailed(rc));
676
677 if (entropy.size()) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700678 rc = KS_HANDLE_HIDL_ERROR(op->device, op->device->addRngEntropy(entropy));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700679 if (!rc.isOk()) {
680 return worker_cb(operationFailed(rc));
681 }
682 }
683
684 OperationResult result;
685 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
686 const ::std::vector<uint8_t>& output) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700687 op->device->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700688 result.resultCode = ret;
689 if (result.resultCode.isOk()) {
690 result.outParams = outParams;
691 result.data = output;
692 }
693 };
694
Janis Danisevskisa359c672019-03-14 17:15:06 -0700695 rc = KS_HANDLE_HIDL_ERROR(op->device, op->device->finish(op->handle, params.hidl_data(),
696 input, signature, op->authToken,
697 op->verificationToken, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700698
699 if (rc.isOk()) {
700 // inform the finalizer that the finish call went through
701 finished = true;
702 // and what the result was
703 rc = result.resultCode;
704 } else {
705 return worker_cb(operationFailed(rc));
706 }
707 return worker_cb(std::move(result));
708 });
709}
710
711void KeymasterWorker::abort(sp<IBinder> token, abort_cb worker_cb) {
712 Worker::addRequest(
713 [this, CAPTURE_MOVE(token), CAPTURE_MOVE(worker_cb)]() { return worker_cb(abort(token)); });
714}
715
716void KeymasterWorker::verifyAuthorization(uint64_t challenge, hidl_vec<KeyParameter> params,
717 HardwareAuthToken token,
718 verifyAuthorization_cb worker_cb) {
719 Worker::addRequest([this, challenge, CAPTURE_MOVE(params), CAPTURE_MOVE(token),
720 CAPTURE_MOVE(worker_cb)]() {
721 KeyStoreServiceReturnCode error;
722 VerificationToken verificationToken;
Janis Danisevskisa359c672019-03-14 17:15:06 -0700723 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
724 keymasterDevice_,
725 keymasterDevice_->verifyAuthorization(
726 challenge, params, token, [&](ErrorCode ret, const VerificationToken& vToken) {
727 keymasterDevice_->logIfKeymasterVendorError(ret);
728 error = ret;
729 verificationToken = vToken;
730 }));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700731 worker_cb(rc.isOk() ? error : rc, std::move(token), std::move(verificationToken));
732 });
733}
734
735void KeymasterWorker::addRngEntropy(hidl_vec<uint8_t> data, addRngEntropy_cb _hidl_cb) {
736 addRequest(&Keymaster::addRngEntropy, std::move(_hidl_cb), std::move(data));
737}
738
739namespace {
740bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
741 return params.end() !=
742 std::find_if(params.begin(), params.end(),
743 [&](const KeyParameter& param) { return param.tag == tag; });
744}
745
746bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
747 return !containsTag(params, Tag::NO_AUTH_REQUIRED);
748}
749} // namespace
750
751void KeymasterWorker::generateKey(LockedKeyBlobEntry lockedEntry, hidl_vec<KeyParameter> keyParams,
752 hidl_vec<uint8_t> entropy, int flags, generateKey_cb worker_cb) {
753 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), CAPTURE_MOVE(keyParams),
754 CAPTURE_MOVE(entropy), CAPTURE_MOVE(worker_cb), flags]() mutable {
755 KeyStoreServiceReturnCode rc =
Janis Danisevskisa359c672019-03-14 17:15:06 -0700756 KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->addRngEntropy(entropy));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700757 if (!rc.isOk()) {
758 return worker_cb(rc, {});
759 }
760
761 SecurityLevel securityLevel = keymasterDevice_->halVersion().securityLevel;
762
763 // Fallback cannot be considered for Strongbox. Further versions restrictions are enforced
764 // by KeyStore::getFallbackDevice()
765 bool consider_fallback = securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT;
766
767 Finalize logOnFail(
768 [&] { uploadKeyCharacteristicsAsProto(keyParams, false /* wasCreationSuccessful */); });
769
770 KeyCharacteristics outCharacteristics;
771 KeyStoreServiceReturnCode error;
772 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
773 const KeyCharacteristics& keyCharacteristics) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700774 keymasterDevice_->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700775 error = ret;
776 if (!error.isOk()) {
777 return;
778 }
779 consider_fallback = false;
780 outCharacteristics = keyCharacteristics;
781
782 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), nullptr, 0, ::TYPE_KEYMASTER_10);
783 keyBlob.setSecurityLevel(securityLevel);
784 keyBlob.setCriticalToDeviceEncryption(flags &
785 KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
786 if (isAuthenticationBound(keyParams) && !keyBlob.isCriticalToDeviceEncryption()) {
787 keyBlob.setSuperEncrypted(true);
788 }
789 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
790
791 AuthorizationSet sw_enforced = keyParams;
792 sw_enforced.Subtract(outCharacteristics.hardwareEnforced);
793 sw_enforced.Union(outCharacteristics.softwareEnforced);
794 sw_enforced.Filter([](const KeyParameter& param) -> bool {
795 return !(param.tag == Tag::APPLICATION_DATA || param.tag == Tag::APPLICATION_ID);
796 });
797 if (!sw_enforced.Contains(Tag::USER_ID)) {
798 // Most Java processes don't have access to this tag
799 sw_enforced.push_back(keymaster::TAG_USER_ID, get_user_id(lockedEntry->uid()));
800 }
801 Blob keyCharBlob;
802 keyCharBlob.putKeyCharacteristics(outCharacteristics.hardwareEnforced, sw_enforced);
803 error = keyStore_->put(lockedEntry, std::move(keyBlob), std::move(keyCharBlob));
804 };
805
Janis Danisevskisa359c672019-03-14 17:15:06 -0700806 rc = KS_HANDLE_HIDL_ERROR(keymasterDevice_,
807 keymasterDevice_->generateKey(keyParams, hidl_cb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700808 if (!rc.isOk()) {
809 return worker_cb(rc, {});
810 }
811
812 if (consider_fallback && !error.isOk()) {
813 auto fallback = keyStore_->getFallbackDevice();
814 if (!fallback) {
815 return worker_cb(error, {});
816 }
817 // No fallback for 3DES
818 for (auto& param : keyParams) {
819 auto algorithm = authorizationValue(TAG_ALGORITHM, param);
820 if (algorithm.isOk() && algorithm.value() == Algorithm::TRIPLE_DES) {
821 return worker_cb(ErrorCode::UNSUPPORTED_ALGORITHM, {});
822 }
823 }
824
825 // delegate to fallback worker
826 fallback->generateKey(std::move(lockedEntry), std::move(keyParams), std::move(entropy),
827 flags, std::move(worker_cb));
828 // let fallback do the logging
829 logOnFail.release();
830 return;
831 }
832
833 if (!error.isOk()) return worker_cb(error, {});
834
835 // log on success
836 logOnFail.release();
837 uploadKeyCharacteristicsAsProto(keyParams, true /* wasCreationSuccessful */);
838
839 return worker_cb(error, std::move(outCharacteristics));
840 });
841}
842
843void KeymasterWorker::generateKey(hidl_vec<KeyParameter> keyParams, generateKey2_cb worker_cb) {
844 addRequest(&Keymaster::generateKey, std::move(worker_cb), std::move(keyParams));
845}
846
847void KeymasterWorker::getKeyCharacteristics(LockedKeyBlobEntry lockedEntry,
848 hidl_vec<uint8_t> clientId, hidl_vec<uint8_t> appData,
849 Blob keyBlob, Blob charBlob,
850 getKeyCharacteristics_cb worker_cb) {
851 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), CAPTURE_MOVE(clientId),
852 CAPTURE_MOVE(appData), CAPTURE_MOVE(keyBlob), CAPTURE_MOVE(charBlob),
853 CAPTURE_MOVE(worker_cb)]() {
854 auto result = createKeyCharacteristicsCache(lockedEntry, clientId, appData,
855 std::move(keyBlob), std::move(charBlob));
856 return worker_cb(std::get<0>(result), std::move(std::get<1>(result)));
857 });
858}
859
860void KeymasterWorker::importKey(LockedKeyBlobEntry lockedEntry, hidl_vec<KeyParameter> keyParams,
861 KeyFormat keyFormat, hidl_vec<uint8_t> keyData, int flags,
862 importKey_cb worker_cb) {
863 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), CAPTURE_MOVE(keyParams), keyFormat,
864 CAPTURE_MOVE(keyData), flags, CAPTURE_MOVE(worker_cb)]() mutable {
865 SecurityLevel securityLevel = keymasterDevice_->halVersion().securityLevel;
866
867 // Fallback cannot be considered for Strongbox. Further versions restrictions are enforced
868 // by KeyStore::getFallbackDevice()
869 bool consider_fallback = securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT;
870
871 Finalize logOnFail(
872 [&] { uploadKeyCharacteristicsAsProto(keyParams, false /* wasCreationSuccessful */); });
873
874 KeyCharacteristics outCharacteristics;
875 KeyStoreServiceReturnCode error;
876 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
877 const KeyCharacteristics& keyCharacteristics) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700878 keymasterDevice_->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700879 error = ret;
880 if (!error.isOk()) {
881 LOG(INFO) << "importKey failed";
882 return;
883 }
884 consider_fallback = false;
885 outCharacteristics = keyCharacteristics;
886
887 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), nullptr, 0, ::TYPE_KEYMASTER_10);
888 keyBlob.setSecurityLevel(securityLevel);
889 keyBlob.setCriticalToDeviceEncryption(flags &
890 KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
891 if (isAuthenticationBound(keyParams) && !keyBlob.isCriticalToDeviceEncryption()) {
892 keyBlob.setSuperEncrypted(true);
893 }
894 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
895
896 AuthorizationSet sw_enforced = keyParams;
897 sw_enforced.Subtract(outCharacteristics.hardwareEnforced);
898 sw_enforced.Union(outCharacteristics.softwareEnforced);
899 sw_enforced.Filter([](const KeyParameter& param) -> bool {
900 return !(param.tag == Tag::APPLICATION_DATA || param.tag == Tag::APPLICATION_ID);
901 });
902 if (!sw_enforced.Contains(Tag::USER_ID)) {
903 // Most Java processes don't have access to this tag
904 sw_enforced.push_back(keymaster::TAG_USER_ID, get_user_id(lockedEntry->uid()));
905 }
906 Blob keyCharBlob;
907 keyCharBlob.putKeyCharacteristics(outCharacteristics.hardwareEnforced, sw_enforced);
908 error = keyStore_->put(lockedEntry, std::move(keyBlob), std::move(keyCharBlob));
909 };
910
911 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
Janis Danisevskisa359c672019-03-14 17:15:06 -0700912 keymasterDevice_, keymasterDevice_->importKey(keyParams, keyFormat, keyData, hidl_cb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700913 if (!rc.isOk()) {
914 return worker_cb(rc, {});
915 }
916
917 if (consider_fallback && !error.isOk()) {
918 auto fallback = keyStore_->getFallbackDevice();
919 if (!fallback) {
920 return worker_cb(error, {});
921 }
922 // No fallback for 3DES
923 for (auto& param : keyParams) {
924 auto algorithm = authorizationValue(TAG_ALGORITHM, param);
925 if (algorithm.isOk() && algorithm.value() == Algorithm::TRIPLE_DES) {
926 return worker_cb(ErrorCode::UNSUPPORTED_ALGORITHM, {});
927 }
928 }
929
930 // delegate to fallback worker
931 fallback->importKey(std::move(lockedEntry), std::move(keyParams), keyFormat,
932 std::move(keyData), flags, std::move(worker_cb));
933 // let fallback to the logging
934 logOnFail.release();
935 return;
936 }
937
938 if (!error.isOk()) return worker_cb(error, {});
939
940 // log on success
941 logOnFail.release();
942 uploadKeyCharacteristicsAsProto(keyParams, true /* wasCreationSuccessful */);
943
944 return worker_cb(error, std::move(outCharacteristics));
945 });
946}
947
948void KeymasterWorker::importWrappedKey(LockedKeyBlobEntry wrappingLockedEntry,
949 LockedKeyBlobEntry wrapppedLockedEntry,
950 hidl_vec<uint8_t> wrappedKeyData,
951 hidl_vec<uint8_t> maskingKey,
952 hidl_vec<KeyParameter> unwrappingParams, Blob wrappingBlob,
953 Blob wrappingCharBlob, uint64_t passwordSid,
954 uint64_t biometricSid, importWrappedKey_cb worker_cb) {
955 Worker::addRequest([this, CAPTURE_MOVE(wrappingLockedEntry), CAPTURE_MOVE(wrapppedLockedEntry),
956 CAPTURE_MOVE(wrappedKeyData), CAPTURE_MOVE(maskingKey),
957 CAPTURE_MOVE(unwrappingParams), CAPTURE_MOVE(wrappingBlob),
958 CAPTURE_MOVE(wrappingCharBlob), passwordSid, biometricSid,
959 CAPTURE_MOVE(worker_cb)]() mutable {
960 auto hidlWrappingKey = blob2hidlVec(wrappingBlob);
961
962 SecurityLevel securityLevel = keymasterDevice_->halVersion().securityLevel;
963
964 KeyCharacteristics outCharacteristics;
965 KeyStoreServiceReturnCode error;
966
967 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
968 const KeyCharacteristics& keyCharacteristics) {
Janis Danisevskisa359c672019-03-14 17:15:06 -0700969 keymasterDevice_->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700970 error = ret;
971 if (!error.isOk()) {
972 return;
973 }
974 outCharacteristics = keyCharacteristics;
975
976 Blob keyBlob(hidlKeyBlob.data(), hidlKeyBlob.size(), nullptr, 0, ::TYPE_KEYMASTER_10);
977 keyBlob.setSecurityLevel(securityLevel);
978 if (isAuthenticationBound(keyCharacteristics.hardwareEnforced)) {
979 keyBlob.setSuperEncrypted(true);
980 }
981
982 AuthorizationSet sw_enforced = outCharacteristics.softwareEnforced;
983 if (!sw_enforced.Contains(Tag::USER_ID)) {
984 // Most Java processes don't have access to this tag
985 sw_enforced.push_back(keymaster::TAG_USER_ID,
986 get_user_id(wrapppedLockedEntry->uid()));
987 }
988 Blob keyCharBlob;
989 keyCharBlob.putKeyCharacteristics(outCharacteristics.hardwareEnforced, sw_enforced);
990 error = keyStore_->put(wrapppedLockedEntry, std::move(keyBlob), std::move(keyCharBlob));
991 };
992
Janis Danisevskisa359c672019-03-14 17:15:06 -0700993 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
994 keymasterDevice_, keymasterDevice_->importWrappedKey(
995 wrappedKeyData, hidlWrappingKey, maskingKey, unwrappingParams,
996 passwordSid, biometricSid, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700997
998 // possible hidl error
999 if (!rc.isOk()) {
1000 return worker_cb(rc, {});
1001 }
1002
1003 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
1004 std::tie(rc, wrappingBlob) = upgradeKeyBlob(wrappingLockedEntry, {});
1005 if (!rc.isOk()) {
1006 return worker_cb(rc, {});
1007 }
1008
1009 auto upgradedHidlKeyBlob = blob2hidlVec(wrappingBlob);
1010
Janis Danisevskisa359c672019-03-14 17:15:06 -07001011 rc = KS_HANDLE_HIDL_ERROR(keymasterDevice_,
1012 keymasterDevice_->importWrappedKey(
1013 wrappedKeyData, upgradedHidlKeyBlob, maskingKey,
1014 unwrappingParams, passwordSid, biometricSid, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001015 if (!rc.isOk()) {
1016 error = rc;
1017 }
1018 }
1019 return worker_cb(error, std::move(outCharacteristics));
1020 });
1021}
1022
1023void KeymasterWorker::exportKey(LockedKeyBlobEntry lockedEntry, KeyFormat exportFormat,
1024 hidl_vec<uint8_t> clientId, hidl_vec<uint8_t> appData, Blob keyBlob,
1025 Blob charBlob, exportKey_cb worker_cb) {
1026 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), exportFormat, CAPTURE_MOVE(clientId),
1027 CAPTURE_MOVE(appData), CAPTURE_MOVE(keyBlob), CAPTURE_MOVE(charBlob),
1028 CAPTURE_MOVE(worker_cb)]() mutable {
1029 auto key = blob2hidlVec(keyBlob);
1030
1031 ExportResult result;
1032 auto hidlCb = [&](ErrorCode ret,
1033 const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001034 keymasterDevice_->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001035 result.resultCode = ret;
1036 if (!result.resultCode.isOk()) {
1037 if (result.resultCode == ErrorCode::INVALID_KEY_BLOB) {
1038 log_key_integrity_violation(lockedEntry->alias().c_str(), lockedEntry->uid());
1039 }
1040 return;
1041 }
1042 result.exportData = keyMaterial;
1043 };
1044 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
Janis Danisevskisa359c672019-03-14 17:15:06 -07001045 keymasterDevice_,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001046 keymasterDevice_->exportKey(exportFormat, key, clientId, appData, hidlCb));
1047
1048 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
1049 // callback hidlCb.
1050 if (!rc.isOk()) {
1051 result.resultCode = rc;
1052 }
1053
1054 if (result.resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1055 AuthorizationSet upgradeParams;
1056 if (clientId.size()) {
1057 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
1058 }
1059 if (appData.size()) {
1060 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
1061 }
1062 std::tie(rc, keyBlob) = upgradeKeyBlob(lockedEntry, upgradeParams);
1063 if (!rc.isOk()) {
1064 return worker_cb(std::move(result));
1065 }
1066
1067 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1068
Janis Danisevskisa359c672019-03-14 17:15:06 -07001069 rc = KS_HANDLE_HIDL_ERROR(keymasterDevice_,
1070 keymasterDevice_->exportKey(exportFormat, upgradedHidlKeyBlob,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001071 clientId, appData, hidlCb));
1072 if (!rc.isOk()) {
1073 result.resultCode = rc;
1074 }
1075 }
1076 return worker_cb(std::move(result));
1077 });
1078}
1079void KeymasterWorker::attestKey(hidl_vec<uint8_t> keyToAttest, hidl_vec<KeyParameter> attestParams,
1080 attestKey_cb worker_cb) {
1081 addRequest(&Keymaster::attestKey, std::move(worker_cb), std::move(keyToAttest),
1082 std::move(attestParams));
1083}
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001084
1085void KeymasterWorker::deleteKey(hidl_vec<uint8_t> keyBlob, deleteKey_cb _hidl_cb) {
1086 addRequest(&Keymaster::deleteKey, std::move(_hidl_cb), std::move(keyBlob));
1087}
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001088
1089void KeymasterWorker::binderDied(android::wp<IBinder> who) {
1090 Worker::addRequest([this, who]() {
1091 auto operations = operationMap_.getOperationsForToken(who.unsafe_get());
1092 for (const auto& token : operations) {
1093 abort(token);
1094 }
1095 });
1096}
1097
1098} // namespace keystore