blob: f6d56211d460b4facaaf0f5e286c052abf2c16e7 [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
Janis Danisevskis6a0d9982019-04-30 15:43:59 -070025#include <log/log_event_list.h>
26
27#include <private/android_logger.h>
28
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070029#include "KeyStore.h"
30#include "keymaster_enforcement.h"
31
32#include "key_proto_handler.h"
33#include "keystore_utils.h"
34
35namespace keystore {
36
37constexpr size_t kMaxOperations = 15;
38
39using AndroidKeymasterArguments = android::security::keymaster::KeymasterArguments;
40using android::security::keymaster::ExportResult;
41using android::security::keymaster::operationFailed;
42using android::security::keymaster::OperationResult;
43
Janis Danisevskis5ec4c2a2018-11-12 10:39:48 -080044Worker::Worker() {}
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070045Worker::~Worker() {
Janis Danisevskis5ec4c2a2018-11-12 10:39:48 -080046 std::unique_lock<std::mutex> lock(pending_requests_mutex_);
47 pending_requests_cond_var_.wait(lock, [this] { return pending_requests_.empty(); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070048}
49void Worker::addRequest(WorkerTask request) {
50 std::unique_lock<std::mutex> lock(pending_requests_mutex_);
Janis Danisevskis5ec4c2a2018-11-12 10:39:48 -080051 bool start_thread = pending_requests_.empty();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070052 pending_requests_.push(std::move(request));
53 lock.unlock();
Janis Danisevskis5ec4c2a2018-11-12 10:39:48 -080054 if (start_thread) {
55 auto worker = std::thread([this] {
56 std::unique_lock<std::mutex> lock(pending_requests_mutex_);
57 running_ = true;
58 while (!pending_requests_.empty()) {
59 auto request = std::move(pending_requests_.front());
60 lock.unlock();
61 request();
62 lock.lock();
63 pending_requests_.pop();
64 pending_requests_cond_var_.notify_all();
65 }
66 });
67 worker.detach();
68 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070069}
70
71KeymasterWorker::KeymasterWorker(sp<Keymaster> keymasterDevice, KeyStore* keyStore)
72 : keymasterDevice_(std::move(keymasterDevice)), operationMap_(keyStore), keyStore_(keyStore) {
73 // make sure that hal version is cached.
74 if (keymasterDevice_) keymasterDevice_->halVersion();
75}
76
Janis Danisevskis37896102019-03-14 17:15:06 -070077void KeymasterWorker::logIfKeymasterVendorError(ErrorCode ec) const {
78 keymasterDevice_->logIfKeymasterVendorError(ec);
79}
80
Janis Danisevskis6a0d9982019-04-30 15:43:59 -070081void KeymasterWorker::deleteOldKeyOnUpgrade(const LockedKeyBlobEntry& blobfile, Blob keyBlob) {
82 // if we got the blob successfully, we try and delete it from the keymaster device
83 auto& dev = keymasterDevice_;
84 uid_t uid = blobfile->uid();
85 const auto& alias = blobfile->alias();
86
87 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
88 auto ret = KS_HANDLE_HIDL_ERROR(dev, dev->deleteKey(blob2hidlVec(keyBlob)));
89 // A device doesn't have to implement delete_key.
90 bool success = ret == ErrorCode::OK || ret == ErrorCode::UNIMPLEMENTED;
91 if (__android_log_security()) {
92 android_log_event_list(SEC_TAG_KEY_DESTROYED)
93 << int32_t(success) << alias << int32_t(uid) << LOG_ID_SECURITY;
94 }
95 if (!success) {
96 LOG(ERROR) << "Keymaster delete for key " << alias << " of uid " << uid << " failed";
97 }
98 }
99}
100
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700101std::tuple<KeyStoreServiceReturnCode, Blob>
102KeymasterWorker::upgradeKeyBlob(const LockedKeyBlobEntry& lockedEntry,
103 const AuthorizationSet& params) {
104 LOG(INFO) << "upgradeKeyBlob " << lockedEntry->alias() << " " << (uint32_t)lockedEntry->uid();
105
106 std::tuple<KeyStoreServiceReturnCode, Blob> result;
107
108 auto userState = keyStore_->getUserStateDB().getUserStateByUid(lockedEntry->uid());
109
110 Blob& blob = std::get<1>(result);
111 KeyStoreServiceReturnCode& error = std::get<0>(result);
112
113 Blob charBlob;
114 ResponseCode rc;
115
116 std::tie(rc, blob, charBlob) =
117 lockedEntry.readBlobs(userState->getEncryptionKey(), userState->getState());
118
Janis Danisevskis265435f2018-11-16 14:10:46 -0800119 userState = {};
120
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700121 if (rc != ResponseCode::NO_ERROR) {
122 return error = rc, result;
123 }
124
125 auto hidlKey = blob2hidlVec(blob);
126 auto& dev = keymasterDevice_;
127
128 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& upgradedKeyBlob) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700129 dev->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700130 error = ret;
131 if (!error.isOk()) {
132 if (error == ErrorCode::INVALID_KEY_BLOB) {
133 log_key_integrity_violation(lockedEntry->alias().c_str(), lockedEntry->uid());
134 }
135 return;
136 }
137
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700138 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
139 0 /* infoLength */, ::TYPE_KEYMASTER_10);
140 newBlob.setSecurityLevel(blob.getSecurityLevel());
141 newBlob.setEncrypted(blob.isEncrypted());
142 newBlob.setSuperEncrypted(blob.isSuperEncrypted());
143 newBlob.setCriticalToDeviceEncryption(blob.isCriticalToDeviceEncryption());
144
145 error = keyStore_->put(lockedEntry, newBlob, charBlob);
146 if (!error.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800147 ALOGI("upgradeKeyBlob keystore->put failed %d", error.getErrorCode());
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700148 return;
149 }
Janis Danisevskis6a0d9982019-04-30 15:43:59 -0700150
151 deleteOldKeyOnUpgrade(lockedEntry, std::move(blob));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700152 blob = std::move(newBlob);
153 };
154
155 KeyStoreServiceReturnCode error2;
Janis Danisevskis37896102019-03-14 17:15:06 -0700156 error2 = KS_HANDLE_HIDL_ERROR(dev, dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700157 if (!error2.isOk()) {
158 return error = error2, result;
159 }
160
161 return result;
162}
163
164std::tuple<KeyStoreServiceReturnCode, KeyCharacteristics, Blob, Blob>
165KeymasterWorker::createKeyCharacteristicsCache(const LockedKeyBlobEntry& lockedEntry,
166 const hidl_vec<uint8_t>& clientId,
167 const hidl_vec<uint8_t>& appData, Blob keyBlob,
168 Blob charBlob) {
169 std::tuple<KeyStoreServiceReturnCode, KeyCharacteristics, Blob, Blob> result;
170
171#if __cplusplus == 201703L
172 auto& [rc, resultCharacteristics, outBlob, charOutBlob] = result;
173#else
174 KeyStoreServiceReturnCode& rc = std::get<0>(result);
175 KeyCharacteristics& resultCharacteristics = std::get<1>(result);
176 Blob& outBlob = std::get<2>(result);
177 Blob& charOutBlob = std::get<3>(result);
178#endif
179
180 rc = ResponseCode::SYSTEM_ERROR;
181 if (!keyBlob) return result;
182 auto hidlKeyBlob = blob2hidlVec(keyBlob);
183 auto& dev = keymasterDevice_;
184
185 KeyStoreServiceReturnCode error;
186
187 AuthorizationSet hwEnforced, swEnforced;
188 bool success = true;
189
190 if (charBlob) {
191 std::tie(success, hwEnforced, swEnforced) = charBlob.getKeyCharacteristics();
192 }
193 if (!success) {
194 LOG(ERROR) << "Failed to read cached key characteristics";
195 return rc = ResponseCode::SYSTEM_ERROR, result;
196 }
197
198 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700199 dev->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700200 error = ret;
201 if (!error.isOk()) {
202 if (error == ErrorCode::INVALID_KEY_BLOB) {
203 log_key_integrity_violation(lockedEntry->alias().c_str(), lockedEntry->uid());
204 }
205 return;
206 }
207
208 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
209 AuthorizationSet softwareEnforced = keyCharacteristics.softwareEnforced;
210 hwEnforced = keyCharacteristics.hardwareEnforced;
211 swEnforced.Union(softwareEnforced);
212 softwareEnforced.Subtract(hwEnforced);
213
214 // We only get the characteristics from keymaster if there was no cache file or the
215 // the chach file was a legacy cache file. So lets write a new cache file for the next time.
216 Blob newCharBlob;
217 success = newCharBlob.putKeyCharacteristics(hwEnforced, swEnforced);
218 if (!success) {
219 error = ResponseCode::SYSTEM_ERROR;
220 LOG(ERROR) << "Failed to serialize cached key characteristics";
221 return;
222 }
223
224 error = keyStore_->put(lockedEntry, {}, newCharBlob);
225 if (!error.isOk()) {
226 ALOGE("Failed to write key characteristics cache");
227 return;
228 }
229 charBlob = std::move(newCharBlob);
230 };
231
232 if (!charBlob || charBlob.getType() == TYPE_KEY_CHARACTERISTICS) {
233 // this updates the key characteristics cache file to the new format or creates one in
234 // in the first place
235 rc = KS_HANDLE_HIDL_ERROR(
Janis Danisevskis37896102019-03-14 17:15:06 -0700236 dev, dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700237 if (!rc.isOk()) {
238 return result;
239 }
240
241 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
242 AuthorizationSet upgradeParams;
243 if (clientId.size()) {
244 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
245 }
246 if (appData.size()) {
247 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
248 }
249 std::tie(rc, keyBlob) = upgradeKeyBlob(lockedEntry, upgradeParams);
250 if (!rc.isOk()) {
251 return result;
252 }
253
254 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
255
256 rc = KS_HANDLE_HIDL_ERROR(
Janis Danisevskis37896102019-03-14 17:15:06 -0700257 dev, dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700258 if (!rc.isOk()) {
259 return result;
260 }
261 }
262 }
263
264 resultCharacteristics.hardwareEnforced = hwEnforced.hidl_data();
265 resultCharacteristics.softwareEnforced = swEnforced.hidl_data();
266
267 outBlob = std::move(keyBlob);
268 charOutBlob = std::move(charBlob);
269 rc = error;
270 return result;
271}
272
273/**
274 * Get the auth token for this operation from the auth token table.
275 *
276 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
277 * ::OP_AUTH_NEEDED if it is a per op authorization, no
278 * authorization token exists for that operation and
279 * failOnTokenMissing is false.
280 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
281 * token for the operation
282 */
283std::pair<KeyStoreServiceReturnCode, HardwareAuthToken>
284KeymasterWorker::getAuthToken(const KeyCharacteristics& characteristics, uint64_t handle,
285 KeyPurpose purpose, bool failOnTokenMissing) {
286
287 AuthorizationSet allCharacteristics(characteristics.softwareEnforced);
288 allCharacteristics.append(characteristics.hardwareEnforced.begin(),
289 characteristics.hardwareEnforced.end());
290
291 HardwareAuthToken authToken;
292 AuthTokenTable::Error err;
293 std::tie(err, authToken) = keyStore_->getAuthTokenTable().FindAuthorization(
294 allCharacteristics, static_cast<KeyPurpose>(purpose), handle);
295
296 KeyStoreServiceReturnCode rc;
297
298 switch (err) {
299 case AuthTokenTable::OK:
300 case AuthTokenTable::AUTH_NOT_REQUIRED:
301 rc = ResponseCode::NO_ERROR;
302 break;
303
304 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
305 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
306 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
307 ALOGE("getAuthToken failed: %d", err); // STOPSHIP: debug only, to be removed
308 rc = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
309 break;
310
311 case AuthTokenTable::OP_HANDLE_REQUIRED:
312 rc = failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
313 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
314 break;
315
316 default:
317 ALOGE("Unexpected FindAuthorization return value %d", err);
318 rc = ErrorCode::INVALID_ARGUMENT;
319 }
320
321 return {rc, std::move(authToken)};
322}
323
324KeyStoreServiceReturnCode KeymasterWorker::abort(const sp<IBinder>& token) {
325 auto op = operationMap_.removeOperation(token, false /* wasOpSuccessful */);
326 if (op) {
327 keyStore_->getAuthTokenTable().MarkCompleted(op->handle);
Janis Danisevskis37896102019-03-14 17:15:06 -0700328 return KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->abort(op->handle));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700329 } else {
330 return ErrorCode::INVALID_OPERATION_HANDLE;
331 }
332}
333
334/**
335 * Prune the oldest pruneable operation.
336 */
337bool KeymasterWorker::pruneOperation() {
338 sp<IBinder> oldest = operationMap_.getOldestPruneableOperation();
339 ALOGD("Trying to prune operation %p", oldest.get());
340 size_t op_count_before_abort = operationMap_.getOperationCount();
341 // We mostly ignore errors from abort() because all we care about is whether at least
342 // one operation has been removed.
343 auto rc = abort(oldest);
Janis Danisevskisbec89992019-08-14 13:42:19 -0700344 keyStore_->removeOperationDevice(oldest);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700345 if (operationMap_.getOperationCount() >= op_count_before_abort) {
Branden Archer70080742018-11-20 11:04:11 -0800346 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), rc.getErrorCode());
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700347 return false;
348 }
349 return true;
350}
351
352// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
353// It should never be redefined by a build system though.
354#ifndef CAPTURE_MOVE
355#define CAPTURE_MOVE(x) x = std::move(x)
356#endif
357
358void KeymasterWorker::begin(LockedKeyBlobEntry lockedEntry, sp<IBinder> appToken, Blob keyBlob,
359 Blob charBlob, bool pruneable, KeyPurpose purpose,
360 AuthorizationSet opParams, hidl_vec<uint8_t> entropy,
361 worker_begin_cb worker_cb) {
362
363 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), CAPTURE_MOVE(appToken),
364 CAPTURE_MOVE(keyBlob), CAPTURE_MOVE(charBlob), pruneable, purpose,
365 CAPTURE_MOVE(opParams), CAPTURE_MOVE(entropy),
366 CAPTURE_MOVE(worker_cb)]() mutable {
367 // Concurrently executed
368
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700369 auto& dev = keymasterDevice_;
370
371 KeyCharacteristics characteristics;
372
373 {
374 hidl_vec<uint8_t> clientId;
375 hidl_vec<uint8_t> appData;
Chih-Hung Hsiehb3bfdb02018-12-12 14:43:33 -0800376 for (const auto& param : opParams) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700377 if (param.tag == Tag::APPLICATION_ID) {
378 clientId = authorizationValue(TAG_APPLICATION_ID, param).value();
379 } else if (param.tag == Tag::APPLICATION_DATA) {
380 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
381 }
382 }
383 KeyStoreServiceReturnCode error;
384 std::tie(error, characteristics, keyBlob, charBlob) = createKeyCharacteristicsCache(
385 lockedEntry, clientId, appData, std::move(keyBlob), std::move(charBlob));
386 if (!error.isOk()) {
387 worker_cb(operationFailed(error));
388 return;
389 }
390 }
391
392 KeyStoreServiceReturnCode rc, authRc;
393 HardwareAuthToken authToken;
394 std::tie(authRc, authToken) = getAuthToken(characteristics, 0 /* no challenge */, purpose,
395 /*failOnTokenMissing*/ false);
396
397 // If per-operation auth is needed we need to begin the operation and
398 // the client will need to authorize that operation before calling
399 // update. Any other auth issues stop here.
400 if (!authRc.isOk() && authRc != ResponseCode::OP_AUTH_NEEDED) {
401 return worker_cb(operationFailed(authRc));
402 }
403
404 // Add entropy to the device first.
405 if (entropy.size()) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700406 rc = KS_HANDLE_HIDL_ERROR(dev, dev->addRngEntropy(entropy));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700407 if (!rc.isOk()) {
408 return worker_cb(operationFailed(rc));
409 }
410 }
411
412 // Create a keyid for this key.
Janis Danisevskis64eb3eb2018-11-27 20:41:52 -0800413 auto keyid = KeymasterEnforcement::CreateKeyId(blob2hidlVec(keyBlob));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700414 if (!keyid) {
415 ALOGE("Failed to create a key ID for authorization checking.");
416 return worker_cb(operationFailed(ErrorCode::UNKNOWN_ERROR));
417 }
418
419 // Check that all key authorization policy requirements are met.
420 AuthorizationSet key_auths = characteristics.hardwareEnforced;
421 key_auths.append(characteristics.softwareEnforced.begin(),
422 characteristics.softwareEnforced.end());
423
424 rc = keyStore_->getEnforcementPolicy().AuthorizeOperation(
425 purpose, *keyid, key_auths, opParams, authToken, 0 /* op_handle */,
426 true /* is_begin_operation */);
427 if (!rc.isOk()) {
428 return worker_cb(operationFailed(rc));
429 }
430
431 // If there are more than kMaxOperations, abort the oldest operation that was started as
432 // pruneable.
433 while (operationMap_.getOperationCount() >= kMaxOperations) {
434 ALOGD("Reached or exceeded concurrent operations limit");
435 if (!pruneOperation()) {
436 break;
437 }
438 }
439
440 android::security::keymaster::OperationResult result;
441
442 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
443 uint64_t operationHandle) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700444 dev->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700445 result.resultCode = ret;
446 if (!result.resultCode.isOk()) {
447 if (result.resultCode == ErrorCode::INVALID_KEY_BLOB) {
448 log_key_integrity_violation(lockedEntry->alias().c_str(), lockedEntry->uid());
449 }
450 return;
451 }
452 result.handle = operationHandle;
453 result.outParams = outParams;
454 };
455
456 do {
Janis Danisevskis37896102019-03-14 17:15:06 -0700457 rc = KS_HANDLE_HIDL_ERROR(dev, dev->begin(purpose, blob2hidlVec(keyBlob),
458 opParams.hidl_data(), authToken, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700459 if (!rc.isOk()) {
460 LOG(ERROR) << "Got error " << rc << " from begin()";
461 return worker_cb(operationFailed(ResponseCode::SYSTEM_ERROR));
462 }
Janis Danisevskis64eb3eb2018-11-27 20:41:52 -0800463
464 if (result.resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
465 std::tie(rc, keyBlob) = upgradeKeyBlob(lockedEntry, opParams);
466 if (!rc.isOk()) {
467 return worker_cb(operationFailed(rc));
468 }
469
Janis Danisevskis37896102019-03-14 17:15:06 -0700470 rc = KS_HANDLE_HIDL_ERROR(dev, dev->begin(purpose, blob2hidlVec(keyBlob),
471 opParams.hidl_data(), authToken, hidlCb));
Janis Danisevskis64eb3eb2018-11-27 20:41:52 -0800472 if (!rc.isOk()) {
473 LOG(ERROR) << "Got error " << rc << " from begin()";
474 return worker_cb(operationFailed(ResponseCode::SYSTEM_ERROR));
475 }
476 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700477 // If there are too many operations abort the oldest operation that was
478 // started as pruneable and try again.
479 } while (result.resultCode == ErrorCode::TOO_MANY_OPERATIONS && pruneOperation());
480
481 rc = result.resultCode;
482 if (!rc.isOk()) {
483 return worker_cb(operationFailed(rc));
484 }
485
486 // Note: The operation map takes possession of the contents of "characteristics".
487 // It is safe to use characteristics after the following line but it will be empty.
488 sp<IBinder> operationToken =
489 operationMap_.addOperation(result.handle, *keyid, purpose, dev, appToken,
490 std::move(characteristics), opParams.hidl_data(), pruneable);
491 assert(characteristics.hardwareEnforced.size() == 0);
492 assert(characteristics.softwareEnforced.size() == 0);
493 result.token = operationToken;
494
495 auto operation = operationMap_.getOperation(operationToken);
496 if (!operation) {
497 return worker_cb(operationFailed(ResponseCode::SYSTEM_ERROR));
498 }
499
500 if (authRc.isOk() && authToken.mac.size() &&
501 dev->halVersion().securityLevel == SecurityLevel::STRONGBOX) {
502 operation->authTokenFuture = operation->authTokenPromise.get_future();
503 std::weak_ptr<Operation> weak_operation = operation;
504
505 auto verifyTokenCB = [weak_operation](KeyStoreServiceReturnCode rc,
506 HardwareAuthToken authToken,
507 VerificationToken verificationToken) {
508 auto operation = weak_operation.lock();
509 if (!operation) {
510 // operation aborted, nothing to do
511 return;
512 }
513 if (rc.isOk()) {
514 operation->authToken = std::move(authToken);
515 operation->verificationToken = std::move(verificationToken);
516 }
517 operation->authTokenPromise.set_value(rc);
518 };
519 auto teeKmDevice = keyStore_->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
520 teeKmDevice->verifyAuthorization(result.handle, {}, std::move(authToken),
521 std::move(verifyTokenCB));
522 }
523
524 // Return the authentication lookup result. If this is a per operation
525 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
526 // application should get an auth token using the handle before the
527 // first call to update, which will fail if keystore hasn't received the
528 // auth token.
529 if (result.resultCode.isOk()) {
530 result.resultCode = authRc;
531 }
532 return worker_cb(result);
533 });
534}
535
536KeyStoreServiceReturnCode
537KeymasterWorker::getOperationAuthTokenIfNeeded(std::shared_ptr<Operation> op) {
538 if (!op) return ErrorCode::INVALID_OPERATION_HANDLE;
539
540 if (op->authTokenFuture.valid()) {
541 LOG(INFO) << "Waiting for verification token";
542 op->authTokenFuture.wait();
543 auto rc = op->authTokenFuture.get();
544 if (!rc.isOk()) {
545 return rc;
546 }
547 op->authTokenFuture = {};
548 } else if (!op->hasAuthToken()) {
549 KeyStoreServiceReturnCode rc;
550 HardwareAuthToken found;
551 std::tie(rc, found) = getAuthToken(op->characteristics, op->handle, op->purpose);
552 if (!rc.isOk()) return rc;
553 op->authToken = std::move(found);
554 }
555
556 return ResponseCode::NO_ERROR;
557}
558
559namespace {
560
561class Finalize {
562 private:
563 std::function<void()> f_;
564
565 public:
Chih-Hung Hsieh4fa39ef2019-01-04 13:34:17 -0800566 explicit Finalize(std::function<void()> f) : f_(f) {}
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700567 ~Finalize() {
568 if (f_) f_();
569 }
570 void release() { f_ = {}; }
571};
572
573} // namespace
574
575void KeymasterWorker::update(sp<IBinder> token, AuthorizationSet params, hidl_vec<uint8_t> data,
576 update_cb worker_cb) {
577 Worker::addRequest([this, CAPTURE_MOVE(token), CAPTURE_MOVE(params), CAPTURE_MOVE(data),
578 CAPTURE_MOVE(worker_cb)]() {
579 KeyStoreServiceReturnCode rc;
580 auto op = operationMap_.getOperation(token);
581 if (!op) {
582 return worker_cb(operationFailed(ErrorCode::INVALID_OPERATION_HANDLE));
583 }
584
585 Finalize abort_operation_in_case_of_error([&] {
586 operationMap_.removeOperation(token, false);
587 keyStore_->getAuthTokenTable().MarkCompleted(op->handle);
Janis Danisevskis37896102019-03-14 17:15:06 -0700588 KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->abort(op->handle));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700589 });
590
591 rc = getOperationAuthTokenIfNeeded(op);
592 if (!rc.isOk()) return worker_cb(operationFailed(rc));
593
594 // Check that all key authorization policy requirements are met.
595 AuthorizationSet key_auths(op->characteristics.hardwareEnforced);
596 key_auths.append(op->characteristics.softwareEnforced.begin(),
597 op->characteristics.softwareEnforced.end());
598
599 rc = keyStore_->getEnforcementPolicy().AuthorizeOperation(op->purpose, op->keyid, key_auths,
600 params, op->authToken, op->handle,
601 false /* is_begin_operation */);
602 if (!rc.isOk()) return worker_cb(operationFailed(rc));
603
604 OperationResult result;
605 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
606 const hidl_vec<KeyParameter>& outParams,
607 const ::std::vector<uint8_t>& output) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700608 op->device->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700609 result.resultCode = ret;
610 if (result.resultCode.isOk()) {
611 result.inputConsumed = inputConsumed;
612 result.outParams = outParams;
613 result.data = output;
614 }
615 };
616
Janis Danisevskis37896102019-03-14 17:15:06 -0700617 rc = KS_HANDLE_HIDL_ERROR(op->device,
618 op->device->update(op->handle, params.hidl_data(), data,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700619 op->authToken, op->verificationToken, hidlCb));
620
621 // just a reminder: on success result->resultCode was set in the callback. So we only
622 // overwrite it if there was a communication error indicated by the ErrorCode.
623 if (!rc.isOk()) result.resultCode = rc;
624 if (result.resultCode.isOk()) {
625 // if everything went well we don't abort the operation.
626 abort_operation_in_case_of_error.release();
627 }
628 return worker_cb(std::move(result));
629 });
630}
631
632/**
633 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
634 * adds itself should be disallowed here.
635 */
636template <typename ParamsIter>
637static bool checkAllowedOperationParams(ParamsIter begin, const ParamsIter end) {
638 while (begin != end) {
639 switch (begin->tag) {
640 case Tag::ATTESTATION_APPLICATION_ID:
641 case Tag::RESET_SINCE_ID_ROTATION:
642 return false;
643 default:
644 break;
645 }
646 ++begin;
647 }
648 return true;
649}
650
651void KeymasterWorker::finish(sp<IBinder> token, AuthorizationSet params, hidl_vec<uint8_t> input,
652 hidl_vec<uint8_t> signature, hidl_vec<uint8_t> entropy,
653 finish_cb worker_cb) {
654 Worker::addRequest([this, CAPTURE_MOVE(token), CAPTURE_MOVE(params), CAPTURE_MOVE(input),
655 CAPTURE_MOVE(signature), CAPTURE_MOVE(entropy),
656 CAPTURE_MOVE(worker_cb)]() mutable {
657 KeyStoreServiceReturnCode rc;
658 auto op = operationMap_.getOperation(token);
659 if (!op) {
660 return worker_cb(operationFailed(ErrorCode::INVALID_OPERATION_HANDLE));
661 }
662
663 bool finished = false;
664 Finalize abort_operation_in_case_of_error([&] {
665 operationMap_.removeOperation(token, finished && rc.isOk());
666 keyStore_->getAuthTokenTable().MarkCompleted(op->handle);
Janis Danisevskis37896102019-03-14 17:15:06 -0700667 if (!finished)
668 KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->abort(op->handle));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700669 });
670
671 if (!checkAllowedOperationParams(params.begin(), params.end())) {
672 return worker_cb(operationFailed(ErrorCode::INVALID_ARGUMENT));
673 }
674
675 rc = getOperationAuthTokenIfNeeded(op);
676 if (!rc.isOk()) return worker_cb(operationFailed(rc));
677
678 // Check that all key authorization policy requirements are met.
679 AuthorizationSet key_auths(op->characteristics.hardwareEnforced);
680 key_auths.append(op->characteristics.softwareEnforced.begin(),
681 op->characteristics.softwareEnforced.end());
682
683 if (key_auths.Contains(Tag::TRUSTED_CONFIRMATION_REQUIRED)) {
684 hidl_vec<uint8_t> confirmationToken =
685 keyStore_->getConfirmationManager().getLatestConfirmationToken();
686 if (confirmationToken.size() == 0) {
687 LOG(ERROR) << "Confirmation token required but none found";
688 return worker_cb(operationFailed(ErrorCode::NO_USER_CONFIRMATION));
689 }
690 params.push_back(keymaster::TAG_CONFIRMATION_TOKEN, std::move(confirmationToken));
691 }
692
693 rc = keyStore_->getEnforcementPolicy().AuthorizeOperation(op->purpose, op->keyid, key_auths,
694 params, op->authToken, op->handle,
695 false /* is_begin_operation */);
696 if (!rc.isOk()) return worker_cb(operationFailed(rc));
697
698 if (entropy.size()) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700699 rc = KS_HANDLE_HIDL_ERROR(op->device, op->device->addRngEntropy(entropy));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700700 if (!rc.isOk()) {
701 return worker_cb(operationFailed(rc));
702 }
703 }
704
705 OperationResult result;
706 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
707 const ::std::vector<uint8_t>& output) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700708 op->device->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700709 result.resultCode = ret;
710 if (result.resultCode.isOk()) {
711 result.outParams = outParams;
712 result.data = output;
713 }
714 };
715
Janis Danisevskis37896102019-03-14 17:15:06 -0700716 rc = KS_HANDLE_HIDL_ERROR(op->device, op->device->finish(op->handle, params.hidl_data(),
717 input, signature, op->authToken,
718 op->verificationToken, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700719
720 if (rc.isOk()) {
721 // inform the finalizer that the finish call went through
722 finished = true;
723 // and what the result was
724 rc = result.resultCode;
725 } else {
726 return worker_cb(operationFailed(rc));
727 }
728 return worker_cb(std::move(result));
729 });
730}
731
732void KeymasterWorker::abort(sp<IBinder> token, abort_cb worker_cb) {
733 Worker::addRequest(
734 [this, CAPTURE_MOVE(token), CAPTURE_MOVE(worker_cb)]() { return worker_cb(abort(token)); });
735}
736
737void KeymasterWorker::verifyAuthorization(uint64_t challenge, hidl_vec<KeyParameter> params,
738 HardwareAuthToken token,
739 verifyAuthorization_cb worker_cb) {
740 Worker::addRequest([this, challenge, CAPTURE_MOVE(params), CAPTURE_MOVE(token),
741 CAPTURE_MOVE(worker_cb)]() {
742 KeyStoreServiceReturnCode error;
743 VerificationToken verificationToken;
Janis Danisevskis37896102019-03-14 17:15:06 -0700744 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
745 keymasterDevice_,
746 keymasterDevice_->verifyAuthorization(
747 challenge, params, token, [&](ErrorCode ret, const VerificationToken& vToken) {
748 keymasterDevice_->logIfKeymasterVendorError(ret);
749 error = ret;
750 verificationToken = vToken;
751 }));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700752 worker_cb(rc.isOk() ? error : rc, std::move(token), std::move(verificationToken));
753 });
754}
755
756void KeymasterWorker::addRngEntropy(hidl_vec<uint8_t> data, addRngEntropy_cb _hidl_cb) {
757 addRequest(&Keymaster::addRngEntropy, std::move(_hidl_cb), std::move(data));
758}
759
760namespace {
761bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
762 return params.end() !=
763 std::find_if(params.begin(), params.end(),
764 [&](const KeyParameter& param) { return param.tag == tag; });
765}
766
767bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
768 return !containsTag(params, Tag::NO_AUTH_REQUIRED);
769}
770} // namespace
771
772void KeymasterWorker::generateKey(LockedKeyBlobEntry lockedEntry, hidl_vec<KeyParameter> keyParams,
773 hidl_vec<uint8_t> entropy, int flags, generateKey_cb worker_cb) {
774 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), CAPTURE_MOVE(keyParams),
775 CAPTURE_MOVE(entropy), CAPTURE_MOVE(worker_cb), flags]() mutable {
776 KeyStoreServiceReturnCode rc =
Janis Danisevskis37896102019-03-14 17:15:06 -0700777 KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->addRngEntropy(entropy));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700778 if (!rc.isOk()) {
779 return worker_cb(rc, {});
780 }
781
782 SecurityLevel securityLevel = keymasterDevice_->halVersion().securityLevel;
783
784 // Fallback cannot be considered for Strongbox. Further versions restrictions are enforced
785 // by KeyStore::getFallbackDevice()
786 bool consider_fallback = securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT;
787
788 Finalize logOnFail(
789 [&] { uploadKeyCharacteristicsAsProto(keyParams, false /* wasCreationSuccessful */); });
790
791 KeyCharacteristics outCharacteristics;
792 KeyStoreServiceReturnCode error;
793 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
794 const KeyCharacteristics& keyCharacteristics) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700795 keymasterDevice_->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700796 error = ret;
797 if (!error.isOk()) {
798 return;
799 }
800 consider_fallback = false;
801 outCharacteristics = keyCharacteristics;
802
803 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), nullptr, 0, ::TYPE_KEYMASTER_10);
804 keyBlob.setSecurityLevel(securityLevel);
805 keyBlob.setCriticalToDeviceEncryption(flags &
806 KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
807 if (isAuthenticationBound(keyParams) && !keyBlob.isCriticalToDeviceEncryption()) {
808 keyBlob.setSuperEncrypted(true);
809 }
810 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
811
812 AuthorizationSet sw_enforced = keyParams;
813 sw_enforced.Subtract(outCharacteristics.hardwareEnforced);
814 sw_enforced.Union(outCharacteristics.softwareEnforced);
815 sw_enforced.Filter([](const KeyParameter& param) -> bool {
816 return !(param.tag == Tag::APPLICATION_DATA || param.tag == Tag::APPLICATION_ID);
817 });
818 if (!sw_enforced.Contains(Tag::USER_ID)) {
819 // Most Java processes don't have access to this tag
820 sw_enforced.push_back(keymaster::TAG_USER_ID, get_user_id(lockedEntry->uid()));
821 }
822 Blob keyCharBlob;
823 keyCharBlob.putKeyCharacteristics(outCharacteristics.hardwareEnforced, sw_enforced);
824 error = keyStore_->put(lockedEntry, std::move(keyBlob), std::move(keyCharBlob));
825 };
826
Janis Danisevskis37896102019-03-14 17:15:06 -0700827 rc = KS_HANDLE_HIDL_ERROR(keymasterDevice_,
828 keymasterDevice_->generateKey(keyParams, hidl_cb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700829 if (!rc.isOk()) {
830 return worker_cb(rc, {});
831 }
832
833 if (consider_fallback && !error.isOk()) {
834 auto fallback = keyStore_->getFallbackDevice();
835 if (!fallback) {
836 return worker_cb(error, {});
837 }
838 // No fallback for 3DES
839 for (auto& param : keyParams) {
840 auto algorithm = authorizationValue(TAG_ALGORITHM, param);
841 if (algorithm.isOk() && algorithm.value() == Algorithm::TRIPLE_DES) {
842 return worker_cb(ErrorCode::UNSUPPORTED_ALGORITHM, {});
843 }
844 }
845
846 // delegate to fallback worker
847 fallback->generateKey(std::move(lockedEntry), std::move(keyParams), std::move(entropy),
848 flags, std::move(worker_cb));
849 // let fallback do the logging
850 logOnFail.release();
851 return;
852 }
853
854 if (!error.isOk()) return worker_cb(error, {});
855
856 // log on success
857 logOnFail.release();
858 uploadKeyCharacteristicsAsProto(keyParams, true /* wasCreationSuccessful */);
859
860 return worker_cb(error, std::move(outCharacteristics));
861 });
862}
863
864void KeymasterWorker::generateKey(hidl_vec<KeyParameter> keyParams, generateKey2_cb worker_cb) {
865 addRequest(&Keymaster::generateKey, std::move(worker_cb), std::move(keyParams));
866}
867
868void KeymasterWorker::getKeyCharacteristics(LockedKeyBlobEntry lockedEntry,
869 hidl_vec<uint8_t> clientId, hidl_vec<uint8_t> appData,
870 Blob keyBlob, Blob charBlob,
871 getKeyCharacteristics_cb worker_cb) {
872 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), CAPTURE_MOVE(clientId),
873 CAPTURE_MOVE(appData), CAPTURE_MOVE(keyBlob), CAPTURE_MOVE(charBlob),
874 CAPTURE_MOVE(worker_cb)]() {
875 auto result = createKeyCharacteristicsCache(lockedEntry, clientId, appData,
876 std::move(keyBlob), std::move(charBlob));
877 return worker_cb(std::get<0>(result), std::move(std::get<1>(result)));
878 });
879}
880
881void KeymasterWorker::importKey(LockedKeyBlobEntry lockedEntry, hidl_vec<KeyParameter> keyParams,
882 KeyFormat keyFormat, hidl_vec<uint8_t> keyData, int flags,
883 importKey_cb worker_cb) {
884 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), CAPTURE_MOVE(keyParams), keyFormat,
885 CAPTURE_MOVE(keyData), flags, CAPTURE_MOVE(worker_cb)]() mutable {
886 SecurityLevel securityLevel = keymasterDevice_->halVersion().securityLevel;
887
888 // Fallback cannot be considered for Strongbox. Further versions restrictions are enforced
889 // by KeyStore::getFallbackDevice()
890 bool consider_fallback = securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT;
891
892 Finalize logOnFail(
893 [&] { uploadKeyCharacteristicsAsProto(keyParams, false /* wasCreationSuccessful */); });
894
895 KeyCharacteristics outCharacteristics;
896 KeyStoreServiceReturnCode error;
897 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
898 const KeyCharacteristics& keyCharacteristics) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700899 keymasterDevice_->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700900 error = ret;
901 if (!error.isOk()) {
902 LOG(INFO) << "importKey failed";
903 return;
904 }
905 consider_fallback = false;
906 outCharacteristics = keyCharacteristics;
907
908 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), nullptr, 0, ::TYPE_KEYMASTER_10);
909 keyBlob.setSecurityLevel(securityLevel);
910 keyBlob.setCriticalToDeviceEncryption(flags &
911 KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
912 if (isAuthenticationBound(keyParams) && !keyBlob.isCriticalToDeviceEncryption()) {
913 keyBlob.setSuperEncrypted(true);
914 }
915 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
916
917 AuthorizationSet sw_enforced = keyParams;
918 sw_enforced.Subtract(outCharacteristics.hardwareEnforced);
919 sw_enforced.Union(outCharacteristics.softwareEnforced);
920 sw_enforced.Filter([](const KeyParameter& param) -> bool {
921 return !(param.tag == Tag::APPLICATION_DATA || param.tag == Tag::APPLICATION_ID);
922 });
923 if (!sw_enforced.Contains(Tag::USER_ID)) {
924 // Most Java processes don't have access to this tag
925 sw_enforced.push_back(keymaster::TAG_USER_ID, get_user_id(lockedEntry->uid()));
926 }
927 Blob keyCharBlob;
928 keyCharBlob.putKeyCharacteristics(outCharacteristics.hardwareEnforced, sw_enforced);
929 error = keyStore_->put(lockedEntry, std::move(keyBlob), std::move(keyCharBlob));
930 };
931
932 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
Janis Danisevskis37896102019-03-14 17:15:06 -0700933 keymasterDevice_, keymasterDevice_->importKey(keyParams, keyFormat, keyData, hidl_cb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700934 if (!rc.isOk()) {
935 return worker_cb(rc, {});
936 }
937
938 if (consider_fallback && !error.isOk()) {
939 auto fallback = keyStore_->getFallbackDevice();
940 if (!fallback) {
941 return worker_cb(error, {});
942 }
943 // No fallback for 3DES
944 for (auto& param : keyParams) {
945 auto algorithm = authorizationValue(TAG_ALGORITHM, param);
946 if (algorithm.isOk() && algorithm.value() == Algorithm::TRIPLE_DES) {
947 return worker_cb(ErrorCode::UNSUPPORTED_ALGORITHM, {});
948 }
949 }
950
951 // delegate to fallback worker
952 fallback->importKey(std::move(lockedEntry), std::move(keyParams), keyFormat,
953 std::move(keyData), flags, std::move(worker_cb));
954 // let fallback to the logging
955 logOnFail.release();
956 return;
957 }
958
959 if (!error.isOk()) return worker_cb(error, {});
960
961 // log on success
962 logOnFail.release();
963 uploadKeyCharacteristicsAsProto(keyParams, true /* wasCreationSuccessful */);
964
965 return worker_cb(error, std::move(outCharacteristics));
966 });
967}
968
969void KeymasterWorker::importWrappedKey(LockedKeyBlobEntry wrappingLockedEntry,
970 LockedKeyBlobEntry wrapppedLockedEntry,
971 hidl_vec<uint8_t> wrappedKeyData,
972 hidl_vec<uint8_t> maskingKey,
973 hidl_vec<KeyParameter> unwrappingParams, Blob wrappingBlob,
974 Blob wrappingCharBlob, uint64_t passwordSid,
975 uint64_t biometricSid, importWrappedKey_cb worker_cb) {
976 Worker::addRequest([this, CAPTURE_MOVE(wrappingLockedEntry), CAPTURE_MOVE(wrapppedLockedEntry),
977 CAPTURE_MOVE(wrappedKeyData), CAPTURE_MOVE(maskingKey),
978 CAPTURE_MOVE(unwrappingParams), CAPTURE_MOVE(wrappingBlob),
979 CAPTURE_MOVE(wrappingCharBlob), passwordSid, biometricSid,
980 CAPTURE_MOVE(worker_cb)]() mutable {
981 auto hidlWrappingKey = blob2hidlVec(wrappingBlob);
982
983 SecurityLevel securityLevel = keymasterDevice_->halVersion().securityLevel;
984
985 KeyCharacteristics outCharacteristics;
986 KeyStoreServiceReturnCode error;
987
988 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
989 const KeyCharacteristics& keyCharacteristics) {
Janis Danisevskis37896102019-03-14 17:15:06 -0700990 keymasterDevice_->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700991 error = ret;
992 if (!error.isOk()) {
993 return;
994 }
995 outCharacteristics = keyCharacteristics;
996
997 Blob keyBlob(hidlKeyBlob.data(), hidlKeyBlob.size(), nullptr, 0, ::TYPE_KEYMASTER_10);
998 keyBlob.setSecurityLevel(securityLevel);
999 if (isAuthenticationBound(keyCharacteristics.hardwareEnforced)) {
1000 keyBlob.setSuperEncrypted(true);
1001 }
1002
1003 AuthorizationSet sw_enforced = outCharacteristics.softwareEnforced;
1004 if (!sw_enforced.Contains(Tag::USER_ID)) {
1005 // Most Java processes don't have access to this tag
1006 sw_enforced.push_back(keymaster::TAG_USER_ID,
1007 get_user_id(wrapppedLockedEntry->uid()));
1008 }
1009 Blob keyCharBlob;
1010 keyCharBlob.putKeyCharacteristics(outCharacteristics.hardwareEnforced, sw_enforced);
1011 error = keyStore_->put(wrapppedLockedEntry, std::move(keyBlob), std::move(keyCharBlob));
1012 };
1013
Janis Danisevskis37896102019-03-14 17:15:06 -07001014 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1015 keymasterDevice_, keymasterDevice_->importWrappedKey(
1016 wrappedKeyData, hidlWrappingKey, maskingKey, unwrappingParams,
1017 passwordSid, biometricSid, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001018
1019 // possible hidl error
1020 if (!rc.isOk()) {
1021 return worker_cb(rc, {});
1022 }
1023
1024 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
1025 std::tie(rc, wrappingBlob) = upgradeKeyBlob(wrappingLockedEntry, {});
1026 if (!rc.isOk()) {
1027 return worker_cb(rc, {});
1028 }
1029
1030 auto upgradedHidlKeyBlob = blob2hidlVec(wrappingBlob);
1031
Janis Danisevskis37896102019-03-14 17:15:06 -07001032 rc = KS_HANDLE_HIDL_ERROR(keymasterDevice_,
1033 keymasterDevice_->importWrappedKey(
1034 wrappedKeyData, upgradedHidlKeyBlob, maskingKey,
1035 unwrappingParams, passwordSid, biometricSid, hidlCb));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001036 if (!rc.isOk()) {
1037 error = rc;
1038 }
1039 }
1040 return worker_cb(error, std::move(outCharacteristics));
1041 });
1042}
1043
1044void KeymasterWorker::exportKey(LockedKeyBlobEntry lockedEntry, KeyFormat exportFormat,
1045 hidl_vec<uint8_t> clientId, hidl_vec<uint8_t> appData, Blob keyBlob,
1046 Blob charBlob, exportKey_cb worker_cb) {
1047 Worker::addRequest([this, CAPTURE_MOVE(lockedEntry), exportFormat, CAPTURE_MOVE(clientId),
1048 CAPTURE_MOVE(appData), CAPTURE_MOVE(keyBlob), CAPTURE_MOVE(charBlob),
1049 CAPTURE_MOVE(worker_cb)]() mutable {
1050 auto key = blob2hidlVec(keyBlob);
1051
1052 ExportResult result;
1053 auto hidlCb = [&](ErrorCode ret,
1054 const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
Janis Danisevskis37896102019-03-14 17:15:06 -07001055 keymasterDevice_->logIfKeymasterVendorError(ret);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001056 result.resultCode = ret;
1057 if (!result.resultCode.isOk()) {
1058 if (result.resultCode == ErrorCode::INVALID_KEY_BLOB) {
1059 log_key_integrity_violation(lockedEntry->alias().c_str(), lockedEntry->uid());
1060 }
1061 return;
1062 }
1063 result.exportData = keyMaterial;
1064 };
1065 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
Janis Danisevskis37896102019-03-14 17:15:06 -07001066 keymasterDevice_,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001067 keymasterDevice_->exportKey(exportFormat, key, clientId, appData, hidlCb));
1068
1069 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
1070 // callback hidlCb.
1071 if (!rc.isOk()) {
1072 result.resultCode = rc;
1073 }
1074
1075 if (result.resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1076 AuthorizationSet upgradeParams;
1077 if (clientId.size()) {
1078 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
1079 }
1080 if (appData.size()) {
1081 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
1082 }
1083 std::tie(rc, keyBlob) = upgradeKeyBlob(lockedEntry, upgradeParams);
1084 if (!rc.isOk()) {
1085 return worker_cb(std::move(result));
1086 }
1087
1088 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1089
Janis Danisevskis37896102019-03-14 17:15:06 -07001090 rc = KS_HANDLE_HIDL_ERROR(keymasterDevice_,
1091 keymasterDevice_->exportKey(exportFormat, upgradedHidlKeyBlob,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001092 clientId, appData, hidlCb));
1093 if (!rc.isOk()) {
1094 result.resultCode = rc;
1095 }
1096 }
1097 return worker_cb(std::move(result));
1098 });
1099}
1100void KeymasterWorker::attestKey(hidl_vec<uint8_t> keyToAttest, hidl_vec<KeyParameter> attestParams,
1101 attestKey_cb worker_cb) {
1102 addRequest(&Keymaster::attestKey, std::move(worker_cb), std::move(keyToAttest),
1103 std::move(attestParams));
1104}
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001105
1106void KeymasterWorker::deleteKey(hidl_vec<uint8_t> keyBlob, deleteKey_cb _hidl_cb) {
1107 addRequest(&Keymaster::deleteKey, std::move(_hidl_cb), std::move(keyBlob));
1108}
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001109
1110void KeymasterWorker::binderDied(android::wp<IBinder> who) {
1111 Worker::addRequest([this, who]() {
1112 auto operations = operationMap_.getOperationsForToken(who.unsafe_get());
1113 for (const auto& token : operations) {
1114 abort(token);
Janis Danisevskisbec89992019-08-14 13:42:19 -07001115 keyStore_->removeOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001116 }
1117 });
1118}
1119
1120} // namespace keystore