• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 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/attestation_record.h>
18 
19 #include <assert.h>
20 
21 #include <openssl/asn1t.h>
22 
23 #include <keymaster/android_keymaster_utils.h>
24 #include <keymaster/km_openssl/openssl_err.h>
25 #include <keymaster/km_openssl/openssl_utils.h>
26 
27 namespace keymaster {
28 
29 constexpr uint kCurrentKeymasterVersion = 3;
30 constexpr uint kCurrentAttestationVersion = 2;
31 constexpr size_t kMaximumAttestationChallengeLength = 128;
32 
33 IMPLEMENT_ASN1_FUNCTIONS(KM_ROOT_OF_TRUST);
34 IMPLEMENT_ASN1_FUNCTIONS(KM_AUTH_LIST);
35 IMPLEMENT_ASN1_FUNCTIONS(KM_KEY_DESCRIPTION);
36 
37 static const keymaster_tag_t kDeviceAttestationTags[] = {
38     KM_TAG_ATTESTATION_ID_BRAND,
39     KM_TAG_ATTESTATION_ID_DEVICE,
40     KM_TAG_ATTESTATION_ID_PRODUCT,
41     KM_TAG_ATTESTATION_ID_SERIAL,
42     KM_TAG_ATTESTATION_ID_IMEI,
43     KM_TAG_ATTESTATION_ID_MEID,
44     KM_TAG_ATTESTATION_ID_MANUFACTURER,
45     KM_TAG_ATTESTATION_ID_MODEL,
46 };
47 
48 struct KM_AUTH_LIST_Delete {
operator ()keymaster::KM_AUTH_LIST_Delete49     void operator()(KM_AUTH_LIST* p) { KM_AUTH_LIST_free(p); }
50 };
51 
52 struct KM_KEY_DESCRIPTION_Delete {
operator ()keymaster::KM_KEY_DESCRIPTION_Delete53     void operator()(KM_KEY_DESCRIPTION* p) { KM_KEY_DESCRIPTION_free(p); }
54 };
55 
get_uint32_value(const keymaster_key_param_t & param)56 static uint32_t get_uint32_value(const keymaster_key_param_t& param) {
57     switch (keymaster_tag_get_type(param.tag)) {
58     case KM_ENUM:
59     case KM_ENUM_REP:
60         return param.enumerated;
61     case KM_UINT:
62     case KM_UINT_REP:
63         return param.integer;
64     default:
65         assert(false);
66         return 0xFFFFFFFF;
67     }
68 }
69 
70 // Insert value in either the dest_integer or the dest_integer_set, whichever is provided.
insert_integer(ASN1_INTEGER * value,ASN1_INTEGER ** dest_integer,ASN1_INTEGER_SET ** dest_integer_set)71 static keymaster_error_t insert_integer(ASN1_INTEGER* value, ASN1_INTEGER** dest_integer,
72                                         ASN1_INTEGER_SET** dest_integer_set) {
73     assert((dest_integer == nullptr) ^ (dest_integer_set == nullptr));
74     assert(value);
75 
76     if (dest_integer_set) {
77         if (!*dest_integer_set)
78             *dest_integer_set = sk_ASN1_INTEGER_new_null();
79         if (!*dest_integer_set)
80             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
81         if (!sk_ASN1_INTEGER_push(*dest_integer_set, value))
82             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
83         return KM_ERROR_OK;
84 
85     } else if (dest_integer) {
86         if (*dest_integer)
87             ASN1_INTEGER_free(*dest_integer);
88         *dest_integer = value;
89         return KM_ERROR_OK;
90     }
91 
92     assert(false);  // Should never get here.
93     return KM_ERROR_OK;
94 }
95 
96 // Put the contents of the keymaster AuthorizationSet auth_list in to the ASN.1 record structure,
97 // record.
build_auth_list(const AuthorizationSet & auth_list,KM_AUTH_LIST * record)98 keymaster_error_t build_auth_list(const AuthorizationSet& auth_list, KM_AUTH_LIST* record) {
99     assert(record);
100 
101     if (auth_list.empty())
102         return KM_ERROR_OK;
103 
104     for (auto entry : auth_list) {
105 
106         ASN1_INTEGER_SET** integer_set = nullptr;
107         ASN1_INTEGER** integer_ptr = nullptr;
108         ASN1_OCTET_STRING** string_ptr = nullptr;
109         ASN1_NULL** bool_ptr = nullptr;
110 
111         switch (entry.tag) {
112 
113         /* Tags ignored because they should never exist */
114         case KM_TAG_INVALID:
115 
116         /* Tags ignored because they're not used. */
117         case KM_TAG_ALL_USERS:
118         case KM_TAG_EXPORTABLE:
119         case KM_TAG_ECIES_SINGLE_HASH_MODE:
120 
121         /* Tags ignored because they're used only to provide information to operations */
122         case KM_TAG_ASSOCIATED_DATA:
123         case KM_TAG_NONCE:
124         case KM_TAG_AUTH_TOKEN:
125         case KM_TAG_MAC_LENGTH:
126         case KM_TAG_ATTESTATION_CHALLENGE:
127         case KM_TAG_RESET_SINCE_ID_ROTATION:
128 
129         /* Tags ignored because they have no meaning off-device */
130         case KM_TAG_USER_ID:
131         case KM_TAG_USER_SECURE_ID:
132         case KM_TAG_BLOB_USAGE_REQUIREMENTS:
133 
134         /* Tags ignored because they're not usable by app keys */
135         case KM_TAG_BOOTLOADER_ONLY:
136         case KM_TAG_INCLUDE_UNIQUE_ID:
137         case KM_TAG_MAX_USES_PER_BOOT:
138         case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
139         case KM_TAG_UNIQUE_ID:
140 
141         /* Tags ignored because they contain data that should not be exported */
142         case KM_TAG_APPLICATION_DATA:
143         case KM_TAG_ROOT_OF_TRUST:
144             continue;
145 
146         /* Non-repeating enumerations */
147         case KM_TAG_ALGORITHM:
148             integer_ptr = &record->algorithm;
149             break;
150         case KM_TAG_EC_CURVE:
151             integer_ptr = &record->ec_curve;
152             break;
153         case KM_TAG_USER_AUTH_TYPE:
154             integer_ptr = &record->user_auth_type;
155             break;
156         case KM_TAG_ORIGIN:
157             integer_ptr = &record->origin;
158             break;
159 
160         /* Repeating enumerations */
161         case KM_TAG_PURPOSE:
162             integer_set = &record->purpose;
163             break;
164         case KM_TAG_PADDING:
165             integer_set = &record->padding;
166             break;
167         case KM_TAG_DIGEST:
168             integer_set = &record->digest;
169             break;
170         case KM_TAG_KDF:
171             integer_set = &record->kdf;
172             break;
173         case KM_TAG_BLOCK_MODE:
174             integer_set = &record->block_mode;
175             break;
176 
177         /* Non-repeating unsigned integers */
178         case KM_TAG_KEY_SIZE:
179             integer_ptr = &record->key_size;
180             break;
181         case KM_TAG_AUTH_TIMEOUT:
182             integer_ptr = &record->auth_timeout;
183             break;
184         case KM_TAG_OS_VERSION:
185             integer_ptr = &record->os_version;
186             break;
187         case KM_TAG_OS_PATCHLEVEL:
188             integer_ptr = &record->os_patchlevel;
189             break;
190         case KM_TAG_MIN_MAC_LENGTH:
191             integer_ptr = &record->min_mac_length;
192             break;
193 
194         /* Non-repeating long unsigned integers */
195         case KM_TAG_RSA_PUBLIC_EXPONENT:
196             integer_ptr = &record->rsa_public_exponent;
197             break;
198 
199         /* Dates */
200         case KM_TAG_ACTIVE_DATETIME:
201             integer_ptr = &record->active_date_time;
202             break;
203         case KM_TAG_ORIGINATION_EXPIRE_DATETIME:
204             integer_ptr = &record->origination_expire_date_time;
205             break;
206         case KM_TAG_USAGE_EXPIRE_DATETIME:
207             integer_ptr = &record->usage_expire_date_time;
208             break;
209         case KM_TAG_CREATION_DATETIME:
210             integer_ptr = &record->creation_date_time;
211             break;
212 
213         /* Booleans */
214         case KM_TAG_NO_AUTH_REQUIRED:
215             bool_ptr = &record->no_auth_required;
216             break;
217         case KM_TAG_ALL_APPLICATIONS:
218             bool_ptr = &record->all_applications;
219             break;
220         case KM_TAG_ROLLBACK_RESISTANT:
221             bool_ptr = &record->rollback_resistant;
222             break;
223         case KM_TAG_ALLOW_WHILE_ON_BODY:
224             bool_ptr = &record->allow_while_on_body;
225             break;
226         case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
227             bool_ptr = &record->unlocked_device_required;
228             break;
229         case KM_TAG_CALLER_NONCE:
230             bool_ptr = &record->caller_nonce;
231             break;
232         case KM_TAG_TRUSTED_CONFIRMATION_REQUIRED:
233             bool_ptr = &record->trusted_confirmation_required;
234             break;
235 
236         /* Byte arrays*/
237         case KM_TAG_APPLICATION_ID:
238             string_ptr = &record->application_id;
239             break;
240         case KM_TAG_ATTESTATION_APPLICATION_ID:
241             string_ptr = &record->attestation_application_id;
242             break;
243         case KM_TAG_ATTESTATION_ID_BRAND:
244             string_ptr = &record->attestation_id_brand;
245             break;
246         case KM_TAG_ATTESTATION_ID_DEVICE:
247             string_ptr = &record->attestation_id_device;
248             break;
249         case KM_TAG_ATTESTATION_ID_PRODUCT:
250             string_ptr = &record->attestation_id_product;
251             break;
252         case KM_TAG_ATTESTATION_ID_SERIAL:
253             string_ptr = &record->attestation_id_serial;
254             break;
255         case KM_TAG_ATTESTATION_ID_IMEI:
256             string_ptr = &record->attestation_id_imei;
257             break;
258         case KM_TAG_ATTESTATION_ID_MEID:
259             string_ptr = &record->attestation_id_meid;
260             break;
261         case KM_TAG_ATTESTATION_ID_MANUFACTURER:
262             string_ptr = &record->attestation_id_manufacturer;
263             break;
264         case KM_TAG_ATTESTATION_ID_MODEL:
265             string_ptr = &record->attestation_id_model;
266             break;
267         }
268 
269         keymaster_tag_type_t type = keymaster_tag_get_type(entry.tag);
270         switch (type) {
271         case KM_ENUM:
272         case KM_ENUM_REP:
273         case KM_UINT:
274         case KM_UINT_REP: {
275             assert((keymaster_tag_repeatable(entry.tag) && integer_set) ||
276                    (!keymaster_tag_repeatable(entry.tag) && integer_ptr));
277 
278             UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> value(ASN1_INTEGER_new());
279             if (!value.get())
280                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
281             if (!ASN1_INTEGER_set(value.get(), get_uint32_value(entry)))
282                 return TranslateLastOpenSslError();
283 
284             insert_integer(value.release(), integer_ptr, integer_set);
285             break;
286         }
287 
288         case KM_ULONG:
289         case KM_ULONG_REP:
290         case KM_DATE: {
291             assert((keymaster_tag_repeatable(entry.tag) && integer_set) ||
292                    (!keymaster_tag_repeatable(entry.tag) && integer_ptr));
293 
294             UniquePtr<BIGNUM, BIGNUM_Delete> bn_value(BN_new());
295             if (!bn_value.get())
296                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
297 
298             if (type == KM_DATE) {
299                 if (!BN_set_u64(bn_value.get(), entry.date_time)) {
300                     return TranslateLastOpenSslError();
301                 }
302             } else {
303                 if (!BN_set_u64(bn_value.get(), entry.long_integer)) {
304                     return TranslateLastOpenSslError();
305                 }
306             }
307 
308             UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> value(
309                 BN_to_ASN1_INTEGER(bn_value.get(), nullptr));
310             if (!value.get())
311                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
312 
313             insert_integer(value.release(), integer_ptr, integer_set);
314             break;
315         }
316 
317         case KM_BOOL:
318             assert(bool_ptr);
319             if (!*bool_ptr)
320                 *bool_ptr = ASN1_NULL_new();
321             if (!*bool_ptr)
322                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
323             break;
324 
325         /* Byte arrays*/
326         case KM_BYTES:
327             assert(string_ptr);
328             if (!*string_ptr)
329                 *string_ptr = ASN1_OCTET_STRING_new();
330             if (!*string_ptr)
331                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
332             if (!ASN1_OCTET_STRING_set(*string_ptr, entry.blob.data, entry.blob.data_length))
333                 return TranslateLastOpenSslError();
334             break;
335 
336         default:
337             return KM_ERROR_UNIMPLEMENTED;
338         }
339     }
340 
341     keymaster_ec_curve_t ec_curve;
342     uint32_t key_size;
343     if (auth_list.Contains(TAG_ALGORITHM, KM_ALGORITHM_EC) &&  //
344         !auth_list.Contains(TAG_EC_CURVE) &&                   //
345         auth_list.GetTagValue(TAG_KEY_SIZE, &key_size)) {
346         // This must be a keymaster1 key. It's an EC key with no curve.  Insert the curve.
347 
348         keymaster_error_t error = EcKeySizeToCurve(key_size, &ec_curve);
349         if (error != KM_ERROR_OK)
350             return error;
351 
352         UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> value(ASN1_INTEGER_new());
353         if (!value.get())
354             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
355 
356         if (!ASN1_INTEGER_set(value.get(), ec_curve))
357             return TranslateLastOpenSslError();
358 
359         insert_integer(value.release(), &record->ec_curve, nullptr);
360     }
361 
362     return KM_ERROR_OK;
363 }
364 
365 // Construct an ASN1.1 DER-encoded attestation record containing the values from sw_enforced and
366 // tee_enforced.
build_attestation_record(const AuthorizationSet & attestation_params,AuthorizationSet sw_enforced,AuthorizationSet tee_enforced,const AttestationRecordContext & context,UniquePtr<uint8_t[]> * asn1_key_desc,size_t * asn1_key_desc_len)367 keymaster_error_t build_attestation_record(const AuthorizationSet& attestation_params,
368                                            AuthorizationSet sw_enforced,
369                                            AuthorizationSet tee_enforced,
370                                            const AttestationRecordContext& context,
371                                            UniquePtr<uint8_t[]>* asn1_key_desc,
372                                            size_t* asn1_key_desc_len) {
373     assert(asn1_key_desc && asn1_key_desc_len);
374 
375     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> key_desc(KM_KEY_DESCRIPTION_new());
376     if (!key_desc.get())
377         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
378 
379     keymaster_security_level_t keymaster_security_level;
380     uint32_t keymaster_version = UINT32_MAX;
381     if (tee_enforced.empty()) {
382         // Software key.
383         keymaster_security_level = KM_SECURITY_LEVEL_SOFTWARE;
384         keymaster_version = kCurrentKeymasterVersion;
385     } else {
386         keymaster_security_level = KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
387         switch (context.GetSecurityLevel()) {
388         case KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT: {
389             keymaster_version = kCurrentKeymasterVersion;
390 
391             // Root of trust is only available in TEE
392             KM_AUTH_LIST* tee_record = key_desc->tee_enforced;
393             tee_record->root_of_trust = KM_ROOT_OF_TRUST_new();
394             keymaster_blob_t verified_boot_key;
395             keymaster_verified_boot_t verified_boot_state;
396             bool device_locked;
397             keymaster_error_t error = context.GetVerifiedBootParams(
398                 &verified_boot_key, &verified_boot_state, &device_locked);
399             if (error != KM_ERROR_OK)
400                 return error;
401             if (verified_boot_key.data_length &&
402                 !ASN1_OCTET_STRING_set(tee_record->root_of_trust->verified_boot_key,
403                                        verified_boot_key.data, verified_boot_key.data_length))
404                 return TranslateLastOpenSslError();
405             tee_record->root_of_trust->device_locked = (int*)device_locked;
406             if (!ASN1_ENUMERATED_set(tee_record->root_of_trust->verified_boot_state,
407                                      verified_boot_state))
408                 return TranslateLastOpenSslError();
409             break;
410         }
411         case KM_SECURITY_LEVEL_SOFTWARE:
412             // We're running in software, wrapping some KM hardware.  Is it KM0 or KM1?  KM1 keys
413             // have the purpose in the tee_enforced list.  It's possible that a key could be created
414             // without a purpose, which would fool this test into reporting it's a KM0 key.  That
415             // corner case doesn't matter much, because purpose-less keys are not usable anyway.
416             // Also, KM1 TEEs should disappear rapidly.
417             keymaster_version = tee_enforced.Contains(TAG_PURPOSE) ? 1 : 0;
418             break;
419         }
420 
421         if (keymaster_version == UINT32_MAX)
422             return KM_ERROR_UNKNOWN_ERROR;
423     }
424 
425     if (!ASN1_INTEGER_set(key_desc->attestation_version, kCurrentAttestationVersion) ||
426         !ASN1_ENUMERATED_set(key_desc->attestation_security_level, context.GetSecurityLevel()) ||
427         !ASN1_INTEGER_set(key_desc->keymaster_version, keymaster_version) ||
428         !ASN1_ENUMERATED_set(key_desc->keymaster_security_level, keymaster_security_level))
429         return TranslateLastOpenSslError();
430 
431     keymaster_blob_t attestation_challenge = {nullptr, 0};
432     if (!attestation_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge))
433         return KM_ERROR_ATTESTATION_CHALLENGE_MISSING;
434 
435     if (attestation_challenge.data_length > kMaximumAttestationChallengeLength)
436         return KM_ERROR_INVALID_INPUT_LENGTH;
437 
438     if (!ASN1_OCTET_STRING_set(key_desc->attestation_challenge, attestation_challenge.data,
439                                attestation_challenge.data_length))
440         return TranslateLastOpenSslError();
441 
442     keymaster_blob_t attestation_app_id;
443     if (!attestation_params.GetTagValue(TAG_ATTESTATION_APPLICATION_ID, &attestation_app_id))
444         return KM_ERROR_ATTESTATION_APPLICATION_ID_MISSING;
445     sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_app_id);
446 
447     keymaster_error_t error = context.VerifyAndCopyDeviceIds(attestation_params,
448             keymaster_security_level == KM_SECURITY_LEVEL_SOFTWARE ? &sw_enforced : &tee_enforced);
449     if (error == KM_ERROR_UNIMPLEMENTED) {
450         // The KeymasterContext implementation does not support device ID attestation. Bail out if
451         // device ID attestation is being attempted.
452         for (const auto& tag : kDeviceAttestationTags) {
453             if (attestation_params.find(tag) != -1) {
454                 return KM_ERROR_CANNOT_ATTEST_IDS;
455             }
456         }
457     } else if (error != KM_ERROR_OK) {
458         return error;
459     }
460 
461     error = build_auth_list(sw_enforced, key_desc->software_enforced);
462     if (error != KM_ERROR_OK)
463         return error;
464 
465     error = build_auth_list(tee_enforced, key_desc->tee_enforced);
466     if (error != KM_ERROR_OK)
467         return error;
468 
469     // Only check tee_enforced for TAG_INCLUDE_UNIQUE_ID.  If we don't have hardware we can't
470     // generate unique IDs.
471     if (tee_enforced.GetTagValue(TAG_INCLUDE_UNIQUE_ID)) {
472         uint64_t creation_datetime;
473         // Only check sw_enforced for TAG_CREATION_DATETIME, since it shouldn't be in tee_enforced,
474         // since this implementation has no secure wall clock.
475         if (!sw_enforced.GetTagValue(TAG_CREATION_DATETIME, &creation_datetime)) {
476             LOG_E("Unique ID cannot be created without creation datetime", 0);
477             return KM_ERROR_INVALID_KEY_BLOB;
478         }
479 
480         keymaster_blob_t application_id = {nullptr, 0};
481         sw_enforced.GetTagValue(TAG_APPLICATION_ID, &application_id);
482 
483         Buffer unique_id;
484         error = context.GenerateUniqueId(
485             creation_datetime, application_id,
486             attestation_params.GetTagValue(TAG_RESET_SINCE_ID_ROTATION), &unique_id);
487         if (error != KM_ERROR_OK)
488             return error;
489 
490         key_desc->unique_id = ASN1_OCTET_STRING_new();
491         if (!key_desc->unique_id ||
492             !ASN1_OCTET_STRING_set(key_desc->unique_id, unique_id.peek_read(),
493                                    unique_id.available_read()))
494             return TranslateLastOpenSslError();
495     }
496 
497     int len = i2d_KM_KEY_DESCRIPTION(key_desc.get(), nullptr);
498     if (len < 0)
499         return TranslateLastOpenSslError();
500     *asn1_key_desc_len = len;
501     asn1_key_desc->reset(new(std::nothrow) uint8_t[*asn1_key_desc_len]);
502     if (!asn1_key_desc->get())
503         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
504     uint8_t* p = asn1_key_desc->get();
505     len = i2d_KM_KEY_DESCRIPTION(key_desc.get(), &p);
506     if (len < 0)
507         return TranslateLastOpenSslError();
508 
509     return KM_ERROR_OK;
510 }
511 
512 // Copy all enumerated values with the specified tag from stack to auth_list.
get_repeated_enums(const ASN1_INTEGER_SET * stack,keymaster_tag_t tag,AuthorizationSet * auth_list)513 static bool get_repeated_enums(const ASN1_INTEGER_SET* stack, keymaster_tag_t tag,
514                                AuthorizationSet* auth_list) {
515     assert(keymaster_tag_get_type(tag) == KM_ENUM_REP);
516     for (size_t i = 0; i < sk_ASN1_INTEGER_num(stack); ++i) {
517         if (!auth_list->push_back(
518                 keymaster_param_enum(tag, ASN1_INTEGER_get(sk_ASN1_INTEGER_value(stack, i)))))
519             return false;
520     }
521     return true;
522 }
523 
524 // Add the specified integer tag/value pair to auth_list.
525 template <keymaster_tag_type_t Type, keymaster_tag_t Tag, typename KeymasterEnum>
get_enum(const ASN1_INTEGER * asn1_int,TypedEnumTag<Type,Tag,KeymasterEnum> tag,AuthorizationSet * auth_list)526 static bool get_enum(const ASN1_INTEGER* asn1_int, TypedEnumTag<Type, Tag, KeymasterEnum> tag,
527                      AuthorizationSet* auth_list) {
528     if (!asn1_int)
529         return true;
530     return auth_list->push_back(tag, static_cast<KeymasterEnum>(ASN1_INTEGER_get(asn1_int)));
531 }
532 
533 // Add the specified ulong tag/value pair to auth_list.
get_ulong(const ASN1_INTEGER * asn1_int,keymaster_tag_t tag,AuthorizationSet * auth_list)534 static bool get_ulong(const ASN1_INTEGER* asn1_int, keymaster_tag_t tag,
535                       AuthorizationSet* auth_list) {
536     if (!asn1_int)
537         return true;
538     UniquePtr<BIGNUM, BIGNUM_Delete> bn(ASN1_INTEGER_to_BN(asn1_int, nullptr));
539     if (!bn.get())
540         return false;
541     uint64_t ulong = BN_get_word(bn.get());
542     return auth_list->push_back(keymaster_param_long(tag, ulong));
543 }
544 
545 // Extract the values from the specified ASN.1 record and place them in auth_list.
extract_auth_list(const KM_AUTH_LIST * record,AuthorizationSet * auth_list)546 keymaster_error_t extract_auth_list(const KM_AUTH_LIST* record, AuthorizationSet* auth_list) {
547     if (!record)
548         return KM_ERROR_OK;
549 
550     // Purpose
551     if (!get_repeated_enums(record->purpose, TAG_PURPOSE, auth_list))
552         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
553 
554     // Algorithm
555     if (!get_enum(record->algorithm, TAG_ALGORITHM, auth_list))
556         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
557 
558     // Key size
559     if (record->key_size && !auth_list->push_back(TAG_KEY_SIZE, ASN1_INTEGER_get(record->key_size)))
560         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
561 
562     // Block mode
563     if (!get_repeated_enums(record->block_mode, TAG_BLOCK_MODE, auth_list))
564         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
565 
566     // Digest
567     if (!get_repeated_enums(record->digest, TAG_DIGEST, auth_list))
568         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
569 
570     // Padding
571     if (!get_repeated_enums(record->padding, TAG_PADDING, auth_list))
572         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
573 
574     // Caller nonce
575     if (record->caller_nonce && !auth_list->push_back(TAG_CALLER_NONCE))
576         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
577 
578     // Min mac length
579     if (!get_ulong(record->min_mac_length, TAG_MIN_MAC_LENGTH, auth_list))
580         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
581 
582     // EC curve
583     if (!get_enum(record->ec_curve, TAG_EC_CURVE, auth_list))
584         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
585 
586     // RSA public exponent
587     if (!get_ulong(record->rsa_public_exponent, TAG_RSA_PUBLIC_EXPONENT, auth_list))
588         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
589 
590     // Active date time
591     if (!get_ulong(record->active_date_time, TAG_ACTIVE_DATETIME, auth_list))
592         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
593 
594     // Origination expire date time
595     if (!get_ulong(record->origination_expire_date_time, TAG_ORIGINATION_EXPIRE_DATETIME,
596                    auth_list))
597         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
598 
599     // Usage Expire date time
600     if (!get_ulong(record->usage_expire_date_time, TAG_USAGE_EXPIRE_DATETIME, auth_list))
601         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
602 
603     // No auth required
604     if (record->no_auth_required && !auth_list->push_back(TAG_NO_AUTH_REQUIRED))
605         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
606 
607     // User auth type
608     if (!get_enum(record->user_auth_type, TAG_USER_AUTH_TYPE, auth_list))
609         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
610 
611     // Auth timeout
612     if (record->auth_timeout &&
613         !auth_list->push_back(TAG_AUTH_TIMEOUT, ASN1_INTEGER_get(record->auth_timeout)))
614         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
615 
616     // All applications
617     if (record->all_applications && !auth_list->push_back(TAG_ALL_APPLICATIONS))
618         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
619 
620     // Application ID
621     if (record->application_id &&
622         !auth_list->push_back(TAG_APPLICATION_ID, record->application_id->data,
623                               record->application_id->length))
624         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
625 
626     // Attestation application ID
627     if (record->attestation_application_id &&
628         !auth_list->push_back(TAG_ATTESTATION_APPLICATION_ID,
629                               record->attestation_application_id->data,
630                               record->attestation_application_id->length))
631         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
632 
633     // Creation date time
634     if (!get_ulong(record->creation_date_time, TAG_CREATION_DATETIME, auth_list))
635         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
636 
637     // Origin
638     if (!get_enum(record->origin, TAG_ORIGIN, auth_list))
639         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
640 
641     // Rollback resistant
642     if (record->rollback_resistant && !auth_list->push_back(TAG_ROLLBACK_RESISTANT))
643         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
644 
645     // Root of trust
646     if (record->root_of_trust) {
647         KM_ROOT_OF_TRUST* rot = record->root_of_trust;
648         if (!rot->verified_boot_key)
649             return KM_ERROR_INVALID_KEY_BLOB;
650 
651         // Other root of trust fields are not mapped to auth set entries.
652     }
653 
654     // OS Version
655     if (record->os_version &&
656         !auth_list->push_back(TAG_OS_VERSION, ASN1_INTEGER_get(record->os_version)))
657         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
658 
659     // OS Patch level
660     if (record->os_patchlevel &&
661         !auth_list->push_back(TAG_OS_PATCHLEVEL, ASN1_INTEGER_get(record->os_patchlevel)))
662         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
663 
664     // Brand name
665     if (record->attestation_id_brand &&
666         !auth_list->push_back(TAG_ATTESTATION_ID_BRAND, record->attestation_id_brand->data,
667                               record->attestation_id_brand->length))
668         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
669 
670     // Device name
671     if (record->attestation_id_device &&
672         !auth_list->push_back(TAG_ATTESTATION_ID_DEVICE, record->attestation_id_device->data,
673                               record->attestation_id_device->length))
674         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
675 
676     // Product name
677     if (record->attestation_id_product &&
678         !auth_list->push_back(TAG_ATTESTATION_ID_PRODUCT, record->attestation_id_product->data,
679                               record->attestation_id_product->length))
680         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
681 
682     // Serial number
683     if (record->attestation_id_serial &&
684         !auth_list->push_back(TAG_ATTESTATION_ID_SERIAL, record->attestation_id_serial->data,
685                               record->attestation_id_serial->length))
686         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
687 
688     // IMEI
689     if (record->attestation_id_imei &&
690         !auth_list->push_back(TAG_ATTESTATION_ID_IMEI, record->attestation_id_imei->data,
691                               record->attestation_id_imei->length))
692         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
693 
694     // MEID
695     if (record->attestation_id_meid &&
696         !auth_list->push_back(TAG_ATTESTATION_ID_MEID, record->attestation_id_meid->data,
697                               record->attestation_id_meid->length))
698         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
699 
700     // Manufacturer name
701     if (record->attestation_id_manufacturer &&
702         !auth_list->push_back(TAG_ATTESTATION_ID_MANUFACTURER,
703                               record->attestation_id_manufacturer->data,
704                               record->attestation_id_manufacturer->length))
705         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
706 
707     // Model name
708     if (record->attestation_id_model &&
709         !auth_list->push_back(TAG_ATTESTATION_ID_MODEL, record->attestation_id_model->data,
710                               record->attestation_id_model->length))
711         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
712 
713     // Trusted confirmation required
714     if (record->trusted_confirmation_required) {
715         if (!auth_list->push_back(TAG_NO_AUTH_REQUIRED)) {
716             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
717         }
718     }
719 
720     return KM_ERROR_OK;
721 }
722 
723 // Parse the DER-encoded attestation record, placing the results in keymaster_version,
724 // attestation_challenge, software_enforced, tee_enforced and unique_id.
parse_attestation_record(const uint8_t * asn1_key_desc,size_t asn1_key_desc_len,uint32_t * attestation_version,keymaster_security_level_t * attestation_security_level,uint32_t * keymaster_version,keymaster_security_level_t * keymaster_security_level,keymaster_blob_t * attestation_challenge,AuthorizationSet * software_enforced,AuthorizationSet * tee_enforced,keymaster_blob_t * unique_id)725 keymaster_error_t parse_attestation_record(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
726                                            uint32_t* attestation_version,  //
727                                            keymaster_security_level_t* attestation_security_level,
728                                            uint32_t* keymaster_version,
729                                            keymaster_security_level_t* keymaster_security_level,
730                                            keymaster_blob_t* attestation_challenge,
731                                            AuthorizationSet* software_enforced,
732                                            AuthorizationSet* tee_enforced,
733                                            keymaster_blob_t* unique_id) {
734     const uint8_t* p = asn1_key_desc;
735     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> record(
736         d2i_KM_KEY_DESCRIPTION(nullptr, &p, asn1_key_desc_len));
737     if (!record.get())
738         return TranslateLastOpenSslError();
739 
740     *attestation_version = ASN1_INTEGER_get(record->attestation_version);
741     *attestation_security_level = static_cast<keymaster_security_level_t>(
742         ASN1_ENUMERATED_get(record->attestation_security_level));
743     *keymaster_version = ASN1_INTEGER_get(record->keymaster_version);
744     *keymaster_security_level = static_cast<keymaster_security_level_t>(
745         ASN1_ENUMERATED_get(record->keymaster_security_level));
746 
747     attestation_challenge->data =
748         dup_buffer(record->attestation_challenge->data, record->attestation_challenge->length);
749     attestation_challenge->data_length = record->attestation_challenge->length;
750 
751     unique_id->data = dup_buffer(record->unique_id->data, record->unique_id->length);
752     unique_id->data_length = record->unique_id->length;
753 
754     keymaster_error_t error = extract_auth_list(record->software_enforced, software_enforced);
755     if (error != KM_ERROR_OK)
756         return error;
757 
758     return extract_auth_list(record->tee_enforced, tee_enforced);
759 }
760 
parse_root_of_trust(const uint8_t * asn1_key_desc,size_t asn1_key_desc_len,keymaster_blob_t * verified_boot_key,keymaster_verified_boot_t * verified_boot_state,bool * device_locked)761 keymaster_error_t parse_root_of_trust(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
762                                       keymaster_blob_t* verified_boot_key,
763                                       keymaster_verified_boot_t* verified_boot_state,
764                                       bool* device_locked) {
765     const uint8_t* p = asn1_key_desc;
766     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> record(
767         d2i_KM_KEY_DESCRIPTION(nullptr, &p, asn1_key_desc_len));
768     if (!record.get()) {
769         return TranslateLastOpenSslError();
770     }
771     if (!record->tee_enforced) {
772         return KM_ERROR_INVALID_ARGUMENT;
773     }
774     if (!record->tee_enforced->root_of_trust) {
775         return KM_ERROR_INVALID_ARGUMENT;
776     }
777     if (!record->tee_enforced->root_of_trust->verified_boot_key) {
778         return KM_ERROR_INVALID_ARGUMENT;
779     }
780     KM_ROOT_OF_TRUST* root_of_trust = record->tee_enforced->root_of_trust;
781     verified_boot_key->data = dup_buffer(root_of_trust->verified_boot_key->data,
782                                          root_of_trust->verified_boot_key->length);
783     verified_boot_key->data_length = root_of_trust->verified_boot_key->length;
784     *verified_boot_state = static_cast<keymaster_verified_boot_t>(
785         ASN1_ENUMERATED_get(root_of_trust->verified_boot_state));
786     *device_locked = root_of_trust->device_locked;
787     return KM_ERROR_OK;
788 }
789 
790 }  // namespace keymaster
791