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