xref: /aosp_15_r20/system/security/keystore2/src/km_compat/km_compat.cpp (revision e1997b9af69e3155ead6e072d106a0077849ffba)
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 
setAdditionalAttestationInfo(const std::vector<KeyParameter> &)842 ScopedAStatus KeyMintDevice::setAdditionalAttestationInfo(
843     const std::vector<KeyParameter>& /* additionalAttestationInfo */) {
844     return convertErrorCode(KMV1::ErrorCode::UNIMPLEMENTED);
845 }
846 
updateAad(const std::vector<uint8_t> & input,const std::optional<HardwareAuthToken> & optAuthToken,const std::optional<TimeStampToken> & optTimeStampToken)847 ScopedAStatus KeyMintOperation::updateAad(const std::vector<uint8_t>& input,
848                                           const std::optional<HardwareAuthToken>& optAuthToken,
849                                           const std::optional<TimeStampToken>& optTimeStampToken) {
850     V4_0_HardwareAuthToken authToken = convertAuthTokenToLegacy(optAuthToken);
851     V4_0_VerificationToken verificationToken = convertTimestampTokenToLegacy(optTimeStampToken);
852 
853     KMV1::ErrorCode errorCode;
854     auto result = mDevice->update(
855         mOperationHandle, {V4_0::makeKeyParameter(V4_0::TAG_ASSOCIATED_DATA, input)}, {}, authToken,
856         verificationToken,
857         [&](V4_0_ErrorCode error, auto, auto, auto) { errorCode = convert(error); });
858 
859     if (!result.isOk()) {
860         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
861         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
862     }
863 
864     // Operation slot is no longer occupied.
865     if (errorCode != KMV1::ErrorCode::OK) {
866         mOperationSlot = std::nullopt;
867     }
868 
869     return convertErrorCode(errorCode);
870 }
871 
setUpdateBuffer(std::vector<uint8_t> data)872 void KeyMintOperation::setUpdateBuffer(std::vector<uint8_t> data) {
873     mUpdateBuffer = std::move(data);
874 }
875 
876 const std::vector<uint8_t>&
getExtendedUpdateBuffer(const std::vector<uint8_t> & suffix)877 KeyMintOperation::getExtendedUpdateBuffer(const std::vector<uint8_t>& suffix) {
878     if (mUpdateBuffer.empty()) {
879         return suffix;
880     } else {
881         mUpdateBuffer.insert(mUpdateBuffer.end(), suffix.begin(), suffix.end());
882         return mUpdateBuffer;
883     }
884 }
885 
update(const std::vector<uint8_t> & input_raw,const std::optional<HardwareAuthToken> & optAuthToken,const std::optional<TimeStampToken> & optTimeStampToken,std::vector<uint8_t> * out_output)886 ScopedAStatus KeyMintOperation::update(const std::vector<uint8_t>& input_raw,
887                                        const std::optional<HardwareAuthToken>& optAuthToken,
888                                        const std::optional<TimeStampToken>& optTimeStampToken,
889                                        std::vector<uint8_t>* out_output) {
890     V4_0_HardwareAuthToken authToken = convertAuthTokenToLegacy(optAuthToken);
891     V4_0_VerificationToken verificationToken = convertTimestampTokenToLegacy(optTimeStampToken);
892 
893     size_t inputPos = 0;
894     *out_output = {};
895     KMV1::ErrorCode errorCode = KMV1::ErrorCode::OK;
896     auto input = getExtendedUpdateBuffer(input_raw);
897 
898     while (inputPos < input.size() && errorCode == KMV1::ErrorCode::OK) {
899         uint32_t consumed = 0;
900         auto result =
901             mDevice->update(mOperationHandle, {} /* inParams */,
902                             {input.begin() + inputPos, input.end()}, authToken, verificationToken,
903                             [&](V4_0_ErrorCode error, uint32_t inputConsumed, auto /* outParams */,
904                                 const hidl_vec<uint8_t>& output) {
905                                 errorCode = convert(error);
906                                 out_output->insert(out_output->end(), output.begin(), output.end());
907                                 consumed = inputConsumed;
908                             });
909 
910         if (!result.isOk()) {
911             LOG(ERROR) << __func__ << " transaction failed. " << result.description();
912             errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
913         }
914 
915         if (errorCode == KMV1::ErrorCode::OK && consumed == 0) {
916             // Some very old KM implementations do not buffer sub blocks in certain block modes,
917             // instead, the simply return consumed == 0. So we buffer the input here in the
918             // hope that we complete the bock in a future call to update.
919             setUpdateBuffer({input.begin() + inputPos, input.end()});
920             return convertErrorCode(errorCode);
921         }
922         inputPos += consumed;
923     }
924 
925     // Operation slot is no longer occupied.
926     if (errorCode != KMV1::ErrorCode::OK) {
927         mOperationSlot = std::nullopt;
928     }
929 
930     return convertErrorCode(errorCode);
931 }
932 
933 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)934 KeyMintOperation::finish(const std::optional<std::vector<uint8_t>>& in_input,
935                          const std::optional<std::vector<uint8_t>>& in_signature,
936                          const std::optional<HardwareAuthToken>& in_authToken,
937                          const std::optional<TimeStampToken>& in_timeStampToken,
938                          const std::optional<std::vector<uint8_t>>& in_confirmationToken,
939                          std::vector<uint8_t>* out_output) {
940     auto input_raw = in_input.value_or(std::vector<uint8_t>());
941     auto input = getExtendedUpdateBuffer(input_raw);
942     auto signature = in_signature.value_or(std::vector<uint8_t>());
943     V4_0_HardwareAuthToken authToken = convertAuthTokenToLegacy(in_authToken);
944     V4_0_VerificationToken verificationToken = convertTimestampTokenToLegacy(in_timeStampToken);
945 
946     std::vector<V4_0_KeyParameter> inParams;
947     if (in_confirmationToken) {
948         inParams.push_back(makeKeyParameter(V4_0::TAG_CONFIRMATION_TOKEN, *in_confirmationToken));
949     }
950 
951     KMV1::ErrorCode errorCode;
952     auto result = mDevice->finish(
953         mOperationHandle, inParams, input, signature, authToken, verificationToken,
954         [&](V4_0_ErrorCode error, auto /* outParams */, const hidl_vec<uint8_t>& output) {
955             errorCode = convert(error);
956             *out_output = output;
957         });
958 
959     if (!result.isOk()) {
960         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
961         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
962     }
963 
964     mOperationSlot = std::nullopt;
965 
966     return convertErrorCode(errorCode);
967 }
968 
abort()969 ScopedAStatus KeyMintOperation::abort() {
970     auto result = mDevice->abort(mOperationHandle);
971     mOperationSlot = std::nullopt;
972     if (!result.isOk()) {
973         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
974         return convertErrorCode(KMV1::ErrorCode::UNKNOWN_ERROR);
975     }
976     return convertErrorCode(result);
977 }
978 
~KeyMintOperation()979 KeyMintOperation::~KeyMintOperation() {
980     if (mOperationSlot) {
981         auto error = abort();
982         if (!error.isOk()) {
983             LOG(WARNING) << "Error calling abort in ~KeyMintOperation: " << error.getMessage();
984         }
985     }
986 }
987 
988 // SecureClock implementation
989 
generateTimeStamp(int64_t in_challenge,TimeStampToken * _aidl_return)990 ScopedAStatus SecureClock::generateTimeStamp(int64_t in_challenge, TimeStampToken* _aidl_return) {
991     KMV1::ErrorCode errorCode;
992     auto result = mDevice->verifyAuthorization(
993         in_challenge, {}, V4_0_HardwareAuthToken(),
994         [&](V4_0_ErrorCode error, const V4_0_VerificationToken& token) {
995             errorCode = convert(error);
996             _aidl_return->challenge = token.challenge;
997             _aidl_return->timestamp.milliSeconds = token.timestamp;
998             _aidl_return->mac = token.mac;
999         });
1000     if (!result.isOk()) {
1001         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
1002         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
1003     }
1004     return convertErrorCode(errorCode);
1005 }
1006 
1007 // SharedSecret implementation
1008 
getSharedSecretParameters(SharedSecretParameters * _aidl_return)1009 ScopedAStatus SharedSecret::getSharedSecretParameters(SharedSecretParameters* _aidl_return) {
1010     KMV1::ErrorCode errorCode;
1011     auto result = mDevice->getHmacSharingParameters(
1012         [&](V4_0_ErrorCode error, const V4_0_HmacSharingParameters& params) {
1013             errorCode = convert(error);
1014             _aidl_return->seed = params.seed;
1015             std::copy(params.nonce.data(), params.nonce.data() + params.nonce.elementCount(),
1016                       std::back_inserter(_aidl_return->nonce));
1017         });
1018     if (!result.isOk()) {
1019         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
1020         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
1021     }
1022     return convertErrorCode(errorCode);
1023 }
1024 
1025 ScopedAStatus
computeSharedSecret(const std::vector<SharedSecretParameters> & in_params,std::vector<uint8_t> * _aidl_return)1026 SharedSecret::computeSharedSecret(const std::vector<SharedSecretParameters>& in_params,
1027                                   std::vector<uint8_t>* _aidl_return) {
1028     KMV1::ErrorCode errorCode;
1029     auto legacyParams = convertSharedSecretParametersToLegacy(in_params);
1030     auto result = mDevice->computeSharedHmac(
1031         legacyParams, [&](V4_0_ErrorCode error, const hidl_vec<uint8_t>& sharingCheck) {
1032             errorCode = convert(error);
1033             *_aidl_return = sharingCheck;
1034         });
1035     if (!result.isOk()) {
1036         LOG(ERROR) << __func__ << " transaction failed. " << result.description();
1037         errorCode = KMV1::ErrorCode::UNKNOWN_ERROR;
1038     }
1039     return convertErrorCode(errorCode);
1040 }
1041 
1042 // Certificate implementation
1043 
1044 template <KMV1::Tag tag, KMV1::TagType type>
getParam(const std::vector<KeyParameter> & keyParams,KMV1::TypedTag<type,tag> ttag)1045 static auto getParam(const std::vector<KeyParameter>& keyParams, KMV1::TypedTag<type, tag> ttag)
1046     -> decltype(authorizationValue(ttag, KeyParameter())) {
1047     for (const auto& p : keyParams) {
1048 
1049         if (auto v = authorizationValue(ttag, p)) {
1050             return v;
1051         }
1052     }
1053     return {};
1054 }
1055 
1056 template <typename T>
containsParam(const std::vector<KeyParameter> & keyParams,T ttag)1057 static bool containsParam(const std::vector<KeyParameter>& keyParams, T ttag) {
1058     return static_cast<bool>(getParam(keyParams, ttag));
1059 }
1060 
1061 // Prefer the smallest.
1062 // If no options are found, return the first.
1063 template <typename T>
1064 static typename KMV1::TypedTag2ValueType<T>::type
getMaximum(const std::vector<KeyParameter> & keyParams,T tag,std::vector<typename KMV1::TypedTag2ValueType<T>::type> sortedOptions)1065 getMaximum(const std::vector<KeyParameter>& keyParams, T tag,
1066            std::vector<typename KMV1::TypedTag2ValueType<T>::type> sortedOptions) {
1067     auto bestSoFar = sortedOptions.end();
1068     for (const KeyParameter& kp : keyParams) {
1069         if (auto value = authorizationValue(tag, kp)) {
1070             auto candidate = std::find(sortedOptions.begin(), sortedOptions.end(), *value);
1071             // sortedOptions is sorted from best to worst. `std::distance(first, last)` counts the
1072             // hops from `first` to `last`. So a better `candidate` yields a positive distance to
1073             // `bestSoFar`.
1074             if (std::distance(candidate, bestSoFar) > 0) {
1075                 bestSoFar = candidate;
1076             }
1077         }
1078     }
1079     if (bestSoFar == sortedOptions.end()) {
1080         return sortedOptions[0];
1081     }
1082     return *bestSoFar;
1083 }
1084 
1085 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)1086 makeCert(::android::sp<Keymaster> mDevice, const std::vector<KeyParameter>& keyParams,
1087          const std::vector<uint8_t>& keyBlob, bool isWrappedKey) {
1088     // Start generating the certificate.
1089     // Get public key for makeCert.
1090     KMV1::ErrorCode errorCode;
1091     std::vector<uint8_t> key;
1092     static std::vector<uint8_t> empty_vector;
1093     auto unwrapBlob = [&](auto b) -> const std::vector<uint8_t>& {
1094         if (b)
1095             return *b;
1096         else
1097             return empty_vector;
1098     };
1099     auto result = mDevice->exportKey(
1100         V4_0_KeyFormat::X509, keyBlob, unwrapBlob(getParam(keyParams, KMV1::TAG_APPLICATION_ID)),
1101         unwrapBlob(getParam(keyParams, KMV1::TAG_APPLICATION_DATA)),
1102         [&](V4_0_ErrorCode error, const hidl_vec<uint8_t>& keyMaterial) {
1103             errorCode = convert(error);
1104             key = keyMaterial;
1105         });
1106     if (!result.isOk()) {
1107         LOG(ERROR) << __func__ << " exportKey transaction failed. " << result.description();
1108         return KMV1::ErrorCode::UNKNOWN_ERROR;
1109     }
1110     if (errorCode != KMV1::ErrorCode::OK) {
1111         return errorCode;
1112     }
1113     // Get pkey for makeCert.
1114     CBS cbs;
1115     CBS_init(&cbs, key.data(), key.size());
1116     auto pkey = EVP_parse_public_key(&cbs);
1117 
1118     // makeCert
1119     std::optional<std::reference_wrapper<const std::vector<uint8_t>>> subject;
1120     if (auto blob = getParam(keyParams, KMV1::TAG_CERTIFICATE_SUBJECT)) {
1121         subject = *blob;
1122     }
1123 
1124     std::optional<std::reference_wrapper<const std::vector<uint8_t>>> serial;
1125     if (auto blob = getParam(keyParams, KMV1::TAG_CERTIFICATE_SERIAL)) {
1126         serial = *blob;
1127     }
1128 
1129     // There is no way to specify CERTIFICATE_NOT_BEFORE and CERTIFICATE_NOT_AFTER for wrapped keys.
1130     // So we provide default values.
1131     int64_t activation;
1132     if (isWrappedKey) {
1133         activation = 0;
1134     } else if (auto date = getParam(keyParams, KMV1::TAG_CERTIFICATE_NOT_BEFORE)) {
1135         activation = static_cast<int64_t>(*date);
1136     } else {
1137         return KMV1::ErrorCode::MISSING_NOT_BEFORE;
1138     }
1139 
1140     int64_t expiration;
1141     if (isWrappedKey) {
1142         expiration = kUndefinedNotAfter;
1143     } else if (auto date = getParam(keyParams, KMV1::TAG_CERTIFICATE_NOT_AFTER)) {
1144         expiration = static_cast<int64_t>(*date);
1145     } else {
1146         return KMV1::ErrorCode::MISSING_NOT_AFTER;
1147     }
1148 
1149     auto certOrError = keystore::makeCert(
1150         pkey, serial, subject, activation, expiration, false /* intentionally left blank */,
1151         std::nullopt /* intentionally left blank */, std::nullopt /* intentionally left blank */);
1152     if (std::holds_alternative<keystore::CertUtilsError>(certOrError)) {
1153         LOG(ERROR) << __func__ << ": Failed to make certificate";
1154         return KMV1::ErrorCode::UNKNOWN_ERROR;
1155     }
1156     return std::move(std::get<keystore::X509_Ptr>(certOrError));
1157 }
1158 
getKeystoreAlgorithm(Algorithm algorithm)1159 static std::variant<keystore::Algo, KMV1::ErrorCode> getKeystoreAlgorithm(Algorithm algorithm) {
1160     switch (algorithm) {
1161     case Algorithm::RSA:
1162         return keystore::Algo::RSA;
1163     case Algorithm::EC:
1164         return keystore::Algo::ECDSA;
1165     default:
1166         LOG(ERROR) << __func__ << ": This should not be called with symmetric algorithm.";
1167         return KMV1::ErrorCode::UNKNOWN_ERROR;
1168     }
1169 }
1170 
getKeystorePadding(PaddingMode padding)1171 static std::variant<keystore::Padding, KMV1::ErrorCode> getKeystorePadding(PaddingMode padding) {
1172     switch (padding) {
1173     case PaddingMode::RSA_PKCS1_1_5_SIGN:
1174         return keystore::Padding::PKCS1_5;
1175     case PaddingMode::RSA_PSS:
1176         return keystore::Padding::PSS;
1177     default:
1178         return keystore::Padding::Ignored;
1179     }
1180 }
1181 
getKeystoreDigest(Digest digest)1182 static std::variant<keystore::Digest, KMV1::ErrorCode> getKeystoreDigest(Digest digest) {
1183     switch (digest) {
1184     case Digest::SHA1:
1185         return keystore::Digest::SHA1;
1186     case Digest::SHA_2_224:
1187         return keystore::Digest::SHA224;
1188     case Digest::SHA_2_256:
1189     case Digest::NONE:
1190         return keystore::Digest::SHA256;
1191     case Digest::SHA_2_384:
1192         return keystore::Digest::SHA384;
1193     case Digest::SHA_2_512:
1194         return keystore::Digest::SHA512;
1195     default:
1196         LOG(ERROR) << __func__ << ": Unknown digest.";
1197         return KMV1::ErrorCode::UNKNOWN_ERROR;
1198     }
1199 }
1200 
1201 std::optional<KMV1::ErrorCode>
signCertificate(const std::vector<KeyParameter> & keyParams,const std::vector<uint8_t> & prefixedKeyBlob,X509 * cert)1202 KeyMintDevice::signCertificate(const std::vector<KeyParameter>& keyParams,
1203                                const std::vector<uint8_t>& prefixedKeyBlob, X509* cert) {
1204 
1205     auto algorithm = getParam(keyParams, KMV1::TAG_ALGORITHM);
1206     auto algoOrError = getKeystoreAlgorithm(*algorithm);
1207     if (std::holds_alternative<KMV1::ErrorCode>(algoOrError)) {
1208         return std::get<KMV1::ErrorCode>(algoOrError);
1209     }
1210     auto algo = std::get<keystore::Algo>(algoOrError);
1211     auto origPadding = getMaximum(keyParams, KMV1::TAG_PADDING,
1212                                   {PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN});
1213     auto paddingOrError = getKeystorePadding(origPadding);
1214     if (std::holds_alternative<KMV1::ErrorCode>(paddingOrError)) {
1215         return std::get<KMV1::ErrorCode>(paddingOrError);
1216     }
1217     auto padding = std::get<keystore::Padding>(paddingOrError);
1218     auto origDigest = getMaximum(keyParams, KMV1::TAG_DIGEST,
1219                                  {Digest::SHA_2_256, Digest::SHA_2_512, Digest::SHA_2_384,
1220                                   Digest::SHA_2_224, Digest::SHA1, Digest::NONE});
1221     auto digestOrError = getKeystoreDigest(origDigest);
1222     if (std::holds_alternative<KMV1::ErrorCode>(digestOrError)) {
1223         return std::get<KMV1::ErrorCode>(digestOrError);
1224     }
1225     auto digest = std::get<keystore::Digest>(digestOrError);
1226 
1227     KMV1::ErrorCode errorCode = KMV1::ErrorCode::OK;
1228     auto error = keystore::signCertWith(
1229         &*cert,
1230         [&](const uint8_t* data, size_t len) {
1231             std::vector<uint8_t> dataVec(data, data + len);
1232             std::vector<KeyParameter> kps = {
1233                 KMV1::makeKeyParameter(KMV1::TAG_DIGEST, origDigest),
1234             };
1235             if (algorithm == KMV1::Algorithm::RSA) {
1236                 kps.push_back(KMV1::makeKeyParameter(KMV1::TAG_PADDING, origPadding));
1237             }
1238             BeginResult beginResult;
1239             auto error = beginInternal(KeyPurpose::SIGN, prefixedKeyBlob, kps, HardwareAuthToken(),
1240                                        true /* useReservedSlot */, &beginResult);
1241             if (!error.isOk()) {
1242                 errorCode = toErrorCode(error);
1243                 return std::vector<uint8_t>();
1244             }
1245 
1246             std::vector<uint8_t> result;
1247             error = beginResult.operation->finish(dataVec,                     //
1248                                                   {} /* signature */,          //
1249                                                   {} /* authToken */,          //
1250                                                   {} /* timestampToken */,     //
1251                                                   {} /* confirmationToken */,  //
1252                                                   &result);
1253             if (!error.isOk()) {
1254                 errorCode = toErrorCode(error);
1255                 return std::vector<uint8_t>();
1256             }
1257             return result;
1258         },
1259         algo, padding, digest);
1260     if (error) {
1261         LOG(ERROR) << __func__
1262                    << ": signCertWith failed. (Callback diagnosed: " << toString(errorCode) << ")";
1263         return KMV1::ErrorCode::UNKNOWN_ERROR;
1264     }
1265     if (errorCode != KMV1::ErrorCode::OK) {
1266         return errorCode;
1267     }
1268     return std::nullopt;
1269 }
1270 
1271 std::variant<std::vector<Certificate>, KMV1::ErrorCode>
getCertificate(const std::vector<KeyParameter> & keyParams,const std::vector<uint8_t> & prefixedKeyBlob,bool isWrappedKey)1272 KeyMintDevice::getCertificate(const std::vector<KeyParameter>& keyParams,
1273                               const std::vector<uint8_t>& prefixedKeyBlob, bool isWrappedKey) {
1274     const std::vector<uint8_t>& keyBlob = prefixedKeyBlobRemovePrefix(prefixedKeyBlob);
1275 
1276     // There are no certificates for symmetric keys.
1277     auto algorithm = getParam(keyParams, KMV1::TAG_ALGORITHM);
1278     if (!algorithm) {
1279         LOG(ERROR) << __func__ << ": Unable to determine key algorithm.";
1280         return KMV1::ErrorCode::UNKNOWN_ERROR;
1281     }
1282     switch (*algorithm) {
1283     case Algorithm::RSA:
1284     case Algorithm::EC:
1285         break;
1286     default:
1287         return KMV1::ErrorCode::OK;
1288     }
1289 
1290     // If attestation was requested, call and use attestKey.
1291     if (containsParam(keyParams, KMV1::TAG_ATTESTATION_CHALLENGE)) {
1292         auto legacyParams = convertKeyParametersToLegacy(extractAttestationParams(keyParams));
1293         std::vector<Certificate> certs;
1294         KMV1::ErrorCode errorCode = KMV1::ErrorCode::OK;
1295         auto result = mDevice->attestKey(
1296             keyBlob, legacyParams,
1297             [&](V4_0::ErrorCode error, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1298                 errorCode = convert(error);
1299                 for (const auto& cert : certChain) {
1300                     Certificate certificate;
1301                     certificate.encodedCertificate = cert;
1302                     certs.push_back(certificate);
1303                 }
1304             });
1305         if (!result.isOk()) {
1306             LOG(ERROR) << __func__ << ": Call to attestKey failed.";
1307             return KMV1::ErrorCode::UNKNOWN_ERROR;
1308         }
1309         if (errorCode != KMV1::ErrorCode::OK) {
1310             return errorCode;
1311         }
1312         return certs;
1313     }
1314 
1315     // makeCert
1316     auto certOrError = makeCert(mDevice, keyParams, keyBlob, isWrappedKey);
1317     if (std::holds_alternative<KMV1::ErrorCode>(certOrError)) {
1318         return std::get<KMV1::ErrorCode>(certOrError);
1319     }
1320     auto cert = std::move(std::get<keystore::X509_Ptr>(certOrError));
1321 
1322     // setIssuer
1323     auto error = keystore::setIssuer(&*cert, &*cert, false);
1324     if (error) {
1325         LOG(ERROR) << __func__ << ": Set issuer failed.";
1326         return KMV1::ErrorCode::UNKNOWN_ERROR;
1327     }
1328 
1329     // Signing
1330     auto canSelfSign =
1331         std::find_if(keyParams.begin(), keyParams.end(), [&](const KeyParameter& kp) {
1332             if (auto v = KMV1::authorizationValue(KMV1::TAG_PURPOSE, kp)) {
1333                 return *v == KeyPurpose::SIGN;
1334             }
1335             return false;
1336         }) != keyParams.end();
1337     auto noAuthRequired = containsParam(keyParams, KMV1::TAG_NO_AUTH_REQUIRED);
1338     // If we cannot sign because of purpose or authorization requirement,
1339     if (!(canSelfSign && noAuthRequired)
1340         // or if self signing fails for any other reason,
1341         || signCertificate(keyParams, keyBlob, &*cert).has_value()) {
1342         // we sign with ephemeral key.
1343         keystore::EVP_PKEY_CTX_Ptr pkey_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL));
1344         EVP_PKEY_keygen_init(pkey_ctx.get());
1345         EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pkey_ctx.get(), NID_X9_62_prime256v1);
1346         EVP_PKEY* pkey_ptr = nullptr;
1347         EVP_PKEY_keygen(pkey_ctx.get(), &pkey_ptr);
1348         error = keystore::signCert(&*cert, pkey_ptr);
1349         if (error) {
1350             LOG(ERROR) << __func__ << ": signCert failed.";
1351             return KMV1::ErrorCode::UNKNOWN_ERROR;
1352         }
1353     }
1354 
1355     // encodeCert
1356     auto encodedCertOrError = keystore::encodeCert(&*cert);
1357     if (std::holds_alternative<keystore::CertUtilsError>(encodedCertOrError)) {
1358         LOG(ERROR) << __func__ << ": encodeCert failed.";
1359         return KMV1::ErrorCode::UNKNOWN_ERROR;
1360     }
1361 
1362     Certificate certificate{.encodedCertificate =
1363                                 std::get<std::vector<uint8_t>>(encodedCertOrError)};
1364     std::vector certificates = {certificate};
1365     return certificates;
1366 }
1367 
1368 // Code to find the Keymaster devices (copied from existing code).
1369 
1370 // Copied from system/security/keystore/include/keystore/keymaster_types.h.
1371 
1372 // Changing this namespace alias will change the keymaster version.
1373 namespace keymasterNs = ::android::hardware::keymaster::V4_1;
1374 
1375 using keymasterNs::SecurityLevel;
1376 
1377 // Copied from system/security/keystore/KeyStore.h.
1378 
1379 using ::android::sp;
1380 using keymasterNs::support::Keymaster;
1381 
1382 template <typename T, size_t count> class Devices : public std::array<T, count> {
1383   public:
operator [](SecurityLevel secLevel)1384     T& operator[](SecurityLevel secLevel) {
1385         static_assert(uint32_t(SecurityLevel::SOFTWARE) == 0 &&
1386                           uint32_t(SecurityLevel::TRUSTED_ENVIRONMENT) == 1 &&
1387                           uint32_t(SecurityLevel::STRONGBOX) == 2,
1388                       "Numeric values of security levels have changed");
1389         return std::array<T, count>::at(static_cast<uint32_t>(secLevel));
1390     }
operator [](SecurityLevel secLevel) const1391     T operator[](SecurityLevel secLevel) const {
1392         if (static_cast<uint32_t>(secLevel) > static_cast<uint32_t>(SecurityLevel::STRONGBOX)) {
1393             LOG(ERROR) << "Invalid security level requested";
1394             return {};
1395         }
1396         return (*const_cast<Devices*>(this))[secLevel];
1397     }
1398 };
1399 
1400 using KeymasterDevices = Devices<sp<Keymaster>, 3>;
1401 
1402 // Copied from system/security/keystore/keystore_main.cpp.
1403 
1404 using ::android::hardware::hidl_string;
1405 using keymasterNs::support::Keymaster3;
1406 using keymasterNs::support::Keymaster4;
1407 
1408 template <typename Wrapper>
enumerateKeymasterDevices(IServiceManager * serviceManager)1409 KeymasterDevices enumerateKeymasterDevices(IServiceManager* serviceManager) {
1410     KeymasterDevices result;
1411     serviceManager->listManifestByInterface(
1412         Wrapper::WrappedIKeymasterDevice::descriptor, [&](const hidl_vec<hidl_string>& names) {
1413             auto try_get_device = [&](const auto& name, bool fail_silent) {
1414                 auto device = Wrapper::WrappedIKeymasterDevice::getService(name);
1415                 if (fail_silent && !device) return;
1416                 CHECK(device) << "Failed to get service for \""
1417                               << Wrapper::WrappedIKeymasterDevice::descriptor
1418                               << "\" with interface name \"" << name << "\"";
1419 
1420                 sp<Keymaster> kmDevice(new Wrapper(device, name));
1421                 auto halVersion = kmDevice->halVersion();
1422                 SecurityLevel securityLevel = halVersion.securityLevel;
1423                 LOG(INFO) << "found " << Wrapper::WrappedIKeymasterDevice::descriptor
1424                           << " with interface name " << name << " and seclevel "
1425                           << toString(securityLevel);
1426                 CHECK(static_cast<uint32_t>(securityLevel) < result.size())
1427                     << "Security level of \"" << Wrapper::WrappedIKeymasterDevice::descriptor
1428                     << "\" with interface name \"" << name << "\" out of range";
1429                 auto& deviceSlot = result[securityLevel];
1430                 if (deviceSlot) {
1431                     if (!fail_silent) {
1432                         LOG(WARNING) << "Implementation of \""
1433                                      << Wrapper::WrappedIKeymasterDevice::descriptor
1434                                      << "\" with interface name \"" << name
1435                                      << "\" and security level: " << toString(securityLevel)
1436                                      << " Masked by other implementation of Keymaster";
1437                     }
1438                 } else {
1439                     deviceSlot = kmDevice;
1440                 }
1441             };
1442             bool has_default = false;
1443             for (auto& n : names) {
1444                 try_get_device(n, false);
1445                 if (n == "default") has_default = true;
1446             }
1447             // Make sure that we always check the default device. If we enumerate only what is
1448             // known to hwservicemanager, we miss a possible passthrough HAL.
1449             if (!has_default) {
1450                 try_get_device("default", true /* fail_silent */);
1451             }
1452         });
1453     return result;
1454 }
1455 
initializeKeymasters()1456 KeymasterDevices initializeKeymasters() {
1457     auto serviceManager = IServiceManager::getService();
1458     if (!serviceManager.get()) {
1459         // New devices no longer have HIDL support, so failing to get hwservicemanager is
1460         // expected behavior.
1461         LOG(INFO) << "Skipping keymaster compat, this system is AIDL only.";
1462         return KeymasterDevices();
1463     }
1464     auto result = enumerateKeymasterDevices<Keymaster4>(serviceManager.get());
1465     auto softKeymaster = result[SecurityLevel::SOFTWARE];
1466     if ((!result[SecurityLevel::TRUSTED_ENVIRONMENT]) && (!result[SecurityLevel::STRONGBOX])) {
1467         result = enumerateKeymasterDevices<Keymaster3>(serviceManager.get());
1468     }
1469     if (softKeymaster) result[SecurityLevel::SOFTWARE] = softKeymaster;
1470     if (result[SecurityLevel::SOFTWARE] && !result[SecurityLevel::TRUSTED_ENVIRONMENT]) {
1471         LOG(WARNING) << "No secure Keymaster implementation found, but device offers insecure"
1472                         " Keymaster HAL. Using as default.";
1473         result[SecurityLevel::TRUSTED_ENVIRONMENT] = result[SecurityLevel::SOFTWARE];
1474         result[SecurityLevel::SOFTWARE] = nullptr;
1475     }
1476     // The software bit was removed since we do not need it.
1477     return result;
1478 }
1479 
setNumFreeSlots(uint8_t numFreeSlots)1480 void KeyMintDevice::setNumFreeSlots(uint8_t numFreeSlots) {
1481     mOperationSlots->setNumFreeSlots(numFreeSlots);
1482 }
1483 
1484 // Constructors and helpers.
1485 
KeyMintDevice(sp<Keymaster> device,KeyMintSecurityLevel securityLevel)1486 KeyMintDevice::KeyMintDevice(sp<Keymaster> device, KeyMintSecurityLevel securityLevel)
1487     : mDevice(device), mOperationSlots(std::make_shared<OperationSlotManager>()),
1488       securityLevel_(securityLevel) {
1489     if (securityLevel == KeyMintSecurityLevel::STRONGBOX) {
1490         setNumFreeSlots(3);
1491     } else {
1492         setNumFreeSlots(15);
1493     }
1494 
1495     softKeyMintDevice_ = CreateKeyMintDevice(KeyMintSecurityLevel::SOFTWARE);
1496 }
1497 
getDevice(KeyMintSecurityLevel securityLevel)1498 sp<Keymaster> getDevice(KeyMintSecurityLevel securityLevel) {
1499     static std::mutex mutex;
1500     static sp<Keymaster> teeDevice;
1501     static sp<Keymaster> sbDevice;
1502     std::lock_guard<std::mutex> lock(mutex);
1503     if (!teeDevice) {
1504         auto devices = initializeKeymasters();
1505         teeDevice = devices[V4_0::SecurityLevel::TRUSTED_ENVIRONMENT];
1506         sbDevice = devices[V4_0::SecurityLevel::STRONGBOX];
1507     }
1508     switch (securityLevel) {
1509     case KeyMintSecurityLevel::TRUSTED_ENVIRONMENT:
1510         return teeDevice;
1511     case KeyMintSecurityLevel::STRONGBOX:
1512         return sbDevice;
1513     default:
1514         return {};
1515     }
1516 }
1517 
getSoftwareKeymintDevice()1518 std::shared_ptr<IKeyMintDevice> getSoftwareKeymintDevice() {
1519     static std::mutex mutex;
1520     static std::shared_ptr<IKeyMintDevice> swDevice;
1521     std::lock_guard<std::mutex> lock(mutex);
1522     if (!swDevice) {
1523         swDevice = CreateKeyMintDevice(KeyMintSecurityLevel::SOFTWARE);
1524     }
1525     return swDevice;
1526 }
1527 
1528 std::shared_ptr<KeyMintDevice>
getWrappedKeymasterDevice(KeyMintSecurityLevel securityLevel)1529 KeyMintDevice::getWrappedKeymasterDevice(KeyMintSecurityLevel securityLevel) {
1530     if (auto dev = getDevice(securityLevel)) {
1531         return ndk::SharedRefBase::make<KeyMintDevice>(std::move(dev), securityLevel);
1532     }
1533     return {};
1534 }
1535 
1536 std::shared_ptr<IKeyMintDevice>
createKeyMintDevice(KeyMintSecurityLevel securityLevel)1537 KeyMintDevice::createKeyMintDevice(KeyMintSecurityLevel securityLevel) {
1538     if (securityLevel == KeyMintSecurityLevel::SOFTWARE) {
1539         return getSoftwareKeymintDevice();
1540     } else {
1541         return getWrappedKeymasterDevice(securityLevel);
1542     }
1543 }
1544 
createSharedSecret(KeyMintSecurityLevel securityLevel)1545 std::shared_ptr<SharedSecret> SharedSecret::createSharedSecret(KeyMintSecurityLevel securityLevel) {
1546     auto device = getDevice(securityLevel);
1547     if (!device) {
1548         return {};
1549     }
1550     return ndk::SharedRefBase::make<SharedSecret>(std::move(device));
1551 }
1552 
createSecureClock(KeyMintSecurityLevel securityLevel)1553 std::shared_ptr<SecureClock> SecureClock::createSecureClock(KeyMintSecurityLevel securityLevel) {
1554     auto device = getDevice(securityLevel);
1555     if (!device) {
1556         return {};
1557     }
1558     return ndk::SharedRefBase::make<SecureClock>(std::move(device));
1559 }
1560 
1561 ScopedAStatus
getKeyMintDevice(KeyMintSecurityLevel in_securityLevel,std::shared_ptr<IKeyMintDevice> * _aidl_return)1562 KeystoreCompatService::getKeyMintDevice(KeyMintSecurityLevel in_securityLevel,
1563                                         std::shared_ptr<IKeyMintDevice>* _aidl_return) {
1564     auto i = mDeviceCache.find(in_securityLevel);
1565     if (i == mDeviceCache.end()) {
1566         auto device = KeyMintDevice::createKeyMintDevice(in_securityLevel);
1567         if (!device) {
1568             return ScopedAStatus::fromStatus(STATUS_NAME_NOT_FOUND);
1569         }
1570         i = mDeviceCache.insert(i, {in_securityLevel, std::move(device)});
1571     }
1572     *_aidl_return = i->second;
1573     return ScopedAStatus::ok();
1574 }
1575 
getSharedSecret(KeyMintSecurityLevel in_securityLevel,std::shared_ptr<ISharedSecret> * _aidl_return)1576 ScopedAStatus KeystoreCompatService::getSharedSecret(KeyMintSecurityLevel in_securityLevel,
1577                                                      std::shared_ptr<ISharedSecret>* _aidl_return) {
1578     auto i = mSharedSecretCache.find(in_securityLevel);
1579     if (i == mSharedSecretCache.end()) {
1580         auto secret = SharedSecret::createSharedSecret(in_securityLevel);
1581         if (!secret) {
1582             return ScopedAStatus::fromStatus(STATUS_NAME_NOT_FOUND);
1583         }
1584         i = mSharedSecretCache.insert(i, {in_securityLevel, std::move(secret)});
1585     }
1586     *_aidl_return = i->second;
1587     return ScopedAStatus::ok();
1588 }
1589 
getSecureClock(std::shared_ptr<ISecureClock> * _aidl_return)1590 ScopedAStatus KeystoreCompatService::getSecureClock(std::shared_ptr<ISecureClock>* _aidl_return) {
1591     if (!mSecureClock) {
1592         // The legacy verification service was always provided by the TEE variant.
1593         auto clock = SecureClock::createSecureClock(KeyMintSecurityLevel::TRUSTED_ENVIRONMENT);
1594         if (!clock) {
1595             return ScopedAStatus::fromStatus(STATUS_NAME_NOT_FOUND);
1596         }
1597         mSecureClock = std::move(clock);
1598     }
1599     *_aidl_return = mSecureClock;
1600     return ScopedAStatus::ok();
1601 }
1602