• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <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 RsaKeyFactory(*this /* blob_maker */, *this /* context */)),
56       ec_factory_(new EcKeyFactory(*this /* blob_maker */, *this /* context */)),
57       aes_factory_(new AesKeyFactory(*this /* blob_maker */, *this /* random_source */)),
58       tdes_factory_(new TripleDesKeyFactory(*this /* blob_maker */, *this /* random_source */)),
59       hmac_factory_(new HmacKeyFactory(*this /* blob_maker */, *this /* random_source */)),
60       km1_dev_(nullptr), root_of_trust_(string2Blob(root_of_trust)), os_version_(0),
61       os_patchlevel_(0) {}
62 
~SoftKeymasterContext()63 SoftKeymasterContext::~SoftKeymasterContext() {}
64 
SetHardwareDevice(keymaster1_device_t * keymaster1_device)65 keymaster_error_t SoftKeymasterContext::SetHardwareDevice(keymaster1_device_t* keymaster1_device) {
66     if (!keymaster1_device) return KM_ERROR_UNEXPECTED_NULL_POINTER;
67 
68     km1_dev_ = keymaster1_device;
69 
70     km1_engine_.reset(new Keymaster1Engine(keymaster1_device));
71     rsa_factory_.reset(new RsaKeymaster1KeyFactory(
72         *this /* blob_maker */, *this /* attestation_context */, km1_engine_.get()));
73     ec_factory_.reset(new EcdsaKeymaster1KeyFactory(
74         *this /* blob_maker */, *this /* attestation_context */, km1_engine_.get()));
75 
76     // Use default HMAC and AES key factories. Higher layers will pass HMAC/AES keys/ops that are
77     // supported by the hardware to it and other ones to the software-only factory.
78 
79     return KM_ERROR_OK;
80 }
81 
SetSystemVersion(uint32_t os_version,uint32_t os_patchlevel)82 keymaster_error_t SoftKeymasterContext::SetSystemVersion(uint32_t os_version,
83                                                          uint32_t os_patchlevel) {
84     os_version_ = os_version;
85     os_patchlevel_ = os_patchlevel;
86     return KM_ERROR_OK;
87 }
88 
GetSystemVersion(uint32_t * os_version,uint32_t * os_patchlevel) const89 void SoftKeymasterContext::GetSystemVersion(uint32_t* os_version, uint32_t* os_patchlevel) const {
90     *os_version = os_version_;
91     *os_patchlevel = os_patchlevel_;
92 }
93 
GetKeyFactory(keymaster_algorithm_t algorithm) const94 KeyFactory* SoftKeymasterContext::GetKeyFactory(keymaster_algorithm_t algorithm) const {
95     switch (algorithm) {
96     case KM_ALGORITHM_RSA:
97         return rsa_factory_.get();
98     case KM_ALGORITHM_EC:
99         return ec_factory_.get();
100     case KM_ALGORITHM_AES:
101         return aes_factory_.get();
102     case KM_ALGORITHM_TRIPLE_DES:
103         return tdes_factory_.get();
104     case KM_ALGORITHM_HMAC:
105         return hmac_factory_.get();
106     default:
107         return nullptr;
108     }
109 }
110 
111 static keymaster_algorithm_t supported_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC,
112                                                        KM_ALGORITHM_AES, KM_ALGORITHM_HMAC};
113 
114 keymaster_algorithm_t*
GetSupportedAlgorithms(size_t * algorithms_count) const115 SoftKeymasterContext::GetSupportedAlgorithms(size_t* algorithms_count) const {
116     *algorithms_count = array_length(supported_algorithms);
117     return supported_algorithms;
118 }
119 
GetOperationFactory(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose) const120 OperationFactory* SoftKeymasterContext::GetOperationFactory(keymaster_algorithm_t algorithm,
121                                                             keymaster_purpose_t purpose) const {
122     KeyFactory* key_factory = GetKeyFactory(algorithm);
123     if (!key_factory) return nullptr;
124     return key_factory->GetOperationFactory(purpose);
125 }
126 
TranslateAuthorizationSetError(AuthorizationSet::Error err)127 static keymaster_error_t TranslateAuthorizationSetError(AuthorizationSet::Error err) {
128     switch (err) {
129     case AuthorizationSet::OK:
130         return KM_ERROR_OK;
131     case AuthorizationSet::ALLOCATION_FAILURE:
132         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
133     case AuthorizationSet::MALFORMED_DATA:
134         return KM_ERROR_UNKNOWN_ERROR;
135     }
136     return KM_ERROR_OK;
137 }
138 
SetAuthorizations(const AuthorizationSet & key_description,keymaster_key_origin_t origin,uint32_t os_version,uint32_t os_patchlevel,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced)139 static keymaster_error_t SetAuthorizations(const AuthorizationSet& key_description,
140                                            keymaster_key_origin_t origin, uint32_t os_version,
141                                            uint32_t os_patchlevel, AuthorizationSet* hw_enforced,
142                                            AuthorizationSet* sw_enforced) {
143     sw_enforced->Clear();
144 
145     for (auto& entry : key_description) {
146         switch (entry.tag) {
147         // These cannot be specified by the client.
148         case KM_TAG_ROOT_OF_TRUST:
149         case KM_TAG_ORIGIN:
150             LOG_E("Root of trust and origin tags may not be specified", 0);
151             return KM_ERROR_INVALID_TAG;
152 
153         // These don't work.
154         case KM_TAG_ROLLBACK_RESISTANT:
155             LOG_E("KM_TAG_ROLLBACK_RESISTANT not supported", 0);
156             return KM_ERROR_UNSUPPORTED_TAG;
157 
158         // These are hidden.
159         case KM_TAG_APPLICATION_ID:
160         case KM_TAG_APPLICATION_DATA:
161             break;
162 
163         // Everything else we just copy into sw_enforced, unless the KeyFactory has placed it in
164         // hw_enforced, in which case we defer to its decision.
165         default:
166             if (hw_enforced->GetTagCount(entry.tag) == 0) sw_enforced->push_back(entry);
167             break;
168         }
169     }
170 
171     sw_enforced->push_back(TAG_CREATION_DATETIME, java_time(time(nullptr)));
172     sw_enforced->push_back(TAG_ORIGIN, origin);
173     sw_enforced->push_back(TAG_OS_VERSION, os_version);
174     sw_enforced->push_back(TAG_OS_PATCHLEVEL, os_patchlevel);
175 
176     return TranslateAuthorizationSetError(sw_enforced->is_valid());
177 }
178 
CreateKeyBlob(const AuthorizationSet & key_description,const keymaster_key_origin_t origin,const KeymasterKeyBlob & key_material,KeymasterKeyBlob * blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const179 keymaster_error_t SoftKeymasterContext::CreateKeyBlob(const AuthorizationSet& key_description,
180                                                       const keymaster_key_origin_t origin,
181                                                       const KeymasterKeyBlob& key_material,
182                                                       KeymasterKeyBlob* blob,
183                                                       AuthorizationSet* hw_enforced,
184                                                       AuthorizationSet* sw_enforced) const {
185     keymaster_error_t error = SetAuthorizations(key_description, origin, os_version_,
186                                                 os_patchlevel_, hw_enforced, sw_enforced);
187     if (error != KM_ERROR_OK) return error;
188 
189     AuthorizationSet hidden;
190     error = BuildHiddenAuthorizations(key_description, &hidden, root_of_trust_);
191     if (error != KM_ERROR_OK) return error;
192 
193     return SerializeIntegrityAssuredBlob(key_material, hidden, *hw_enforced, *sw_enforced, blob);
194 }
195 
UpgradeKeyBlob(const KeymasterKeyBlob & key_to_upgrade,const AuthorizationSet & upgrade_params,KeymasterKeyBlob * upgraded_key) const196 keymaster_error_t SoftKeymasterContext::UpgradeKeyBlob(const KeymasterKeyBlob& key_to_upgrade,
197                                                        const AuthorizationSet& upgrade_params,
198                                                        KeymasterKeyBlob* upgraded_key) const {
199     UniquePtr<Key> key;
200     keymaster_error_t error = ParseKeyBlob(key_to_upgrade, upgrade_params, &key);
201     if (error != KM_ERROR_OK) return error;
202 
203     // Three cases here:
204     //
205     // 1. Software key blob.  Version info, if present, is in sw_enforced.  If not present, we
206     //    should add it.
207     //
208     // 2. Keymaster0 hardware key blob.  Version info, if present, is in sw_enforced.  If not
209     //    present we should add it.
210     //
211     // 3. Keymaster1 hardware key blob.  Version info is not present and we shouldn't have been
212     //    asked to upgrade.
213 
214     // Handle case 3.
215     if (km1_dev_ && key->hw_enforced().Contains(TAG_PURPOSE) &&
216         !key->hw_enforced().Contains(TAG_OS_PATCHLEVEL))
217         return KM_ERROR_INVALID_ARGUMENT;
218 
219     // Handle case 1 and 2
220     return UpgradeSoftKeyBlob(key, os_version_, os_patchlevel_, upgrade_params, upgraded_key);
221 }
222 
ParseKeyBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,UniquePtr<Key> * key) const223 keymaster_error_t SoftKeymasterContext::ParseKeyBlob(const KeymasterKeyBlob& blob,
224                                                      const AuthorizationSet& additional_params,
225                                                      UniquePtr<Key>* key) const {
226     // This is a little bit complicated.
227     //
228     // The SoftKeymasterContext has to handle a lot of different kinds of key blobs.
229     //
230     // 1.  New keymaster1 software key blobs.  These are integrity-assured but not encrypted.  The
231     //     raw key material and auth sets should be extracted and returned.  This is the kind
232     //     produced by this context when the KeyFactory doesn't use keymaster0 to back the keys.
233     //
234     // 2.  Old keymaster1 software key blobs.  These are OCB-encrypted with an all-zero master key.
235     //     They should be decrypted and the key material and auth sets extracted and returned.
236     //
237     // 3.  Old keymaster0 software key blobs.  These are raw key material with a small header tacked
238     //     on the front.  They don't have auth sets, so reasonable defaults are generated and
239     //     returned along with the raw key material.
240     //
241     // 4.  New keymaster0 hardware key blobs.  These are integrity-assured but not encrypted (though
242     //     they're protected by the keymaster0 hardware implementation).  The keymaster0 key blob
243     //     and auth sets should be extracted and returned.
244     //
245     // 5.  Keymaster1 hardware key blobs.  These are raw hardware key blobs.  They contain auth
246     //     sets, which we retrieve from the hardware module.
247     //
248     // 6.  Old keymaster0 hardware key blobs.  These are raw hardware key blobs.  They don't have
249     //     auth sets so reasonable defaults are generated and returned along with the key blob.
250     //
251     // Determining what kind of blob has arrived is somewhat tricky.  What helps is that
252     // integrity-assured and OCB-encrypted blobs are self-consistent and effectively impossible to
253     // parse as anything else.  Old keymaster0 software key blobs have a header.  It's reasonably
254     // unlikely that hardware keys would have the same header.  So anything that is neither
255     // integrity-assured nor OCB-encrypted and lacks the old software key header is assumed to be
256     // keymaster0 hardware.
257 
258     AuthorizationSet hw_enforced;
259     AuthorizationSet sw_enforced;
260     KeymasterKeyBlob key_material;
261     AuthorizationSet hidden;
262     keymaster_error_t error;
263 
264     auto constructKey = [&, this]() mutable -> keymaster_error_t {
265         // GetKeyFactory
266         if (error != KM_ERROR_OK) return error;
267         keymaster_algorithm_t algorithm;
268         if (!hw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm) &&
269             !sw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm)) {
270             return KM_ERROR_INVALID_ARGUMENT;
271         }
272         auto factory = GetKeyFactory(algorithm);
273         return factory->LoadKey(move(key_material), additional_params, move(hw_enforced),
274                                 move(sw_enforced), key);
275     };
276 
277     error = BuildHiddenAuthorizations(additional_params, &hidden, root_of_trust_);
278     if (error != KM_ERROR_OK) return error;
279 
280     // Assume it's an integrity-assured blob (new software-only blob, or new keymaster0-backed
281     // blob).
282     error =
283         DeserializeIntegrityAssuredBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
284     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
285 
286     // Wasn't an integrity-assured blob.  Maybe it's an Auth-encrypted blob.
287     error = ParseAuthEncryptedBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
288     if (error == KM_ERROR_OK) LOG_D("Parsed an old keymaster1 software key", 0);
289     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
290 
291     // Wasn't an OCB-encrypted blob.  Maybe it's an old softkeymaster blob.
292     error = ParseOldSoftkeymasterBlob(blob, &key_material, &hw_enforced, &sw_enforced);
293     if (error == KM_ERROR_OK) LOG_D("Parsed an old sofkeymaster key", 0);
294     if (error != KM_ERROR_INVALID_KEY_BLOB) return constructKey();
295 
296     if (km1_dev_) {
297         error = ParseKeymaster1HwBlob(blob, additional_params, &key_material, &hw_enforced,
298                                       &sw_enforced);
299     } else {
300         return KM_ERROR_INVALID_KEY_BLOB;
301     }
302     return constructKey();
303 }
304 
DeleteKey(const KeymasterKeyBlob & blob) const305 keymaster_error_t SoftKeymasterContext::DeleteKey(const KeymasterKeyBlob& blob) const {
306     if (km1_engine_) {
307         // HACK. Due to a bug with Qualcomm's Keymaster implementation, which causes the device to
308         // reboot if we pass it a key blob it doesn't understand, we need to check for software
309         // keys.  If it looks like a software key there's nothing to do so we just return.
310         KeymasterKeyBlob key_material;
311         AuthorizationSet hw_enforced, sw_enforced;
312         keymaster_error_t error = DeserializeIntegrityAssuredBlob_NoHmacCheck(
313             blob, &key_material, &hw_enforced, &sw_enforced);
314         if (error == KM_ERROR_OK) {
315             return KM_ERROR_OK;
316         }
317 
318         return km1_engine_->DeleteKey(blob);
319     }
320 
321     // Nothing to do for software-only contexts.
322     return KM_ERROR_OK;
323 }
324 
DeleteAllKeys() const325 keymaster_error_t SoftKeymasterContext::DeleteAllKeys() const {
326     if (km1_engine_) return km1_engine_->DeleteAllKeys();
327     return KM_ERROR_OK;
328 }
329 
AddRngEntropy(const uint8_t * buf,size_t length) const330 keymaster_error_t SoftKeymasterContext::AddRngEntropy(const uint8_t* buf, size_t length) const {
331     RAND_add(buf, length, 0 /* Don't assume any entropy is added to the pool. */);
332     return KM_ERROR_OK;
333 }
334 
ParseKeymaster1HwBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,KeymasterKeyBlob * key_material,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const335 keymaster_error_t SoftKeymasterContext::ParseKeymaster1HwBlob(
336     const KeymasterKeyBlob& blob, const AuthorizationSet& additional_params,
337     KeymasterKeyBlob* key_material, AuthorizationSet* hw_enforced,
338     AuthorizationSet* sw_enforced) const {
339     assert(km1_dev_);
340 
341     keymaster_blob_t client_id = {nullptr, 0};
342     keymaster_blob_t app_data = {nullptr, 0};
343     keymaster_blob_t* client_id_ptr = nullptr;
344     keymaster_blob_t* app_data_ptr = nullptr;
345     if (additional_params.GetTagValue(TAG_APPLICATION_ID, &client_id)) client_id_ptr = &client_id;
346     if (additional_params.GetTagValue(TAG_APPLICATION_DATA, &app_data)) app_data_ptr = &app_data;
347 
348     // Get key characteristics, which incidentally verifies that the HW recognizes the key.
349     keymaster_key_characteristics_t* characteristics;
350     keymaster_error_t error = km1_dev_->get_key_characteristics(km1_dev_, &blob, client_id_ptr,
351                                                                 app_data_ptr, &characteristics);
352     if (error != KM_ERROR_OK) return error;
353     unique_ptr<keymaster_key_characteristics_t, Characteristics_Delete> characteristics_deleter(
354         characteristics);
355 
356     LOG_D("Module \"%s\" accepted key", km1_dev_->common.module->name);
357 
358     hw_enforced->Reinitialize(characteristics->hw_enforced);
359     sw_enforced->Reinitialize(characteristics->sw_enforced);
360     *key_material = blob;
361     return KM_ERROR_OK;
362 }
363 
364 CertificateChain
GenerateAttestation(const Key & key,const AuthorizationSet & attest_params,UniquePtr<Key>,const KeymasterBlob &,keymaster_error_t * error) const365 SoftKeymasterContext::GenerateAttestation(const Key& key,  //
366                                           const AuthorizationSet& attest_params,
367                                           UniquePtr<Key> /* attest_key */,
368                                           const KeymasterBlob& /* issuer_subject */,  //
369                                           keymaster_error_t* error) const {
370     keymaster_algorithm_t key_algorithm;
371     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
372         *error = KM_ERROR_UNKNOWN_ERROR;
373         return {};
374     }
375 
376     if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC)) {
377         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
378         return {};
379     }
380 
381     // We have established that the given key has the correct algorithm, and because this is the
382     // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
383     const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
384 
385     return generate_attestation(asymmetric_key, attest_params, {} /* attest_key */, *this, error);
386 }
387 
GenerateSelfSignedCertificate(const Key & key,const AuthorizationSet & cert_params,bool fake_signature,keymaster_error_t * error) const388 CertificateChain SoftKeymasterContext::GenerateSelfSignedCertificate(
389     const Key& key, const AuthorizationSet& cert_params, bool fake_signature,
390     keymaster_error_t* error) const {
391     keymaster_algorithm_t key_algorithm;
392     if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
393         *error = KM_ERROR_UNKNOWN_ERROR;
394         return {};
395     }
396 
397     if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC)) {
398         *error = KM_ERROR_INCOMPATIBLE_ALGORITHM;
399         return {};
400     }
401 
402     // We have established that the given key has the correct algorithm, and because this is the
403     // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
404     const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
405 
406     return generate_self_signed_cert(asymmetric_key, cert_params, fake_signature, error);
407 }
408 
UnwrapKey(const KeymasterKeyBlob &,const KeymasterKeyBlob &,const AuthorizationSet &,const KeymasterKeyBlob &,AuthorizationSet *,keymaster_key_format_t *,KeymasterKeyBlob *) const409 keymaster_error_t SoftKeymasterContext::UnwrapKey(const KeymasterKeyBlob&, const KeymasterKeyBlob&,
410                                                   const AuthorizationSet&, const KeymasterKeyBlob&,
411                                                   AuthorizationSet*, keymaster_key_format_t*,
412                                                   KeymasterKeyBlob*) const {
413     return KM_ERROR_UNIMPLEMENTED;
414 }
415 
416 }  // namespace keymaster
417