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/legacy_support/keymaster1_engine.h>
18 
19 #include <assert.h>
20 
21 #include <algorithm>
22 #include <memory>
23 
24 #define LOG_TAG "Keymaster1Engine"
25 #include <log/log.h>
26 
27 #include <keymaster/android_keymaster_utils.h>
28 #include <keymaster/km_openssl/openssl_err.h>
29 #include <keymaster/km_openssl/openssl_utils.h>
30 
31 #include <openssl/bn.h>
32 #include <openssl/ec_key.h>
33 #include <openssl/ecdsa.h>
34 
35 using std::unique_ptr;
36 
37 namespace keymaster {
38 
39 Keymaster1Engine* Keymaster1Engine::instance_ = nullptr;
40 
Keymaster1Engine(const keymaster1_device_t * keymaster1_device)41 Keymaster1Engine::Keymaster1Engine(const keymaster1_device_t* keymaster1_device)
42     : keymaster1_device_(keymaster1_device), engine_(ENGINE_new()),
43       rsa_index_(RSA_get_ex_new_index(0 /* argl */, nullptr /* argp */, nullptr /* new_func */,
44                                       Keymaster1Engine::duplicate_key_data,
45                                       Keymaster1Engine::free_key_data)),
46       ec_key_index_(EC_KEY_get_ex_new_index(
47           0 /* argl */, nullptr /* argp */, nullptr /* new_func */,
48           Keymaster1Engine::duplicate_key_data, Keymaster1Engine::free_key_data)),
49       rsa_method_(BuildRsaMethod()), ecdsa_method_(BuildEcdsaMethod()) {
50     assert(rsa_index_ != -1);
51     assert(ec_key_index_ != -1);
52     assert(keymaster1_device);
53     assert(!instance_);
54 
55     instance_ = this;
56 
57     ENGINE_set_RSA_method(engine_.get(), &rsa_method_, sizeof(rsa_method_));
58     ENGINE_set_ECDSA_method(engine_.get(), &ecdsa_method_, sizeof(ecdsa_method_));
59 }
60 
~Keymaster1Engine()61 Keymaster1Engine::~Keymaster1Engine() {
62     keymaster1_device_->common.close(
63         reinterpret_cast<hw_device_t*>(const_cast<keymaster1_device_t*>(keymaster1_device_)));
64     instance_ = nullptr;
65 }
66 
ConvertCharacteristics(keymaster_key_characteristics_t * characteristics,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced)67 static void ConvertCharacteristics(keymaster_key_characteristics_t* characteristics,
68                                    AuthorizationSet* hw_enforced, AuthorizationSet* sw_enforced) {
69     unique_ptr<keymaster_key_characteristics_t, Characteristics_Delete> characteristics_deleter(
70         characteristics);
71     if (hw_enforced) hw_enforced->Reinitialize(characteristics->hw_enforced);
72     if (sw_enforced) sw_enforced->Reinitialize(characteristics->sw_enforced);
73 }
74 
GenerateKey(const AuthorizationSet & key_description,KeymasterKeyBlob * key_blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const75 keymaster_error_t Keymaster1Engine::GenerateKey(const AuthorizationSet& key_description,
76                                                 KeymasterKeyBlob* key_blob,
77                                                 AuthorizationSet* hw_enforced,
78                                                 AuthorizationSet* sw_enforced) const {
79     assert(key_blob);
80 
81     keymaster_key_characteristics_t* characteristics;
82     keymaster_key_blob_t blob;
83     keymaster_error_t error = keymaster1_device_->generate_key(keymaster1_device_, &key_description,
84                                                                &blob, &characteristics);
85     if (error != KM_ERROR_OK) return error;
86     unique_ptr<uint8_t, Malloc_Delete> blob_deleter(const_cast<uint8_t*>(blob.key_material));
87     key_blob->key_material = dup_buffer(blob.key_material, blob.key_material_size);
88     key_blob->key_material_size = blob.key_material_size;
89 
90     ConvertCharacteristics(characteristics, hw_enforced, sw_enforced);
91     return error;
92 }
93 
ImportKey(const AuthorizationSet & key_description,keymaster_key_format_t input_key_material_format,const KeymasterKeyBlob & input_key_material,KeymasterKeyBlob * output_key_blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const94 keymaster_error_t Keymaster1Engine::ImportKey(const AuthorizationSet& key_description,
95                                               keymaster_key_format_t input_key_material_format,
96                                               const KeymasterKeyBlob& input_key_material,
97                                               KeymasterKeyBlob* output_key_blob,
98                                               AuthorizationSet* hw_enforced,
99                                               AuthorizationSet* sw_enforced) const {
100     assert(output_key_blob);
101 
102     keymaster_key_characteristics_t* characteristics;
103     const keymaster_blob_t input_key = {input_key_material.key_material,
104                                         input_key_material.key_material_size};
105     keymaster_key_blob_t blob;
106     keymaster_error_t error = keymaster1_device_->import_key(keymaster1_device_, &key_description,
107                                                              input_key_material_format, &input_key,
108                                                              &blob, &characteristics);
109     if (error != KM_ERROR_OK) return error;
110     unique_ptr<uint8_t, Malloc_Delete> blob_deleter(const_cast<uint8_t*>(blob.key_material));
111     output_key_blob->key_material = dup_buffer(blob.key_material, blob.key_material_size);
112     output_key_blob->key_material_size = blob.key_material_size;
113 
114     ConvertCharacteristics(characteristics, hw_enforced, sw_enforced);
115     return error;
116 }
117 
DeleteKey(const KeymasterKeyBlob & blob) const118 keymaster_error_t Keymaster1Engine::DeleteKey(const KeymasterKeyBlob& blob) const {
119     if (!keymaster1_device_->delete_key) return KM_ERROR_OK;
120     return keymaster1_device_->delete_key(keymaster1_device_, &blob);
121 }
122 
DeleteAllKeys() const123 keymaster_error_t Keymaster1Engine::DeleteAllKeys() const {
124     if (!keymaster1_device_->delete_all_keys) return KM_ERROR_OK;
125     return keymaster1_device_->delete_all_keys(keymaster1_device_);
126 }
127 
BuildRsaKey(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,keymaster_error_t * error) const128 RSA* Keymaster1Engine::BuildRsaKey(const KeymasterKeyBlob& blob,
129                                    const AuthorizationSet& additional_params,
130                                    keymaster_error_t* error) const {
131     // Create new RSA key (with engine methods) and add metadata
132     unique_ptr<RSA, RSA_Delete> rsa(RSA_new_method(engine_.get()));
133     if (!rsa) {
134         *error = TranslateLastOpenSslError();
135         return nullptr;
136     }
137 
138     KeyData* key_data = new (std::nothrow) KeyData(blob, additional_params);
139     if (!RSA_set_ex_data(rsa.get(), rsa_index_, key_data)) {
140         *error = TranslateLastOpenSslError();
141         delete key_data;
142         return nullptr;
143     }
144 
145     // Copy public key into new RSA key
146     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
147         GetKeymaster1PublicKey(key_data->key_material, key_data->begin_params, error));
148     if (*error != KM_ERROR_OK) return nullptr;
149 
150     unique_ptr<RSA, RSA_Delete> public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
151     if (!public_rsa) {
152         *error = TranslateLastOpenSslError();
153         return nullptr;
154     }
155 
156     BIGNUM_Ptr n(BN_dup(RSA_get0_n(public_rsa.get())));
157     BIGNUM_Ptr e(BN_dup(RSA_get0_e(public_rsa.get())));
158     if (!n || !e || !RSA_set0_key(rsa.get(), n.get(), e.get(), /*d=*/nullptr)) {
159         *error = TranslateLastOpenSslError();
160         return nullptr;
161     }
162     // RSA_set0_key takes ownership on success.
163     (void)n.release();
164     (void)e.release();
165 
166     *error = KM_ERROR_OK;
167     return rsa.release();
168 }
169 
BuildEcKey(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,keymaster_error_t * error) const170 EC_KEY* Keymaster1Engine::BuildEcKey(const KeymasterKeyBlob& blob,
171                                      const AuthorizationSet& additional_params,
172                                      keymaster_error_t* error) const {
173     // Create new EC key (with engine methods) and insert blob
174     unique_ptr<EC_KEY, EC_KEY_Delete> ec_key(EC_KEY_new_method(engine_.get()));
175     if (!ec_key) {
176         *error = TranslateLastOpenSslError();
177         return nullptr;
178     }
179 
180     KeyData* key_data = new (std::nothrow) KeyData(blob, additional_params);
181     if (!EC_KEY_set_ex_data(ec_key.get(), ec_key_index_, key_data)) {
182         *error = TranslateLastOpenSslError();
183         delete key_data;
184         return nullptr;
185     }
186 
187     // Copy public key into new EC key
188     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
189         GetKeymaster1PublicKey(blob, additional_params, error));
190     if (*error != KM_ERROR_OK) return nullptr;
191 
192     unique_ptr<EC_KEY, EC_KEY_Delete> public_ec_key(EVP_PKEY_get1_EC_KEY(pkey.get()));
193     if (!public_ec_key) {
194         *error = TranslateLastOpenSslError();
195         return nullptr;
196     }
197 
198     if (!EC_KEY_set_group(ec_key.get(), EC_KEY_get0_group(public_ec_key.get())) ||
199         !EC_KEY_set_public_key(ec_key.get(), EC_KEY_get0_public_key(public_ec_key.get()))) {
200         *error = TranslateLastOpenSslError();
201         return nullptr;
202     }
203 
204     *error = KM_ERROR_OK;
205     return ec_key.release();
206 }
207 
GetData(EVP_PKEY * key) const208 Keymaster1Engine::KeyData* Keymaster1Engine::GetData(EVP_PKEY* key) const {
209     switch (EVP_PKEY_id(key)) {
210     case EVP_PKEY_RSA: {
211         unique_ptr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(key));
212         return GetData(rsa.get());
213     }
214 
215     case EVP_PKEY_EC: {
216         unique_ptr<EC_KEY, EC_KEY_Delete> ec_key(EVP_PKEY_get1_EC_KEY(key));
217         return GetData(ec_key.get());
218     }
219 
220     default:
221         return nullptr;
222     };
223 }
224 
GetData(const RSA * rsa) const225 Keymaster1Engine::KeyData* Keymaster1Engine::GetData(const RSA* rsa) const {
226     if (!rsa) return nullptr;
227     return reinterpret_cast<KeyData*>(RSA_get_ex_data(rsa, rsa_index_));
228 }
229 
GetData(const EC_KEY * ec_key) const230 Keymaster1Engine::KeyData* Keymaster1Engine::GetData(const EC_KEY* ec_key) const {
231     if (!ec_key) return nullptr;
232     return reinterpret_cast<KeyData*>(EC_KEY_get_ex_data(ec_key, ec_key_index_));
233 }
234 
235 /* static */
duplicate_key_data(CRYPTO_EX_DATA *,const CRYPTO_EX_DATA *,void ** from_d,int,long,void *)236 int Keymaster1Engine::duplicate_key_data(CRYPTO_EX_DATA* /* to */, const CRYPTO_EX_DATA* /* from */,
237                                          // NOLINTNEXTLINE(google-runtime-int)
238                                          void** from_d, int /* index */, long /* argl */,
239                                          void* /* argp */) {
240     KeyData* data = reinterpret_cast<KeyData*>(*from_d);
241     if (!data) return 1;
242 
243     // Default copy ctor is good.
244     *from_d = new (std::nothrow) KeyData(*data);
245     if (*from_d) return 1;
246     return 0;
247 }
248 
249 /* static */
free_key_data(void *,void * ptr,CRYPTO_EX_DATA *,int,long,void *)250 void Keymaster1Engine::free_key_data(void* /* parent */, void* ptr, CRYPTO_EX_DATA* /* data */,
251                                      // NOLINTNEXTLINE(google-runtime-int)
252                                      int /* index*/, long /* argl */, void* /* argp */) {
253     delete reinterpret_cast<KeyData*>(ptr);
254 }
255 
Keymaster1Finish(const KeyData * key_data,const keymaster_blob_t & input,keymaster_blob_t * output)256 keymaster_error_t Keymaster1Engine::Keymaster1Finish(const KeyData* key_data,
257                                                      const keymaster_blob_t& input,
258                                                      keymaster_blob_t* output) {
259     if (key_data->op_handle == 0) return KM_ERROR_UNKNOWN_ERROR;
260 
261     size_t input_consumed;
262     // Note: devices are required to consume all input in a single update call for undigested
263     // signing operations and encryption operations.  No need to loop here.
264     keymaster_error_t error =
265         device()->update(device(), key_data->op_handle, &key_data->finish_params, &input,
266                          &input_consumed, nullptr /* out_params */, nullptr /* output */);
267     if (error != KM_ERROR_OK) return error;
268 
269     return device()->finish(device(), key_data->op_handle, &key_data->finish_params,
270                             nullptr /* signature */, nullptr /* out_params */, output);
271 }
272 
273 /* static */
rsa_sign_raw(RSA * rsa,size_t * out_len,uint8_t * out,size_t max_out,const uint8_t * in,size_t in_len,int padding)274 int Keymaster1Engine::rsa_sign_raw(RSA* rsa, size_t* out_len, uint8_t* out, size_t max_out,
275                                    const uint8_t* in, size_t in_len, int padding) {
276     KeyData* key_data = instance_->GetData(rsa);
277     if (!key_data) return 0;
278 
279     if (padding != key_data->expected_openssl_padding) {
280         LOG_E("Expected sign_raw with padding %d but got padding %d",
281               key_data->expected_openssl_padding, padding);
282         return KM_ERROR_UNKNOWN_ERROR;
283     }
284 
285     keymaster_blob_t input = {in, in_len};
286     keymaster_blob_t output;
287     key_data->error = instance_->Keymaster1Finish(key_data, input, &output);
288     if (key_data->error != KM_ERROR_OK) return 0;
289     unique_ptr<uint8_t, Malloc_Delete> output_deleter(const_cast<uint8_t*>(output.data));
290 
291     *out_len = std::min(output.data_length, max_out);
292     memcpy(out, output.data, *out_len);
293     return 1;
294 }
295 
296 /* static */
rsa_decrypt(RSA * rsa,size_t * out_len,uint8_t * out,size_t max_out,const uint8_t * in,size_t in_len,int padding)297 int Keymaster1Engine::rsa_decrypt(RSA* rsa, size_t* out_len, uint8_t* out, size_t max_out,
298                                   const uint8_t* in, size_t in_len, int padding) {
299     KeyData* key_data = instance_->GetData(rsa);
300     if (!key_data) return 0;
301 
302     if (padding != key_data->expected_openssl_padding) {
303         LOG_E("Expected sign_raw with padding %d but got padding %d",
304               key_data->expected_openssl_padding, padding);
305         return KM_ERROR_UNKNOWN_ERROR;
306     }
307 
308     keymaster_blob_t input = {in, in_len};
309     keymaster_blob_t output;
310     key_data->error = instance_->Keymaster1Finish(key_data, input, &output);
311     if (key_data->error != KM_ERROR_OK) return 0;
312     unique_ptr<uint8_t, Malloc_Delete> output_deleter(const_cast<uint8_t*>(output.data));
313 
314     *out_len = std::min(output.data_length, max_out);
315     memcpy(out, output.data, *out_len);
316     return 1;
317 }
318 
319 /* static */
ecdsa_sign(const uint8_t * digest,size_t digest_len,uint8_t * sig,unsigned int * sig_len,EC_KEY * ec_key)320 int Keymaster1Engine::ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
321                                  unsigned int* sig_len, EC_KEY* ec_key) {
322     KeyData* key_data = instance_->GetData(ec_key);
323     if (!key_data) return 0;
324 
325     // Truncate digest if it's too long
326     size_t max_input_len = (ec_group_size_bits(ec_key) + 7) / 8;
327     if (digest_len > max_input_len) digest_len = max_input_len;
328 
329     keymaster_blob_t input = {digest, digest_len};
330     keymaster_blob_t output;
331     key_data->error = instance_->Keymaster1Finish(key_data, input, &output);
332     if (key_data->error != KM_ERROR_OK) return 0;
333     unique_ptr<uint8_t, Malloc_Delete> output_deleter(const_cast<uint8_t*>(output.data));
334 
335     *sig_len = std::min(output.data_length, ECDSA_size(ec_key));
336     memcpy(sig, output.data, *sig_len);
337     return 1;
338 }
339 
GetKeymaster1PublicKey(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,keymaster_error_t * error) const340 EVP_PKEY* Keymaster1Engine::GetKeymaster1PublicKey(const KeymasterKeyBlob& blob,
341                                                    const AuthorizationSet& additional_params,
342                                                    keymaster_error_t* error) const {
343     keymaster_blob_t client_id = {nullptr, 0};
344     keymaster_blob_t app_data = {nullptr, 0};
345     keymaster_blob_t* client_id_ptr = nullptr;
346     keymaster_blob_t* app_data_ptr = nullptr;
347     if (additional_params.GetTagValue(TAG_APPLICATION_ID, &client_id)) client_id_ptr = &client_id;
348     if (additional_params.GetTagValue(TAG_APPLICATION_DATA, &app_data)) app_data_ptr = &app_data;
349 
350     keymaster_blob_t export_data = {nullptr, 0};
351     *error = keymaster1_device_->export_key(keymaster1_device_, KM_KEY_FORMAT_X509, &blob,
352                                             client_id_ptr, app_data_ptr, &export_data);
353     if (*error != KM_ERROR_OK) return nullptr;
354 
355     unique_ptr<uint8_t, Malloc_Delete> pub_key(const_cast<uint8_t*>(export_data.data));
356 
357     const uint8_t* p = export_data.data;
358     auto result = d2i_PUBKEY(nullptr /* allocate new struct */, &p, export_data.data_length);
359     if (!result) {
360         *error = TranslateLastOpenSslError();
361     }
362     return result;
363 }
364 
BuildRsaMethod()365 RSA_METHOD Keymaster1Engine::BuildRsaMethod() {
366     RSA_METHOD method = {};
367 
368     method.common.is_static = 1;
369     method.sign_raw = Keymaster1Engine::rsa_sign_raw;
370     method.decrypt = Keymaster1Engine::rsa_decrypt;
371     method.flags = RSA_FLAG_OPAQUE;
372 
373     return method;
374 }
375 
BuildEcdsaMethod()376 ECDSA_METHOD Keymaster1Engine::BuildEcdsaMethod() {
377     ECDSA_METHOD method = {};
378 
379     method.common.is_static = 1;
380     method.sign = Keymaster1Engine::ecdsa_sign;
381     method.flags = ECDSA_FLAG_OPAQUE;
382 
383     return method;
384 }
385 
386 }  // namespace keymaster
387