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