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