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 <memory>
20 
21 #include <openssl/aes.h>
22 #include <openssl/evp.h>
23 #include <openssl/hmac.h>
24 #include <openssl/rand.h>
25 #include <openssl/sha.h>
26 #include <openssl/x509v3.h>
27 
28 #include <keymaster/android_keymaster_utils.h>
29 #include <keymaster/key_blob_utils/auth_encrypted_key_blob.h>
30 #include <keymaster/key_blob_utils/integrity_assured_key_blob.h>
31 #include <keymaster/key_blob_utils/ocb_utils.h>
32 #include <keymaster/key_blob_utils/software_keyblobs.h>
33 #include <keymaster/km_openssl/aes_key.h>
34 #include <keymaster/km_openssl/asymmetric_key.h>
35 #include <keymaster/km_openssl/attestation_utils.h>
36 #include <keymaster/km_openssl/ec_key_factory.h>
37 #include <keymaster/km_openssl/hmac_key.h>
38 #include <keymaster/km_openssl/openssl_err.h>
39 #include <keymaster/km_openssl/openssl_utils.h>
40 #include <keymaster/km_openssl/rsa_key_factory.h>
41 #include <keymaster/km_openssl/soft_keymaster_enforcement.h>
42 #include <keymaster/km_openssl/triple_des_key.h>
43 #include <keymaster/logger.h>
44 #include <keymaster/operation.h>
45 #include <keymaster/wrapped_key.h>
46 
47 #include <keymaster/contexts/soft_attestation_cert.h>
48 
49 using std::unique_ptr;
50 
51 namespace keymaster {
52 
PureSoftKeymasterContext(keymaster_security_level_t security_level)53 PureSoftKeymasterContext::PureSoftKeymasterContext(keymaster_security_level_t security_level)
54     : rsa_factory_(new RsaKeyFactory(this)), ec_factory_(new EcKeyFactory(this)),
55       aes_factory_(new AesKeyFactory(this, this)),
56       tdes_factory_(new TripleDesKeyFactory(this, this)),
57       hmac_factory_(new HmacKeyFactory(this, this)), os_version_(0), os_patchlevel_(0),
58       soft_keymaster_enforcement_(64, 64), security_level_(security_level) {}
59 
~PureSoftKeymasterContext()60 PureSoftKeymasterContext::~PureSoftKeymasterContext() {}
61 
SetSystemVersion(uint32_t os_version,uint32_t os_patchlevel)62 keymaster_error_t PureSoftKeymasterContext::SetSystemVersion(uint32_t os_version,
63                                                          uint32_t os_patchlevel) {
64     os_version_ = os_version;
65     os_patchlevel_ = os_patchlevel;
66     return KM_ERROR_OK;
67 }
68 
GetSystemVersion(uint32_t * os_version,uint32_t * os_patchlevel) const69 void PureSoftKeymasterContext::GetSystemVersion(uint32_t* os_version, uint32_t* os_patchlevel) const {
70     *os_version = os_version_;
71     *os_patchlevel = os_patchlevel_;
72 }
73 
GetKeyFactory(keymaster_algorithm_t algorithm) const74 KeyFactory* PureSoftKeymasterContext::GetKeyFactory(keymaster_algorithm_t algorithm) const {
75     switch (algorithm) {
76     case KM_ALGORITHM_RSA:
77         return rsa_factory_.get();
78     case KM_ALGORITHM_EC:
79         return ec_factory_.get();
80     case KM_ALGORITHM_AES:
81         return aes_factory_.get();
82     case KM_ALGORITHM_TRIPLE_DES:
83         return tdes_factory_.get();
84     case KM_ALGORITHM_HMAC:
85         return hmac_factory_.get();
86     default:
87         return nullptr;
88     }
89 }
90 
91 static keymaster_algorithm_t supported_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC,
92                                                        KM_ALGORITHM_AES, KM_ALGORITHM_HMAC};
93 
94 keymaster_algorithm_t*
GetSupportedAlgorithms(size_t * algorithms_count) const95 PureSoftKeymasterContext::GetSupportedAlgorithms(size_t* algorithms_count) const {
96     *algorithms_count = array_length(supported_algorithms);
97     return supported_algorithms;
98 }
99 
GetOperationFactory(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose) const100 OperationFactory* PureSoftKeymasterContext::GetOperationFactory(keymaster_algorithm_t algorithm,
101                                                             keymaster_purpose_t purpose) const {
102     KeyFactory* key_factory = GetKeyFactory(algorithm);
103     if (!key_factory)
104         return nullptr;
105     return key_factory->GetOperationFactory(purpose);
106 }
107 
CreateKeyBlob(const AuthorizationSet & key_description,const keymaster_key_origin_t origin,const KeymasterKeyBlob & key_material,KeymasterKeyBlob * blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const108 keymaster_error_t PureSoftKeymasterContext::CreateKeyBlob(const AuthorizationSet& key_description,
109                                                           const keymaster_key_origin_t origin,
110                                                           const KeymasterKeyBlob& key_material,
111                                                           KeymasterKeyBlob* blob,
112                                                           AuthorizationSet* hw_enforced,
113                                                           AuthorizationSet* sw_enforced) const {
114     if (key_description.GetTagValue(TAG_ROLLBACK_RESISTANCE)) {
115         return KM_ERROR_ROLLBACK_RESISTANCE_UNAVAILABLE;
116     }
117 
118     if (GetSecurityLevel() != KM_SECURITY_LEVEL_SOFTWARE) {
119         // We're pretending to be some sort of secure hardware.  Put relevant tags in hw_enforced.
120         for (auto& entry : key_description) {
121             switch (entry.tag) {
122             case KM_TAG_PURPOSE:
123             case KM_TAG_ALGORITHM:
124             case KM_TAG_KEY_SIZE:
125             case KM_TAG_RSA_PUBLIC_EXPONENT:
126             case KM_TAG_BLOB_USAGE_REQUIREMENTS:
127             case KM_TAG_DIGEST:
128             case KM_TAG_PADDING:
129             case KM_TAG_BLOCK_MODE:
130             case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
131             case KM_TAG_MAX_USES_PER_BOOT:
132             case KM_TAG_USER_SECURE_ID:
133             case KM_TAG_NO_AUTH_REQUIRED:
134             case KM_TAG_AUTH_TIMEOUT:
135             case KM_TAG_CALLER_NONCE:
136             case KM_TAG_MIN_MAC_LENGTH:
137             case KM_TAG_KDF:
138             case KM_TAG_EC_CURVE:
139             case KM_TAG_ECIES_SINGLE_HASH_MODE:
140             case KM_TAG_USER_AUTH_TYPE:
141             case KM_TAG_ORIGIN:
142             case KM_TAG_OS_VERSION:
143             case KM_TAG_OS_PATCHLEVEL:
144             case KM_TAG_EARLY_BOOT_ONLY:
145             case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
146                 hw_enforced->push_back(entry);
147                 break;
148             default:
149                 break;
150             }
151         }
152     }
153 
154     keymaster_error_t error = SetKeyBlobAuthorizations(key_description, origin, os_version_,
155                                                        os_patchlevel_, hw_enforced, sw_enforced);
156     if (error != KM_ERROR_OK) return error;
157 
158     AuthorizationSet hidden;
159     error = BuildHiddenAuthorizations(key_description, &hidden, softwareRootOfTrust);
160     if (error != KM_ERROR_OK) return error;
161 
162     return SerializeIntegrityAssuredBlob(key_material, hidden, *hw_enforced, *sw_enforced, blob);
163 }
164 
UpgradeKeyBlob(const KeymasterKeyBlob & key_to_upgrade,const AuthorizationSet & upgrade_params,KeymasterKeyBlob * upgraded_key) const165 keymaster_error_t PureSoftKeymasterContext::UpgradeKeyBlob(const KeymasterKeyBlob& key_to_upgrade,
166                                                        const AuthorizationSet& upgrade_params,
167                                                        KeymasterKeyBlob* upgraded_key) const {
168     UniquePtr<Key> key;
169     keymaster_error_t error = ParseKeyBlob(key_to_upgrade, upgrade_params, &key);
170     if (error != KM_ERROR_OK)
171         return error;
172 
173     return UpgradeSoftKeyBlob(key, os_version_, os_patchlevel_, upgrade_params, upgraded_key);
174 }
175 
ParseKeyBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,UniquePtr<Key> * key) const176 keymaster_error_t PureSoftKeymasterContext::ParseKeyBlob(const KeymasterKeyBlob& blob,
177                                                          const AuthorizationSet& additional_params,
178                                                          UniquePtr<Key>* key) const {
179     // This is a little bit complicated.
180     //
181     // The SoftKeymasterContext has to handle a lot of different kinds of key blobs.
182     //
183     // 1.  New keymaster1 software key blobs.  These are integrity-assured but not encrypted.  The
184     //     raw key material and auth sets should be extracted and returned.  This is the kind
185     //     produced by this context when the KeyFactory doesn't use keymaster0 to back the keys.
186     //
187     // 2.  Old keymaster1 software key blobs.  These are OCB-encrypted with an all-zero master key.
188     //     They should be decrypted and the key material and auth sets extracted and returned.
189     //
190     // 3.  Old keymaster0 software key blobs.  These are raw key material with a small header tacked
191     //     on the front.  They don't have auth sets, so reasonable defaults are generated and
192     //     returned along with the raw key material.
193     //
194     // Determining what kind of blob has arrived is somewhat tricky.  What helps is that
195     // integrity-assured and OCB-encrypted blobs are self-consistent and effectively impossible to
196     // parse as anything else.  Old keymaster0 software key blobs have a header.  It's reasonably
197     // unlikely that hardware keys would have the same header.  So anything that is neither
198     // integrity-assured nor OCB-encrypted and lacks the old software key header is assumed to be
199     // keymaster0 hardware.
200 
201     AuthorizationSet hw_enforced;
202     AuthorizationSet sw_enforced;
203     KeymasterKeyBlob key_material;
204     keymaster_error_t error;
205 
206     auto constructKey = [&, this] () mutable -> keymaster_error_t {
207         // GetKeyFactory
208         if (error != KM_ERROR_OK) return error;
209         keymaster_algorithm_t algorithm;
210         if (!hw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm) &&
211             !sw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm)) {
212             return KM_ERROR_INVALID_ARGUMENT;
213         }
214         auto factory = GetKeyFactory(algorithm);
215         return factory->LoadKey(move(key_material), additional_params, move(hw_enforced),
216                                 move(sw_enforced), key);
217     };
218 
219     AuthorizationSet hidden;
220     error = BuildHiddenAuthorizations(additional_params, &hidden, softwareRootOfTrust);
221     if (error != KM_ERROR_OK)
222         return error;
223 
224     // Assume it's an integrity-assured blob (new software-only blob, or new keymaster0-backed
225     // blob).
226     error = DeserializeIntegrityAssuredBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
227     if (error != KM_ERROR_INVALID_KEY_BLOB)
228         return constructKey();
229 
230     // Wasn't an integrity-assured blob.  Maybe it's an OCB-encrypted blob.
231     error = ParseOcbAuthEncryptedBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
232     if (error == KM_ERROR_OK)
233         LOG_D("Parsed an old keymaster1 software key", 0);
234     if (error != KM_ERROR_INVALID_KEY_BLOB)
235         return constructKey();
236 
237     // Wasn't an OCB-encrypted blob.  Maybe it's an old softkeymaster blob.
238     error = ParseOldSoftkeymasterBlob(blob, &key_material, &hw_enforced, &sw_enforced);
239     if (error == KM_ERROR_OK)
240         LOG_D("Parsed an old sofkeymaster key", 0);
241 
242     return constructKey();
243 }
244 
DeleteKey(const KeymasterKeyBlob &) const245 keymaster_error_t PureSoftKeymasterContext::DeleteKey(const KeymasterKeyBlob& /* blob */) const {
246     // Nothing to do for software-only contexts.
247     return KM_ERROR_OK;
248 }
249 
DeleteAllKeys() const250 keymaster_error_t PureSoftKeymasterContext::DeleteAllKeys() const {
251     return KM_ERROR_OK;
252 }
253 
AddRngEntropy(const uint8_t * buf,size_t length) const254 keymaster_error_t PureSoftKeymasterContext::AddRngEntropy(const uint8_t* buf, size_t length) const {
255     // XXX TODO according to boringssl openssl/rand.h RAND_add is deprecated and does
256     // nothing
257     RAND_add(buf, length, 0 /* Don't assume any entropy is added to the pool. */);
258     return KM_ERROR_OK;
259 }
260 
GenerateAttestation(const Key & key,const AuthorizationSet & attest_params,CertChainPtr * cert_chain) const261 keymaster_error_t PureSoftKeymasterContext::GenerateAttestation(const Key& key,
262                                       const AuthorizationSet& attest_params,
263                                       CertChainPtr* cert_chain) const {
264 
265     keymaster_error_t error = KM_ERROR_OK;
266     keymaster_algorithm_t key_algorithm;
267     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
268         return KM_ERROR_UNKNOWN_ERROR;
269     }
270 
271     if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC))
272         return KM_ERROR_INCOMPATIBLE_ALGORITHM;
273 
274     // We have established that the given key has the correct algorithm, and because this is the
275     // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
276     const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
277 
278     auto attestation_chain = getAttestationChain(key_algorithm, &error);
279     if (error != KM_ERROR_OK) return error;
280 
281     auto attestation_key = getAttestationKey(key_algorithm, &error);
282     if (error != KM_ERROR_OK) return error;
283 
284     return generate_attestation(asymmetric_key, attest_params,
285             *attestation_chain, *attestation_key, *this, cert_chain);
286 }
287 
TranslateAuthorizationSetError(AuthorizationSet::Error err)288 static keymaster_error_t TranslateAuthorizationSetError(AuthorizationSet::Error err) {
289     switch (err) {
290     case AuthorizationSet::OK:
291         return KM_ERROR_OK;
292     case AuthorizationSet::ALLOCATION_FAILURE:
293         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
294     case AuthorizationSet::MALFORMED_DATA:
295         return KM_ERROR_UNKNOWN_ERROR;
296     }
297     return KM_ERROR_OK;
298 }
299 
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) const300 keymaster_error_t PureSoftKeymasterContext::UnwrapKey(
301     const KeymasterKeyBlob& wrapped_key_blob, const KeymasterKeyBlob& wrapping_key_blob,
302     const AuthorizationSet& /* wrapping_key_params */, const KeymasterKeyBlob& masking_key,
303     AuthorizationSet* wrapped_key_params, keymaster_key_format_t* wrapped_key_format,
304     KeymasterKeyBlob* wrapped_key_material) const {
305     keymaster_error_t error = KM_ERROR_OK;
306 
307     if (!wrapped_key_material) return KM_ERROR_UNEXPECTED_NULL_POINTER;
308 
309     // Parse wrapped key data
310     KeymasterBlob iv;
311     KeymasterKeyBlob transit_key;
312     KeymasterKeyBlob secure_key;
313     KeymasterBlob tag;
314     KeymasterBlob wrapped_key_description;
315     error = parse_wrapped_key(wrapped_key_blob, &iv, &transit_key, &secure_key, &tag,
316                               wrapped_key_params, wrapped_key_format, &wrapped_key_description);
317     if (error != KM_ERROR_OK) return error;
318 
319     UniquePtr<Key> key;
320     auto wrapping_key_params = AuthorizationSetBuilder()
321                                    .RsaEncryptionKey(2048, 65537)
322                                    .Digest(KM_DIGEST_SHA_2_256)
323                                    .Padding(KM_PAD_RSA_OAEP)
324                                    .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
325                                    .build();
326     error = ParseKeyBlob(wrapping_key_blob, wrapping_key_params, &key);
327     if (error != KM_ERROR_OK) return error;
328 
329     // Ensure the wrapping key has the right purpose
330     if (!key->hw_enforced().Contains(TAG_PURPOSE, KM_PURPOSE_WRAP) &&
331         !key->sw_enforced().Contains(TAG_PURPOSE, KM_PURPOSE_WRAP)) {
332         return KM_ERROR_INCOMPATIBLE_PURPOSE;
333     }
334 
335     auto operation_factory = GetOperationFactory(KM_ALGORITHM_RSA, KM_PURPOSE_DECRYPT);
336     if (!operation_factory) return KM_ERROR_UNKNOWN_ERROR;
337 
338     AuthorizationSet out_params;
339     OperationPtr operation(
340         operation_factory->CreateOperation(move(*key), wrapping_key_params, &error));
341     if (!operation.get()) return error;
342 
343     error = operation->Begin(wrapping_key_params, &out_params);
344     if (error != KM_ERROR_OK) return error;
345 
346     Buffer input;
347     Buffer output;
348     if (!input.Reinitialize(transit_key.key_material, transit_key.key_material_size)) {
349         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
350     }
351 
352     error = operation->Finish(wrapping_key_params, input, Buffer() /* signature */, &out_params,
353                               &output);
354     if (error != KM_ERROR_OK) return error;
355 
356     // decrypt the encrypted key material with the transit key
357     KeymasterKeyBlob key_material = {output.peek_read(), output.available_read()};
358 
359     // XOR the transit key with the masking key
360     if (key_material.key_material_size != masking_key.key_material_size) {
361         return KM_ERROR_INVALID_ARGUMENT;
362     }
363     for (size_t i = 0; i < key_material.key_material_size; i++) {
364         key_material.writable_data()[i] ^= masking_key.key_material[i];
365     }
366 
367     auto transit_key_authorizations = AuthorizationSetBuilder()
368                                           .AesEncryptionKey(256)
369                                           .Padding(KM_PAD_NONE)
370                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
371                                           .Authorization(TAG_NONCE, iv)
372                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)
373                                           .build();
374     if (transit_key_authorizations.is_valid() != AuthorizationSet::Error::OK) {
375         return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
376     }
377     auto gcm_params = AuthorizationSetBuilder()
378                           .Padding(KM_PAD_NONE)
379                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
380                           .Authorization(TAG_NONCE, iv)
381                           .Authorization(TAG_MAC_LENGTH, 128)
382                           .build();
383     if (gcm_params.is_valid() != AuthorizationSet::Error::OK) {
384         return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
385     }
386 
387     auto aes_factory = GetKeyFactory(KM_ALGORITHM_AES);
388     if (!aes_factory) return KM_ERROR_UNKNOWN_ERROR;
389 
390     UniquePtr<Key> aes_key;
391     error = aes_factory->LoadKey(move(key_material), gcm_params, move(transit_key_authorizations),
392                                  AuthorizationSet(), &aes_key);
393     if (error != KM_ERROR_OK) return error;
394 
395     auto aes_operation_factory = GetOperationFactory(KM_ALGORITHM_AES, KM_PURPOSE_DECRYPT);
396     if (!aes_operation_factory) return KM_ERROR_UNKNOWN_ERROR;
397 
398     OperationPtr aes_operation(
399         aes_operation_factory->CreateOperation(move(*aes_key), gcm_params, &error));
400     if (!aes_operation.get()) return error;
401 
402     error = aes_operation->Begin(gcm_params, &out_params);
403     if (error != KM_ERROR_OK) return error;
404 
405     size_t consumed = 0;
406     Buffer encrypted_key, plaintext;
407     if (!plaintext.Reinitialize(secure_key.key_material_size + tag.data_length)) {
408         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
409     }
410     if (!encrypted_key.Reinitialize(secure_key.key_material_size + tag.data_length)) {
411         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
412     }
413     if (!encrypted_key.write(secure_key.key_material, secure_key.key_material_size)) {
414         return KM_ERROR_UNKNOWN_ERROR;
415     }
416     if (!encrypted_key.write(tag.data, tag.data_length)) {
417         return KM_ERROR_UNKNOWN_ERROR;
418     }
419 
420     AuthorizationSet update_outparams;
421     auto update_params = AuthorizationSetBuilder()
422                              .Authorization(TAG_ASSOCIATED_DATA, wrapped_key_description.data,
423                                             wrapped_key_description.data_length)
424                              .build();
425     if (update_params.is_valid() != AuthorizationSet::Error::OK) {
426         return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
427     }
428 
429     error = aes_operation->Update(update_params, encrypted_key, &update_outparams, &plaintext,
430                                   &consumed);
431     if (error != KM_ERROR_OK) return error;
432 
433     AuthorizationSet finish_params, finish_out_params;
434     Buffer finish_input;
435     error = aes_operation->Finish(finish_params, finish_input, Buffer() /* signature */,
436                                   &finish_out_params, &plaintext);
437     if (error != KM_ERROR_OK) return error;
438 
439     *wrapped_key_material = {plaintext.peek_read(), plaintext.available_read()};
440     if (!wrapped_key_material->key_material && plaintext.peek_read()) {
441         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
442     }
443 
444     return error;
445 }
446 
GetVerifiedBootParams(keymaster_blob_t * verified_boot_key,keymaster_blob_t * verified_boot_hash,keymaster_verified_boot_t * verified_boot_state,bool * device_locked) const447 keymaster_error_t PureSoftKeymasterContext::GetVerifiedBootParams(
448     keymaster_blob_t* verified_boot_key, keymaster_blob_t* verified_boot_hash,
449     keymaster_verified_boot_t* verified_boot_state, bool* device_locked) const {
450     // TODO(swillden): See if there might be some sort of vbmeta data in goldfish/cuttlefish.
451     static std::string fake_vb_key(32, 0);
452     *verified_boot_key = {reinterpret_cast<uint8_t*>(fake_vb_key.data()), fake_vb_key.size()};
453     *verified_boot_hash = {reinterpret_cast<uint8_t*>(fake_vb_key.data()), fake_vb_key.size()};
454     *verified_boot_state = KM_VERIFIED_BOOT_UNVERIFIED;
455     *device_locked = false;
456     return KM_ERROR_OK;
457 }
458 
459 }  // namespace keymaster
460