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 "trusty_keymaster_context.h"
18 
19 #include <array>
20 #include <utility>
21 
22 #include <stdlib.h>
23 #include <string.h>
24 
25 #include <keymaster/android_keymaster_utils.h>
26 #include <keymaster/contexts/soft_attestation_cert.h>
27 #include <keymaster/key_blob_utils/auth_encrypted_key_blob.h>
28 #include <keymaster/key_blob_utils/ocb_utils.h>
29 #include <keymaster/km_openssl/aes_key.h>
30 #include <keymaster/km_openssl/asymmetric_key.h>
31 #include <keymaster/km_openssl/attestation_record.h>
32 #include <keymaster/km_openssl/attestation_utils.h>
33 #include <keymaster/km_openssl/certificate_utils.h>
34 #include <keymaster/km_openssl/ec_key_factory.h>
35 #include <keymaster/km_openssl/hmac_key.h>
36 #include <keymaster/km_openssl/openssl_err.h>
37 #include <keymaster/km_openssl/rsa_key_factory.h>
38 #include <keymaster/km_openssl/triple_des_key.h>
39 #include <keymaster/logger.h>
40 #include <keymaster/operation.h>
41 #include <keymaster/wrapped_key.h>
42 #include <lib/hwkey/hwkey.h>
43 #include <lib/rng/trusty_rng.h>
44 #include <openssl/hmac.h>
45 
46 #include "second_imei_attestation.h"
47 #include "secure_storage_manager.h"
48 #include "trusty_aes_key.h"
49 
50 constexpr bool kUseSecureDeletion = true;
51 uint8_t allZerosOrHashOfVerifiedBootKey[32] = {};
52 
53 #ifdef KEYMASTER_DEBUG
54 #pragma message \
55         "Compiling with fake Keymaster Root of Trust values! DO NOT SHIP THIS!"
56 #endif
57 
58 // TRUSTY_KM_WRAPPING_KEY_SIZE controls the size of the AES key that is used
59 // to wrap keys before allowing NS to hold on to them.
60 // Previously, it had a hardcoded value of 16 bytes, but current guidance is to
61 // expand this to a 256-bit (32-byte) key.
62 //
63 // The plan is to leave old devices as they are, and issue new devices with a
64 // 32-byte key to ensure compatibility. New devices should set
65 // TRUSTY_WRAPPING_KEY_SIZE to 32 in their device Makefile to control this.
66 
67 #ifndef TRUSTY_KM_WRAPPING_KEY_SIZE
68 #define TRUSTY_KM_WRAPPING_KEY_SIZE 16
69 #endif
70 
71 namespace keymaster {
72 
73 namespace {
74 static const int kAesKeySize = TRUSTY_KM_WRAPPING_KEY_SIZE;
75 static const int kCallsBetweenRngReseeds = 32;
76 static const int kRngReseedSize = 64;
77 static const uint8_t kMasterKeyDerivationData[kAesKeySize] = "KeymasterMaster";
78 
UpgradeIntegerTag(keymaster_tag_t tag,uint32_t value,AuthorizationSet * set,bool * set_changed)79 bool UpgradeIntegerTag(keymaster_tag_t tag,
80                        uint32_t value,
81                        AuthorizationSet* set,
82                        bool* set_changed) {
83     int index = set->find(tag);
84     if (index == -1) {
85         *set_changed = true;
86         set->push_back(keymaster_key_param_t{.tag = tag, .integer = value});
87         return true;
88     }
89 
90     if (set->params[index].integer > value) {
91         return false;
92     }
93 
94     if (set->params[index].integer != value) {
95         *set_changed = true;
96         set->params[index].integer = value;
97     }
98     return true;
99 }
100 
101 }  // anonymous namespace
102 
TrustyKeymasterContext()103 TrustyKeymasterContext::TrustyKeymasterContext()
104         : AttestationContext(KmVersion::KEYMASTER_4),
105           enforcement_policy_(this),
106           secure_deletion_secret_storage_(*this /* random_source */),
107           rng_initialized_(false),
108           calls_since_reseed_(0) {
109     LOG_D("Creating TrustyKeymaster");
110     rsa_factory_.reset(new (std::nothrow) RsaKeyFactory(*this /* blob_maker */,
111                                                         *this /* context */));
112     tdes_factory_.reset(new (std::nothrow) TripleDesKeyFactory(
113             *this /* blob_maker */, *this /* random_source */));
114     ec_factory_.reset(new (std::nothrow) EcKeyFactory(*this /* blob_maker */,
115                                                       *this /* context */));
116     aes_factory_.reset(new (std::nothrow) TrustyAesKeyFactory(
117             *this /* blob_maker */, *this /* random_source */));
118     hmac_factory_.reset(new (std::nothrow) HmacKeyFactory(
119             *this /* blob_maker */, *this /* random_source */));
120     boot_params_.verified_boot_key.Reinitialize("Unbound", 7);
121     trusty_remote_provisioning_context_.reset(
122             new (std::nothrow) TrustyRemoteProvisioningContext());
123 }
124 
GetKeyFactory(keymaster_algorithm_t algorithm) const125 const KeyFactory* TrustyKeymasterContext::GetKeyFactory(
126         keymaster_algorithm_t algorithm) const {
127     switch (algorithm) {
128     case KM_ALGORITHM_RSA:
129         return rsa_factory_.get();
130     case KM_ALGORITHM_EC:
131         return ec_factory_.get();
132     case KM_ALGORITHM_AES:
133         return aes_factory_.get();
134     case KM_ALGORITHM_HMAC:
135         return hmac_factory_.get();
136     case KM_ALGORITHM_TRIPLE_DES:
137         return tdes_factory_.get();
138     default:
139         return nullptr;
140     }
141 }
142 
143 static keymaster_algorithm_t supported_algorithms[] = {
144         KM_ALGORITHM_RSA, KM_ALGORITHM_EC, KM_ALGORITHM_AES, KM_ALGORITHM_HMAC,
145         KM_ALGORITHM_TRIPLE_DES};
146 
GetSupportedAlgorithms(size_t * algorithms_count) const147 const keymaster_algorithm_t* TrustyKeymasterContext::GetSupportedAlgorithms(
148         size_t* algorithms_count) const {
149     *algorithms_count = array_length(supported_algorithms);
150     return supported_algorithms;
151 }
152 
GetOperationFactory(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose) const153 OperationFactory* TrustyKeymasterContext::GetOperationFactory(
154         keymaster_algorithm_t algorithm,
155         keymaster_purpose_t purpose) const {
156     const KeyFactory* key_factory = GetKeyFactory(algorithm);
157     if (!key_factory)
158         return nullptr;
159     return key_factory->GetOperationFactory(purpose);
160 }
161 
TranslateAuthorizationSetError(AuthorizationSet::Error err)162 static keymaster_error_t TranslateAuthorizationSetError(
163         AuthorizationSet::Error err) {
164     switch (err) {
165     case AuthorizationSet::OK:
166         return KM_ERROR_OK;
167     case AuthorizationSet::ALLOCATION_FAILURE:
168         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
169     case AuthorizationSet::MALFORMED_DATA:
170         return KM_ERROR_UNKNOWN_ERROR;
171     }
172     return KM_ERROR_OK;
173 }
174 
SetAuthorizations(const AuthorizationSet & key_description,keymaster_key_origin_t origin,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced,bool has_secure_deletion) const175 keymaster_error_t TrustyKeymasterContext::SetAuthorizations(
176         const AuthorizationSet& key_description,
177         keymaster_key_origin_t origin,
178         AuthorizationSet* hw_enforced,
179         AuthorizationSet* sw_enforced,
180         bool has_secure_deletion) const {
181     sw_enforced->Clear();
182     hw_enforced->Clear();
183 
184     for (auto& entry : key_description) {
185         switch (entry.tag) {
186         // Tags that should never appear in key descriptions.
187         case KM_TAG_ASSOCIATED_DATA:
188         case KM_TAG_AUTH_TOKEN:
189         case KM_TAG_BOOTLOADER_ONLY:
190         case KM_TAG_INVALID:
191         case KM_TAG_MAC_LENGTH:
192         case KM_TAG_NONCE:
193         case KM_TAG_ROOT_OF_TRUST:
194         case KM_TAG_UNIQUE_ID:
195         case KM_TAG_IDENTITY_CREDENTIAL_KEY:
196             return KM_ERROR_INVALID_KEY_BLOB;
197 
198         // Tags used only to provide information for certificate creation, but
199         // which should not be included in blobs.
200         case KM_TAG_ATTESTATION_APPLICATION_ID:
201         case KM_TAG_ATTESTATION_CHALLENGE:
202         case KM_TAG_ATTESTATION_ID_BRAND:
203         case KM_TAG_ATTESTATION_ID_DEVICE:
204         case KM_TAG_ATTESTATION_ID_IMEI:
205         case KM_TAG_ATTESTATION_ID_SECOND_IMEI:
206         case KM_TAG_ATTESTATION_ID_MANUFACTURER:
207         case KM_TAG_ATTESTATION_ID_MEID:
208         case KM_TAG_ATTESTATION_ID_MODEL:
209         case KM_TAG_ATTESTATION_ID_PRODUCT:
210         case KM_TAG_ATTESTATION_ID_SERIAL:
211         case KM_TAG_CERTIFICATE_NOT_AFTER:
212         case KM_TAG_CERTIFICATE_NOT_BEFORE:
213         case KM_TAG_CERTIFICATE_SERIAL:
214         case KM_TAG_CERTIFICATE_SUBJECT:
215         case KM_TAG_RESET_SINCE_ID_ROTATION:
216         case KM_TAG_MODULE_HASH:
217             break;
218 
219         // Unimplemented tags for which we return an error.
220         case KM_TAG_DEVICE_UNIQUE_ATTESTATION:
221             return KM_ERROR_INVALID_ARGUMENT;
222 
223         // Unimplemented tags we silently ignore.
224         case KM_TAG_ALLOW_WHILE_ON_BODY:
225             break;
226 
227         // Obsolete tags we silently ignore.
228         case KM_TAG_ALL_APPLICATIONS:
229         case KM_TAG_ROLLBACK_RESISTANT:
230         case KM_TAG_CONFIRMATION_TOKEN:
231 
232         // Tags that should not be added to blobs.
233         case KM_TAG_APPLICATION_ID:
234         case KM_TAG_APPLICATION_DATA:
235             break;
236 
237         // Tags we ignore because they'll be set below.
238         case KM_TAG_BOOT_PATCHLEVEL:
239         case KM_TAG_ORIGIN:
240         case KM_TAG_OS_PATCHLEVEL:
241         case KM_TAG_OS_VERSION:
242         case KM_TAG_VENDOR_PATCHLEVEL:
243             break;
244 
245         // Tags that are hardware-enforced
246         case KM_TAG_ALGORITHM:
247         case KM_TAG_AUTH_TIMEOUT:
248         case KM_TAG_BLOB_USAGE_REQUIREMENTS:
249         case KM_TAG_BLOCK_MODE:
250         case KM_TAG_CALLER_NONCE:
251         case KM_TAG_DIGEST:
252         case KM_TAG_EARLY_BOOT_ONLY:
253         case KM_TAG_ECIES_SINGLE_HASH_MODE:
254         case KM_TAG_EC_CURVE:
255         case KM_TAG_KDF:
256         case KM_TAG_KEY_SIZE:
257         case KM_TAG_MAX_USES_PER_BOOT:
258         case KM_TAG_MIN_MAC_LENGTH:
259         case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
260         case KM_TAG_NO_AUTH_REQUIRED:
261         case KM_TAG_PADDING:
262         case KM_TAG_PURPOSE:
263         case KM_TAG_ROLLBACK_RESISTANCE:
264         case KM_TAG_RSA_OAEP_MGF_DIGEST:
265         case KM_TAG_RSA_PUBLIC_EXPONENT:
266         case KM_TAG_TRUSTED_CONFIRMATION_REQUIRED:
267         case KM_TAG_TRUSTED_USER_PRESENCE_REQUIRED:
268         case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
269         case KM_TAG_USER_SECURE_ID:
270             hw_enforced->push_back(entry);
271             break;
272 
273         // KM_TAG_STORAGE_KEY handling depends if the feature is enabled.
274         case KM_TAG_STORAGE_KEY:
275 #if WITH_HWWSK_SUPPORT
276             hw_enforced->push_back(entry);
277             break;
278 #else
279             return KM_ERROR_UNIMPLEMENTED;
280 #endif
281 
282         case KM_TAG_USER_AUTH_TYPE: {
283             keymaster_key_param_t elem = entry;
284 
285             // This implementation does support TEE enforced password auth
286             elem.enumerated = entry.enumerated & HW_AUTH_PASSWORD;
287 
288 #if TEE_FINGERPRINT_AUTH_SUPPORTED
289             // If HW_AUTH_FINGERPRINT is supported it needs to be included too
290             elem.enumerated |= entry.enumerated & HW_AUTH_FINGERPRINT;
291 #endif
292             hw_enforced->push_back(elem);
293         } break;
294 
295         case KM_TAG_USAGE_COUNT_LIMIT:
296             LOG_D("Found usage count limit tag: %u", entry.integer);
297             if (entry.integer == 1 && has_secure_deletion) {
298                 // We can enforce a usage count of 1 in HW.
299                 hw_enforced->push_back(entry);
300             } else {
301                 // Otherwise we delegate to keystore.
302                 sw_enforced->push_back(entry);
303             }
304             break;
305 
306         // Keystore-enforced tags
307         case KM_TAG_ACTIVE_DATETIME:
308         case KM_TAG_ALL_USERS:
309         case KM_TAG_CREATION_DATETIME:
310         case KM_TAG_EXPORTABLE:
311         case KM_TAG_INCLUDE_UNIQUE_ID:
312         case KM_TAG_MAX_BOOT_LEVEL:
313         case KM_TAG_ORIGINATION_EXPIRE_DATETIME:
314         case KM_TAG_USAGE_EXPIRE_DATETIME:
315         case KM_TAG_USER_ID:
316             sw_enforced->push_back(entry);
317             break;
318         }
319     }
320 
321     hw_enforced->push_back(TAG_ORIGIN, origin);
322 
323     // these values will be 0 if not set by bootloader
324     hw_enforced->push_back(TAG_OS_VERSION, boot_params_.boot_os_version);
325     hw_enforced->push_back(TAG_OS_PATCHLEVEL, boot_params_.boot_os_patchlevel);
326 
327     if (vendor_patchlevel_.has_value()) {
328         hw_enforced->push_back(TAG_VENDOR_PATCHLEVEL,
329                                vendor_patchlevel_.value());
330     }
331     if (boot_patchlevel_.has_value()) {
332         hw_enforced->push_back(TAG_BOOT_PATCHLEVEL, boot_patchlevel_.value());
333     }
334     if (module_hash_.has_value()) {
335         keymaster_blob_t mod_hash = {module_hash_.value().data(),
336                                      module_hash_.value().size()};
337         sw_enforced->push_back(TAG_MODULE_HASH, mod_hash);
338     }
339 
340     if (sw_enforced->is_valid() != AuthorizationSet::OK)
341         return TranslateAuthorizationSetError(sw_enforced->is_valid());
342     if (hw_enforced->is_valid() != AuthorizationSet::OK)
343         return TranslateAuthorizationSetError(hw_enforced->is_valid());
344     return KM_ERROR_OK;
345 }
346 
BuildHiddenAuthorizations(const AuthorizationSet & input_set,AuthorizationSet * hidden) const347 keymaster_error_t TrustyKeymasterContext::BuildHiddenAuthorizations(
348         const AuthorizationSet& input_set,
349         AuthorizationSet* hidden) const {
350     keymaster_blob_t entry;
351     if (input_set.GetTagValue(TAG_APPLICATION_ID, &entry))
352         hidden->push_back(TAG_APPLICATION_ID, entry.data, entry.data_length);
353     if (input_set.GetTagValue(TAG_APPLICATION_DATA, &entry))
354         hidden->push_back(TAG_APPLICATION_DATA, entry.data, entry.data_length);
355 
356     // Copy verified boot key, verified boot state, and device lock state to
357     // hidden authorization set for binding to key.
358     keymaster_key_param_t root_of_trust;
359     root_of_trust.tag = KM_TAG_ROOT_OF_TRUST;
360     root_of_trust.blob.data = boot_params_.verified_boot_key.begin();
361     root_of_trust.blob.data_length =
362             boot_params_.verified_boot_key.buffer_size();
363     hidden->push_back(root_of_trust);
364 
365     root_of_trust.blob.data =
366             reinterpret_cast<const uint8_t*>(&boot_params_.verified_boot_state);
367     root_of_trust.blob.data_length = sizeof(boot_params_.verified_boot_state);
368     hidden->push_back(root_of_trust);
369 
370     root_of_trust.blob.data =
371             reinterpret_cast<const uint8_t*>(&boot_params_.device_locked);
372     root_of_trust.blob.data_length = sizeof(boot_params_.device_locked);
373     hidden->push_back(root_of_trust);
374 
375     return TranslateAuthorizationSetError(hidden->is_valid());
376 }
377 
GetKdfState(EncryptedKey * info) const378 keymaster_error_t TrustyKeymasterContext::GetKdfState(
379         EncryptedKey* info) const {
380     long rc = hwkey_open();
381     if (rc < 0) {
382         LOG_S("Error failing to open a connection to hwkey: %ld", rc);
383         return KM_ERROR_UNKNOWN_ERROR;
384     }
385 
386     hwkey_session_t session = (hwkey_session_t)rc;
387     struct hwkey_versioned_key_options opt = {
388             .kdf_version = HWKEY_KDF_VERSION_BEST,
389             .shared_key = false,
390             .rollback_version_source = HWKEY_ROLLBACK_COMMITTED_VERSION,
391             .os_rollback_version = HWKEY_ROLLBACK_VERSION_CURRENT,
392             .context = NULL,
393             .context_len = 0,
394             .key = NULL,
395             .key_len = 0,
396     };
397     rc = hwkey_derive_versioned(session, &opt);
398     if (rc < 0) {
399         LOG_S("Error deriving versioned master key: %ld", rc);
400         hwkey_close(session);
401         return KM_ERROR_UNKNOWN_ERROR;
402     }
403     hwkey_close(session);
404     // Any versioned format will put the KDF selection into the correct mode.
405     info->format = AES_GCM_WITH_SW_ENFORCED_VERSIONED;
406     info->kdf_version = opt.kdf_version;
407     info->addl_info = opt.os_rollback_version;
408     return KM_ERROR_OK;
409 }
410 
CreateAuthEncryptedKeyBlob(const AuthorizationSet & key_description,const KeymasterKeyBlob & key_material,const AuthorizationSet & hw_enforced,const AuthorizationSet & sw_enforced,const std::optional<SecureDeletionData> & secure_deletion_data,KeymasterKeyBlob * blob) const411 keymaster_error_t TrustyKeymasterContext::CreateAuthEncryptedKeyBlob(
412         const AuthorizationSet& key_description,
413         const KeymasterKeyBlob& key_material,
414         const AuthorizationSet& hw_enforced,
415         const AuthorizationSet& sw_enforced,
416         const std::optional<SecureDeletionData>& secure_deletion_data,
417         KeymasterKeyBlob* blob) const {
418     AuthorizationSet hidden;
419     keymaster_error_t error =
420             BuildHiddenAuthorizations(key_description, &hidden);
421     if (error != KM_ERROR_OK)
422         return error;
423 
424     KeymasterKeyBlob master_key;
425     EncryptedKey info;
426     error = GetKdfState(&info);
427     if (error != KM_ERROR_OK) {
428         return error;
429     }
430     error = DeriveMasterKey(&master_key, info);
431     if (error != KM_ERROR_OK) {
432         return error;
433     }
434 
435     KmErrorOr<EncryptedKey> encrypted_key;
436     if (secure_deletion_data) {
437         encrypted_key = EncryptKey(
438                 key_material, AES_GCM_WITH_SECURE_DELETION_VERSIONED,
439                 hw_enforced, sw_enforced, hidden, *secure_deletion_data,
440                 master_key, *this /* random */);
441     } else {
442         encrypted_key = EncryptKey(
443                 key_material, AES_GCM_WITH_SW_ENFORCED_VERSIONED, hw_enforced,
444                 sw_enforced, hidden, SecureDeletionData{}, master_key,
445                 *this /* random */);
446     }
447     if (!encrypted_key) {
448         return encrypted_key.error();
449     }
450 
451     encrypted_key->kdf_version = info.kdf_version;
452     encrypted_key->addl_info = info.addl_info;
453     KmErrorOr<KeymasterKeyBlob> serialized_key = SerializeAuthEncryptedBlob(
454             *encrypted_key, hw_enforced, sw_enforced,
455             secure_deletion_data ? secure_deletion_data->key_slot : 0);
456 
457     if (!serialized_key) {
458         return serialized_key.error();
459     }
460 
461     *blob = std::move(*serialized_key);
462     return KM_ERROR_OK;
463 }
464 
465 class KeySlotCleanup {
466 public:
KeySlotCleanup(const SecureDeletionSecretStorage & storage,uint32_t key_slot)467     KeySlotCleanup(const SecureDeletionSecretStorage& storage,
468                    uint32_t key_slot)
469             : storage_(storage), key_slot_(key_slot) {}
~KeySlotCleanup()470     ~KeySlotCleanup() {
471         if (key_slot_ != 0) {
472             storage_.DeleteKey(key_slot_);
473         }
474     }
475 
release()476     void release() { key_slot_ = 0; }
477 
478 private:
479     const SecureDeletionSecretStorage& storage_;
480     uint32_t key_slot_;
481 };
482 
CreateKeyBlob(const AuthorizationSet & key_description,keymaster_key_origin_t origin,const KeymasterKeyBlob & key_material,KeymasterKeyBlob * blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const483 keymaster_error_t TrustyKeymasterContext::CreateKeyBlob(
484         const AuthorizationSet& key_description,
485         keymaster_key_origin_t origin,
486         const KeymasterKeyBlob& key_material,
487         KeymasterKeyBlob* blob,
488         AuthorizationSet* hw_enforced,
489         AuthorizationSet* sw_enforced) const {
490     bool request_rollback_resistance =
491             key_description.Contains(TAG_ROLLBACK_RESISTANCE);
492     bool request_usage_limit =
493             key_description.Contains(TAG_USAGE_COUNT_LIMIT, 1);
494     bool request_secure_deletion =
495             request_rollback_resistance || request_usage_limit;
496 
497     LOG_D("Getting secure deletion data");
498     std::optional<SecureDeletionData> sdd;
499     if (kUseSecureDeletion) {
500         sdd = secure_deletion_secret_storage_.CreateDataForNewKey(
501                 request_secure_deletion,
502                 /* is_upgrade */ false);
503     }
504 
505     if (sdd) {
506         LOG_D("Got secure deletion data, FR size = %zu, SD size = %zu, slot = %u",
507               sdd->factory_reset_secret.buffer_size(),
508               sdd->secure_deletion_secret.buffer_size(), sdd->key_slot);
509     } else if (!kUseSecureDeletion) {
510         LOG_I("Not using secure deletion");
511     } else {
512         LOG_W("Failed to get secure deletion data. storageproxy not up?");
513     }
514 
515     uint32_t key_slot = sdd ? sdd->key_slot : 0;
516     bool has_secure_deletion = key_slot != 0;
517     if (request_secure_deletion && !has_secure_deletion) {
518         LOG_E("Secure deletion requested (rollback_resistance:%d, usage_limit:%d) but no slot available!",
519               request_rollback_resistance, request_usage_limit);
520         return KM_ERROR_ROLLBACK_RESISTANCE_UNAVAILABLE;
521     }
522 
523     // At this point we may have stored a secure deletion secret for this key.
524     // If something goes wrong before we return the blob, that slot will leak.
525     // Create an object to clean up on the error paths.
526     KeySlotCleanup key_slot_cleanup(secure_deletion_secret_storage_, key_slot);
527 
528     keymaster_error_t error =
529             SetAuthorizations(key_description, origin, hw_enforced, sw_enforced,
530                               has_secure_deletion);
531 
532     if (error != KM_ERROR_OK) {
533         return error;
534     }
535 
536     error = CreateAuthEncryptedKeyBlob(key_description, key_material,
537                                        *hw_enforced, *sw_enforced,
538                                        std::move(sdd), blob);
539     if (error != KM_ERROR_OK) {
540         return error;
541     }
542 
543     key_slot_cleanup.release();
544     return KM_ERROR_OK;
545 }
546 
UpgradeKeyBlob(const KeymasterKeyBlob & key_to_upgrade,const AuthorizationSet & upgrade_params,KeymasterKeyBlob * upgraded_key) const547 keymaster_error_t TrustyKeymasterContext::UpgradeKeyBlob(
548         const KeymasterKeyBlob& key_to_upgrade,
549         const AuthorizationSet& upgrade_params,
550         KeymasterKeyBlob* upgraded_key) const {
551     UniquePtr<Key> key;
552     keymaster_error_t error =
553             ParseKeyBlob(key_to_upgrade, upgrade_params, &key);
554     LOG_I("Upgrading key blob");
555     if (error != KM_ERROR_OK) {
556         return error;
557     }
558 
559     bool set_changed = false;
560     if (boot_params_.boot_os_version == 0) {
561         // We need to allow "upgrading" OS version to zero, to support upgrading
562         // from proper numbered releases to unnumbered development and preview
563         // releases.
564 
565         if (int pos = key->sw_enforced().find(TAG_OS_VERSION);
566             pos != -1 &&
567             key->sw_enforced()[pos].integer != boot_params_.boot_os_version) {
568             set_changed = true;
569             key->sw_enforced()[pos].integer = boot_params_.boot_os_version;
570         }
571     }
572 
573     if (!UpgradeIntegerTag(TAG_OS_VERSION, boot_params_.boot_os_version,
574                            &key->hw_enforced(), &set_changed) ||
575         !UpgradeIntegerTag(TAG_OS_PATCHLEVEL, boot_params_.boot_os_patchlevel,
576                            &key->hw_enforced(), &set_changed) ||
577         (vendor_patchlevel_.has_value() &&
578          !UpgradeIntegerTag(TAG_VENDOR_PATCHLEVEL, vendor_patchlevel_.value(),
579                             &key->hw_enforced(), &set_changed)) ||
580         (boot_patchlevel_.has_value() &&
581          !UpgradeIntegerTag(TAG_BOOT_PATCHLEVEL, boot_patchlevel_.value(),
582                             &key->hw_enforced(), &set_changed))) {
583         // One of the version fields would have been a downgrade. Not allowed.
584         return KM_ERROR_INVALID_ARGUMENT;
585     }
586 
587     if (!set_changed) {
588         return KM_ERROR_OK;
589     }
590 
591     bool has_secure_deletion = false;
592     if (key->secure_deletion_slot() != 0) {
593         LOG_D("Upgrading rollback-protected key blob in slot %u",
594               key->secure_deletion_slot());
595         has_secure_deletion = true;
596     }
597     if (!has_secure_deletion &&
598         upgrade_params.Contains(TAG_ROLLBACK_RESISTANCE)) {
599         LOG_D("Upgrading non rollback-protected key, adding rollback protection");
600         has_secure_deletion = true;
601     }
602 
603     std::optional<SecureDeletionData> sdd;
604     if (kUseSecureDeletion) {
605         sdd = secure_deletion_secret_storage_.CreateDataForNewKey(
606                 has_secure_deletion, true /* is_upgrade */);
607     }
608 
609     // At this point we may have stored a secure deletion secret for this key.
610     // If something goes wrong before we return the blob, that slot will leak.
611     // Create an object to clean up on the error paths.
612     KeySlotCleanup key_slot_cleanup(secure_deletion_secret_storage_,
613                                     sdd ? sdd->key_slot : 0);
614 
615     error = CreateAuthEncryptedKeyBlob(upgrade_params, key->key_material(),
616                                        key->hw_enforced(), key->sw_enforced(),
617                                        std::move(sdd), upgraded_key);
618     if (error != KM_ERROR_OK) {
619         return error;
620     }
621 
622     key_slot_cleanup.release();
623     return KM_ERROR_OK;
624 }
625 
626 constexpr std::array<uint8_t, 7> kKeystoreKeyBlobMagic = {'p', 'K', 'M', 'b',
627                                                           'l', 'o', 'b'};
628 constexpr size_t kKeystoreKeyTypeOffset = kKeystoreKeyBlobMagic.size();
629 constexpr size_t kKeystoreKeyBlobPrefixSize = kKeystoreKeyTypeOffset + 1;
630 
DeserializeKmCompatKeyBlob(const KeymasterKeyBlob & blob) const631 KmErrorOr<DeserializedKey> TrustyKeymasterContext::DeserializeKmCompatKeyBlob(
632         const KeymasterKeyBlob& blob) const {
633     // This blob has a keystore km_compat prefix.  This means that it was
634     // created by keystore calling TrustyKeymaster through the km_compat layer.
635     // The km_compat layer adds this prefix to determine whether it's actually a
636     // hardware blob that should be passed through to Keymaster, or whether it's
637     // a software only key and should be used by the emulation layer.
638     //
639     // In the case of hardware blobs, km_compat strips the prefix before handing
640     // the blob to Keymaster.  In the case of software blobs, km_compat never
641     // hands the blob to Keymaster.
642     //
643     // The fact that we've received this prefixed blob means that it was created
644     // through km_compat... but the device has now been upgraded from
645     // TrustyKeymaster to TrustyKeyMint, and so keystore is no longer using the
646     // km_compat layer, and the blob is just passed through with its prefix
647     // intact.
648     auto keyType = *(blob.begin() + kKeystoreKeyTypeOffset);
649     switch (keyType) {
650     case 0:
651         // This is a hardware blob. Strip the prefix and use the blob.
652         return DeserializeAuthEncryptedBlob(
653                 KeymasterKeyBlob(blob.begin() + kKeystoreKeyBlobPrefixSize,
654                                  blob.size() - kKeystoreKeyBlobPrefixSize));
655 
656     case 1:
657         LOG_E("Software key blobs are not supported.");
658         return KM_ERROR_INVALID_KEY_BLOB;
659 
660     default:
661         LOG_E("Invalid keystore blob prefix value %d", keyType);
662         return KM_ERROR_INVALID_KEY_BLOB;
663     }
664 }
665 
is_km_compat_blob(const KeymasterKeyBlob & blob)666 bool is_km_compat_blob(const KeymasterKeyBlob& blob) {
667     return blob.size() >= kKeystoreKeyBlobPrefixSize &&
668            std::equal(kKeystoreKeyBlobMagic.begin(),
669                       kKeystoreKeyBlobMagic.end(), blob.begin());
670 }
671 
DeserializeKeyBlob(const KeymasterKeyBlob & blob) const672 KmErrorOr<DeserializedKey> TrustyKeymasterContext::DeserializeKeyBlob(
673         const KeymasterKeyBlob& blob) const {
674     if (is_km_compat_blob(blob)) {
675         return DeserializeKmCompatKeyBlob(blob);
676     } else {
677         return DeserializeAuthEncryptedBlob(blob);
678     }
679 }
680 
ParseKeyBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,UniquePtr<Key> * key) const681 keymaster_error_t TrustyKeymasterContext::ParseKeyBlob(
682         const KeymasterKeyBlob& blob,
683         const AuthorizationSet& additional_params,
684         UniquePtr<Key>* key) const {
685     keymaster_error_t error;
686 
687     if (!key) {
688         return KM_ERROR_UNEXPECTED_NULL_POINTER;
689     }
690 
691     KmErrorOr<DeserializedKey> deserialized_key = DeserializeKeyBlob(blob);
692     if (!deserialized_key) {
693         return deserialized_key.error();
694     }
695     LOG_D("Deserialized blob with format: %d",
696           deserialized_key->encrypted_key.format);
697 
698     KeymasterKeyBlob master_key;
699     error = DeriveMasterKey(&master_key, deserialized_key->encrypted_key);
700     if (error != KM_ERROR_OK) {
701         return error;
702     }
703 
704     AuthorizationSet hidden;
705     error = BuildHiddenAuthorizations(additional_params, &hidden);
706     if (error != KM_ERROR_OK) {
707         return error;
708     }
709 
710     SecureDeletionData sdd;
711     if (deserialized_key->encrypted_key.format ==
712                 AES_GCM_WITH_SECURE_DELETION ||
713         deserialized_key->encrypted_key.format ==
714                 AES_GCM_WITH_SECURE_DELETION_VERSIONED) {
715         // This key requires secure deletion data.
716         sdd = secure_deletion_secret_storage_.GetDataForKey(
717                 deserialized_key->key_slot);
718     }
719 
720     LOG_D("Decrypting blob with format: %d",
721           deserialized_key->encrypted_key.format);
722     KmErrorOr<KeymasterKeyBlob> key_material =
723             DecryptKey(*deserialized_key, hidden, sdd, master_key);
724     if (!key_material) {
725         return key_material.error();
726     }
727 
728     keymaster_algorithm_t algorithm;
729     if (!deserialized_key->hw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm)) {
730         return KM_ERROR_INVALID_KEY_BLOB;
731     }
732 
733     auto factory = GetKeyFactory(algorithm);
734     error = factory->LoadKey(std::move(*key_material), additional_params,
735                              std::move(deserialized_key->hw_enforced),
736                              std::move(deserialized_key->sw_enforced), key);
737     if (key && key->get()) {
738         (*key)->set_secure_deletion_slot(deserialized_key->key_slot);
739     }
740 
741     return error;
742 }
743 
DeleteKey(const KeymasterKeyBlob & blob) const744 keymaster_error_t TrustyKeymasterContext::DeleteKey(
745         const KeymasterKeyBlob& blob) const {
746     KmErrorOr<DeserializedKey> deserialized_key = DeserializeKeyBlob(blob);
747     if (deserialized_key) {
748         LOG_D("Deserialized blob with format: %u",
749               deserialized_key->encrypted_key.format);
750         secure_deletion_secret_storage_.DeleteKey(deserialized_key->key_slot);
751     }
752 
753     return KM_ERROR_OK;
754 }
755 
DeleteAllKeys() const756 keymaster_error_t TrustyKeymasterContext::DeleteAllKeys() const {
757     secure_deletion_secret_storage_.DeleteAllKeys();
758     return KM_ERROR_OK;
759 }
760 
AddRngEntropy(const uint8_t * buf,size_t length) const761 keymaster_error_t TrustyKeymasterContext::AddRngEntropy(const uint8_t* buf,
762                                                         size_t length) const {
763     if (trusty_rng_add_entropy(buf, length) != 0)
764         return KM_ERROR_UNKNOWN_ERROR;
765     return KM_ERROR_OK;
766 }
767 
SetModuleHash(const keymaster_blob_t & mod_hash)768 keymaster_error_t TrustyKeymasterContext::SetModuleHash(
769         const keymaster_blob_t& mod_hash) {
770     std::vector<uint8_t> module_hash(mod_hash.data,
771                                      mod_hash.data + mod_hash.data_length);
772     if (module_hash_.has_value()) {
773         if (module_hash != module_hash_.value()) {
774             // Can't set module hash to a different value.
775             return KM_ERROR_MODULE_HASH_ALREADY_SET;
776         } else {
777             LOG_I("module hash already set, ignoring repeated attempt to set same info");
778             return KM_ERROR_OK;
779         }
780     } else {
781         module_hash_ = module_hash;
782         return KM_ERROR_OK;
783     }
784 }
785 
SeedRngIfNeeded() const786 bool TrustyKeymasterContext::SeedRngIfNeeded() const {
787     if (ShouldReseedRng())
788         const_cast<TrustyKeymasterContext*>(this)->ReseedRng();
789     return rng_initialized_;
790 }
791 
ShouldReseedRng() const792 bool TrustyKeymasterContext::ShouldReseedRng() const {
793     if (!rng_initialized_) {
794         LOG_I("RNG not initialized, reseed");
795         return true;
796     }
797 
798     if (++calls_since_reseed_ % kCallsBetweenRngReseeds == 0) {
799         LOG_I("Periodic reseed");
800         return true;
801     }
802     return false;
803 }
804 
ReseedRng()805 bool TrustyKeymasterContext::ReseedRng() {
806     uint8_t rand_seed[kRngReseedSize];
807     memset(rand_seed, 0, kRngReseedSize);
808     if (trusty_rng_hw_rand(rand_seed, kRngReseedSize) != 0) {
809         LOG_E("Failed to get bytes from HW RNG");
810         return false;
811     }
812     LOG_I("Reseeding with %d bytes from HW RNG", kRngReseedSize);
813     trusty_rng_add_entropy(rand_seed, kRngReseedSize);
814 
815     rng_initialized_ = true;
816     return true;
817 }
818 
819 // Gee wouldn't it be nice if the crypto service headers defined this.
820 enum DerivationParams {
821     DERIVATION_DATA_PARAM = 0,
822     OUTPUT_BUFFER_PARAM = 1,
823 };
824 
DeriveMasterKey(KeymasterKeyBlob * master_key,const EncryptedKey & enc_key) const825 keymaster_error_t TrustyKeymasterContext::DeriveMasterKey(
826         KeymasterKeyBlob* master_key,
827         const EncryptedKey& enc_key) const {
828     LOG_D("Deriving master key");
829 
830     long rc = hwkey_open();
831     if (rc < 0) {
832         return KM_ERROR_UNKNOWN_ERROR;
833     }
834 
835     hwkey_session_t session = (hwkey_session_t)rc;
836 
837     if (!master_key->Reset(kAesKeySize)) {
838         LOG_S("Could not allocate memory for master key buffer");
839         hwkey_close(session);
840         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
841     }
842 
843     if (enc_key.format < AES_GCM_WITH_SW_ENFORCED_VERSIONED) {
844         uint32_t kdf_version = HWKEY_KDF_VERSION_1;
845         rc = hwkey_derive(session, &kdf_version, kMasterKeyDerivationData,
846                           master_key->writable_data(), kAesKeySize);
847         if (rc < 0) {
848             LOG_S("Error deriving legacy master key: %ld", rc);
849             hwkey_close(session);
850             return KM_ERROR_UNKNOWN_ERROR;
851         }
852     } else {
853         struct hwkey_versioned_key_options opt = {
854                 .kdf_version = enc_key.kdf_version,
855                 .shared_key = false,
856                 .rollback_version_source = HWKEY_ROLLBACK_COMMITTED_VERSION,
857                 .os_rollback_version = enc_key.addl_info,
858                 .context = kMasterKeyDerivationData,
859                 .context_len = sizeof(kMasterKeyDerivationData),
860                 .key = master_key->writable_data(),
861                 .key_len = kAesKeySize,
862         };
863         rc = hwkey_derive_versioned(session, &opt);
864         if (rc < 0) {
865             LOG_S("Error deriving versioned master key: %ld", rc);
866             hwkey_close(session);
867             return KM_ERROR_UNKNOWN_ERROR;
868         }
869     }
870 
871     hwkey_close(session);
872     LOG_D("Key derivation complete");
873     return KM_ERROR_OK;
874 }
875 
InitializeAuthTokenKey()876 bool TrustyKeymasterContext::InitializeAuthTokenKey() {
877     if (auth_token_key_initialized_)
878         return true;
879 
880     keymaster_key_blob_t key;
881     key.key_material = auth_token_key_;
882     key.key_material_size = kAuthTokenKeySize;
883     keymaster_error_t error = enforcement_policy_.GetHmacKey(&key);
884     if (error == KM_ERROR_OK)
885         auth_token_key_initialized_ = true;
886     else
887         auth_token_key_initialized_ = false;
888 
889     return auth_token_key_initialized_;
890 }
891 
GetAuthTokenKey(keymaster_key_blob_t * key) const892 keymaster_error_t TrustyKeymasterContext::GetAuthTokenKey(
893         keymaster_key_blob_t* key) const {
894     if (!auth_token_key_initialized_ &&
895         !const_cast<TrustyKeymasterContext*>(this)->InitializeAuthTokenKey())
896         return KM_ERROR_UNKNOWN_ERROR;
897 
898     key->key_material = auth_token_key_;
899     key->key_material_size = kAuthTokenKeySize;
900     return KM_ERROR_OK;
901 }
902 
SetSystemVersion(uint32_t os_version,uint32_t os_patchlevel)903 keymaster_error_t TrustyKeymasterContext::SetSystemVersion(
904         uint32_t os_version,
905         uint32_t os_patchlevel) {
906     if (!version_info_set_) {
907         // Note that version info is now set by Configure, rather than by the
908         // bootloader.  This is to ensure that system-only updates can be done,
909         // to avoid breaking Project Treble.
910         boot_params_.boot_os_version = os_version;
911         boot_params_.boot_os_patchlevel = os_patchlevel;
912         version_info_set_ = true;
913     }
914 
915 #ifdef KEYMASTER_DEBUG
916     Buffer fake_root_of_trust("000111222333444555666777888999000", 32);
917     Buffer verified_boot_hash_none;
918     if (!root_of_trust_set_) {
919         /* Sets bootloader parameters to what is expected on a 'good' device,
920          * will pass attestation CTS tests. FOR DEBUGGING ONLY.
921          */
922         SetBootParams(os_version, os_patchlevel, fake_root_of_trust,
923                       KM_VERIFIED_BOOT_VERIFIED, true, verified_boot_hash_none);
924     }
925 #endif
926 
927     return KM_ERROR_OK;
928 }
929 
GetSystemVersion(uint32_t * os_version,uint32_t * os_patchlevel) const930 void TrustyKeymasterContext::GetSystemVersion(uint32_t* os_version,
931                                               uint32_t* os_patchlevel) const {
932     *os_version = boot_params_.boot_os_version;
933     *os_patchlevel = boot_params_.boot_os_patchlevel;
934 }
935 
936 const AttestationContext::VerifiedBootParams*
GetVerifiedBootParams(keymaster_error_t * error) const937 TrustyKeymasterContext::GetVerifiedBootParams(keymaster_error_t* error) const {
938     VerifiedBootParams& vb_parms =
939             const_cast<VerifiedBootParams&>(verified_boot_params_);
940 
941     if (boot_params_.verified_boot_key.buffer_size() == 0) {
942         // If an empty verified boot key was passed by the boot loader, set the
943         // verfified boot key in attestation parameters to 32 bytes of all
944         // zeros.
945         vb_parms.verified_boot_key = {allZerosOrHashOfVerifiedBootKey,
946                                       sizeof(allZerosOrHashOfVerifiedBootKey)};
947     } else if (boot_params_.verified_boot_key.buffer_size() > 0 &&
948                boot_params_.verified_boot_key.buffer_size() <= 32) {
949         vb_parms.verified_boot_key = {
950                 boot_params_.verified_boot_key.begin(),
951                 boot_params_.verified_boot_key.buffer_size()};
952     } else if (boot_params_.verified_boot_key.buffer_size() > 32) {
953         // If the verified boot key itself was passed by the boot loader, set
954         // SHA-256 hash of it to the verified boot key parameter of the
955         // attetation information.
956         vb_parms.verified_boot_key = {
957                 SHA256(boot_params_.verified_boot_key.begin(),
958                        boot_params_.verified_boot_key.buffer_size(),
959                        allZerosOrHashOfVerifiedBootKey),
960                 SHA256_DIGEST_LENGTH};
961     }
962 
963     vb_parms.verified_boot_hash = {
964             boot_params_.verified_boot_hash.begin(),
965             boot_params_.verified_boot_hash.buffer_size()};
966     vb_parms.verified_boot_state = boot_params_.verified_boot_state;
967     vb_parms.device_locked = boot_params_.device_locked;
968 
969     *error = KM_ERROR_OK;
970     return &verified_boot_params_;
971 }
972 
973 #define PROTO_BYTES_DOES_NOT_MATCH_BLOB(blob, proto) \
974     ((blob).data_length != (proto).size) ||          \
975             (memcmp((blob).data, (proto).bytes, (proto).size) != 0)
976 
VerifyAndCopyDeviceIds(const AuthorizationSet & attestation_params,AuthorizationSet * values_to_attest) const977 keymaster_error_t TrustyKeymasterContext::VerifyAndCopyDeviceIds(
978         const AuthorizationSet& attestation_params,
979         AuthorizationSet* values_to_attest) const {
980     SecureStorageManager* ss_manager = SecureStorageManager::get_instance();
981     if (ss_manager == nullptr) {
982         LOG_E("Failed to open secure storage session.");
983         return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
984     }
985 
986     AttestationIds ids;
987     auto err = ss_manager->ReadAttestationIds(&ids);
988     if (err != KM_ERROR_OK) {
989         return err;
990     }
991 
992     bool found_mismatch = false;
993     for (auto& entry : attestation_params) {
994         switch (entry.tag) {
995         case KM_TAG_ATTESTATION_ID_BRAND:
996             found_mismatch |=
997                     PROTO_BYTES_DOES_NOT_MATCH_BLOB(entry.blob, ids.brand);
998             values_to_attest->push_back(entry);
999             break;
1000 
1001         case KM_TAG_ATTESTATION_ID_DEVICE:
1002             found_mismatch |=
1003                     PROTO_BYTES_DOES_NOT_MATCH_BLOB(entry.blob, ids.device);
1004             values_to_attest->push_back(entry);
1005             break;
1006 
1007         case KM_TAG_ATTESTATION_ID_PRODUCT:
1008             found_mismatch |=
1009                     PROTO_BYTES_DOES_NOT_MATCH_BLOB(entry.blob, ids.product);
1010             values_to_attest->push_back(entry);
1011             break;
1012 
1013         case KM_TAG_ATTESTATION_ID_SERIAL:
1014             found_mismatch |=
1015                     PROTO_BYTES_DOES_NOT_MATCH_BLOB(entry.blob, ids.serial);
1016             values_to_attest->push_back(entry);
1017             break;
1018 
1019         case KM_TAG_ATTESTATION_ID_IMEI:
1020             found_mismatch |=
1021                     PROTO_BYTES_DOES_NOT_MATCH_BLOB(entry.blob, ids.imei);
1022             values_to_attest->push_back(entry);
1023             break;
1024 
1025         case KM_TAG_ATTESTATION_ID_SECOND_IMEI: {
1026             // Validate directly against storage if it is present.
1027             if (ids.second_imei.size > 0) {
1028                 found_mismatch |= PROTO_BYTES_DOES_NOT_MATCH_BLOB(
1029                         entry.blob, ids.second_imei);
1030                 values_to_attest->push_back(entry);
1031             } else {
1032 #ifndef KEYMASTER_NO_AUTO_SECOND_IMEI
1033                 // Typically dual-SIM devices ship with two sequential IMEIs.
1034                 // As the second IMEI was not provisioned to the KeyMint
1035                 // instance, it is still possible to attest to the second IMEI
1036                 // by validating that the second IMEI is the one after the first
1037                 // IMEI, which was provisoned to the KeyMint instance.
1038                 std::string imei_str(
1039                         reinterpret_cast<const char*>(ids.imei.bytes),
1040                         ids.imei.size);
1041 
1042                 long imei_numeric = strtol(imei_str.c_str(), NULL, 10);
1043                 bool second_imei_mismatch =
1044                         !validate_second_imei(entry.blob, imei_numeric);
1045                 if (second_imei_mismatch) {
1046                     LOG_E("Mismatch in second IMEI.");
1047                 }
1048                 found_mismatch |= second_imei_mismatch;
1049                 values_to_attest->push_back(entry);
1050 #endif
1051             }
1052         } break;
1053 
1054         case KM_TAG_ATTESTATION_ID_MEID:
1055             found_mismatch |=
1056                     PROTO_BYTES_DOES_NOT_MATCH_BLOB(entry.blob, ids.meid);
1057             values_to_attest->push_back(entry);
1058             break;
1059 
1060         case KM_TAG_ATTESTATION_ID_MANUFACTURER:
1061             found_mismatch |= PROTO_BYTES_DOES_NOT_MATCH_BLOB(entry.blob,
1062                                                               ids.manufacturer);
1063             values_to_attest->push_back(entry);
1064             break;
1065 
1066         case KM_TAG_ATTESTATION_ID_MODEL:
1067             found_mismatch |=
1068                     PROTO_BYTES_DOES_NOT_MATCH_BLOB(entry.blob, ids.model);
1069             values_to_attest->push_back(entry);
1070             break;
1071 
1072         default:
1073             // Ignore non-ID tags.
1074             break;
1075         }
1076     }
1077 
1078     if (found_mismatch) {
1079         values_to_attest->Clear();
1080         return KM_ERROR_CANNOT_ATTEST_IDS;
1081     }
1082 
1083     return KM_ERROR_OK;
1084 }
1085 
GenerateUniqueId(uint64_t creation_date_time,const keymaster_blob_t & application_id,bool reset_since_rotation,keymaster_error_t * error) const1086 Buffer TrustyKeymasterContext::GenerateUniqueId(
1087         uint64_t creation_date_time,
1088         const keymaster_blob_t& application_id,
1089         bool reset_since_rotation,
1090         keymaster_error_t* error) const {
1091     if (unique_id_hbk_.empty()) {
1092         KeymasterKeyBlob hbk;
1093         keymaster_error_t derive_error =
1094                 enforcement_policy_.GetUniqueIdKey(&hbk);
1095         if (derive_error != KM_ERROR_OK) {
1096             LOG_E("Failed to derive unique ID HBK: %d", derive_error);
1097             *error = derive_error;
1098             return {};
1099         }
1100         unique_id_hbk_ = std::vector(hbk.begin(), hbk.end());
1101     }
1102 
1103     Buffer unique_id;
1104     *error = keymaster::generate_unique_id(unique_id_hbk_, creation_date_time,
1105                                            application_id, reset_since_rotation,
1106                                            &unique_id);
1107     return unique_id;
1108 }
1109 
GetAttestationKey(keymaster_algorithm_t algorithm,keymaster_error_t * error) const1110 KeymasterKeyBlob TrustyKeymasterContext::GetAttestationKey(
1111         keymaster_algorithm_t algorithm,
1112         keymaster_error_t* error) const {
1113     AttestationKeySlot key_slot;
1114 
1115     switch (algorithm) {
1116     case KM_ALGORITHM_RSA:
1117         key_slot = AttestationKeySlot::kRsa;
1118         break;
1119 
1120     case KM_ALGORITHM_EC:
1121         key_slot = AttestationKeySlot::kEcdsa;
1122         break;
1123 
1124     default:
1125         *error = KM_ERROR_UNSUPPORTED_ALGORITHM;
1126         return {};
1127     }
1128 
1129     SecureStorageManager* ss_manager = SecureStorageManager::get_instance();
1130     if (ss_manager == nullptr) {
1131         LOG_E("Failed to open secure storage session.");
1132         *error = KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
1133         return {};
1134     }
1135     auto result = ss_manager->ReadKeyFromStorage(key_slot, error);
1136 #if KEYMASTER_SOFT_ATTESTATION_FALLBACK
1137     if (*error != KM_ERROR_OK) {
1138         LOG_I("Failed to read attestation key from RPMB, falling back to test key");
1139         auto key = getAttestationKey(algorithm, error);
1140         if (*error != KM_ERROR_OK) {
1141             LOG_D("Software attestation key missing: %d", *error);
1142             return {};
1143         }
1144         result = KeymasterKeyBlob(*key);
1145         if (!result.key_material)
1146             *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
1147     }
1148 #endif
1149     return result;
1150 }
1151 
GetAttestationChain(keymaster_algorithm_t algorithm,keymaster_error_t * error) const1152 CertificateChain TrustyKeymasterContext::GetAttestationChain(
1153         keymaster_algorithm_t algorithm,
1154         keymaster_error_t* error) const {
1155     AttestationKeySlot key_slot;
1156     switch (algorithm) {
1157     case KM_ALGORITHM_RSA:
1158         key_slot = AttestationKeySlot::kRsa;
1159         break;
1160     case KM_ALGORITHM_EC:
1161         key_slot = AttestationKeySlot::kEcdsa;
1162         break;
1163     default:
1164         *error = KM_ERROR_UNSUPPORTED_ALGORITHM;
1165         return {};
1166     }
1167 
1168     CertificateChain chain;
1169     SecureStorageManager* ss_manager = SecureStorageManager::get_instance();
1170     if (ss_manager == nullptr) {
1171         LOG_E("Failed to open secure storage session.");
1172         *error = KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
1173     } else {
1174         *error = ss_manager->ReadCertChainFromStorage(key_slot, &chain);
1175     }
1176 #if KEYMASTER_SOFT_ATTESTATION_FALLBACK
1177     if ((*error != KM_ERROR_OK) || (chain.entry_count == 0)) {
1178         LOG_I("Failed to read attestation chain from RPMB, falling back to test chain");
1179         chain = getAttestationChain(algorithm, error);
1180     }
1181 #endif
1182     return chain;
1183 }
1184 
GenerateAttestation(const Key & key,const AuthorizationSet & attest_params,UniquePtr<Key> attest_key,const KeymasterBlob & issuer_subject,keymaster_error_t * error) const1185 CertificateChain TrustyKeymasterContext::GenerateAttestation(
1186         const Key& key,
1187         const AuthorizationSet& attest_params,
1188         UniquePtr<Key> attest_key,
1189         const KeymasterBlob& issuer_subject,
1190         keymaster_error_t* error) const {
1191     *error = KM_ERROR_OK;
1192     keymaster_algorithm_t key_algorithm;
1193     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
1194         *error = KM_ERROR_UNKNOWN_ERROR;
1195         return {};
1196     }
1197 
1198     if ((key_algorithm != KM_ALGORITHM_RSA &&
1199          key_algorithm != KM_ALGORITHM_EC)) {
1200         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
1201         return {};
1202     }
1203 
1204     // We have established that the given key has the correct algorithm, and
1205     // because this is the TrustyKeymasterContext we can assume that the Key is
1206     // an AsymmetricKey. So we can downcast.
1207     const AsymmetricKey& asymmetric_key =
1208             static_cast<const AsymmetricKey&>(key);
1209 
1210     AttestKeyInfo attest_key_info(attest_key, &issuer_subject, error);
1211     if (*error != KM_ERROR_OK) {
1212         return {};
1213     }
1214 
1215     return generate_attestation(asymmetric_key, attest_params,
1216                                 std::move(attest_key_info), *this, error);
1217 }
1218 
GenerateSelfSignedCertificate(const Key & key,const AuthorizationSet & cert_params,bool fake_signature,keymaster_error_t * error) const1219 CertificateChain TrustyKeymasterContext::GenerateSelfSignedCertificate(
1220         const Key& key,
1221         const AuthorizationSet& cert_params,
1222         bool fake_signature,
1223         keymaster_error_t* error) const {
1224     keymaster_algorithm_t key_algorithm;
1225     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
1226         *error = KM_ERROR_UNKNOWN_ERROR;
1227         return {};
1228     }
1229 
1230     if ((key_algorithm != KM_ALGORITHM_RSA &&
1231          key_algorithm != KM_ALGORITHM_EC)) {
1232         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
1233         return {};
1234     }
1235 
1236     const AsymmetricKey& asymmetric_key =
1237             static_cast<const AsymmetricKey&>(key);
1238 
1239     return generate_self_signed_cert(asymmetric_key, cert_params,
1240                                      fake_signature, error);
1241 }
1242 
SetBootParams(uint32_t,uint32_t,const Buffer & verified_boot_key,keymaster_verified_boot_t verified_boot_state,bool device_locked,const Buffer & verified_boot_hash)1243 keymaster_error_t TrustyKeymasterContext::SetBootParams(
1244         uint32_t /* os_version */,
1245         uint32_t /* os_patchlevel */,
1246         const Buffer& verified_boot_key,
1247         keymaster_verified_boot_t verified_boot_state,
1248         bool device_locked,
1249         const Buffer& verified_boot_hash) {
1250     if (root_of_trust_set_)
1251         return KM_ERROR_ROOT_OF_TRUST_ALREADY_SET;
1252     boot_params_.verified_boot_hash.Reinitialize(verified_boot_hash);
1253     root_of_trust_set_ = true;
1254     boot_params_.verified_boot_state = verified_boot_state;
1255     boot_params_.device_locked = device_locked;
1256     boot_params_.verified_boot_key.Reinitialize("", 0);
1257 
1258     if (verified_boot_key.buffer_size()) {
1259         boot_params_.verified_boot_key.Reinitialize(verified_boot_key);
1260     } else {
1261         // If no boot key was passed, default to unverified/unlocked
1262         boot_params_.verified_boot_state = KM_VERIFIED_BOOT_UNVERIFIED;
1263     }
1264 
1265     if ((verified_boot_state != KM_VERIFIED_BOOT_VERIFIED) &&
1266         (verified_boot_state != KM_VERIFIED_BOOT_SELF_SIGNED)) {
1267         // If the device image was not verified or self signed, it cannot be
1268         // locked
1269         boot_params_.device_locked = false;
1270     }
1271 
1272     trusty_remote_provisioning_context_->SetBootParams(&boot_params_);
1273 
1274     return KM_ERROR_OK;
1275 }
1276 
1277 // Mostly adapted from pure_soft_keymaster_context.cpp
UnwrapKey(const KeymasterKeyBlob & wrapped_key_blob,const KeymasterKeyBlob & wrapping_key_blob,const AuthorizationSet & wrapping_key_params,const KeymasterKeyBlob & masking_key,AuthorizationSet * wrapped_key_params,keymaster_key_format_t * wrapped_key_format,KeymasterKeyBlob * wrapped_key_material) const1278 keymaster_error_t TrustyKeymasterContext::UnwrapKey(
1279         const KeymasterKeyBlob& wrapped_key_blob,
1280         const KeymasterKeyBlob& wrapping_key_blob,
1281         const AuthorizationSet& wrapping_key_params,
1282         const KeymasterKeyBlob& masking_key,
1283         AuthorizationSet* wrapped_key_params,
1284         keymaster_key_format_t* wrapped_key_format,
1285         KeymasterKeyBlob* wrapped_key_material) const {
1286     LOG_D("UnwrapKey:0");
1287 
1288     keymaster_error_t error = KM_ERROR_OK;
1289 
1290     if (wrapped_key_material == NULL) {
1291         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1292     }
1293 
1294     LOG_D("UnwrapKey:1");
1295     // Step 1 from IKeymasterDevice.hal file spec
1296     // Parse wrapping key
1297     UniquePtr<Key> wrapping_key;
1298     error = ParseKeyBlob(wrapping_key_blob, wrapping_key_params, &wrapping_key);
1299     if (error != KM_ERROR_OK) {
1300         LOG_E("Failed to parse wrapping key");
1301         return error;
1302     }
1303 
1304     AuthProxy wrapping_key_auths(wrapping_key->hw_enforced(),
1305                                  wrapping_key->sw_enforced());
1306 
1307     // Check Wrapping Key Purpose
1308     if (!wrapping_key_auths.Contains(TAG_PURPOSE, KM_PURPOSE_WRAP)) {
1309         LOG_E("Wrapping key did not have KM_PURPOSE_WRAP");
1310         return KM_ERROR_INCOMPATIBLE_PURPOSE;
1311     }
1312 
1313     // Check Padding mode is RSA_OAEP and digest is SHA_2_256 (spec
1314     // mandated)
1315     if (!wrapping_key_auths.Contains(TAG_DIGEST, KM_DIGEST_SHA_2_256)) {
1316         LOG_E("Wrapping key lacks authorization for SHA2-256");
1317         return KM_ERROR_INCOMPATIBLE_DIGEST;
1318     }
1319     if (!wrapping_key_auths.Contains(TAG_PADDING, KM_PAD_RSA_OAEP)) {
1320         LOG_E("Wrapping key lacks authorization for padding OAEP");
1321         return KM_ERROR_INCOMPATIBLE_PADDING_MODE;
1322     }
1323 
1324     // Check that that was also the padding mode and digest specified
1325     if (!wrapping_key_params.Contains(TAG_DIGEST, KM_DIGEST_SHA_2_256)) {
1326         LOG_E("Wrapping key must use SHA2-256");
1327         return KM_ERROR_INCOMPATIBLE_DIGEST;
1328     }
1329     if (!wrapping_key_params.Contains(TAG_PADDING, KM_PAD_RSA_OAEP)) {
1330         LOG_E("Wrapping key must use OAEP padding");
1331         return KM_ERROR_INCOMPATIBLE_PADDING_MODE;
1332     }
1333 
1334     LOG_D("UnwrapKey:2");
1335     // Step 2 from IKeymasterDevice.hal spec
1336     // Parse wrapped key
1337     KeymasterBlob iv;
1338     KeymasterKeyBlob transit_key;
1339     KeymasterKeyBlob secure_key;
1340     KeymasterBlob tag;
1341     KeymasterBlob wrapped_key_description;
1342     error = parse_wrapped_key(wrapped_key_blob, &iv, &transit_key, &secure_key,
1343                               &tag, wrapped_key_params, wrapped_key_format,
1344                               &wrapped_key_description);
1345     if (error != KM_ERROR_OK) {
1346         return error;
1347     }
1348 
1349     // Decrypt encryptedTransportKey (transit_key) with wrapping_key
1350     auto operation_factory = wrapping_key->key_factory()->GetOperationFactory(
1351             KM_PURPOSE_DECRYPT);
1352     if (operation_factory == NULL) {
1353         return KM_ERROR_UNKNOWN_ERROR;
1354     }
1355 
1356     AuthorizationSet out_params;
1357     OperationPtr operation(operation_factory->CreateOperation(
1358             std::move(*wrapping_key), wrapping_key_params, &error));
1359     if ((operation.get() == NULL) || (error != KM_ERROR_OK)) {
1360         return error;
1361     }
1362 
1363     error = operation->Begin(wrapping_key_params, &out_params);
1364     if (error != KM_ERROR_OK) {
1365         return error;
1366     }
1367 
1368     Buffer input;
1369     Buffer output;
1370     // Explicitly reinitialize rather than constructing in order to report
1371     // allocation failure.
1372     if (!input.Reinitialize(transit_key.key_material,
1373                             transit_key.key_material_size)) {
1374         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1375     }
1376 
1377     error = operation->Finish(wrapping_key_params, input,
1378                               Buffer() /* signature */, &out_params, &output);
1379     if (error != KM_ERROR_OK) {
1380         return error;
1381     }
1382 
1383     KeymasterKeyBlob transport_key = {
1384             output.peek_read(),
1385             output.available_read(),
1386     };
1387 
1388     LOG_D("UnwrapKey:3");
1389     // Step 3 of IKeymasterDevice.hal
1390     // XOR the transit key with the masking key
1391     if (transport_key.key_material_size != masking_key.key_material_size) {
1392         return KM_ERROR_INVALID_ARGUMENT;
1393     }
1394     for (size_t i = 0; i < transport_key.key_material_size; i++) {
1395         transport_key.writable_data()[i] ^= masking_key.key_material[i];
1396     }
1397 
1398     LOG_D("UnwrapKey:4");
1399     // Step 4 of IKeymasterDevice.hal
1400     // transit_key_authorizations is defined by spec
1401     // TODO the mac len is NOT in the spec, but probably should be
1402     auto transport_key_authorizations =
1403             AuthorizationSetBuilder()
1404                     .AesEncryptionKey(256)
1405                     .Padding(KM_PAD_NONE)
1406                     .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
1407                     .Authorization(TAG_NONCE, iv)
1408                     .Authorization(TAG_MIN_MAC_LENGTH, 128)
1409                     .build();
1410     auto validity = transport_key_authorizations.is_valid();
1411     if (validity != AuthorizationSet::Error::OK) {
1412         return TranslateAuthorizationSetError(validity);
1413     }
1414 
1415     // gcm_params is also defined by spec
1416     // TODO same problem with mac len not being specced
1417     auto gcm_params = AuthorizationSetBuilder()
1418                               .Padding(KM_PAD_NONE)
1419                               .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
1420                               .Authorization(TAG_NONCE, iv)
1421                               .Authorization(TAG_MAC_LENGTH, 128)
1422                               .build();
1423     validity = gcm_params.is_valid();
1424     if (validity != AuthorizationSet::Error::OK) {
1425         return TranslateAuthorizationSetError(validity);
1426     }
1427 
1428     auto aes_factory = GetKeyFactory(KM_ALGORITHM_AES);
1429     if (aes_factory == NULL) {
1430         return KM_ERROR_UNKNOWN_ERROR;
1431     }
1432 
1433     UniquePtr<Key> aes_transport_key;
1434     error = aes_factory->LoadKey(std::move(transport_key), gcm_params,
1435                                  std::move(transport_key_authorizations),
1436                                  AuthorizationSet(), &aes_transport_key);
1437     if (error != KM_ERROR_OK) {
1438         return error;
1439     }
1440 
1441     auto aes_operation_factory =
1442             GetOperationFactory(KM_ALGORITHM_AES, KM_PURPOSE_DECRYPT);
1443     if (aes_operation_factory == NULL) {
1444         return KM_ERROR_UNKNOWN_ERROR;
1445     }
1446 
1447     OperationPtr aes_operation(aes_operation_factory->CreateOperation(
1448             std::move(*aes_transport_key), gcm_params, &error));
1449     if ((aes_operation.get() == NULL) || (error != KM_ERROR_OK)) {
1450         return error;
1451     }
1452 
1453     error = aes_operation->Begin(gcm_params, &out_params);
1454     if (error != KM_ERROR_OK) {
1455         return error;
1456     }
1457 
1458     size_t update_consumed = 0;
1459     AuthorizationSet update_outparams;
1460 
1461     Buffer encrypted_key;
1462     Buffer plaintext_key;
1463 
1464     // Separate initialization to catch memory errors
1465     size_t total_key_size = secure_key.key_material_size + tag.data_length;
1466     if (!plaintext_key.Reinitialize(total_key_size)) {
1467         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1468     }
1469     if (!encrypted_key.Reinitialize(total_key_size)) {
1470         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1471     }
1472 
1473     // Concatenate key data
1474     if (!encrypted_key.write(secure_key.key_material,
1475                              secure_key.key_material_size)) {
1476         return KM_ERROR_UNKNOWN_ERROR;
1477     }
1478     if (!encrypted_key.write(tag.data, tag.data_length)) {
1479         return KM_ERROR_UNKNOWN_ERROR;
1480     }
1481 
1482     auto update_params =
1483             AuthorizationSetBuilder()
1484                     .Authorization(TAG_ASSOCIATED_DATA,
1485                                    wrapped_key_description.data,
1486                                    wrapped_key_description.data_length)
1487                     .build();
1488     validity = update_params.is_valid();
1489     if (validity != AuthorizationSet::Error::OK) {
1490         return TranslateAuthorizationSetError(validity);
1491     }
1492 
1493     error = aes_operation->Update(update_params, encrypted_key,
1494                                   &update_outparams, &plaintext_key,
1495                                   &update_consumed);
1496     if (error != KM_ERROR_OK) {
1497         return error;
1498     }
1499 
1500     AuthorizationSet finish_params;
1501     AuthorizationSet finish_out_params;
1502     Buffer finish_input;
1503     error = aes_operation->Finish(finish_params, finish_input,
1504                                   Buffer() /* signature */, &finish_out_params,
1505                                   &plaintext_key);
1506     if (error != KM_ERROR_OK) {
1507         return error;
1508     }
1509 
1510     *wrapped_key_material = {plaintext_key.peek_read(),
1511                              plaintext_key.available_read()};
1512 
1513     if (!wrapped_key_material->key_material && plaintext_key.peek_read()) {
1514         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1515     }
1516 
1517     LOG_D("UnwrapKey:Done");
1518     return error;
1519 }
1520 
CheckConfirmationToken(const uint8_t * input_data,size_t input_data_size,const uint8_t confirmation_token[kConfirmationTokenSize]) const1521 keymaster_error_t TrustyKeymasterContext::CheckConfirmationToken(
1522         const uint8_t* input_data,
1523         size_t input_data_size,
1524         const uint8_t confirmation_token[kConfirmationTokenSize]) const {
1525     // Note: ConfirmationUI is using the same secret key as auth tokens, the
1526     // difference is that messages are prefixed using the message tag
1527     // "confirmation token".
1528     keymaster_key_blob_t auth_token_key;
1529     keymaster_error_t error = GetAuthTokenKey(&auth_token_key);
1530     if (error != KM_ERROR_OK) {
1531         return error;
1532     }
1533 
1534     uint8_t computed_hash[EVP_MAX_MD_SIZE];
1535     unsigned int computed_hash_length;
1536     if (!HMAC(EVP_sha256(), auth_token_key.key_material,
1537               auth_token_key.key_material_size, input_data, input_data_size,
1538               computed_hash, &computed_hash_length)) {
1539         return KM_ERROR_UNKNOWN_ERROR;
1540     }
1541 
1542     if (computed_hash_length != kConfirmationTokenSize ||
1543         memcmp_s(computed_hash, confirmation_token, kConfirmationTokenSize) !=
1544                 0) {
1545         return KM_ERROR_NO_USER_CONFIRMATION;
1546     }
1547 
1548     return KM_ERROR_OK;
1549 }
1550 
GetDeviceIds() const1551 std::unique_ptr<cppbor::Map> TrustyKeymasterContext::GetDeviceIds() const {
1552     // Use the most up to date version of device info, back compat is
1553     // unnecessary here.
1554     return trusty_remote_provisioning_context_->CreateDeviceInfo(
1555             3 /* csrVersion */);
1556 }
1557 
1558 }  // namespace keymaster
1559