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/soft_keymaster_context.h>
42#include <keymaster/soft_keymaster_logger.h>
43
44#include "openssl_utils.h"
45
46struct keystore_module soft_keymaster1_device_module = {
47    .common =
48        {
49            .tag = HARDWARE_MODULE_TAG,
50            .module_api_version = KEYMASTER_MODULE_API_VERSION_1_0,
51            .hal_api_version = HARDWARE_HAL_API_VERSION,
52            .id = KEYSTORE_HARDWARE_MODULE_ID,
53            .name = "OpenSSL-based SoftKeymaster HAL",
54            .author = "The Android Open Source Project",
55            .methods = nullptr,
56            .dso = 0,
57            .reserved = {},
58        },
59};
60
61struct keystore_module soft_keymaster2_device_module = {
62    .common =
63        {
64            .tag = HARDWARE_MODULE_TAG,
65            .module_api_version = KEYMASTER_MODULE_API_VERSION_2_0,
66            .hal_api_version = HARDWARE_HAL_API_VERSION,
67            .id = KEYSTORE_HARDWARE_MODULE_ID,
68            .name = "OpenSSL-based SoftKeymaster HAL",
69            .author = "The Android Open Source Project",
70            .methods = nullptr,
71            .dso = 0,
72            .reserved = {},
73        },
74};
75
76namespace keymaster {
77
78const size_t kMaximumAttestationChallengeLength = 128;
79const size_t kOperationTableSize = 16;
80
81template <typename T> std::vector<T> make_vector(const T* array, size_t len) {
82    return std::vector<T>(array, array + len);
83}
84
85// This helper class implements just enough of the C++ standard collection interface to be able to
86// accept push_back calls, and it does nothing but count them.  It's useful when you want to count
87// insertions but not actually store anything.  It's used in digest_set_is_full below to count the
88// size of a set intersection.
89struct PushbackCounter {
90    struct value_type {
91        template <typename T> value_type(const T&) {}
92    };
93    void push_back(const value_type&) { ++count; }
94    size_t count = 0;
95};
96
97static std::vector<keymaster_digest_t> full_digest_list = {
98    KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
99    KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
100
101template <typename Iter> static bool digest_set_is_full(Iter begin, Iter end) {
102    PushbackCounter counter;
103    std::set_intersection(begin, end, full_digest_list.begin(), full_digest_list.end(),
104                          std::back_inserter(counter));
105    return counter.count == full_digest_list.size();
106}
107
108static keymaster_error_t add_digests(keymaster1_device_t* dev, keymaster_algorithm_t algorithm,
109                                     keymaster_purpose_t purpose,
110                                     SoftKeymasterDevice::DigestMap* map, bool* supports_all) {
111    auto key = std::make_pair(algorithm, purpose);
112
113    keymaster_digest_t* digests;
114    size_t digests_length;
115    keymaster_error_t error =
116        dev->get_supported_digests(dev, algorithm, purpose, &digests, &digests_length);
117    if (error != KM_ERROR_OK) {
118        LOG_E("Error %d getting supported digests from keymaster1 device", error);
119        return error;
120    }
121    std::unique_ptr<keymaster_digest_t, Malloc_Delete> digests_deleter(digests);
122
123    auto digest_vec = make_vector(digests, digests_length);
124    *supports_all = digest_set_is_full(digest_vec.begin(), digest_vec.end());
125    (*map)[key] = std::move(digest_vec);
126    return error;
127}
128
129static keymaster_error_t map_digests(keymaster1_device_t* dev, SoftKeymasterDevice::DigestMap* map,
130                                     bool* supports_all) {
131    map->clear();
132    *supports_all = true;
133
134    keymaster_algorithm_t sig_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC, KM_ALGORITHM_HMAC};
135    keymaster_purpose_t sig_purposes[] = {KM_PURPOSE_SIGN, KM_PURPOSE_VERIFY};
136    for (auto algorithm : sig_algorithms)
137        for (auto purpose : sig_purposes) {
138            bool alg_purpose_supports_all;
139            keymaster_error_t error =
140                add_digests(dev, algorithm, purpose, map, &alg_purpose_supports_all);
141            if (error != KM_ERROR_OK)
142                return error;
143            *supports_all &= alg_purpose_supports_all;
144        }
145
146    keymaster_algorithm_t crypt_algorithms[] = {KM_ALGORITHM_RSA};
147    keymaster_purpose_t crypt_purposes[] = {KM_PURPOSE_ENCRYPT, KM_PURPOSE_DECRYPT};
148    for (auto algorithm : crypt_algorithms)
149        for (auto purpose : crypt_purposes) {
150            bool alg_purpose_supports_all;
151            keymaster_error_t error =
152                add_digests(dev, algorithm, purpose, map, &alg_purpose_supports_all);
153            if (error != KM_ERROR_OK)
154                return error;
155            *supports_all &= alg_purpose_supports_all;
156        }
157
158    return KM_ERROR_OK;
159}
160
161SoftKeymasterDevice::SoftKeymasterDevice()
162    : wrapped_km0_device_(nullptr), wrapped_km1_device_(nullptr),
163      context_(new SoftKeymasterContext),
164      impl_(new AndroidKeymaster(context_, kOperationTableSize)), configured_(false) {
165    LOG_I("Creating device", 0);
166    LOG_D("Device address: %p", this);
167
168    initialize_device_struct(KEYMASTER_SOFTWARE_ONLY | KEYMASTER_BLOBS_ARE_STANDALONE |
169                             KEYMASTER_SUPPORTS_EC);
170}
171
172SoftKeymasterDevice::SoftKeymasterDevice(SoftKeymasterContext* context)
173    : wrapped_km0_device_(nullptr), wrapped_km1_device_(nullptr), context_(context),
174      impl_(new AndroidKeymaster(context_, kOperationTableSize)), configured_(false) {
175    LOG_I("Creating test device", 0);
176    LOG_D("Device address: %p", this);
177
178    initialize_device_struct(KEYMASTER_SOFTWARE_ONLY | KEYMASTER_BLOBS_ARE_STANDALONE |
179                             KEYMASTER_SUPPORTS_EC);
180}
181
182keymaster_error_t SoftKeymasterDevice::SetHardwareDevice(keymaster0_device_t* keymaster0_device) {
183    assert(keymaster0_device);
184    LOG_D("Reinitializing SoftKeymasterDevice to use HW keymaster0", 0);
185
186    if (!context_)
187        return KM_ERROR_UNEXPECTED_NULL_POINTER;
188
189    supports_all_digests_ = false;
190    keymaster_error_t error = context_->SetHardwareDevice(keymaster0_device);
191    if (error != KM_ERROR_OK)
192        return error;
193
194    initialize_device_struct(keymaster0_device->flags);
195
196    module_name_ = km1_device_.common.module->name;
197    module_name_.append("(Wrapping ");
198    module_name_.append(keymaster0_device->common.module->name);
199    module_name_.append(")");
200
201    updated_module_ = *km1_device_.common.module;
202    updated_module_.name = module_name_.c_str();
203
204    km1_device_.common.module = &updated_module_;
205
206    wrapped_km0_device_ = keymaster0_device;
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_km0_device_ = nullptr;
240    wrapped_km1_device_ = keymaster1_device;
241    return KM_ERROR_OK;
242}
243
244bool SoftKeymasterDevice::Keymaster1DeviceIsGood() {
245    std::vector<keymaster_digest_t> expected_rsa_digests = {
246        KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,     KM_DIGEST_SHA_2_224,
247        KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
248    std::vector<keymaster_digest_t> expected_ec_digests = {
249        KM_DIGEST_NONE,      KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
250        KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
251
252    for (auto& entry : km1_device_digests_) {
253        if (entry.first.first == KM_ALGORITHM_RSA)
254            if (!std::is_permutation(entry.second.begin(), entry.second.end(),
255                                     expected_rsa_digests.begin()))
256                return false;
257        if (entry.first.first == KM_ALGORITHM_EC)
258            if (!std::is_permutation(entry.second.begin(), entry.second.end(),
259                                     expected_ec_digests.begin()))
260                return false;
261    }
262    return true;
263}
264
265void SoftKeymasterDevice::initialize_device_struct(uint32_t flags) {
266    memset(&km1_device_, 0, sizeof(km1_device_));
267
268    km1_device_.common.tag = HARDWARE_DEVICE_TAG;
269    km1_device_.common.version = 1;
270    km1_device_.common.module = reinterpret_cast<hw_module_t*>(&soft_keymaster1_device_module);
271    km1_device_.common.close = &close_device;
272
273    km1_device_.flags = flags;
274
275    km1_device_.context = this;
276
277    // keymaster0 APIs
278    km1_device_.generate_keypair = nullptr;
279    km1_device_.import_keypair = nullptr;
280    km1_device_.get_keypair_public = nullptr;
281    km1_device_.delete_keypair = nullptr;
282    km1_device_.delete_all = nullptr;
283    km1_device_.sign_data = nullptr;
284    km1_device_.verify_data = nullptr;
285
286    // keymaster1 APIs
287    km1_device_.get_supported_algorithms = get_supported_algorithms;
288    km1_device_.get_supported_block_modes = get_supported_block_modes;
289    km1_device_.get_supported_padding_modes = get_supported_padding_modes;
290    km1_device_.get_supported_digests = get_supported_digests;
291    km1_device_.get_supported_import_formats = get_supported_import_formats;
292    km1_device_.get_supported_export_formats = get_supported_export_formats;
293    km1_device_.add_rng_entropy = add_rng_entropy;
294    km1_device_.generate_key = generate_key;
295    km1_device_.get_key_characteristics = get_key_characteristics;
296    km1_device_.import_key = import_key;
297    km1_device_.export_key = export_key;
298    km1_device_.delete_key = delete_key;
299    km1_device_.delete_all_keys = delete_all_keys;
300    km1_device_.begin = begin;
301    km1_device_.update = update;
302    km1_device_.finish = finish;
303    km1_device_.abort = abort;
304
305    // keymaster2 APIs
306    memset(&km2_device_, 0, sizeof(km2_device_));
307
308    km2_device_.flags = flags;
309    km2_device_.context = this;
310
311    km2_device_.common.tag = HARDWARE_DEVICE_TAG;
312    km2_device_.common.version = 1;
313    km2_device_.common.module = reinterpret_cast<hw_module_t*>(&soft_keymaster2_device_module);
314    km2_device_.common.close = &close_device;
315
316    km2_device_.configure = configure;
317    km2_device_.add_rng_entropy = add_rng_entropy;
318    km2_device_.generate_key = generate_key;
319    km2_device_.get_key_characteristics = get_key_characteristics;
320    km2_device_.import_key = import_key;
321    km2_device_.export_key = export_key;
322    km2_device_.attest_key = attest_key;
323    km2_device_.upgrade_key = upgrade_key;
324    km2_device_.delete_key = delete_key;
325    km2_device_.delete_all_keys = delete_all_keys;
326    km2_device_.begin = begin;
327    km2_device_.update = update;
328    km2_device_.finish = finish;
329    km2_device_.abort = abort;
330}
331
332hw_device_t* SoftKeymasterDevice::hw_device() {
333    return &km1_device_.common;
334}
335
336keymaster1_device_t* SoftKeymasterDevice::keymaster_device() {
337    return &km1_device_;
338}
339
340keymaster2_device_t* SoftKeymasterDevice::keymaster2_device() {
341    return &km2_device_;
342}
343
344namespace {
345
346keymaster_key_characteristics_t* BuildCharacteristics(const AuthorizationSet& hw_enforced,
347                                                      const AuthorizationSet& sw_enforced) {
348    keymaster_key_characteristics_t* characteristics =
349        reinterpret_cast<keymaster_key_characteristics_t*>(
350            malloc(sizeof(keymaster_key_characteristics_t)));
351    if (characteristics) {
352        hw_enforced.CopyToParamSet(&characteristics->hw_enforced);
353        sw_enforced.CopyToParamSet(&characteristics->sw_enforced);
354    }
355    return characteristics;
356}
357
358template <typename RequestType>
359void AddClientAndAppData(const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
360                         RequestType* request) {
361    request->additional_params.Clear();
362    if (client_id)
363        request->additional_params.push_back(TAG_APPLICATION_ID, *client_id);
364    if (app_data)
365        request->additional_params.push_back(TAG_APPLICATION_DATA, *app_data);
366}
367
368template <typename T> SoftKeymasterDevice* convert_device(const T* dev) {
369    static_assert((std::is_same<T, keymaster0_device_t>::value ||
370                   std::is_same<T, keymaster1_device_t>::value ||
371                   std::is_same<T, keymaster2_device_t>::value),
372                  "convert_device should only be applied to keymaster devices");
373    return reinterpret_cast<SoftKeymasterDevice*>(dev->context);
374}
375
376template <keymaster_tag_t Tag, keymaster_tag_type_t Type, typename KeymasterEnum>
377bool FindTagValue(const keymaster_key_param_set_t& params,
378                  TypedEnumTag<Type, Tag, KeymasterEnum> tag, KeymasterEnum* value) {
379    for (size_t i = 0; i < params.length; ++i)
380        if (params.params[i].tag == tag) {
381            *value = static_cast<KeymasterEnum>(params.params[i].enumerated);
382            return true;
383        }
384    return false;
385}
386
387}  // unnamed namespaced
388
389/* static */
390int SoftKeymasterDevice::close_device(hw_device_t* dev) {
391    switch (dev->module->module_api_version) {
392    case KEYMASTER_MODULE_API_VERSION_2_0: {
393        delete convert_device(reinterpret_cast<keymaster2_device_t*>(dev));
394        break;
395    }
396
397    case KEYMASTER_MODULE_API_VERSION_1_0: {
398        delete convert_device(reinterpret_cast<keymaster1_device_t*>(dev));
399        break;
400    }
401
402    default:
403        return -1;
404    }
405
406    return 0;
407}
408
409/* static */
410keymaster_error_t SoftKeymasterDevice::get_supported_algorithms(const keymaster1_device_t* dev,
411                                                                keymaster_algorithm_t** algorithms,
412                                                                size_t* algorithms_length) {
413    if (!dev)
414        return KM_ERROR_UNEXPECTED_NULL_POINTER;
415
416    if (!algorithms || !algorithms_length)
417        return KM_ERROR_OUTPUT_PARAMETER_NULL;
418
419    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
420    if (km1_dev)
421        return km1_dev->get_supported_algorithms(km1_dev, algorithms, algorithms_length);
422
423    SupportedAlgorithmsRequest request;
424    SupportedAlgorithmsResponse response;
425    convert_device(dev)->impl_->SupportedAlgorithms(request, &response);
426    if (response.error != KM_ERROR_OK) {
427        LOG_E("get_supported_algorithms failed with %d", response.error);
428
429        return response.error;
430    }
431
432    *algorithms_length = response.results_length;
433    *algorithms =
434        reinterpret_cast<keymaster_algorithm_t*>(malloc(*algorithms_length * sizeof(**algorithms)));
435    if (!*algorithms)
436        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
437    std::copy(response.results, response.results + response.results_length, *algorithms);
438    return KM_ERROR_OK;
439}
440
441/* static */
442keymaster_error_t SoftKeymasterDevice::get_supported_block_modes(const keymaster1_device_t* dev,
443                                                                 keymaster_algorithm_t algorithm,
444                                                                 keymaster_purpose_t purpose,
445                                                                 keymaster_block_mode_t** modes,
446                                                                 size_t* modes_length) {
447    if (!dev)
448        return KM_ERROR_UNEXPECTED_NULL_POINTER;
449
450    if (!modes || !modes_length)
451        return KM_ERROR_OUTPUT_PARAMETER_NULL;
452
453    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
454    if (km1_dev)
455        return km1_dev->get_supported_block_modes(km1_dev, algorithm, purpose, modes, modes_length);
456
457    SupportedBlockModesRequest request;
458    request.algorithm = algorithm;
459    request.purpose = purpose;
460    SupportedBlockModesResponse response;
461    convert_device(dev)->impl_->SupportedBlockModes(request, &response);
462
463    if (response.error != KM_ERROR_OK) {
464        LOG_E("get_supported_block_modes failed with %d", response.error);
465
466        return response.error;
467    }
468
469    *modes_length = response.results_length;
470    *modes = reinterpret_cast<keymaster_block_mode_t*>(malloc(*modes_length * sizeof(**modes)));
471    if (!*modes)
472        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
473    std::copy(response.results, response.results + response.results_length, *modes);
474    return KM_ERROR_OK;
475}
476
477/* static */
478keymaster_error_t SoftKeymasterDevice::get_supported_padding_modes(const keymaster1_device_t* dev,
479                                                                   keymaster_algorithm_t algorithm,
480                                                                   keymaster_purpose_t purpose,
481                                                                   keymaster_padding_t** modes,
482                                                                   size_t* modes_length) {
483    if (!dev)
484        return KM_ERROR_UNEXPECTED_NULL_POINTER;
485
486    if (!modes || !modes_length)
487        return KM_ERROR_OUTPUT_PARAMETER_NULL;
488
489    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
490    if (km1_dev)
491        return km1_dev->get_supported_padding_modes(km1_dev, algorithm, purpose, modes,
492                                                    modes_length);
493
494    SupportedPaddingModesRequest request;
495    request.algorithm = algorithm;
496    request.purpose = purpose;
497    SupportedPaddingModesResponse response;
498    convert_device(dev)->impl_->SupportedPaddingModes(request, &response);
499
500    if (response.error != KM_ERROR_OK) {
501        LOG_E("get_supported_padding_modes failed with %d", response.error);
502        return response.error;
503    }
504
505    *modes_length = response.results_length;
506    *modes = reinterpret_cast<keymaster_padding_t*>(malloc(*modes_length * sizeof(**modes)));
507    if (!*modes)
508        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
509    std::copy(response.results, response.results + response.results_length, *modes);
510    return KM_ERROR_OK;
511}
512
513/* static */
514keymaster_error_t SoftKeymasterDevice::get_supported_digests(const keymaster1_device_t* dev,
515                                                             keymaster_algorithm_t algorithm,
516                                                             keymaster_purpose_t purpose,
517                                                             keymaster_digest_t** digests,
518                                                             size_t* digests_length) {
519    if (!dev)
520        return KM_ERROR_UNEXPECTED_NULL_POINTER;
521
522    if (!digests || !digests_length)
523        return KM_ERROR_OUTPUT_PARAMETER_NULL;
524
525    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
526    if (km1_dev)
527        return km1_dev->get_supported_digests(km1_dev, algorithm, purpose, digests, digests_length);
528
529    SupportedDigestsRequest request;
530    request.algorithm = algorithm;
531    request.purpose = purpose;
532    SupportedDigestsResponse response;
533    convert_device(dev)->impl_->SupportedDigests(request, &response);
534
535    if (response.error != KM_ERROR_OK) {
536        LOG_E("get_supported_digests failed with %d", response.error);
537        return response.error;
538    }
539
540    *digests_length = response.results_length;
541    *digests = reinterpret_cast<keymaster_digest_t*>(malloc(*digests_length * sizeof(**digests)));
542    if (!*digests)
543        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
544    std::copy(response.results, response.results + response.results_length, *digests);
545    return KM_ERROR_OK;
546}
547
548/* static */
549keymaster_error_t SoftKeymasterDevice::get_supported_import_formats(
550    const keymaster1_device_t* dev, keymaster_algorithm_t algorithm,
551    keymaster_key_format_t** formats, size_t* formats_length) {
552    if (!dev)
553        return KM_ERROR_UNEXPECTED_NULL_POINTER;
554
555    if (!formats || !formats_length)
556        return KM_ERROR_OUTPUT_PARAMETER_NULL;
557
558    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
559    if (km1_dev)
560        return km1_dev->get_supported_import_formats(km1_dev, algorithm, formats, formats_length);
561
562    SupportedImportFormatsRequest request;
563    request.algorithm = algorithm;
564    SupportedImportFormatsResponse response;
565    convert_device(dev)->impl_->SupportedImportFormats(request, &response);
566
567    if (response.error != KM_ERROR_OK) {
568        LOG_E("get_supported_import_formats failed with %d", response.error);
569        return response.error;
570    }
571
572    *formats_length = response.results_length;
573    *formats =
574        reinterpret_cast<keymaster_key_format_t*>(malloc(*formats_length * sizeof(**formats)));
575    if (!*formats)
576        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
577    std::copy(response.results, response.results + response.results_length, *formats);
578    return KM_ERROR_OK;
579}
580
581/* static */
582keymaster_error_t SoftKeymasterDevice::get_supported_export_formats(
583    const keymaster1_device_t* dev, keymaster_algorithm_t algorithm,
584    keymaster_key_format_t** formats, size_t* formats_length) {
585    if (!dev)
586        return KM_ERROR_UNEXPECTED_NULL_POINTER;
587
588    if (!formats || !formats_length)
589        return KM_ERROR_OUTPUT_PARAMETER_NULL;
590
591    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
592    if (km1_dev)
593        return km1_dev->get_supported_export_formats(km1_dev, algorithm, formats, formats_length);
594
595    SupportedExportFormatsRequest request;
596    request.algorithm = algorithm;
597    SupportedExportFormatsResponse response;
598    convert_device(dev)->impl_->SupportedExportFormats(request, &response);
599
600    if (response.error != KM_ERROR_OK) {
601        LOG_E("get_supported_export_formats failed with %d", response.error);
602        return response.error;
603    }
604
605    *formats_length = response.results_length;
606    *formats =
607        reinterpret_cast<keymaster_key_format_t*>(malloc(*formats_length * sizeof(**formats)));
608    if (!*formats)
609        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
610    std::copy(response.results, response.results + *formats_length, *formats);
611    return KM_ERROR_OK;
612}
613
614/* static */
615keymaster_error_t SoftKeymasterDevice::configure(const keymaster2_device_t* dev,
616                                                 const keymaster_key_param_set_t* params) {
617    AuthorizationSet params_copy(*params);
618    ConfigureRequest request;
619    if (!params_copy.GetTagValue(TAG_OS_VERSION, &request.os_version) ||
620        !params_copy.GetTagValue(TAG_OS_PATCHLEVEL, &request.os_patchlevel)) {
621        LOG_E("Configuration parameters must contain OS version and patch level", 0);
622        return KM_ERROR_INVALID_ARGUMENT;
623    }
624    ConfigureResponse response;
625    convert_device(dev)->impl_->Configure(request, &response);
626    if (response.error == KM_ERROR_OK)
627        convert_device(dev)->configured_ = true;
628    return response.error;
629}
630
631/* static */
632keymaster_error_t SoftKeymasterDevice::add_rng_entropy(const keymaster1_device_t* dev,
633                                                       const uint8_t* data, size_t data_length) {
634    if (!dev)
635        return KM_ERROR_UNEXPECTED_NULL_POINTER;
636
637    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
638    if (km1_dev)
639        return km1_dev->add_rng_entropy(km1_dev, data, data_length);
640
641    AddEntropyRequest request;
642    request.random_data.Reinitialize(data, data_length);
643    AddEntropyResponse response;
644    convert_device(dev)->impl_->AddRngEntropy(request, &response);
645    if (response.error != KM_ERROR_OK)
646        LOG_E("add_rng_entropy failed with %d", response.error);
647    return response.error;
648}
649
650/* static */
651keymaster_error_t SoftKeymasterDevice::add_rng_entropy(const keymaster2_device_t* dev,
652                                                       const uint8_t* data, size_t data_length) {
653    if (!dev)
654        return KM_ERROR_UNEXPECTED_NULL_POINTER;
655
656    if (!convert_device(dev)->configured())
657        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
658
659    SoftKeymasterDevice* sk_dev = convert_device(dev);
660    return add_rng_entropy(&sk_dev->km1_device_, data, data_length);
661}
662
663template <typename Collection, typename Value> bool contains(const Collection& c, const Value& v) {
664    return std::find(c.begin(), c.end(), v) != c.end();
665}
666
667bool SoftKeymasterDevice::FindUnsupportedDigest(keymaster_algorithm_t algorithm,
668                                                keymaster_purpose_t purpose,
669                                                const AuthorizationSet& params,
670                                                keymaster_digest_t* unsupported) const {
671    assert(wrapped_km1_device_);
672
673    auto supported_digests = km1_device_digests_.find(std::make_pair(algorithm, purpose));
674    if (supported_digests == km1_device_digests_.end())
675        // Invalid algorith/purpose pair (e.g. EC encrypt).  Let the error be handled by HW module.
676        return false;
677
678    for (auto& entry : params)
679        if (entry.tag == TAG_DIGEST)
680            if (!contains(supported_digests->second, entry.enumerated)) {
681                LOG_I("Digest %d requested but not supported by module %s", entry.enumerated,
682                      wrapped_km1_device_->common.module->name);
683                *unsupported = static_cast<keymaster_digest_t>(entry.enumerated);
684                return true;
685            }
686    return false;
687}
688
689bool SoftKeymasterDevice::RequiresSoftwareDigesting(keymaster_algorithm_t algorithm,
690                                                    keymaster_purpose_t purpose,
691                                                    const AuthorizationSet& params) const {
692    assert(wrapped_km1_device_);
693    if (!wrapped_km1_device_)
694        return true;
695
696    switch (algorithm) {
697    case KM_ALGORITHM_AES:
698        LOG_D("Not performing software digesting for AES keys", 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        KeymasterKeyBlob key_material;
1218        AuthorizationSet hw_enforced;
1219        AuthorizationSet sw_enforced;
1220        skdev->context_->ParseKeyBlob(KeymasterKeyBlob(*key), in_params_set, &key_material,
1221                                      &hw_enforced, &sw_enforced);
1222
1223        keymaster_algorithm_t algorithm = KM_ALGORITHM_AES;
1224        if (!hw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm) &&
1225            !sw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm)) {
1226            return KM_ERROR_INVALID_KEY_BLOB;
1227        }
1228
1229        if (algorithm == KM_ALGORITHM_HMAC) {
1230            // Because HMAC keys can have only one digest, in_params_set doesn't contain it.  We
1231            // need to get the digest from the key and add it to in_params_set.
1232            keymaster_digest_t digest;
1233            if (!hw_enforced.GetTagValue(TAG_DIGEST, &digest) &&
1234                !sw_enforced.GetTagValue(TAG_DIGEST, &digest)) {
1235                return KM_ERROR_INVALID_KEY_BLOB;
1236            }
1237            in_params_set.push_back(TAG_DIGEST, digest);
1238        }
1239
1240        if (!skdev->RequiresSoftwareDigesting(algorithm, purpose, in_params_set)) {
1241            LOG_D("Operation supported by %s, passing through to keymaster1 module",
1242                  km1_dev->common.module->name);
1243            return km1_dev->begin(km1_dev, purpose, key, in_params, out_params, operation_handle);
1244        }
1245        LOG_I("Doing software digesting for keymaster1 module %s", km1_dev->common.module->name);
1246    }
1247
1248    if (out_params) {
1249        out_params->params = nullptr;
1250        out_params->length = 0;
1251    }
1252
1253    BeginOperationRequest request;
1254    request.purpose = purpose;
1255    request.SetKeyMaterial(*key);
1256    request.additional_params.Reinitialize(*in_params);
1257
1258    BeginOperationResponse response;
1259    skdev->impl_->BeginOperation(request, &response);
1260    if (response.error != KM_ERROR_OK)
1261        return response.error;
1262
1263    if (response.output_params.size() > 0) {
1264        if (out_params)
1265            response.output_params.CopyToParamSet(out_params);
1266        else
1267            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1268    }
1269
1270    *operation_handle = response.op_handle;
1271    return KM_ERROR_OK;
1272}
1273
1274/* static */
1275keymaster_error_t SoftKeymasterDevice::begin(const keymaster2_device_t* dev,
1276                                             keymaster_purpose_t purpose,
1277                                             const keymaster_key_blob_t* key,
1278                                             const keymaster_key_param_set_t* in_params,
1279                                             keymaster_key_param_set_t* out_params,
1280                                             keymaster_operation_handle_t* operation_handle) {
1281    if (!dev)
1282        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1283
1284    if (!convert_device(dev)->configured())
1285        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1286
1287    SoftKeymasterDevice* sk_dev = convert_device(dev);
1288    return begin(&sk_dev->km1_device_, purpose, key, in_params, out_params, operation_handle);
1289}
1290
1291/* static */
1292keymaster_error_t SoftKeymasterDevice::update(const keymaster1_device_t* dev,
1293                                              keymaster_operation_handle_t operation_handle,
1294                                              const keymaster_key_param_set_t* in_params,
1295                                              const keymaster_blob_t* input, size_t* input_consumed,
1296                                              keymaster_key_param_set_t* out_params,
1297                                              keymaster_blob_t* output) {
1298    if (!input)
1299        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1300
1301    if (!input_consumed)
1302        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1303
1304    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1305    if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1306        // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1307        // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1308        // km1_dev after doing necessary digesting.
1309        return km1_dev->update(km1_dev, operation_handle, in_params, input, input_consumed,
1310                               out_params, output);
1311    }
1312
1313    if (out_params) {
1314        out_params->params = nullptr;
1315        out_params->length = 0;
1316    }
1317    if (output) {
1318        output->data = nullptr;
1319        output->data_length = 0;
1320    }
1321
1322    UpdateOperationRequest request;
1323    request.op_handle = operation_handle;
1324    if (input)
1325        request.input.Reinitialize(input->data, input->data_length);
1326    if (in_params)
1327        request.additional_params.Reinitialize(*in_params);
1328
1329    UpdateOperationResponse response;
1330    convert_device(dev)->impl_->UpdateOperation(request, &response);
1331    if (response.error != KM_ERROR_OK)
1332        return response.error;
1333
1334    if (response.output_params.size() > 0) {
1335        if (out_params)
1336            response.output_params.CopyToParamSet(out_params);
1337        else
1338            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1339    }
1340
1341    *input_consumed = response.input_consumed;
1342    if (output) {
1343        output->data_length = response.output.available_read();
1344        uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1345        if (!tmp)
1346            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1347        memcpy(tmp, response.output.peek_read(), output->data_length);
1348        output->data = tmp;
1349    } else if (response.output.available_read() > 0) {
1350        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1351    }
1352    return KM_ERROR_OK;
1353}
1354
1355/* static */
1356keymaster_error_t SoftKeymasterDevice::update(const keymaster2_device_t* dev,
1357                                              keymaster_operation_handle_t operation_handle,
1358                                              const keymaster_key_param_set_t* in_params,
1359                                              const keymaster_blob_t* input, size_t* input_consumed,
1360                                              keymaster_key_param_set_t* out_params,
1361                                              keymaster_blob_t* output) {
1362    if (!dev)
1363        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1364
1365    if (!convert_device(dev)->configured())
1366        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1367
1368    SoftKeymasterDevice* sk_dev = convert_device(dev);
1369    return update(&sk_dev->km1_device_, operation_handle, in_params, input, input_consumed,
1370                  out_params, output);
1371}
1372
1373/* static */
1374keymaster_error_t SoftKeymasterDevice::finish(const keymaster1_device_t* dev,
1375                                              keymaster_operation_handle_t operation_handle,
1376                                              const keymaster_key_param_set_t* params,
1377                                              const keymaster_blob_t* signature,
1378                                              keymaster_key_param_set_t* out_params,
1379                                              keymaster_blob_t* output) {
1380    if (!dev)
1381        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1382
1383    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1384    if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1385        // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1386        // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1387        // km1_dev after doing necessary digesting.
1388        return km1_dev->finish(km1_dev, operation_handle, params, signature, out_params, output);
1389    }
1390
1391    if (out_params) {
1392        out_params->params = nullptr;
1393        out_params->length = 0;
1394    }
1395
1396    if (output) {
1397        output->data = nullptr;
1398        output->data_length = 0;
1399    }
1400
1401    FinishOperationRequest request;
1402    request.op_handle = operation_handle;
1403    if (signature && signature->data_length > 0)
1404        request.signature.Reinitialize(signature->data, signature->data_length);
1405    request.additional_params.Reinitialize(*params);
1406
1407    FinishOperationResponse response;
1408    convert_device(dev)->impl_->FinishOperation(request, &response);
1409    if (response.error != KM_ERROR_OK)
1410        return response.error;
1411
1412    if (response.output_params.size() > 0) {
1413        if (out_params)
1414            response.output_params.CopyToParamSet(out_params);
1415        else
1416            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1417    }
1418    if (output) {
1419        output->data_length = response.output.available_read();
1420        uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1421        if (!tmp)
1422            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1423        memcpy(tmp, response.output.peek_read(), output->data_length);
1424        output->data = tmp;
1425    } else if (response.output.available_read() > 0) {
1426        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1427    }
1428
1429    return KM_ERROR_OK;
1430}
1431
1432struct KeyParamSetContents_Delete {
1433    void operator()(keymaster_key_param_set_t* p) { keymaster_free_param_set(p); }
1434};
1435
1436/* static */
1437keymaster_error_t SoftKeymasterDevice::finish(const keymaster2_device_t* dev,
1438                                              keymaster_operation_handle_t operation_handle,
1439                                              const keymaster_key_param_set_t* params,
1440                                              const keymaster_blob_t* input,
1441                                              const keymaster_blob_t* signature,
1442                                              keymaster_key_param_set_t* out_params,
1443                                              keymaster_blob_t* output) {
1444    if (!dev)
1445        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1446
1447    if (!convert_device(dev)->configured())
1448        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1449
1450    if (out_params)
1451        *out_params = {};
1452
1453    if (output)
1454        *output = {};
1455
1456    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1457    if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1458        // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1459        // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1460        // km1_dev after doing necessary digesting.
1461
1462        std::vector<uint8_t> accumulated_output;
1463        AuthorizationSet accumulated_out_params;
1464        AuthorizationSet mutable_params(*params);
1465        if (input && input->data && input->data_length) {
1466            // Keymaster1 doesn't support input to finish().  Call update() to process input.
1467
1468            accumulated_output.reserve(input->data_length);  // Guess at output size
1469            keymaster_blob_t mutable_input = *input;
1470
1471            while (mutable_input.data_length > 0) {
1472                keymaster_key_param_set_t update_out_params = {};
1473                keymaster_blob_t update_output = {};
1474                size_t input_consumed = 0;
1475                keymaster_error_t error =
1476                    km1_dev->update(km1_dev, operation_handle, &mutable_params, &mutable_input,
1477                                    &input_consumed, &update_out_params, &update_output);
1478                if (error != KM_ERROR_OK) {
1479                    return error;
1480                }
1481
1482                accumulated_output.reserve(accumulated_output.size() + update_output.data_length);
1483                std::copy(update_output.data, update_output.data + update_output.data_length,
1484                          std::back_inserter(accumulated_output));
1485                free(const_cast<uint8_t*>(update_output.data));
1486
1487                accumulated_out_params.push_back(update_out_params);
1488                keymaster_free_param_set(&update_out_params);
1489
1490                mutable_input.data += input_consumed;
1491                mutable_input.data_length -= input_consumed;
1492
1493                // AAD should only be sent once, so remove it if present.
1494                int aad_pos = mutable_params.find(TAG_ASSOCIATED_DATA);
1495                if (aad_pos != -1) {
1496                    mutable_params.erase(aad_pos);
1497                }
1498
1499                if (input_consumed == 0) {
1500                    // Apparently we need more input than we have to complete an operation.
1501                    km1_dev->abort(km1_dev, operation_handle);
1502                    return KM_ERROR_INVALID_INPUT_LENGTH;
1503                }
1504            }
1505        }
1506
1507        keymaster_key_param_set_t finish_out_params = {};
1508        keymaster_blob_t finish_output = {};
1509        keymaster_error_t error = km1_dev->finish(km1_dev, operation_handle, &mutable_params,
1510                                                  signature, &finish_out_params, &finish_output);
1511        if (error != KM_ERROR_OK) {
1512            return error;
1513        }
1514
1515        if (!accumulated_out_params.empty()) {
1516            accumulated_out_params.push_back(finish_out_params);
1517            keymaster_free_param_set(&finish_out_params);
1518            accumulated_out_params.Deduplicate();
1519            accumulated_out_params.CopyToParamSet(&finish_out_params);
1520        }
1521        std::unique_ptr<keymaster_key_param_set_t, KeyParamSetContents_Delete>
1522            finish_out_params_deleter(&finish_out_params);
1523
1524        if (!accumulated_output.empty()) {
1525            size_t finish_out_length = accumulated_output.size() + finish_output.data_length;
1526            uint8_t* finish_out_buf = reinterpret_cast<uint8_t*>(malloc(finish_out_length));
1527
1528            std::copy(accumulated_output.begin(), accumulated_output.end(), finish_out_buf);
1529            std::copy(finish_output.data, finish_output.data + finish_output.data_length,
1530                      finish_out_buf + accumulated_output.size());
1531
1532            free(const_cast<uint8_t*>(finish_output.data));
1533            finish_output.data_length = finish_out_length;
1534            finish_output.data = finish_out_buf;
1535        }
1536        std::unique_ptr<uint8_t, Malloc_Delete> finish_output_deleter(
1537            const_cast<uint8_t*>(finish_output.data));
1538
1539        if ((!out_params && finish_out_params.length) || (!output && finish_output.data_length)) {
1540            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1541        }
1542
1543        if (out_params) {
1544            *out_params = finish_out_params;
1545        }
1546
1547        if (output) {
1548            *output = finish_output;
1549        }
1550
1551        finish_out_params_deleter.release();
1552        finish_output_deleter.release();
1553
1554        return KM_ERROR_OK;
1555    }
1556
1557    FinishOperationRequest request;
1558    request.op_handle = operation_handle;
1559    if (signature && signature->data_length > 0)
1560        request.signature.Reinitialize(signature->data, signature->data_length);
1561    if (input && input->data_length > 0)
1562        request.input.Reinitialize(input->data, input->data_length);
1563    request.additional_params.Reinitialize(*params);
1564
1565    FinishOperationResponse response;
1566    convert_device(dev)->impl_->FinishOperation(request, &response);
1567    if (response.error != KM_ERROR_OK)
1568        return response.error;
1569
1570    if (response.output_params.size() > 0) {
1571        if (out_params)
1572            response.output_params.CopyToParamSet(out_params);
1573        else
1574            return KM_ERROR_OUTPUT_PARAMETER_NULL;
1575    }
1576    if (output) {
1577        output->data_length = response.output.available_read();
1578        uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1579        if (!tmp)
1580            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1581        memcpy(tmp, response.output.peek_read(), output->data_length);
1582        output->data = tmp;
1583    } else if (response.output.available_read() > 0) {
1584        return KM_ERROR_OUTPUT_PARAMETER_NULL;
1585    }
1586
1587    return KM_ERROR_OK;
1588}
1589
1590/* static */
1591keymaster_error_t SoftKeymasterDevice::abort(const keymaster1_device_t* dev,
1592                                             keymaster_operation_handle_t operation_handle) {
1593    const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1594    if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1595        // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1596        // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1597        // km1_dev.
1598        return km1_dev->abort(km1_dev, operation_handle);
1599    }
1600
1601    AbortOperationRequest request;
1602    request.op_handle = operation_handle;
1603    AbortOperationResponse response;
1604    convert_device(dev)->impl_->AbortOperation(request, &response);
1605    return response.error;
1606}
1607
1608/* static */
1609keymaster_error_t SoftKeymasterDevice::abort(const keymaster2_device_t* dev,
1610                                             keymaster_operation_handle_t operation_handle) {
1611    if (!dev)
1612        return KM_ERROR_UNEXPECTED_NULL_POINTER;
1613
1614    if (!convert_device(dev)->configured())
1615        return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1616
1617    SoftKeymasterDevice* sk_dev = convert_device(dev);
1618    return abort(&sk_dev->km1_device_, operation_handle);
1619}
1620
1621/* static */
1622void SoftKeymasterDevice::StoreDefaultNewKeyParams(keymaster_algorithm_t algorithm,
1623                                                   AuthorizationSet* auth_set) {
1624    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
1625    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
1626    auth_set->push_back(TAG_ALL_USERS);
1627    auth_set->push_back(TAG_NO_AUTH_REQUIRED);
1628
1629    // All digests.
1630    auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE);
1631    auth_set->push_back(TAG_DIGEST, KM_DIGEST_MD5);
1632    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA1);
1633    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_224);
1634    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1635    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
1636    auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_512);
1637
1638    if (algorithm == KM_ALGORITHM_RSA) {
1639        auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_ENCRYPT);
1640        auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_DECRYPT);
1641        auth_set->push_back(TAG_PADDING, KM_PAD_NONE);
1642        auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1643        auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1644        auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1645        auth_set->push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
1646    }
1647}
1648
1649}  // namespace keymaster
1650