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