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 <log/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 
47 struct 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 = nullptr,
58             .reserved = {},
59         },
60 };
61 
62 struct 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 = nullptr,
73             .reserved = {},
74         },
75 };
76 
77 namespace keymaster {
78 
79 const size_t kMaximumAttestationChallengeLength = 128;
80 const size_t kOperationTableSize = 16;
81 
make_vector(const T * array,size_t len)82 template <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.
90 struct PushbackCounter {
91     struct value_type {
92         // NOLINTNEXTLINE(google-explicit-constructor)
value_typekeymaster::PushbackCounter::value_type93         template <typename T> value_type(const T&) {}
94     };
push_backkeymaster::PushbackCounter95     void push_back(const value_type&) { ++count; }
96     size_t count = 0;
97 };
98 
99 static std::vector<keymaster_digest_t> full_digest_list = {
100     KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
101     KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
102 
digest_set_is_full(Iter begin,Iter end)103 template <typename Iter> static bool digest_set_is_full(Iter begin, Iter end) {
104     PushbackCounter counter;
105     std::set_intersection(begin, end, full_digest_list.begin(), full_digest_list.end(),
106                           std::back_inserter(counter));
107     return counter.count == full_digest_list.size();
108 }
109 
add_digests(keymaster1_device_t * dev,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,SoftKeymasterDevice::DigestMap * map,bool * supports_all)110 static keymaster_error_t add_digests(keymaster1_device_t* dev, keymaster_algorithm_t algorithm,
111                                      keymaster_purpose_t purpose,
112                                      SoftKeymasterDevice::DigestMap* map, bool* supports_all) {
113     auto key = std::make_pair(algorithm, purpose);
114 
115     keymaster_digest_t* digests;
116     size_t digests_length;
117     keymaster_error_t error =
118         dev->get_supported_digests(dev, algorithm, purpose, &digests, &digests_length);
119     if (error != KM_ERROR_OK) {
120         LOG_E("Error %d getting supported digests from keymaster1 device", error);
121         return error;
122     }
123     std::unique_ptr<keymaster_digest_t, Malloc_Delete> digests_deleter(digests);
124 
125     auto digest_vec = make_vector(digests, digests_length);
126     *supports_all = digest_set_is_full(digest_vec.begin(), digest_vec.end());
127     (*map)[key] = std::move(digest_vec);
128     return error;
129 }
130 
map_digests(keymaster1_device_t * dev,SoftKeymasterDevice::DigestMap * map,bool * supports_all)131 static keymaster_error_t map_digests(keymaster1_device_t* dev, SoftKeymasterDevice::DigestMap* map,
132                                      bool* supports_all) {
133     map->clear();
134     *supports_all = true;
135 
136     keymaster_algorithm_t sig_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC, KM_ALGORITHM_HMAC};
137     keymaster_purpose_t sig_purposes[] = {KM_PURPOSE_SIGN, KM_PURPOSE_VERIFY};
138     for (auto algorithm : sig_algorithms)
139         for (auto purpose : sig_purposes) {
140             bool alg_purpose_supports_all;
141             keymaster_error_t error =
142                 add_digests(dev, algorithm, purpose, map, &alg_purpose_supports_all);
143             if (error != KM_ERROR_OK)
144                 return error;
145             *supports_all &= alg_purpose_supports_all;
146         }
147 
148     keymaster_algorithm_t crypt_algorithms[] = {KM_ALGORITHM_RSA};
149     keymaster_purpose_t crypt_purposes[] = {KM_PURPOSE_ENCRYPT, KM_PURPOSE_DECRYPT};
150     for (auto algorithm : crypt_algorithms)
151         for (auto purpose : crypt_purposes) {
152             bool alg_purpose_supports_all;
153             keymaster_error_t error =
154                 add_digests(dev, algorithm, purpose, map, &alg_purpose_supports_all);
155             if (error != KM_ERROR_OK)
156                 return error;
157             *supports_all &= alg_purpose_supports_all;
158         }
159 
160     return KM_ERROR_OK;
161 }
162 
SoftKeymasterDevice()163 SoftKeymasterDevice::SoftKeymasterDevice()
164     : wrapped_km1_device_(nullptr),
165       context_(new SoftKeymasterContext),
166       impl_(new AndroidKeymaster(context_, kOperationTableSize)), configured_(false) {
167     LOG_I("Creating device", 0);
168     LOG_D("Device address: %p", this);
169 
170     initialize_device_struct(KEYMASTER_SOFTWARE_ONLY | KEYMASTER_BLOBS_ARE_STANDALONE |
171                              KEYMASTER_SUPPORTS_EC);
172 }
173 
SoftKeymasterDevice(SoftKeymasterContext * context)174 SoftKeymasterDevice::SoftKeymasterDevice(SoftKeymasterContext* context)
175     : wrapped_km1_device_(nullptr), context_(context),
176       impl_(new AndroidKeymaster(context_, kOperationTableSize)), configured_(false) {
177     LOG_I("Creating test device", 0);
178     LOG_D("Device address: %p", this);
179 
180     initialize_device_struct(KEYMASTER_SOFTWARE_ONLY | KEYMASTER_BLOBS_ARE_STANDALONE |
181                              KEYMASTER_SUPPORTS_EC);
182 }
183 
SetHardwareDevice(keymaster0_device_t * keymaster0_device)184 keymaster_error_t SoftKeymasterDevice::SetHardwareDevice(keymaster0_device_t* keymaster0_device) {
185     assert(keymaster0_device);
186     LOG_D("Reinitializing SoftKeymasterDevice to use HW keymaster0", 0);
187 
188     if (!context_)
189         return KM_ERROR_UNEXPECTED_NULL_POINTER;
190 
191     supports_all_digests_ = false;
192     keymaster_error_t error = context_->SetHardwareDevice(keymaster0_device);
193     if (error != KM_ERROR_OK)
194         return error;
195 
196     initialize_device_struct(keymaster0_device->flags);
197 
198     module_name_ = km1_device_.common.module->name;
199     module_name_.append("(Wrapping ");
200     module_name_.append(keymaster0_device->common.module->name);
201     module_name_.append(")");
202 
203     updated_module_ = *km1_device_.common.module;
204     updated_module_.name = module_name_.c_str();
205 
206     km1_device_.common.module = &updated_module_;
207 
208     wrapped_km1_device_ = nullptr;
209     return KM_ERROR_OK;
210 }
211 
SetHardwareDevice(keymaster1_device_t * keymaster1_device)212 keymaster_error_t SoftKeymasterDevice::SetHardwareDevice(keymaster1_device_t* keymaster1_device) {
213     assert(keymaster1_device);
214     LOG_D("Reinitializing SoftKeymasterDevice to use HW keymaster1", 0);
215 
216     if (!context_)
217         return KM_ERROR_UNEXPECTED_NULL_POINTER;
218 
219     keymaster_error_t error =
220         map_digests(keymaster1_device, &km1_device_digests_, &supports_all_digests_);
221     if (error != KM_ERROR_OK)
222         return error;
223 
224     error = context_->SetHardwareDevice(keymaster1_device);
225     if (error != KM_ERROR_OK)
226         return error;
227 
228     initialize_device_struct(keymaster1_device->flags);
229 
230     module_name_ = km1_device_.common.module->name;
231     module_name_.append(" (Wrapping ");
232     module_name_.append(keymaster1_device->common.module->name);
233     module_name_.append(")");
234 
235     updated_module_ = *km1_device_.common.module;
236     updated_module_.name = module_name_.c_str();
237 
238     km1_device_.common.module = &updated_module_;
239 
240     wrapped_km1_device_ = keymaster1_device;
241     return KM_ERROR_OK;
242 }
243 
Keymaster1DeviceIsGood()244 bool 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 
initialize_device_struct(uint32_t flags)265 void 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 
hw_device()332 hw_device_t* SoftKeymasterDevice::hw_device() {
333     return &km1_device_.common;
334 }
335 
keymaster_device()336 keymaster1_device_t* SoftKeymasterDevice::keymaster_device() {
337     return &km1_device_;
338 }
339 
keymaster2_device()340 keymaster2_device_t* SoftKeymasterDevice::keymaster2_device() {
341     return &km2_device_;
342 }
343 
344 namespace {
345 
BuildCharacteristics(const AuthorizationSet & hw_enforced,const AuthorizationSet & sw_enforced)346 keymaster_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 
358 template <typename RequestType>
AddClientAndAppData(const keymaster_blob_t * client_id,const keymaster_blob_t * app_data,RequestType * request)359 void 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 
convert_device(const T * dev)368 template <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 
376 template <keymaster_tag_t Tag, keymaster_tag_type_t Type, typename KeymasterEnum>
FindTagValue(const keymaster_key_param_set_t & params,TypedEnumTag<Type,Tag,KeymasterEnum> tag,KeymasterEnum * value)377 bool 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 */
close_device(hw_device_t * dev)390 int 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 */
get_supported_algorithms(const keymaster1_device_t * dev,keymaster_algorithm_t ** algorithms,size_t * algorithms_length)410 keymaster_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 */
get_supported_block_modes(const keymaster1_device_t * dev,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,keymaster_block_mode_t ** modes,size_t * modes_length)442 keymaster_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 */
get_supported_padding_modes(const keymaster1_device_t * dev,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,keymaster_padding_t ** modes,size_t * modes_length)478 keymaster_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 */
get_supported_digests(const keymaster1_device_t * dev,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,keymaster_digest_t ** digests,size_t * digests_length)514 keymaster_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 */
get_supported_import_formats(const keymaster1_device_t * dev,keymaster_algorithm_t algorithm,keymaster_key_format_t ** formats,size_t * formats_length)549 keymaster_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 */
get_supported_export_formats(const keymaster1_device_t * dev,keymaster_algorithm_t algorithm,keymaster_key_format_t ** formats,size_t * formats_length)582 keymaster_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 */
configure(const keymaster2_device_t * dev,const keymaster_key_param_set_t * params)615 keymaster_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 */
add_rng_entropy(const keymaster1_device_t * dev,const uint8_t * data,size_t data_length)632 keymaster_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 */
add_rng_entropy(const keymaster2_device_t * dev,const uint8_t * data,size_t data_length)651 keymaster_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 
contains(const Collection & c,const Value & v)663 template <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 
FindUnsupportedDigest(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,const AuthorizationSet & params,keymaster_digest_t * unsupported) const667 bool 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 
RequiresSoftwareDigesting(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,const AuthorizationSet & params) const689 bool 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     case KM_ALGORITHM_TRIPLE_DES:
699         LOG_D("Not performing software digesting for algorithm %d", algorithm);
700         return false;
701     case KM_ALGORITHM_HMAC:
702     case KM_ALGORITHM_RSA:
703     case KM_ALGORITHM_EC:
704         break;
705     }
706 
707     keymaster_digest_t unsupported;
708     if (!FindUnsupportedDigest(algorithm, purpose, params, &unsupported)) {
709         LOG_D("Requested digest(s) supported for algorithm %d and purpose %d", algorithm, purpose);
710         return false;
711     }
712 
713     return true;
714 }
715 
KeyRequiresSoftwareDigesting(const AuthorizationSet & key_description) const716 bool SoftKeymasterDevice::KeyRequiresSoftwareDigesting(
717     const AuthorizationSet& key_description) const {
718     assert(wrapped_km1_device_);
719     if (!wrapped_km1_device_)
720         return true;
721 
722     keymaster_algorithm_t algorithm;
723     if (!key_description.GetTagValue(TAG_ALGORITHM, &algorithm)) {
724         // The hardware module will return an error during keygen.
725         return false;
726     }
727 
728     for (auto& entry : key_description)
729         if (entry.tag == TAG_PURPOSE) {
730             keymaster_purpose_t purpose = static_cast<keymaster_purpose_t>(entry.enumerated);
731             if (RequiresSoftwareDigesting(algorithm, purpose, key_description))
732                 return true;
733         }
734 
735     return false;
736 }
737 
738 /* static */
generate_key(const keymaster1_device_t * dev,const keymaster_key_param_set_t * params,keymaster_key_blob_t * key_blob,keymaster_key_characteristics_t ** characteristics)739 keymaster_error_t SoftKeymasterDevice::generate_key(
740     const keymaster1_device_t* dev, const keymaster_key_param_set_t* params,
741     keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
742     if (!dev || !params)
743         return KM_ERROR_UNEXPECTED_NULL_POINTER;
744 
745     if (!key_blob)
746         return KM_ERROR_OUTPUT_PARAMETER_NULL;
747 
748     SoftKeymasterDevice* sk_dev = convert_device(dev);
749 
750     GenerateKeyRequest request;
751     request.key_description.Reinitialize(*params);
752 
753     keymaster1_device_t* km1_dev = sk_dev->wrapped_km1_device_;
754     if (km1_dev && !sk_dev->KeyRequiresSoftwareDigesting(request.key_description))
755         return km1_dev->generate_key(km1_dev, params, key_blob, characteristics);
756 
757     GenerateKeyResponse response;
758     sk_dev->impl_->GenerateKey(request, &response);
759     if (response.error != KM_ERROR_OK)
760         return response.error;
761 
762     key_blob->key_material_size = response.key_blob.key_material_size;
763     uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
764     if (!tmp)
765         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
766     memcpy(tmp, response.key_blob.key_material, response.key_blob.key_material_size);
767     key_blob->key_material = tmp;
768 
769     if (characteristics) {
770         // This is a keymaster1 method, and keymaster1 doesn't include version info, so remove it.
771         response.enforced.erase(response.enforced.find(TAG_OS_VERSION));
772         response.enforced.erase(response.enforced.find(TAG_OS_PATCHLEVEL));
773         response.unenforced.erase(response.unenforced.find(TAG_OS_VERSION));
774         response.unenforced.erase(response.unenforced.find(TAG_OS_PATCHLEVEL));
775 
776         *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
777         if (!*characteristics)
778             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
779     }
780 
781     return KM_ERROR_OK;
782 }
783 
784 keymaster_error_t
generate_key(const keymaster2_device_t * dev,const keymaster_key_param_set_t * params,keymaster_key_blob_t * key_blob,keymaster_key_characteristics_t * characteristics)785 SoftKeymasterDevice::generate_key(const keymaster2_device_t* dev,  //
786                                   const keymaster_key_param_set_t* params,
787                                   keymaster_key_blob_t* key_blob,
788                                   keymaster_key_characteristics_t* characteristics) {
789     if (!dev)
790         return KM_ERROR_UNEXPECTED_NULL_POINTER;
791 
792     if (!convert_device(dev)->configured())
793         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
794 
795     if (!key_blob)
796         return KM_ERROR_OUTPUT_PARAMETER_NULL;
797 
798     SoftKeymasterDevice* sk_dev = convert_device(dev);
799 
800     GenerateKeyRequest request;
801     request.key_description.Reinitialize(*params);
802 
803     keymaster1_device_t* km1_dev = sk_dev->wrapped_km1_device_;
804     if (km1_dev && !sk_dev->KeyRequiresSoftwareDigesting(request.key_description)) {
805         keymaster_ec_curve_t curve;
806         if (request.key_description.Contains(TAG_ALGORITHM, KM_ALGORITHM_EC) &&
807             request.key_description.GetTagValue(TAG_EC_CURVE, &curve)) {
808             // Keymaster1 doesn't know about EC curves. We need to translate to key size.
809             uint32_t key_size_from_curve;
810             keymaster_error_t error = EcCurveToKeySize(curve, &key_size_from_curve);
811             if (error != KM_ERROR_OK) {
812                 return error;
813             }
814 
815             uint32_t key_size_from_desc;
816             if (request.key_description.GetTagValue(TAG_KEY_SIZE, &key_size_from_desc)) {
817                 if (key_size_from_desc != key_size_from_curve) {
818                     return KM_ERROR_INVALID_ARGUMENT;
819                 }
820             } else {
821                 request.key_description.push_back(TAG_KEY_SIZE, key_size_from_curve);
822             }
823         }
824 
825         keymaster_key_characteristics_t* chars_ptr;
826         keymaster_error_t error = km1_dev->generate_key(km1_dev, &request.key_description, key_blob,
827                                                         characteristics ? &chars_ptr : nullptr);
828         if (error != KM_ERROR_OK)
829             return error;
830 
831         if (characteristics) {
832             *characteristics = *chars_ptr;
833             free(chars_ptr);
834         }
835 
836         return KM_ERROR_OK;
837     }
838 
839     GenerateKeyResponse response;
840     sk_dev->impl_->GenerateKey(request, &response);
841     if (response.error != KM_ERROR_OK)
842         return response.error;
843 
844     key_blob->key_material_size = response.key_blob.key_material_size;
845     uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
846     if (!tmp)
847         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
848     memcpy(tmp, response.key_blob.key_material, response.key_blob.key_material_size);
849     key_blob->key_material = tmp;
850 
851     if (characteristics) {
852         response.enforced.CopyToParamSet(&characteristics->hw_enforced);
853         response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
854     }
855 
856     return KM_ERROR_OK;
857 }
858 
859 /* static */
get_key_characteristics(const keymaster1_device_t * dev,const keymaster_key_blob_t * key_blob,const keymaster_blob_t * client_id,const keymaster_blob_t * app_data,keymaster_key_characteristics_t ** characteristics)860 keymaster_error_t SoftKeymasterDevice::get_key_characteristics(
861     const keymaster1_device_t* dev, const keymaster_key_blob_t* key_blob,
862     const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
863     keymaster_key_characteristics_t** characteristics) {
864     if (!dev || !key_blob || !key_blob->key_material)
865         return KM_ERROR_UNEXPECTED_NULL_POINTER;
866 
867     if (!characteristics)
868         return KM_ERROR_OUTPUT_PARAMETER_NULL;
869 
870     const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
871     if (km1_dev) {
872         keymaster_error_t error = km1_dev->get_key_characteristics(km1_dev, key_blob, client_id,
873                                                                    app_data, characteristics);
874         if (error != KM_ERROR_INVALID_KEY_BLOB) {
875             return error;
876         }
877         // If we got "invalid blob", continue to try with the software device. This might be a
878         // software key blob.
879     }
880 
881     GetKeyCharacteristicsRequest request;
882     request.SetKeyMaterial(*key_blob);
883     AddClientAndAppData(client_id, app_data, &request);
884 
885     GetKeyCharacteristicsResponse response;
886     convert_device(dev)->impl_->GetKeyCharacteristics(request, &response);
887     if (response.error != KM_ERROR_OK)
888         return response.error;
889 
890     // This is a keymaster1 method, and keymaster1 doesn't include version info, so remove it.
891     response.enforced.erase(response.enforced.find(TAG_OS_VERSION));
892     response.enforced.erase(response.enforced.find(TAG_OS_PATCHLEVEL));
893     response.unenforced.erase(response.unenforced.find(TAG_OS_VERSION));
894     response.unenforced.erase(response.unenforced.find(TAG_OS_PATCHLEVEL));
895 
896     *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
897     if (!*characteristics)
898         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
899 
900     return KM_ERROR_OK;
901 }
902 
903 /* static */
get_key_characteristics(const keymaster2_device_t * dev,const keymaster_key_blob_t * key_blob,const keymaster_blob_t * client_id,const keymaster_blob_t * app_data,keymaster_key_characteristics_t * characteristics)904 keymaster_error_t SoftKeymasterDevice::get_key_characteristics(
905     const keymaster2_device_t* dev, const keymaster_key_blob_t* key_blob,
906     const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
907     keymaster_key_characteristics_t* characteristics) {
908     if (!dev)
909         return KM_ERROR_UNEXPECTED_NULL_POINTER;
910 
911     if (!convert_device(dev)->configured())
912         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
913 
914     if (!characteristics)
915         return KM_ERROR_OUTPUT_PARAMETER_NULL;
916 
917     SoftKeymasterDevice* sk_dev = convert_device(dev);
918 
919     GetKeyCharacteristicsRequest request;
920     request.SetKeyMaterial(*key_blob);
921     AddClientAndAppData(client_id, app_data, &request);
922 
923     GetKeyCharacteristicsResponse response;
924     sk_dev->impl_->GetKeyCharacteristics(request, &response);
925     if (response.error != KM_ERROR_OK)
926         return response.error;
927 
928     response.enforced.CopyToParamSet(&characteristics->hw_enforced);
929     response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
930 
931     return KM_ERROR_OK;
932 }
933 
934 /* static */
import_key(const keymaster1_device_t * dev,const keymaster_key_param_set_t * params,keymaster_key_format_t key_format,const keymaster_blob_t * key_data,keymaster_key_blob_t * key_blob,keymaster_key_characteristics_t ** characteristics)935 keymaster_error_t SoftKeymasterDevice::import_key(
936     const keymaster1_device_t* dev, const keymaster_key_param_set_t* params,
937     keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
938     keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
939     if (!params || !key_data)
940         return KM_ERROR_UNEXPECTED_NULL_POINTER;
941 
942     if (!key_blob)
943         return KM_ERROR_OUTPUT_PARAMETER_NULL;
944 
945     SoftKeymasterDevice* sk_dev = convert_device(dev);
946 
947     ImportKeyRequest request;
948     request.key_description.Reinitialize(*params);
949 
950     keymaster1_device_t* km1_dev = sk_dev->wrapped_km1_device_;
951     if (km1_dev && !sk_dev->KeyRequiresSoftwareDigesting(request.key_description))
952         return km1_dev->import_key(km1_dev, params, key_format, key_data, key_blob,
953                                    characteristics);
954 
955     if (characteristics)
956         *characteristics = nullptr;
957 
958     request.key_format = key_format;
959     request.SetKeyMaterial(key_data->data, key_data->data_length);
960 
961     ImportKeyResponse response;
962     convert_device(dev)->impl_->ImportKey(request, &response);
963     if (response.error != KM_ERROR_OK)
964         return response.error;
965 
966     key_blob->key_material_size = response.key_blob.key_material_size;
967     key_blob->key_material = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
968     if (!key_blob->key_material)
969         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
970     memcpy(const_cast<uint8_t*>(key_blob->key_material), response.key_blob.key_material,
971            response.key_blob.key_material_size);
972 
973     if (characteristics) {
974         *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
975         if (!*characteristics)
976             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
977     }
978     return KM_ERROR_OK;
979 }
980 
981 /* static */
import_key(const keymaster2_device_t * dev,const keymaster_key_param_set_t * params,keymaster_key_format_t key_format,const keymaster_blob_t * key_data,keymaster_key_blob_t * key_blob,keymaster_key_characteristics_t * characteristics)982 keymaster_error_t SoftKeymasterDevice::import_key(
983     const keymaster2_device_t* dev, const keymaster_key_param_set_t* params,
984     keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
985     keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t* characteristics) {
986     if (!dev)
987         return KM_ERROR_UNEXPECTED_NULL_POINTER;
988 
989     if (!convert_device(dev)->configured())
990         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
991 
992     SoftKeymasterDevice* sk_dev = convert_device(dev);
993 
994     keymaster_error_t error;
995     if (characteristics) {
996         keymaster_key_characteristics_t* characteristics_ptr;
997         error = import_key(&sk_dev->km1_device_, params, key_format, key_data, key_blob,
998                            &characteristics_ptr);
999         if (error == KM_ERROR_OK) {
1000             *characteristics = *characteristics_ptr;
1001             free(characteristics_ptr);
1002         }
1003     } else {
1004         error = import_key(&sk_dev->km1_device_, params, key_format, key_data, key_blob, nullptr);
1005     }
1006 
1007     return error;
1008 }
1009 
1010 /* static */
export_key(const keymaster1_device_t * dev,keymaster_key_format_t export_format,const keymaster_key_blob_t * key_to_export,const keymaster_blob_t * client_id,const keymaster_blob_t * app_data,keymaster_blob_t * export_data)1011 keymaster_error_t SoftKeymasterDevice::export_key(const keymaster1_device_t* dev,
1012                                                   keymaster_key_format_t export_format,
1013                                                   const keymaster_key_blob_t* key_to_export,
1014                                                   const keymaster_blob_t* client_id,
1015                                                   const keymaster_blob_t* app_data,
1016                                                   keymaster_blob_t* export_data) {
1017     if (!key_to_export || !key_to_export->key_material)
1018         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1019 
1020     if (!export_data)
1021         return KM_ERROR_OUTPUT_PARAMETER_NULL;
1022 
1023     const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1024     if (km1_dev)
1025         return km1_dev->export_key(km1_dev, export_format, key_to_export, client_id, app_data,
1026                                    export_data);
1027 
1028     export_data->data = nullptr;
1029     export_data->data_length = 0;
1030 
1031     ExportKeyRequest request;
1032     request.key_format = export_format;
1033     request.SetKeyMaterial(*key_to_export);
1034     AddClientAndAppData(client_id, app_data, &request);
1035 
1036     ExportKeyResponse response;
1037     convert_device(dev)->impl_->ExportKey(request, &response);
1038     if (response.error != KM_ERROR_OK)
1039         return response.error;
1040 
1041     export_data->data_length = response.key_data_length;
1042     uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(export_data->data_length));
1043     if (!tmp)
1044         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1045     memcpy(tmp, response.key_data, export_data->data_length);
1046     export_data->data = tmp;
1047     return KM_ERROR_OK;
1048 }
1049 
1050 /* static */
export_key(const keymaster2_device_t * dev,keymaster_key_format_t export_format,const keymaster_key_blob_t * key_to_export,const keymaster_blob_t * client_id,const keymaster_blob_t * app_data,keymaster_blob_t * export_data)1051 keymaster_error_t SoftKeymasterDevice::export_key(const keymaster2_device_t* dev,
1052                                                   keymaster_key_format_t export_format,
1053                                                   const keymaster_key_blob_t* key_to_export,
1054                                                   const keymaster_blob_t* client_id,
1055                                                   const keymaster_blob_t* app_data,
1056                                                   keymaster_blob_t* export_data) {
1057     if (!dev)
1058         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1059 
1060     if (!convert_device(dev)->configured())
1061         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1062 
1063     SoftKeymasterDevice* sk_dev = convert_device(dev);
1064     return export_key(&sk_dev->km1_device_, export_format, key_to_export, client_id, app_data,
1065                       export_data);
1066 }
1067 
1068 /* static */
attest_key(const keymaster2_device_t * dev,const keymaster_key_blob_t * key_to_attest,const keymaster_key_param_set_t * attest_params,keymaster_cert_chain_t * cert_chain)1069 keymaster_error_t SoftKeymasterDevice::attest_key(const keymaster2_device_t* dev,
1070                                                   const keymaster_key_blob_t* key_to_attest,
1071                                                   const keymaster_key_param_set_t* attest_params,
1072                                                   keymaster_cert_chain_t* cert_chain) {
1073     if (!dev || !key_to_attest || !attest_params || !cert_chain)
1074         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1075 
1076     if (!convert_device(dev)->configured())
1077         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1078 
1079     *cert_chain = {};
1080 
1081     AttestKeyRequest request;
1082     request.SetKeyMaterial(*key_to_attest);
1083     request.attest_params.Reinitialize(*attest_params);
1084 
1085     keymaster_blob_t attestation_challenge = {};
1086     request.attest_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge);
1087     if (attestation_challenge.data_length > kMaximumAttestationChallengeLength) {
1088         LOG_E("%d-byte attestation challenge; only %d bytes allowed",
1089               attestation_challenge.data_length, kMaximumAttestationChallengeLength);
1090         return KM_ERROR_INVALID_INPUT_LENGTH;
1091     }
1092 
1093     AttestKeyResponse response;
1094     convert_device(dev)->impl_->AttestKey(request, &response);
1095     if (response.error != KM_ERROR_OK)
1096         return response.error;
1097 
1098     // Allocate and clear storage for cert_chain.
1099     keymaster_cert_chain_t& rsp_chain = response.certificate_chain;
1100     cert_chain->entries = reinterpret_cast<keymaster_blob_t*>(
1101         malloc(rsp_chain.entry_count * sizeof(*cert_chain->entries)));
1102     if (!cert_chain->entries)
1103         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1104     cert_chain->entry_count = rsp_chain.entry_count;
1105     for (keymaster_blob_t& entry : array_range(cert_chain->entries, cert_chain->entry_count))
1106         entry = {};
1107 
1108     // Copy cert_chain contents
1109     size_t i = 0;
1110     for (keymaster_blob_t& entry : array_range(rsp_chain.entries, rsp_chain.entry_count)) {
1111         cert_chain->entries[i].data = reinterpret_cast<uint8_t*>(malloc(entry.data_length));
1112         if (!cert_chain->entries[i].data) {
1113             keymaster_free_cert_chain(cert_chain);
1114             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1115         }
1116         cert_chain->entries[i].data_length = entry.data_length;
1117         memcpy(const_cast<uint8_t*>(cert_chain->entries[i].data), entry.data, entry.data_length);
1118         ++i;
1119     }
1120 
1121     return KM_ERROR_OK;
1122 }
1123 
1124 /* static */
upgrade_key(const keymaster2_device_t * dev,const keymaster_key_blob_t * key_to_upgrade,const keymaster_key_param_set_t * upgrade_params,keymaster_key_blob_t * upgraded_key)1125 keymaster_error_t SoftKeymasterDevice::upgrade_key(const keymaster2_device_t* dev,
1126                                                    const keymaster_key_blob_t* key_to_upgrade,
1127                                                    const keymaster_key_param_set_t* upgrade_params,
1128                                                    keymaster_key_blob_t* upgraded_key) {
1129     if (!dev || !key_to_upgrade || !upgrade_params)
1130         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1131 
1132     if (!upgraded_key)
1133         return KM_ERROR_OUTPUT_PARAMETER_NULL;
1134 
1135     if (!convert_device(dev)->configured())
1136         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1137 
1138     UpgradeKeyRequest request;
1139     request.SetKeyMaterial(*key_to_upgrade);
1140     request.upgrade_params.Reinitialize(*upgrade_params);
1141 
1142     UpgradeKeyResponse response;
1143     convert_device(dev)->impl_->UpgradeKey(request, &response);
1144     if (response.error != KM_ERROR_OK)
1145         return response.error;
1146 
1147     upgraded_key->key_material_size = response.upgraded_key.key_material_size;
1148     uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(upgraded_key->key_material_size));
1149     if (!tmp)
1150         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1151     memcpy(tmp, response.upgraded_key.key_material, response.upgraded_key.key_material_size);
1152     upgraded_key->key_material = tmp;
1153 
1154     return KM_ERROR_OK;
1155 }
1156 
1157 /* static */
delete_key(const keymaster1_device_t * dev,const keymaster_key_blob_t * key)1158 keymaster_error_t SoftKeymasterDevice::delete_key(const keymaster1_device_t* dev,
1159                                                   const keymaster_key_blob_t* key) {
1160     if (!dev || !key || !key->key_material)
1161         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1162 
1163     KeymasterKeyBlob blob(*key);
1164     return convert_device(dev)->context_->DeleteKey(blob);
1165 }
1166 
1167 /* static */
delete_key(const keymaster2_device_t * dev,const keymaster_key_blob_t * key)1168 keymaster_error_t SoftKeymasterDevice::delete_key(const keymaster2_device_t* dev,
1169                                                   const keymaster_key_blob_t* key) {
1170     if (!dev || !key || !key->key_material)
1171         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1172 
1173     if (!convert_device(dev)->configured())
1174         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1175 
1176     KeymasterKeyBlob blob(*key);
1177     return convert_device(dev)->context_->DeleteKey(blob);
1178 }
1179 
1180 /* static */
delete_all_keys(const keymaster1_device_t * dev)1181 keymaster_error_t SoftKeymasterDevice::delete_all_keys(const keymaster1_device_t* dev) {
1182     if (!dev)
1183         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1184 
1185     return convert_device(dev)->context_->DeleteAllKeys();
1186 }
1187 
1188 /* static */
delete_all_keys(const keymaster2_device_t * dev)1189 keymaster_error_t SoftKeymasterDevice::delete_all_keys(const keymaster2_device_t* dev) {
1190     if (!dev)
1191         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1192 
1193     if (!convert_device(dev)->configured())
1194         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1195 
1196     return convert_device(dev)->context_->DeleteAllKeys();
1197 }
1198 
1199 /* static */
begin(const keymaster1_device_t * dev,keymaster_purpose_t purpose,const keymaster_key_blob_t * key,const keymaster_key_param_set_t * in_params,keymaster_key_param_set_t * out_params,keymaster_operation_handle_t * operation_handle)1200 keymaster_error_t SoftKeymasterDevice::begin(const keymaster1_device_t* dev,
1201                                              keymaster_purpose_t purpose,
1202                                              const keymaster_key_blob_t* key,
1203                                              const keymaster_key_param_set_t* in_params,
1204                                              keymaster_key_param_set_t* out_params,
1205                                              keymaster_operation_handle_t* operation_handle) {
1206     if (!dev || !key || !key->key_material)
1207         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1208 
1209     if (!operation_handle)
1210         return KM_ERROR_OUTPUT_PARAMETER_NULL;
1211 
1212     SoftKeymasterDevice* skdev = convert_device(dev);
1213     const keymaster1_device_t* km1_dev = skdev->wrapped_km1_device_;
1214 
1215     if (km1_dev) {
1216         AuthorizationSet in_params_set(*in_params);
1217 
1218         UniquePtr<Key> akmKey; // android keymaster key
1219         skdev->context_->ParseKeyBlob(KeymasterKeyBlob(*key), in_params_set, &akmKey);
1220 
1221         keymaster_algorithm_t algorithm = KM_ALGORITHM_AES;
1222         if (!akmKey->hw_enforced().GetTagValue(TAG_ALGORITHM, &algorithm) &&
1223             !akmKey->sw_enforced().GetTagValue(TAG_ALGORITHM, &algorithm)) {
1224             return KM_ERROR_INVALID_KEY_BLOB;
1225         }
1226 
1227         if (algorithm == KM_ALGORITHM_HMAC) {
1228             // Because HMAC keys can have only one digest, in_params_set doesn't contain it.  We
1229             // need to get the digest from the key and add it to in_params_set.
1230             keymaster_digest_t digest;
1231             if (!akmKey->hw_enforced().GetTagValue(TAG_DIGEST, &digest) &&
1232                 !akmKey->sw_enforced().GetTagValue(TAG_DIGEST, &digest)) {
1233                 return KM_ERROR_INVALID_KEY_BLOB;
1234             }
1235             in_params_set.push_back(TAG_DIGEST, digest);
1236         }
1237 
1238         if (!skdev->RequiresSoftwareDigesting(algorithm, purpose, in_params_set)) {
1239             LOG_D("Operation supported by %s, passing through to keymaster1 module",
1240                   km1_dev->common.module->name);
1241             return km1_dev->begin(km1_dev, purpose, key, in_params, out_params, operation_handle);
1242         }
1243         LOG_I("Doing software digesting for keymaster1 module %s", km1_dev->common.module->name);
1244     }
1245 
1246     if (out_params) {
1247         out_params->params = nullptr;
1248         out_params->length = 0;
1249     }
1250 
1251     BeginOperationRequest request;
1252     request.purpose = purpose;
1253     request.SetKeyMaterial(*key);
1254     request.additional_params.Reinitialize(*in_params);
1255 
1256     BeginOperationResponse response;
1257     skdev->impl_->BeginOperation(request, &response);
1258     if (response.error != KM_ERROR_OK)
1259         return response.error;
1260 
1261     if (response.output_params.size() > 0) {
1262         if (out_params)
1263             response.output_params.CopyToParamSet(out_params);
1264         else
1265             return KM_ERROR_OUTPUT_PARAMETER_NULL;
1266     }
1267 
1268     *operation_handle = response.op_handle;
1269     return KM_ERROR_OK;
1270 }
1271 
1272 /* static */
begin(const keymaster2_device_t * dev,keymaster_purpose_t purpose,const keymaster_key_blob_t * key,const keymaster_key_param_set_t * in_params,keymaster_key_param_set_t * out_params,keymaster_operation_handle_t * operation_handle)1273 keymaster_error_t SoftKeymasterDevice::begin(const keymaster2_device_t* dev,
1274                                              keymaster_purpose_t purpose,
1275                                              const keymaster_key_blob_t* key,
1276                                              const keymaster_key_param_set_t* in_params,
1277                                              keymaster_key_param_set_t* out_params,
1278                                              keymaster_operation_handle_t* operation_handle) {
1279     if (!dev)
1280         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1281 
1282     if (!convert_device(dev)->configured())
1283         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1284 
1285     SoftKeymasterDevice* sk_dev = convert_device(dev);
1286     return begin(&sk_dev->km1_device_, purpose, key, in_params, out_params, operation_handle);
1287 }
1288 
1289 /* static */
update(const keymaster1_device_t * dev,keymaster_operation_handle_t operation_handle,const keymaster_key_param_set_t * in_params,const keymaster_blob_t * input,size_t * input_consumed,keymaster_key_param_set_t * out_params,keymaster_blob_t * output)1290 keymaster_error_t SoftKeymasterDevice::update(const keymaster1_device_t* dev,
1291                                               keymaster_operation_handle_t operation_handle,
1292                                               const keymaster_key_param_set_t* in_params,
1293                                               const keymaster_blob_t* input, size_t* input_consumed,
1294                                               keymaster_key_param_set_t* out_params,
1295                                               keymaster_blob_t* output) {
1296     if (!input)
1297         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1298 
1299     if (!input_consumed)
1300         return KM_ERROR_OUTPUT_PARAMETER_NULL;
1301 
1302     const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1303     if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1304         // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1305         // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1306         // km1_dev after doing necessary digesting.
1307         return km1_dev->update(km1_dev, operation_handle, in_params, input, input_consumed,
1308                                out_params, output);
1309     }
1310 
1311     if (out_params) {
1312         out_params->params = nullptr;
1313         out_params->length = 0;
1314     }
1315     if (output) {
1316         output->data = nullptr;
1317         output->data_length = 0;
1318     }
1319 
1320     UpdateOperationRequest request;
1321     request.op_handle = operation_handle;
1322     if (input)
1323         request.input.Reinitialize(input->data, input->data_length);
1324     if (in_params)
1325         request.additional_params.Reinitialize(*in_params);
1326 
1327     UpdateOperationResponse response;
1328     convert_device(dev)->impl_->UpdateOperation(request, &response);
1329     if (response.error != KM_ERROR_OK)
1330         return response.error;
1331 
1332     if (response.output_params.size() > 0) {
1333         if (out_params)
1334             response.output_params.CopyToParamSet(out_params);
1335         else
1336             return KM_ERROR_OUTPUT_PARAMETER_NULL;
1337     }
1338 
1339     *input_consumed = response.input_consumed;
1340     if (output) {
1341         output->data_length = response.output.available_read();
1342         uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1343         if (!tmp)
1344             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1345         memcpy(tmp, response.output.peek_read(), output->data_length);
1346         output->data = tmp;
1347     } else if (response.output.available_read() > 0) {
1348         return KM_ERROR_OUTPUT_PARAMETER_NULL;
1349     }
1350     return KM_ERROR_OK;
1351 }
1352 
1353 /* static */
update(const keymaster2_device_t * dev,keymaster_operation_handle_t operation_handle,const keymaster_key_param_set_t * in_params,const keymaster_blob_t * input,size_t * input_consumed,keymaster_key_param_set_t * out_params,keymaster_blob_t * output)1354 keymaster_error_t SoftKeymasterDevice::update(const keymaster2_device_t* dev,
1355                                               keymaster_operation_handle_t operation_handle,
1356                                               const keymaster_key_param_set_t* in_params,
1357                                               const keymaster_blob_t* input, size_t* input_consumed,
1358                                               keymaster_key_param_set_t* out_params,
1359                                               keymaster_blob_t* output) {
1360     if (!dev)
1361         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1362 
1363     if (!convert_device(dev)->configured())
1364         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1365 
1366     SoftKeymasterDevice* sk_dev = convert_device(dev);
1367     return update(&sk_dev->km1_device_, operation_handle, in_params, input, input_consumed,
1368                   out_params, output);
1369 }
1370 
1371 /* static */
finish(const keymaster1_device_t * dev,keymaster_operation_handle_t operation_handle,const keymaster_key_param_set_t * params,const keymaster_blob_t * signature,keymaster_key_param_set_t * out_params,keymaster_blob_t * output)1372 keymaster_error_t SoftKeymasterDevice::finish(const keymaster1_device_t* dev,
1373                                               keymaster_operation_handle_t operation_handle,
1374                                               const keymaster_key_param_set_t* params,
1375                                               const keymaster_blob_t* signature,
1376                                               keymaster_key_param_set_t* out_params,
1377                                               keymaster_blob_t* output) {
1378     if (!dev)
1379         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1380 
1381     const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1382     if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1383         // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1384         // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1385         // km1_dev after doing necessary digesting.
1386         return km1_dev->finish(km1_dev, operation_handle, params, signature, out_params, output);
1387     }
1388 
1389     if (out_params) {
1390         out_params->params = nullptr;
1391         out_params->length = 0;
1392     }
1393 
1394     if (output) {
1395         output->data = nullptr;
1396         output->data_length = 0;
1397     }
1398 
1399     FinishOperationRequest request;
1400     request.op_handle = operation_handle;
1401     if (signature && signature->data_length > 0)
1402         request.signature.Reinitialize(signature->data, signature->data_length);
1403     request.additional_params.Reinitialize(*params);
1404 
1405     FinishOperationResponse response;
1406     convert_device(dev)->impl_->FinishOperation(request, &response);
1407     if (response.error != KM_ERROR_OK)
1408         return response.error;
1409 
1410     if (response.output_params.size() > 0) {
1411         if (out_params)
1412             response.output_params.CopyToParamSet(out_params);
1413         else
1414             return KM_ERROR_OUTPUT_PARAMETER_NULL;
1415     }
1416     if (output) {
1417         output->data_length = response.output.available_read();
1418         uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1419         if (!tmp)
1420             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1421         memcpy(tmp, response.output.peek_read(), output->data_length);
1422         output->data = tmp;
1423     } else if (response.output.available_read() > 0) {
1424         return KM_ERROR_OUTPUT_PARAMETER_NULL;
1425     }
1426 
1427     return KM_ERROR_OK;
1428 }
1429 
1430 struct KeyParamSetContents_Delete {
operator ()keymaster::KeyParamSetContents_Delete1431     void operator()(keymaster_key_param_set_t* p) { keymaster_free_param_set(p); }
1432 };
1433 
1434 /* static */
finish(const keymaster2_device_t * dev,keymaster_operation_handle_t operation_handle,const keymaster_key_param_set_t * params,const keymaster_blob_t * input,const keymaster_blob_t * signature,keymaster_key_param_set_t * out_params,keymaster_blob_t * output)1435 keymaster_error_t SoftKeymasterDevice::finish(const keymaster2_device_t* dev,
1436                                               keymaster_operation_handle_t operation_handle,
1437                                               const keymaster_key_param_set_t* params,
1438                                               const keymaster_blob_t* input,
1439                                               const keymaster_blob_t* signature,
1440                                               keymaster_key_param_set_t* out_params,
1441                                               keymaster_blob_t* output) {
1442     if (!dev)
1443         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1444 
1445     if (!convert_device(dev)->configured())
1446         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1447 
1448     if (out_params)
1449         *out_params = {};
1450 
1451     if (output)
1452         *output = {};
1453 
1454     const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1455     if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1456         // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1457         // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1458         // km1_dev after doing necessary digesting.
1459 
1460         std::vector<uint8_t> accumulated_output;
1461         AuthorizationSet accumulated_out_params;
1462         AuthorizationSet mutable_params(*params);
1463         if (input && input->data && input->data_length) {
1464             // Keymaster1 doesn't support input to finish().  Call update() to process input.
1465 
1466             accumulated_output.reserve(input->data_length);  // Guess at output size
1467             keymaster_blob_t mutable_input = *input;
1468 
1469             while (mutable_input.data_length > 0) {
1470                 keymaster_key_param_set_t update_out_params = {};
1471                 keymaster_blob_t update_output = {};
1472                 size_t input_consumed = 0;
1473                 keymaster_error_t error =
1474                     km1_dev->update(km1_dev, operation_handle, &mutable_params, &mutable_input,
1475                                     &input_consumed, &update_out_params, &update_output);
1476                 if (error != KM_ERROR_OK) {
1477                     return error;
1478                 }
1479 
1480                 accumulated_output.reserve(accumulated_output.size() + update_output.data_length);
1481                 std::copy(update_output.data, update_output.data + update_output.data_length,
1482                           std::back_inserter(accumulated_output));
1483                 free(const_cast<uint8_t*>(update_output.data));
1484 
1485                 accumulated_out_params.push_back(update_out_params);
1486                 keymaster_free_param_set(&update_out_params);
1487 
1488                 mutable_input.data += input_consumed;
1489                 mutable_input.data_length -= input_consumed;
1490 
1491                 // AAD should only be sent once, so remove it if present.
1492                 int aad_pos = mutable_params.find(TAG_ASSOCIATED_DATA);
1493                 if (aad_pos != -1) {
1494                     mutable_params.erase(aad_pos);
1495                 }
1496 
1497                 if (input_consumed == 0) {
1498                     // Apparently we need more input than we have to complete an operation.
1499                     km1_dev->abort(km1_dev, operation_handle);
1500                     return KM_ERROR_INVALID_INPUT_LENGTH;
1501                 }
1502             }
1503         }
1504 
1505         keymaster_key_param_set_t finish_out_params = {};
1506         keymaster_blob_t finish_output = {};
1507         keymaster_error_t error = km1_dev->finish(km1_dev, operation_handle, &mutable_params,
1508                                                   signature, &finish_out_params, &finish_output);
1509         if (error != KM_ERROR_OK) {
1510             return error;
1511         }
1512 
1513         if (!accumulated_out_params.empty()) {
1514             accumulated_out_params.push_back(finish_out_params);
1515             keymaster_free_param_set(&finish_out_params);
1516             accumulated_out_params.Deduplicate();
1517             accumulated_out_params.CopyToParamSet(&finish_out_params);
1518         }
1519         std::unique_ptr<keymaster_key_param_set_t, KeyParamSetContents_Delete>
1520             finish_out_params_deleter(&finish_out_params);
1521 
1522         if (!accumulated_output.empty()) {
1523             size_t finish_out_length = accumulated_output.size() + finish_output.data_length;
1524             uint8_t* finish_out_buf = reinterpret_cast<uint8_t*>(malloc(finish_out_length));
1525 
1526             std::copy(accumulated_output.begin(), accumulated_output.end(), finish_out_buf);
1527             std::copy(finish_output.data, finish_output.data + finish_output.data_length,
1528                       finish_out_buf + accumulated_output.size());
1529 
1530             free(const_cast<uint8_t*>(finish_output.data));
1531             finish_output.data_length = finish_out_length;
1532             finish_output.data = finish_out_buf;
1533         }
1534         std::unique_ptr<uint8_t, Malloc_Delete> finish_output_deleter(
1535             const_cast<uint8_t*>(finish_output.data));
1536 
1537         if ((!out_params && finish_out_params.length) || (!output && finish_output.data_length)) {
1538             return KM_ERROR_OUTPUT_PARAMETER_NULL;
1539         }
1540 
1541         if (out_params) {
1542             *out_params = finish_out_params;
1543         }
1544 
1545         if (output) {
1546             *output = finish_output;
1547         }
1548 
1549         finish_out_params_deleter.release();
1550         finish_output_deleter.release();
1551 
1552         return KM_ERROR_OK;
1553     }
1554 
1555     FinishOperationRequest request;
1556     request.op_handle = operation_handle;
1557     if (signature && signature->data_length > 0)
1558         request.signature.Reinitialize(signature->data, signature->data_length);
1559     if (input && input->data_length > 0)
1560         request.input.Reinitialize(input->data, input->data_length);
1561     request.additional_params.Reinitialize(*params);
1562 
1563     FinishOperationResponse response;
1564     convert_device(dev)->impl_->FinishOperation(request, &response);
1565     if (response.error != KM_ERROR_OK)
1566         return response.error;
1567 
1568     if (response.output_params.size() > 0) {
1569         if (out_params)
1570             response.output_params.CopyToParamSet(out_params);
1571         else
1572             return KM_ERROR_OUTPUT_PARAMETER_NULL;
1573     }
1574     if (output) {
1575         output->data_length = response.output.available_read();
1576         uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1577         if (!tmp)
1578             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1579         memcpy(tmp, response.output.peek_read(), output->data_length);
1580         output->data = tmp;
1581     } else if (response.output.available_read() > 0) {
1582         return KM_ERROR_OUTPUT_PARAMETER_NULL;
1583     }
1584 
1585     return KM_ERROR_OK;
1586 }
1587 
1588 /* static */
abort(const keymaster1_device_t * dev,keymaster_operation_handle_t operation_handle)1589 keymaster_error_t SoftKeymasterDevice::abort(const keymaster1_device_t* dev,
1590                                              keymaster_operation_handle_t operation_handle) {
1591     const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1592     if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1593         // This operation is being handled by km1_dev (or doesn't exist).  Pass it through to
1594         // km1_dev.  Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1595         // km1_dev.
1596         return km1_dev->abort(km1_dev, operation_handle);
1597     }
1598 
1599     AbortOperationRequest request;
1600     request.op_handle = operation_handle;
1601     AbortOperationResponse response;
1602     convert_device(dev)->impl_->AbortOperation(request, &response);
1603     return response.error;
1604 }
1605 
1606 /* static */
abort(const keymaster2_device_t * dev,keymaster_operation_handle_t operation_handle)1607 keymaster_error_t SoftKeymasterDevice::abort(const keymaster2_device_t* dev,
1608                                              keymaster_operation_handle_t operation_handle) {
1609     if (!dev)
1610         return KM_ERROR_UNEXPECTED_NULL_POINTER;
1611 
1612     if (!convert_device(dev)->configured())
1613         return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1614 
1615     SoftKeymasterDevice* sk_dev = convert_device(dev);
1616     return abort(&sk_dev->km1_device_, operation_handle);
1617 }
1618 
1619 /* static */
StoreDefaultNewKeyParams(keymaster_algorithm_t algorithm,AuthorizationSet * auth_set)1620 void SoftKeymasterDevice::StoreDefaultNewKeyParams(keymaster_algorithm_t algorithm,
1621                                                    AuthorizationSet* auth_set) {
1622     auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
1623     auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
1624     auth_set->push_back(TAG_ALL_USERS);
1625     auth_set->push_back(TAG_NO_AUTH_REQUIRED);
1626 
1627     // All digests.
1628     auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE);
1629     auth_set->push_back(TAG_DIGEST, KM_DIGEST_MD5);
1630     auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA1);
1631     auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_224);
1632     auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1633     auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
1634     auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_512);
1635 
1636     if (algorithm == KM_ALGORITHM_RSA) {
1637         auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_ENCRYPT);
1638         auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_DECRYPT);
1639         auth_set->push_back(TAG_PADDING, KM_PAD_NONE);
1640         auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1641         auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1642         auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1643         auth_set->push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
1644     }
1645 }
1646 
1647 }  // namespace keymaster
1648