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