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
46 struct 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
61 struct 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
76 namespace keymaster {
77
78 const size_t kMaximumAttestationChallengeLength = 128;
79 const size_t kOperationTableSize = 16;
80
make_vector(const T * array,size_t len)81 template <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.
89 struct PushbackCounter {
90 struct value_type {
value_typekeymaster::PushbackCounter::value_type91 template <typename T> value_type(const T&) {}
92 };
push_backkeymaster::PushbackCounter93 void push_back(const value_type&) { ++count; }
94 size_t count = 0;
95 };
96
97 static 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
digest_set_is_full(Iter begin,Iter end)101 template <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
add_digests(keymaster1_device_t * dev,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,SoftKeymasterDevice::DigestMap * map,bool * supports_all)108 static 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
map_digests(keymaster1_device_t * dev,SoftKeymasterDevice::DigestMap * map,bool * supports_all)129 static 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
SoftKeymasterDevice()161 SoftKeymasterDevice::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
SoftKeymasterDevice(SoftKeymasterContext * context)172 SoftKeymasterDevice::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
SetHardwareDevice(keymaster0_device_t * keymaster0_device)182 keymaster_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
SetHardwareDevice(keymaster1_device_t * keymaster1_device)211 keymaster_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
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 uint32_t os_version;
619 uint32_t os_patchlevel;
620 if (!params_copy.GetTagValue(TAG_OS_VERSION, &os_version) ||
621 !params_copy.GetTagValue(TAG_OS_PATCHLEVEL, &os_patchlevel)) {
622 LOG_E("Configuration parameters must contain OS version and patch level", 0);
623 return KM_ERROR_INVALID_ARGUMENT;
624 }
625
626 keymaster_error_t error =
627 convert_device(dev)->context_->SetSystemVersion(os_version, os_patchlevel);
628 if (error == KM_ERROR_OK)
629 convert_device(dev)->configured_ = true;
630 return error;
631 }
632
633 /* static */
add_rng_entropy(const keymaster1_device_t * dev,const uint8_t * data,size_t data_length)634 keymaster_error_t SoftKeymasterDevice::add_rng_entropy(const keymaster1_device_t* dev,
635 const uint8_t* data, size_t data_length) {
636 if (!dev)
637 return KM_ERROR_UNEXPECTED_NULL_POINTER;
638
639 const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
640 if (km1_dev)
641 return km1_dev->add_rng_entropy(km1_dev, data, data_length);
642
643 AddEntropyRequest request;
644 request.random_data.Reinitialize(data, data_length);
645 AddEntropyResponse response;
646 convert_device(dev)->impl_->AddRngEntropy(request, &response);
647 if (response.error != KM_ERROR_OK)
648 LOG_E("add_rng_entropy failed with %d", response.error);
649 return response.error;
650 }
651
652 /* static */
add_rng_entropy(const keymaster2_device_t * dev,const uint8_t * data,size_t data_length)653 keymaster_error_t SoftKeymasterDevice::add_rng_entropy(const keymaster2_device_t* dev,
654 const uint8_t* data, size_t data_length) {
655 if (!dev)
656 return KM_ERROR_UNEXPECTED_NULL_POINTER;
657
658 if (!convert_device(dev)->configured())
659 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
660
661 SoftKeymasterDevice* sk_dev = convert_device(dev);
662 return add_rng_entropy(&sk_dev->km1_device_, data, data_length);
663 }
664
contains(const Collection & c,const Value & v)665 template <typename Collection, typename Value> bool contains(const Collection& c, const Value& v) {
666 return std::find(c.begin(), c.end(), v) != c.end();
667 }
668
FindUnsupportedDigest(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,const AuthorizationSet & params,keymaster_digest_t * unsupported) const669 bool SoftKeymasterDevice::FindUnsupportedDigest(keymaster_algorithm_t algorithm,
670 keymaster_purpose_t purpose,
671 const AuthorizationSet& params,
672 keymaster_digest_t* unsupported) const {
673 assert(wrapped_km1_device_);
674
675 auto supported_digests = km1_device_digests_.find(std::make_pair(algorithm, purpose));
676 if (supported_digests == km1_device_digests_.end())
677 // Invalid algorith/purpose pair (e.g. EC encrypt). Let the error be handled by HW module.
678 return false;
679
680 for (auto& entry : params)
681 if (entry.tag == TAG_DIGEST)
682 if (!contains(supported_digests->second, entry.enumerated)) {
683 LOG_I("Digest %d requested but not supported by module %s", entry.enumerated,
684 wrapped_km1_device_->common.module->name);
685 *unsupported = static_cast<keymaster_digest_t>(entry.enumerated);
686 return true;
687 }
688 return false;
689 }
690
RequiresSoftwareDigesting(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,const AuthorizationSet & params) const691 bool SoftKeymasterDevice::RequiresSoftwareDigesting(keymaster_algorithm_t algorithm,
692 keymaster_purpose_t purpose,
693 const AuthorizationSet& params) const {
694 assert(wrapped_km1_device_);
695 if (!wrapped_km1_device_)
696 return true;
697
698 switch (algorithm) {
699 case KM_ALGORITHM_AES:
700 LOG_D("Not performing software digesting for AES keys", algorithm);
701 return false;
702 case KM_ALGORITHM_HMAC:
703 case KM_ALGORITHM_RSA:
704 case KM_ALGORITHM_EC:
705 break;
706 }
707
708 keymaster_digest_t unsupported;
709 if (!FindUnsupportedDigest(algorithm, purpose, params, &unsupported)) {
710 LOG_D("Requested digest(s) supported for algorithm %d and purpose %d", algorithm, purpose);
711 return false;
712 }
713
714 return true;
715 }
716
KeyRequiresSoftwareDigesting(const AuthorizationSet & key_description) const717 bool SoftKeymasterDevice::KeyRequiresSoftwareDigesting(
718 const AuthorizationSet& key_description) const {
719 assert(wrapped_km1_device_);
720 if (!wrapped_km1_device_)
721 return true;
722
723 keymaster_algorithm_t algorithm;
724 if (!key_description.GetTagValue(TAG_ALGORITHM, &algorithm)) {
725 // The hardware module will return an error during keygen.
726 return false;
727 }
728
729 for (auto& entry : key_description)
730 if (entry.tag == TAG_PURPOSE) {
731 keymaster_purpose_t purpose = static_cast<keymaster_purpose_t>(entry.enumerated);
732 if (RequiresSoftwareDigesting(algorithm, purpose, key_description))
733 return true;
734 }
735
736 return false;
737 }
738
739 /* 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)740 keymaster_error_t SoftKeymasterDevice::generate_key(
741 const keymaster1_device_t* dev, const keymaster_key_param_set_t* params,
742 keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
743 if (!dev || !params)
744 return KM_ERROR_UNEXPECTED_NULL_POINTER;
745
746 if (!key_blob)
747 return KM_ERROR_OUTPUT_PARAMETER_NULL;
748
749 SoftKeymasterDevice* sk_dev = convert_device(dev);
750
751 GenerateKeyRequest request;
752 request.key_description.Reinitialize(*params);
753
754 keymaster1_device_t* km1_dev = sk_dev->wrapped_km1_device_;
755 if (km1_dev && !sk_dev->KeyRequiresSoftwareDigesting(request.key_description))
756 return km1_dev->generate_key(km1_dev, params, key_blob, characteristics);
757
758 GenerateKeyResponse response;
759 sk_dev->impl_->GenerateKey(request, &response);
760 if (response.error != KM_ERROR_OK)
761 return response.error;
762
763 key_blob->key_material_size = response.key_blob.key_material_size;
764 uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
765 if (!tmp)
766 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
767 memcpy(tmp, response.key_blob.key_material, response.key_blob.key_material_size);
768 key_blob->key_material = tmp;
769
770 if (characteristics) {
771 // This is a keymaster1 method, and keymaster1 doesn't include version info, so remove it.
772 response.enforced.erase(response.enforced.find(TAG_OS_VERSION));
773 response.enforced.erase(response.enforced.find(TAG_OS_PATCHLEVEL));
774 response.unenforced.erase(response.unenforced.find(TAG_OS_VERSION));
775 response.unenforced.erase(response.unenforced.find(TAG_OS_PATCHLEVEL));
776
777 *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
778 if (!*characteristics)
779 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
780 }
781
782 return KM_ERROR_OK;
783 }
784
785 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)786 SoftKeymasterDevice::generate_key(const keymaster2_device_t* dev, //
787 const keymaster_key_param_set_t* params,
788 keymaster_key_blob_t* key_blob,
789 keymaster_key_characteristics_t* characteristics) {
790 if (!dev)
791 return KM_ERROR_UNEXPECTED_NULL_POINTER;
792
793 if (!convert_device(dev)->configured())
794 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
795
796 if (!key_blob)
797 return KM_ERROR_OUTPUT_PARAMETER_NULL;
798
799 SoftKeymasterDevice* sk_dev = convert_device(dev);
800
801 GenerateKeyRequest request;
802 request.key_description.Reinitialize(*params);
803
804 keymaster1_device_t* km1_dev = sk_dev->wrapped_km1_device_;
805 if (km1_dev && !sk_dev->KeyRequiresSoftwareDigesting(request.key_description)) {
806 keymaster_ec_curve_t curve;
807 if (request.key_description.Contains(TAG_ALGORITHM, KM_ALGORITHM_EC) &&
808 request.key_description.GetTagValue(TAG_EC_CURVE, &curve)) {
809 // Keymaster1 doesn't know about EC curves. We need to translate to key size.
810 uint32_t key_size_from_curve;
811 keymaster_error_t error = EcCurveToKeySize(curve, &key_size_from_curve);
812 if (error != KM_ERROR_OK) {
813 return error;
814 }
815
816 uint32_t key_size_from_desc;
817 if (request.key_description.GetTagValue(TAG_KEY_SIZE, &key_size_from_desc)) {
818 if (key_size_from_desc != key_size_from_curve) {
819 return KM_ERROR_INVALID_ARGUMENT;
820 }
821 } else {
822 request.key_description.push_back(TAG_KEY_SIZE, key_size_from_curve);
823 }
824 }
825
826 keymaster_key_characteristics_t* chars_ptr;
827 keymaster_error_t error = km1_dev->generate_key(km1_dev, &request.key_description, key_blob,
828 characteristics ? &chars_ptr : nullptr);
829 if (error != KM_ERROR_OK)
830 return error;
831
832 if (characteristics) {
833 *characteristics = *chars_ptr;
834 free(chars_ptr);
835 }
836
837 return KM_ERROR_OK;
838 }
839
840 GenerateKeyResponse response;
841 sk_dev->impl_->GenerateKey(request, &response);
842 if (response.error != KM_ERROR_OK)
843 return response.error;
844
845 key_blob->key_material_size = response.key_blob.key_material_size;
846 uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
847 if (!tmp)
848 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
849 memcpy(tmp, response.key_blob.key_material, response.key_blob.key_material_size);
850 key_blob->key_material = tmp;
851
852 if (characteristics) {
853 response.enforced.CopyToParamSet(&characteristics->hw_enforced);
854 response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
855 }
856
857 return KM_ERROR_OK;
858 }
859
860 /* 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)861 keymaster_error_t SoftKeymasterDevice::get_key_characteristics(
862 const keymaster1_device_t* dev, const keymaster_key_blob_t* key_blob,
863 const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
864 keymaster_key_characteristics_t** characteristics) {
865 if (!dev || !key_blob || !key_blob->key_material)
866 return KM_ERROR_UNEXPECTED_NULL_POINTER;
867
868 if (!characteristics)
869 return KM_ERROR_OUTPUT_PARAMETER_NULL;
870
871 const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
872 if (km1_dev) {
873 keymaster_error_t error = km1_dev->get_key_characteristics(km1_dev, key_blob, client_id,
874 app_data, characteristics);
875 if (error != KM_ERROR_INVALID_KEY_BLOB) {
876 return error;
877 }
878 // If we got "invalid blob", continue to try with the software device. This might be a
879 // software key blob.
880 }
881
882 GetKeyCharacteristicsRequest request;
883 request.SetKeyMaterial(*key_blob);
884 AddClientAndAppData(client_id, app_data, &request);
885
886 GetKeyCharacteristicsResponse response;
887 convert_device(dev)->impl_->GetKeyCharacteristics(request, &response);
888 if (response.error != KM_ERROR_OK)
889 return response.error;
890
891 // This is a keymaster1 method, and keymaster1 doesn't include version info, so remove it.
892 response.enforced.erase(response.enforced.find(TAG_OS_VERSION));
893 response.enforced.erase(response.enforced.find(TAG_OS_PATCHLEVEL));
894 response.unenforced.erase(response.unenforced.find(TAG_OS_VERSION));
895 response.unenforced.erase(response.unenforced.find(TAG_OS_PATCHLEVEL));
896
897 *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
898 if (!*characteristics)
899 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
900
901 return KM_ERROR_OK;
902 }
903
904 /* 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)905 keymaster_error_t SoftKeymasterDevice::get_key_characteristics(
906 const keymaster2_device_t* dev, const keymaster_key_blob_t* key_blob,
907 const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
908 keymaster_key_characteristics_t* characteristics) {
909 if (!dev)
910 return KM_ERROR_UNEXPECTED_NULL_POINTER;
911
912 if (!convert_device(dev)->configured())
913 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
914
915 if (!characteristics)
916 return KM_ERROR_OUTPUT_PARAMETER_NULL;
917
918 SoftKeymasterDevice* sk_dev = convert_device(dev);
919
920 GetKeyCharacteristicsRequest request;
921 request.SetKeyMaterial(*key_blob);
922 AddClientAndAppData(client_id, app_data, &request);
923
924 GetKeyCharacteristicsResponse response;
925 sk_dev->impl_->GetKeyCharacteristics(request, &response);
926 if (response.error != KM_ERROR_OK)
927 return response.error;
928
929 response.enforced.CopyToParamSet(&characteristics->hw_enforced);
930 response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
931
932 return KM_ERROR_OK;
933 }
934
935 /* 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)936 keymaster_error_t SoftKeymasterDevice::import_key(
937 const keymaster1_device_t* dev, const keymaster_key_param_set_t* params,
938 keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
939 keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
940 if (!params || !key_data)
941 return KM_ERROR_UNEXPECTED_NULL_POINTER;
942
943 if (!key_blob)
944 return KM_ERROR_OUTPUT_PARAMETER_NULL;
945
946 SoftKeymasterDevice* sk_dev = convert_device(dev);
947
948 ImportKeyRequest request;
949 request.key_description.Reinitialize(*params);
950
951 keymaster1_device_t* km1_dev = sk_dev->wrapped_km1_device_;
952 if (km1_dev && !sk_dev->KeyRequiresSoftwareDigesting(request.key_description))
953 return km1_dev->import_key(km1_dev, params, key_format, key_data, key_blob,
954 characteristics);
955
956 if (characteristics)
957 *characteristics = nullptr;
958
959 request.key_format = key_format;
960 request.SetKeyMaterial(key_data->data, key_data->data_length);
961
962 ImportKeyResponse response;
963 convert_device(dev)->impl_->ImportKey(request, &response);
964 if (response.error != KM_ERROR_OK)
965 return response.error;
966
967 key_blob->key_material_size = response.key_blob.key_material_size;
968 key_blob->key_material = reinterpret_cast<uint8_t*>(malloc(key_blob->key_material_size));
969 if (!key_blob->key_material)
970 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
971 memcpy(const_cast<uint8_t*>(key_blob->key_material), response.key_blob.key_material,
972 response.key_blob.key_material_size);
973
974 if (characteristics) {
975 *characteristics = BuildCharacteristics(response.enforced, response.unenforced);
976 if (!*characteristics)
977 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
978 }
979 return KM_ERROR_OK;
980 }
981
982 /* 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)983 keymaster_error_t SoftKeymasterDevice::import_key(
984 const keymaster2_device_t* dev, const keymaster_key_param_set_t* params,
985 keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
986 keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t* characteristics) {
987 if (!dev)
988 return KM_ERROR_UNEXPECTED_NULL_POINTER;
989
990 if (!convert_device(dev)->configured())
991 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
992
993 SoftKeymasterDevice* sk_dev = convert_device(dev);
994
995 keymaster_error_t error;
996 if (characteristics) {
997 keymaster_key_characteristics_t* characteristics_ptr;
998 error = import_key(&sk_dev->km1_device_, params, key_format, key_data, key_blob,
999 &characteristics_ptr);
1000 if (error == KM_ERROR_OK) {
1001 *characteristics = *characteristics_ptr;
1002 free(characteristics_ptr);
1003 }
1004 } else {
1005 error = import_key(&sk_dev->km1_device_, params, key_format, key_data, key_blob, nullptr);
1006 }
1007
1008 return error;
1009 }
1010
1011 /* 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)1012 keymaster_error_t SoftKeymasterDevice::export_key(const keymaster1_device_t* dev,
1013 keymaster_key_format_t export_format,
1014 const keymaster_key_blob_t* key_to_export,
1015 const keymaster_blob_t* client_id,
1016 const keymaster_blob_t* app_data,
1017 keymaster_blob_t* export_data) {
1018 if (!key_to_export || !key_to_export->key_material)
1019 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1020
1021 if (!export_data)
1022 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1023
1024 const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1025 if (km1_dev)
1026 return km1_dev->export_key(km1_dev, export_format, key_to_export, client_id, app_data,
1027 export_data);
1028
1029 export_data->data = nullptr;
1030 export_data->data_length = 0;
1031
1032 ExportKeyRequest request;
1033 request.key_format = export_format;
1034 request.SetKeyMaterial(*key_to_export);
1035 AddClientAndAppData(client_id, app_data, &request);
1036
1037 ExportKeyResponse response;
1038 convert_device(dev)->impl_->ExportKey(request, &response);
1039 if (response.error != KM_ERROR_OK)
1040 return response.error;
1041
1042 export_data->data_length = response.key_data_length;
1043 uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(export_data->data_length));
1044 if (!tmp)
1045 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1046 memcpy(tmp, response.key_data, export_data->data_length);
1047 export_data->data = tmp;
1048 return KM_ERROR_OK;
1049 }
1050
1051 /* 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)1052 keymaster_error_t SoftKeymasterDevice::export_key(const keymaster2_device_t* dev,
1053 keymaster_key_format_t export_format,
1054 const keymaster_key_blob_t* key_to_export,
1055 const keymaster_blob_t* client_id,
1056 const keymaster_blob_t* app_data,
1057 keymaster_blob_t* export_data) {
1058 if (!dev)
1059 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1060
1061 if (!convert_device(dev)->configured())
1062 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1063
1064 SoftKeymasterDevice* sk_dev = convert_device(dev);
1065 return export_key(&sk_dev->km1_device_, export_format, key_to_export, client_id, app_data,
1066 export_data);
1067 }
1068
1069 /* 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)1070 keymaster_error_t SoftKeymasterDevice::attest_key(const keymaster2_device_t* dev,
1071 const keymaster_key_blob_t* key_to_attest,
1072 const keymaster_key_param_set_t* attest_params,
1073 keymaster_cert_chain_t* cert_chain) {
1074 if (!dev || !key_to_attest || !attest_params || !cert_chain)
1075 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1076
1077 if (!convert_device(dev)->configured())
1078 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1079
1080 cert_chain->entry_count = 0;
1081 cert_chain->entries = nullptr;
1082
1083 AttestKeyRequest request;
1084 request.SetKeyMaterial(*key_to_attest);
1085 request.attest_params.Reinitialize(*attest_params);
1086
1087 keymaster_blob_t attestation_challenge = {};
1088 request.attest_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge);
1089 if (attestation_challenge.data_length > kMaximumAttestationChallengeLength) {
1090 LOG_E("%d-byte attestation challenge; only %d bytes allowed",
1091 attestation_challenge.data_length, kMaximumAttestationChallengeLength);
1092 return KM_ERROR_INVALID_INPUT_LENGTH;
1093 }
1094
1095 AttestKeyResponse response;
1096 convert_device(dev)->impl_->AttestKey(request, &response);
1097 if (response.error != KM_ERROR_OK)
1098 return response.error;
1099
1100 // Allocate and clear storage for cert_chain.
1101 keymaster_cert_chain_t& rsp_chain = response.certificate_chain;
1102 cert_chain->entries = reinterpret_cast<keymaster_blob_t*>(
1103 malloc(rsp_chain.entry_count * sizeof(*cert_chain->entries)));
1104 if (!cert_chain->entries)
1105 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1106 cert_chain->entry_count = rsp_chain.entry_count;
1107 for (keymaster_blob_t& entry : array_range(cert_chain->entries, cert_chain->entry_count))
1108 entry = {};
1109
1110 // Copy cert_chain contents
1111 size_t i = 0;
1112 for (keymaster_blob_t& entry : array_range(rsp_chain.entries, rsp_chain.entry_count)) {
1113 cert_chain->entries[i].data = reinterpret_cast<uint8_t*>(malloc(entry.data_length));
1114 if (!cert_chain->entries[i].data) {
1115 keymaster_free_cert_chain(cert_chain);
1116 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1117 }
1118 cert_chain->entries[i].data_length = entry.data_length;
1119 memcpy(const_cast<uint8_t*>(cert_chain->entries[i].data), entry.data, entry.data_length);
1120 ++i;
1121 }
1122
1123 return KM_ERROR_OK;
1124 }
1125
1126 /* 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)1127 keymaster_error_t SoftKeymasterDevice::upgrade_key(const keymaster2_device_t* dev,
1128 const keymaster_key_blob_t* key_to_upgrade,
1129 const keymaster_key_param_set_t* upgrade_params,
1130 keymaster_key_blob_t* upgraded_key) {
1131 if (!dev || !key_to_upgrade || !upgrade_params)
1132 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1133
1134 if (!upgraded_key)
1135 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1136
1137 if (!convert_device(dev)->configured())
1138 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1139
1140 UpgradeKeyRequest request;
1141 request.SetKeyMaterial(*key_to_upgrade);
1142 request.upgrade_params.Reinitialize(*upgrade_params);
1143
1144 UpgradeKeyResponse response;
1145 convert_device(dev)->impl_->UpgradeKey(request, &response);
1146 if (response.error != KM_ERROR_OK)
1147 return response.error;
1148
1149 upgraded_key->key_material_size = response.upgraded_key.key_material_size;
1150 uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(upgraded_key->key_material_size));
1151 if (!tmp)
1152 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1153 memcpy(tmp, response.upgraded_key.key_material, response.upgraded_key.key_material_size);
1154 upgraded_key->key_material = tmp;
1155
1156 return KM_ERROR_OK;
1157 }
1158
1159 /* static */
delete_key(const keymaster1_device_t * dev,const keymaster_key_blob_t * key)1160 keymaster_error_t SoftKeymasterDevice::delete_key(const keymaster1_device_t* dev,
1161 const keymaster_key_blob_t* key) {
1162 if (!dev || !key || !key->key_material)
1163 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1164
1165 KeymasterKeyBlob blob(*key);
1166 return convert_device(dev)->context_->DeleteKey(blob);
1167 }
1168
1169 /* static */
delete_key(const keymaster2_device_t * dev,const keymaster_key_blob_t * key)1170 keymaster_error_t SoftKeymasterDevice::delete_key(const keymaster2_device_t* dev,
1171 const keymaster_key_blob_t* key) {
1172 if (!dev || !key || !key->key_material)
1173 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1174
1175 if (!convert_device(dev)->configured())
1176 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1177
1178 KeymasterKeyBlob blob(*key);
1179 return convert_device(dev)->context_->DeleteKey(blob);
1180 }
1181
1182 /* static */
delete_all_keys(const keymaster1_device_t * dev)1183 keymaster_error_t SoftKeymasterDevice::delete_all_keys(const keymaster1_device_t* dev) {
1184 if (!dev)
1185 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1186
1187 return convert_device(dev)->context_->DeleteAllKeys();
1188 }
1189
1190 /* static */
delete_all_keys(const keymaster2_device_t * dev)1191 keymaster_error_t SoftKeymasterDevice::delete_all_keys(const keymaster2_device_t* dev) {
1192 if (!dev)
1193 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1194
1195 if (!convert_device(dev)->configured())
1196 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1197
1198 return convert_device(dev)->context_->DeleteAllKeys();
1199 }
1200
1201 /* 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)1202 keymaster_error_t SoftKeymasterDevice::begin(const keymaster1_device_t* dev,
1203 keymaster_purpose_t purpose,
1204 const keymaster_key_blob_t* key,
1205 const keymaster_key_param_set_t* in_params,
1206 keymaster_key_param_set_t* out_params,
1207 keymaster_operation_handle_t* operation_handle) {
1208 if (!dev || !key || !key->key_material)
1209 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1210
1211 if (!operation_handle)
1212 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1213
1214 SoftKeymasterDevice* skdev = convert_device(dev);
1215 const keymaster1_device_t* km1_dev = skdev->wrapped_km1_device_;
1216
1217 if (km1_dev) {
1218 AuthorizationSet in_params_set(*in_params);
1219
1220 KeymasterKeyBlob key_material;
1221 AuthorizationSet hw_enforced;
1222 AuthorizationSet sw_enforced;
1223 skdev->context_->ParseKeyBlob(KeymasterKeyBlob(*key), in_params_set, &key_material,
1224 &hw_enforced, &sw_enforced);
1225
1226 keymaster_algorithm_t algorithm = KM_ALGORITHM_AES;
1227 if (!hw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm) &&
1228 !sw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm)) {
1229 return KM_ERROR_INVALID_KEY_BLOB;
1230 }
1231
1232 if (algorithm == KM_ALGORITHM_HMAC) {
1233 // Because HMAC keys can have only one digest, in_params_set doesn't contain it. We
1234 // need to get the digest from the key and add it to in_params_set.
1235 keymaster_digest_t digest;
1236 if (!hw_enforced.GetTagValue(TAG_DIGEST, &digest) &&
1237 !sw_enforced.GetTagValue(TAG_DIGEST, &digest)) {
1238 return KM_ERROR_INVALID_KEY_BLOB;
1239 }
1240 in_params_set.push_back(TAG_DIGEST, digest);
1241 }
1242
1243 if (!skdev->RequiresSoftwareDigesting(algorithm, purpose, in_params_set)) {
1244 LOG_D("Operation supported by %s, passing through to keymaster1 module",
1245 km1_dev->common.module->name);
1246 return km1_dev->begin(km1_dev, purpose, key, in_params, out_params, operation_handle);
1247 }
1248 LOG_I("Doing software digesting for keymaster1 module %s", km1_dev->common.module->name);
1249 }
1250
1251 if (out_params) {
1252 out_params->params = nullptr;
1253 out_params->length = 0;
1254 }
1255
1256 BeginOperationRequest request;
1257 request.purpose = purpose;
1258 request.SetKeyMaterial(*key);
1259 request.additional_params.Reinitialize(*in_params);
1260
1261 BeginOperationResponse response;
1262 skdev->impl_->BeginOperation(request, &response);
1263 if (response.error != KM_ERROR_OK)
1264 return response.error;
1265
1266 if (response.output_params.size() > 0) {
1267 if (out_params)
1268 response.output_params.CopyToParamSet(out_params);
1269 else
1270 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1271 }
1272
1273 *operation_handle = response.op_handle;
1274 return KM_ERROR_OK;
1275 }
1276
1277 /* 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)1278 keymaster_error_t SoftKeymasterDevice::begin(const keymaster2_device_t* dev,
1279 keymaster_purpose_t purpose,
1280 const keymaster_key_blob_t* key,
1281 const keymaster_key_param_set_t* in_params,
1282 keymaster_key_param_set_t* out_params,
1283 keymaster_operation_handle_t* operation_handle) {
1284 if (!dev)
1285 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1286
1287 if (!convert_device(dev)->configured())
1288 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1289
1290 SoftKeymasterDevice* sk_dev = convert_device(dev);
1291 return begin(&sk_dev->km1_device_, purpose, key, in_params, out_params, operation_handle);
1292 }
1293
1294 /* 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)1295 keymaster_error_t SoftKeymasterDevice::update(const keymaster1_device_t* dev,
1296 keymaster_operation_handle_t operation_handle,
1297 const keymaster_key_param_set_t* in_params,
1298 const keymaster_blob_t* input, size_t* input_consumed,
1299 keymaster_key_param_set_t* out_params,
1300 keymaster_blob_t* output) {
1301 if (!input)
1302 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1303
1304 if (!input_consumed)
1305 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1306
1307 const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1308 if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1309 // This operation is being handled by km1_dev (or doesn't exist). Pass it through to
1310 // km1_dev. Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1311 // km1_dev after doing necessary digesting.
1312 return km1_dev->update(km1_dev, operation_handle, in_params, input, input_consumed,
1313 out_params, output);
1314 }
1315
1316 if (out_params) {
1317 out_params->params = nullptr;
1318 out_params->length = 0;
1319 }
1320 if (output) {
1321 output->data = nullptr;
1322 output->data_length = 0;
1323 }
1324
1325 UpdateOperationRequest request;
1326 request.op_handle = operation_handle;
1327 if (input)
1328 request.input.Reinitialize(input->data, input->data_length);
1329 if (in_params)
1330 request.additional_params.Reinitialize(*in_params);
1331
1332 UpdateOperationResponse response;
1333 convert_device(dev)->impl_->UpdateOperation(request, &response);
1334 if (response.error != KM_ERROR_OK)
1335 return response.error;
1336
1337 if (response.output_params.size() > 0) {
1338 if (out_params)
1339 response.output_params.CopyToParamSet(out_params);
1340 else
1341 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1342 }
1343
1344 *input_consumed = response.input_consumed;
1345 if (output) {
1346 output->data_length = response.output.available_read();
1347 uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1348 if (!tmp)
1349 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1350 memcpy(tmp, response.output.peek_read(), output->data_length);
1351 output->data = tmp;
1352 } else if (response.output.available_read() > 0) {
1353 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1354 }
1355 return KM_ERROR_OK;
1356 }
1357
1358 /* 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)1359 keymaster_error_t SoftKeymasterDevice::update(const keymaster2_device_t* dev,
1360 keymaster_operation_handle_t operation_handle,
1361 const keymaster_key_param_set_t* in_params,
1362 const keymaster_blob_t* input, size_t* input_consumed,
1363 keymaster_key_param_set_t* out_params,
1364 keymaster_blob_t* output) {
1365 if (!dev)
1366 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1367
1368 if (!convert_device(dev)->configured())
1369 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1370
1371 SoftKeymasterDevice* sk_dev = convert_device(dev);
1372 return update(&sk_dev->km1_device_, operation_handle, in_params, input, input_consumed,
1373 out_params, output);
1374 }
1375
1376 /* 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)1377 keymaster_error_t SoftKeymasterDevice::finish(const keymaster1_device_t* dev,
1378 keymaster_operation_handle_t operation_handle,
1379 const keymaster_key_param_set_t* params,
1380 const keymaster_blob_t* signature,
1381 keymaster_key_param_set_t* out_params,
1382 keymaster_blob_t* output) {
1383 if (!dev)
1384 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1385
1386 const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1387 if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1388 // This operation is being handled by km1_dev (or doesn't exist). Pass it through to
1389 // km1_dev. Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1390 // km1_dev after doing necessary digesting.
1391 return km1_dev->finish(km1_dev, operation_handle, params, signature, out_params, output);
1392 }
1393
1394 if (out_params) {
1395 out_params->params = nullptr;
1396 out_params->length = 0;
1397 }
1398
1399 if (output) {
1400 output->data = nullptr;
1401 output->data_length = 0;
1402 }
1403
1404 FinishOperationRequest request;
1405 request.op_handle = operation_handle;
1406 if (signature && signature->data_length > 0)
1407 request.signature.Reinitialize(signature->data, signature->data_length);
1408 request.additional_params.Reinitialize(*params);
1409
1410 FinishOperationResponse response;
1411 convert_device(dev)->impl_->FinishOperation(request, &response);
1412 if (response.error != KM_ERROR_OK)
1413 return response.error;
1414
1415 if (response.output_params.size() > 0) {
1416 if (out_params)
1417 response.output_params.CopyToParamSet(out_params);
1418 else
1419 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1420 }
1421 if (output) {
1422 output->data_length = response.output.available_read();
1423 uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1424 if (!tmp)
1425 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1426 memcpy(tmp, response.output.peek_read(), output->data_length);
1427 output->data = tmp;
1428 } else if (response.output.available_read() > 0) {
1429 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1430 }
1431
1432 return KM_ERROR_OK;
1433 }
1434
1435 struct KeyParamSetContents_Delete {
operator ()keymaster::KeyParamSetContents_Delete1436 void operator()(keymaster_key_param_set_t* p) { keymaster_free_param_set(p); }
1437 };
1438
1439 /* 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)1440 keymaster_error_t SoftKeymasterDevice::finish(const keymaster2_device_t* dev,
1441 keymaster_operation_handle_t operation_handle,
1442 const keymaster_key_param_set_t* params,
1443 const keymaster_blob_t* input,
1444 const keymaster_blob_t* signature,
1445 keymaster_key_param_set_t* out_params,
1446 keymaster_blob_t* output) {
1447 if (!dev)
1448 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1449
1450 if (!convert_device(dev)->configured())
1451 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1452
1453 if (out_params)
1454 *out_params = {};
1455
1456 if (output)
1457 *output = {};
1458
1459 const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1460 if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1461 // This operation is being handled by km1_dev (or doesn't exist). Pass it through to
1462 // km1_dev. Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1463 // km1_dev after doing necessary digesting.
1464
1465 std::vector<uint8_t> accumulated_output;
1466 AuthorizationSet accumulated_out_params;
1467 AuthorizationSet mutable_params(*params);
1468 if (input && input->data && input->data_length) {
1469 // Keymaster1 doesn't support input to finish(). Call update() to process input.
1470
1471 accumulated_output.reserve(input->data_length); // Guess at output size
1472 keymaster_blob_t mutable_input = *input;
1473
1474 while (mutable_input.data_length > 0) {
1475 keymaster_key_param_set_t update_out_params = {};
1476 keymaster_blob_t update_output = {};
1477 size_t input_consumed = 0;
1478 keymaster_error_t error =
1479 km1_dev->update(km1_dev, operation_handle, &mutable_params, &mutable_input,
1480 &input_consumed, &update_out_params, &update_output);
1481 if (error != KM_ERROR_OK) {
1482 return error;
1483 }
1484
1485 accumulated_output.reserve(accumulated_output.size() + update_output.data_length);
1486 std::copy(update_output.data, update_output.data + update_output.data_length,
1487 std::back_inserter(accumulated_output));
1488 free(const_cast<uint8_t*>(update_output.data));
1489
1490 accumulated_out_params.push_back(update_out_params);
1491 keymaster_free_param_set(&update_out_params);
1492
1493 mutable_input.data += input_consumed;
1494 mutable_input.data_length -= input_consumed;
1495
1496 // AAD should only be sent once, so remove it if present.
1497 int aad_pos = mutable_params.find(TAG_ASSOCIATED_DATA);
1498 if (aad_pos != -1) {
1499 mutable_params.erase(aad_pos);
1500 }
1501
1502 if (input_consumed == 0) {
1503 // Apparently we need more input than we have to complete an operation.
1504 km1_dev->abort(km1_dev, operation_handle);
1505 return KM_ERROR_INVALID_INPUT_LENGTH;
1506 }
1507 }
1508 }
1509
1510 keymaster_key_param_set_t finish_out_params = {};
1511 keymaster_blob_t finish_output = {};
1512 keymaster_error_t error = km1_dev->finish(km1_dev, operation_handle, &mutable_params,
1513 signature, &finish_out_params, &finish_output);
1514 if (error != KM_ERROR_OK) {
1515 return error;
1516 }
1517
1518 if (!accumulated_out_params.empty()) {
1519 accumulated_out_params.push_back(finish_out_params);
1520 keymaster_free_param_set(&finish_out_params);
1521 accumulated_out_params.Deduplicate();
1522 accumulated_out_params.CopyToParamSet(&finish_out_params);
1523 }
1524 std::unique_ptr<keymaster_key_param_set_t, KeyParamSetContents_Delete>
1525 finish_out_params_deleter(&finish_out_params);
1526
1527 if (!accumulated_output.empty()) {
1528 size_t finish_out_length = accumulated_output.size() + finish_output.data_length;
1529 uint8_t* finish_out_buf = reinterpret_cast<uint8_t*>(malloc(finish_out_length));
1530
1531 std::copy(accumulated_output.begin(), accumulated_output.end(), finish_out_buf);
1532 std::copy(finish_output.data, finish_output.data + finish_output.data_length,
1533 finish_out_buf + accumulated_output.size());
1534
1535 free(const_cast<uint8_t*>(finish_output.data));
1536 finish_output.data_length = finish_out_length;
1537 finish_output.data = finish_out_buf;
1538 }
1539 std::unique_ptr<uint8_t, Malloc_Delete> finish_output_deleter(
1540 const_cast<uint8_t*>(finish_output.data));
1541
1542 if ((!out_params && finish_out_params.length) || (!output && finish_output.data_length)) {
1543 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1544 }
1545
1546 if (out_params) {
1547 *out_params = finish_out_params;
1548 }
1549
1550 if (output) {
1551 *output = finish_output;
1552 }
1553
1554 finish_out_params_deleter.release();
1555 finish_output_deleter.release();
1556
1557 return KM_ERROR_OK;
1558 }
1559
1560 FinishOperationRequest request;
1561 request.op_handle = operation_handle;
1562 if (signature && signature->data_length > 0)
1563 request.signature.Reinitialize(signature->data, signature->data_length);
1564 if (input && input->data_length > 0)
1565 request.input.Reinitialize(input->data, input->data_length);
1566 request.additional_params.Reinitialize(*params);
1567
1568 FinishOperationResponse response;
1569 convert_device(dev)->impl_->FinishOperation(request, &response);
1570 if (response.error != KM_ERROR_OK)
1571 return response.error;
1572
1573 if (response.output_params.size() > 0) {
1574 if (out_params)
1575 response.output_params.CopyToParamSet(out_params);
1576 else
1577 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1578 }
1579 if (output) {
1580 output->data_length = response.output.available_read();
1581 uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(output->data_length));
1582 if (!tmp)
1583 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1584 memcpy(tmp, response.output.peek_read(), output->data_length);
1585 output->data = tmp;
1586 } else if (response.output.available_read() > 0) {
1587 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1588 }
1589
1590 return KM_ERROR_OK;
1591 }
1592
1593 /* static */
abort(const keymaster1_device_t * dev,keymaster_operation_handle_t operation_handle)1594 keymaster_error_t SoftKeymasterDevice::abort(const keymaster1_device_t* dev,
1595 keymaster_operation_handle_t operation_handle) {
1596 const keymaster1_device_t* km1_dev = convert_device(dev)->wrapped_km1_device_;
1597 if (km1_dev && !convert_device(dev)->impl_->has_operation(operation_handle)) {
1598 // This operation is being handled by km1_dev (or doesn't exist). Pass it through to
1599 // km1_dev. Otherwise, we'll use the software AndroidKeymaster, which may delegate to
1600 // km1_dev.
1601 return km1_dev->abort(km1_dev, operation_handle);
1602 }
1603
1604 AbortOperationRequest request;
1605 request.op_handle = operation_handle;
1606 AbortOperationResponse response;
1607 convert_device(dev)->impl_->AbortOperation(request, &response);
1608 return response.error;
1609 }
1610
1611 /* static */
abort(const keymaster2_device_t * dev,keymaster_operation_handle_t operation_handle)1612 keymaster_error_t SoftKeymasterDevice::abort(const keymaster2_device_t* dev,
1613 keymaster_operation_handle_t operation_handle) {
1614 if (!dev)
1615 return KM_ERROR_UNEXPECTED_NULL_POINTER;
1616
1617 if (!convert_device(dev)->configured())
1618 return KM_ERROR_KEYMASTER_NOT_CONFIGURED;
1619
1620 SoftKeymasterDevice* sk_dev = convert_device(dev);
1621 return abort(&sk_dev->km1_device_, operation_handle);
1622 }
1623
1624 /* static */
StoreDefaultNewKeyParams(keymaster_algorithm_t algorithm,AuthorizationSet * auth_set)1625 void SoftKeymasterDevice::StoreDefaultNewKeyParams(keymaster_algorithm_t algorithm,
1626 AuthorizationSet* auth_set) {
1627 auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
1628 auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
1629 auth_set->push_back(TAG_ALL_USERS);
1630 auth_set->push_back(TAG_NO_AUTH_REQUIRED);
1631
1632 // All digests.
1633 auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE);
1634 auth_set->push_back(TAG_DIGEST, KM_DIGEST_MD5);
1635 auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA1);
1636 auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_224);
1637 auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1638 auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
1639 auth_set->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_512);
1640
1641 if (algorithm == KM_ALGORITHM_RSA) {
1642 auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_ENCRYPT);
1643 auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_DECRYPT);
1644 auth_set->push_back(TAG_PADDING, KM_PAD_NONE);
1645 auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1646 auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1647 auth_set->push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1648 auth_set->push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
1649 }
1650 }
1651
1652 } // namespace keymaster
1653