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/soft_keymaster_context.h>
18 
19 #include <memory>
20 
21 #include <openssl/rand.h>
22 
23 #include <keymaster/android_keymaster_utils.h>
24 #include <keymaster/key_blob_utils/auth_encrypted_key_blob.h>
25 #include <keymaster/key_blob_utils/integrity_assured_key_blob.h>
26 #include <keymaster/key_blob_utils/ocb_utils.h>
27 #include <keymaster/key_blob_utils/software_keyblobs.h>
28 #include <keymaster/km_openssl/aes_key.h>
29 #include <keymaster/km_openssl/asymmetric_key.h>
30 #include <keymaster/km_openssl/attestation_utils.h>
31 #include <keymaster/km_openssl/certificate_utils.h>
32 #include <keymaster/km_openssl/hmac_key.h>
33 #include <keymaster/km_openssl/openssl_err.h>
34 #include <keymaster/km_openssl/triple_des_key.h>
35 #include <keymaster/legacy_support/ec_keymaster1_key.h>
36 #include <keymaster/legacy_support/rsa_keymaster1_key.h>
37 #include <keymaster/logger.h>
38 
39 #include <keymaster/contexts/soft_attestation_cert.h>
40 
41 using std::unique_ptr;
42 
43 namespace keymaster {
44 
45 namespace {
46 
string2Blob(const std::string & str)47 KeymasterBlob string2Blob(const std::string& str) {
48     return KeymasterBlob(reinterpret_cast<const uint8_t*>(str.data()), str.size());
49 }
50 
51 }  // anonymous namespace
52 
SoftKeymasterContext(KmVersion version,const std::string & root_of_trust)53 SoftKeymasterContext::SoftKeymasterContext(KmVersion version, const std::string& root_of_trust)
54     : SoftAttestationContext(version),  //
55       rsa_factory_(new (std::nothrow) RsaKeyFactory(*this /* blob_maker */, *this /* context */)),
56       ec_factory_(new (std::nothrow) EcKeyFactory(*this /* blob_maker */, *this /* context */)),
57       aes_factory_(new (std::nothrow)
58                        AesKeyFactory(*this /* blob_maker */, *this /* random_source */)),
59       tdes_factory_(new (std::nothrow)
60                         TripleDesKeyFactory(*this /* blob_maker */, *this /* random_source */)),
61       hmac_factory_(new (std::nothrow)
62                         HmacKeyFactory(*this /* blob_maker */, *this /* random_source */)),
63       km1_dev_(nullptr), root_of_trust_(string2Blob(root_of_trust)), os_version_(0),
64       os_patchlevel_(0) {}
65 
~SoftKeymasterContext()66 SoftKeymasterContext::~SoftKeymasterContext() {}
67 
SetHardwareDevice(keymaster1_device_t * keymaster1_device)68 keymaster_error_t SoftKeymasterContext::SetHardwareDevice(keymaster1_device_t* keymaster1_device) {
69     if (!keymaster1_device) return KM_ERROR_UNEXPECTED_NULL_POINTER;
70 
71     km1_dev_ = keymaster1_device;
72 
73     km1_engine_.reset(new (std::nothrow) Keymaster1Engine(keymaster1_device));
74     rsa_factory_.reset(new (std::nothrow) RsaKeymaster1KeyFactory(
75         *this /* blob_maker */, *this /* attestation_context */, km1_engine_.get()));
76     ec_factory_.reset(new (std::nothrow) EcdsaKeymaster1KeyFactory(
77         *this /* blob_maker */, *this /* attestation_context */, km1_engine_.get()));
78 
79     // Use default HMAC and AES key factories. Higher layers will pass HMAC/AES keys/ops that are
80     // supported by the hardware to it and other ones to the software-only factory.
81 
82     return KM_ERROR_OK;
83 }
84 
SetSystemVersion(uint32_t os_version,uint32_t os_patchlevel)85 keymaster_error_t SoftKeymasterContext::SetSystemVersion(uint32_t os_version,
86                                                          uint32_t os_patchlevel) {
87     os_version_ = os_version;
88     os_patchlevel_ = os_patchlevel;
89     return KM_ERROR_OK;
90 }
91 
GetSystemVersion(uint32_t * os_version,uint32_t * os_patchlevel) const92 void SoftKeymasterContext::GetSystemVersion(uint32_t* os_version, uint32_t* os_patchlevel) const {
93     *os_version = os_version_;
94     *os_patchlevel = os_patchlevel_;
95 }
96 
GetKeyFactory(keymaster_algorithm_t algorithm) const97 KeyFactory* SoftKeymasterContext::GetKeyFactory(keymaster_algorithm_t algorithm) const {
98     switch (algorithm) {
99     case KM_ALGORITHM_RSA:
100         return rsa_factory_.get();
101     case KM_ALGORITHM_EC:
102         return ec_factory_.get();
103     case KM_ALGORITHM_AES:
104         return aes_factory_.get();
105     case KM_ALGORITHM_TRIPLE_DES:
106         return tdes_factory_.get();
107     case KM_ALGORITHM_HMAC:
108         return hmac_factory_.get();
109     default:
110         return nullptr;
111     }
112 }
113 
114 static keymaster_algorithm_t supported_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC,
115                                                        KM_ALGORITHM_AES, KM_ALGORITHM_HMAC};
116 
117 keymaster_algorithm_t*
GetSupportedAlgorithms(size_t * algorithms_count) const118 SoftKeymasterContext::GetSupportedAlgorithms(size_t* algorithms_count) const {
119     *algorithms_count = array_length(supported_algorithms);
120     return supported_algorithms;
121 }
122 
GetOperationFactory(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose) const123 OperationFactory* SoftKeymasterContext::GetOperationFactory(keymaster_algorithm_t algorithm,
124                                                             keymaster_purpose_t purpose) const {
125     KeyFactory* key_factory = GetKeyFactory(algorithm);
126     if (!key_factory) return nullptr;
127     return key_factory->GetOperationFactory(purpose);
128 }
129 
TranslateAuthorizationSetError(AuthorizationSet::Error err)130 static keymaster_error_t TranslateAuthorizationSetError(AuthorizationSet::Error err) {
131     switch (err) {
132     case AuthorizationSet::OK:
133         return KM_ERROR_OK;
134     case AuthorizationSet::ALLOCATION_FAILURE:
135         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
136     case AuthorizationSet::MALFORMED_DATA:
137         return KM_ERROR_UNKNOWN_ERROR;
138     }
139     return KM_ERROR_OK;
140 }
141 
SetAuthorizations(const AuthorizationSet & key_description,keymaster_key_origin_t origin,uint32_t os_version,uint32_t os_patchlevel,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced)142 static keymaster_error_t SetAuthorizations(const AuthorizationSet& key_description,
143                                            keymaster_key_origin_t origin, uint32_t os_version,
144                                            uint32_t os_patchlevel, AuthorizationSet* hw_enforced,
145                                            AuthorizationSet* sw_enforced) {
146     sw_enforced->Clear();
147 
148     for (auto& entry : key_description) {
149         switch (entry.tag) {
150         // These cannot be specified by the client.
151         case KM_TAG_ROOT_OF_TRUST:
152         case KM_TAG_ORIGIN:
153             LOG_E("Root of trust and origin tags may not be specified");
154             return KM_ERROR_INVALID_TAG;
155 
156         // These don't work.
157         case KM_TAG_ROLLBACK_RESISTANT:
158             LOG_E("KM_TAG_ROLLBACK_RESISTANT not supported");
159             return KM_ERROR_UNSUPPORTED_TAG;
160 
161         // These are hidden.
162         case KM_TAG_APPLICATION_ID:
163         case KM_TAG_APPLICATION_DATA:
164             break;
165 
166         // Everything else we just copy into sw_enforced, unless the KeyFactory has placed it in
167         // hw_enforced, in which case we defer to its decision.
168         default:
169             if (hw_enforced->GetTagCount(entry.tag) == 0) sw_enforced->push_back(entry);
170             break;
171         }
172     }
173 
174     sw_enforced->push_back(TAG_CREATION_DATETIME, java_time(time(nullptr)));
175     sw_enforced->push_back(TAG_ORIGIN, origin);
176     sw_enforced->push_back(TAG_OS_VERSION, os_version);
177     sw_enforced->push_back(TAG_OS_PATCHLEVEL, os_patchlevel);
178 
179     return TranslateAuthorizationSetError(sw_enforced->is_valid());
180 }
181 
CreateKeyBlob(const AuthorizationSet & key_description,const keymaster_key_origin_t origin,const KeymasterKeyBlob & key_material,KeymasterKeyBlob * blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const182 keymaster_error_t SoftKeymasterContext::CreateKeyBlob(const AuthorizationSet& key_description,
183                                                       const keymaster_key_origin_t origin,
184                                                       const KeymasterKeyBlob& key_material,
185                                                       KeymasterKeyBlob* blob,
186                                                       AuthorizationSet* hw_enforced,
187                                                       AuthorizationSet* sw_enforced) const {
188     keymaster_error_t error = SetAuthorizations(key_description, origin, os_version_,
189                                                 os_patchlevel_, hw_enforced, sw_enforced);
190     if (error != KM_ERROR_OK) return error;
191 
192     AuthorizationSet hidden;
193     error = BuildHiddenAuthorizations(key_description, &hidden, root_of_trust_);
194     if (error != KM_ERROR_OK) return error;
195 
196     return SerializeIntegrityAssuredBlob(key_material, hidden, *hw_enforced, *sw_enforced, blob);
197 }
198 
UpgradeKeyBlob(const KeymasterKeyBlob & key_to_upgrade,const AuthorizationSet & upgrade_params,KeymasterKeyBlob * upgraded_key) const199 keymaster_error_t SoftKeymasterContext::UpgradeKeyBlob(const KeymasterKeyBlob& key_to_upgrade,
200                                                        const AuthorizationSet& upgrade_params,
201                                                        KeymasterKeyBlob* upgraded_key) const {
202     UniquePtr<Key> key;
203     keymaster_error_t error = ParseKeyBlob(key_to_upgrade, upgrade_params, &key);
204     if (error != KM_ERROR_OK) return error;
205 
206     // Three cases here:
207     //
208     // 1. Software key blob.  Version info, if present, is in sw_enforced.  If not present, we
209     //    should add it.
210     //
211     // 2. Keymaster0 hardware key blob.  Version info, if present, is in sw_enforced.  If not
212     //    present we should add it.
213     //
214     // 3. Keymaster1 hardware key blob.  Version info is not present and we shouldn't have been
215     //    asked to upgrade.
216 
217     // Handle case 3.
218     if (km1_dev_ && key->hw_enforced().Contains(TAG_PURPOSE) &&
219         !key->hw_enforced().Contains(TAG_OS_PATCHLEVEL))
220         return KM_ERROR_INVALID_ARGUMENT;
221 
222     // Handle case 1 and 2
223     return UpgradeSoftKeyBlob(key, os_version_, os_patchlevel_, upgrade_params, upgraded_key);
224 }
225 
ParseKeyBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,UniquePtr<Key> * key) const226 keymaster_error_t SoftKeymasterContext::ParseKeyBlob(const KeymasterKeyBlob& blob,
227                                                      const AuthorizationSet& additional_params,
228                                                      UniquePtr<Key>* key) const {
229     // This is a little bit complicated.
230     //
231     // The SoftKeymasterContext has to handle a lot of different kinds of key blobs.
232     //
233     // 1.  New keymaster1 software key blobs.  These are integrity-assured but not encrypted.  The
234     //     raw key material and auth sets should be extracted and returned.  This is the kind
235     //     produced by this context when the KeyFactory doesn't use keymaster0 to back the keys.
236     //
237     // 2.  Old keymaster1 software key blobs.  These are OCB-encrypted with an all-zero master key.
238     //     They should be decrypted and the key material and auth sets extracted and returned.
239     //
240     // 3.  Old keymaster0 software key blobs.  These are raw key material with a small header tacked
241     //     on the front.  They don't have auth sets, so reasonable defaults are generated and
242     //     returned along with the raw key material.
243     //
244     // 4.  New keymaster0 hardware key blobs.  These are integrity-assured but not encrypted (though
245     //     they're protected by the keymaster0 hardware implementation).  The keymaster0 key blob
246     //     and auth sets should be extracted and returned.
247     //
248     // 5.  Keymaster1 hardware key blobs.  These are raw hardware key blobs.  They contain auth
249     //     sets, which we retrieve from the hardware module.
250     //
251     // 6.  Old keymaster0 hardware key blobs.  These are raw hardware key blobs.  They don't have
252     //     auth sets so reasonable defaults are generated and returned along with the key blob.
253     //
254     // Determining what kind of blob has arrived is somewhat tricky.  What helps is that
255     // integrity-assured and OCB-encrypted blobs are self-consistent and effectively impossible to
256     // parse as anything else.  Old keymaster0 software key blobs have a header.  It's reasonably
257     // unlikely that hardware keys would have the same header.  So anything that is neither
258     // integrity-assured nor OCB-encrypted and lacks the old software key header is assumed to be
259     // keymaster0 hardware.
260 
261     AuthorizationSet hw_enforced;
262     AuthorizationSet sw_enforced;
263     KeymasterKeyBlob key_material;
264     AuthorizationSet hidden;
265     keymaster_error_t error;
266 
267     auto constructKey = [&, this]() mutable -> keymaster_error_t {
268         // GetKeyFactory
269         if (error != KM_ERROR_OK) return error;
270         keymaster_algorithm_t algorithm;
271         if (!hw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm) &&
272             !sw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm)) {
273             return KM_ERROR_INVALID_ARGUMENT;
274         }
275         auto factory = GetKeyFactory(algorithm);
276         return factory->LoadKey(std::move(key_material), additional_params, std::move(hw_enforced),
277                                 std::move(sw_enforced), key);
278     };
279 
280     error = BuildHiddenAuthorizations(additional_params, &hidden, root_of_trust_);
281     if (error != KM_ERROR_OK) return error;
282 
283     // Assume it's an integrity-assured blob (new software-only blob, or new keymaster0-backed
284     // blob).
285     error =
286         DeserializeIntegrityAssuredBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
287     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
288 
289     // Wasn't an integrity-assured blob.  Maybe it's an Auth-encrypted blob.
290     error = ParseAuthEncryptedBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
291     if (error == KM_ERROR_OK) LOG_D("Parsed an old keymaster1 software key");
292     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
293 
294     // Wasn't an OCB-encrypted blob.  Maybe it's an old softkeymaster blob.
295     error = ParseOldSoftkeymasterBlob(blob, &key_material, &hw_enforced, &sw_enforced);
296     if (error == KM_ERROR_OK) LOG_D("Parsed an old sofkeymaster key");
297     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
298 
299     if (km1_dev_) {
300         error = ParseKeymaster1HwBlob(blob, additional_params, &key_material, &hw_enforced,
301                                       &sw_enforced);
302     } else {
303         return KM_ERROR_INVALID_KEY_BLOB;
304     }
305     return constructKey();
306 }
307 
DeleteKey(const KeymasterKeyBlob & blob) const308 keymaster_error_t SoftKeymasterContext::DeleteKey(const KeymasterKeyBlob& blob) const {
309     if (km1_engine_) {
310         // HACK. Due to a bug with Qualcomm's Keymaster implementation, which causes the device to
311         // reboot if we pass it a key blob it doesn't understand, we need to check for software
312         // keys.  If it looks like a software key there's nothing to do so we just return.
313         KeymasterKeyBlob key_material;
314         AuthorizationSet hw_enforced, sw_enforced;
315         keymaster_error_t error = DeserializeIntegrityAssuredBlob_NoHmacCheck(
316             blob, &key_material, &hw_enforced, &sw_enforced);
317         if (error == KM_ERROR_OK) {
318             return KM_ERROR_OK;
319         }
320 
321         return km1_engine_->DeleteKey(blob);
322     }
323 
324     // Nothing to do for software-only contexts.
325     return KM_ERROR_OK;
326 }
327 
DeleteAllKeys() const328 keymaster_error_t SoftKeymasterContext::DeleteAllKeys() const {
329     if (km1_engine_) return km1_engine_->DeleteAllKeys();
330     return KM_ERROR_OK;
331 }
332 
AddRngEntropy(const uint8_t * buf,size_t length) const333 keymaster_error_t SoftKeymasterContext::AddRngEntropy(const uint8_t* buf, size_t length) const {
334     RAND_add(buf, length, 0 /* Don't assume any entropy is added to the pool. */);
335     return KM_ERROR_OK;
336 }
337 
ParseKeymaster1HwBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,KeymasterKeyBlob * key_material,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const338 keymaster_error_t SoftKeymasterContext::ParseKeymaster1HwBlob(
339     const KeymasterKeyBlob& blob, const AuthorizationSet& additional_params,
340     KeymasterKeyBlob* key_material, AuthorizationSet* hw_enforced,
341     AuthorizationSet* sw_enforced) const {
342     assert(km1_dev_);
343 
344     keymaster_blob_t client_id = {nullptr, 0};
345     keymaster_blob_t app_data = {nullptr, 0};
346     keymaster_blob_t* client_id_ptr = nullptr;
347     keymaster_blob_t* app_data_ptr = nullptr;
348     if (additional_params.GetTagValue(TAG_APPLICATION_ID, &client_id)) client_id_ptr = &client_id;
349     if (additional_params.GetTagValue(TAG_APPLICATION_DATA, &app_data)) app_data_ptr = &app_data;
350 
351     // Get key characteristics, which incidentally verifies that the HW recognizes the key.
352     keymaster_key_characteristics_t* characteristics;
353     keymaster_error_t error = km1_dev_->get_key_characteristics(km1_dev_, &blob, client_id_ptr,
354                                                                 app_data_ptr, &characteristics);
355     if (error != KM_ERROR_OK) return error;
356     unique_ptr<keymaster_key_characteristics_t, Characteristics_Delete> characteristics_deleter(
357         characteristics);
358 
359     LOG_D("Module \"%s\" accepted key", km1_dev_->common.module->name);
360 
361     hw_enforced->Reinitialize(characteristics->hw_enforced);
362     sw_enforced->Reinitialize(characteristics->sw_enforced);
363     *key_material = blob;
364     return KM_ERROR_OK;
365 }
366 
367 CertificateChain
GenerateAttestation(const Key & key,const AuthorizationSet & attest_params,UniquePtr<Key>,const KeymasterBlob &,keymaster_error_t * error) const368 SoftKeymasterContext::GenerateAttestation(const Key& key,  //
369                                           const AuthorizationSet& attest_params,
370                                           UniquePtr<Key> /* attest_key */,
371                                           const KeymasterBlob& /* issuer_subject */,  //
372                                           keymaster_error_t* error) const {
373     keymaster_algorithm_t key_algorithm;
374     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
375         *error = KM_ERROR_UNKNOWN_ERROR;
376         return {};
377     }
378 
379     if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC)) {
380         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
381         return {};
382     }
383 
384     // We have established that the given key has the correct algorithm, and because this is the
385     // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
386     const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
387 
388     return generate_attestation(asymmetric_key, attest_params, {} /* attest_key */, *this, error);
389 }
390 
GenerateSelfSignedCertificate(const Key & key,const AuthorizationSet & cert_params,bool fake_signature,keymaster_error_t * error) const391 CertificateChain SoftKeymasterContext::GenerateSelfSignedCertificate(
392     const Key& key, const AuthorizationSet& cert_params, bool fake_signature,
393     keymaster_error_t* error) const {
394     keymaster_algorithm_t key_algorithm;
395     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
396         *error = KM_ERROR_UNKNOWN_ERROR;
397         return {};
398     }
399 
400     if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC)) {
401         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
402         return {};
403     }
404 
405     // We have established that the given key has the correct algorithm, and because this is the
406     // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
407     const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
408 
409     return generate_self_signed_cert(asymmetric_key, cert_params, fake_signature, error);
410 }
411 
UnwrapKey(const KeymasterKeyBlob &,const KeymasterKeyBlob &,const AuthorizationSet &,const KeymasterKeyBlob &,AuthorizationSet *,keymaster_key_format_t *,KeymasterKeyBlob *) const412 keymaster_error_t SoftKeymasterContext::UnwrapKey(const KeymasterKeyBlob&, const KeymasterKeyBlob&,
413                                                   const AuthorizationSet&, const KeymasterKeyBlob&,
414                                                   AuthorizationSet*, keymaster_key_format_t*,
415                                                   KeymasterKeyBlob*) const {
416     return KM_ERROR_UNIMPLEMENTED;
417 }
418 
419 }  // namespace keymaster
420