xref: /aosp_15_r20/system/keymaster/contexts/pure_soft_keymaster_context.cpp (revision 789431f29546679ab5188a97751fb38e3018d44d)
1 /*
2  * Copyright 2015 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 <keymaster/contexts/pure_soft_keymaster_context.h>
18 
19 #include <assert.h>
20 #include <memory>
21 #include <utility>
22 
23 #include <openssl/aes.h>
24 #include <openssl/evp.h>
25 #include <openssl/hmac.h>
26 #include <openssl/rand.h>
27 #include <openssl/sha.h>
28 #include <openssl/x509v3.h>
29 
30 #include <keymaster/android_keymaster_utils.h>
31 #include <keymaster/key_blob_utils/auth_encrypted_key_blob.h>
32 #include <keymaster/key_blob_utils/integrity_assured_key_blob.h>
33 #include <keymaster/key_blob_utils/ocb_utils.h>
34 #include <keymaster/key_blob_utils/software_keyblobs.h>
35 #include <keymaster/km_openssl/aes_key.h>
36 #include <keymaster/km_openssl/asymmetric_key.h>
37 #include <keymaster/km_openssl/attestation_utils.h>
38 #include <keymaster/km_openssl/certificate_utils.h>
39 #include <keymaster/km_openssl/ec_key_factory.h>
40 #include <keymaster/km_openssl/hmac_key.h>
41 #include <keymaster/km_openssl/openssl_err.h>
42 #include <keymaster/km_openssl/openssl_utils.h>
43 #include <keymaster/km_openssl/rsa_key_factory.h>
44 #include <keymaster/km_openssl/soft_keymaster_enforcement.h>
45 #include <keymaster/km_openssl/triple_des_key.h>
46 #include <keymaster/logger.h>
47 #include <keymaster/operation.h>
48 #include <keymaster/wrapped_key.h>
49 
50 #include <keymaster/contexts/soft_attestation_cert.h>
51 
52 namespace keymaster {
53 
PureSoftKeymasterContext(KmVersion version,keymaster_security_level_t security_level)54 PureSoftKeymasterContext::PureSoftKeymasterContext(KmVersion version,
55                                                    keymaster_security_level_t security_level)
56 
57     : SoftAttestationContext(version),
58       rsa_factory_(new (std::nothrow) RsaKeyFactory(*this /* blob_maker */, *this /* context */)),
59       ec_factory_(new (std::nothrow) EcKeyFactory(*this /* blob_maker */, *this /* context */)),
60       aes_factory_(new (std::nothrow)
61                        AesKeyFactory(*this /* blob_maker */, *this /* random_source */)),
62       tdes_factory_(new (std::nothrow)
63                         TripleDesKeyFactory(*this /* blob_maker */, *this /* random_source */)),
64       hmac_factory_(new (std::nothrow)
65                         HmacKeyFactory(*this /* blob_maker */, *this /* random_source */)),
66       os_version_(0), os_patchlevel_(0), soft_keymaster_enforcement_(64, 64),
67       security_level_(security_level) {
68     // We're pretending to be some sort of secure hardware which supports secure key storage,
69     // this must only be used for testing.
70     if (security_level != KM_SECURITY_LEVEL_SOFTWARE) {
71         pure_soft_secure_key_storage_ = std::make_unique<PureSoftSecureKeyStorage>(64);
72     }
73     if (version >= KmVersion::KEYMINT_1) {
74         pure_soft_remote_provisioning_context_ =
75             std::make_unique<PureSoftRemoteProvisioningContext>(security_level_);
76     }
77 }
78 
~PureSoftKeymasterContext()79 PureSoftKeymasterContext::~PureSoftKeymasterContext() {}
80 
SetSystemVersion(uint32_t os_version,uint32_t os_patchlevel)81 keymaster_error_t PureSoftKeymasterContext::SetSystemVersion(uint32_t os_version,
82                                                              uint32_t os_patchlevel) {
83     os_version_ = os_version;
84     os_patchlevel_ = os_patchlevel;
85     if (pure_soft_remote_provisioning_context_ != nullptr) {
86         pure_soft_remote_provisioning_context_->SetSystemVersion(os_version, os_patchlevel);
87     }
88     return KM_ERROR_OK;
89 }
90 
GetSystemVersion(uint32_t * os_version,uint32_t * os_patchlevel) const91 void PureSoftKeymasterContext::GetSystemVersion(uint32_t* os_version,
92                                                 uint32_t* os_patchlevel) const {
93     *os_version = os_version_;
94     *os_patchlevel = os_patchlevel_;
95 }
96 
97 keymaster_error_t
SetVerifiedBootInfo(std::string_view boot_state,std::string_view bootloader_state,const std::vector<uint8_t> & vbmeta_digest)98 PureSoftKeymasterContext::SetVerifiedBootInfo(std::string_view boot_state,
99                                               std::string_view bootloader_state,
100                                               const std::vector<uint8_t>& vbmeta_digest) {
101     if (verified_boot_state_.has_value() && boot_state != verified_boot_state_.value()) {
102         return KM_ERROR_INVALID_ARGUMENT;
103     }
104     if (bootloader_state_.has_value() && bootloader_state != bootloader_state_.value()) {
105         return KM_ERROR_INVALID_ARGUMENT;
106     }
107     if (vbmeta_digest_.has_value() && vbmeta_digest != vbmeta_digest_.value()) {
108         return KM_ERROR_INVALID_ARGUMENT;
109     }
110     verified_boot_state_ = boot_state;
111     bootloader_state_ = bootloader_state;
112     vbmeta_digest_ = vbmeta_digest;
113     if (pure_soft_remote_provisioning_context_ != nullptr) {
114         pure_soft_remote_provisioning_context_->SetVerifiedBootInfo(boot_state, bootloader_state,
115                                                                     vbmeta_digest);
116     }
117     return KM_ERROR_OK;
118 }
119 
SetVendorPatchlevel(uint32_t vendor_patchlevel)120 keymaster_error_t PureSoftKeymasterContext::SetVendorPatchlevel(uint32_t vendor_patchlevel) {
121     if (vendor_patchlevel_.has_value() && vendor_patchlevel != vendor_patchlevel_.value()) {
122         // Can't set patchlevel to a different value.
123         return KM_ERROR_INVALID_ARGUMENT;
124     }
125     vendor_patchlevel_ = vendor_patchlevel;
126     if (pure_soft_remote_provisioning_context_ != nullptr) {
127         pure_soft_remote_provisioning_context_->SetVendorPatchlevel(vendor_patchlevel);
128     }
129     return KM_ERROR_OK;
130 }
131 
SetBootPatchlevel(uint32_t boot_patchlevel)132 keymaster_error_t PureSoftKeymasterContext::SetBootPatchlevel(uint32_t boot_patchlevel) {
133     if (boot_patchlevel_.has_value() && boot_patchlevel != boot_patchlevel_.value()) {
134         // Can't set patchlevel to a different value.
135         return KM_ERROR_INVALID_ARGUMENT;
136     }
137     boot_patchlevel_ = boot_patchlevel;
138     if (pure_soft_remote_provisioning_context_ != nullptr) {
139         pure_soft_remote_provisioning_context_->SetBootPatchlevel(boot_patchlevel);
140     }
141     return KM_ERROR_OK;
142 }
143 
SetModuleHash(const keymaster_blob_t & mod_hash)144 keymaster_error_t PureSoftKeymasterContext::SetModuleHash(const keymaster_blob_t& mod_hash) {
145     std::vector<uint8_t> module_hash(mod_hash.data, mod_hash.data + mod_hash.data_length);
146     if (module_hash_.has_value()) {
147         if (module_hash != module_hash_.value()) {
148             // Can't set module hash to a different value.
149             return KM_ERROR_MODULE_HASH_ALREADY_SET;
150         } else {
151             LOG_I("module hash already set, ignoring repeated attempt to set same info");
152             return KM_ERROR_OK;
153         }
154     } else {
155         module_hash_ = module_hash;
156         return KM_ERROR_OK;
157     }
158 }
159 
GetKeyFactory(keymaster_algorithm_t algorithm) const160 KeyFactory* PureSoftKeymasterContext::GetKeyFactory(keymaster_algorithm_t algorithm) const {
161     switch (algorithm) {
162     case KM_ALGORITHM_RSA:
163         return rsa_factory_.get();
164     case KM_ALGORITHM_EC:
165         return ec_factory_.get();
166     case KM_ALGORITHM_AES:
167         return aes_factory_.get();
168     case KM_ALGORITHM_TRIPLE_DES:
169         return tdes_factory_.get();
170     case KM_ALGORITHM_HMAC:
171         return hmac_factory_.get();
172     default:
173         return nullptr;
174     }
175 }
176 
177 static keymaster_algorithm_t supported_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC,
178                                                        KM_ALGORITHM_AES, KM_ALGORITHM_HMAC};
179 
180 const keymaster_algorithm_t*
GetSupportedAlgorithms(size_t * algorithms_count) const181 PureSoftKeymasterContext::GetSupportedAlgorithms(size_t* algorithms_count) const {
182     *algorithms_count = array_length(supported_algorithms);
183     return supported_algorithms;
184 }
185 
GetOperationFactory(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose) const186 OperationFactory* PureSoftKeymasterContext::GetOperationFactory(keymaster_algorithm_t algorithm,
187                                                                 keymaster_purpose_t purpose) const {
188     KeyFactory* key_factory = GetKeyFactory(algorithm);
189     if (!key_factory) return nullptr;
190     return key_factory->GetOperationFactory(purpose);
191 }
192 
CreateKeyBlob(const AuthorizationSet & key_description,const keymaster_key_origin_t origin,const KeymasterKeyBlob & key_material,KeymasterKeyBlob * blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const193 keymaster_error_t PureSoftKeymasterContext::CreateKeyBlob(const AuthorizationSet& key_description,
194                                                           const keymaster_key_origin_t origin,
195                                                           const KeymasterKeyBlob& key_material,
196                                                           KeymasterKeyBlob* blob,
197                                                           AuthorizationSet* hw_enforced,
198                                                           AuthorizationSet* sw_enforced) const {
199     // Check whether the key blob can be securely stored by pure software secure key storage.
200     bool canStoreBySecureKeyStorageIfRequired = false;
201     if (GetSecurityLevel() != KM_SECURITY_LEVEL_SOFTWARE &&
202         pure_soft_secure_key_storage_ != nullptr) {
203         pure_soft_secure_key_storage_->HasSlot(&canStoreBySecureKeyStorageIfRequired);
204     }
205 
206     bool needStoreBySecureKeyStorage = false;
207     if (key_description.GetTagValue(TAG_ROLLBACK_RESISTANCE)) {
208         needStoreBySecureKeyStorage = true;
209         if (!canStoreBySecureKeyStorageIfRequired) return KM_ERROR_ROLLBACK_RESISTANCE_UNAVAILABLE;
210     }
211 
212     if (GetSecurityLevel() != KM_SECURITY_LEVEL_SOFTWARE) {
213         // We're pretending to be some sort of secure hardware.  Put relevant tags in hw_enforced.
214         for (auto& entry : key_description) {
215             switch (entry.tag) {
216             case KM_TAG_PURPOSE:
217             case KM_TAG_ALGORITHM:
218             case KM_TAG_KEY_SIZE:
219             case KM_TAG_RSA_PUBLIC_EXPONENT:
220             case KM_TAG_BLOB_USAGE_REQUIREMENTS:
221             case KM_TAG_DIGEST:
222             case KM_TAG_PADDING:
223             case KM_TAG_BLOCK_MODE:
224             case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
225             case KM_TAG_MAX_USES_PER_BOOT:
226             case KM_TAG_USER_SECURE_ID:
227             case KM_TAG_NO_AUTH_REQUIRED:
228             case KM_TAG_AUTH_TIMEOUT:
229             case KM_TAG_CALLER_NONCE:
230             case KM_TAG_MIN_MAC_LENGTH:
231             case KM_TAG_KDF:
232             case KM_TAG_EC_CURVE:
233             case KM_TAG_ECIES_SINGLE_HASH_MODE:
234             case KM_TAG_USER_AUTH_TYPE:
235             case KM_TAG_ORIGIN:
236             case KM_TAG_OS_VERSION:
237             case KM_TAG_OS_PATCHLEVEL:
238             case KM_TAG_EARLY_BOOT_ONLY:
239             case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
240             case KM_TAG_RSA_OAEP_MGF_DIGEST:
241             case KM_TAG_ROLLBACK_RESISTANCE:
242                 hw_enforced->push_back(entry);
243                 break;
244             case KM_TAG_USAGE_COUNT_LIMIT:
245                 // Enforce single use key with usage count limit = 1 into secure key storage.
246                 if (canStoreBySecureKeyStorageIfRequired && entry.integer == 1) {
247                     needStoreBySecureKeyStorage = true;
248                     hw_enforced->push_back(entry);
249                 }
250                 break;
251             default:
252                 break;
253             }
254         }
255     }
256 
257     keymaster_error_t error =
258         SetKeyBlobAuthorizations(key_description, origin, os_version_, os_patchlevel_, hw_enforced,
259                                  sw_enforced, GetKmVersion());
260     if (error != KM_ERROR_OK) return error;
261     error =
262         ExtendKeyBlobAuthorizations(hw_enforced, sw_enforced, vendor_patchlevel_, boot_patchlevel_);
263     if (error != KM_ERROR_OK) return error;
264     if (module_hash_.has_value()) {
265         keymaster_blob_t mod_hash = {module_hash_.value().data(), module_hash_.value().size()};
266         sw_enforced->push_back(TAG_MODULE_HASH, mod_hash);
267     }
268 
269     AuthorizationSet hidden;
270     error = BuildHiddenAuthorizations(key_description, &hidden, softwareRootOfTrust);
271     if (error != KM_ERROR_OK) return error;
272 
273     error = SerializeIntegrityAssuredBlob(key_material, hidden, *hw_enforced, *sw_enforced, blob);
274     if (error != KM_ERROR_OK) return error;
275 
276     // Pretend to be some sort of secure hardware that can securely store the key blob.
277     if (!needStoreBySecureKeyStorage) return KM_ERROR_OK;
278     km_id_t keyid;
279     if (!soft_keymaster_enforcement_.CreateKeyId(*blob, &keyid)) return KM_ERROR_UNKNOWN_ERROR;
280     assert(needStoreBySecureKeyStorage && canStoreBySecureKeyStorageIfRequired);
281     return pure_soft_secure_key_storage_->WriteKey(keyid, *blob);
282 }
283 
UpgradeKeyBlob(const KeymasterKeyBlob & key_to_upgrade,const AuthorizationSet & upgrade_params,KeymasterKeyBlob * upgraded_key) const284 keymaster_error_t PureSoftKeymasterContext::UpgradeKeyBlob(const KeymasterKeyBlob& key_to_upgrade,
285                                                            const AuthorizationSet& upgrade_params,
286                                                            KeymasterKeyBlob* upgraded_key) const {
287     UniquePtr<Key> key;
288     keymaster_error_t error = ParseKeyBlob(key_to_upgrade, upgrade_params, &key);
289     if (error != KM_ERROR_OK) return error;
290 
291     return FullUpgradeSoftKeyBlob(key, os_version_, os_patchlevel_, vendor_patchlevel_,
292                                   boot_patchlevel_, upgrade_params, upgraded_key);
293 }
294 
ParseKeyBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,UniquePtr<Key> * key) const295 keymaster_error_t PureSoftKeymasterContext::ParseKeyBlob(const KeymasterKeyBlob& blob,
296                                                          const AuthorizationSet& additional_params,
297                                                          UniquePtr<Key>* key) const {
298     // This is a little bit complicated.
299     //
300     // The SoftKeymasterContext has to handle a lot of different kinds of key blobs.
301     //
302     // 1.  New keymaster1 software key blobs.  These are integrity-assured but not encrypted.  The
303     //     raw key material and auth sets should be extracted and returned.  This is the kind
304     //     produced by this context when the KeyFactory doesn't use keymaster0 to back the keys.
305     //
306     // 2.  Old keymaster1 software key blobs.  These are OCB-encrypted with an all-zero master key.
307     //     They should be decrypted and the key material and auth sets extracted and returned.
308     //
309     // 3.  Old keymaster0 software key blobs.  These are raw key material with a small header tacked
310     //     on the front.  They don't have auth sets, so reasonable defaults are generated and
311     //     returned along with the raw key material.
312     //
313     // Determining what kind of blob has arrived is somewhat tricky.  What helps is that
314     // integrity-assured and OCB-encrypted blobs are self-consistent and effectively impossible to
315     // parse as anything else.  Old keymaster0 software key blobs have a header.  It's reasonably
316     // unlikely that hardware keys would have the same header.  So anything that is neither
317     // integrity-assured nor OCB-encrypted and lacks the old software key header is assumed to be
318     // keymaster0 hardware.
319 
320     AuthorizationSet hw_enforced;
321     AuthorizationSet sw_enforced;
322     KeymasterKeyBlob key_material;
323     keymaster_error_t error;
324 
325     auto constructKey = [&, this]() mutable -> keymaster_error_t {
326         // GetKeyFactory
327         if (error != KM_ERROR_OK) return error;
328         keymaster_algorithm_t algorithm;
329         if (!hw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm) &&
330             !sw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm)) {
331             return KM_ERROR_INVALID_ARGUMENT;
332         }
333 
334         // Pretend to be some sort of secure hardware that can securely store
335         // the key blob. Check the key blob is still securely stored now.
336         if (hw_enforced.Contains(KM_TAG_ROLLBACK_RESISTANCE) ||
337             hw_enforced.Contains(KM_TAG_USAGE_COUNT_LIMIT)) {
338             if (pure_soft_secure_key_storage_ == nullptr) return KM_ERROR_INVALID_KEY_BLOB;
339             km_id_t keyid;
340             bool exists;
341             if (!soft_keymaster_enforcement_.CreateKeyId(blob, &keyid))
342                 return KM_ERROR_INVALID_KEY_BLOB;
343             error = pure_soft_secure_key_storage_->KeyExists(keyid, &exists);
344             if (error != KM_ERROR_OK || !exists) return KM_ERROR_INVALID_KEY_BLOB;
345         }
346 
347         auto factory = GetKeyFactory(algorithm);
348         return factory->LoadKey(std::move(key_material), additional_params, std::move(hw_enforced),
349                                 std::move(sw_enforced), key);
350     };
351 
352     AuthorizationSet hidden;
353     error = BuildHiddenAuthorizations(additional_params, &hidden, softwareRootOfTrust);
354     if (error != KM_ERROR_OK) return error;
355 
356     // Assume it's an integrity-assured blob (new software-only blob, or new keymaster0-backed
357     // blob).
358     error =
359         DeserializeIntegrityAssuredBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
360     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
361 
362     // Wasn't an integrity-assured blob.  Maybe it's an auth-encrypted blob.
363     error = ParseAuthEncryptedBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
364     if (error == KM_ERROR_OK) LOG_D("Parsed an old keymaster1 software key");
365     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
366 
367     // Wasn't an auth-encrypted blob.  Maybe it's an old softkeymaster blob.
368     error = ParseOldSoftkeymasterBlob(blob, &key_material, &hw_enforced, &sw_enforced);
369     if (error == KM_ERROR_OK) LOG_D("Parsed an old sofkeymaster key");
370 
371     return constructKey();
372 }
373 
DeleteKey(const KeymasterKeyBlob & blob) const374 keymaster_error_t PureSoftKeymasterContext::DeleteKey(const KeymasterKeyBlob& blob) const {
375     // Pretend to be some secure hardware with secure storage.
376     if (GetSecurityLevel() != KM_SECURITY_LEVEL_SOFTWARE &&
377         pure_soft_secure_key_storage_ != nullptr) {
378         km_id_t keyid;
379         if (!soft_keymaster_enforcement_.CreateKeyId(blob, &keyid)) return KM_ERROR_UNKNOWN_ERROR;
380         return pure_soft_secure_key_storage_->DeleteKey(keyid);
381     }
382 
383     // Otherwise, nothing to do for software-only contexts.
384     return KM_ERROR_OK;
385 }
386 
DeleteAllKeys() const387 keymaster_error_t PureSoftKeymasterContext::DeleteAllKeys() const {
388     // Pretend to be some secure hardware with secure storage.
389     if (GetSecurityLevel() != KM_SECURITY_LEVEL_SOFTWARE &&
390         pure_soft_secure_key_storage_ != nullptr) {
391         return pure_soft_secure_key_storage_->DeleteAllKeys();
392     }
393 
394     // Otherwise, nothing to do for software-only contexts.
395     return KM_ERROR_OK;
396 }
397 
AddRngEntropy(const uint8_t * buf,size_t length) const398 keymaster_error_t PureSoftKeymasterContext::AddRngEntropy(const uint8_t* buf, size_t length) const {
399     if (length > 2 * 1024) {
400         // At most 2KiB is allowed to be added at once.
401         return KM_ERROR_INVALID_INPUT_LENGTH;
402     }
403     // XXX TODO according to boringssl openssl/rand.h RAND_add is deprecated and does
404     // nothing
405     RAND_add(buf, length, 0 /* Don't assume any entropy is added to the pool. */);
406     return KM_ERROR_OK;
407 }
408 
409 CertificateChain
GenerateAttestation(const Key & key,const AuthorizationSet & attest_params,UniquePtr<Key> attest_key,const KeymasterBlob & issuer_subject,keymaster_error_t * error) const410 PureSoftKeymasterContext::GenerateAttestation(const Key& key,                         //
411                                               const AuthorizationSet& attest_params,  //
412                                               UniquePtr<Key> attest_key,
413                                               const KeymasterBlob& issuer_subject,
414                                               keymaster_error_t* error) const {
415     if (!error) return {};
416     *error = KM_ERROR_OK;
417 
418     keymaster_algorithm_t key_algorithm;
419     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
420         *error = KM_ERROR_UNKNOWN_ERROR;
421         return {};
422     }
423 
424     if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC)) {
425         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
426         return {};
427     }
428 
429     if (attest_params.GetTagValue(TAG_DEVICE_UNIQUE_ATTESTATION)) {
430         *error = KM_ERROR_UNIMPLEMENTED;
431         return {};
432     }
433     // We have established that the given key has the correct algorithm, and because this is the
434     // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
435     const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
436 
437     AttestKeyInfo attest_key_info(attest_key, &issuer_subject, error);
438     if (*error != KM_ERROR_OK) return {};
439 
440     return generate_attestation(asymmetric_key, attest_params, std::move(attest_key_info), *this,
441                                 error);
442 }
443 
GenerateSelfSignedCertificate(const Key & key,const AuthorizationSet & cert_params,bool fake_signature,keymaster_error_t * error) const444 CertificateChain PureSoftKeymasterContext::GenerateSelfSignedCertificate(
445     const Key& key, const AuthorizationSet& cert_params, bool fake_signature,
446     keymaster_error_t* error) const {
447     keymaster_algorithm_t key_algorithm;
448     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
449         *error = KM_ERROR_UNKNOWN_ERROR;
450         return {};
451     }
452 
453     if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC)) {
454         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
455         return {};
456     }
457 
458     // We have established that the given key has the correct algorithm, and because this is the
459     // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
460     const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
461 
462     return generate_self_signed_cert(asymmetric_key, cert_params, fake_signature, error);
463 }
464 
GenerateUniqueId(uint64_t creation_date_time,const keymaster_blob_t & application_id,bool reset_since_rotation,keymaster_error_t * error) const465 keymaster::Buffer PureSoftKeymasterContext::GenerateUniqueId(uint64_t creation_date_time,
466                                                              const keymaster_blob_t& application_id,
467                                                              bool reset_since_rotation,
468                                                              keymaster_error_t* error) const {
469     *error = KM_ERROR_OK;
470     // The default implementation fakes the hardware bound key with an arbitrary 128-bit value.
471     // Any real implementation must follow the guidance from the interface definition
472     // hardware/interfaces/security/keymint/aidl/android/hardware/security/keymint/Tag.aidl:
473     // "..a unique hardware-bound secret known to the secure environment and never revealed by it.
474     // The secret must contain at least 128 bits of entropy and be unique to the individual device"
475     const std::vector<uint8_t> fake_hbk = {'M', 'u', 's', 't', 'B', 'e', 'R', 'a',
476                                            'n', 'd', 'o', 'm', 'B', 'i', 't', 's'};
477     Buffer unique_id;
478     *error = keymaster::generate_unique_id(fake_hbk, creation_date_time, application_id,
479                                            reset_since_rotation, &unique_id);
480     return unique_id;
481 }
482 
TranslateAuthorizationSetError(AuthorizationSet::Error err)483 static keymaster_error_t TranslateAuthorizationSetError(AuthorizationSet::Error err) {
484     switch (err) {
485     case AuthorizationSet::OK:
486         return KM_ERROR_OK;
487     case AuthorizationSet::ALLOCATION_FAILURE:
488         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
489     case AuthorizationSet::MALFORMED_DATA:
490         return KM_ERROR_UNKNOWN_ERROR;
491     }
492     return KM_ERROR_OK;
493 }
494 
UnwrapKey(const KeymasterKeyBlob & wrapped_key_blob,const KeymasterKeyBlob & wrapping_key_blob,const AuthorizationSet &,const KeymasterKeyBlob & masking_key,AuthorizationSet * wrapped_key_params,keymaster_key_format_t * wrapped_key_format,KeymasterKeyBlob * wrapped_key_material) const495 keymaster_error_t PureSoftKeymasterContext::UnwrapKey(
496     const KeymasterKeyBlob& wrapped_key_blob, const KeymasterKeyBlob& wrapping_key_blob,
497     const AuthorizationSet& /* wrapping_key_params */, const KeymasterKeyBlob& masking_key,
498     AuthorizationSet* wrapped_key_params, keymaster_key_format_t* wrapped_key_format,
499     KeymasterKeyBlob* wrapped_key_material) const {
500     keymaster_error_t error = KM_ERROR_OK;
501 
502     if (!wrapped_key_material) return KM_ERROR_UNEXPECTED_NULL_POINTER;
503 
504     // Parse wrapped key data
505     KeymasterBlob iv;
506     KeymasterKeyBlob transit_key;
507     KeymasterKeyBlob secure_key;
508     KeymasterBlob tag;
509     KeymasterBlob wrapped_key_description;
510     error = parse_wrapped_key(wrapped_key_blob, &iv, &transit_key, &secure_key, &tag,
511                               wrapped_key_params, wrapped_key_format, &wrapped_key_description);
512     if (error != KM_ERROR_OK) return error;
513 
514     UniquePtr<Key> key;
515     auto wrapping_key_params = AuthorizationSetBuilder()
516                                    .RsaEncryptionKey(2048, 65537)
517                                    .Digest(KM_DIGEST_SHA_2_256)
518                                    .Padding(KM_PAD_RSA_OAEP)
519                                    .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
520                                    .build();
521     error = ParseKeyBlob(wrapping_key_blob, wrapping_key_params, &key);
522     if (error != KM_ERROR_OK) return error;
523 
524     // Ensure the wrapping key has the right purpose
525     if (!key->hw_enforced().Contains(TAG_PURPOSE, KM_PURPOSE_WRAP) &&
526         !key->sw_enforced().Contains(TAG_PURPOSE, KM_PURPOSE_WRAP)) {
527         return KM_ERROR_INCOMPATIBLE_PURPOSE;
528     }
529 
530     auto operation_factory = GetOperationFactory(KM_ALGORITHM_RSA, KM_PURPOSE_DECRYPT);
531     if (!operation_factory) return KM_ERROR_UNKNOWN_ERROR;
532 
533     AuthorizationSet out_params;
534     OperationPtr operation(
535         operation_factory->CreateOperation(std::move(*key), wrapping_key_params, &error));
536     if (!operation.get()) return error;
537 
538     error = operation->Begin(wrapping_key_params, &out_params);
539     if (error != KM_ERROR_OK) return error;
540 
541     Buffer input;
542     Buffer output;
543     if (!input.Reinitialize(transit_key.key_material, transit_key.key_material_size)) {
544         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
545     }
546 
547     error = operation->Finish(wrapping_key_params, input, Buffer() /* signature */, &out_params,
548                               &output);
549     if (error != KM_ERROR_OK) return error;
550 
551     // decrypt the encrypted key material with the transit key
552     KeymasterKeyBlob key_material = {output.peek_read(), output.available_read()};
553 
554     // XOR the transit key with the masking key
555     if (key_material.key_material_size != masking_key.key_material_size) {
556         return KM_ERROR_INVALID_ARGUMENT;
557     }
558     for (size_t i = 0; i < key_material.key_material_size; i++) {
559         key_material.writable_data()[i] ^= masking_key.key_material[i];
560     }
561 
562     auto transit_key_authorizations = AuthorizationSetBuilder()
563                                           .AesEncryptionKey(256)
564                                           .Padding(KM_PAD_NONE)
565                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
566                                           .Authorization(TAG_NONCE, iv)
567                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)
568                                           .build();
569     if (transit_key_authorizations.is_valid() != AuthorizationSet::Error::OK) {
570         return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
571     }
572     auto gcm_params = AuthorizationSetBuilder()
573                           .Padding(KM_PAD_NONE)
574                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
575                           .Authorization(TAG_NONCE, iv)
576                           .Authorization(TAG_MAC_LENGTH, 128)
577                           .build();
578     if (gcm_params.is_valid() != AuthorizationSet::Error::OK) {
579         return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
580     }
581 
582     auto aes_factory = GetKeyFactory(KM_ALGORITHM_AES);
583     if (!aes_factory) return KM_ERROR_UNKNOWN_ERROR;
584 
585     UniquePtr<Key> aes_key;
586     error = aes_factory->LoadKey(std::move(key_material), gcm_params,
587                                  std::move(transit_key_authorizations), AuthorizationSet(),
588                                  &aes_key);
589     if (error != KM_ERROR_OK) return error;
590 
591     auto aes_operation_factory = GetOperationFactory(KM_ALGORITHM_AES, KM_PURPOSE_DECRYPT);
592     if (!aes_operation_factory) return KM_ERROR_UNKNOWN_ERROR;
593 
594     OperationPtr aes_operation(
595         aes_operation_factory->CreateOperation(std::move(*aes_key), gcm_params, &error));
596     if (!aes_operation.get()) return error;
597 
598     error = aes_operation->Begin(gcm_params, &out_params);
599     if (error != KM_ERROR_OK) return error;
600 
601     size_t consumed = 0;
602     Buffer encrypted_key, plaintext;
603     if (!plaintext.Reinitialize(secure_key.key_material_size + tag.data_length)) {
604         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
605     }
606     if (!encrypted_key.Reinitialize(secure_key.key_material_size + tag.data_length)) {
607         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
608     }
609     if (!encrypted_key.write(secure_key.key_material, secure_key.key_material_size)) {
610         return KM_ERROR_UNKNOWN_ERROR;
611     }
612     if (!encrypted_key.write(tag.data, tag.data_length)) {
613         return KM_ERROR_UNKNOWN_ERROR;
614     }
615 
616     AuthorizationSet update_outparams;
617     auto update_params = AuthorizationSetBuilder()
618                              .Authorization(TAG_ASSOCIATED_DATA, wrapped_key_description.data,
619                                             wrapped_key_description.data_length)
620                              .build();
621     if (update_params.is_valid() != AuthorizationSet::Error::OK) {
622         return TranslateAuthorizationSetError(update_params.is_valid());
623     }
624 
625     error = aes_operation->Update(update_params, encrypted_key, &update_outparams, &plaintext,
626                                   &consumed);
627     if (error != KM_ERROR_OK) return error;
628 
629     AuthorizationSet finish_params, finish_out_params;
630     Buffer finish_input;
631     error = aes_operation->Finish(finish_params, finish_input, Buffer() /* signature */,
632                                   &finish_out_params, &plaintext);
633     if (error != KM_ERROR_OK) return error;
634 
635     *wrapped_key_material = {plaintext.peek_read(), plaintext.available_read()};
636     if (!wrapped_key_material->key_material && plaintext.peek_read()) {
637         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
638     }
639 
640     return error;
641 }
642 
643 const AttestationContext::VerifiedBootParams*
GetVerifiedBootParams(keymaster_error_t * error) const644 PureSoftKeymasterContext::GetVerifiedBootParams(keymaster_error_t* error) const {
645     static VerifiedBootParams params;
646     static std::string fake_vb_key(32, 0);
647     params.verified_boot_key = {reinterpret_cast<uint8_t*>(fake_vb_key.data()), fake_vb_key.size()};
648     params.verified_boot_hash = {reinterpret_cast<uint8_t*>(fake_vb_key.data()),
649                                  fake_vb_key.size()};
650     params.verified_boot_state = KM_VERIFIED_BOOT_UNVERIFIED;
651     params.device_locked = false;
652     *error = KM_ERROR_OK;
653     return &params;
654 }
655 
656 }  // namespace keymaster
657