• 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/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     rsa->n = BN_dup(public_rsa->n);
157     rsa->e = BN_dup(public_rsa->e);
158     if (!rsa->n || !rsa->e) {
159         *error = TranslateLastOpenSslError();
160         return nullptr;
161     }
162 
163     *error = KM_ERROR_OK;
164     return rsa.release();
165 }
166 
BuildEcKey(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,keymaster_error_t * error) const167 EC_KEY* Keymaster1Engine::BuildEcKey(const KeymasterKeyBlob& blob,
168                                      const AuthorizationSet& additional_params,
169                                      keymaster_error_t* error) const {
170     // Create new EC key (with engine methods) and insert blob
171     unique_ptr<EC_KEY, EC_KEY_Delete> ec_key(EC_KEY_new_method(engine_.get()));
172     if (!ec_key) {
173         *error = TranslateLastOpenSslError();
174         return nullptr;
175     }
176 
177     KeyData* key_data = new (std::nothrow) KeyData(blob, additional_params);
178     if (!EC_KEY_set_ex_data(ec_key.get(), ec_key_index_, key_data)) {
179         *error = TranslateLastOpenSslError();
180         delete key_data;
181         return nullptr;
182     }
183 
184     // Copy public key into new EC key
185     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
186         GetKeymaster1PublicKey(blob, additional_params, error));
187     if (*error != KM_ERROR_OK) return nullptr;
188 
189     unique_ptr<EC_KEY, EC_KEY_Delete> public_ec_key(EVP_PKEY_get1_EC_KEY(pkey.get()));
190     if (!public_ec_key) {
191         *error = TranslateLastOpenSslError();
192         return nullptr;
193     }
194 
195     if (!EC_KEY_set_group(ec_key.get(), EC_KEY_get0_group(public_ec_key.get())) ||
196         !EC_KEY_set_public_key(ec_key.get(), EC_KEY_get0_public_key(public_ec_key.get()))) {
197         *error = TranslateLastOpenSslError();
198         return nullptr;
199     }
200 
201     *error = KM_ERROR_OK;
202     return ec_key.release();
203 }
204 
GetData(EVP_PKEY * key) const205 Keymaster1Engine::KeyData* Keymaster1Engine::GetData(EVP_PKEY* key) const {
206     switch (EVP_PKEY_id(key)) {
207     case EVP_PKEY_RSA: {
208         unique_ptr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(key));
209         return GetData(rsa.get());
210     }
211 
212     case EVP_PKEY_EC: {
213         unique_ptr<EC_KEY, EC_KEY_Delete> ec_key(EVP_PKEY_get1_EC_KEY(key));
214         return GetData(ec_key.get());
215     }
216 
217     default:
218         return nullptr;
219     };
220 }
221 
GetData(const RSA * rsa) const222 Keymaster1Engine::KeyData* Keymaster1Engine::GetData(const RSA* rsa) const {
223     if (!rsa) return nullptr;
224     return reinterpret_cast<KeyData*>(RSA_get_ex_data(rsa, rsa_index_));
225 }
226 
GetData(const EC_KEY * ec_key) const227 Keymaster1Engine::KeyData* Keymaster1Engine::GetData(const EC_KEY* ec_key) const {
228     if (!ec_key) return nullptr;
229     return reinterpret_cast<KeyData*>(EC_KEY_get_ex_data(ec_key, ec_key_index_));
230 }
231 
232 /* static */
duplicate_key_data(CRYPTO_EX_DATA *,const CRYPTO_EX_DATA *,void ** from_d,int,long,void *)233 int Keymaster1Engine::duplicate_key_data(CRYPTO_EX_DATA* /* to */, const CRYPTO_EX_DATA* /* from */,
234                                          // NOLINTNEXTLINE(google-runtime-int)
235                                          void** from_d, int /* index */, long /* argl */,
236                                          void* /* argp */) {
237     KeyData* data = reinterpret_cast<KeyData*>(*from_d);
238     if (!data) return 1;
239 
240     // Default copy ctor is good.
241     *from_d = new (std::nothrow) KeyData(*data);
242     if (*from_d) return 1;
243     return 0;
244 }
245 
246 /* static */
free_key_data(void *,void * ptr,CRYPTO_EX_DATA *,int,long,void *)247 void Keymaster1Engine::free_key_data(void* /* parent */, void* ptr, CRYPTO_EX_DATA* /* data */,
248                                      // NOLINTNEXTLINE(google-runtime-int)
249                                      int /* index*/, long /* argl */, void* /* argp */) {
250     delete reinterpret_cast<KeyData*>(ptr);
251 }
252 
Keymaster1Finish(const KeyData * key_data,const keymaster_blob_t & input,keymaster_blob_t * output)253 keymaster_error_t Keymaster1Engine::Keymaster1Finish(const KeyData* key_data,
254                                                      const keymaster_blob_t& input,
255                                                      keymaster_blob_t* output) {
256     if (key_data->op_handle == 0) return KM_ERROR_UNKNOWN_ERROR;
257 
258     size_t input_consumed;
259     // Note: devices are required to consume all input in a single update call for undigested
260     // signing operations and encryption operations.  No need to loop here.
261     keymaster_error_t error =
262         device()->update(device(), key_data->op_handle, &key_data->finish_params, &input,
263                          &input_consumed, nullptr /* out_params */, nullptr /* output */);
264     if (error != KM_ERROR_OK) return error;
265 
266     return device()->finish(device(), key_data->op_handle, &key_data->finish_params,
267                             nullptr /* signature */, nullptr /* out_params */, output);
268 }
269 
270 /* 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)271 int Keymaster1Engine::rsa_sign_raw(RSA* rsa, size_t* out_len, uint8_t* out, size_t max_out,
272                                    const uint8_t* in, size_t in_len, int padding) {
273     KeyData* key_data = instance_->GetData(rsa);
274     if (!key_data) return 0;
275 
276     if (padding != key_data->expected_openssl_padding) {
277         LOG_E("Expected sign_raw with padding %d but got padding %d",
278               key_data->expected_openssl_padding, padding);
279         return KM_ERROR_UNKNOWN_ERROR;
280     }
281 
282     keymaster_blob_t input = {in, in_len};
283     keymaster_blob_t output;
284     key_data->error = instance_->Keymaster1Finish(key_data, input, &output);
285     if (key_data->error != KM_ERROR_OK) return 0;
286     unique_ptr<uint8_t, Malloc_Delete> output_deleter(const_cast<uint8_t*>(output.data));
287 
288     *out_len = std::min(output.data_length, max_out);
289     memcpy(out, output.data, *out_len);
290     return 1;
291 }
292 
293 /* 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)294 int Keymaster1Engine::rsa_decrypt(RSA* rsa, size_t* out_len, uint8_t* out, size_t max_out,
295                                   const uint8_t* in, size_t in_len, int padding) {
296     KeyData* key_data = instance_->GetData(rsa);
297     if (!key_data) return 0;
298 
299     if (padding != key_data->expected_openssl_padding) {
300         LOG_E("Expected sign_raw with padding %d but got padding %d",
301               key_data->expected_openssl_padding, padding);
302         return KM_ERROR_UNKNOWN_ERROR;
303     }
304 
305     keymaster_blob_t input = {in, in_len};
306     keymaster_blob_t output;
307     key_data->error = instance_->Keymaster1Finish(key_data, input, &output);
308     if (key_data->error != KM_ERROR_OK) return 0;
309     unique_ptr<uint8_t, Malloc_Delete> output_deleter(const_cast<uint8_t*>(output.data));
310 
311     *out_len = std::min(output.data_length, max_out);
312     memcpy(out, output.data, *out_len);
313     return 1;
314 }
315 
316 /* static */
ecdsa_sign(const uint8_t * digest,size_t digest_len,uint8_t * sig,unsigned int * sig_len,EC_KEY * ec_key)317 int Keymaster1Engine::ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
318                                  unsigned int* sig_len, EC_KEY* ec_key) {
319     KeyData* key_data = instance_->GetData(ec_key);
320     if (!key_data) return 0;
321 
322     // Truncate digest if it's too long
323     size_t max_input_len = (ec_group_size_bits(ec_key) + 7) / 8;
324     if (digest_len > max_input_len) digest_len = max_input_len;
325 
326     keymaster_blob_t input = {digest, digest_len};
327     keymaster_blob_t output;
328     key_data->error = instance_->Keymaster1Finish(key_data, input, &output);
329     if (key_data->error != KM_ERROR_OK) return 0;
330     unique_ptr<uint8_t, Malloc_Delete> output_deleter(const_cast<uint8_t*>(output.data));
331 
332     *sig_len = std::min(output.data_length, ECDSA_size(ec_key));
333     memcpy(sig, output.data, *sig_len);
334     return 1;
335 }
336 
GetKeymaster1PublicKey(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,keymaster_error_t * error) const337 EVP_PKEY* Keymaster1Engine::GetKeymaster1PublicKey(const KeymasterKeyBlob& blob,
338                                                    const AuthorizationSet& additional_params,
339                                                    keymaster_error_t* error) const {
340     keymaster_blob_t client_id = {nullptr, 0};
341     keymaster_blob_t app_data = {nullptr, 0};
342     keymaster_blob_t* client_id_ptr = nullptr;
343     keymaster_blob_t* app_data_ptr = nullptr;
344     if (additional_params.GetTagValue(TAG_APPLICATION_ID, &client_id)) client_id_ptr = &client_id;
345     if (additional_params.GetTagValue(TAG_APPLICATION_DATA, &app_data)) app_data_ptr = &app_data;
346 
347     keymaster_blob_t export_data = {nullptr, 0};
348     *error = keymaster1_device_->export_key(keymaster1_device_, KM_KEY_FORMAT_X509, &blob,
349                                             client_id_ptr, app_data_ptr, &export_data);
350     if (*error != KM_ERROR_OK) return nullptr;
351 
352     unique_ptr<uint8_t, Malloc_Delete> pub_key(const_cast<uint8_t*>(export_data.data));
353 
354     const uint8_t* p = export_data.data;
355     auto result = d2i_PUBKEY(nullptr /* allocate new struct */, &p, export_data.data_length);
356     if (!result) {
357         *error = TranslateLastOpenSslError();
358     }
359     return result;
360 }
361 
BuildRsaMethod()362 RSA_METHOD Keymaster1Engine::BuildRsaMethod() {
363     RSA_METHOD method = {};
364 
365     method.common.is_static = 1;
366     method.sign_raw = Keymaster1Engine::rsa_sign_raw;
367     method.decrypt = Keymaster1Engine::rsa_decrypt;
368     method.flags = RSA_FLAG_OPAQUE;
369 
370     return method;
371 }
372 
BuildEcdsaMethod()373 ECDSA_METHOD Keymaster1Engine::BuildEcdsaMethod() {
374     ECDSA_METHOD method = {};
375 
376     method.common.is_static = 1;
377     method.sign = Keymaster1Engine::ecdsa_sign;
378     method.flags = ECDSA_FLAG_OPAQUE;
379 
380     return method;
381 }
382 
383 }  // namespace keymaster
384