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 
GetKeyFactory(keymaster_algorithm_t algorithm) const144 KeyFactory* PureSoftKeymasterContext::GetKeyFactory(keymaster_algorithm_t algorithm) const {
145     switch (algorithm) {
146     case KM_ALGORITHM_RSA:
147         return rsa_factory_.get();
148     case KM_ALGORITHM_EC:
149         return ec_factory_.get();
150     case KM_ALGORITHM_AES:
151         return aes_factory_.get();
152     case KM_ALGORITHM_TRIPLE_DES:
153         return tdes_factory_.get();
154     case KM_ALGORITHM_HMAC:
155         return hmac_factory_.get();
156     default:
157         return nullptr;
158     }
159 }
160 
161 static keymaster_algorithm_t supported_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC,
162                                                        KM_ALGORITHM_AES, KM_ALGORITHM_HMAC};
163 
164 keymaster_algorithm_t*
GetSupportedAlgorithms(size_t * algorithms_count) const165 PureSoftKeymasterContext::GetSupportedAlgorithms(size_t* algorithms_count) const {
166     *algorithms_count = array_length(supported_algorithms);
167     return supported_algorithms;
168 }
169 
GetOperationFactory(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose) const170 OperationFactory* PureSoftKeymasterContext::GetOperationFactory(keymaster_algorithm_t algorithm,
171                                                                 keymaster_purpose_t purpose) const {
172     KeyFactory* key_factory = GetKeyFactory(algorithm);
173     if (!key_factory) return nullptr;
174     return key_factory->GetOperationFactory(purpose);
175 }
176 
CreateKeyBlob(const AuthorizationSet & key_description,const keymaster_key_origin_t origin,const KeymasterKeyBlob & key_material,KeymasterKeyBlob * blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const177 keymaster_error_t PureSoftKeymasterContext::CreateKeyBlob(const AuthorizationSet& key_description,
178                                                           const keymaster_key_origin_t origin,
179                                                           const KeymasterKeyBlob& key_material,
180                                                           KeymasterKeyBlob* blob,
181                                                           AuthorizationSet* hw_enforced,
182                                                           AuthorizationSet* sw_enforced) const {
183     // Check whether the key blob can be securely stored by pure software secure key storage.
184     bool canStoreBySecureKeyStorageIfRequired = false;
185     if (GetSecurityLevel() != KM_SECURITY_LEVEL_SOFTWARE &&
186         pure_soft_secure_key_storage_ != nullptr) {
187         pure_soft_secure_key_storage_->HasSlot(&canStoreBySecureKeyStorageIfRequired);
188     }
189 
190     bool needStoreBySecureKeyStorage = false;
191     if (key_description.GetTagValue(TAG_ROLLBACK_RESISTANCE)) {
192         needStoreBySecureKeyStorage = true;
193         if (!canStoreBySecureKeyStorageIfRequired) return KM_ERROR_ROLLBACK_RESISTANCE_UNAVAILABLE;
194     }
195 
196     if (GetSecurityLevel() != KM_SECURITY_LEVEL_SOFTWARE) {
197         // We're pretending to be some sort of secure hardware.  Put relevant tags in hw_enforced.
198         for (auto& entry : key_description) {
199             switch (entry.tag) {
200             case KM_TAG_PURPOSE:
201             case KM_TAG_ALGORITHM:
202             case KM_TAG_KEY_SIZE:
203             case KM_TAG_RSA_PUBLIC_EXPONENT:
204             case KM_TAG_BLOB_USAGE_REQUIREMENTS:
205             case KM_TAG_DIGEST:
206             case KM_TAG_PADDING:
207             case KM_TAG_BLOCK_MODE:
208             case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
209             case KM_TAG_MAX_USES_PER_BOOT:
210             case KM_TAG_USER_SECURE_ID:
211             case KM_TAG_NO_AUTH_REQUIRED:
212             case KM_TAG_AUTH_TIMEOUT:
213             case KM_TAG_CALLER_NONCE:
214             case KM_TAG_MIN_MAC_LENGTH:
215             case KM_TAG_KDF:
216             case KM_TAG_EC_CURVE:
217             case KM_TAG_ECIES_SINGLE_HASH_MODE:
218             case KM_TAG_USER_AUTH_TYPE:
219             case KM_TAG_ORIGIN:
220             case KM_TAG_OS_VERSION:
221             case KM_TAG_OS_PATCHLEVEL:
222             case KM_TAG_EARLY_BOOT_ONLY:
223             case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
224             case KM_TAG_RSA_OAEP_MGF_DIGEST:
225             case KM_TAG_ROLLBACK_RESISTANCE:
226                 hw_enforced->push_back(entry);
227                 break;
228             case KM_TAG_USAGE_COUNT_LIMIT:
229                 // Enforce single use key with usage count limit = 1 into secure key storage.
230                 if (canStoreBySecureKeyStorageIfRequired && entry.integer == 1) {
231                     needStoreBySecureKeyStorage = true;
232                     hw_enforced->push_back(entry);
233                 }
234                 break;
235             default:
236                 break;
237             }
238         }
239     }
240 
241     keymaster_error_t error =
242         SetKeyBlobAuthorizations(key_description, origin, os_version_, os_patchlevel_, hw_enforced,
243                                  sw_enforced, GetKmVersion());
244     if (error != KM_ERROR_OK) return error;
245     error =
246         ExtendKeyBlobAuthorizations(hw_enforced, sw_enforced, vendor_patchlevel_, boot_patchlevel_);
247     if (error != KM_ERROR_OK) return error;
248 
249     AuthorizationSet hidden;
250     error = BuildHiddenAuthorizations(key_description, &hidden, softwareRootOfTrust);
251     if (error != KM_ERROR_OK) return error;
252 
253     error = SerializeIntegrityAssuredBlob(key_material, hidden, *hw_enforced, *sw_enforced, blob);
254     if (error != KM_ERROR_OK) return error;
255 
256     // Pretend to be some sort of secure hardware that can securely store the key blob.
257     if (!needStoreBySecureKeyStorage) return KM_ERROR_OK;
258     km_id_t keyid;
259     if (!soft_keymaster_enforcement_.CreateKeyId(*blob, &keyid)) return KM_ERROR_UNKNOWN_ERROR;
260     assert(needStoreBySecureKeyStorage && canStoreBySecureKeyStorageIfRequired);
261     return pure_soft_secure_key_storage_->WriteKey(keyid, *blob);
262 }
263 
UpgradeKeyBlob(const KeymasterKeyBlob & key_to_upgrade,const AuthorizationSet & upgrade_params,KeymasterKeyBlob * upgraded_key) const264 keymaster_error_t PureSoftKeymasterContext::UpgradeKeyBlob(const KeymasterKeyBlob& key_to_upgrade,
265                                                            const AuthorizationSet& upgrade_params,
266                                                            KeymasterKeyBlob* upgraded_key) const {
267     UniquePtr<Key> key;
268     keymaster_error_t error = ParseKeyBlob(key_to_upgrade, upgrade_params, &key);
269     if (error != KM_ERROR_OK) return error;
270 
271     return FullUpgradeSoftKeyBlob(key, os_version_, os_patchlevel_, vendor_patchlevel_,
272                                   boot_patchlevel_, upgrade_params, upgraded_key);
273 }
274 
ParseKeyBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,UniquePtr<Key> * key) const275 keymaster_error_t PureSoftKeymasterContext::ParseKeyBlob(const KeymasterKeyBlob& blob,
276                                                          const AuthorizationSet& additional_params,
277                                                          UniquePtr<Key>* key) const {
278     // This is a little bit complicated.
279     //
280     // The SoftKeymasterContext has to handle a lot of different kinds of key blobs.
281     //
282     // 1.  New keymaster1 software key blobs.  These are integrity-assured but not encrypted.  The
283     //     raw key material and auth sets should be extracted and returned.  This is the kind
284     //     produced by this context when the KeyFactory doesn't use keymaster0 to back the keys.
285     //
286     // 2.  Old keymaster1 software key blobs.  These are OCB-encrypted with an all-zero master key.
287     //     They should be decrypted and the key material and auth sets extracted and returned.
288     //
289     // 3.  Old keymaster0 software key blobs.  These are raw key material with a small header tacked
290     //     on the front.  They don't have auth sets, so reasonable defaults are generated and
291     //     returned along with the raw key material.
292     //
293     // Determining what kind of blob has arrived is somewhat tricky.  What helps is that
294     // integrity-assured and OCB-encrypted blobs are self-consistent and effectively impossible to
295     // parse as anything else.  Old keymaster0 software key blobs have a header.  It's reasonably
296     // unlikely that hardware keys would have the same header.  So anything that is neither
297     // integrity-assured nor OCB-encrypted and lacks the old software key header is assumed to be
298     // keymaster0 hardware.
299 
300     AuthorizationSet hw_enforced;
301     AuthorizationSet sw_enforced;
302     KeymasterKeyBlob key_material;
303     keymaster_error_t error;
304 
305     auto constructKey = [&, this]() mutable -> keymaster_error_t {
306         // GetKeyFactory
307         if (error != KM_ERROR_OK) return error;
308         keymaster_algorithm_t algorithm;
309         if (!hw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm) &&
310             !sw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm)) {
311             return KM_ERROR_INVALID_ARGUMENT;
312         }
313 
314         // Pretend to be some sort of secure hardware that can securely store
315         // the key blob. Check the key blob is still securely stored now.
316         if (hw_enforced.Contains(KM_TAG_ROLLBACK_RESISTANCE) ||
317             hw_enforced.Contains(KM_TAG_USAGE_COUNT_LIMIT)) {
318             if (pure_soft_secure_key_storage_ == nullptr) return KM_ERROR_INVALID_KEY_BLOB;
319             km_id_t keyid;
320             bool exists;
321             if (!soft_keymaster_enforcement_.CreateKeyId(blob, &keyid))
322                 return KM_ERROR_INVALID_KEY_BLOB;
323             error = pure_soft_secure_key_storage_->KeyExists(keyid, &exists);
324             if (error != KM_ERROR_OK || !exists) return KM_ERROR_INVALID_KEY_BLOB;
325         }
326 
327         auto factory = GetKeyFactory(algorithm);
328         return factory->LoadKey(std::move(key_material), additional_params, std::move(hw_enforced),
329                                 std::move(sw_enforced), key);
330     };
331 
332     AuthorizationSet hidden;
333     error = BuildHiddenAuthorizations(additional_params, &hidden, softwareRootOfTrust);
334     if (error != KM_ERROR_OK) return error;
335 
336     // Assume it's an integrity-assured blob (new software-only blob, or new keymaster0-backed
337     // blob).
338     error =
339         DeserializeIntegrityAssuredBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
340     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
341 
342     // Wasn't an integrity-assured blob.  Maybe it's an auth-encrypted blob.
343     error = ParseAuthEncryptedBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
344     if (error == KM_ERROR_OK) LOG_D("Parsed an old keymaster1 software key");
345     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
346 
347     // Wasn't an auth-encrypted blob.  Maybe it's an old softkeymaster blob.
348     error = ParseOldSoftkeymasterBlob(blob, &key_material, &hw_enforced, &sw_enforced);
349     if (error == KM_ERROR_OK) LOG_D("Parsed an old sofkeymaster key");
350 
351     return constructKey();
352 }
353 
DeleteKey(const KeymasterKeyBlob & blob) const354 keymaster_error_t PureSoftKeymasterContext::DeleteKey(const KeymasterKeyBlob& blob) const {
355     // Pretend to be some secure hardware with secure storage.
356     if (GetSecurityLevel() != KM_SECURITY_LEVEL_SOFTWARE &&
357         pure_soft_secure_key_storage_ != nullptr) {
358         km_id_t keyid;
359         if (!soft_keymaster_enforcement_.CreateKeyId(blob, &keyid)) return KM_ERROR_UNKNOWN_ERROR;
360         return pure_soft_secure_key_storage_->DeleteKey(keyid);
361     }
362 
363     // Otherwise, nothing to do for software-only contexts.
364     return KM_ERROR_OK;
365 }
366 
DeleteAllKeys() const367 keymaster_error_t PureSoftKeymasterContext::DeleteAllKeys() const {
368     // Pretend to be some secure hardware with secure storage.
369     if (GetSecurityLevel() != KM_SECURITY_LEVEL_SOFTWARE &&
370         pure_soft_secure_key_storage_ != nullptr) {
371         return pure_soft_secure_key_storage_->DeleteAllKeys();
372     }
373 
374     // Otherwise, nothing to do for software-only contexts.
375     return KM_ERROR_OK;
376 }
377 
AddRngEntropy(const uint8_t * buf,size_t length) const378 keymaster_error_t PureSoftKeymasterContext::AddRngEntropy(const uint8_t* buf, size_t length) const {
379     if (length > 2 * 1024) {
380         // At most 2KiB is allowed to be added at once.
381         return KM_ERROR_INVALID_INPUT_LENGTH;
382     }
383     // XXX TODO according to boringssl openssl/rand.h RAND_add is deprecated and does
384     // nothing
385     RAND_add(buf, length, 0 /* Don't assume any entropy is added to the pool. */);
386     return KM_ERROR_OK;
387 }
388 
389 CertificateChain
GenerateAttestation(const Key & key,const AuthorizationSet & attest_params,UniquePtr<Key> attest_key,const KeymasterBlob & issuer_subject,keymaster_error_t * error) const390 PureSoftKeymasterContext::GenerateAttestation(const Key& key,                         //
391                                               const AuthorizationSet& attest_params,  //
392                                               UniquePtr<Key> attest_key,
393                                               const KeymasterBlob& issuer_subject,
394                                               keymaster_error_t* error) const {
395     if (!error) return {};
396     *error = KM_ERROR_OK;
397 
398     keymaster_algorithm_t key_algorithm;
399     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
400         *error = KM_ERROR_UNKNOWN_ERROR;
401         return {};
402     }
403 
404     if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC)) {
405         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
406         return {};
407     }
408 
409     if (attest_params.GetTagValue(TAG_DEVICE_UNIQUE_ATTESTATION)) {
410         *error = KM_ERROR_UNIMPLEMENTED;
411         return {};
412     }
413     // We have established that the given key has the correct algorithm, and because this is the
414     // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
415     const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
416 
417     AttestKeyInfo attest_key_info(attest_key, &issuer_subject, error);
418     if (*error != KM_ERROR_OK) return {};
419 
420     return generate_attestation(asymmetric_key, attest_params, std::move(attest_key_info), *this,
421                                 error);
422 }
423 
GenerateSelfSignedCertificate(const Key & key,const AuthorizationSet & cert_params,bool fake_signature,keymaster_error_t * error) const424 CertificateChain PureSoftKeymasterContext::GenerateSelfSignedCertificate(
425     const Key& key, const AuthorizationSet& cert_params, bool fake_signature,
426     keymaster_error_t* error) const {
427     keymaster_algorithm_t key_algorithm;
428     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
429         *error = KM_ERROR_UNKNOWN_ERROR;
430         return {};
431     }
432 
433     if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC)) {
434         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
435         return {};
436     }
437 
438     // We have established that the given key has the correct algorithm, and because this is the
439     // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
440     const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
441 
442     return generate_self_signed_cert(asymmetric_key, cert_params, fake_signature, error);
443 }
444 
GenerateUniqueId(uint64_t creation_date_time,const keymaster_blob_t & application_id,bool reset_since_rotation,keymaster_error_t * error) const445 keymaster::Buffer PureSoftKeymasterContext::GenerateUniqueId(uint64_t creation_date_time,
446                                                              const keymaster_blob_t& application_id,
447                                                              bool reset_since_rotation,
448                                                              keymaster_error_t* error) const {
449     *error = KM_ERROR_OK;
450     // The default implementation fakes the hardware bound key with an arbitrary 128-bit value.
451     // Any real implementation must follow the guidance from the interface definition
452     // hardware/interfaces/security/keymint/aidl/android/hardware/security/keymint/Tag.aidl:
453     // "..a unique hardware-bound secret known to the secure environment and never revealed by it.
454     // The secret must contain at least 128 bits of entropy and be unique to the individual device"
455     const std::vector<uint8_t> fake_hbk = {'M', 'u', 's', 't', 'B', 'e', 'R', 'a',
456                                            'n', 'd', 'o', 'm', 'B', 'i', 't', 's'};
457     Buffer unique_id;
458     *error = keymaster::generate_unique_id(fake_hbk, creation_date_time, application_id,
459                                            reset_since_rotation, &unique_id);
460     return unique_id;
461 }
462 
TranslateAuthorizationSetError(AuthorizationSet::Error err)463 static keymaster_error_t TranslateAuthorizationSetError(AuthorizationSet::Error err) {
464     switch (err) {
465     case AuthorizationSet::OK:
466         return KM_ERROR_OK;
467     case AuthorizationSet::ALLOCATION_FAILURE:
468         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
469     case AuthorizationSet::MALFORMED_DATA:
470         return KM_ERROR_UNKNOWN_ERROR;
471     }
472     return KM_ERROR_OK;
473 }
474 
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) const475 keymaster_error_t PureSoftKeymasterContext::UnwrapKey(
476     const KeymasterKeyBlob& wrapped_key_blob, const KeymasterKeyBlob& wrapping_key_blob,
477     const AuthorizationSet& /* wrapping_key_params */, const KeymasterKeyBlob& masking_key,
478     AuthorizationSet* wrapped_key_params, keymaster_key_format_t* wrapped_key_format,
479     KeymasterKeyBlob* wrapped_key_material) const {
480     keymaster_error_t error = KM_ERROR_OK;
481 
482     if (!wrapped_key_material) return KM_ERROR_UNEXPECTED_NULL_POINTER;
483 
484     // Parse wrapped key data
485     KeymasterBlob iv;
486     KeymasterKeyBlob transit_key;
487     KeymasterKeyBlob secure_key;
488     KeymasterBlob tag;
489     KeymasterBlob wrapped_key_description;
490     error = parse_wrapped_key(wrapped_key_blob, &iv, &transit_key, &secure_key, &tag,
491                               wrapped_key_params, wrapped_key_format, &wrapped_key_description);
492     if (error != KM_ERROR_OK) return error;
493 
494     UniquePtr<Key> key;
495     auto wrapping_key_params = AuthorizationSetBuilder()
496                                    .RsaEncryptionKey(2048, 65537)
497                                    .Digest(KM_DIGEST_SHA_2_256)
498                                    .Padding(KM_PAD_RSA_OAEP)
499                                    .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
500                                    .build();
501     error = ParseKeyBlob(wrapping_key_blob, wrapping_key_params, &key);
502     if (error != KM_ERROR_OK) return error;
503 
504     // Ensure the wrapping key has the right purpose
505     if (!key->hw_enforced().Contains(TAG_PURPOSE, KM_PURPOSE_WRAP) &&
506         !key->sw_enforced().Contains(TAG_PURPOSE, KM_PURPOSE_WRAP)) {
507         return KM_ERROR_INCOMPATIBLE_PURPOSE;
508     }
509 
510     auto operation_factory = GetOperationFactory(KM_ALGORITHM_RSA, KM_PURPOSE_DECRYPT);
511     if (!operation_factory) return KM_ERROR_UNKNOWN_ERROR;
512 
513     AuthorizationSet out_params;
514     OperationPtr operation(
515         operation_factory->CreateOperation(std::move(*key), wrapping_key_params, &error));
516     if (!operation.get()) return error;
517 
518     error = operation->Begin(wrapping_key_params, &out_params);
519     if (error != KM_ERROR_OK) return error;
520 
521     Buffer input;
522     Buffer output;
523     if (!input.Reinitialize(transit_key.key_material, transit_key.key_material_size)) {
524         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
525     }
526 
527     error = operation->Finish(wrapping_key_params, input, Buffer() /* signature */, &out_params,
528                               &output);
529     if (error != KM_ERROR_OK) return error;
530 
531     // decrypt the encrypted key material with the transit key
532     KeymasterKeyBlob key_material = {output.peek_read(), output.available_read()};
533 
534     // XOR the transit key with the masking key
535     if (key_material.key_material_size != masking_key.key_material_size) {
536         return KM_ERROR_INVALID_ARGUMENT;
537     }
538     for (size_t i = 0; i < key_material.key_material_size; i++) {
539         key_material.writable_data()[i] ^= masking_key.key_material[i];
540     }
541 
542     auto transit_key_authorizations = AuthorizationSetBuilder()
543                                           .AesEncryptionKey(256)
544                                           .Padding(KM_PAD_NONE)
545                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
546                                           .Authorization(TAG_NONCE, iv)
547                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)
548                                           .build();
549     if (transit_key_authorizations.is_valid() != AuthorizationSet::Error::OK) {
550         return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
551     }
552     auto gcm_params = AuthorizationSetBuilder()
553                           .Padding(KM_PAD_NONE)
554                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
555                           .Authorization(TAG_NONCE, iv)
556                           .Authorization(TAG_MAC_LENGTH, 128)
557                           .build();
558     if (gcm_params.is_valid() != AuthorizationSet::Error::OK) {
559         return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
560     }
561 
562     auto aes_factory = GetKeyFactory(KM_ALGORITHM_AES);
563     if (!aes_factory) return KM_ERROR_UNKNOWN_ERROR;
564 
565     UniquePtr<Key> aes_key;
566     error = aes_factory->LoadKey(std::move(key_material), gcm_params,
567                                  std::move(transit_key_authorizations), AuthorizationSet(),
568                                  &aes_key);
569     if (error != KM_ERROR_OK) return error;
570 
571     auto aes_operation_factory = GetOperationFactory(KM_ALGORITHM_AES, KM_PURPOSE_DECRYPT);
572     if (!aes_operation_factory) return KM_ERROR_UNKNOWN_ERROR;
573 
574     OperationPtr aes_operation(
575         aes_operation_factory->CreateOperation(std::move(*aes_key), gcm_params, &error));
576     if (!aes_operation.get()) return error;
577 
578     error = aes_operation->Begin(gcm_params, &out_params);
579     if (error != KM_ERROR_OK) return error;
580 
581     size_t consumed = 0;
582     Buffer encrypted_key, plaintext;
583     if (!plaintext.Reinitialize(secure_key.key_material_size + tag.data_length)) {
584         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
585     }
586     if (!encrypted_key.Reinitialize(secure_key.key_material_size + tag.data_length)) {
587         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
588     }
589     if (!encrypted_key.write(secure_key.key_material, secure_key.key_material_size)) {
590         return KM_ERROR_UNKNOWN_ERROR;
591     }
592     if (!encrypted_key.write(tag.data, tag.data_length)) {
593         return KM_ERROR_UNKNOWN_ERROR;
594     }
595 
596     AuthorizationSet update_outparams;
597     auto update_params = AuthorizationSetBuilder()
598                              .Authorization(TAG_ASSOCIATED_DATA, wrapped_key_description.data,
599                                             wrapped_key_description.data_length)
600                              .build();
601     if (update_params.is_valid() != AuthorizationSet::Error::OK) {
602         return TranslateAuthorizationSetError(update_params.is_valid());
603     }
604 
605     error = aes_operation->Update(update_params, encrypted_key, &update_outparams, &plaintext,
606                                   &consumed);
607     if (error != KM_ERROR_OK) return error;
608 
609     AuthorizationSet finish_params, finish_out_params;
610     Buffer finish_input;
611     error = aes_operation->Finish(finish_params, finish_input, Buffer() /* signature */,
612                                   &finish_out_params, &plaintext);
613     if (error != KM_ERROR_OK) return error;
614 
615     *wrapped_key_material = {plaintext.peek_read(), plaintext.available_read()};
616     if (!wrapped_key_material->key_material && plaintext.peek_read()) {
617         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
618     }
619 
620     return error;
621 }
622 
623 const AttestationContext::VerifiedBootParams*
GetVerifiedBootParams(keymaster_error_t * error) const624 PureSoftKeymasterContext::GetVerifiedBootParams(keymaster_error_t* error) const {
625     static VerifiedBootParams params;
626     static std::string fake_vb_key(32, 0);
627     params.verified_boot_key = {reinterpret_cast<uint8_t*>(fake_vb_key.data()), fake_vb_key.size()};
628     params.verified_boot_hash = {reinterpret_cast<uint8_t*>(fake_vb_key.data()),
629                                  fake_vb_key.size()};
630     params.verified_boot_state = KM_VERIFIED_BOOT_UNVERIFIED;
631     params.device_locked = false;
632     *error = KM_ERROR_OK;
633     return &params;
634 }
635 
636 }  // namespace keymaster
637