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