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