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