• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "km_compat.h"
18 
19 #include "km_compat_type_conversion.h"
20 #include <AndroidKeyMintDevice.h>
21 #include <aidl/android/hardware/security/keymint/Algorithm.h>
22 #include <aidl/android/hardware/security/keymint/Digest.h>
23 #include <aidl/android/hardware/security/keymint/ErrorCode.h>
24 #include <aidl/android/hardware/security/keymint/KeyParameterValue.h>
25 #include <aidl/android/hardware/security/keymint/PaddingMode.h>
26 #include <aidl/android/system/keystore2/ResponseCode.h>
27 #include <android-base/logging.h>
28 #include <android/hidl/manager/1.2/IServiceManager.h>
29 #include <binder/IServiceManager.h>
30 #include <hardware/keymaster_defs.h>
31 #include <keymasterV4_1/Keymaster.h>
32 #include <keymasterV4_1/Keymaster3.h>
33 #include <keymasterV4_1/Keymaster4.h>
34 
35 #include <chrono>
36 
37 #include "certificate_utils.h"
38 
39 using ::aidl::android::hardware::security::keymint::Algorithm;
40 using ::aidl::android::hardware::security::keymint::CreateKeyMintDevice;
41 using ::aidl::android::hardware::security::keymint::Digest;
42 using ::aidl::android::hardware::security::keymint::KeyParameterValue;
43 using ::aidl::android::hardware::security::keymint::PaddingMode;
44 using ::aidl::android::hardware::security::keymint::Tag;
45 using ::aidl::android::system::keystore2::ResponseCode;
46 using ::android::hardware::hidl_vec;
47 using ::android::hardware::keymaster::V4_0::TagType;
48 using ::android::hidl::manager::V1_2::IServiceManager;
49 using V4_0_HardwareAuthToken = ::android::hardware::keymaster::V4_0::HardwareAuthToken;
50 using V4_0_HmacSharingParameters = ::android::hardware::keymaster::V4_0::HmacSharingParameters;
51 using V4_0_KeyCharacteristics = ::android::hardware::keymaster::V4_0::KeyCharacteristics;
52 using V4_0_KeyFormat = ::android::hardware::keymaster::V4_0::KeyFormat;
53 using V4_0_KeyParameter = ::android::hardware::keymaster::V4_0::KeyParameter;
54 using V4_0_VerificationToken = ::android::hardware::keymaster::V4_0::VerificationToken;
55 namespace V4_0 = ::android::hardware::keymaster::V4_0;
56 namespace V4_1 = ::android::hardware::keymaster::V4_1;
57 namespace KMV1 = ::aidl::android::hardware::security::keymint;
58 
59 using namespace std::chrono_literals;
60 using std::chrono::duration_cast;
61 
62 // Utility functions
63 
64 // Returns true if this parameter may be passed to attestKey.
isAttestationParameter(const KMV1::KeyParameter & param)65 bool isAttestationParameter(const KMV1::KeyParameter& param) {
66     switch (param.tag) {
67     case Tag::APPLICATION_ID:
68     case Tag::APPLICATION_DATA:
69     case Tag::ATTESTATION_CHALLENGE:
70     case Tag::ATTESTATION_APPLICATION_ID:
71     case Tag::ATTESTATION_ID_BRAND:
72     case Tag::ATTESTATION_ID_DEVICE:
73     case Tag::ATTESTATION_ID_PRODUCT:
74     case Tag::ATTESTATION_ID_SERIAL:
75     case Tag::ATTESTATION_ID_IMEI:
76     case Tag::ATTESTATION_ID_MEID:
77     case Tag::ATTESTATION_ID_MANUFACTURER:
78     case Tag::ATTESTATION_ID_MODEL:
79     case Tag::CERTIFICATE_SERIAL:
80     case Tag::CERTIFICATE_SUBJECT:
81     case Tag::CERTIFICATE_NOT_BEFORE:
82     case Tag::CERTIFICATE_NOT_AFTER:
83     case Tag::DEVICE_UNIQUE_ATTESTATION:
84         return true;
85     default:
86         return false;
87     }
88 }
89 
90 // Returns true if this parameter may be passed to generate/importKey.
isKeyCreationParameter(const KMV1::KeyParameter & param)91 bool isKeyCreationParameter(const KMV1::KeyParameter& param) {
92     switch (param.tag) {
93     case Tag::APPLICATION_ID:
94     case Tag::APPLICATION_DATA:
95     case Tag::CERTIFICATE_SERIAL:
96     case Tag::CERTIFICATE_SUBJECT:
97     case Tag::CERTIFICATE_NOT_BEFORE:
98     case Tag::CERTIFICATE_NOT_AFTER:
99     case Tag::PURPOSE:
100     case Tag::ALGORITHM:
101     case Tag::KEY_SIZE:
102     case Tag::BLOCK_MODE:
103     case Tag::DIGEST:
104     case Tag::PADDING:
105     case Tag::CALLER_NONCE:
106     case Tag::MIN_MAC_LENGTH:
107     case Tag::EC_CURVE:
108     case Tag::RSA_PUBLIC_EXPONENT:
109     case Tag::RSA_OAEP_MGF_DIGEST:
110     case Tag::BOOTLOADER_ONLY:
111     case Tag::ROLLBACK_RESISTANCE:
112     case Tag::EARLY_BOOT_ONLY:
113     case Tag::ACTIVE_DATETIME:
114     case Tag::ORIGINATION_EXPIRE_DATETIME:
115     case Tag::USAGE_EXPIRE_DATETIME:
116     case Tag::MIN_SECONDS_BETWEEN_OPS:
117     case Tag::MAX_USES_PER_BOOT:
118     case Tag::USAGE_COUNT_LIMIT:
119     case Tag::USER_ID:
120     case Tag::USER_SECURE_ID:
121     case Tag::NO_AUTH_REQUIRED:
122     case Tag::USER_AUTH_TYPE:
123     case Tag::AUTH_TIMEOUT:
124     case Tag::ALLOW_WHILE_ON_BODY:
125     case Tag::TRUSTED_USER_PRESENCE_REQUIRED:
126     case Tag::TRUSTED_CONFIRMATION_REQUIRED:
127     case Tag::UNLOCKED_DEVICE_REQUIRED:
128     case Tag::CREATION_DATETIME:
129     case Tag::INCLUDE_UNIQUE_ID:
130     case Tag::IDENTITY_CREDENTIAL_KEY:
131     case Tag::STORAGE_KEY:
132     case Tag::MAC_LENGTH:
133         return true;
134     default:
135         return false;
136     }
137 }
138 
139 // Size of prefix for blobs, see keyBlobPrefix().
140 //
141 const size_t kKeyBlobPrefixSize = 8;
142 
143 // Magic used in blob prefix, see keyBlobPrefix().
144 //
145 const uint8_t kKeyBlobMagic[7] = {'p', 'K', 'M', 'b', 'l', 'o', 'b'};
146 
147 // Prefixes a keyblob returned by e.g. generateKey() with information on whether it
148 // originated from the real underlying KeyMaster HAL or from soft-KeyMint.
149 //
150 // When dealing with a keyblob, use prefixedKeyBlobRemovePrefix() to remove the
151 // prefix and prefixedKeyBlobIsSoftKeyMint() to determine its origin.
152 //
153 // Note how the prefix itself has a magic marker ("pKMblob") which can be used
154 // to identify if a blob has a prefix at all (it's assumed that any valid blob
155 // from KeyMint or KeyMaster HALs never starts with the magic). This is needed
156 // because blobs persisted to disk prior to using this code will not have the
157 // prefix and in that case we want prefixedKeyBlobRemovePrefix() to still work.
158 //
keyBlobPrefix(const std::vector<uint8_t> & blob,bool isSoftKeyMint)159 std::vector<uint8_t> keyBlobPrefix(const std::vector<uint8_t>& blob, bool isSoftKeyMint) {
160     std::vector<uint8_t> result;
161     result.reserve(blob.size() + kKeyBlobPrefixSize);
162     result.insert(result.begin(), kKeyBlobMagic, kKeyBlobMagic + sizeof kKeyBlobMagic);
163     result.push_back(isSoftKeyMint ? 1 : 0);
164     std::copy(blob.begin(), blob.end(), std::back_inserter(result));
165     return result;
166 }
167 
168 // Helper for prefixedKeyBlobRemovePrefix() and prefixedKeyBlobIsSoftKeyMint().
169 //
170 // First bool is whether there's a valid prefix. If there is, the second bool is
171 // the |isSoftKeyMint| value of the prefix
172 //
prefixedKeyBlobParsePrefix(const std::vector<uint8_t> & prefixedBlob)173 std::pair<bool, bool> prefixedKeyBlobParsePrefix(const std::vector<uint8_t>& prefixedBlob) {
174     // Having a unprefixed blob is not that uncommon, for example all devices
175     // upgrading to keystore2 (so e.g. upgrading to Android 12) will have
176     // unprefixed blobs. So don't spew warnings/errors in this case...
177     if (prefixedBlob.size() < kKeyBlobPrefixSize) {
178         return std::make_pair(false, false);
179     }
180     if (std::memcmp(prefixedBlob.data(), kKeyBlobMagic, sizeof kKeyBlobMagic) != 0) {
181         return std::make_pair(false, false);
182     }
183     if (prefixedBlob[kKeyBlobPrefixSize - 1] != 0 && prefixedBlob[kKeyBlobPrefixSize - 1] != 1) {
184         return std::make_pair(false, false);
185     }
186     bool isSoftKeyMint = (prefixedBlob[kKeyBlobPrefixSize - 1] == 1);
187     return std::make_pair(true, isSoftKeyMint);
188 }
189 
190 // Removes the prefix from a blob. If there's no prefix, returns the passed-in blob.
191 //
prefixedKeyBlobRemovePrefix(const std::vector<uint8_t> & prefixedBlob)192 std::vector<uint8_t> prefixedKeyBlobRemovePrefix(const std::vector<uint8_t>& prefixedBlob) {
193     auto parsed = prefixedKeyBlobParsePrefix(prefixedBlob);
194     if (!parsed.first) {
195         // Not actually prefixed, blob was probably persisted to disk prior to the
196         // prefixing code being introduced.
197         return prefixedBlob;
198     }
199     return std::vector<uint8_t>(prefixedBlob.begin() + kKeyBlobPrefixSize, prefixedBlob.end());
200 }
201 
202 // Returns true if the blob's origin is soft-KeyMint, false otherwise or if there
203 // is no prefix on the passed-in blob.
204 //
prefixedKeyBlobIsSoftKeyMint(const std::vector<uint8_t> & prefixedBlob)205 bool prefixedKeyBlobIsSoftKeyMint(const std::vector<uint8_t>& prefixedBlob) {
206     auto parsed = prefixedKeyBlobParsePrefix(prefixedBlob);
207     return parsed.second;
208 }
209 
210 // Inspects the given blob for prefixes.
211 // Returns the blob stripped of the prefix if present. The boolean argument is true if the blob was
212 // a software blob.
213 std::pair<std::vector<uint8_t>, bool>
dissectPrefixedKeyBlob(const std::vector<uint8_t> & prefixedBlob)214 dissectPrefixedKeyBlob(const std::vector<uint8_t>& prefixedBlob) {
215     auto [hasPrefix, isSoftware] = prefixedKeyBlobParsePrefix(prefixedBlob);
216     if (!hasPrefix) {
217         // Not actually prefixed, blob was probably persisted to disk prior to the
218         // prefixing code being introduced.
219         return {prefixedBlob, false};
220     }
221     return {std::vector<uint8_t>(prefixedBlob.begin() + kKeyBlobPrefixSize, prefixedBlob.end()),
222             isSoftware};
223 }
224 
225 /*
226  * Returns true if the parameter is not understood by KM 4.1 and older but can be enforced by
227  * Keystore. These parameters need to be included in the returned KeyCharacteristics, but will not
228  * be passed to the legacy backend.
229  */
isNewAndKeystoreEnforceable(const KMV1::KeyParameter & param)230 bool isNewAndKeystoreEnforceable(const KMV1::KeyParameter& param) {
231     switch (param.tag) {
232     case KMV1::Tag::MAX_BOOT_LEVEL:
233         return true;
234     case KMV1::Tag::USAGE_COUNT_LIMIT:
235         return true;
236     default:
237         return false;
238     }
239 }
240 
241 std::vector<KMV1::KeyParameter>
extractGenerationParams(const std::vector<KMV1::KeyParameter> & params)242 extractGenerationParams(const std::vector<KMV1::KeyParameter>& params) {
243     std::vector<KMV1::KeyParameter> result;
244     std::copy_if(params.begin(), params.end(), std::back_inserter(result), isKeyCreationParameter);
245     return result;
246 }
247 
248 std::vector<KMV1::KeyParameter>
extractAttestationParams(const std::vector<KMV1::KeyParameter> & params)249 extractAttestationParams(const std::vector<KMV1::KeyParameter>& params) {
250     std::vector<KMV1::KeyParameter> result;
251     std::copy_if(params.begin(), params.end(), std::back_inserter(result), isAttestationParameter);
252     return result;
253 }
254 
255 std::vector<KMV1::KeyParameter>
extractNewAndKeystoreEnforceableParams(const std::vector<KMV1::KeyParameter> & params)256 extractNewAndKeystoreEnforceableParams(const std::vector<KMV1::KeyParameter>& params) {
257     std::vector<KMV1::KeyParameter> result;
258     std::copy_if(params.begin(), params.end(), std::back_inserter(result),
259                  isNewAndKeystoreEnforceable);
260     return result;
261 }
262 
convertErrorCode(KMV1::ErrorCode result)263 ScopedAStatus convertErrorCode(KMV1::ErrorCode result) {
264     if (result == KMV1::ErrorCode::OK) {
265         return ScopedAStatus::ok();
266     }
267     return ScopedAStatus::fromServiceSpecificError(static_cast<int32_t>(result));
268 }
269 
270 // Converts a V4 error code into a ScopedAStatus
convertErrorCode(V4_0_ErrorCode result)271 ScopedAStatus convertErrorCode(V4_0_ErrorCode result) {
272     return convertErrorCode(convert(result));
273 }
274 
toErrorCode(const ScopedAStatus & status)275 static KMV1::ErrorCode toErrorCode(const ScopedAStatus& status) {
276     if (status.getExceptionCode() == EX_SERVICE_SPECIFIC) {
277         return static_cast<KMV1::ErrorCode>(status.getServiceSpecificError());
278     } else {
279         return KMV1::ErrorCode::UNKNOWN_ERROR;
280     }
281 }
282 
283 static std::vector<V4_0::KeyParameter>
convertKeyParametersToLegacy(const std::vector<KeyParameter> & kps)284 convertKeyParametersToLegacy(const std::vector<KeyParameter>& kps) {
285     std::vector<V4_0::KeyParameter> legacyKps;
286     legacyKps.reserve(kps.size());
287     for (const auto& kp : kps) {
288         auto p = convertKeyParameterToLegacy(kp);
289         if (p.tag != V4_0::Tag::INVALID) {
290             legacyKps.push_back(std::move(p));
291         }
292     }
293     return legacyKps;
294 }
295 
296 static std::vector<KeyParameter>
convertKeyParametersFromLegacy(const std::vector<V4_0_KeyParameter> & legacyKps)297 convertKeyParametersFromLegacy(const std::vector<V4_0_KeyParameter>& legacyKps) {
298     std::vector<KeyParameter> kps(legacyKps.size());
299     std::transform(legacyKps.begin(), legacyKps.end(), kps.begin(), convertKeyParameterFromLegacy);
300     return kps;
301 }
302 
303 static std::vector<KeyCharacteristics>
processLegacyCharacteristics(KeyMintSecurityLevel securityLevel,const std::vector<KeyParameter> & genParams,const V4_0_KeyCharacteristics & legacyKc,bool kmEnforcedOnly=false)304 processLegacyCharacteristics(KeyMintSecurityLevel securityLevel,
305                              const std::vector<KeyParameter>& genParams,
306                              const V4_0_KeyCharacteristics& legacyKc, bool kmEnforcedOnly = false) {
307 
308     KeyCharacteristics kmEnforced{securityLevel, convertKeyParametersFromLegacy(
309                                                      securityLevel == KeyMintSecurityLevel::SOFTWARE
310                                                          ? legacyKc.softwareEnforced
311                                                          : legacyKc.hardwareEnforced)};
312 
313     if (securityLevel == KeyMintSecurityLevel::SOFTWARE && legacyKc.hardwareEnforced.size() > 0) {
314         LOG(WARNING) << "Unexpected hardware enforced parameters.";
315     }
316 
317     if (kmEnforcedOnly) {
318         return {kmEnforced};
319     }
320 
321     KeyCharacteristics keystoreEnforced{KeyMintSecurityLevel::KEYSTORE, {}};
322 
323     if (securityLevel != KeyMintSecurityLevel::SOFTWARE) {
324         // Don't include these tags on software backends, else they'd end up duplicated
325         // across both the keystore-enforced and software keymaster-enforced tags.
326         keystoreEnforced.authorizations = convertKeyParametersFromLegacy(legacyKc.softwareEnforced);
327     }
328 
329     // Add all parameters that we know can be enforced by keystore but not by the legacy backend.
330     auto unsupported_requested = extractNewAndKeystoreEnforceableParams(genParams);
331     keystoreEnforced.authorizations.insert(keystoreEnforced.authorizations.end(),
332                                            std::begin(unsupported_requested),
333                                            std::end(unsupported_requested));
334 
335     return {kmEnforced, keystoreEnforced};
336 }
337 
convertKeyFormatToLegacy(const KeyFormat & kf)338 static V4_0_KeyFormat convertKeyFormatToLegacy(const KeyFormat& kf) {
339     return static_cast<V4_0_KeyFormat>(kf);
340 }
341 
convertAuthTokenToLegacy(const std::optional<HardwareAuthToken> & at)342 static V4_0_HardwareAuthToken convertAuthTokenToLegacy(const std::optional<HardwareAuthToken>& at) {
343     if (!at) return {};
344 
345     V4_0_HardwareAuthToken legacyAt;
346     legacyAt.challenge = at->challenge;
347     legacyAt.userId = at->userId;
348     legacyAt.authenticatorId = at->authenticatorId;
349     legacyAt.authenticatorType =
350         static_cast<::android::hardware::keymaster::V4_0::HardwareAuthenticatorType>(
351             at->authenticatorType);
352     legacyAt.timestamp = at->timestamp.milliSeconds;
353     legacyAt.mac = at->mac;
354     return legacyAt;
355 }
356 
357 static V4_0_VerificationToken
convertTimestampTokenToLegacy(const std::optional<TimeStampToken> & tst)358 convertTimestampTokenToLegacy(const std::optional<TimeStampToken>& tst) {
359     if (!tst) return {};
360 
361     V4_0_VerificationToken legacyVt;
362     legacyVt.challenge = tst->challenge;
363     legacyVt.timestamp = tst->timestamp.milliSeconds;
364     // Legacy verification tokens were always minted by TEE.
365     legacyVt.securityLevel = V4_0::SecurityLevel::TRUSTED_ENVIRONMENT;
366     legacyVt.mac = tst->mac;
367     return legacyVt;
368 }
369 
370 static V4_0_HmacSharingParameters
convertSharedSecretParameterToLegacy(const SharedSecretParameters & ssp)371 convertSharedSecretParameterToLegacy(const SharedSecretParameters& ssp) {
372     V4_0_HmacSharingParameters legacyHsp;
373     legacyHsp.seed = ssp.seed;
374     std::copy(ssp.nonce.begin(), ssp.nonce.end(), legacyHsp.nonce.data());
375     return legacyHsp;
376 }
377 
378 static std::vector<V4_0_HmacSharingParameters>
convertSharedSecretParametersToLegacy(const std::vector<SharedSecretParameters> & legacySsps)379 convertSharedSecretParametersToLegacy(const std::vector<SharedSecretParameters>& legacySsps) {
380     std::vector<V4_0_HmacSharingParameters> ssps(legacySsps.size());
381     std::transform(legacySsps.begin(), legacySsps.end(), ssps.begin(),
382                    convertSharedSecretParameterToLegacy);
383     return ssps;
384 }
385 
setNumFreeSlots(uint8_t numFreeSlots)386 void OperationSlotManager::setNumFreeSlots(uint8_t numFreeSlots) {
387     std::lock_guard<std::mutex> lock(mNumFreeSlotsMutex);
388     mNumFreeSlots = numFreeSlots;
389 }
390 
391 std::optional<OperationSlot>
claimSlot(std::shared_ptr<OperationSlotManager> operationSlots)392 OperationSlotManager::claimSlot(std::shared_ptr<OperationSlotManager> operationSlots) {
393     std::lock_guard<std::mutex> lock(operationSlots->mNumFreeSlotsMutex);
394     if (operationSlots->mNumFreeSlots > 0) {
395         operationSlots->mNumFreeSlots--;
396         return OperationSlot(std::move(operationSlots), std::nullopt);
397     }
398     return std::nullopt;
399 }
400 
401 OperationSlot
claimReservedSlot(std::shared_ptr<OperationSlotManager> operationSlots)402 OperationSlotManager::claimReservedSlot(std::shared_ptr<OperationSlotManager> operationSlots) {
403     std::unique_lock<std::mutex> reservedGuard(operationSlots->mReservedSlotMutex);
404     return OperationSlot(std::move(operationSlots), std::move(reservedGuard));
405 }
406 
OperationSlot(std::shared_ptr<OperationSlotManager> slots,std::optional<std::unique_lock<std::mutex>> reservedGuard)407 OperationSlot::OperationSlot(std::shared_ptr<OperationSlotManager> slots,
408                              std::optional<std::unique_lock<std::mutex>> reservedGuard)
409     : mOperationSlots(std::move(slots)), mReservedGuard(std::move(reservedGuard)) {}
410 
freeSlot()411 void OperationSlotManager::freeSlot() {
412     std::lock_guard<std::mutex> lock(mNumFreeSlotsMutex);
413     mNumFreeSlots++;
414 }
415 
~OperationSlot()416 OperationSlot::~OperationSlot() {
417     if (!mReservedGuard && mOperationSlots) {
418         mOperationSlots->freeSlot();
419     }
420 }
421 
422 // KeyMintDevice implementation
423 
getHardwareInfo(KeyMintHardwareInfo * _aidl_return)424 ScopedAStatus KeyMintDevice::getHardwareInfo(KeyMintHardwareInfo* _aidl_return) {
425     auto result = mDevice->halVersion();
426     _aidl_return->versionNumber = result.majorVersion * 10 + result.minorVersion;
427     securityLevel_ = convert(result.securityLevel);
428     _aidl_return->securityLevel = securityLevel_;
429     _aidl_return->keyMintName = result.keymasterName;
430     _aidl_return->keyMintAuthorName = result.authorName;
431     _aidl_return->timestampTokenRequired = securityLevel_ == KMV1::SecurityLevel::STRONGBOX;
432     return ScopedAStatus::ok();
433 }
434 
addRngEntropy(const std::vector<uint8_t> & in_data)435 ScopedAStatus KeyMintDevice::addRngEntropy(const std::vector<uint8_t>& in_data) {
436     auto result = mDevice->addRngEntropy(in_data);
437     if (!result.isOk()) {
438         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
439         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
440     }
441     return convertErrorCode(result);
442 }
443 
generateKey(const std::vector<KeyParameter> & inKeyParams,const std::optional<AttestationKey> & in_attestationKey,KeyCreationResult * out_creationResult)444 ScopedAStatus KeyMintDevice::generateKey(const std::vector<KeyParameter>& inKeyParams,
445                                          const std::optional<AttestationKey>& in_attestationKey,
446                                          KeyCreationResult* out_creationResult) {
447 
448     // Since KeyMaster doesn't support ECDH, route all key creation requests to
449     // soft-KeyMint if and only an ECDH key is requested.
450     //
451     // For this to work we'll need to also route begin() and deleteKey() calls to
452     // soft-KM. In order to do that, we'll prefix all keyblobs with whether it was
453     // created by the real underlying KeyMaster HAL or whether it was created by
454     // soft-KeyMint.
455     //
456     // See keyBlobPrefix() for more discussion.
457     //
458     for (const auto& keyParam : inKeyParams) {
459         if (keyParam.tag == Tag::PURPOSE &&
460             keyParam.value.get<KeyParameterValue::Tag::keyPurpose>() == KeyPurpose::AGREE_KEY) {
461             auto ret =
462                 softKeyMintDevice_->generateKey(inKeyParams, in_attestationKey, out_creationResult);
463             if (ret.isOk()) {
464                 out_creationResult->keyBlob = keyBlobPrefix(out_creationResult->keyBlob, true);
465             }
466             return ret;
467         }
468     }
469 
470     auto legacyKeyGenParams = convertKeyParametersToLegacy(extractGenerationParams(inKeyParams));
471     KMV1::ErrorCode errorCode;
472     auto result = mDevice->generateKey(
473         legacyKeyGenParams, [&](V4_0_ErrorCode error, const hidl_vec<uint8_t>& keyBlob,
474                                 const V4_0_KeyCharacteristics& keyCharacteristics) {
475             errorCode = convert(error);
476             out_creationResult->keyBlob = keyBlobPrefix(keyBlob, false);
477             out_creationResult->keyCharacteristics =
478                 processLegacyCharacteristics(securityLevel_, inKeyParams, keyCharacteristics);
479         });
480     if (!result.isOk()) {
481         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
482         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
483     }
484     if (errorCode == KMV1::ErrorCode::OK) {
485         auto cert = getCertificate(inKeyParams, out_creationResult->keyBlob);
486         if (std::holds_alternative<KMV1::ErrorCode>(cert)) {
487             auto code = std::get<KMV1::ErrorCode>(cert);
488             // We return OK in successful cases that do not generate a certificate.
489             if (code != KMV1::ErrorCode::OK) {
490                 errorCode = code;
491                 deleteKey(out_creationResult->keyBlob);
492             }
493         } else {
494             out_creationResult->certificateChain = std::get<std::vector<Certificate>>(cert);
495         }
496     }
497     return convertErrorCode(errorCode);
498 }
499 
importKey(const std::vector<KeyParameter> & inKeyParams,KeyFormat in_inKeyFormat,const std::vector<uint8_t> & in_inKeyData,const std::optional<AttestationKey> & in_attestationKey,KeyCreationResult * out_creationResult)500 ScopedAStatus KeyMintDevice::importKey(const std::vector<KeyParameter>& inKeyParams,
501                                        KeyFormat in_inKeyFormat,
502                                        const std::vector<uint8_t>& in_inKeyData,
503                                        const std::optional<AttestationKey>& in_attestationKey,
504                                        KeyCreationResult* out_creationResult) {
505     // Since KeyMaster doesn't support ECDH, route all ECDH key import requests to
506     // soft-KeyMint.
507     //
508     // For this to work we'll need to also route begin() and deleteKey() calls to
509     // soft-KM. In order to do that, we'll prefix all keyblobs with whether it was
510     // created by the real underlying KeyMaster HAL or whether it was created by
511     // soft-KeyMint.
512     //
513     // See keyBlobPrefix() for more discussion.
514     //
515     for (const auto& keyParam : inKeyParams) {
516         if (keyParam.tag == Tag::PURPOSE &&
517             keyParam.value.get<KeyParameterValue::Tag::keyPurpose>() == KeyPurpose::AGREE_KEY) {
518             auto ret = softKeyMintDevice_->importKey(inKeyParams, in_inKeyFormat, in_inKeyData,
519                                                      in_attestationKey, out_creationResult);
520             if (ret.isOk()) {
521                 out_creationResult->keyBlob = keyBlobPrefix(out_creationResult->keyBlob, true);
522             }
523             return ret;
524         }
525     }
526 
527     auto legacyKeyGENParams = convertKeyParametersToLegacy(extractGenerationParams(inKeyParams));
528     auto legacyKeyFormat = convertKeyFormatToLegacy(in_inKeyFormat);
529     KMV1::ErrorCode errorCode;
530     auto result = mDevice->importKey(
531         legacyKeyGENParams, legacyKeyFormat, in_inKeyData,
532         [&](V4_0_ErrorCode error, const hidl_vec<uint8_t>& keyBlob,
533             const V4_0_KeyCharacteristics& keyCharacteristics) {
534             errorCode = convert(error);
535             out_creationResult->keyBlob = keyBlobPrefix(keyBlob, false);
536             out_creationResult->keyCharacteristics =
537                 processLegacyCharacteristics(securityLevel_, inKeyParams, keyCharacteristics);
538         });
539     if (!result.isOk()) {
540         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
541         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
542     }
543     if (errorCode == KMV1::ErrorCode::OK) {
544         auto cert = getCertificate(inKeyParams, out_creationResult->keyBlob);
545         if (std::holds_alternative<KMV1::ErrorCode>(cert)) {
546             auto code = std::get<KMV1::ErrorCode>(cert);
547             // We return OK in successful cases that do not generate a certificate.
548             if (code != KMV1::ErrorCode::OK) {
549                 errorCode = code;
550                 deleteKey(out_creationResult->keyBlob);
551             }
552         } else {
553             out_creationResult->certificateChain = std::get<std::vector<Certificate>>(cert);
554         }
555     }
556     return convertErrorCode(errorCode);
557 }
558 
559 ScopedAStatus
importWrappedKey(const std::vector<uint8_t> & in_inWrappedKeyData,const std::vector<uint8_t> & in_inPrefixedWrappingKeyBlob,const std::vector<uint8_t> & in_inMaskingKey,const std::vector<KeyParameter> & in_inUnwrappingParams,int64_t in_inPasswordSid,int64_t in_inBiometricSid,KeyCreationResult * out_creationResult)560 KeyMintDevice::importWrappedKey(const std::vector<uint8_t>& in_inWrappedKeyData,
561                                 const std::vector<uint8_t>& in_inPrefixedWrappingKeyBlob,
562                                 const std::vector<uint8_t>& in_inMaskingKey,
563                                 const std::vector<KeyParameter>& in_inUnwrappingParams,
564                                 int64_t in_inPasswordSid, int64_t in_inBiometricSid,
565                                 KeyCreationResult* out_creationResult) {
566     const std::vector<uint8_t>& wrappingKeyBlob =
567         prefixedKeyBlobRemovePrefix(in_inPrefixedWrappingKeyBlob);
568     if (prefixedKeyBlobIsSoftKeyMint(in_inPrefixedWrappingKeyBlob)) {
569         return softKeyMintDevice_->importWrappedKey(
570             in_inWrappedKeyData, wrappingKeyBlob, in_inMaskingKey, in_inUnwrappingParams,
571             in_inPasswordSid, in_inBiometricSid, out_creationResult);
572     }
573 
574     auto legacyUnwrappingParams = convertKeyParametersToLegacy(in_inUnwrappingParams);
575     KMV1::ErrorCode errorCode;
576     auto result = mDevice->importWrappedKey(
577         in_inWrappedKeyData, wrappingKeyBlob, in_inMaskingKey, legacyUnwrappingParams,
578         in_inPasswordSid, in_inBiometricSid,
579         [&](V4_0_ErrorCode error, const hidl_vec<uint8_t>& keyBlob,
580             const V4_0_KeyCharacteristics& keyCharacteristics) {
581             errorCode = convert(error);
582             out_creationResult->keyBlob = keyBlobPrefix(keyBlob, false);
583             out_creationResult->keyCharacteristics =
584                 processLegacyCharacteristics(securityLevel_, {}, keyCharacteristics);
585         });
586     if (!result.isOk()) {
587         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
588         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
589     }
590     return convertErrorCode(errorCode);
591 }
592 
upgradeKey(const std::vector<uint8_t> & in_inKeyBlobToUpgrade,const std::vector<KeyParameter> & in_inUpgradeParams,std::vector<uint8_t> * _aidl_return)593 ScopedAStatus KeyMintDevice::upgradeKey(const std::vector<uint8_t>& in_inKeyBlobToUpgrade,
594                                         const std::vector<KeyParameter>& in_inUpgradeParams,
595                                         std::vector<uint8_t>* _aidl_return) {
596     auto legacyUpgradeParams = convertKeyParametersToLegacy(in_inUpgradeParams);
597     V4_0_ErrorCode errorCode;
598 
599     if (prefixedKeyBlobIsSoftKeyMint(in_inKeyBlobToUpgrade)) {
600         auto status = softKeyMintDevice_->upgradeKey(
601             prefixedKeyBlobRemovePrefix(in_inKeyBlobToUpgrade), in_inUpgradeParams, _aidl_return);
602         if (!status.isOk()) {
603             LOG(ERROR) << __func__ << " transaction failed. " << status.getDescription();
604         } else {
605             *_aidl_return = keyBlobPrefix(*_aidl_return, true);
606         }
607         return status;
608     }
609 
610     auto result =
611         mDevice->upgradeKey(prefixedKeyBlobRemovePrefix(in_inKeyBlobToUpgrade), legacyUpgradeParams,
612                             [&](V4_0_ErrorCode error, const hidl_vec<uint8_t>& upgradedKeyBlob) {
613                                 errorCode = error;
614                                 *_aidl_return = keyBlobPrefix(upgradedKeyBlob, false);
615                             });
616     if (!result.isOk()) {
617         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
618         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
619     }
620     return convertErrorCode(errorCode);
621 }
622 
deleteKey(const std::vector<uint8_t> & prefixedKeyBlob)623 ScopedAStatus KeyMintDevice::deleteKey(const std::vector<uint8_t>& prefixedKeyBlob) {
624     const std::vector<uint8_t>& keyBlob = prefixedKeyBlobRemovePrefix(prefixedKeyBlob);
625     if (prefixedKeyBlobIsSoftKeyMint(prefixedKeyBlob)) {
626         return softKeyMintDevice_->deleteKey(keyBlob);
627     }
628 
629     auto result = mDevice->deleteKey(keyBlob);
630     if (!result.isOk()) {
631         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
632         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
633     }
634     return convertErrorCode(result);
635 }
636 
deleteAllKeys()637 ScopedAStatus KeyMintDevice::deleteAllKeys() {
638     auto result = mDevice->deleteAllKeys();
639     if (!result.isOk()) {
640         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
641         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
642     }
643     return convertErrorCode(result);
644 }
645 
646 // We're not implementing this.
destroyAttestationIds()647 ScopedAStatus KeyMintDevice::destroyAttestationIds() {
648     return ScopedAStatus::fromServiceSpecificError(
649         static_cast<int32_t>(V4_0_ErrorCode::UNIMPLEMENTED));
650 }
651 
begin(KeyPurpose in_inPurpose,const std::vector<uint8_t> & prefixedKeyBlob,const std::vector<KeyParameter> & in_inParams,const std::optional<HardwareAuthToken> & in_inAuthToken,BeginResult * _aidl_return)652 ScopedAStatus KeyMintDevice::begin(KeyPurpose in_inPurpose,
653                                    const std::vector<uint8_t>& prefixedKeyBlob,
654                                    const std::vector<KeyParameter>& in_inParams,
655                                    const std::optional<HardwareAuthToken>& in_inAuthToken,
656                                    BeginResult* _aidl_return) {
657     return beginInternal(in_inPurpose, prefixedKeyBlob, in_inParams, in_inAuthToken,
658                          false /* useReservedSlot */, _aidl_return);
659 }
660 
beginInternal(KeyPurpose in_inPurpose,const std::vector<uint8_t> & prefixedKeyBlob,const std::vector<KeyParameter> & in_inParams,const std::optional<HardwareAuthToken> & in_inAuthToken,bool useReservedSlot,BeginResult * _aidl_return)661 ScopedAStatus KeyMintDevice::beginInternal(KeyPurpose in_inPurpose,
662                                            const std::vector<uint8_t>& prefixedKeyBlob,
663                                            const std::vector<KeyParameter>& in_inParams,
664                                            const std::optional<HardwareAuthToken>& in_inAuthToken,
665                                            bool useReservedSlot, BeginResult* _aidl_return) {
666 
667     const std::vector<uint8_t>& in_inKeyBlob = prefixedKeyBlobRemovePrefix(prefixedKeyBlob);
668     if (prefixedKeyBlobIsSoftKeyMint(prefixedKeyBlob)) {
669         return softKeyMintDevice_->begin(in_inPurpose, in_inKeyBlob, in_inParams, in_inAuthToken,
670                                          _aidl_return);
671     }
672 
673     OperationSlot slot;
674     // No need to claim a slot for software device.
675     if (useReservedSlot) {
676         // There is only one reserved slot. This function blocks until
677         // the reserved slot becomes available.
678         slot = OperationSlotManager::claimReservedSlot(mOperationSlots);
679     } else {
680         if (auto opt_slot = OperationSlotManager::claimSlot(mOperationSlots)) {
681             slot = std::move(*opt_slot);
682         } else {
683             return convertErrorCode(V4_0_ErrorCode::TOO_MANY_OPERATIONS);
684         }
685     }
686 
687     auto legacyPurpose =
688         static_cast<::android::hardware::keymaster::V4_0::KeyPurpose>(in_inPurpose);
689     auto legacyParams = convertKeyParametersToLegacy(in_inParams);
690     auto legacyAuthToken = convertAuthTokenToLegacy(in_inAuthToken);
691     KMV1::ErrorCode errorCode;
692     auto result =
693         mDevice->begin(legacyPurpose, in_inKeyBlob, legacyParams, legacyAuthToken,
694                        [&](V4_0_ErrorCode error, const hidl_vec<V4_0_KeyParameter>& outParams,
695                            uint64_t operationHandle) {
696                            errorCode = convert(error);
697                            if (error == V4_0_ErrorCode::OK) {
698                                _aidl_return->challenge = operationHandle;
699                                _aidl_return->params = convertKeyParametersFromLegacy(outParams);
700                                _aidl_return->operation = ndk::SharedRefBase::make<KeyMintOperation>(
701                                    mDevice, operationHandle, std::move(slot));
702                            }
703                        });
704     if (!result.isOk()) {
705         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
706         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
707     }
708     return convertErrorCode(errorCode);
709 }
710 
deviceLocked(bool passwordOnly,const std::optional<TimeStampToken> & timestampToken)711 ScopedAStatus KeyMintDevice::deviceLocked(bool passwordOnly,
712                                           const std::optional<TimeStampToken>& timestampToken) {
713     V4_0_VerificationToken token;
714     if (timestampToken.has_value()) {
715         token = convertTimestampTokenToLegacy(timestampToken.value());
716     }
717     auto ret = mDevice->deviceLocked(passwordOnly, token);
718     if (!ret.isOk()) {
719         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
720     } else {
721         return convertErrorCode(KMV1::ErrorCode::OK);
722     }
723 }
724 
earlyBootEnded()725 ScopedAStatus KeyMintDevice::earlyBootEnded() {
726     auto ret = mDevice->earlyBootEnded();
727     if (!ret.isOk()) {
728         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
729     } else {
730         return convertErrorCode(KMV1::ErrorCode::OK);
731     }
732 }
733 
734 ScopedAStatus
convertStorageKeyToEphemeral(const std::vector<uint8_t> & prefixedStorageKeyBlob,std::vector<uint8_t> * ephemeralKeyBlob)735 KeyMintDevice::convertStorageKeyToEphemeral(const std::vector<uint8_t>& prefixedStorageKeyBlob,
736                                             std::vector<uint8_t>* ephemeralKeyBlob) {
737     KMV1::ErrorCode km_error;
738 
739     /*
740      * Wrapped storage keys cannot be emulated (and they don't need to, because if a platform
741      * supports wrapped storage keys, then the legacy backend will support it too. So error out
742      * if the wrapped storage key given is a soft keymint key.
743      */
744     if (prefixedKeyBlobIsSoftKeyMint(prefixedStorageKeyBlob)) {
745         return convertErrorCode(KMV1::ErrorCode::UNIMPLEMENTED);
746     }
747 
748     const std::vector<uint8_t>& storageKeyBlob =
749         prefixedKeyBlobRemovePrefix(prefixedStorageKeyBlob);
750 
751     auto hidlCb = [&](V4_0_ErrorCode ret, const hidl_vec<uint8_t>& exportedKeyBlob) {
752         km_error = convert(ret);
753         if (km_error != KMV1::ErrorCode::OK) return;
754         /*
755          * This must return the blob without the prefix since it will be used directly
756          * as a storage encryption key. But this is alright, since this wrapped ephemeral
757          * key shouldn't/won't ever be used with keymint.
758          */
759         *ephemeralKeyBlob = exportedKeyBlob;
760     };
761 
762     auto ret = mDevice->exportKey(V4_0_KeyFormat::RAW, storageKeyBlob, {}, {}, hidlCb);
763     if (!ret.isOk()) {
764         LOG(ERROR) << __func__ << " export_key failed: " << ret.description();
765         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
766     }
767     if (km_error != KMV1::ErrorCode::OK) {
768         LOG(ERROR) << __func__ << " export_key failed, code " << int32_t(km_error);
769     }
770 
771     return convertErrorCode(km_error);
772 }
773 
getKeyCharacteristics(const std::vector<uint8_t> & prefixedKeyBlob,const std::vector<uint8_t> & appId,const std::vector<uint8_t> & appData,std::vector<KeyCharacteristics> * keyCharacteristics)774 ScopedAStatus KeyMintDevice::getKeyCharacteristics(
775     const std::vector<uint8_t>& prefixedKeyBlob, const std::vector<uint8_t>& appId,
776     const std::vector<uint8_t>& appData, std::vector<KeyCharacteristics>* keyCharacteristics) {
777     auto [strippedKeyBlob, isSoftware] = dissectPrefixedKeyBlob(prefixedKeyBlob);
778     if (isSoftware) {
779         return softKeyMintDevice_->getKeyCharacteristics(strippedKeyBlob, appId, appData,
780                                                          keyCharacteristics);
781     } else {
782         KMV1::ErrorCode km_error;
783         auto ret = mDevice->getKeyCharacteristics(
784             strippedKeyBlob, appId, appData,
785             [&](V4_0_ErrorCode errorCode, const V4_0_KeyCharacteristics& v40KeyCharacteristics) {
786                 km_error = convert(errorCode);
787                 *keyCharacteristics =
788                     processLegacyCharacteristics(securityLevel_, {} /* getParams */,
789                                                  v40KeyCharacteristics, true /* kmEnforcedOnly */);
790             });
791 
792         if (!ret.isOk()) {
793             LOG(ERROR) << __func__ << " getKeyCharacteristics failed: " << ret.description();
794             return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
795         }
796         if (km_error != KMV1::ErrorCode::OK) {
797             LOG(ERROR) << __func__
798                        << " getKeyCharacteristics failed with code: " << toString(km_error);
799         }
800 
801         return convertErrorCode(km_error);
802     }
803 }
804 
getRootOfTrustChallenge(std::array<uint8_t,16> *)805 ScopedAStatus KeyMintDevice::getRootOfTrustChallenge(std::array<uint8_t, 16>* /* challenge */) {
806     return convertErrorCode(KMV1::ErrorCode::UNIMPLEMENTED);
807 }
808 
getRootOfTrust(const std::array<uint8_t,16> &,std::vector<uint8_t> *)809 ScopedAStatus KeyMintDevice::getRootOfTrust(const std::array<uint8_t, 16>& /* challenge */,
810                                             std::vector<uint8_t>* /* rootOfTrust */) {
811     return convertErrorCode(KMV1::ErrorCode::UNIMPLEMENTED);
812 }
813 
sendRootOfTrust(const std::vector<uint8_t> &)814 ScopedAStatus KeyMintDevice::sendRootOfTrust(const std::vector<uint8_t>& /* rootOfTrust */) {
815     return convertErrorCode(KMV1::ErrorCode::UNIMPLEMENTED);
816 }
817 
updateAad(const std::vector<uint8_t> & input,const std::optional<HardwareAuthToken> & optAuthToken,const std::optional<TimeStampToken> & optTimeStampToken)818 ScopedAStatus KeyMintOperation::updateAad(const std::vector<uint8_t>& input,
819                                           const std::optional<HardwareAuthToken>& optAuthToken,
820                                           const std::optional<TimeStampToken>& optTimeStampToken) {
821     V4_0_HardwareAuthToken authToken = convertAuthTokenToLegacy(optAuthToken);
822     V4_0_VerificationToken verificationToken = convertTimestampTokenToLegacy(optTimeStampToken);
823 
824     KMV1::ErrorCode errorCode;
825     auto result = mDevice->update(
826         mOperationHandle, {V4_0::makeKeyParameter(V4_0::TAG_ASSOCIATED_DATA, input)}, {}, authToken,
827         verificationToken,
828         [&](V4_0_ErrorCode error, auto, auto, auto) { errorCode = convert(error); });
829 
830     if (!result.isOk()) {
831         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
832         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
833     }
834 
835     // Operation slot is no longer occupied.
836     if (errorCode != KMV1::ErrorCode::OK) {
837         mOperationSlot = std::nullopt;
838     }
839 
840     return convertErrorCode(errorCode);
841 }
842 
setUpdateBuffer(std::vector<uint8_t> data)843 void KeyMintOperation::setUpdateBuffer(std::vector<uint8_t> data) {
844     mUpdateBuffer = std::move(data);
845 }
846 
847 const std::vector<uint8_t>&
getExtendedUpdateBuffer(const std::vector<uint8_t> & suffix)848 KeyMintOperation::getExtendedUpdateBuffer(const std::vector<uint8_t>& suffix) {
849     if (mUpdateBuffer.empty()) {
850         return suffix;
851     } else {
852         mUpdateBuffer.insert(mUpdateBuffer.end(), suffix.begin(), suffix.end());
853         return mUpdateBuffer;
854     }
855 }
856 
update(const std::vector<uint8_t> & input_raw,const std::optional<HardwareAuthToken> & optAuthToken,const std::optional<TimeStampToken> & optTimeStampToken,std::vector<uint8_t> * out_output)857 ScopedAStatus KeyMintOperation::update(const std::vector<uint8_t>& input_raw,
858                                        const std::optional<HardwareAuthToken>& optAuthToken,
859                                        const std::optional<TimeStampToken>& optTimeStampToken,
860                                        std::vector<uint8_t>* out_output) {
861     V4_0_HardwareAuthToken authToken = convertAuthTokenToLegacy(optAuthToken);
862     V4_0_VerificationToken verificationToken = convertTimestampTokenToLegacy(optTimeStampToken);
863 
864     size_t inputPos = 0;
865     *out_output = {};
866     KMV1::ErrorCode errorCode = KMV1::ErrorCode::OK;
867     auto input = getExtendedUpdateBuffer(input_raw);
868 
869     while (inputPos < input.size() && errorCode == KMV1::ErrorCode::OK) {
870         uint32_t consumed = 0;
871         auto result =
872             mDevice->update(mOperationHandle, {} /* inParams */,
873                             {input.begin() + inputPos, input.end()}, authToken, verificationToken,
874                             [&](V4_0_ErrorCode error, uint32_t inputConsumed, auto /* outParams */,
875                                 const hidl_vec<uint8_t>& output) {
876                                 errorCode = convert(error);
877                                 out_output->insert(out_output->end(), output.begin(), output.end());
878                                 consumed = inputConsumed;
879                             });
880 
881         if (!result.isOk()) {
882             LOG(ERROR) << __func__ << " transaction failed. " << result.description();
883             errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
884         }
885 
886         if (errorCode == KMV1::ErrorCode::OK && consumed == 0) {
887             // Some very old KM implementations do not buffer sub blocks in certain block modes,
888             // instead, the simply return consumed == 0. So we buffer the input here in the
889             // hope that we complete the bock in a future call to update.
890             setUpdateBuffer({input.begin() + inputPos, input.end()});
891             return convertErrorCode(errorCode);
892         }
893         inputPos += consumed;
894     }
895 
896     // Operation slot is no longer occupied.
897     if (errorCode != KMV1::ErrorCode::OK) {
898         mOperationSlot = std::nullopt;
899     }
900 
901     return convertErrorCode(errorCode);
902 }
903 
904 ScopedAStatus
finish(const std::optional<std::vector<uint8_t>> & in_input,const std::optional<std::vector<uint8_t>> & in_signature,const std::optional<HardwareAuthToken> & in_authToken,const std::optional<TimeStampToken> & in_timeStampToken,const std::optional<std::vector<uint8_t>> & in_confirmationToken,std::vector<uint8_t> * out_output)905 KeyMintOperation::finish(const std::optional<std::vector<uint8_t>>& in_input,
906                          const std::optional<std::vector<uint8_t>>& in_signature,
907                          const std::optional<HardwareAuthToken>& in_authToken,
908                          const std::optional<TimeStampToken>& in_timeStampToken,
909                          const std::optional<std::vector<uint8_t>>& in_confirmationToken,
910                          std::vector<uint8_t>* out_output) {
911     auto input_raw = in_input.value_or(std::vector<uint8_t>());
912     auto input = getExtendedUpdateBuffer(input_raw);
913     auto signature = in_signature.value_or(std::vector<uint8_t>());
914     V4_0_HardwareAuthToken authToken = convertAuthTokenToLegacy(in_authToken);
915     V4_0_VerificationToken verificationToken = convertTimestampTokenToLegacy(in_timeStampToken);
916 
917     std::vector<V4_0_KeyParameter> inParams;
918     if (in_confirmationToken) {
919         inParams.push_back(makeKeyParameter(V4_0::TAG_CONFIRMATION_TOKEN, *in_confirmationToken));
920     }
921 
922     KMV1::ErrorCode errorCode;
923     auto result = mDevice->finish(
924         mOperationHandle, inParams, input, signature, authToken, verificationToken,
925         [&](V4_0_ErrorCode error, auto /* outParams */, const hidl_vec<uint8_t>& output) {
926             errorCode = convert(error);
927             *out_output = output;
928         });
929 
930     if (!result.isOk()) {
931         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
932         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
933     }
934 
935     mOperationSlot = std::nullopt;
936 
937     return convertErrorCode(errorCode);
938 }
939 
abort()940 ScopedAStatus KeyMintOperation::abort() {
941     auto result = mDevice->abort(mOperationHandle);
942     mOperationSlot = std::nullopt;
943     if (!result.isOk()) {
944         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
945         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
946     }
947     return convertErrorCode(result);
948 }
949 
~KeyMintOperation()950 KeyMintOperation::~KeyMintOperation() {
951     if (mOperationSlot) {
952         auto error = abort();
953         if (!error.isOk()) {
954             LOG(WARNING) << "Error calling abort in ~KeyMintOperation: " << error.getMessage();
955         }
956     }
957 }
958 
959 // SecureClock implementation
960 
generateTimeStamp(int64_t in_challenge,TimeStampToken * _aidl_return)961 ScopedAStatus SecureClock::generateTimeStamp(int64_t in_challenge, TimeStampToken* _aidl_return) {
962     KMV1::ErrorCode errorCode;
963     auto result = mDevice->verifyAuthorization(
964         in_challenge, {}, V4_0_HardwareAuthToken(),
965         [&](V4_0_ErrorCode error, const V4_0_VerificationToken& token) {
966             errorCode = convert(error);
967             _aidl_return->challenge = token.challenge;
968             _aidl_return->timestamp.milliSeconds = token.timestamp;
969             _aidl_return->mac = token.mac;
970         });
971     if (!result.isOk()) {
972         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
973         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
974     }
975     return convertErrorCode(errorCode);
976 }
977 
978 // SharedSecret implementation
979 
getSharedSecretParameters(SharedSecretParameters * _aidl_return)980 ScopedAStatus SharedSecret::getSharedSecretParameters(SharedSecretParameters* _aidl_return) {
981     KMV1::ErrorCode errorCode;
982     auto result = mDevice->getHmacSharingParameters(
983         [&](V4_0_ErrorCode error, const V4_0_HmacSharingParameters& params) {
984             errorCode = convert(error);
985             _aidl_return->seed = params.seed;
986             std::copy(params.nonce.data(), params.nonce.data() + params.nonce.elementCount(),
987                       std::back_inserter(_aidl_return->nonce));
988         });
989     if (!result.isOk()) {
990         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
991         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
992     }
993     return convertErrorCode(errorCode);
994 }
995 
996 ScopedAStatus
computeSharedSecret(const std::vector<SharedSecretParameters> & in_params,std::vector<uint8_t> * _aidl_return)997 SharedSecret::computeSharedSecret(const std::vector<SharedSecretParameters>& in_params,
998                                   std::vector<uint8_t>* _aidl_return) {
999     KMV1::ErrorCode errorCode;
1000     auto legacyParams = convertSharedSecretParametersToLegacy(in_params);
1001     auto result = mDevice->computeSharedHmac(
1002         legacyParams, [&](V4_0_ErrorCode error, const hidl_vec<uint8_t>& sharingCheck) {
1003             errorCode = convert(error);
1004             *_aidl_return = sharingCheck;
1005         });
1006     if (!result.isOk()) {
1007         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
1008         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
1009     }
1010     return convertErrorCode(errorCode);
1011 }
1012 
1013 // Certificate implementation
1014 
1015 template <KMV1::Tag tag, KMV1::TagType type>
getParam(const std::vector<KeyParameter> & keyParams,KMV1::TypedTag<type,tag> ttag)1016 static auto getParam(const std::vector<KeyParameter>& keyParams, KMV1::TypedTag<type, tag> ttag)
1017     -> decltype(authorizationValue(ttag, KeyParameter())) {
1018     for (const auto& p : keyParams) {
1019 
1020         if (auto v = authorizationValue(ttag, p)) {
1021             return v;
1022         }
1023     }
1024     return {};
1025 }
1026 
1027 template <typename T>
containsParam(const std::vector<KeyParameter> & keyParams,T ttag)1028 static bool containsParam(const std::vector<KeyParameter>& keyParams, T ttag) {
1029     return static_cast<bool>(getParam(keyParams, ttag));
1030 }
1031 
1032 // Prefer the smallest.
1033 // If no options are found, return the first.
1034 template <typename T>
1035 static typename KMV1::TypedTag2ValueType<T>::type
getMaximum(const std::vector<KeyParameter> & keyParams,T tag,std::vector<typename KMV1::TypedTag2ValueType<T>::type> sortedOptions)1036 getMaximum(const std::vector<KeyParameter>& keyParams, T tag,
1037            std::vector<typename KMV1::TypedTag2ValueType<T>::type> sortedOptions) {
1038     auto bestSoFar = sortedOptions.end();
1039     for (const KeyParameter& kp : keyParams) {
1040         if (auto value = authorizationValue(tag, kp)) {
1041             auto candidate = std::find(sortedOptions.begin(), sortedOptions.end(), *value);
1042             // sortedOptions is sorted from best to worst. `std::distance(first, last)` counts the
1043             // hops from `first` to `last`. So a better `candidate` yields a positive distance to
1044             // `bestSoFar`.
1045             if (std::distance(candidate, bestSoFar) > 0) {
1046                 bestSoFar = candidate;
1047             }
1048         }
1049     }
1050     if (bestSoFar == sortedOptions.end()) {
1051         return sortedOptions[0];
1052     }
1053     return *bestSoFar;
1054 }
1055 
1056 static std::variant<keystore::X509_Ptr, KMV1::ErrorCode>
makeCert(::android::sp<Keymaster> mDevice,const std::vector<KeyParameter> & keyParams,const std::vector<uint8_t> & keyBlob)1057 makeCert(::android::sp<Keymaster> mDevice, const std::vector<KeyParameter>& keyParams,
1058          const std::vector<uint8_t>& keyBlob) {
1059     // Start generating the certificate.
1060     // Get public key for makeCert.
1061     KMV1::ErrorCode errorCode;
1062     std::vector<uint8_t> key;
1063     static std::vector<uint8_t> empty_vector;
1064     auto unwrapBlob = [&](auto b) -> const std::vector<uint8_t>& {
1065         if (b)
1066             return *b;
1067         else
1068             return empty_vector;
1069     };
1070     auto result = mDevice->exportKey(
1071         V4_0_KeyFormat::X509, keyBlob, unwrapBlob(getParam(keyParams, KMV1::TAG_APPLICATION_ID)),
1072         unwrapBlob(getParam(keyParams, KMV1::TAG_APPLICATION_DATA)),
1073         [&](V4_0_ErrorCode error, const hidl_vec<uint8_t>& keyMaterial) {
1074             errorCode = convert(error);
1075             key = keyMaterial;
1076         });
1077     if (!result.isOk()) {
1078         LOG(ERROR) << __func__ << " exportKey transaction failed. " << result.description();
1079         return KMV1::ErrorCode::UNKNOWN_ERROR;
1080     }
1081     if (errorCode != KMV1::ErrorCode::OK) {
1082         return errorCode;
1083     }
1084     // Get pkey for makeCert.
1085     CBS cbs;
1086     CBS_init(&cbs, key.data(), key.size());
1087     auto pkey = EVP_parse_public_key(&cbs);
1088 
1089     // makeCert
1090     std::optional<std::reference_wrapper<const std::vector<uint8_t>>> subject;
1091     if (auto blob = getParam(keyParams, KMV1::TAG_CERTIFICATE_SUBJECT)) {
1092         subject = *blob;
1093     }
1094 
1095     std::optional<std::reference_wrapper<const std::vector<uint8_t>>> serial;
1096     if (auto blob = getParam(keyParams, KMV1::TAG_CERTIFICATE_SERIAL)) {
1097         serial = *blob;
1098     }
1099 
1100     int64_t activation;
1101     if (auto date = getParam(keyParams, KMV1::TAG_CERTIFICATE_NOT_BEFORE)) {
1102         activation = static_cast<int64_t>(*date);
1103     } else {
1104         return KMV1::ErrorCode::MISSING_NOT_BEFORE;
1105     }
1106 
1107     int64_t expiration;
1108     if (auto date = getParam(keyParams, KMV1::TAG_CERTIFICATE_NOT_AFTER)) {
1109         expiration = static_cast<int64_t>(*date);
1110     } else {
1111         return KMV1::ErrorCode::MISSING_NOT_AFTER;
1112     }
1113 
1114     auto certOrError = keystore::makeCert(
1115         pkey, serial, subject, activation, expiration, false /* intentionally left blank */,
1116         std::nullopt /* intentionally left blank */, std::nullopt /* intentionally left blank */);
1117     if (std::holds_alternative<keystore::CertUtilsError>(certOrError)) {
1118         LOG(ERROR) << __func__ << ": Failed to make certificate";
1119         return KMV1::ErrorCode::UNKNOWN_ERROR;
1120     }
1121     return std::move(std::get<keystore::X509_Ptr>(certOrError));
1122 }
1123 
getKeystoreAlgorithm(Algorithm algorithm)1124 static std::variant<keystore::Algo, KMV1::ErrorCode> getKeystoreAlgorithm(Algorithm algorithm) {
1125     switch (algorithm) {
1126     case Algorithm::RSA:
1127         return keystore::Algo::RSA;
1128     case Algorithm::EC:
1129         return keystore::Algo::ECDSA;
1130     default:
1131         LOG(ERROR) << __func__ << ": This should not be called with symmetric algorithm.";
1132         return KMV1::ErrorCode::UNKNOWN_ERROR;
1133     }
1134 }
1135 
getKeystorePadding(PaddingMode padding)1136 static std::variant<keystore::Padding, KMV1::ErrorCode> getKeystorePadding(PaddingMode padding) {
1137     switch (padding) {
1138     case PaddingMode::RSA_PKCS1_1_5_SIGN:
1139         return keystore::Padding::PKCS1_5;
1140     case PaddingMode::RSA_PSS:
1141         return keystore::Padding::PSS;
1142     default:
1143         return keystore::Padding::Ignored;
1144     }
1145 }
1146 
getKeystoreDigest(Digest digest)1147 static std::variant<keystore::Digest, KMV1::ErrorCode> getKeystoreDigest(Digest digest) {
1148     switch (digest) {
1149     case Digest::SHA1:
1150         return keystore::Digest::SHA1;
1151     case Digest::SHA_2_224:
1152         return keystore::Digest::SHA224;
1153     case Digest::SHA_2_256:
1154     case Digest::NONE:
1155         return keystore::Digest::SHA256;
1156     case Digest::SHA_2_384:
1157         return keystore::Digest::SHA384;
1158     case Digest::SHA_2_512:
1159         return keystore::Digest::SHA512;
1160     default:
1161         LOG(ERROR) << __func__ << ": Unknown digest.";
1162         return KMV1::ErrorCode::UNKNOWN_ERROR;
1163     }
1164 }
1165 
1166 std::optional<KMV1::ErrorCode>
signCertificate(const std::vector<KeyParameter> & keyParams,const std::vector<uint8_t> & prefixedKeyBlob,X509 * cert)1167 KeyMintDevice::signCertificate(const std::vector<KeyParameter>& keyParams,
1168                                const std::vector<uint8_t>& prefixedKeyBlob, X509* cert) {
1169 
1170     auto algorithm = getParam(keyParams, KMV1::TAG_ALGORITHM);
1171     auto algoOrError = getKeystoreAlgorithm(*algorithm);
1172     if (std::holds_alternative<KMV1::ErrorCode>(algoOrError)) {
1173         return std::get<KMV1::ErrorCode>(algoOrError);
1174     }
1175     auto algo = std::get<keystore::Algo>(algoOrError);
1176     auto origPadding = getMaximum(keyParams, KMV1::TAG_PADDING,
1177                                   {PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN});
1178     auto paddingOrError = getKeystorePadding(origPadding);
1179     if (std::holds_alternative<KMV1::ErrorCode>(paddingOrError)) {
1180         return std::get<KMV1::ErrorCode>(paddingOrError);
1181     }
1182     auto padding = std::get<keystore::Padding>(paddingOrError);
1183     auto origDigest = getMaximum(keyParams, KMV1::TAG_DIGEST,
1184                                  {Digest::SHA_2_256, Digest::SHA_2_512, Digest::SHA_2_384,
1185                                   Digest::SHA_2_224, Digest::SHA1, Digest::NONE});
1186     auto digestOrError = getKeystoreDigest(origDigest);
1187     if (std::holds_alternative<KMV1::ErrorCode>(digestOrError)) {
1188         return std::get<KMV1::ErrorCode>(digestOrError);
1189     }
1190     auto digest = std::get<keystore::Digest>(digestOrError);
1191 
1192     KMV1::ErrorCode errorCode = KMV1::ErrorCode::OK;
1193     auto error = keystore::signCertWith(
1194         &*cert,
1195         [&](const uint8_t* data, size_t len) {
1196             std::vector<uint8_t> dataVec(data, data + len);
1197             std::vector<KeyParameter> kps = {
1198                 KMV1::makeKeyParameter(KMV1::TAG_DIGEST, origDigest),
1199             };
1200             if (algorithm == KMV1::Algorithm::RSA) {
1201                 kps.push_back(KMV1::makeKeyParameter(KMV1::TAG_PADDING, origPadding));
1202             }
1203             BeginResult beginResult;
1204             auto error = beginInternal(KeyPurpose::SIGN, prefixedKeyBlob, kps, HardwareAuthToken(),
1205                                        true /* useReservedSlot */, &beginResult);
1206             if (!error.isOk()) {
1207                 errorCode = toErrorCode(error);
1208                 return std::vector<uint8_t>();
1209             }
1210 
1211             std::vector<uint8_t> result;
1212             error = beginResult.operation->finish(dataVec,                     //
1213                                                   {} /* signature */,          //
1214                                                   {} /* authToken */,          //
1215                                                   {} /* timestampToken */,     //
1216                                                   {} /* confirmationToken */,  //
1217                                                   &result);
1218             if (!error.isOk()) {
1219                 errorCode = toErrorCode(error);
1220                 return std::vector<uint8_t>();
1221             }
1222             return result;
1223         },
1224         algo, padding, digest);
1225     if (error) {
1226         LOG(ERROR) << __func__
1227                    << ": signCertWith failed. (Callback diagnosed: " << toString(errorCode) << ")";
1228         return KMV1::ErrorCode::UNKNOWN_ERROR;
1229     }
1230     if (errorCode != KMV1::ErrorCode::OK) {
1231         return errorCode;
1232     }
1233     return std::nullopt;
1234 }
1235 
1236 std::variant<std::vector<Certificate>, KMV1::ErrorCode>
getCertificate(const std::vector<KeyParameter> & keyParams,const std::vector<uint8_t> & prefixedKeyBlob)1237 KeyMintDevice::getCertificate(const std::vector<KeyParameter>& keyParams,
1238                               const std::vector<uint8_t>& prefixedKeyBlob) {
1239     const std::vector<uint8_t>& keyBlob = prefixedKeyBlobRemovePrefix(prefixedKeyBlob);
1240 
1241     // There are no certificates for symmetric keys.
1242     auto algorithm = getParam(keyParams, KMV1::TAG_ALGORITHM);
1243     if (!algorithm) {
1244         LOG(ERROR) << __func__ << ": Unable to determine key algorithm.";
1245         return KMV1::ErrorCode::UNKNOWN_ERROR;
1246     }
1247     switch (*algorithm) {
1248     case Algorithm::RSA:
1249     case Algorithm::EC:
1250         break;
1251     default:
1252         return KMV1::ErrorCode::OK;
1253     }
1254 
1255     // If attestation was requested, call and use attestKey.
1256     if (containsParam(keyParams, KMV1::TAG_ATTESTATION_CHALLENGE)) {
1257         auto legacyParams = convertKeyParametersToLegacy(extractAttestationParams(keyParams));
1258         std::vector<Certificate> certs;
1259         KMV1::ErrorCode errorCode = KMV1::ErrorCode::OK;
1260         auto result = mDevice->attestKey(
1261             keyBlob, legacyParams,
1262             [&](V4_0::ErrorCode error, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1263                 errorCode = convert(error);
1264                 for (const auto& cert : certChain) {
1265                     Certificate certificate;
1266                     certificate.encodedCertificate = cert;
1267                     certs.push_back(certificate);
1268                 }
1269             });
1270         if (!result.isOk()) {
1271             LOG(ERROR) << __func__ << ": Call to attestKey failed.";
1272             return KMV1::ErrorCode::UNKNOWN_ERROR;
1273         }
1274         if (errorCode != KMV1::ErrorCode::OK) {
1275             return errorCode;
1276         }
1277         return certs;
1278     }
1279 
1280     // makeCert
1281     auto certOrError = makeCert(mDevice, keyParams, keyBlob);
1282     if (std::holds_alternative<KMV1::ErrorCode>(certOrError)) {
1283         return std::get<KMV1::ErrorCode>(certOrError);
1284     }
1285     auto cert = std::move(std::get<keystore::X509_Ptr>(certOrError));
1286 
1287     // setIssuer
1288     auto error = keystore::setIssuer(&*cert, &*cert, false);
1289     if (error) {
1290         LOG(ERROR) << __func__ << ": Set issuer failed.";
1291         return KMV1::ErrorCode::UNKNOWN_ERROR;
1292     }
1293 
1294     // Signing
1295     auto canSelfSign =
1296         std::find_if(keyParams.begin(), keyParams.end(), [&](const KeyParameter& kp) {
1297             if (auto v = KMV1::authorizationValue(KMV1::TAG_PURPOSE, kp)) {
1298                 return *v == KeyPurpose::SIGN;
1299             }
1300             return false;
1301         }) != keyParams.end();
1302     auto noAuthRequired = containsParam(keyParams, KMV1::TAG_NO_AUTH_REQUIRED);
1303     // If we cannot sign because of purpose or authorization requirement,
1304     if (!(canSelfSign && noAuthRequired)
1305         // or if self signing fails for any other reason,
1306         || signCertificate(keyParams, keyBlob, &*cert).has_value()) {
1307         // we sign with ephemeral key.
1308         keystore::EVP_PKEY_CTX_Ptr pkey_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL));
1309         EVP_PKEY_keygen_init(pkey_ctx.get());
1310         EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pkey_ctx.get(), NID_X9_62_prime256v1);
1311         EVP_PKEY* pkey_ptr = nullptr;
1312         EVP_PKEY_keygen(pkey_ctx.get(), &pkey_ptr);
1313         error = keystore::signCert(&*cert, pkey_ptr);
1314         if (error) {
1315             LOG(ERROR) << __func__ << ": signCert failed.";
1316             return KMV1::ErrorCode::UNKNOWN_ERROR;
1317         }
1318     }
1319 
1320     // encodeCert
1321     auto encodedCertOrError = keystore::encodeCert(&*cert);
1322     if (std::holds_alternative<keystore::CertUtilsError>(encodedCertOrError)) {
1323         LOG(ERROR) << __func__ << ": encodeCert failed.";
1324         return KMV1::ErrorCode::UNKNOWN_ERROR;
1325     }
1326 
1327     Certificate certificate{.encodedCertificate =
1328                                 std::get<std::vector<uint8_t>>(encodedCertOrError)};
1329     std::vector certificates = {certificate};
1330     return certificates;
1331 }
1332 
1333 // Code to find the Keymaster devices (copied from existing code).
1334 
1335 // Copied from system/security/keystore/include/keystore/keymaster_types.h.
1336 
1337 // Changing this namespace alias will change the keymaster version.
1338 namespace keymasterNs = ::android::hardware::keymaster::V4_1;
1339 
1340 using keymasterNs::SecurityLevel;
1341 
1342 // Copied from system/security/keystore/KeyStore.h.
1343 
1344 using ::android::sp;
1345 using keymasterNs::support::Keymaster;
1346 
1347 template <typename T, size_t count> class Devices : public std::array<T, count> {
1348   public:
operator [](SecurityLevel secLevel)1349     T& operator[](SecurityLevel secLevel) {
1350         static_assert(uint32_t(SecurityLevel::SOFTWARE) == 0 &&
1351                           uint32_t(SecurityLevel::TRUSTED_ENVIRONMENT) == 1 &&
1352                           uint32_t(SecurityLevel::STRONGBOX) == 2,
1353                       "Numeric values of security levels have changed");
1354         return std::array<T, count>::at(static_cast<uint32_t>(secLevel));
1355     }
operator [](SecurityLevel secLevel) const1356     T operator[](SecurityLevel secLevel) const {
1357         if (static_cast<uint32_t>(secLevel) > static_cast<uint32_t>(SecurityLevel::STRONGBOX)) {
1358             LOG(ERROR) << "Invalid security level requested";
1359             return {};
1360         }
1361         return (*const_cast<Devices*>(this))[secLevel];
1362     }
1363 };
1364 
1365 using KeymasterDevices = Devices<sp<Keymaster>, 3>;
1366 
1367 // Copied from system/security/keystore/keystore_main.cpp.
1368 
1369 using ::android::hardware::hidl_string;
1370 using keymasterNs::support::Keymaster3;
1371 using keymasterNs::support::Keymaster4;
1372 
1373 template <typename Wrapper>
enumerateKeymasterDevices(IServiceManager * serviceManager)1374 KeymasterDevices enumerateKeymasterDevices(IServiceManager* serviceManager) {
1375     KeymasterDevices result;
1376     serviceManager->listManifestByInterface(
1377         Wrapper::WrappedIKeymasterDevice::descriptor, [&](const hidl_vec<hidl_string>& names) {
1378             auto try_get_device = [&](const auto& name, bool fail_silent) {
1379                 auto device = Wrapper::WrappedIKeymasterDevice::getService(name);
1380                 if (fail_silent && !device) return;
1381                 CHECK(device) << "Failed to get service for \""
1382                               << Wrapper::WrappedIKeymasterDevice::descriptor
1383                               << "\" with interface name \"" << name << "\"";
1384 
1385                 sp<Keymaster> kmDevice(new Wrapper(device, name));
1386                 auto halVersion = kmDevice->halVersion();
1387                 SecurityLevel securityLevel = halVersion.securityLevel;
1388                 LOG(INFO) << "found " << Wrapper::WrappedIKeymasterDevice::descriptor
1389                           << " with interface name " << name << " and seclevel "
1390                           << toString(securityLevel);
1391                 CHECK(static_cast<uint32_t>(securityLevel) < result.size())
1392                     << "Security level of \"" << Wrapper::WrappedIKeymasterDevice::descriptor
1393                     << "\" with interface name \"" << name << "\" out of range";
1394                 auto& deviceSlot = result[securityLevel];
1395                 if (deviceSlot) {
1396                     if (!fail_silent) {
1397                         LOG(WARNING) << "Implementation of \""
1398                                      << Wrapper::WrappedIKeymasterDevice::descriptor
1399                                      << "\" with interface name \"" << name
1400                                      << "\" and security level: " << toString(securityLevel)
1401                                      << " Masked by other implementation of Keymaster";
1402                     }
1403                 } else {
1404                     deviceSlot = kmDevice;
1405                 }
1406             };
1407             bool has_default = false;
1408             for (auto& n : names) {
1409                 try_get_device(n, false);
1410                 if (n == "default") has_default = true;
1411             }
1412             // Make sure that we always check the default device. If we enumerate only what is
1413             // known to hwservicemanager, we miss a possible passthrough HAL.
1414             if (!has_default) {
1415                 try_get_device("default", true /* fail_silent */);
1416             }
1417         });
1418     return result;
1419 }
1420 
initializeKeymasters()1421 KeymasterDevices initializeKeymasters() {
1422     auto serviceManager = IServiceManager::getService();
1423     CHECK(serviceManager.get()) << "Failed to get ServiceManager";
1424     auto result = enumerateKeymasterDevices<Keymaster4>(serviceManager.get());
1425     auto softKeymaster = result[SecurityLevel::SOFTWARE];
1426     if ((!result[SecurityLevel::TRUSTED_ENVIRONMENT]) && (!result[SecurityLevel::STRONGBOX])) {
1427         result = enumerateKeymasterDevices<Keymaster3>(serviceManager.get());
1428     }
1429     if (softKeymaster) result[SecurityLevel::SOFTWARE] = softKeymaster;
1430     if (result[SecurityLevel::SOFTWARE] && !result[SecurityLevel::TRUSTED_ENVIRONMENT]) {
1431         LOG(WARNING) << "No secure Keymaster implementation found, but device offers insecure"
1432                         " Keymaster HAL. Using as default.";
1433         result[SecurityLevel::TRUSTED_ENVIRONMENT] = result[SecurityLevel::SOFTWARE];
1434         result[SecurityLevel::SOFTWARE] = nullptr;
1435     }
1436     // The software bit was removed since we do not need it.
1437     return result;
1438 }
1439 
setNumFreeSlots(uint8_t numFreeSlots)1440 void KeyMintDevice::setNumFreeSlots(uint8_t numFreeSlots) {
1441     mOperationSlots->setNumFreeSlots(numFreeSlots);
1442 }
1443 
1444 // Constructors and helpers.
1445 
KeyMintDevice(sp<Keymaster> device,KeyMintSecurityLevel securityLevel)1446 KeyMintDevice::KeyMintDevice(sp<Keymaster> device, KeyMintSecurityLevel securityLevel)
1447     : mDevice(device), mOperationSlots(std::make_shared<OperationSlotManager>()),
1448       securityLevel_(securityLevel) {
1449     if (securityLevel == KeyMintSecurityLevel::STRONGBOX) {
1450         setNumFreeSlots(3);
1451     } else {
1452         setNumFreeSlots(15);
1453     }
1454 
1455     softKeyMintDevice_ = CreateKeyMintDevice(KeyMintSecurityLevel::SOFTWARE);
1456 }
1457 
getDevice(KeyMintSecurityLevel securityLevel)1458 sp<Keymaster> getDevice(KeyMintSecurityLevel securityLevel) {
1459     static std::mutex mutex;
1460     static sp<Keymaster> teeDevice;
1461     static sp<Keymaster> sbDevice;
1462     std::lock_guard<std::mutex> lock(mutex);
1463     if (!teeDevice) {
1464         auto devices = initializeKeymasters();
1465         teeDevice = devices[V4_0::SecurityLevel::TRUSTED_ENVIRONMENT];
1466         sbDevice = devices[V4_0::SecurityLevel::STRONGBOX];
1467     }
1468     switch (securityLevel) {
1469     case KeyMintSecurityLevel::TRUSTED_ENVIRONMENT:
1470         return teeDevice;
1471     case KeyMintSecurityLevel::STRONGBOX:
1472         return sbDevice;
1473     default:
1474         return {};
1475     }
1476 }
1477 
getSoftwareKeymintDevice()1478 std::shared_ptr<IKeyMintDevice> getSoftwareKeymintDevice() {
1479     static std::mutex mutex;
1480     static std::shared_ptr<IKeyMintDevice> swDevice;
1481     std::lock_guard<std::mutex> lock(mutex);
1482     if (!swDevice) {
1483         swDevice = CreateKeyMintDevice(KeyMintSecurityLevel::SOFTWARE);
1484     }
1485     return swDevice;
1486 }
1487 
1488 std::shared_ptr<KeyMintDevice>
getWrappedKeymasterDevice(KeyMintSecurityLevel securityLevel)1489 KeyMintDevice::getWrappedKeymasterDevice(KeyMintSecurityLevel securityLevel) {
1490     if (auto dev = getDevice(securityLevel)) {
1491         return ndk::SharedRefBase::make<KeyMintDevice>(std::move(dev), securityLevel);
1492     }
1493     return {};
1494 }
1495 
1496 std::shared_ptr<IKeyMintDevice>
createKeyMintDevice(KeyMintSecurityLevel securityLevel)1497 KeyMintDevice::createKeyMintDevice(KeyMintSecurityLevel securityLevel) {
1498     if (securityLevel == KeyMintSecurityLevel::SOFTWARE) {
1499         return getSoftwareKeymintDevice();
1500     } else {
1501         return getWrappedKeymasterDevice(securityLevel);
1502     }
1503 }
1504 
createSharedSecret(KeyMintSecurityLevel securityLevel)1505 std::shared_ptr<SharedSecret> SharedSecret::createSharedSecret(KeyMintSecurityLevel securityLevel) {
1506     auto device = getDevice(securityLevel);
1507     if (!device) {
1508         return {};
1509     }
1510     return ndk::SharedRefBase::make<SharedSecret>(std::move(device));
1511 }
1512 
createSecureClock(KeyMintSecurityLevel securityLevel)1513 std::shared_ptr<SecureClock> SecureClock::createSecureClock(KeyMintSecurityLevel securityLevel) {
1514     auto device = getDevice(securityLevel);
1515     if (!device) {
1516         return {};
1517     }
1518     return ndk::SharedRefBase::make<SecureClock>(std::move(device));
1519 }
1520 
1521 ScopedAStatus
getKeyMintDevice(KeyMintSecurityLevel in_securityLevel,std::shared_ptr<IKeyMintDevice> * _aidl_return)1522 KeystoreCompatService::getKeyMintDevice(KeyMintSecurityLevel in_securityLevel,
1523                                         std::shared_ptr<IKeyMintDevice>* _aidl_return) {
1524     auto i = mDeviceCache.find(in_securityLevel);
1525     if (i == mDeviceCache.end()) {
1526         auto device = KeyMintDevice::createKeyMintDevice(in_securityLevel);
1527         if (!device) {
1528             return ScopedAStatus::fromStatus(STATUS_NAME_NOT_FOUND);
1529         }
1530         i = mDeviceCache.insert(i, {in_securityLevel, std::move(device)});
1531     }
1532     *_aidl_return = i->second;
1533     return ScopedAStatus::ok();
1534 }
1535 
getSharedSecret(KeyMintSecurityLevel in_securityLevel,std::shared_ptr<ISharedSecret> * _aidl_return)1536 ScopedAStatus KeystoreCompatService::getSharedSecret(KeyMintSecurityLevel in_securityLevel,
1537                                                      std::shared_ptr<ISharedSecret>* _aidl_return) {
1538     auto i = mSharedSecretCache.find(in_securityLevel);
1539     if (i == mSharedSecretCache.end()) {
1540         auto secret = SharedSecret::createSharedSecret(in_securityLevel);
1541         if (!secret) {
1542             return ScopedAStatus::fromStatus(STATUS_NAME_NOT_FOUND);
1543         }
1544         i = mSharedSecretCache.insert(i, {in_securityLevel, std::move(secret)});
1545     }
1546     *_aidl_return = i->second;
1547     return ScopedAStatus::ok();
1548 }
1549 
getSecureClock(std::shared_ptr<ISecureClock> * _aidl_return)1550 ScopedAStatus KeystoreCompatService::getSecureClock(std::shared_ptr<ISecureClock>* _aidl_return) {
1551     if (!mSecureClock) {
1552         // The legacy verification service was always provided by the TEE variant.
1553         auto clock = SecureClock::createSecureClock(KeyMintSecurityLevel::TRUSTED_ENVIRONMENT);
1554         if (!clock) {
1555             return ScopedAStatus::fromStatus(STATUS_NAME_NOT_FOUND);
1556         }
1557         mSecureClock = std::move(clock);
1558     }
1559     *_aidl_return = mSecureClock;
1560     return ScopedAStatus::ok();
1561 }
1562