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