soft_keymaster_device.cpp revision 8ba2a043f0d44ad3f58d4af518f9391c03eca9c3
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/soft_keymaster_device.h>
18
19#include <assert.h>
20#include <stdio.h>
21#include <stdlib.h>
22#include <string.h>
23#include <time.h>
24#include <stddef.h>
25
26#include <algorithm>
27
28#include <type_traits>
29
30#include <openssl/x509.h>
31
32#include <hardware/keymaster1.h>
33#define LOG_TAG "SoftKeymasterDevice"
34#include <cutils/log.h>
35
36#include <keymaster/android_keymaster.h>
37#include <keymaster/android_keymaster_messages.h>
38#include <keymaster/authorization_set.h>
39#include <keymaster/soft_keymaster_logger.h>
40
41#include "soft_keymaster_context.h"
42#include "openssl_utils.h"
43
44struct keystore_module soft_keymaster_device_module = {
45    .common =
46        {
47            .tag = HARDWARE_MODULE_TAG,
48            .module_api_version = KEYMASTER_MODULE_API_VERSION_1_0,
49            .hal_api_version = HARDWARE_HAL_API_VERSION,
50            .id = KEYSTORE_HARDWARE_MODULE_ID,
51            .name = "Keymaster OpenSSL HAL",
52            .author = "The Android Open Source Project",
53            .methods = NULL,
54            .dso = 0,
55            .reserved = {},
56        },
57};
58
59namespace keymaster {
60
61SoftKeymasterDevice::SoftKeymasterDevice()
62    : impl_(new AndroidKeymaster(new SoftKeymasterContext, 16)) {
63#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
64    static_assert(std::is_standard_layout<SoftKeymasterDevice>::value,
65                  "SoftKeymasterDevice must be standard layout");
66    static_assert(offsetof(SoftKeymasterDevice, device_) == 0,
67                  "device_ must be the first member of KeymasterOpenSsl");
68    static_assert(offsetof(SoftKeymasterDevice, device_.common) == 0,
69                  "common must be the first member of keymaster_device");
70#else
71    assert(reinterpret_cast<keymaster_device*>(this) == &device_);
72    assert(reinterpret_cast<hw_device_t*>(this) == &(device_.common));
73#endif
74    LOG_I("Creating device", 0);
75    LOG_D("Device address: %p", this);
76
77    memset(&device_, 0, sizeof(device_));
78
79    device_.common.tag = HARDWARE_DEVICE_TAG;
80    device_.common.version = 1;
81    device_.common.module = reinterpret_cast<hw_module_t*>(&soft_keymaster_device_module);
82    device_.common.close = &close_device;
83
84    device_.flags =
85        KEYMASTER_SOFTWARE_ONLY | KEYMASTER_BLOBS_ARE_STANDALONE | KEYMASTER_SUPPORTS_EC;
86
87    // V0.3 APIs
88    device_.generate_keypair = generate_keypair;
89    device_.import_keypair = import_keypair;
90    device_.get_keypair_public = get_keypair_public;
91    device_.delete_keypair = NULL;
92    device_.delete_all = NULL;
93    device_.sign_data = sign_data;
94    device_.verify_data = verify_data;
95
96    // V0.4 APIs
97    device_.get_supported_algorithms = get_supported_algorithms;
98    device_.get_supported_block_modes = get_supported_block_modes;
99    device_.get_supported_padding_modes = get_supported_padding_modes;
100    device_.get_supported_digests = get_supported_digests;
101    device_.get_supported_import_formats = get_supported_import_formats;
102    device_.get_supported_export_formats = get_supported_export_formats;
103    device_.add_rng_entropy = add_rng_entropy;
104    device_.generate_key = generate_key;
105    device_.get_key_characteristics = get_key_characteristics;
106    device_.import_key = import_key;
107    device_.export_key = export_key;
108    device_.delete_key = NULL;
109    device_.delete_all_keys = NULL;
110    device_.begin = begin;
111    device_.update = update;
112    device_.finish = finish;
113    device_.abort = abort;
114
115    device_.context = NULL;
116}
117
118const uint64_t HUNDRED_YEARS = 1000LL * 60 * 60 * 24 * 365 * 100;
119
120hw_device_t* SoftKeymasterDevice::hw_device() {
121    return &device_.common;
122}
123
124keymaster1_device_t* SoftKeymasterDevice::keymaster_device() {
125    return &device_;
126}
127
128static keymaster_key_characteristics_t* BuildCharacteristics(const AuthorizationSet& hw_enforced,
129                                                             const AuthorizationSet& sw_enforced) {
130    keymaster_key_characteristics_t* characteristics =
131        reinterpret_cast<keymaster_key_characteristics_t*>(
132            malloc(sizeof(keymaster_key_characteristics_t)));
133    if (characteristics) {
134        hw_enforced.CopyToParamSet(&characteristics->hw_enforced);
135        sw_enforced.CopyToParamSet(&characteristics->sw_enforced);
136    }
137    return characteristics;
138}
139
140template <typename RequestType>
141static void AddClientAndAppData(const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
142                                RequestType* request) {
143    request->additional_params.Clear();
144    if (client_id)
145        request->additional_params.push_back(TAG_APPLICATION_ID, *client_id);
146    if (app_data)
147        request->additional_params.push_back(TAG_APPLICATION_DATA, *app_data);
148}
149
150static inline SoftKeymasterDevice* convert_device(const keymaster1_device_t* dev) {
151    return reinterpret_cast<SoftKeymasterDevice*>(const_cast<keymaster1_device_t*>(dev));
152}
153
154/* static */
155int SoftKeymasterDevice::close_device(hw_device_t* dev) {
156    delete reinterpret_cast<SoftKeymasterDevice*>(dev);
157    return 0;
158}
159
160/* static */
161int SoftKeymasterDevice::generate_keypair(const keymaster1_device_t* dev,
162                                          const keymaster_keypair_t key_type,
163                                          const void* key_params, uint8_t** key_blob,
164                                          size_t* key_blob_length) {
165    LOG_D("%s", "Device received generate_keypair");
166    if (!dev || !key_params)
167        return KM_ERROR_UNEXPECTED_NULL_POINTER;
168
169    if (!key_blob || !key_blob_length)
170        return KM_ERROR_OUTPUT_PARAMETER_NULL;
171
172    GenerateKeyRequest req;
173    StoreDefaultNewKeyParams(&req.key_description);
174
175    switch (key_type) {
176    case TYPE_RSA: {
177        req.key_description.push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
178        const keymaster_rsa_keygen_params_t* rsa_params =
179            static_cast<const keymaster_rsa_keygen_params_t*>(key_params);
180        LOG_D("Generating RSA pair, modulus size: %u, public exponent: %lu",
181              rsa_params->modulus_size, rsa_params->public_exponent);
182        req.key_description.push_back(TAG_KEY_SIZE, rsa_params->modulus_size);
183        req.key_description.push_back(TAG_RSA_PUBLIC_EXPONENT, rsa_params->public_exponent);
184        break;
185    }
186
187    case TYPE_EC: {
188        req.key_description.push_back(TAG_ALGORITHM, KM_ALGORITHM_EC);
189        const keymaster_ec_keygen_params_t* ec_params =
190            static_cast<const keymaster_ec_keygen_params_t*>(key_params);
191        LOG_D("Generating ECDSA pair, key size: %u", ec_params->field_size);
192        req.key_description.push_back(TAG_KEY_SIZE, ec_params->field_size);
193        break;
194    }
195
196    default:
197        LOG_D("Received request for unsuported key type %d", key_type);
198        return KM_ERROR_UNSUPPORTED_ALGORITHM;
199    }
200
201    GenerateKeyResponse rsp;
202    convert_device(dev)->impl_->GenerateKey(req, &rsp);
203    if (rsp.error != KM_ERROR_OK) {
204        LOG_E("Key generation failed with error: %d", rsp.error);
205        return rsp.error;
206    }
207
208    *key_blob_length = rsp.key_blob.key_material_size;
209    *key_blob = static_cast<uint8_t*>(malloc(*key_blob_length));
210    if (!*key_blob) {
211        LOG_E("Failed to allocate %d bytes", *key_blob_length);
212        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
213    }
214    memcpy(*key_blob, rsp.key_blob.key_material, *key_blob_length);
215    LOG_D("Returning %d bytes in key blob\n", (int)*key_blob_length);
216
217    return KM_ERROR_OK;
218}
219
220/* static */
221int SoftKeymasterDevice::import_keypair(const keymaster1_device_t* dev, const uint8_t* key,
222                                        const size_t key_length, uint8_t** key_blob,
223                                        size_t* key_blob_length) {
224    LOG_D("Device received import_keypair", 0);
225
226    if (!dev || !key)
227        return KM_ERROR_UNEXPECTED_NULL_POINTER;
228
229    if (!key_blob || !key_blob_length)
230        return KM_ERROR_OUTPUT_PARAMETER_NULL;
231
232    ImportKeyRequest request;
233    StoreDefaultNewKeyParams(&request.key_description);
234    keymaster_algorithm_t algorithm;
235    keymaster_error_t err = GetPkcs8KeyAlgorithm(key, key_length, &algorithm);
236    if (err != KM_ERROR_OK)
237        return err;
238    request.key_description.push_back(TAG_ALGORITHM, algorithm);
239    request.SetKeyMaterial(key, key_length);
240    request.key_format = KM_KEY_FORMAT_PKCS8;
241
242    ImportKeyResponse response;
243    convert_device(dev)->impl_->ImportKey(request, &response);
244    if (response.error != KM_ERROR_OK) {
245        LOG_E("Key import failed with error: %d", response.error);
246        return response.error;
247    }
248
249    *key_blob_length = response.key_blob.key_material_size;
250    *key_blob = static_cast<uint8_t*>(malloc(*key_blob_length));
251    if (!*key_blob) {
252        LOG_E("Failed to allocate %d bytes", *key_blob_length);
253        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
254    }
255    memcpy(*key_blob, response.key_blob.key_material, *key_blob_length);
256    LOG_D("Returning %d bytes in key blob\n", (int)*key_blob_length);
257
258    return KM_ERROR_OK;
259}
260
261/* static */
262keymaster_error_t SoftKeymasterDevice::GetPkcs8KeyAlgorithm(const uint8_t* key, size_t key_length,
263                                                            keymaster_algorithm_t* algorithm) {
264    if (key == NULL) {
265        LOG_E("No key specified for import", 0);
266        return KM_ERROR_UNEXPECTED_NULL_POINTER;
267    }
268
269    UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> pkcs8(
270        d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length));
271    if (pkcs8.get() == NULL) {
272        LOG_E("Could not parse PKCS8 key blob", 0);
273        return KM_ERROR_INVALID_KEY_BLOB;
274    }
275
276    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKCS82PKEY(pkcs8.get()));
277    if (pkey.get() == NULL) {
278        LOG_E("Could not extract key from PKCS8 key blob", 0);
279        return KM_ERROR_INVALID_KEY_BLOB;
280    }
281
282    switch (EVP_PKEY_type(pkey->type)) {
283    case EVP_PKEY_RSA:
284        *algorithm = KM_ALGORITHM_RSA;
285        break;
286    case EVP_PKEY_EC:
287        *algorithm = KM_ALGORITHM_EC;
288        break;
289    default:
290        LOG_E("Unsupported algorithm %d", EVP_PKEY_type(pkey->type));
291        return KM_ERROR_UNSUPPORTED_ALGORITHM;
292    }
293
294    return KM_ERROR_OK;
295}
296
297/* static */
298int SoftKeymasterDevice::get_keypair_public(const struct keymaster1_device* dev,
299                                            const uint8_t* key_blob, const size_t key_blob_length,
300                                            uint8_t** x509_data, size_t* x509_data_length) {
301    LOG_D("Device received get_keypair_public", 0);
302
303    if (!dev || !key_blob)
304        return KM_ERROR_UNEXPECTED_NULL_POINTER;
305
306    if (!x509_data || !x509_data_length)
307        return KM_ERROR_OUTPUT_PARAMETER_NULL;
308
309    ExportKeyRequest req;
310    req.SetKeyMaterial(key_blob, key_blob_length);
311    req.key_format = KM_KEY_FORMAT_X509;
312
313    ExportKeyResponse rsp;
314    convert_device(dev)->impl_->ExportKey(req, &rsp);
315    if (rsp.error != KM_ERROR_OK) {
316        LOG_E("get_keypair_public failed with error: %d", rsp.error);
317        return rsp.error;
318    }
319
320    *x509_data_length = rsp.key_data_length;
321    *x509_data = static_cast<uint8_t*>(malloc(*x509_data_length));
322    if (!*x509_data)
323        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
324    memcpy(*x509_data, rsp.key_data, *x509_data_length);
325    LOG_D("Returning %d bytes in x509 key\n", (int)*x509_data_length);
326
327    return KM_ERROR_OK;
328}
329
330/* static */
331int SoftKeymasterDevice::sign_data(const keymaster1_device_t* dev, const void* params,
332                                   const uint8_t* key_blob, const size_t key_blob_length,
333                                   const uint8_t* data, const size_t data_length,
334                                   uint8_t** signed_data, size_t* signed_data_length) {
335    LOG_D("Device received sign_data", 0);
336
337    if (!dev || !params || !key_blob)
338        return KM_ERROR_UNEXPECTED_NULL_POINTER;
339
340    if (!signed_data || !signed_data_length)
341        return KM_ERROR_OUTPUT_PARAMETER_NULL;
342
343    *signed_data_length = 0;
344
345    BeginOperationRequest begin_request;
346    begin_request.purpose = KM_PURPOSE_SIGN;
347    begin_request.SetKeyMaterial(key_blob, key_blob_length);
348    keymaster_error_t err = ExtractSigningParams(dev, params, key_blob, key_blob_length,
349                                                 &begin_request.additional_params);
350    if (err != KM_ERROR_OK)
351        return err;
352
353    BeginOperationResponse begin_response;
354    convert_device(dev)->impl_->BeginOperation(begin_request, &begin_response);
355    if (begin_response.error != KM_ERROR_OK) {
356        LOG_E("sign_data begin operation failed with error: %d", begin_response.error);
357        return begin_response.error;
358    }
359
360    UpdateOperationRequest update_request;
361    update_request.op_handle = begin_response.op_handle;
362    update_request.input.Reinitialize(data, data_length);
363    UpdateOperationResponse update_response;
364    convert_device(dev)->impl_->UpdateOperation(update_request, &update_response);
365    if (update_response.error != KM_ERROR_OK) {
366        LOG_E("sign_data update operation failed with error: %d", update_response.error);
367        return update_response.error;
368    }
369
370    FinishOperationRequest finish_request;
371    finish_request.op_handle = begin_response.op_handle;
372    FinishOperationResponse finish_response;
373    convert_device(dev)->impl_->FinishOperation(finish_request, &finish_response);
374    if (finish_response.error != KM_ERROR_OK) {
375        LOG_E("sign_data finish operation failed with error: %d", finish_response.error);
376        return finish_response.error;
377    }
378
379    *signed_data_length = finish_response.output.available_read();
380    *signed_data = static_cast<uint8_t*>(malloc(*signed_data_length));
381    if (!*signed_data)
382        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
383    if (!finish_response.output.read(*signed_data, *signed_data_length))
384        return KM_ERROR_UNKNOWN_ERROR;
385    return KM_ERROR_OK;
386}
387
388/* static */
389int SoftKeymasterDevice::verify_data(const keymaster1_device_t* dev, const void* params,
390                                     const uint8_t* key_blob, const size_t key_blob_length,
391                                     const uint8_t* signed_data, const size_t signed_data_length,
392                                     const uint8_t* signature, const size_t signature_length) {
393    LOG_D("Device received verify_data", 0);
394
395    if (!dev || !params || !key_blob || !signed_data || !signature)
396        return KM_ERROR_UNEXPECTED_NULL_POINTER;
397
398    BeginOperationRequest begin_request;
399    begin_request.purpose = KM_PURPOSE_VERIFY;
400    begin_request.SetKeyMaterial(key_blob, key_blob_length);
401    keymaster_error_t err = ExtractSigningParams(dev, params, key_blob, key_blob_length,
402                                                 &begin_request.additional_params);
403    if (err != KM_ERROR_OK)
404        return err;
405
406    BeginOperationResponse begin_response;
407    convert_device(dev)->impl_->BeginOperation(begin_request, &begin_response);
408    if (begin_response.error != KM_ERROR_OK) {
409        LOG_E("verify_data begin operation failed with error: %d", begin_response.error);
410        return begin_response.error;
411    }
412
413    UpdateOperationRequest update_request;
414    update_request.op_handle = begin_response.op_handle;
415    update_request.input.Reinitialize(signed_data, signed_data_length);
416    UpdateOperationResponse update_response;
417    convert_device(dev)->impl_->UpdateOperation(update_request, &update_response);
418    if (update_response.error != KM_ERROR_OK) {
419        LOG_E("verify_data update operation failed with error: %d", update_response.error);
420        return update_response.error;
421    }
422
423    FinishOperationRequest finish_request;
424    finish_request.op_handle = begin_response.op_handle;
425    finish_request.signature.Reinitialize(signature, signature_length);
426    FinishOperationResponse finish_response;
427    convert_device(dev)->impl_->FinishOperation(finish_request, &finish_response);
428    if (finish_response.error != KM_ERROR_OK) {
429        LOG_E("verify_data finish operation failed with error: %d", finish_response.error);
430        return finish_response.error;
431    }
432    return KM_ERROR_OK;
433}
434
435/* static */
436keymaster_error_t SoftKeymasterDevice::get_supported_algorithms(const keymaster1_device_t* dev,
437                                                                keymaster_algorithm_t** algorithms,
438                                                                size_t* algorithms_length) {
439    if (!dev)
440        return KM_ERROR_UNEXPECTED_NULL_POINTER;
441
442    if (!algorithms || !algorithms_length)
443        return KM_ERROR_OUTPUT_PARAMETER_NULL;
444
445    SupportedResponse<keymaster_algorithm_t> response;
446    convert_device(dev)->impl_->SupportedAlgorithms(&response);
447    if (response.error != KM_ERROR_OK) {
448        LOG_E("get_supported_algorithms failed with %d", response.error);
449
450        return response.error;
451    }
452
453    *algorithms_length = response.results_length;
454    *algorithms =
455        reinterpret_cast<keymaster_algorithm_t*>(malloc(*algorithms_length * sizeof(**algorithms)));
456    if (!*algorithms)
457        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
458    std::copy(response.results, response.results + response.results_length, *algorithms);
459    return KM_ERROR_OK;
460}
461
462/* static */
463keymaster_error_t SoftKeymasterDevice::get_supported_block_modes(const keymaster1_device_t* dev,
464                                                                 keymaster_algorithm_t algorithm,
465                                                                 keymaster_purpose_t purpose,
466                                                                 keymaster_block_mode_t** modes,
467                                                                 size_t* modes_length) {
468    if (!dev)
469        return KM_ERROR_UNEXPECTED_NULL_POINTER;
470
471    if (!modes || !modes_length)
472        return KM_ERROR_OUTPUT_PARAMETER_NULL;
473
474    SupportedResponse<keymaster_block_mode_t> response;
475    convert_device(dev)->impl_->SupportedBlockModes(algorithm, purpose, &response);
476
477    if (response.error != KM_ERROR_OK) {
478        LOG_E("get_supported_block_modes failed with %d", response.error);
479
480        return response.error;
481    }
482
483    *modes_length = response.results_length;
484    *modes = reinterpret_cast<keymaster_block_mode_t*>(malloc(*modes_length * sizeof(**modes)));
485    if (!*modes)
486        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
487    std::copy(response.results, response.results + response.results_length, *modes);
488    return KM_ERROR_OK;
489}
490
491/* static */
492keymaster_error_t SoftKeymasterDevice::get_supported_padding_modes(const keymaster1_device_t* dev,
493                                                                   keymaster_algorithm_t algorithm,
494                                                                   keymaster_purpose_t purpose,
495                                                                   keymaster_padding_t** modes,
496                                                                   size_t* modes_length) {
497    if (!dev)
498        return KM_ERROR_UNEXPECTED_NULL_POINTER;
499
500    if (!modes || !modes_length)
501        return KM_ERROR_OUTPUT_PARAMETER_NULL;
502
503    SupportedResponse<keymaster_padding_t> response;
504    convert_device(dev)->impl_->SupportedPaddingModes(algorithm, purpose, &response);
505
506    if (response.error != KM_ERROR_OK) {
507        LOG_E("get_supported_padding_modes failed with %d", response.error);
508        return response.error;
509    }
510
511    *modes_length = response.results_length;
512    *modes = reinterpret_cast<keymaster_padding_t*>(malloc(*modes_length * sizeof(**modes)));
513    if (!*modes)
514        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
515    std::copy(response.results, response.results + response.results_length, *modes);
516    return KM_ERROR_OK;
517}
518
519/* static */
520keymaster_error_t SoftKeymasterDevice::get_supported_digests(const keymaster1_device_t* dev,
521                                                             keymaster_algorithm_t algorithm,
522                                                             keymaster_purpose_t purpose,
523                                                             keymaster_digest_t** digests,
524                                                             size_t* digests_length) {
525    if (!dev)
526        return KM_ERROR_UNEXPECTED_NULL_POINTER;
527
528    if (!digests || !digests_length)
529        return KM_ERROR_OUTPUT_PARAMETER_NULL;
530
531    SupportedResponse<keymaster_digest_t> response;
532    convert_device(dev)->impl_->SupportedDigests(algorithm, purpose, &response);
533
534    if (response.error != KM_ERROR_OK) {
535        LOG_E("get_supported_digests failed with %d", response.error);
536        return response.error;
537    }
538
539    *digests_length = response.results_length;
540    *digests = reinterpret_cast<keymaster_digest_t*>(malloc(*digests_length * sizeof(**digests)));
541    if (!*digests)
542        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
543    std::copy(response.results, response.results + response.results_length, *digests);
544    return KM_ERROR_OK;
545}
546
547/* static */
548keymaster_error_t SoftKeymasterDevice::get_supported_import_formats(
549    const keymaster1_device_t* dev, keymaster_algorithm_t algorithm,
550    keymaster_key_format_t** formats, size_t* formats_length) {
551    if (!dev)
552        return KM_ERROR_UNEXPECTED_NULL_POINTER;
553
554    if (!formats || !formats_length)
555        return KM_ERROR_OUTPUT_PARAMETER_NULL;
556
557    SupportedResponse<keymaster_key_format_t> response;
558    convert_device(dev)->impl_->SupportedImportFormats(algorithm, &response);
559
560    if (response.error != KM_ERROR_OK) {
561        LOG_E("get_supported_import_formats failed with %d", response.error);
562        return response.error;
563    }
564
565    *formats_length = response.results_length;
566    *formats =
567        reinterpret_cast<keymaster_key_format_t*>(malloc(*formats_length * sizeof(**formats)));
568    if (!*formats)
569        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
570    std::copy(response.results, response.results + response.results_length, *formats);
571    return KM_ERROR_OK;
572}
573
574/* static */
575keymaster_error_t SoftKeymasterDevice::get_supported_export_formats(
576    const keymaster1_device_t* dev, keymaster_algorithm_t algorithm,
577    keymaster_key_format_t** formats, size_t* formats_length) {
578    if (!dev)
579        return KM_ERROR_UNEXPECTED_NULL_POINTER;
580
581    if (!formats || !formats_length)
582        return KM_ERROR_OUTPUT_PARAMETER_NULL;
583
584    SupportedResponse<keymaster_key_format_t> response;
585    convert_device(dev)->impl_->SupportedExportFormats(algorithm, &response);
586
587    if (response.error != KM_ERROR_OK) {
588        LOG_E("get_supported_export_formats failed with %d", response.error);
589        return response.error;
590    }
591
592    *formats_length = response.results_length;
593    *formats =
594        reinterpret_cast<keymaster_key_format_t*>(malloc(*formats_length * sizeof(**formats)));
595    if (!*formats)
596        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
597    std::copy(response.results, response.results + *formats_length, *formats);
598    return KM_ERROR_OK;
599}
600
601/* static */
602keymaster_error_t SoftKeymasterDevice::add_rng_entropy(const keymaster1_device_t* dev,
603                                                       const uint8_t* data, size_t data_length) {
604    if (!dev)
605        return KM_ERROR_UNEXPECTED_NULL_POINTER;
606
607    AddEntropyRequest request;
608    request.random_data.Reinitialize(data, data_length);
609    return convert_device(dev)->impl_->AddRngEntropy(request);
610}
611
612/* static */
613keymaster_error_t SoftKeymasterDevice::generate_key(
614    const keymaster1_device_t* dev, const keymaster_key_param_t* params, size_t params_count,
615    keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
616    if (!dev || !params)
617        return KM_ERROR_UNEXPECTED_NULL_POINTER;
618
619    if (!key_blob)
620        return KM_ERROR_OUTPUT_PARAMETER_NULL;
621
622    GenerateKeyRequest request;
623    request.key_description.Reinitialize(params, params_count);
624
625    GenerateKeyResponse response;
626    convert_device(dev)->impl_->GenerateKey(request, &response);
627    if (response.error != KM_ERROR_OK)
628        return response.error;
629
630    key_blob->key_material_size = response.key_blob.key_material_size;
631    uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
632    if (!tmp)
633        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
634    memcpy(tmp, response.key_blob.key_material, response.key_blob.key_material_size);
635    key_blob->key_material = tmp;
636
637    if (characteristics) {
638        *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
639        if (!*characteristics)
640            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
641    }
642
643    return KM_ERROR_OK;
644}
645
646/* static */
647keymaster_error_t SoftKeymasterDevice::get_key_characteristics(
648    const keymaster1_device_t* dev, const keymaster_key_blob_t* key_blob,
649    const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
650    keymaster_key_characteristics_t** characteristics) {
651    if (!dev || !key_blob || !key_blob->key_material)
652        return KM_ERROR_UNEXPECTED_NULL_POINTER;
653
654    if (!characteristics)
655        return KM_ERROR_OUTPUT_PARAMETER_NULL;
656
657    GetKeyCharacteristicsRequest request;
658    request.SetKeyMaterial(*key_blob);
659    AddClientAndAppData(client_id, app_data, &request);
660
661    GetKeyCharacteristicsResponse response;
662    convert_device(dev)->impl_->GetKeyCharacteristics(request, &response);
663    if (response.error != KM_ERROR_OK)
664        return response.error;
665
666    *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
667    if (!*characteristics)
668        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
669    return KM_ERROR_OK;
670}
671
672/* static */
673keymaster_error_t SoftKeymasterDevice::import_key(
674    const keymaster1_device_t* dev, const keymaster_key_param_t* params, size_t params_count,
675    keymaster_key_format_t key_format, const uint8_t* key_data, size_t key_data_length,
676    keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
677    if (!params || !key_data)
678        return KM_ERROR_UNEXPECTED_NULL_POINTER;
679
680    if (!key_blob)
681        return KM_ERROR_OUTPUT_PARAMETER_NULL;
682
683    *characteristics = NULL;
684
685    ImportKeyRequest request;
686    request.key_description.Reinitialize(params, params_count);
687    request.key_format = key_format;
688    request.SetKeyMaterial(key_data, key_data_length);
689
690    ImportKeyResponse response;
691    convert_device(dev)->impl_->ImportKey(request, &response);
692    if (response.error != KM_ERROR_OK)
693        return response.error;
694
695    key_blob->key_material_size = response.key_blob.key_material_size;
696    key_blob->key_material = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
697    if (!key_blob->key_material)
698        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
699    memcpy(const_cast<uint8_t*>(key_blob->key_material), response.key_blob.key_material,
700           response.key_blob.key_material_size);
701
702    if (characteristics) {
703        *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
704        if (!*characteristics)
705            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
706    }
707    return KM_ERROR_OK;
708}
709
710/* static */
711keymaster_error_t SoftKeymasterDevice::export_key(
712    const keymaster1_device_t* dev, keymaster_key_format_t export_format,
713    const keymaster_key_blob_t* key_to_export, const keymaster_blob_t* client_id,
714    const keymaster_blob_t* app_data, uint8_t** export_data, size_t* export_data_length) {
715    if (!key_to_export || !key_to_export->key_material)
716        return KM_ERROR_UNEXPECTED_NULL_POINTER;
717
718    if (!export_data || !export_data_length)
719        return KM_ERROR_OUTPUT_PARAMETER_NULL;
720
721    *export_data = NULL;
722    *export_data_length = 0;
723
724    ExportKeyRequest request;
725    request.key_format = export_format;
726    request.SetKeyMaterial(*key_to_export);
727    AddClientAndAppData(client_id, app_data, &request);
728
729    ExportKeyResponse response;
730    convert_device(dev)->impl_->ExportKey(request, &response);
731    if (response.error != KM_ERROR_OK)
732        return response.error;
733
734    *export_data_length = response.key_data_length;
735    *export_data = reinterpret_cast<uint8_t*>(malloc(*export_data_length));
736    if (!export_data)
737        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
738    memcpy(*export_data, response.key_data, *export_data_length);
739    return KM_ERROR_OK;
740}
741
742/* static */
743keymaster_error_t SoftKeymasterDevice::begin(
744    const keymaster1_device_t* dev, keymaster_purpose_t purpose, const keymaster_key_blob_t* key,
745    const keymaster_key_param_t* params, size_t params_count, keymaster_key_param_t** out_params,
746    size_t* out_params_count, keymaster_operation_handle_t* operation_handle) {
747    if (!key || !key->key_material)
748        return KM_ERROR_UNEXPECTED_NULL_POINTER;
749
750    if (!operation_handle || !out_params || !out_params_count)
751        return KM_ERROR_OUTPUT_PARAMETER_NULL;
752
753    *out_params = NULL;
754    *out_params_count = 0;
755
756    BeginOperationRequest request;
757    request.purpose = purpose;
758    request.SetKeyMaterial(*key);
759    request.additional_params.Reinitialize(params, params_count);
760
761    BeginOperationResponse response;
762    convert_device(dev)->impl_->BeginOperation(request, &response);
763    if (response.error != KM_ERROR_OK)
764        return response.error;
765
766    if (response.output_params.size() > 0) {
767        keymaster_key_param_set_t out_params_set;
768        response.output_params.CopyToParamSet(&out_params_set);
769        *out_params = out_params_set.params;
770        *out_params_count = out_params_set.length;
771    }
772
773    *operation_handle = response.op_handle;
774    return KM_ERROR_OK;
775}
776
777/* static */
778keymaster_error_t SoftKeymasterDevice::update(const keymaster1_device_t* dev,
779                                              keymaster_operation_handle_t operation_handle,
780                                              const keymaster_key_param_t* params,
781                                              size_t params_count, const uint8_t* input,
782                                              size_t input_length, size_t* input_consumed,
783                                              uint8_t** output, size_t* output_length) {
784    if (!input)
785        return KM_ERROR_UNEXPECTED_NULL_POINTER;
786
787    if (!input_consumed || !output || !output_length)
788        return KM_ERROR_OUTPUT_PARAMETER_NULL;
789
790    UpdateOperationRequest request;
791    request.op_handle = operation_handle;
792    request.input.Reinitialize(input, input_length);
793    request.additional_params.Reinitialize(params, params_count);
794
795    UpdateOperationResponse response;
796    convert_device(dev)->impl_->UpdateOperation(request, &response);
797    if (response.error != KM_ERROR_OK)
798        return response.error;
799
800    *input_consumed = response.input_consumed;
801    *output_length = response.output.available_read();
802    *output = reinterpret_cast<uint8_t*>(malloc(*output_length));
803    if (!*output)
804        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
805    memcpy(*output, response.output.peek_read(), *output_length);
806    return KM_ERROR_OK;
807}
808
809/* static */
810keymaster_error_t SoftKeymasterDevice::finish(const keymaster1_device_t* dev,
811                                              keymaster_operation_handle_t operation_handle,
812                                              const keymaster_key_param_t* params,
813                                              size_t params_count, const uint8_t* signature,
814                                              size_t signature_length, uint8_t** output,
815                                              size_t* output_length) {
816    if (!output || !output_length)
817        return KM_ERROR_OUTPUT_PARAMETER_NULL;
818
819    FinishOperationRequest request;
820    request.op_handle = operation_handle;
821    if (signature)
822        request.signature.Reinitialize(signature, signature_length);
823    request.additional_params.Reinitialize(params, params_count);
824
825    FinishOperationResponse response;
826    convert_device(dev)->impl_->FinishOperation(request, &response);
827    if (response.error != KM_ERROR_OK)
828        return response.error;
829
830    *output_length = response.output.available_read();
831    *output = reinterpret_cast<uint8_t*>(malloc(*output_length));
832    if (!*output)
833        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
834    memcpy(*output, response.output.peek_read(), *output_length);
835    return KM_ERROR_OK;
836}
837
838/* static */
839keymaster_error_t SoftKeymasterDevice::abort(const keymaster1_device_t* dev,
840                                             keymaster_operation_handle_t operation_handle) {
841    return convert_device(dev)->impl_->AbortOperation(operation_handle);
842}
843
844/* static */
845keymaster_error_t SoftKeymasterDevice::ExtractSigningParams(const keymaster1_device_t* dev,
846                                                            const void* signing_params,
847                                                            const uint8_t* key_blob,
848                                                            size_t key_blob_length,
849                                                            AuthorizationSet* auth_set) {
850    const keymaster_blob_t client_id = {nullptr, 0};
851    const keymaster_blob_t app_data = {nullptr, 0};
852    const keymaster_key_blob_t blob = {key_blob, key_blob_length};
853    keymaster_key_characteristics_t* characteristics;
854    keymaster_error_t error =
855        get_key_characteristics(dev, &blob, &client_id, &app_data, &characteristics);
856
857    if (error != KM_ERROR_OK)
858        return error;
859
860    AuthorizationSet auths(characteristics->hw_enforced);
861    auths.push_back(AuthorizationSet(characteristics->sw_enforced));
862    keymaster_algorithm_t algorithm;
863    if (!auths.GetTagValue(TAG_ALGORITHM, &algorithm))
864        return KM_ERROR_INVALID_KEY_BLOB;
865
866    switch (algorithm) {
867    case KM_ALGORITHM_RSA: {
868        const keymaster_rsa_sign_params_t* rsa_params =
869            reinterpret_cast<const keymaster_rsa_sign_params_t*>(signing_params);
870        if (rsa_params->digest_type != DIGEST_NONE)
871            return KM_ERROR_UNSUPPORTED_DIGEST;
872        if (rsa_params->padding_type != PADDING_NONE)
873            return KM_ERROR_UNSUPPORTED_PADDING_MODE;
874        if (!auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE) ||
875            !auth_set->push_back(TAG_PADDING, KM_PAD_NONE))
876            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
877    } break;
878    case KM_ALGORITHM_EC: {
879        const keymaster_ec_sign_params_t* ecdsa_params =
880            reinterpret_cast<const keymaster_ec_sign_params_t*>(signing_params);
881        if (ecdsa_params->digest_type != DIGEST_NONE)
882            return KM_ERROR_UNSUPPORTED_DIGEST;
883        if (!auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE))
884            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
885    } break;
886    default:
887        return KM_ERROR_UNSUPPORTED_ALGORITHM;
888    }
889    return KM_ERROR_OK;
890}
891
892/* static */
893void SoftKeymasterDevice::StoreDefaultNewKeyParams(AuthorizationSet* auth_set) {
894    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
895    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
896    auth_set->push_back(TAG_ALL_USERS);
897    auth_set->push_back(TAG_NO_AUTH_REQUIRED);
898    uint64_t now = java_time(time(NULL));
899    auth_set->push_back(TAG_CREATION_DATETIME, now);
900    auth_set->push_back(TAG_ORIGINATION_EXPIRE_DATETIME, now + HUNDRED_YEARS);
901    auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE);
902    auth_set->push_back(TAG_PADDING, KM_PAD_NONE);
903}
904
905}  // namespace keymaster
906