• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
31 namespace keystore {
32 
33 constexpr size_t kMaxOperations = 15;
34 
35 using AndroidKeymasterArguments = android::security::keymaster::KeymasterArguments;
36 using android::security::keymaster::ExportResult;
37 using android::security::keymaster::operationFailed;
38 using android::security::keymaster::OperationResult;
39 
Worker()40 Worker::Worker() {}
~Worker()41 Worker::~Worker() {
42     std::unique_lock<std::mutex> lock(pending_requests_mutex_);
43     pending_requests_cond_var_.wait(lock, [this] { return pending_requests_.empty(); });
44 }
addRequest(WorkerTask request)45 void Worker::addRequest(WorkerTask request) {
46     std::unique_lock<std::mutex> lock(pending_requests_mutex_);
47     bool start_thread = pending_requests_.empty();
48     pending_requests_.push(std::move(request));
49     lock.unlock();
50     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     }
65 }
66 
KeymasterWorker(sp<Keymaster> keymasterDevice,KeyStore * keyStore)67 KeymasterWorker::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 
logIfKeymasterVendorError(ErrorCode ec) const73 void KeymasterWorker::logIfKeymasterVendorError(ErrorCode ec) const {
74     keymasterDevice_->logIfKeymasterVendorError(ec);
75 }
76 
77 std::tuple<KeyStoreServiceReturnCode, Blob>
upgradeKeyBlob(const LockedKeyBlobEntry & lockedEntry,const AuthorizationSet & params)78 KeymasterWorker::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 
95     userState = {};
96 
97     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) {
105         dev->logIfKeymasterVendorError(ret);
106         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()) {
116             ALOGI("upgradeKeyBlob keystore->del failed %d", error.getErrorCode());
117             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()) {
129             ALOGI("upgradeKeyBlob keystore->put failed %d", error.getErrorCode());
130             return;
131         }
132         blob = std::move(newBlob);
133     };
134 
135     KeyStoreServiceReturnCode error2;
136     error2 = KS_HANDLE_HIDL_ERROR(dev, dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
137     if (!error2.isOk()) {
138         return error = error2, result;
139     }
140 
141     return result;
142 }
143 
144 std::tuple<KeyStoreServiceReturnCode, KeyCharacteristics, Blob, Blob>
createKeyCharacteristicsCache(const LockedKeyBlobEntry & lockedEntry,const hidl_vec<uint8_t> & clientId,const hidl_vec<uint8_t> & appData,Blob keyBlob,Blob charBlob)145 KeymasterWorker::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) {
179         dev->logIfKeymasterVendorError(ret);
180         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(
216             dev, dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
217         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(
237                 dev, dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
238             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  */
263 std::pair<KeyStoreServiceReturnCode, HardwareAuthToken>
getAuthToken(const KeyCharacteristics & characteristics,uint64_t handle,KeyPurpose purpose,bool failOnTokenMissing)264 KeymasterWorker::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 
abort(const sp<IBinder> & token)304 KeyStoreServiceReturnCode KeymasterWorker::abort(const sp<IBinder>& token) {
305     auto op = operationMap_.removeOperation(token, false /* wasOpSuccessful */);
306     if (op) {
307         keyStore_->getAuthTokenTable().MarkCompleted(op->handle);
308         return KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->abort(op->handle));
309     } else {
310         return ErrorCode::INVALID_OPERATION_HANDLE;
311     }
312 }
313 
314 /**
315  * Prune the oldest pruneable operation.
316  */
pruneOperation()317 bool 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) {
325         ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), rc.getErrorCode());
326         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 
begin(LockedKeyBlobEntry lockedEntry,sp<IBinder> appToken,Blob keyBlob,Blob charBlob,bool pruneable,KeyPurpose purpose,AuthorizationSet opParams,hidl_vec<uint8_t> entropy,worker_begin_cb worker_cb)337 void 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 
348         auto& dev = keymasterDevice_;
349 
350         KeyCharacteristics characteristics;
351 
352         {
353             hidl_vec<uint8_t> clientId;
354             hidl_vec<uint8_t> appData;
355             for (const auto& param : opParams) {
356                 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()) {
385             rc = KS_HANDLE_HIDL_ERROR(dev, dev->addRngEntropy(entropy));
386             if (!rc.isOk()) {
387                 return worker_cb(operationFailed(rc));
388             }
389         }
390 
391         // Create a keyid for this key.
392         auto keyid = KeymasterEnforcement::CreateKeyId(blob2hidlVec(keyBlob));
393         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) {
423             dev->logIfKeymasterVendorError(ret);
424             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 {
436             rc = KS_HANDLE_HIDL_ERROR(dev, dev->begin(purpose, blob2hidlVec(keyBlob),
437                                                       opParams.hidl_data(), authToken, hidlCb));
438             if (!rc.isOk()) {
439                 LOG(ERROR) << "Got error " << rc << " from begin()";
440                 return worker_cb(operationFailed(ResponseCode::SYSTEM_ERROR));
441             }
442 
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 
449                 rc = KS_HANDLE_HIDL_ERROR(dev, dev->begin(purpose, blob2hidlVec(keyBlob),
450                                                           opParams.hidl_data(), authToken, hidlCb));
451                 if (!rc.isOk()) {
452                     LOG(ERROR) << "Got error " << rc << " from begin()";
453                     return worker_cb(operationFailed(ResponseCode::SYSTEM_ERROR));
454                 }
455             }
456             // 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 
515 KeyStoreServiceReturnCode
getOperationAuthTokenIfNeeded(std::shared_ptr<Operation> op)516 KeymasterWorker::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 
538 namespace {
539 
540 class Finalize {
541   private:
542     std::function<void()> f_;
543 
544   public:
Finalize(std::function<void ()> f)545     explicit Finalize(std::function<void()> f) : f_(f) {}
~Finalize()546     ~Finalize() {
547         if (f_) f_();
548     }
release()549     void release() { f_ = {}; }
550 };
551 
552 }  // namespace
553 
update(sp<IBinder> token,AuthorizationSet params,hidl_vec<uint8_t> data,update_cb worker_cb)554 void 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);
567             KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->abort(op->handle));
568         });
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) {
587             op->device->logIfKeymasterVendorError(ret);
588             result.resultCode = ret;
589             if (result.resultCode.isOk()) {
590                 result.inputConsumed = inputConsumed;
591                 result.outParams = outParams;
592                 result.data = output;
593             }
594         };
595 
596         rc = KS_HANDLE_HIDL_ERROR(op->device,
597                                   op->device->update(op->handle, params.hidl_data(), data,
598                                                      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  */
615 template <typename ParamsIter>
checkAllowedOperationParams(ParamsIter begin,const ParamsIter end)616 static 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 
finish(sp<IBinder> token,AuthorizationSet params,hidl_vec<uint8_t> input,hidl_vec<uint8_t> signature,hidl_vec<uint8_t> entropy,finish_cb worker_cb)630 void 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);
646             if (!finished)
647                 KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->abort(op->handle));
648         });
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()) {
678             rc = KS_HANDLE_HIDL_ERROR(op->device, op->device->addRngEntropy(entropy));
679             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) {
687             op->device->logIfKeymasterVendorError(ret);
688             result.resultCode = ret;
689             if (result.resultCode.isOk()) {
690                 result.outParams = outParams;
691                 result.data = output;
692             }
693         };
694 
695         rc = KS_HANDLE_HIDL_ERROR(op->device, op->device->finish(op->handle, params.hidl_data(),
696                                                                  input, signature, op->authToken,
697                                                                  op->verificationToken, hidlCb));
698 
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 
abort(sp<IBinder> token,abort_cb worker_cb)711 void 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 
verifyAuthorization(uint64_t challenge,hidl_vec<KeyParameter> params,HardwareAuthToken token,verifyAuthorization_cb worker_cb)716 void 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;
723         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                 }));
731         worker_cb(rc.isOk() ? error : rc, std::move(token), std::move(verificationToken));
732     });
733 }
734 
addRngEntropy(hidl_vec<uint8_t> data,addRngEntropy_cb _hidl_cb)735 void KeymasterWorker::addRngEntropy(hidl_vec<uint8_t> data, addRngEntropy_cb _hidl_cb) {
736     addRequest(&Keymaster::addRngEntropy, std::move(_hidl_cb), std::move(data));
737 }
738 
739 namespace {
containsTag(const hidl_vec<KeyParameter> & params,Tag tag)740 bool 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 
isAuthenticationBound(const hidl_vec<KeyParameter> & params)746 bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
747     return !containsTag(params, Tag::NO_AUTH_REQUIRED);
748 }
749 }  // namespace
750 
generateKey(LockedKeyBlobEntry lockedEntry,hidl_vec<KeyParameter> keyParams,hidl_vec<uint8_t> entropy,int flags,generateKey_cb worker_cb)751 void 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 =
756             KS_HANDLE_HIDL_ERROR(keymasterDevice_, keymasterDevice_->addRngEntropy(entropy));
757         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) {
774             keymasterDevice_->logIfKeymasterVendorError(ret);
775             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 
806         rc = KS_HANDLE_HIDL_ERROR(keymasterDevice_,
807                                   keymasterDevice_->generateKey(keyParams, hidl_cb));
808         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 
generateKey(hidl_vec<KeyParameter> keyParams,generateKey2_cb worker_cb)843 void KeymasterWorker::generateKey(hidl_vec<KeyParameter> keyParams, generateKey2_cb worker_cb) {
844     addRequest(&Keymaster::generateKey, std::move(worker_cb), std::move(keyParams));
845 }
846 
getKeyCharacteristics(LockedKeyBlobEntry lockedEntry,hidl_vec<uint8_t> clientId,hidl_vec<uint8_t> appData,Blob keyBlob,Blob charBlob,getKeyCharacteristics_cb worker_cb)847 void 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 
importKey(LockedKeyBlobEntry lockedEntry,hidl_vec<KeyParameter> keyParams,KeyFormat keyFormat,hidl_vec<uint8_t> keyData,int flags,importKey_cb worker_cb)860 void 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) {
878             keymasterDevice_->logIfKeymasterVendorError(ret);
879             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(
912             keymasterDevice_, keymasterDevice_->importKey(keyParams, keyFormat, keyData, hidl_cb));
913         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 
importWrappedKey(LockedKeyBlobEntry wrappingLockedEntry,LockedKeyBlobEntry wrapppedLockedEntry,hidl_vec<uint8_t> wrappedKeyData,hidl_vec<uint8_t> maskingKey,hidl_vec<KeyParameter> unwrappingParams,Blob wrappingBlob,Blob wrappingCharBlob,uint64_t passwordSid,uint64_t biometricSid,importWrappedKey_cb worker_cb)948 void 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) {
969             keymasterDevice_->logIfKeymasterVendorError(ret);
970             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 
993         KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
994             keymasterDevice_, keymasterDevice_->importWrappedKey(
995                                   wrappedKeyData, hidlWrappingKey, maskingKey, unwrappingParams,
996                                   passwordSid, biometricSid, hidlCb));
997 
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 
1011             rc = KS_HANDLE_HIDL_ERROR(keymasterDevice_,
1012                                       keymasterDevice_->importWrappedKey(
1013                                           wrappedKeyData, upgradedHidlKeyBlob, maskingKey,
1014                                           unwrappingParams, passwordSid, biometricSid, hidlCb));
1015             if (!rc.isOk()) {
1016                 error = rc;
1017             }
1018         }
1019         return worker_cb(error, std::move(outCharacteristics));
1020     });
1021 }
1022 
exportKey(LockedKeyBlobEntry lockedEntry,KeyFormat exportFormat,hidl_vec<uint8_t> clientId,hidl_vec<uint8_t> appData,Blob keyBlob,Blob charBlob,exportKey_cb worker_cb)1023 void 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) {
1034             keymasterDevice_->logIfKeymasterVendorError(ret);
1035             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(
1045             keymasterDevice_,
1046             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 
1069             rc = KS_HANDLE_HIDL_ERROR(keymasterDevice_,
1070                                       keymasterDevice_->exportKey(exportFormat, upgradedHidlKeyBlob,
1071                                                                   clientId, appData, hidlCb));
1072             if (!rc.isOk()) {
1073                 result.resultCode = rc;
1074             }
1075         }
1076         return worker_cb(std::move(result));
1077     });
1078 }
attestKey(hidl_vec<uint8_t> keyToAttest,hidl_vec<KeyParameter> attestParams,attestKey_cb worker_cb)1079 void 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 }
1084 
deleteKey(hidl_vec<uint8_t> keyBlob,deleteKey_cb _hidl_cb)1085 void KeymasterWorker::deleteKey(hidl_vec<uint8_t> keyBlob, deleteKey_cb _hidl_cb) {
1086     addRequest(&Keymaster::deleteKey, std::move(_hidl_cb), std::move(keyBlob));
1087 }
1088 
binderDied(android::wp<IBinder> who)1089 void 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
1099