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