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