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