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 <stddef.h>
21#include <stdio.h>
22#include <stdlib.h>
23#include <string.h>
24#include <time.h>
25
26#include <algorithm>
27#include <vector>
28
29#include <type_traits>
30
31#include <openssl/x509.h>
32
33#include <hardware/keymaster1.h>
34#define LOG_TAG "SoftKeymasterDevice"
35#include <cutils/log.h>
36
37#include <keymaster/android_keymaster.h>
38#include <keymaster/android_keymaster_messages.h>
39#include <keymaster/android_keymaster_utils.h>
40#include <keymaster/authorization_set.h>
41#include <keymaster/km_openssl/openssl_utils.h>
42#include <keymaster/contexts/soft_keymaster_context.h>
43#include <keymaster/soft_keymaster_logger.h>
44#include <keymaster/key.h>
45
46
47struct keystore_module soft_keymaster1_device_module = {
48    .common =
49        {
50            .tag = HARDWARE_MODULE_TAG,
51            .module_api_version = KEYMASTER_MODULE_API_VERSION_1_0,
52            .hal_api_version = HARDWARE_HAL_API_VERSION,
53            .id = KEYSTORE_HARDWARE_MODULE_ID,
54            .name = "OpenSSL-based SoftKeymaster HAL",
55            .author = "The Android Open Source Project",
56            .methods = nullptr,
57            .dso = 0,
58            .reserved = {},
59        },
60};
61
62struct keystore_module soft_keymaster2_device_module = {
63    .common =
64        {
65            .tag = HARDWARE_MODULE_TAG,
66            .module_api_version = KEYMASTER_MODULE_API_VERSION_2_0,
67            .hal_api_version = HARDWARE_HAL_API_VERSION,
68            .id = KEYSTORE_HARDWARE_MODULE_ID,
69            .name = "OpenSSL-based SoftKeymaster HAL",
70            .author = "The Android Open Source Project",
71            .methods = nullptr,
72            .dso = 0,
73            .reserved = {},
74        },
75};
76
77namespace keymaster {
78
79const size_t kMaximumAttestationChallengeLength = 128;
80const size_t kOperationTableSize = 16;
81
82template <typename T> std::vector<T> make_vector(const T* array, size_t len) {
83    return std::vector<T>(array, array + len);
84}
85
86// This helper class implements just enough of the C++ standard collection interface to be able to
87// accept push_back calls, and it does nothing but count them.  It's useful when you want to count
88// insertions but not actually store anything.  It's used in digest_set_is_full below to count the
89// size of a set intersection.
90struct PushbackCounter {
91    struct value_type {
92        template <typename T> value_type(const T&) {}
93    };
94    void push_back(const value_type&) { ++count; }
95    size_t count = 0;
96};
97
98static std::vector<keymaster_digest_t> full_digest_list = {
99    KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
100    KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
101
102template <typename Iter> static bool digest_set_is_full(Iter begin, Iter end) {
103    PushbackCounter counter;
104    std::set_intersection(begin, end, full_digest_list.begin(), full_digest_list.end(),
105                          std::back_inserter(counter));
106    return counter.count == full_digest_list.size();
107}
108
109static keymaster_error_t add_digests(keymaster1_device_t* dev, keymaster_algorithm_t algorithm,
110                                     keymaster_purpose_t purpose,
111                                     SoftKeymasterDevice::DigestMap* map, bool* supports_all) {
112    auto key = std::make_pair(algorithm, purpose);
113
114    keymaster_digest_t* digests;
115    size_t digests_length;
116    keymaster_error_t error =
117        dev->get_supported_digests(dev, algorithm, purpose, &digests, &digests_length);
118    if (error != KM_ERROR_OK) {
119        LOG_E("Error %d getting supported digests from keymaster1 device", error);
120        return error;
121    }
122    std::unique_ptr<keymaster_digest_t, Malloc_Delete> digests_deleter(digests);
123
124    auto digest_vec = make_vector(digests, digests_length);
125    *supports_all = digest_set_is_full(digest_vec.begin(), digest_vec.end());
126    (*map)[key] = std::move(digest_vec);
127    return error;
128}
129
130static keymaster_error_t map_digests(keymaster1_device_t* dev, SoftKeymasterDevice::DigestMap* map,
131                                     bool* supports_all) {
132    map->clear();
133    *supports_all = true;
134
135    keymaster_algorithm_t sig_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC, KM_ALGORITHM_HMAC};
136    keymaster_purpose_t sig_purposes[] = {KM_PURPOSE_SIGN, KM_PURPOSE_VERIFY};
137    for (auto algorithm : sig_algorithms)
138        for (auto purpose : sig_purposes) {
139            bool alg_purpose_supports_all;
140            keymaster_error_t error =
141                add_digests(dev, algorithm, purpose, map, &alg_purpose_supports_all);
142            if (error != KM_ERROR_OK)
143                return error;
144            *supports_all &= alg_purpose_supports_all;
145        }
146
147    keymaster_algorithm_t crypt_algorithms[] = {KM_ALGORITHM_RSA};
148    keymaster_purpose_t crypt_purposes[] = {KM_PURPOSE_ENCRYPT, KM_PURPOSE_DECRYPT};
149    for (auto algorithm : crypt_algorithms)
150        for (auto purpose : crypt_purposes) {
151            bool alg_purpose_supports_all;
152            keymaster_error_t error =
153                add_digests(dev, algorithm, purpose, map, &alg_purpose_supports_all);
154            if (error != KM_ERROR_OK)
155                return error;
156            *supports_all &= alg_purpose_supports_all;
157        }
158
159    return KM_ERROR_OK;
160}
161
162SoftKeymasterDevice::SoftKeymasterDevice()
163    : wrapped_km1_device_(nullptr),
164      context_(new SoftKeymasterContext),
165      impl_(new AndroidKeymaster(context_, kOperationTableSize)), configured_(false) {
166    LOG_I("Creating device", 0);
167    LOG_D("Device address: %p", this);
168
169    initialize_device_struct(KEYMASTER_SOFTWARE_ONLY | KEYMASTER_BLOBS_ARE_STANDALONE |
170                             KEYMASTER_SUPPORTS_EC);
171}
172
173SoftKeymasterDevice::SoftKeymasterDevice(SoftKeymasterContext* context)
174    : wrapped_km1_device_(nullptr), context_(context),
175      impl_(new AndroidKeymaster(context_, kOperationTableSize)), configured_(false) {
176    LOG_I("Creating test device", 0);
177    LOG_D("Device address: %p", this);
178
179    initialize_device_struct(KEYMASTER_SOFTWARE_ONLY | KEYMASTER_BLOBS_ARE_STANDALONE |
180                             KEYMASTER_SUPPORTS_EC);
181}
182
183keymaster_error_t SoftKeymasterDevice::SetHardwareDevice(keymaster0_device_t* keymaster0_device) {
184    assert(keymaster0_device);
185    LOG_D("Reinitializing SoftKeymasterDevice to use HW keymaster0", 0);
186
187    if (!context_)
188        return KM_ERROR_UNEXPECTED_NULL_POINTER;
189
190    supports_all_digests_ = false;
191    keymaster_error_t error = context_->SetHardwareDevice(keymaster0_device);
192    if (error != KM_ERROR_OK)
193        return error;
194
195    initialize_device_struct(keymaster0_device->flags);
196
197    module_name_ = km1_device_.common.module->name;
198    module_name_.append("(Wrapping ");
199    module_name_.append(keymaster0_device->common.module->name);
200    module_name_.append(")");
201
202    updated_module_ = *km1_device_.common.module;
203    updated_module_.name = module_name_.c_str();
204
205    km1_device_.common.module = &updated_module_;
206
207    wrapped_km1_device_ = nullptr;
208    return KM_ERROR_OK;
209}
210
211keymaster_error_t SoftKeymasterDevice::SetHardwareDevice(keymaster1_device_t* keymaster1_device) {
212    assert(keymaster1_device);
213    LOG_D("Reinitializing SoftKeymasterDevice to use HW keymaster1", 0);
214
215    if (!context_)
216        return KM_ERROR_UNEXPECTED_NULL_POINTER;
217
218    keymaster_error_t error =
219        map_digests(keymaster1_device, &km1_device_digests_, &supports_all_digests_);
220    if (error != KM_ERROR_OK)
221        return error;
222
223    error = context_->SetHardwareDevice(keymaster1_device);
224    if (error != KM_ERROR_OK)
225        return error;
226
227    initialize_device_struct(keymaster1_device->flags);
228
229    module_name_ = km1_device_.common.module->name;
230    module_name_.append(" (Wrapping ");
231    module_name_.append(keymaster1_device->common.module->name);
232    module_name_.append(")");
233
234    updated_module_ = *km1_device_.common.module;
235    updated_module_.name = module_name_.c_str();
236
237    km1_device_.common.module = &updated_module_;
238
239    wrapped_km1_device_ = keymaster1_device;
240    return KM_ERROR_OK;
241}
242
243bool SoftKeymasterDevice::Keymaster1DeviceIsGood() {
244    std::vector<keymaster_digest_t> expected_rsa_digests = {
245        KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,     KM_DIGEST_SHA_2_224,
246        KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
247    std::vector<keymaster_digest_t> expected_ec_digests = {
248        KM_DIGEST_NONE,      KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
249        KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
250
251    for (auto& entry : km1_device_digests_) {
252        if (entry.first.first == KM_ALGORITHM_RSA)
253            if (!std::is_permutation(entry.second.begin(), entry.second.end(),
254                                     expected_rsa_digests.begin()))
255                return false;
256        if (entry.first.first == KM_ALGORITHM_EC)
257            if (!std::is_permutation(entry.second.begin(), entry.second.end(),
258                                     expected_ec_digests.begin()))
259                return false;
260    }
261    return true;
262}
263
264void SoftKeymasterDevice::initialize_device_struct(uint32_t flags) {
265    memset(&km1_device_, 0, sizeof(km1_device_));
266
267    km1_device_.common.tag = HARDWARE_DEVICE_TAG;
268    km1_device_.common.version = 1;
269    km1_device_.common.module = reinterpret_cast<hw_module_t*>(&soft_keymaster1_device_module);
270    km1_device_.common.close = &close_device;
271
272    km1_device_.flags = flags;
273
274    km1_device_.context = this;
275
276    // keymaster0 APIs
277    km1_device_.generate_keypair = nullptr;
278    km1_device_.import_keypair = nullptr;
279    km1_device_.get_keypair_public = nullptr;
280    km1_device_.delete_keypair = nullptr;
281    km1_device_.delete_all = nullptr;
282    km1_device_.sign_data = nullptr;
283    km1_device_.verify_data = nullptr;
284
285    // keymaster1 APIs
286    km1_device_.get_supported_algorithms = get_supported_algorithms;
287    km1_device_.get_supported_block_modes = get_supported_block_modes;
288    km1_device_.get_supported_padding_modes = get_supported_padding_modes;
289    km1_device_.get_supported_digests = get_supported_digests;
290    km1_device_.get_supported_import_formats = get_supported_import_formats;
291    km1_device_.get_supported_export_formats = get_supported_export_formats;
292    km1_device_.add_rng_entropy = add_rng_entropy;
293    km1_device_.generate_key = generate_key;
294    km1_device_.get_key_characteristics = get_key_characteristics;
295    km1_device_.import_key = import_key;
296    km1_device_.export_key = export_key;
297    km1_device_.delete_key = delete_key;
298    km1_device_.delete_all_keys = delete_all_keys;
299    km1_device_.begin = begin;
300    km1_device_.update = update;
301    km1_device_.finish = finish;
302    km1_device_.abort = abort;
303
304    // keymaster2 APIs
305    memset(&km2_device_, 0, sizeof(km2_device_));
306
307    km2_device_.flags = flags;
308    km2_device_.context = this;
309
310    km2_device_.common.tag = HARDWARE_DEVICE_TAG;
311    km2_device_.common.version = 1;
312    km2_device_.common.module = reinterpret_cast<hw_module_t*>(&soft_keymaster2_device_module);
313    km2_device_.common.close = &close_device;
314
315    km2_device_.configure = configure;
316    km2_device_.add_rng_entropy = add_rng_entropy;
317    km2_device_.generate_key = generate_key;
318    km2_device_.get_key_characteristics = get_key_characteristics;
319    km2_device_.import_key = import_key;
320    km2_device_.export_key = export_key;
321    km2_device_.attest_key = attest_key;
322    km2_device_.upgrade_key = upgrade_key;
323    km2_device_.delete_key = delete_key;
324    km2_device_.delete_all_keys = delete_all_keys;
325    km2_device_.begin = begin;
326    km2_device_.update = update;
327    km2_device_.finish = finish;
328    km2_device_.abort = abort;
329}
330
331hw_device_t* SoftKeymasterDevice::hw_device() {
332    return &km1_device_.common;
333}
334
335keymaster1_device_t* SoftKeymasterDevice::keymaster_device() {
336    return &km1_device_;
337}
338
339keymaster2_device_t* SoftKeymasterDevice::keymaster2_device() {
340    return &km2_device_;
341}
342
343namespace {
344
345keymaster_key_characteristics_t* BuildCharacteristics(const AuthorizationSet& hw_enforced,
346                                                      const AuthorizationSet& sw_enforced) {
347    keymaster_key_characteristics_t* characteristics =
348        reinterpret_cast<keymaster_key_characteristics_t*>(
349            malloc(sizeof(keymaster_key_characteristics_t)));
350    if (characteristics) {
351        hw_enforced.CopyToParamSet(&characteristics->hw_enforced);
352        sw_enforced.CopyToParamSet(&characteristics->sw_enforced);
353    }
354    return characteristics;
355}
356
357template <typename RequestType>
358void AddClientAndAppData(const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
359                         RequestType* request) {
360    request->additional_params.Clear();
361    if (client_id)
362        request->additional_params.push_back(TAG_APPLICATION_ID, *client_id);
363    if (app_data)
364        request->additional_params.push_back(TAG_APPLICATION_DATA, *app_data);
365}
366
367template <typename T> SoftKeymasterDevice* convert_device(const T* dev) {
368    static_assert((std::is_same<T, keymaster0_device_t>::value ||
369                   std::is_same<T, keymaster1_device_t>::value ||
370                   std::is_same<T, keymaster2_device_t>::value),
371                  "convert_device should only be applied to keymaster devices");
372    return reinterpret_cast<SoftKeymasterDevice*>(dev->context);
373}
374
375template <keymaster_tag_t Tag, keymaster_tag_type_t Type, typename KeymasterEnum>
376bool FindTagValue(const keymaster_key_param_set_t& params,
377                  TypedEnumTag<Type, Tag, KeymasterEnum> tag, KeymasterEnum* value) {
378    for (size_t i = 0; i < params.length; ++i)
379        if (params.params[i].tag == tag) {
380            *value = static_cast<KeymasterEnum>(params.params[i].enumerated);
381            return true;
382        }
383    return false;
384}
385
386}  // unnamed namespaced
387
388/* static */
389int SoftKeymasterDevice::close_device(hw_device_t* dev) {
390    switch (dev->module->module_api_version) {
391    case KEYMASTER_MODULE_API_VERSION_2_0: {
392        delete convert_device(reinterpret_cast<keymaster2_device_t*>(dev));
393        break;
394    }
395
396    case KEYMASTER_MODULE_API_VERSION_1_0: {
397        delete convert_device(reinterpret_cast<keymaster1_device_t*>(dev));
398        break;
399    }
400
401    default:
402        return -1;
403    }
404
405    return 0;
406}
407
408/* static */
409keymaster_error_t SoftKeymasterDevice::get_supported_algorithms(const keymaster1_device_t* dev,
410                                                                keymaster_algorithm_t** algorithms,
411                                                                size_t* algorithms_length) {
412    if (!dev)
413        return KM_ERROR_UNEXPECTED_NULL_POINTER;
414
415    if (!algorithms || !algorithms_length)
416        return KM_ERROR_OUTPUT_PARAMETER_NULL;
417
418    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
419    if (km1_dev)
420        return km1_dev->get_supported_algorithms(km1_dev, algorithms, algorithms_length);
421
422    SupportedAlgorithmsRequest request;
423    SupportedAlgorithmsResponse response;
424    convert_device(dev)->impl_->SupportedAlgorithms(request, &response);
425    if (response.error != KM_ERROR_OK) {
426        LOG_E("get_supported_algorithms failed with %d", response.error);
427
428        return response.error;
429    }
430
431    *algorithms_length = response.results_length;
432    *algorithms =
433        reinterpret_cast<keymaster_algorithm_t*>(malloc(*algorithms_length * sizeof(**algorithms)));
434    if (!*algorithms)
435        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
436    std::copy(response.results, response.results + response.results_length, *algorithms);
437    return KM_ERROR_OK;
438}
439
440/* static */
441keymaster_error_t SoftKeymasterDevice::get_supported_block_modes(const keymaster1_device_t* dev,
442                                                                 keymaster_algorithm_t algorithm,
443                                                                 keymaster_purpose_t purpose,
444                                                                 keymaster_block_mode_t** modes,
445                                                                 size_t* modes_length) {
446    if (!dev)
447        return KM_ERROR_UNEXPECTED_NULL_POINTER;
448
449    if (!modes || !modes_length)
450        return KM_ERROR_OUTPUT_PARAMETER_NULL;
451
452    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
453    if (km1_dev)
454        return km1_dev->get_supported_block_modes(km1_dev, algorithm, purpose, modes, modes_length);
455
456    SupportedBlockModesRequest request;
457    request.algorithm = algorithm;
458    request.purpose = purpose;
459    SupportedBlockModesResponse response;
460    convert_device(dev)->impl_->SupportedBlockModes(request, &response);
461
462    if (response.error != KM_ERROR_OK) {
463        LOG_E("get_supported_block_modes failed with %d", response.error);
464
465        return response.error;
466    }
467
468    *modes_length = response.results_length;
469    *modes = reinterpret_cast<keymaster_block_mode_t*>(malloc(*modes_length * sizeof(**modes)));
470    if (!*modes)
471        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
472    std::copy(response.results, response.results + response.results_length, *modes);
473    return KM_ERROR_OK;
474}
475
476/* static */
477keymaster_error_t SoftKeymasterDevice::get_supported_padding_modes(const keymaster1_device_t* dev,
478                                                                   keymaster_algorithm_t algorithm,
479                                                                   keymaster_purpose_t purpose,
480                                                                   keymaster_padding_t** modes,
481                                                                   size_t* modes_length) {
482    if (!dev)
483        return KM_ERROR_UNEXPECTED_NULL_POINTER;
484
485    if (!modes || !modes_length)
486        return KM_ERROR_OUTPUT_PARAMETER_NULL;
487
488    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
489    if (km1_dev)
490        return km1_dev->get_supported_padding_modes(km1_dev, algorithm, purpose, modes,
491                                                    modes_length);
492
493    SupportedPaddingModesRequest request;
494    request.algorithm = algorithm;
495    request.purpose = purpose;
496    SupportedPaddingModesResponse response;
497    convert_device(dev)->impl_->SupportedPaddingModes(request, &response);
498
499    if (response.error != KM_ERROR_OK) {
500        LOG_E("get_supported_padding_modes failed with %d", response.error);
501        return response.error;
502    }
503
504    *modes_length = response.results_length;
505    *modes = reinterpret_cast<keymaster_padding_t*>(malloc(*modes_length * sizeof(**modes)));
506    if (!*modes)
507        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
508    std::copy(response.results, response.results + response.results_length, *modes);
509    return KM_ERROR_OK;
510}
511
512/* static */
513keymaster_error_t SoftKeymasterDevice::get_supported_digests(const keymaster1_device_t* dev,
514                                                             keymaster_algorithm_t algorithm,
515                                                             keymaster_purpose_t purpose,
516                                                             keymaster_digest_t** digests,
517                                                             size_t* digests_length) {
518    if (!dev)
519        return KM_ERROR_UNEXPECTED_NULL_POINTER;
520
521    if (!digests || !digests_length)
522        return KM_ERROR_OUTPUT_PARAMETER_NULL;
523
524    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
525    if (km1_dev)
526        return km1_dev->get_supported_digests(km1_dev, algorithm, purpose, digests, digests_length);
527
528    SupportedDigestsRequest request;
529    request.algorithm = algorithm;
530    request.purpose = purpose;
531    SupportedDigestsResponse response;
532    convert_device(dev)->impl_->SupportedDigests(request, &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    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
558    if (km1_dev)
559        return km1_dev->get_supported_import_formats(km1_dev, algorithm, formats, formats_length);
560
561    SupportedImportFormatsRequest request;
562    request.algorithm = algorithm;
563    SupportedImportFormatsResponse response;
564    convert_device(dev)->impl_->SupportedImportFormats(request, &response);
565
566    if (response.error != KM_ERROR_OK) {
567        LOG_E("get_supported_import_formats failed with %d", response.error);
568        return response.error;
569    }
570
571    *formats_length = response.results_length;
572    *formats =
573        reinterpret_cast<keymaster_key_format_t*>(malloc(*formats_length * sizeof(**formats)));
574    if (!*formats)
575        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
576    std::copy(response.results, response.results + response.results_length, *formats);
577    return KM_ERROR_OK;
578}
579
580/* static */
581keymaster_error_t SoftKeymasterDevice::get_supported_export_formats(
582    const keymaster1_device_t* dev, keymaster_algorithm_t algorithm,
583    keymaster_key_format_t** formats, size_t* formats_length) {
584    if (!dev)
585        return KM_ERROR_UNEXPECTED_NULL_POINTER;
586
587    if (!formats || !formats_length)
588        return KM_ERROR_OUTPUT_PARAMETER_NULL;
589
590    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
591    if (km1_dev)
592        return km1_dev->get_supported_export_formats(km1_dev, algorithm, formats, formats_length);
593
594    SupportedExportFormatsRequest request;
595    request.algorithm = algorithm;
596    SupportedExportFormatsResponse response;
597    convert_device(dev)->impl_->SupportedExportFormats(request, &response);
598
599    if (response.error != KM_ERROR_OK) {
600        LOG_E("get_supported_export_formats failed with %d", response.error);
601        return response.error;
602    }
603
604    *formats_length = response.results_length;
605    *formats =
606        reinterpret_cast<keymaster_key_format_t*>(malloc(*formats_length * sizeof(**formats)));
607    if (!*formats)
608        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
609    std::copy(response.results, response.results + *formats_length, *formats);
610    return KM_ERROR_OK;
611}
612
613/* static */
614keymaster_error_t SoftKeymasterDevice::configure(const keymaster2_device_t* dev,
615                                                 const keymaster_key_param_set_t* params) {
616    AuthorizationSet params_copy(*params);
617    ConfigureRequest request;
618    if (!params_copy.GetTagValue(TAG_OS_VERSION, &request.os_version) ||
619        !params_copy.GetTagValue(TAG_OS_PATCHLEVEL, &request.os_patchlevel)) {
620        LOG_E("Configuration parameters must contain OS version and patch level", 0);
621        return KM_ERROR_INVALID_ARGUMENT;
622    }
623    ConfigureResponse response;
624    convert_device(dev)->impl_->Configure(request, &response);
625    if (response.error == KM_ERROR_OK)
626        convert_device(dev)->configured_ = true;
627    return response.error;
628}
629
630/* static */
631keymaster_error_t SoftKeymasterDevice::add_rng_entropy(const keymaster1_device_t* dev,
632                                                       const uint8_t* data, size_t data_length) {
633    if (!dev)
634        return KM_ERROR_UNEXPECTED_NULL_POINTER;
635
636    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
637    if (km1_dev)
638        return km1_dev->add_rng_entropy(km1_dev, data, data_length);
639
640    AddEntropyRequest request;
641    request.random_data.Reinitialize(data, data_length);
642    AddEntropyResponse response;
643    convert_device(dev)->impl_->AddRngEntropy(request, &response);
644    if (response.error != KM_ERROR_OK)
645        LOG_E("add_rng_entropy failed with %d", response.error);
646    return response.error;
647}
648
649/* static */
650keymaster_error_t SoftKeymasterDevice::add_rng_entropy(const keymaster2_device_t* dev,
651                                                       const uint8_t* data, size_t data_length) {
652    if (!dev)
653        return KM_ERROR_UNEXPECTED_NULL_POINTER;
654
655    if (!convert_device(dev)->configured())
656        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
657
658    SoftKeymasterDevice* sk_dev = convert_device(dev);
659    return add_rng_entropy(&sk_dev->km1_device_, data, data_length);
660}
661
662template <typename Collection, typename Value> bool contains(const Collection& c, const Value& v) {
663    return std::find(c.begin(), c.end(), v) != c.end();
664}
665
666bool SoftKeymasterDevice::FindUnsupportedDigest(keymaster_algorithm_t algorithm,
667                                                keymaster_purpose_t purpose,
668                                                const AuthorizationSet& params,
669                                                keymaster_digest_t* unsupported) const {
670    assert(wrapped_km1_device_);
671
672    auto supported_digests = km1_device_digests_.find(std::make_pair(algorithm, purpose));
673    if (supported_digests == km1_device_digests_.end())
674        // Invalid algorith/purpose pair (e.g. EC encrypt).  Let the error be handled by HW module.
675        return false;
676
677    for (auto& entry : params)
678        if (entry.tag == TAG_DIGEST)
679            if (!contains(supported_digests->second, entry.enumerated)) {
680                LOG_I("Digest %d requested but not supported by module %s", entry.enumerated,
681                      wrapped_km1_device_->common.module->name);
682                *unsupported = static_cast<keymaster_digest_t>(entry.enumerated);
683                return true;
684            }
685    return false;
686}
687
688bool SoftKeymasterDevice::RequiresSoftwareDigesting(keymaster_algorithm_t algorithm,
689                                                    keymaster_purpose_t purpose,
690                                                    const AuthorizationSet& params) const {
691    assert(wrapped_km1_device_);
692    if (!wrapped_km1_device_)
693        return true;
694
695    switch (algorithm) {
696    case KM_ALGORITHM_AES:
697    case KM_ALGORITHM_TRIPLE_DES:
698        LOG_D("Not performing software digesting for algorithm %d", algorithm);
699        return false;
700    case KM_ALGORITHM_HMAC:
701    case KM_ALGORITHM_RSA:
702    case KM_ALGORITHM_EC:
703        break;
704    }
705
706    keymaster_digest_t unsupported;
707    if (!FindUnsupportedDigest(algorithm, purpose, params, &unsupported)) {
708        LOG_D("Requested digest(s) supported for algorithm %d and purpose %d", algorithm, purpose);
709        return false;
710    }
711
712    return true;
713}
714
715bool SoftKeymasterDevice::KeyRequiresSoftwareDigesting(
716    const AuthorizationSet& key_description) const {
717    assert(wrapped_km1_device_);
718    if (!wrapped_km1_device_)
719        return true;
720
721    keymaster_algorithm_t algorithm;
722    if (!key_description.GetTagValue(TAG_ALGORITHM, &algorithm)) {
723        // The hardware module will return an error during keygen.
724        return false;
725    }
726
727    for (auto& entry : key_description)
728        if (entry.tag == TAG_PURPOSE) {
729            keymaster_purpose_t purpose = static_cast<keymaster_purpose_t>(entry.enumerated);
730            if (RequiresSoftwareDigesting(algorithm, purpose, key_description))
731                return true;
732        }
733
734    return false;
735}
736
737/* static */
738keymaster_error_t SoftKeymasterDevice::generate_key(
739    const keymaster1_device_t* dev, const keymaster_key_param_set_t* params,
740    keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
741    if (!dev || !params)
742        return KM_ERROR_UNEXPECTED_NULL_POINTER;
743
744    if (!key_blob)
745        return KM_ERROR_OUTPUT_PARAMETER_NULL;
746
747    SoftKeymasterDevice* sk_dev = convert_device(dev);
748
749    GenerateKeyRequest request;
750    request.key_description.Reinitialize(*params);
751
752    keymaster1_device_t* km1_dev = sk_dev->wrapped_km1_device_;
753    if (km1_dev && !sk_dev->KeyRequiresSoftwareDigesting(request.key_description))
754        return km1_dev->generate_key(km1_dev, params, key_blob, characteristics);
755
756    GenerateKeyResponse response;
757    sk_dev->impl_->GenerateKey(request, &response);
758    if (response.error != KM_ERROR_OK)
759        return response.error;
760
761    key_blob->key_material_size = response.key_blob.key_material_size;
762    uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
763    if (!tmp)
764        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
765    memcpy(tmp, response.key_blob.key_material, response.key_blob.key_material_size);
766    key_blob->key_material = tmp;
767
768    if (characteristics) {
769        // This is a keymaster1 method, and keymaster1 doesn't include version info, so remove it.
770        response.enforced.erase(response.enforced.find(TAG_OS_VERSION));
771        response.enforced.erase(response.enforced.find(TAG_OS_PATCHLEVEL));
772        response.unenforced.erase(response.unenforced.find(TAG_OS_VERSION));
773        response.unenforced.erase(response.unenforced.find(TAG_OS_PATCHLEVEL));
774
775        *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
776        if (!*characteristics)
777            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
778    }
779
780    return KM_ERROR_OK;
781}
782
783keymaster_error_t
784SoftKeymasterDevice::generate_key(const keymaster2_device_t* dev,  //
785                                  const keymaster_key_param_set_t* params,
786                                  keymaster_key_blob_t* key_blob,
787                                  keymaster_key_characteristics_t* characteristics) {
788    if (!dev)
789        return KM_ERROR_UNEXPECTED_NULL_POINTER;
790
791    if (!convert_device(dev)->configured())
792        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
793
794    if (!key_blob)
795        return KM_ERROR_OUTPUT_PARAMETER_NULL;
796
797    SoftKeymasterDevice* sk_dev = convert_device(dev);
798
799    GenerateKeyRequest request;
800    request.key_description.Reinitialize(*params);
801
802    keymaster1_device_t* km1_dev = sk_dev->wrapped_km1_device_;
803    if (km1_dev && !sk_dev->KeyRequiresSoftwareDigesting(request.key_description)) {
804        keymaster_ec_curve_t curve;
805        if (request.key_description.Contains(TAG_ALGORITHM, KM_ALGORITHM_EC) &&
806            request.key_description.GetTagValue(TAG_EC_CURVE, &curve)) {
807            // Keymaster1 doesn't know about EC curves. We need to translate to key size.
808            uint32_t key_size_from_curve;
809            keymaster_error_t error = EcCurveToKeySize(curve, &key_size_from_curve);
810            if (error != KM_ERROR_OK) {
811                return error;
812            }
813
814            uint32_t key_size_from_desc;
815            if (request.key_description.GetTagValue(TAG_KEY_SIZE, &key_size_from_desc)) {
816                if (key_size_from_desc != key_size_from_curve) {
817                    return KM_ERROR_INVALID_ARGUMENT;
818                }
819            } else {
820                request.key_description.push_back(TAG_KEY_SIZE, key_size_from_curve);
821            }
822        }
823
824        keymaster_key_characteristics_t* chars_ptr;
825        keymaster_error_t error = km1_dev->generate_key(km1_dev, &request.key_description, key_blob,
826                                                        characteristics ? &chars_ptr : nullptr);
827        if (error != KM_ERROR_OK)
828            return error;
829
830        if (characteristics) {
831            *characteristics = *chars_ptr;
832            free(chars_ptr);
833        }
834
835        return KM_ERROR_OK;
836    }
837
838    GenerateKeyResponse response;
839    sk_dev->impl_->GenerateKey(request, &response);
840    if (response.error != KM_ERROR_OK)
841        return response.error;
842
843    key_blob->key_material_size = response.key_blob.key_material_size;
844    uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
845    if (!tmp)
846        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
847    memcpy(tmp, response.key_blob.key_material, response.key_blob.key_material_size);
848    key_blob->key_material = tmp;
849
850    if (characteristics) {
851        response.enforced.CopyToParamSet(&characteristics->hw_enforced);
852        response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
853    }
854
855    return KM_ERROR_OK;
856}
857
858/* static */
859keymaster_error_t SoftKeymasterDevice::get_key_characteristics(
860    const keymaster1_device_t* dev, const keymaster_key_blob_t* key_blob,
861    const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
862    keymaster_key_characteristics_t** characteristics) {
863    if (!dev || !key_blob || !key_blob->key_material)
864        return KM_ERROR_UNEXPECTED_NULL_POINTER;
865
866    if (!characteristics)
867        return KM_ERROR_OUTPUT_PARAMETER_NULL;
868
869    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
870    if (km1_dev) {
871        keymaster_error_t error = km1_dev->get_key_characteristics(km1_dev, key_blob, client_id,
872                                                                   app_data, characteristics);
873        if (error != KM_ERROR_INVALID_KEY_BLOB) {
874            return error;
875        }
876        // If we got "invalid blob", continue to try with the software device. This might be a
877        // software key blob.
878    }
879
880    GetKeyCharacteristicsRequest request;
881    request.SetKeyMaterial(*key_blob);
882    AddClientAndAppData(client_id, app_data, &request);
883
884    GetKeyCharacteristicsResponse response;
885    convert_device(dev)->impl_->GetKeyCharacteristics(request, &response);
886    if (response.error != KM_ERROR_OK)
887        return response.error;
888
889    // This is a keymaster1 method, and keymaster1 doesn't include version info, so remove it.
890    response.enforced.erase(response.enforced.find(TAG_OS_VERSION));
891    response.enforced.erase(response.enforced.find(TAG_OS_PATCHLEVEL));
892    response.unenforced.erase(response.unenforced.find(TAG_OS_VERSION));
893    response.unenforced.erase(response.unenforced.find(TAG_OS_PATCHLEVEL));
894
895    *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
896    if (!*characteristics)
897        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
898
899    return KM_ERROR_OK;
900}
901
902/* static */
903keymaster_error_t SoftKeymasterDevice::get_key_characteristics(
904    const keymaster2_device_t* dev, const keymaster_key_blob_t* key_blob,
905    const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
906    keymaster_key_characteristics_t* characteristics) {
907    if (!dev)
908        return KM_ERROR_UNEXPECTED_NULL_POINTER;
909
910    if (!convert_device(dev)->configured())
911        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
912
913    if (!characteristics)
914        return KM_ERROR_OUTPUT_PARAMETER_NULL;
915
916    SoftKeymasterDevice* sk_dev = convert_device(dev);
917
918    GetKeyCharacteristicsRequest request;
919    request.SetKeyMaterial(*key_blob);
920    AddClientAndAppData(client_id, app_data, &request);
921
922    GetKeyCharacteristicsResponse response;
923    sk_dev->impl_->GetKeyCharacteristics(request, &response);
924    if (response.error != KM_ERROR_OK)
925        return response.error;
926
927    response.enforced.CopyToParamSet(&characteristics->hw_enforced);
928    response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
929
930    return KM_ERROR_OK;
931}
932
933/* static */
934keymaster_error_t SoftKeymasterDevice::import_key(
935    const keymaster1_device_t* dev, const keymaster_key_param_set_t* params,
936    keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
937    keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
938    if (!params || !key_data)
939        return KM_ERROR_UNEXPECTED_NULL_POINTER;
940
941    if (!key_blob)
942        return KM_ERROR_OUTPUT_PARAMETER_NULL;
943
944    SoftKeymasterDevice* sk_dev = convert_device(dev);
945
946    ImportKeyRequest request;
947    request.key_description.Reinitialize(*params);
948
949    keymaster1_device_t* km1_dev = sk_dev->wrapped_km1_device_;
950    if (km1_dev && !sk_dev->KeyRequiresSoftwareDigesting(request.key_description))
951        return km1_dev->import_key(km1_dev, params, key_format, key_data, key_blob,
952                                   characteristics);
953
954    if (characteristics)
955        *characteristics = nullptr;
956
957    request.key_format = key_format;
958    request.SetKeyMaterial(key_data->data, key_data->data_length);
959
960    ImportKeyResponse response;
961    convert_device(dev)->impl_->ImportKey(request, &response);
962    if (response.error != KM_ERROR_OK)
963        return response.error;
964
965    key_blob->key_material_size = response.key_blob.key_material_size;
966    key_blob->key_material = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
967    if (!key_blob->key_material)
968        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
969    memcpy(const_cast<uint8_t*>(key_blob->key_material), response.key_blob.key_material,
970           response.key_blob.key_material_size);
971
972    if (characteristics) {
973        *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
974        if (!*characteristics)
975            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
976    }
977    return KM_ERROR_OK;
978}
979
980/* static */
981keymaster_error_t SoftKeymasterDevice::import_key(
982    const keymaster2_device_t* dev, const keymaster_key_param_set_t* params,
983    keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
984    keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t* characteristics) {
985    if (!dev)
986        return KM_ERROR_UNEXPECTED_NULL_POINTER;
987
988    if (!convert_device(dev)->configured())
989        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
990
991    SoftKeymasterDevice* sk_dev = convert_device(dev);
992
993    keymaster_error_t error;
994    if (characteristics) {
995        keymaster_key_characteristics_t* characteristics_ptr;
996        error = import_key(&sk_dev->km1_device_, params, key_format, key_data, key_blob,
997                           &characteristics_ptr);
998        if (error == KM_ERROR_OK) {
999            *characteristics = *characteristics_ptr;
1000            free(characteristics_ptr);
1001        }
1002    } else {
1003        error = import_key(&sk_dev->km1_device_, params, key_format, key_data, key_blob, nullptr);
1004    }
1005
1006    return error;
1007}
1008
1009/* static */
1010keymaster_error_t SoftKeymasterDevice::export_key(const keymaster1_device_t* dev,
1011                                                  keymaster_key_format_t export_format,
1012                                                  const keymaster_key_blob_t* key_to_export,
1013                                                  const keymaster_blob_t* client_id,
1014                                                  const keymaster_blob_t* app_data,
1015                                                  keymaster_blob_t* export_data) {
1016    if (!key_to_export || !key_to_export->key_material)
1017        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1018
1019    if (!export_data)
1020        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1021
1022    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1023    if (km1_dev)
1024        return km1_dev->export_key(km1_dev, export_format, key_to_export, client_id, app_data,
1025                                   export_data);
1026
1027    export_data->data = nullptr;
1028    export_data->data_length = 0;
1029
1030    ExportKeyRequest request;
1031    request.key_format = export_format;
1032    request.SetKeyMaterial(*key_to_export);
1033    AddClientAndAppData(client_id, app_data, &request);
1034
1035    ExportKeyResponse response;
1036    convert_device(dev)->impl_->ExportKey(request, &response);
1037    if (response.error != KM_ERROR_OK)
1038        return response.error;
1039
1040    export_data->data_length = response.key_data_length;
1041    uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(export_data->data_length));
1042    if (!tmp)
1043        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1044    memcpy(tmp, response.key_data, export_data->data_length);
1045    export_data->data = tmp;
1046    return KM_ERROR_OK;
1047}
1048
1049/* static */
1050keymaster_error_t SoftKeymasterDevice::export_key(const keymaster2_device_t* dev,
1051                                                  keymaster_key_format_t export_format,
1052                                                  const keymaster_key_blob_t* key_to_export,
1053                                                  const keymaster_blob_t* client_id,
1054                                                  const keymaster_blob_t* app_data,
1055                                                  keymaster_blob_t* export_data) {
1056    if (!dev)
1057        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1058
1059    if (!convert_device(dev)->configured())
1060        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1061
1062    SoftKeymasterDevice* sk_dev = convert_device(dev);
1063    return export_key(&sk_dev->km1_device_, export_format, key_to_export, client_id, app_data,
1064                      export_data);
1065}
1066
1067/* static */
1068keymaster_error_t SoftKeymasterDevice::attest_key(const keymaster2_device_t* dev,
1069                                                  const keymaster_key_blob_t* key_to_attest,
1070                                                  const keymaster_key_param_set_t* attest_params,
1071                                                  keymaster_cert_chain_t* cert_chain) {
1072    if (!dev || !key_to_attest || !attest_params || !cert_chain)
1073        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1074
1075    if (!convert_device(dev)->configured())
1076        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1077
1078    *cert_chain = {};
1079
1080    AttestKeyRequest request;
1081    request.SetKeyMaterial(*key_to_attest);
1082    request.attest_params.Reinitialize(*attest_params);
1083
1084    keymaster_blob_t attestation_challenge = {};
1085    request.attest_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge);
1086    if (attestation_challenge.data_length > kMaximumAttestationChallengeLength) {
1087        LOG_E("%d-byte attestation challenge; only %d bytes allowed",
1088              attestation_challenge.data_length, kMaximumAttestationChallengeLength);
1089        return KM_ERROR_INVALID_INPUT_LENGTH;
1090    }
1091
1092    AttestKeyResponse response;
1093    convert_device(dev)->impl_->AttestKey(request, &response);
1094    if (response.error != KM_ERROR_OK)
1095        return response.error;
1096
1097    // Allocate and clear storage for cert_chain.
1098    keymaster_cert_chain_t& rsp_chain = response.certificate_chain;
1099    cert_chain->entries = reinterpret_cast<keymaster_blob_t*>(
1100        malloc(rsp_chain.entry_count * sizeof(*cert_chain->entries)));
1101    if (!cert_chain->entries)
1102        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1103    cert_chain->entry_count = rsp_chain.entry_count;
1104    for (keymaster_blob_t& entry : array_range(cert_chain->entries, cert_chain->entry_count))
1105        entry = {};
1106
1107    // Copy cert_chain contents
1108    size_t i = 0;
1109    for (keymaster_blob_t& entry : array_range(rsp_chain.entries, rsp_chain.entry_count)) {
1110        cert_chain->entries[i].data = reinterpret_cast<uint8_t*>(malloc(entry.data_length));
1111        if (!cert_chain->entries[i].data) {
1112            keymaster_free_cert_chain(cert_chain);
1113            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1114        }
1115        cert_chain->entries[i].data_length = entry.data_length;
1116        memcpy(const_cast<uint8_t*>(cert_chain->entries[i].data), entry.data, entry.data_length);
1117        ++i;
1118    }
1119
1120    return KM_ERROR_OK;
1121}
1122
1123/* static */
1124keymaster_error_t SoftKeymasterDevice::upgrade_key(const keymaster2_device_t* dev,
1125                                                   const keymaster_key_blob_t* key_to_upgrade,
1126                                                   const keymaster_key_param_set_t* upgrade_params,
1127                                                   keymaster_key_blob_t* upgraded_key) {
1128    if (!dev || !key_to_upgrade || !upgrade_params)
1129        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1130
1131    if (!upgraded_key)
1132        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1133
1134    if (!convert_device(dev)->configured())
1135        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1136
1137    UpgradeKeyRequest request;
1138    request.SetKeyMaterial(*key_to_upgrade);
1139    request.upgrade_params.Reinitialize(*upgrade_params);
1140
1141    UpgradeKeyResponse response;
1142    convert_device(dev)->impl_->UpgradeKey(request, &response);
1143    if (response.error != KM_ERROR_OK)
1144        return response.error;
1145
1146    upgraded_key->key_material_size = response.upgraded_key.key_material_size;
1147    uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(upgraded_key->key_material_size));
1148    if (!tmp)
1149        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1150    memcpy(tmp, response.upgraded_key.key_material, response.upgraded_key.key_material_size);
1151    upgraded_key->key_material = tmp;
1152
1153    return KM_ERROR_OK;
1154}
1155
1156/* static */
1157keymaster_error_t SoftKeymasterDevice::delete_key(const keymaster1_device_t* dev,
1158                                                  const keymaster_key_blob_t* key) {
1159    if (!dev || !key || !key->key_material)
1160        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1161
1162    KeymasterKeyBlob blob(*key);
1163    return convert_device(dev)->context_->DeleteKey(blob);
1164}
1165
1166/* static */
1167keymaster_error_t SoftKeymasterDevice::delete_key(const keymaster2_device_t* dev,
1168                                                  const keymaster_key_blob_t* key) {
1169    if (!dev || !key || !key->key_material)
1170        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1171
1172    if (!convert_device(dev)->configured())
1173        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1174
1175    KeymasterKeyBlob blob(*key);
1176    return convert_device(dev)->context_->DeleteKey(blob);
1177}
1178
1179/* static */
1180keymaster_error_t SoftKeymasterDevice::delete_all_keys(const keymaster1_device_t* dev) {
1181    if (!dev)
1182        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1183
1184    return convert_device(dev)->context_->DeleteAllKeys();
1185}
1186
1187/* static */
1188keymaster_error_t SoftKeymasterDevice::delete_all_keys(const keymaster2_device_t* dev) {
1189    if (!dev)
1190        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1191
1192    if (!convert_device(dev)->configured())
1193        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1194
1195    return convert_device(dev)->context_->DeleteAllKeys();
1196}
1197
1198/* static */
1199keymaster_error_t SoftKeymasterDevice::begin(const keymaster1_device_t* dev,
1200                                             keymaster_purpose_t purpose,
1201                                             const keymaster_key_blob_t* key,
1202                                             const keymaster_key_param_set_t* in_params,
1203                                             keymaster_key_param_set_t* out_params,
1204                                             keymaster_operation_handle_t* operation_handle) {
1205    if (!dev || !key || !key->key_material)
1206        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1207
1208    if (!operation_handle)
1209        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1210
1211    SoftKeymasterDevice* skdev = convert_device(dev);
1212    const keymaster1_device_t* km1_dev = skdev->wrapped_km1_device_;
1213
1214    if (km1_dev) {
1215        AuthorizationSet in_params_set(*in_params);
1216
1217        UniquePtr<Key> akmKey; // android keymaster key
1218        skdev->context_->ParseKeyBlob(KeymasterKeyBlob(*key), in_params_set, &akmKey);
1219
1220        keymaster_algorithm_t algorithm = KM_ALGORITHM_AES;
1221        if (!akmKey->hw_enforced().GetTagValue(TAG_ALGORITHM, &algorithm) &&
1222            !akmKey->sw_enforced().GetTagValue(TAG_ALGORITHM, &algorithm)) {
1223            return KM_ERROR_INVALID_KEY_BLOB;
1224        }
1225
1226        if (algorithm == KM_ALGORITHM_HMAC) {
1227            // Because HMAC keys can have only one digest, in_params_set doesn't contain it.  We
1228            // need to get the digest from the key and add it to in_params_set.
1229            keymaster_digest_t digest;
1230            if (!akmKey->hw_enforced().GetTagValue(TAG_DIGEST, &digest) &&
1231                !akmKey->sw_enforced().GetTagValue(TAG_DIGEST, &digest)) {
1232                return KM_ERROR_INVALID_KEY_BLOB;
1233            }
1234            in_params_set.push_back(TAG_DIGEST, digest);
1235        }
1236
1237        if (!skdev->RequiresSoftwareDigesting(algorithm, purpose, in_params_set)) {
1238            LOG_D("Operation supported by %s, passing through to keymaster1 module",
1239                  km1_dev->common.module->name);
1240            return km1_dev->begin(km1_dev, purpose, key, in_params, out_params, operation_handle);
1241        }
1242        LOG_I("Doing software digesting for keymaster1 module %s", km1_dev->common.module->name);
1243    }
1244
1245    if (out_params) {
1246        out_params->params = nullptr;
1247        out_params->length = 0;
1248    }
1249
1250    BeginOperationRequest request;
1251    request.purpose = purpose;
1252    request.SetKeyMaterial(*key);
1253    request.additional_params.Reinitialize(*in_params);
1254
1255    BeginOperationResponse response;
1256    skdev->impl_->BeginOperation(request, &response);
1257    if (response.error != KM_ERROR_OK)
1258        return response.error;
1259
1260    if (response.output_params.size() > 0) {
1261        if (out_params)
1262            response.output_params.CopyToParamSet(out_params);
1263        else
1264            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1265    }
1266
1267    *operation_handle = response.op_handle;
1268    return KM_ERROR_OK;
1269}
1270
1271/* static */
1272keymaster_error_t SoftKeymasterDevice::begin(const keymaster2_device_t* dev,
1273                                             keymaster_purpose_t purpose,
1274                                             const keymaster_key_blob_t* key,
1275                                             const keymaster_key_param_set_t* in_params,
1276                                             keymaster_key_param_set_t* out_params,
1277                                             keymaster_operation_handle_t* operation_handle) {
1278    if (!dev)
1279        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1280
1281    if (!convert_device(dev)->configured())
1282        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1283
1284    SoftKeymasterDevice* sk_dev = convert_device(dev);
1285    return begin(&sk_dev->km1_device_, purpose, key, in_params, out_params, operation_handle);
1286}
1287
1288/* static */
1289keymaster_error_t SoftKeymasterDevice::update(const keymaster1_device_t* dev,
1290                                              keymaster_operation_handle_t operation_handle,
1291                                              const keymaster_key_param_set_t* in_params,
1292                                              const keymaster_blob_t* input, size_t* input_consumed,
1293                                              keymaster_key_param_set_t* out_params,
1294                                              keymaster_blob_t* output) {
1295    if (!input)
1296        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1297
1298    if (!input_consumed)
1299        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1300
1301    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1302    if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1303        // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1304        // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1305        // km1_dev after doing necessary digesting.
1306        return km1_dev->update(km1_dev, operation_handle, in_params, input, input_consumed,
1307                               out_params, output);
1308    }
1309
1310    if (out_params) {
1311        out_params->params = nullptr;
1312        out_params->length = 0;
1313    }
1314    if (output) {
1315        output->data = nullptr;
1316        output->data_length = 0;
1317    }
1318
1319    UpdateOperationRequest request;
1320    request.op_handle = operation_handle;
1321    if (input)
1322        request.input.Reinitialize(input->data, input->data_length);
1323    if (in_params)
1324        request.additional_params.Reinitialize(*in_params);
1325
1326    UpdateOperationResponse response;
1327    convert_device(dev)->impl_->UpdateOperation(request, &response);
1328    if (response.error != KM_ERROR_OK)
1329        return response.error;
1330
1331    if (response.output_params.size() > 0) {
1332        if (out_params)
1333            response.output_params.CopyToParamSet(out_params);
1334        else
1335            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1336    }
1337
1338    *input_consumed = response.input_consumed;
1339    if (output) {
1340        output->data_length = response.output.available_read();
1341        uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1342        if (!tmp)
1343            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1344        memcpy(tmp, response.output.peek_read(), output->data_length);
1345        output->data = tmp;
1346    } else if (response.output.available_read() > 0) {
1347        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1348    }
1349    return KM_ERROR_OK;
1350}
1351
1352/* static */
1353keymaster_error_t SoftKeymasterDevice::update(const keymaster2_device_t* dev,
1354                                              keymaster_operation_handle_t operation_handle,
1355                                              const keymaster_key_param_set_t* in_params,
1356                                              const keymaster_blob_t* input, size_t* input_consumed,
1357                                              keymaster_key_param_set_t* out_params,
1358                                              keymaster_blob_t* output) {
1359    if (!dev)
1360        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1361
1362    if (!convert_device(dev)->configured())
1363        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1364
1365    SoftKeymasterDevice* sk_dev = convert_device(dev);
1366    return update(&sk_dev->km1_device_, operation_handle, in_params, input, input_consumed,
1367                  out_params, output);
1368}
1369
1370/* static */
1371keymaster_error_t SoftKeymasterDevice::finish(const keymaster1_device_t* dev,
1372                                              keymaster_operation_handle_t operation_handle,
1373                                              const keymaster_key_param_set_t* params,
1374                                              const keymaster_blob_t* signature,
1375                                              keymaster_key_param_set_t* out_params,
1376                                              keymaster_blob_t* output) {
1377    if (!dev)
1378        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1379
1380    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1381    if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1382        // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1383        // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1384        // km1_dev after doing necessary digesting.
1385        return km1_dev->finish(km1_dev, operation_handle, params, signature, out_params, output);
1386    }
1387
1388    if (out_params) {
1389        out_params->params = nullptr;
1390        out_params->length = 0;
1391    }
1392
1393    if (output) {
1394        output->data = nullptr;
1395        output->data_length = 0;
1396    }
1397
1398    FinishOperationRequest request;
1399    request.op_handle = operation_handle;
1400    if (signature && signature->data_length > 0)
1401        request.signature.Reinitialize(signature->data, signature->data_length);
1402    request.additional_params.Reinitialize(*params);
1403
1404    FinishOperationResponse response;
1405    convert_device(dev)->impl_->FinishOperation(request, &response);
1406    if (response.error != KM_ERROR_OK)
1407        return response.error;
1408
1409    if (response.output_params.size() > 0) {
1410        if (out_params)
1411            response.output_params.CopyToParamSet(out_params);
1412        else
1413            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1414    }
1415    if (output) {
1416        output->data_length = response.output.available_read();
1417        uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1418        if (!tmp)
1419            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1420        memcpy(tmp, response.output.peek_read(), output->data_length);
1421        output->data = tmp;
1422    } else if (response.output.available_read() > 0) {
1423        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1424    }
1425
1426    return KM_ERROR_OK;
1427}
1428
1429struct KeyParamSetContents_Delete {
1430    void operator()(keymaster_key_param_set_t* p) { keymaster_free_param_set(p); }
1431};
1432
1433/* static */
1434keymaster_error_t SoftKeymasterDevice::finish(const keymaster2_device_t* dev,
1435                                              keymaster_operation_handle_t operation_handle,
1436                                              const keymaster_key_param_set_t* params,
1437                                              const keymaster_blob_t* input,
1438                                              const keymaster_blob_t* signature,
1439                                              keymaster_key_param_set_t* out_params,
1440                                              keymaster_blob_t* output) {
1441    if (!dev)
1442        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1443
1444    if (!convert_device(dev)->configured())
1445        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1446
1447    if (out_params)
1448        *out_params = {};
1449
1450    if (output)
1451        *output = {};
1452
1453    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1454    if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1455        // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1456        // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1457        // km1_dev after doing necessary digesting.
1458
1459        std::vector<uint8_t> accumulated_output;
1460        AuthorizationSet accumulated_out_params;
1461        AuthorizationSet mutable_params(*params);
1462        if (input && input->data && input->data_length) {
1463            // Keymaster1 doesn't support input to finish().  Call update() to process input.
1464
1465            accumulated_output.reserve(input->data_length);  // Guess at output size
1466            keymaster_blob_t mutable_input = *input;
1467
1468            while (mutable_input.data_length > 0) {
1469                keymaster_key_param_set_t update_out_params = {};
1470                keymaster_blob_t update_output = {};
1471                size_t input_consumed = 0;
1472                keymaster_error_t error =
1473                    km1_dev->update(km1_dev, operation_handle, &mutable_params, &mutable_input,
1474                                    &input_consumed, &update_out_params, &update_output);
1475                if (error != KM_ERROR_OK) {
1476                    return error;
1477                }
1478
1479                accumulated_output.reserve(accumulated_output.size() + update_output.data_length);
1480                std::copy(update_output.data, update_output.data + update_output.data_length,
1481                          std::back_inserter(accumulated_output));
1482                free(const_cast<uint8_t*>(update_output.data));
1483
1484                accumulated_out_params.push_back(update_out_params);
1485                keymaster_free_param_set(&update_out_params);
1486
1487                mutable_input.data += input_consumed;
1488                mutable_input.data_length -= input_consumed;
1489
1490                // AAD should only be sent once, so remove it if present.
1491                int aad_pos = mutable_params.find(TAG_ASSOCIATED_DATA);
1492                if (aad_pos != -1) {
1493                    mutable_params.erase(aad_pos);
1494                }
1495
1496                if (input_consumed == 0) {
1497                    // Apparently we need more input than we have to complete an operation.
1498                    km1_dev->abort(km1_dev, operation_handle);
1499                    return KM_ERROR_INVALID_INPUT_LENGTH;
1500                }
1501            }
1502        }
1503
1504        keymaster_key_param_set_t finish_out_params = {};
1505        keymaster_blob_t finish_output = {};
1506        keymaster_error_t error = km1_dev->finish(km1_dev, operation_handle, &mutable_params,
1507                                                  signature, &finish_out_params, &finish_output);
1508        if (error != KM_ERROR_OK) {
1509            return error;
1510        }
1511
1512        if (!accumulated_out_params.empty()) {
1513            accumulated_out_params.push_back(finish_out_params);
1514            keymaster_free_param_set(&finish_out_params);
1515            accumulated_out_params.Deduplicate();
1516            accumulated_out_params.CopyToParamSet(&finish_out_params);
1517        }
1518        std::unique_ptr<keymaster_key_param_set_t, KeyParamSetContents_Delete>
1519            finish_out_params_deleter(&finish_out_params);
1520
1521        if (!accumulated_output.empty()) {
1522            size_t finish_out_length = accumulated_output.size() + finish_output.data_length;
1523            uint8_t* finish_out_buf = reinterpret_cast<uint8_t*>(malloc(finish_out_length));
1524
1525            std::copy(accumulated_output.begin(), accumulated_output.end(), finish_out_buf);
1526            std::copy(finish_output.data, finish_output.data + finish_output.data_length,
1527                      finish_out_buf + accumulated_output.size());
1528
1529            free(const_cast<uint8_t*>(finish_output.data));
1530            finish_output.data_length = finish_out_length;
1531            finish_output.data = finish_out_buf;
1532        }
1533        std::unique_ptr<uint8_t, Malloc_Delete> finish_output_deleter(
1534            const_cast<uint8_t*>(finish_output.data));
1535
1536        if ((!out_params && finish_out_params.length) || (!output && finish_output.data_length)) {
1537            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1538        }
1539
1540        if (out_params) {
1541            *out_params = finish_out_params;
1542        }
1543
1544        if (output) {
1545            *output = finish_output;
1546        }
1547
1548        finish_out_params_deleter.release();
1549        finish_output_deleter.release();
1550
1551        return KM_ERROR_OK;
1552    }
1553
1554    FinishOperationRequest request;
1555    request.op_handle = operation_handle;
1556    if (signature && signature->data_length > 0)
1557        request.signature.Reinitialize(signature->data, signature->data_length);
1558    if (input && input->data_length > 0)
1559        request.input.Reinitialize(input->data, input->data_length);
1560    request.additional_params.Reinitialize(*params);
1561
1562    FinishOperationResponse response;
1563    convert_device(dev)->impl_->FinishOperation(request, &response);
1564    if (response.error != KM_ERROR_OK)
1565        return response.error;
1566
1567    if (response.output_params.size() > 0) {
1568        if (out_params)
1569            response.output_params.CopyToParamSet(out_params);
1570        else
1571            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1572    }
1573    if (output) {
1574        output->data_length = response.output.available_read();
1575        uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1576        if (!tmp)
1577            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1578        memcpy(tmp, response.output.peek_read(), output->data_length);
1579        output->data = tmp;
1580    } else if (response.output.available_read() > 0) {
1581        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1582    }
1583
1584    return KM_ERROR_OK;
1585}
1586
1587/* static */
1588keymaster_error_t SoftKeymasterDevice::abort(const keymaster1_device_t* dev,
1589                                             keymaster_operation_handle_t operation_handle) {
1590    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1591    if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1592        // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1593        // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1594        // km1_dev.
1595        return km1_dev->abort(km1_dev, operation_handle);
1596    }
1597
1598    AbortOperationRequest request;
1599    request.op_handle = operation_handle;
1600    AbortOperationResponse response;
1601    convert_device(dev)->impl_->AbortOperation(request, &response);
1602    return response.error;
1603}
1604
1605/* static */
1606keymaster_error_t SoftKeymasterDevice::abort(const keymaster2_device_t* dev,
1607                                             keymaster_operation_handle_t operation_handle) {
1608    if (!dev)
1609        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1610
1611    if (!convert_device(dev)->configured())
1612        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1613
1614    SoftKeymasterDevice* sk_dev = convert_device(dev);
1615    return abort(&sk_dev->km1_device_, operation_handle);
1616}
1617
1618/* static */
1619void SoftKeymasterDevice::StoreDefaultNewKeyParams(keymaster_algorithm_t algorithm,
1620                                                   AuthorizationSet* auth_set) {
1621    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
1622    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
1623    auth_set->push_back(TAG_ALL_USERS);
1624    auth_set->push_back(TAG_NO_AUTH_REQUIRED);
1625
1626    // All digests.
1627    auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE);
1628    auth_set->push_back(TAG_DIGEST, KM_DIGEST_MD5);
1629    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA1);
1630    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_224);
1631    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1632    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
1633    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_512);
1634
1635    if (algorithm == KM_ALGORITHM_RSA) {
1636        auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_ENCRYPT);
1637        auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_DECRYPT);
1638        auth_set->push_back(TAG_PADDING, KM_PAD_NONE);
1639        auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1640        auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1641        auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1642        auth_set->push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
1643    }
1644}
1645
1646}  // namespace keymaster
1647