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