1 /*
2  **
3  ** Copyright 2016, The Android Open Source Project
4  **
5  ** Licensed under the Apache License, Version 2.0 (the "License");
6  ** you may not use this file except in compliance with the License.
7  ** You may obtain a copy of the License at
8  **
9  **     http://www.apache.org/licenses/LICENSE-2.0
10  **
11  ** Unless required by applicable law or agreed to in writing, software
12  ** distributed under the License is distributed on an "AS IS" BASIS,
13  ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  ** See the License for the specific language governing permissions and
15  ** limitations under the License.
16  */
17 
18 #define LOG_TAG "android.hardware.keymaster@3.0-impl"
19 
20 #include "KeymasterDevice.h"
21 
22 #include <cutils/log.h>
23 
24 #include <hardware/keymaster_defs.h>
25 #include <keymaster/keymaster_configuration.h>
26 #include <keymaster/soft_keymaster_device.h>
27 
28 namespace android {
29 namespace hardware {
30 namespace keymaster {
31 namespace V3_0 {
32 namespace implementation {
33 
34 using ::keymaster::SoftKeymasterDevice;
35 
36 class SoftwareOnlyHidlKeymasterEnforcement : public ::keymaster::KeymasterEnforcement {
37   public:
SoftwareOnlyHidlKeymasterEnforcement()38     SoftwareOnlyHidlKeymasterEnforcement() : KeymasterEnforcement(64, 64) {}
39 
get_current_time() const40     uint32_t get_current_time() const override {
41         struct timespec tp;
42         int err = clock_gettime(CLOCK_MONOTONIC, &tp);
43         if (err || tp.tv_sec < 0) return 0;
44         return static_cast<uint32_t>(tp.tv_sec);
45     }
46 
activation_date_valid(uint64_t) const47     bool activation_date_valid(uint64_t) const override { return true; }
expiration_date_passed(uint64_t) const48     bool expiration_date_passed(uint64_t) const override { return false; }
auth_token_timed_out(const hw_auth_token_t &,uint32_t) const49     bool auth_token_timed_out(const hw_auth_token_t&, uint32_t) const override { return false; }
ValidateTokenSignature(const hw_auth_token_t &) const50     bool ValidateTokenSignature(const hw_auth_token_t&) const override { return true; }
51 };
52 
53 class SoftwareOnlyHidlKeymasterContext : public ::keymaster::SoftKeymasterContext {
54   public:
SoftwareOnlyHidlKeymasterContext()55     SoftwareOnlyHidlKeymasterContext() : enforcement_(new SoftwareOnlyHidlKeymasterEnforcement) {}
56 
enforcement_policy()57     ::keymaster::KeymasterEnforcement* enforcement_policy() override { return enforcement_.get(); }
58 
59   private:
60     std::unique_ptr<::keymaster::KeymasterEnforcement> enforcement_;
61 };
62 
keymaster0_device_initialize(const hw_module_t * mod,keymaster2_device_t ** dev)63 static int keymaster0_device_initialize(const hw_module_t* mod, keymaster2_device_t** dev) {
64     assert(mod->module_api_version < KEYMASTER_MODULE_API_VERSION_1_0);
65     ALOGI("Found keymaster0 module %s, version %x", mod->name, mod->module_api_version);
66 
67     UniquePtr<SoftKeymasterDevice> soft_keymaster(new SoftKeymasterDevice);
68     keymaster0_device_t* km0_device = NULL;
69     keymaster_error_t error = KM_ERROR_OK;
70 
71     int rc = keymaster0_open(mod, &km0_device);
72     if (rc) {
73         ALOGE("Error opening keystore keymaster0 device.");
74         goto err;
75     }
76 
77     if (km0_device->flags & KEYMASTER_SOFTWARE_ONLY) {
78         ALOGI("Keymaster0 module is software-only.  Using SoftKeymasterDevice instead.");
79         km0_device->common.close(&km0_device->common);
80         km0_device = NULL;
81         // SoftKeymasterDevice will be deleted by keymaster_device_release()
82         *dev = soft_keymaster.release()->keymaster2_device();
83         return 0;
84     }
85 
86     ALOGD("Wrapping keymaster0 module %s with SoftKeymasterDevice", mod->name);
87     error = soft_keymaster->SetHardwareDevice(km0_device);
88     km0_device = NULL;  // SoftKeymasterDevice has taken ownership.
89     if (error != KM_ERROR_OK) {
90         ALOGE("Got error %d from SetHardwareDevice", error);
91         rc = error;
92         goto err;
93     }
94 
95     // SoftKeymasterDevice will be deleted by  keymaster_device_release()
96     *dev = soft_keymaster.release()->keymaster2_device();
97     return 0;
98 
99 err:
100     if (km0_device) km0_device->common.close(&km0_device->common);
101     *dev = NULL;
102     return rc;
103 }
104 
keymaster1_device_initialize(const hw_module_t * mod,keymaster2_device_t ** dev,bool * supports_all_digests)105 static int keymaster1_device_initialize(const hw_module_t* mod, keymaster2_device_t** dev,
106                                         bool* supports_all_digests) {
107     assert(mod->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0);
108     ALOGI("Found keymaster1 module %s, version %x", mod->name, mod->module_api_version);
109 
110     UniquePtr<SoftKeymasterDevice> soft_keymaster(new SoftKeymasterDevice);
111     keymaster1_device_t* km1_device = nullptr;
112     keymaster_error_t error = KM_ERROR_OK;
113 
114     int rc = keymaster1_open(mod, &km1_device);
115     if (rc) {
116         ALOGE("Error %d opening keystore keymaster1 device", rc);
117         goto err;
118     }
119 
120     ALOGD("Wrapping keymaster1 module %s with SofKeymasterDevice", mod->name);
121     error = soft_keymaster->SetHardwareDevice(km1_device);
122     km1_device = nullptr;  // SoftKeymasterDevice has taken ownership.
123     if (error != KM_ERROR_OK) {
124         ALOGE("Got error %d from SetHardwareDevice", error);
125         rc = error;
126         goto err;
127     }
128 
129     // SoftKeymasterDevice will be deleted by keymaster_device_release()
130     *supports_all_digests = soft_keymaster->supports_all_digests();
131     *dev = soft_keymaster.release()->keymaster2_device();
132     return 0;
133 
134 err:
135     if (km1_device) km1_device->common.close(&km1_device->common);
136     *dev = NULL;
137     return rc;
138 }
139 
keymaster2_device_initialize(const hw_module_t * mod,keymaster2_device_t ** dev)140 static int keymaster2_device_initialize(const hw_module_t* mod, keymaster2_device_t** dev) {
141     assert(mod->module_api_version >= KEYMASTER_MODULE_API_VERSION_2_0);
142     ALOGI("Found keymaster2 module %s, version %x", mod->name, mod->module_api_version);
143 
144     keymaster2_device_t* km2_device = nullptr;
145 
146     int rc = keymaster2_open(mod, &km2_device);
147     if (rc) {
148         ALOGE("Error %d opening keystore keymaster2 device", rc);
149         goto err;
150     }
151 
152     *dev = km2_device;
153     return 0;
154 
155 err:
156     if (km2_device) km2_device->common.close(&km2_device->common);
157     *dev = nullptr;
158     return rc;
159 }
160 
keymaster_device_initialize(keymaster2_device_t ** dev,uint32_t * version,bool * supports_ec,bool * supports_all_digests)161 static int keymaster_device_initialize(keymaster2_device_t** dev, uint32_t* version,
162                                        bool* supports_ec, bool* supports_all_digests) {
163     const hw_module_t* mod;
164 
165     *supports_ec = true;
166 
167     int rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
168     if (rc) {
169         ALOGI("Could not find any keystore module, using software-only implementation.");
170         // SoftKeymasterDevice will be deleted by keymaster_device_release()
171         *dev = (new SoftKeymasterDevice(new SoftwareOnlyHidlKeymasterContext))->keymaster2_device();
172         *version = -1;
173         return 0;
174     }
175 
176     if (mod->module_api_version < KEYMASTER_MODULE_API_VERSION_1_0) {
177         *version = 0;
178         *supports_all_digests = false;
179         int rc = keymaster0_device_initialize(mod, dev);
180         if (rc == 0 && ((*dev)->flags & KEYMASTER_SUPPORTS_EC) == 0) {
181             *supports_ec = false;
182         }
183         return rc;
184     } else if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
185         *version = 1;
186         return keymaster1_device_initialize(mod, dev, supports_all_digests);
187     } else {
188         *version = 2;
189         *supports_all_digests = true;
190         return keymaster2_device_initialize(mod, dev);
191     }
192 }
193 
~KeymasterDevice()194 KeymasterDevice::~KeymasterDevice() {
195     if (keymaster_device_) keymaster_device_->common.close(&keymaster_device_->common);
196 }
197 
typeFromTag(const keymaster_tag_t tag)198 static inline keymaster_tag_type_t typeFromTag(const keymaster_tag_t tag) {
199     return keymaster_tag_get_type(tag);
200 }
201 
202 /**
203  * legacy_enum_conversion converts enums from hidl to keymaster and back. Currently, this is just a
204  * cast to make the compiler happy. One of two thigs should happen though:
205  * TODO The keymaster enums should become aliases for the hidl generated enums so that we have a
206  *      single point of truth. Then this cast function can go away.
207  */
legacy_enum_conversion(const Tag value)208 inline static keymaster_tag_t legacy_enum_conversion(const Tag value) {
209     return keymaster_tag_t(value);
210 }
legacy_enum_conversion(const keymaster_tag_t value)211 inline static Tag legacy_enum_conversion(const keymaster_tag_t value) {
212     return Tag(value);
213 }
legacy_enum_conversion(const KeyPurpose value)214 inline static keymaster_purpose_t legacy_enum_conversion(const KeyPurpose value) {
215     return keymaster_purpose_t(value);
216 }
legacy_enum_conversion(const KeyFormat value)217 inline static keymaster_key_format_t legacy_enum_conversion(const KeyFormat value) {
218     return keymaster_key_format_t(value);
219 }
legacy_enum_conversion(const keymaster_error_t value)220 inline static ErrorCode legacy_enum_conversion(const keymaster_error_t value) {
221     return ErrorCode(value);
222 }
223 
224 class KmParamSet : public keymaster_key_param_set_t {
225   public:
KmParamSet(const hidl_vec<KeyParameter> & keyParams)226     KmParamSet(const hidl_vec<KeyParameter>& keyParams) {
227         params = new keymaster_key_param_t[keyParams.size()];
228         length = keyParams.size();
229         for (size_t i = 0; i < keyParams.size(); ++i) {
230             auto tag = legacy_enum_conversion(keyParams[i].tag);
231             switch (typeFromTag(tag)) {
232             case KM_ENUM:
233             case KM_ENUM_REP:
234                 params[i] = keymaster_param_enum(tag, keyParams[i].f.integer);
235                 break;
236             case KM_UINT:
237             case KM_UINT_REP:
238                 params[i] = keymaster_param_int(tag, keyParams[i].f.integer);
239                 break;
240             case KM_ULONG:
241             case KM_ULONG_REP:
242                 params[i] = keymaster_param_long(tag, keyParams[i].f.longInteger);
243                 break;
244             case KM_DATE:
245                 params[i] = keymaster_param_date(tag, keyParams[i].f.dateTime);
246                 break;
247             case KM_BOOL:
248                 if (keyParams[i].f.boolValue)
249                     params[i] = keymaster_param_bool(tag);
250                 else
251                     params[i].tag = KM_TAG_INVALID;
252                 break;
253             case KM_BIGNUM:
254             case KM_BYTES:
255                 params[i] =
256                     keymaster_param_blob(tag, &keyParams[i].blob[0], keyParams[i].blob.size());
257                 break;
258             case KM_INVALID:
259             default:
260                 params[i].tag = KM_TAG_INVALID;
261                 /* just skip */
262                 break;
263             }
264         }
265     }
KmParamSet(KmParamSet && other)266     KmParamSet(KmParamSet&& other) : keymaster_key_param_set_t{other.params, other.length} {
267         other.length = 0;
268         other.params = nullptr;
269     }
270     KmParamSet(const KmParamSet&) = delete;
~KmParamSet()271     ~KmParamSet() { delete[] params; }
272 };
273 
hidlParams2KmParamSet(const hidl_vec<KeyParameter> & params)274 inline static KmParamSet hidlParams2KmParamSet(const hidl_vec<KeyParameter>& params) {
275     return KmParamSet(params);
276 }
277 
hidlVec2KmBlob(const hidl_vec<uint8_t> & blob)278 inline static keymaster_blob_t hidlVec2KmBlob(const hidl_vec<uint8_t>& blob) {
279     /* hidl unmarshals funny pointers if the the blob is empty */
280     if (blob.size()) return {&blob[0], blob.size()};
281     return {nullptr, 0};
282 }
283 
hidlVec2KmKeyBlob(const hidl_vec<uint8_t> & blob)284 inline static keymaster_key_blob_t hidlVec2KmKeyBlob(const hidl_vec<uint8_t>& blob) {
285     /* hidl unmarshals funny pointers if the the blob is empty */
286     if (blob.size()) return {&blob[0], blob.size()};
287     return {nullptr, 0};
288 }
289 
kmBlob2hidlVec(const keymaster_key_blob_t & blob)290 inline static hidl_vec<uint8_t> kmBlob2hidlVec(const keymaster_key_blob_t& blob) {
291     hidl_vec<uint8_t> result;
292     result.setToExternal(const_cast<unsigned char*>(blob.key_material), blob.key_material_size);
293     return result;
294 }
kmBlob2hidlVec(const keymaster_blob_t & blob)295 inline static hidl_vec<uint8_t> kmBlob2hidlVec(const keymaster_blob_t& blob) {
296     hidl_vec<uint8_t> result;
297     result.setToExternal(const_cast<unsigned char*>(blob.data), blob.data_length);
298     return result;
299 }
300 
301 inline static hidl_vec<hidl_vec<uint8_t>>
kmCertChain2Hidl(const keymaster_cert_chain_t * cert_chain)302 kmCertChain2Hidl(const keymaster_cert_chain_t* cert_chain) {
303     hidl_vec<hidl_vec<uint8_t>> result;
304     if (!cert_chain || cert_chain->entry_count == 0 || !cert_chain->entries) return result;
305 
306     result.resize(cert_chain->entry_count);
307     for (size_t i = 0; i < cert_chain->entry_count; ++i) {
308         auto& entry = cert_chain->entries[i];
309         result[i] = kmBlob2hidlVec(entry);
310     }
311 
312     return result;
313 }
314 
kmParamSet2Hidl(const keymaster_key_param_set_t & set)315 static inline hidl_vec<KeyParameter> kmParamSet2Hidl(const keymaster_key_param_set_t& set) {
316     hidl_vec<KeyParameter> result;
317     if (set.length == 0 || set.params == nullptr) return result;
318 
319     result.resize(set.length);
320     keymaster_key_param_t* params = set.params;
321     for (size_t i = 0; i < set.length; ++i) {
322         auto tag = params[i].tag;
323         result[i].tag = legacy_enum_conversion(tag);
324         switch (typeFromTag(tag)) {
325         case KM_ENUM:
326         case KM_ENUM_REP:
327             result[i].f.integer = params[i].enumerated;
328             break;
329         case KM_UINT:
330         case KM_UINT_REP:
331             result[i].f.integer = params[i].integer;
332             break;
333         case KM_ULONG:
334         case KM_ULONG_REP:
335             result[i].f.longInteger = params[i].long_integer;
336             break;
337         case KM_DATE:
338             result[i].f.dateTime = params[i].date_time;
339             break;
340         case KM_BOOL:
341             result[i].f.boolValue = params[i].boolean;
342             break;
343         case KM_BIGNUM:
344         case KM_BYTES:
345             result[i].blob.setToExternal(const_cast<unsigned char*>(params[i].blob.data),
346                                          params[i].blob.data_length);
347             break;
348         case KM_INVALID:
349         default:
350             params[i].tag = KM_TAG_INVALID;
351             /* just skip */
352             break;
353         }
354     }
355     return result;
356 }
357 
358 // Methods from ::android::hardware::keymaster::V3_0::IKeymasterDevice follow.
getHardwareFeatures(getHardwareFeatures_cb _hidl_cb)359 Return<void> KeymasterDevice::getHardwareFeatures(getHardwareFeatures_cb _hidl_cb) {
360     bool is_secure = !(keymaster_device_->flags & KEYMASTER_SOFTWARE_ONLY);
361     bool supports_symmetric_cryptography = false;
362     bool supports_attestation = false;
363 
364     switch (hardware_version_) {
365     case 2:
366         supports_attestation = true;
367     /* Falls through */
368     case 1:
369         supports_symmetric_cryptography = true;
370         break;
371     };
372 
373     _hidl_cb(is_secure, hardware_supports_ec_, supports_symmetric_cryptography,
374              supports_attestation, hardware_supports_all_digests_,
375              keymaster_device_->common.module->name, keymaster_device_->common.module->author);
376     return Void();
377 }
378 
addRngEntropy(const hidl_vec<uint8_t> & data)379 Return<ErrorCode> KeymasterDevice::addRngEntropy(const hidl_vec<uint8_t>& data) {
380     if (!data.size()) return ErrorCode::OK;
381     return legacy_enum_conversion(
382         keymaster_device_->add_rng_entropy(keymaster_device_, &data[0], data.size()));
383 }
384 
generateKey(const hidl_vec<KeyParameter> & keyParams,generateKey_cb _hidl_cb)385 Return<void> KeymasterDevice::generateKey(const hidl_vec<KeyParameter>& keyParams,
386                                           generateKey_cb _hidl_cb) {
387     // result variables for the wire
388     KeyCharacteristics resultCharacteristics;
389     hidl_vec<uint8_t> resultKeyBlob;
390 
391     // result variables the backend understands
392     keymaster_key_blob_t key_blob{nullptr, 0};
393     keymaster_key_characteristics_t key_characteristics{{nullptr, 0}, {nullptr, 0}};
394 
395     // convert the parameter set to something our backend understands
396     auto kmParams = hidlParams2KmParamSet(keyParams);
397 
398     auto rc = keymaster_device_->generate_key(keymaster_device_, &kmParams, &key_blob,
399                                               &key_characteristics);
400 
401     if (rc == KM_ERROR_OK) {
402         // on success convert the result to wire format
403         resultKeyBlob = kmBlob2hidlVec(key_blob);
404         resultCharacteristics.softwareEnforced = kmParamSet2Hidl(key_characteristics.sw_enforced);
405         resultCharacteristics.teeEnforced = kmParamSet2Hidl(key_characteristics.hw_enforced);
406     }
407 
408     // send results off to the client
409     _hidl_cb(legacy_enum_conversion(rc), resultKeyBlob, resultCharacteristics);
410 
411     // free buffers that we are responsible for
412     if (key_blob.key_material) free(const_cast<uint8_t*>(key_blob.key_material));
413     keymaster_free_characteristics(&key_characteristics);
414 
415     return Void();
416 }
417 
getKeyCharacteristics(const hidl_vec<uint8_t> & keyBlob,const hidl_vec<uint8_t> & clientId,const hidl_vec<uint8_t> & appData,getKeyCharacteristics_cb _hidl_cb)418 Return<void> KeymasterDevice::getKeyCharacteristics(const hidl_vec<uint8_t>& keyBlob,
419                                                     const hidl_vec<uint8_t>& clientId,
420                                                     const hidl_vec<uint8_t>& appData,
421                                                     getKeyCharacteristics_cb _hidl_cb) {
422     // result variables for the wire
423     KeyCharacteristics resultCharacteristics;
424 
425     // result variables the backend understands
426     keymaster_key_characteristics_t key_characteristics{{nullptr, 0}, {nullptr, 0}};
427 
428     auto kmKeyBlob = hidlVec2KmKeyBlob(keyBlob);
429     auto kmClientId = hidlVec2KmBlob(clientId);
430     auto kmAppData = hidlVec2KmBlob(appData);
431 
432     auto rc = keymaster_device_->get_key_characteristics(
433         keymaster_device_, keyBlob.size() ? &kmKeyBlob : nullptr,
434         clientId.size() ? &kmClientId : nullptr, appData.size() ? &kmAppData : nullptr,
435         &key_characteristics);
436 
437     if (rc == KM_ERROR_OK) {
438         resultCharacteristics.softwareEnforced = kmParamSet2Hidl(key_characteristics.sw_enforced);
439         resultCharacteristics.teeEnforced = kmParamSet2Hidl(key_characteristics.hw_enforced);
440     }
441 
442     _hidl_cb(legacy_enum_conversion(rc), resultCharacteristics);
443 
444     keymaster_free_characteristics(&key_characteristics);
445 
446     return Void();
447 }
448 
importKey(const hidl_vec<KeyParameter> & params,KeyFormat keyFormat,const hidl_vec<uint8_t> & keyData,importKey_cb _hidl_cb)449 Return<void> KeymasterDevice::importKey(const hidl_vec<KeyParameter>& params, KeyFormat keyFormat,
450                                         const hidl_vec<uint8_t>& keyData, importKey_cb _hidl_cb) {
451     // result variables for the wire
452     KeyCharacteristics resultCharacteristics;
453     hidl_vec<uint8_t> resultKeyBlob;
454 
455     // result variables the backend understands
456     keymaster_key_blob_t key_blob{nullptr, 0};
457     keymaster_key_characteristics_t key_characteristics{{nullptr, 0}, {nullptr, 0}};
458 
459     auto kmParams = hidlParams2KmParamSet(params);
460     auto kmKeyData = hidlVec2KmBlob(keyData);
461 
462     auto rc = keymaster_device_->import_key(keymaster_device_, &kmParams,
463                                             legacy_enum_conversion(keyFormat), &kmKeyData,
464                                             &key_blob, &key_characteristics);
465 
466     if (rc == KM_ERROR_OK) {
467         // on success convert the result to wire format
468         // (Can we assume that key_blob is {nullptr, 0} or a valid buffer description?)
469         resultKeyBlob = kmBlob2hidlVec(key_blob);
470         resultCharacteristics.softwareEnforced = kmParamSet2Hidl(key_characteristics.sw_enforced);
471         resultCharacteristics.teeEnforced = kmParamSet2Hidl(key_characteristics.hw_enforced);
472     }
473 
474     _hidl_cb(legacy_enum_conversion(rc), resultKeyBlob, resultCharacteristics);
475 
476     // free buffers that we are responsible for
477     if (key_blob.key_material) free(const_cast<uint8_t*>(key_blob.key_material));
478     keymaster_free_characteristics(&key_characteristics);
479 
480     return Void();
481 }
482 
exportKey(KeyFormat exportFormat,const hidl_vec<uint8_t> & keyBlob,const hidl_vec<uint8_t> & clientId,const hidl_vec<uint8_t> & appData,exportKey_cb _hidl_cb)483 Return<void> KeymasterDevice::exportKey(KeyFormat exportFormat, const hidl_vec<uint8_t>& keyBlob,
484                                         const hidl_vec<uint8_t>& clientId,
485                                         const hidl_vec<uint8_t>& appData, exportKey_cb _hidl_cb) {
486 
487     // result variables for the wire
488     hidl_vec<uint8_t> resultKeyBlob;
489 
490     // result variables the backend understands
491     keymaster_blob_t out_blob{nullptr, 0};
492 
493     auto kmKeyBlob = hidlVec2KmKeyBlob(keyBlob);
494     auto kmClientId = hidlVec2KmBlob(clientId);
495     auto kmAppData = hidlVec2KmBlob(appData);
496 
497     auto rc = keymaster_device_->export_key(keymaster_device_, legacy_enum_conversion(exportFormat),
498                                             keyBlob.size() ? &kmKeyBlob : nullptr,
499                                             clientId.size() ? &kmClientId : nullptr,
500                                             appData.size() ? &kmAppData : nullptr, &out_blob);
501 
502     if (rc == KM_ERROR_OK) {
503         // on success convert the result to wire format
504         // (Can we assume that key_blob is {nullptr, 0} or a valid buffer description?)
505         resultKeyBlob = kmBlob2hidlVec(out_blob);
506     }
507 
508     _hidl_cb(legacy_enum_conversion(rc), resultKeyBlob);
509 
510     // free buffers that we are responsible for
511     if (out_blob.data) free(const_cast<uint8_t*>(out_blob.data));
512 
513     return Void();
514 }
515 
attestKey(const hidl_vec<uint8_t> & keyToAttest,const hidl_vec<KeyParameter> & attestParams,attestKey_cb _hidl_cb)516 Return<void> KeymasterDevice::attestKey(const hidl_vec<uint8_t>& keyToAttest,
517                                         const hidl_vec<KeyParameter>& attestParams,
518                                         attestKey_cb _hidl_cb) {
519 
520     hidl_vec<hidl_vec<uint8_t>> resultCertChain;
521 
522     bool foundAttestationApplicationId = false;
523     for (size_t i = 0; i < attestParams.size(); ++i) {
524         switch (attestParams[i].tag) {
525         case Tag::ATTESTATION_ID_BRAND:
526         case Tag::ATTESTATION_ID_DEVICE:
527         case Tag::ATTESTATION_ID_PRODUCT:
528         case Tag::ATTESTATION_ID_SERIAL:
529         case Tag::ATTESTATION_ID_IMEI:
530         case Tag::ATTESTATION_ID_MEID:
531         case Tag::ATTESTATION_ID_MANUFACTURER:
532         case Tag::ATTESTATION_ID_MODEL:
533             // Device id attestation may only be supported if the device is able to permanently
534             // destroy its knowledge of the ids. This device is unable to do this, so it must
535             // never perform any device id attestation.
536             _hidl_cb(ErrorCode::CANNOT_ATTEST_IDS, resultCertChain);
537             return Void();
538 
539         case Tag::ATTESTATION_APPLICATION_ID:
540             foundAttestationApplicationId = true;
541             break;
542 
543         default:
544             break;
545         }
546     }
547 
548     // KM3 devices reject missing attest application IDs. KM2 devices do not.
549     if (!foundAttestationApplicationId) {
550         _hidl_cb(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
551                  resultCertChain);
552         return Void();
553     }
554 
555     keymaster_cert_chain_t cert_chain{nullptr, 0};
556 
557     auto kmKeyToAttest = hidlVec2KmKeyBlob(keyToAttest);
558     auto kmAttestParams = hidlParams2KmParamSet(attestParams);
559 
560     auto rc = keymaster_device_->attest_key(keymaster_device_, &kmKeyToAttest, &kmAttestParams,
561                                             &cert_chain);
562 
563     if (rc == KM_ERROR_OK) {
564         resultCertChain = kmCertChain2Hidl(&cert_chain);
565     }
566 
567     _hidl_cb(legacy_enum_conversion(rc), resultCertChain);
568 
569     keymaster_free_cert_chain(&cert_chain);
570 
571     return Void();
572 }
573 
upgradeKey(const hidl_vec<uint8_t> & keyBlobToUpgrade,const hidl_vec<KeyParameter> & upgradeParams,upgradeKey_cb _hidl_cb)574 Return<void> KeymasterDevice::upgradeKey(const hidl_vec<uint8_t>& keyBlobToUpgrade,
575                                          const hidl_vec<KeyParameter>& upgradeParams,
576                                          upgradeKey_cb _hidl_cb) {
577 
578     // result variables for the wire
579     hidl_vec<uint8_t> resultKeyBlob;
580 
581     // result variables the backend understands
582     keymaster_key_blob_t key_blob{nullptr, 0};
583 
584     auto kmKeyBlobToUpgrade = hidlVec2KmKeyBlob(keyBlobToUpgrade);
585     auto kmUpgradeParams = hidlParams2KmParamSet(upgradeParams);
586 
587     auto rc = keymaster_device_->upgrade_key(keymaster_device_, &kmKeyBlobToUpgrade,
588                                              &kmUpgradeParams, &key_blob);
589 
590     if (rc == KM_ERROR_OK) {
591         // on success convert the result to wire format
592         resultKeyBlob = kmBlob2hidlVec(key_blob);
593     }
594 
595     _hidl_cb(legacy_enum_conversion(rc), resultKeyBlob);
596 
597     if (key_blob.key_material) free(const_cast<uint8_t*>(key_blob.key_material));
598 
599     return Void();
600 }
601 
deleteKey(const hidl_vec<uint8_t> & keyBlob)602 Return<ErrorCode> KeymasterDevice::deleteKey(const hidl_vec<uint8_t>& keyBlob) {
603     if (keymaster_device_->delete_key == nullptr) {
604         return ErrorCode::UNIMPLEMENTED;
605     }
606     auto kmKeyBlob = hidlVec2KmKeyBlob(keyBlob);
607     auto rc = legacy_enum_conversion(
608         keymaster_device_->delete_key(keymaster_device_, &kmKeyBlob));
609     // Keymaster 3.0 requires deleteKey to return ErrorCode::OK if the key
610     // blob is unusable after the call. This is equally true if the key blob was
611     // unusable before.
612     if (rc == ErrorCode::INVALID_KEY_BLOB) return ErrorCode::OK;
613     return rc;
614 }
615 
deleteAllKeys()616 Return<ErrorCode> KeymasterDevice::deleteAllKeys() {
617     if (keymaster_device_->delete_all_keys == nullptr) {
618         return ErrorCode::UNIMPLEMENTED;
619     }
620     return legacy_enum_conversion(keymaster_device_->delete_all_keys(keymaster_device_));
621 }
622 
destroyAttestationIds()623 Return<ErrorCode> KeymasterDevice::destroyAttestationIds() {
624     return ErrorCode::UNIMPLEMENTED;
625 }
626 
begin(KeyPurpose purpose,const hidl_vec<uint8_t> & key,const hidl_vec<KeyParameter> & inParams,begin_cb _hidl_cb)627 Return<void> KeymasterDevice::begin(KeyPurpose purpose, const hidl_vec<uint8_t>& key,
628                                     const hidl_vec<KeyParameter>& inParams, begin_cb _hidl_cb) {
629 
630     // result variables for the wire
631     hidl_vec<KeyParameter> resultParams;
632     uint64_t resultOpHandle = 0;
633 
634     // result variables the backend understands
635     keymaster_key_param_set_t out_params{nullptr, 0};
636     keymaster_operation_handle_t& operation_handle = resultOpHandle;
637 
638     auto kmKey = hidlVec2KmKeyBlob(key);
639     auto kmInParams = hidlParams2KmParamSet(inParams);
640 
641     auto rc = keymaster_device_->begin(keymaster_device_, legacy_enum_conversion(purpose), &kmKey,
642                                        &kmInParams, &out_params, &operation_handle);
643 
644     if (rc == KM_ERROR_OK) resultParams = kmParamSet2Hidl(out_params);
645 
646     _hidl_cb(legacy_enum_conversion(rc), resultParams, resultOpHandle);
647 
648     keymaster_free_param_set(&out_params);
649 
650     return Void();
651 }
652 
update(uint64_t operationHandle,const hidl_vec<KeyParameter> & inParams,const hidl_vec<uint8_t> & input,update_cb _hidl_cb)653 Return<void> KeymasterDevice::update(uint64_t operationHandle,
654                                      const hidl_vec<KeyParameter>& inParams,
655                                      const hidl_vec<uint8_t>& input, update_cb _hidl_cb) {
656     // result variables for the wire
657     uint32_t resultConsumed = 0;
658     hidl_vec<KeyParameter> resultParams;
659     hidl_vec<uint8_t> resultBlob;
660 
661     // result variables the backend understands
662     size_t consumed = 0;
663     keymaster_key_param_set_t out_params{nullptr, 0};
664     keymaster_blob_t out_blob{nullptr, 0};
665 
666     auto kmInParams = hidlParams2KmParamSet(inParams);
667     auto kmInput = hidlVec2KmBlob(input);
668 
669     auto rc = keymaster_device_->update(keymaster_device_, operationHandle, &kmInParams, &kmInput,
670                                         &consumed, &out_params, &out_blob);
671 
672     if (rc == KM_ERROR_OK) {
673         resultConsumed = consumed;
674         resultParams = kmParamSet2Hidl(out_params);
675         resultBlob = kmBlob2hidlVec(out_blob);
676     }
677 
678     _hidl_cb(legacy_enum_conversion(rc), resultConsumed, resultParams, resultBlob);
679 
680     keymaster_free_param_set(&out_params);
681     if (out_blob.data) free(const_cast<uint8_t*>(out_blob.data));
682 
683     return Void();
684 }
685 
finish(uint64_t operationHandle,const hidl_vec<KeyParameter> & inParams,const hidl_vec<uint8_t> & input,const hidl_vec<uint8_t> & signature,finish_cb _hidl_cb)686 Return<void> KeymasterDevice::finish(uint64_t operationHandle,
687                                      const hidl_vec<KeyParameter>& inParams,
688                                      const hidl_vec<uint8_t>& input,
689                                      const hidl_vec<uint8_t>& signature, finish_cb _hidl_cb) {
690     // result variables for the wire
691     hidl_vec<KeyParameter> resultParams;
692     hidl_vec<uint8_t> resultBlob;
693 
694     // result variables the backend understands
695     keymaster_key_param_set_t out_params{nullptr, 0};
696     keymaster_blob_t out_blob{nullptr, 0};
697 
698     auto kmInParams = hidlParams2KmParamSet(inParams);
699     auto kmInput = hidlVec2KmBlob(input);
700     auto kmSignature = hidlVec2KmBlob(signature);
701 
702     auto rc = keymaster_device_->finish(keymaster_device_, operationHandle, &kmInParams, &kmInput,
703                                         &kmSignature, &out_params, &out_blob);
704 
705     if (rc == KM_ERROR_OK) {
706         resultParams = kmParamSet2Hidl(out_params);
707         resultBlob = kmBlob2hidlVec(out_blob);
708     }
709 
710     _hidl_cb(legacy_enum_conversion(rc), resultParams, resultBlob);
711 
712     keymaster_free_param_set(&out_params);
713     if (out_blob.data) free(const_cast<uint8_t*>(out_blob.data));
714 
715     return Void();
716 }
717 
abort(uint64_t operationHandle)718 Return<ErrorCode> KeymasterDevice::abort(uint64_t operationHandle) {
719     return legacy_enum_conversion(keymaster_device_->abort(keymaster_device_, operationHandle));
720 }
721 
HIDL_FETCH_IKeymasterDevice(const char * name)722 IKeymasterDevice* HIDL_FETCH_IKeymasterDevice(const char* name) {
723     keymaster2_device_t* dev = nullptr;
724 
725     ALOGI("Fetching keymaster device name %s", name);
726 
727     uint32_t version = -1;
728     bool supports_ec = false;
729     bool supports_all_digests = false;
730 
731     if (name && strcmp(name, "softwareonly") == 0) {
732         dev = (new SoftKeymasterDevice(new SoftwareOnlyHidlKeymasterContext))->keymaster2_device();
733     } else if (name && strcmp(name, "default") == 0) {
734         auto rc = keymaster_device_initialize(&dev, &version, &supports_ec, &supports_all_digests);
735         if (rc) return nullptr;
736     }
737 
738     auto kmrc = ::keymaster::ConfigureDevice(dev);
739     if (kmrc != KM_ERROR_OK) {
740         dev->common.close(&dev->common);
741         return nullptr;
742     }
743 
744     return new KeymasterDevice(dev, version, supports_ec, supports_all_digests);
745 }
746 
747 }  // namespace implementation
748 }  // namespace V3_0
749 }  // namespace keymaster
750 }  // namespace hardware
751 }  // namespace android
752