xref: /aosp_15_r20/system/keymaster/km_openssl/attestation_record.cpp (revision 789431f29546679ab5188a97751fb38e3018d44d)
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/km_openssl/attestation_record.h>
18 
19 #include <assert.h>
20 #include <math.h>
21 
22 #include <unordered_map>
23 
24 #include <cppbor_parse.h>
25 #include <openssl/asn1t.h>
26 
27 #include <keymaster/android_keymaster_utils.h>
28 #include <keymaster/attestation_context.h>
29 #include <keymaster/km_openssl/hmac.h>
30 #include <keymaster/km_openssl/openssl_err.h>
31 #include <keymaster/km_openssl/openssl_utils.h>
32 
33 #define ASSERT_OR_RETURN_ERROR(stmt, error)                                                        \
34     do {                                                                                           \
35         assert(stmt);                                                                              \
36         if (!(stmt)) {                                                                             \
37             return error;                                                                          \
38         }                                                                                          \
39     } while (0)
40 
41 namespace keymaster {
42 
43 constexpr size_t kMaximumAttestationChallengeLength = 128;
44 
45 IMPLEMENT_ASN1_FUNCTIONS(KM_ROOT_OF_TRUST);
46 IMPLEMENT_ASN1_FUNCTIONS(KM_AUTH_LIST);
47 IMPLEMENT_ASN1_FUNCTIONS(KM_KEY_DESCRIPTION);
48 
49 static const keymaster_tag_t kDeviceAttestationTags[] = {
50     KM_TAG_ATTESTATION_ID_BRAND,        KM_TAG_ATTESTATION_ID_DEVICE,
51     KM_TAG_ATTESTATION_ID_PRODUCT,      KM_TAG_ATTESTATION_ID_SERIAL,
52     KM_TAG_ATTESTATION_ID_IMEI,         KM_TAG_ATTESTATION_ID_MEID,
53     KM_TAG_ATTESTATION_ID_MANUFACTURER, KM_TAG_ATTESTATION_ID_MODEL,
54     KM_TAG_ATTESTATION_ID_SECOND_IMEI};
55 
56 struct KM_AUTH_LIST_Delete {
operator ()keymaster::KM_AUTH_LIST_Delete57     void operator()(KM_AUTH_LIST* p) { KM_AUTH_LIST_free(p); }
58 };
59 
60 struct KM_KEY_DESCRIPTION_Delete {
operator ()keymaster::KM_KEY_DESCRIPTION_Delete61     void operator()(KM_KEY_DESCRIPTION* p) { KM_KEY_DESCRIPTION_free(p); }
62 };
63 
64 struct KM_ROOT_OF_TRUST_Delete {
operator ()keymaster::KM_ROOT_OF_TRUST_Delete65     void operator()(KM_ROOT_OF_TRUST* p) { KM_ROOT_OF_TRUST_free(p); }
66 };
67 
blob_to_bstr(const keymaster_blob_t & blob)68 static cppbor::Bstr blob_to_bstr(const keymaster_blob_t& blob) {
69     return cppbor::Bstr(std::pair(blob.data, blob.data_length));
70 }
71 
bstr_to_blob(const cppbor::Bstr * bstr,keymaster_blob_t * blob)72 static keymaster_error_t bstr_to_blob(const cppbor::Bstr* bstr, keymaster_blob_t* blob) {
73     ASSERT_OR_RETURN_ERROR(bstr, KM_ERROR_INVALID_TAG);
74     const std::vector<uint8_t>& vec = bstr->value();
75     uint8_t* data = (uint8_t*)calloc(vec.size(), sizeof(uint8_t));
76     if (data == nullptr) {
77         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
78     }
79 
80     std::copy(vec.begin(), vec.end(), data);
81     blob->data = data;
82     blob->data_length = vec.size();
83 
84     return KM_ERROR_OK;
85 }
86 
get_uint32_value(const keymaster_key_param_t & param)87 static uint32_t get_uint32_value(const keymaster_key_param_t& param) {
88     switch (keymaster_tag_get_type(param.tag)) {
89     case KM_ENUM:
90     case KM_ENUM_REP:
91         return param.enumerated;
92     case KM_UINT:
93     case KM_UINT_REP:
94         return param.integer;
95     default:
96         ASSERT_OR_RETURN_ERROR(false, 0xFFFFFFFF);
97     }
98 }
99 
get_uint32_value(EatSecurityLevel level)100 static int64_t get_uint32_value(EatSecurityLevel level) {
101     return static_cast<int64_t>(level);
102 }
103 
104 // 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)105 static keymaster_error_t insert_integer(ASN1_INTEGER* value, ASN1_INTEGER** dest_integer,
106                                         ASN1_INTEGER_SET** dest_integer_set) {
107     ASSERT_OR_RETURN_ERROR((dest_integer == nullptr) ^ (dest_integer_set == nullptr),
108                            KM_ERROR_UNEXPECTED_NULL_POINTER);
109     ASSERT_OR_RETURN_ERROR(value, KM_ERROR_INVALID_ARGUMENT);
110 
111     if (dest_integer_set) {
112         if (!*dest_integer_set) {
113             *dest_integer_set = sk_ASN1_INTEGER_new_null();
114         }
115         if (!*dest_integer_set) {
116             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
117         }
118         if (!sk_ASN1_INTEGER_push(*dest_integer_set, value)) {
119             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
120         }
121         return KM_ERROR_OK;
122 
123     } else if (dest_integer) {
124         if (*dest_integer) {
125             ASN1_INTEGER_free(*dest_integer);
126         }
127         *dest_integer = value;
128         return KM_ERROR_OK;
129     }
130 
131     ASSERT_OR_RETURN_ERROR(false, KM_ERROR_UNKNOWN_ERROR);  // Should never get here.
132 }
133 
134 // Add a repeating enum to a map going mapping its key to list of values.
add_repeating_enum(EatClaim key,uint32_t value,std::unordered_map<EatClaim,cppbor::Array> * fields_map)135 static void add_repeating_enum(EatClaim key, uint32_t value,
136                                std::unordered_map<EatClaim, cppbor::Array>* fields_map) {
137     auto field = fields_map->find(key);
138     if (field != fields_map->end()) {
139         field->second.add(value);
140     } else {
141         fields_map->insert({key, cppbor::Array().add(value)});
142     }
143 }
144 
145 static keymaster_error_t
insert_unknown_tag(const keymaster_key_param_t & param,cppbor::Map * dest_map,std::unordered_map<EatClaim,cppbor::Array> * fields_map)146 insert_unknown_tag(const keymaster_key_param_t& param, cppbor::Map* dest_map,
147                    std::unordered_map<EatClaim, cppbor::Array>* fields_map) {
148     EatClaim private_eat_tag = static_cast<EatClaim>(convert_to_eat_claim(param.tag));
149     switch (keymaster_tag_get_type(param.tag)) {
150     case KM_ENUM:
151         dest_map->add(private_eat_tag, param.enumerated);
152         break;
153     case KM_ENUM_REP:
154         add_repeating_enum(private_eat_tag, param.enumerated, fields_map);
155         break;
156     case KM_UINT:
157         dest_map->add(private_eat_tag, param.integer);
158         break;
159     case KM_UINT_REP:
160         add_repeating_enum(private_eat_tag, param.integer, fields_map);
161         break;
162     case KM_ULONG:
163         dest_map->add(private_eat_tag, param.long_integer);
164         break;
165     case KM_ULONG_REP:
166         add_repeating_enum(private_eat_tag, param.long_integer, fields_map);
167         break;
168     case KM_DATE:
169         dest_map->add(private_eat_tag, param.date_time);
170         break;
171     case KM_BOOL:
172         dest_map->add(private_eat_tag, true);
173         break;
174     case KM_BIGNUM:
175     case KM_BYTES:
176         dest_map->add(private_eat_tag, blob_to_bstr(param.blob));
177         break;
178     default:
179         ASSERT_OR_RETURN_ERROR(false, KM_ERROR_INVALID_TAG);
180     }
181     return KM_ERROR_OK;
182 }
183 
184 /**
185  * Convert an IMEI encoded as a string of numbers into the UEID format defined in
186  * https://tools.ietf.org/html/draft-ietf-rats-eat.
187  * The resulting format is a bstr encoded as follows:
188  * - Type byte: 0x03
189  * - IMEI (without check digit), encoded as byte string of length 14 with each byte as the digit's
190  *   value. The IMEI value encoded SHALL NOT include Luhn checksum or SVN information.
191  */
imei_to_ueid(const keymaster_blob_t & imei_blob,cppbor::Bstr * out)192 keymaster_error_t imei_to_ueid(const keymaster_blob_t& imei_blob, cppbor::Bstr* out) {
193     ASSERT_OR_RETURN_ERROR(imei_blob.data_length == kImeiBlobLength, KM_ERROR_INVALID_TAG);
194 
195     uint8_t ueid[kUeidLength];
196     ueid[0] = kImeiTypeByte;
197     // imei_blob corresponds to android.telephony.TelephonyManager#getDeviceId(), which is the
198     // 15-digit IMEI (including the check digit), encoded as a string.
199     for (size_t i = 1; i < kUeidLength; i++) {
200         // Convert each character to its numeric value.
201         ueid[i] = imei_blob.data[i - 1] - '0';  // Intentionally skip check digit at last position.
202     }
203 
204     *out = cppbor::Bstr(std::pair(ueid, sizeof(ueid)));
205     return KM_ERROR_OK;
206 }
207 
ueid_to_imei_blob(const cppbor::Bstr * ueid,keymaster_blob_t * out)208 keymaster_error_t ueid_to_imei_blob(const cppbor::Bstr* ueid, keymaster_blob_t* out) {
209     ASSERT_OR_RETURN_ERROR(ueid, KM_ERROR_INVALID_TAG);
210     const std::vector<uint8_t>& ueid_vec = ueid->value();
211     ASSERT_OR_RETURN_ERROR(ueid_vec.size() == kUeidLength, KM_ERROR_INVALID_TAG);
212     ASSERT_OR_RETURN_ERROR(ueid_vec[0] == kImeiTypeByte, KM_ERROR_INVALID_TAG);
213 
214     uint8_t* imei_string = (uint8_t*)calloc(kImeiBlobLength, sizeof(uint8_t));
215     // Fill string from left to right, and calculate Luhn check digit.
216     int luhn_digit_sum = 0;
217     for (size_t i = 0; i < kImeiBlobLength - 1; i++) {
218         uint8_t digit_i = ueid_vec[i + 1];
219         // Convert digit to its string value.
220         imei_string[i] = '0' + digit_i;
221         luhn_digit_sum += i % 2 == 0 ? digit_i : digit_i * 2 / 10 + (digit_i * 2) % 10;
222     }
223     imei_string[kImeiBlobLength - 1] = '0' + (10 - luhn_digit_sum % 10) % 10;
224 
225     *out = {.data = imei_string, .data_length = kImeiBlobLength};
226     return KM_ERROR_OK;
227 }
228 
ec_key_size_to_eat_curve(uint32_t key_size_bits,int * curve)229 keymaster_error_t ec_key_size_to_eat_curve(uint32_t key_size_bits, int* curve) {
230     switch (key_size_bits) {
231     default:
232         return KM_ERROR_UNSUPPORTED_KEY_SIZE;
233 
234     case 224:
235         *curve = (int)EatEcCurve::P_224;
236         break;
237 
238     case 256:
239         *curve = (int)EatEcCurve::P_256;
240         break;
241 
242     case 384:
243         *curve = (int)EatEcCurve::P_384;
244         break;
245 
246     case 521:
247         *curve = (int)EatEcCurve::P_521;
248         break;
249     }
250 
251     return KM_ERROR_OK;
252 }
253 
is_valid_attestation_challenge(const keymaster_blob_t & attestation_challenge)254 bool is_valid_attestation_challenge(const keymaster_blob_t& attestation_challenge) {
255     // TODO(171864369): Limit apps targeting >= API 30 to attestations in the range of
256     // [0, 128] bytes.
257     return (attestation_challenge.data_length <= kMaximumAttestationChallengeLength);
258 }
259 
260 // Put the contents of the keymaster AuthorizationSet auth_list into the EAT record structure.
build_eat_submod(const AuthorizationSet & auth_list,const EatSecurityLevel security_level,cppbor::Map * submod)261 keymaster_error_t build_eat_submod(const AuthorizationSet& auth_list,
262                                    const EatSecurityLevel security_level, cppbor::Map* submod) {
263     ASSERT_OR_RETURN_ERROR(submod, KM_ERROR_UNEXPECTED_NULL_POINTER);
264 
265     if (auth_list.empty()) return KM_ERROR_OK;
266 
267     submod->add(EatClaim::SECURITY_LEVEL, get_uint32_value(security_level));
268 
269     // Keep repeating fields in a separate map for easy lookup.
270     // Add them to submod map in postprocessing.
271     std::unordered_map<EatClaim, cppbor::Array> repeating_fields =
272         std::unordered_map<EatClaim, cppbor::Array>();
273 
274     for (auto entry : auth_list) {
275 
276         switch (entry.tag) {
277 
278         default:
279             // Unknown tags should only be included if they're software-enforced.
280             if (security_level == EatSecurityLevel::UNRESTRICTED) {
281                 keymaster_error_t error = insert_unknown_tag(entry, submod, &repeating_fields);
282                 if (error != KM_ERROR_OK) {
283                     return error;
284                 }
285             }
286             break;
287 
288         /* Tags ignored because they should never exist */
289         case KM_TAG_INVALID:
290 
291         /* Tags ignored because they're not used. */
292         case KM_TAG_ALL_USERS:
293         case KM_TAG_EXPORTABLE:
294         case KM_TAG_ECIES_SINGLE_HASH_MODE:
295         case KM_TAG_KDF:
296 
297         /* Tags ignored because they're used only to provide information to operations */
298         case KM_TAG_ASSOCIATED_DATA:
299         case KM_TAG_NONCE:
300         case KM_TAG_AUTH_TOKEN:
301         case KM_TAG_MAC_LENGTH:
302         case KM_TAG_ATTESTATION_CHALLENGE:
303         case KM_TAG_RESET_SINCE_ID_ROTATION:
304 
305         /* Tags ignored because they have no meaning off-device */
306         case KM_TAG_USER_ID:
307         case KM_TAG_USER_SECURE_ID:
308         case KM_TAG_BLOB_USAGE_REQUIREMENTS:
309 
310         /* Tags ignored because they're not usable by app keys */
311         case KM_TAG_BOOTLOADER_ONLY:
312         case KM_TAG_INCLUDE_UNIQUE_ID:
313         case KM_TAG_MAX_USES_PER_BOOT:
314         case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
315         case KM_TAG_UNIQUE_ID:
316 
317         /* Tags ignored because they contain data that should not be exported */
318         case KM_TAG_APPLICATION_DATA:
319         case KM_TAG_APPLICATION_ID:
320         case KM_TAG_ROOT_OF_TRUST:
321             continue;
322 
323         /* Non-repeating enumerations */
324         case KM_TAG_ALGORITHM:
325             submod->add(EatClaim::ALGORITHM, get_uint32_value(entry));
326             break;
327         case KM_TAG_EC_CURVE:
328             submod->add(EatClaim::EC_CURVE, get_uint32_value(entry));
329             break;
330         case KM_TAG_USER_AUTH_TYPE:
331             submod->add(EatClaim::USER_AUTH_TYPE, get_uint32_value(entry));
332             break;
333         case KM_TAG_ORIGIN:
334             submod->add(EatClaim::ORIGIN, get_uint32_value(entry));
335             break;
336 
337         /* Repeating enumerations */
338         case KM_TAG_PURPOSE:
339             add_repeating_enum(EatClaim::PURPOSE, get_uint32_value(entry), &repeating_fields);
340             break;
341         case KM_TAG_PADDING:
342             add_repeating_enum(EatClaim::PADDING, get_uint32_value(entry), &repeating_fields);
343             break;
344         case KM_TAG_DIGEST:
345             add_repeating_enum(EatClaim::DIGEST, get_uint32_value(entry), &repeating_fields);
346             break;
347         case KM_TAG_BLOCK_MODE:
348             add_repeating_enum(EatClaim::BLOCK_MODE, get_uint32_value(entry), &repeating_fields);
349             break;
350 
351         /* Non-repeating unsigned integers */
352         case KM_TAG_KEY_SIZE:
353             submod->add(EatClaim::KEY_SIZE, get_uint32_value(entry));
354             break;
355         case KM_TAG_AUTH_TIMEOUT:
356             submod->add(EatClaim::AUTH_TIMEOUT, get_uint32_value(entry));
357             break;
358         case KM_TAG_OS_VERSION:
359             submod->add(EatClaim::OS_VERSION, get_uint32_value(entry));
360             break;
361         case KM_TAG_OS_PATCHLEVEL:
362             submod->add(EatClaim::OS_PATCHLEVEL, get_uint32_value(entry));
363             break;
364         case KM_TAG_VENDOR_PATCHLEVEL:
365             submod->add(EatClaim::VENDOR_PATCHLEVEL, get_uint32_value(entry));
366             break;
367         case KM_TAG_BOOT_PATCHLEVEL:
368             submod->add(EatClaim::BOOT_PATCHLEVEL, get_uint32_value(entry));
369             break;
370         case KM_TAG_MIN_MAC_LENGTH:
371             submod->add(EatClaim::MIN_MAC_LENGTH, get_uint32_value(entry));
372             break;
373 
374         /* Non-repeating long unsigned integers */
375         case KM_TAG_RSA_PUBLIC_EXPONENT:
376             submod->add(EatClaim::RSA_PUBLIC_EXPONENT, entry.long_integer);
377             break;
378 
379         /* Dates */
380         case KM_TAG_ACTIVE_DATETIME:
381             submod->add(EatClaim::ACTIVE_DATETIME, entry.date_time);
382             break;
383         case KM_TAG_ORIGINATION_EXPIRE_DATETIME:
384             submod->add(EatClaim::ORIGINATION_EXPIRE_DATETIME, entry.date_time);
385             break;
386         case KM_TAG_USAGE_EXPIRE_DATETIME:
387             submod->add(EatClaim::USAGE_EXPIRE_DATETIME, entry.date_time);
388             break;
389         case KM_TAG_CREATION_DATETIME:
390             submod->add(EatClaim::IAT, entry.date_time);
391             break;
392 
393         /* Booleans */
394         case KM_TAG_NO_AUTH_REQUIRED:
395             submod->add(EatClaim::NO_AUTH_REQUIRED, true);
396             break;
397         case KM_TAG_ALL_APPLICATIONS:
398             submod->add(EatClaim::ALL_APPLICATIONS, true);
399             break;
400         case KM_TAG_ROLLBACK_RESISTANT:
401             submod->add(EatClaim::ROLLBACK_RESISTANT, true);
402             break;
403         case KM_TAG_ALLOW_WHILE_ON_BODY:
404             submod->add(EatClaim::ALLOW_WHILE_ON_BODY, true);
405             break;
406         case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
407             submod->add(EatClaim::UNLOCKED_DEVICE_REQUIRED, true);
408             break;
409         case KM_TAG_CALLER_NONCE:
410             submod->add(EatClaim::CALLER_NONCE, true);
411             break;
412         case KM_TAG_TRUSTED_CONFIRMATION_REQUIRED:
413             submod->add(EatClaim::TRUSTED_CONFIRMATION_REQUIRED, true);
414             break;
415         case KM_TAG_EARLY_BOOT_ONLY:
416             submod->add(EatClaim::EARLY_BOOT_ONLY, true);
417             break;
418         case KM_TAG_DEVICE_UNIQUE_ATTESTATION:
419             submod->add(EatClaim::DEVICE_UNIQUE_ATTESTATION, true);
420             break;
421         case KM_TAG_IDENTITY_CREDENTIAL_KEY:
422             submod->add(EatClaim::IDENTITY_CREDENTIAL_KEY, true);
423             break;
424         case KM_TAG_TRUSTED_USER_PRESENCE_REQUIRED:
425             submod->add(EatClaim::TRUSTED_USER_PRESENCE_REQUIRED, true);
426             break;
427         case KM_TAG_STORAGE_KEY:
428             submod->add(EatClaim::STORAGE_KEY, true);
429             break;
430 
431         /* Byte arrays*/
432         case KM_TAG_ATTESTATION_APPLICATION_ID:
433             submod->add(EatClaim::ATTESTATION_APPLICATION_ID, blob_to_bstr(entry.blob));
434             break;
435         case KM_TAG_ATTESTATION_ID_BRAND:
436             submod->add(EatClaim::ATTESTATION_ID_BRAND, blob_to_bstr(entry.blob));
437             break;
438         case KM_TAG_ATTESTATION_ID_DEVICE:
439             submod->add(EatClaim::ATTESTATION_ID_DEVICE, blob_to_bstr(entry.blob));
440             break;
441         case KM_TAG_ATTESTATION_ID_PRODUCT:
442             submod->add(EatClaim::ATTESTATION_ID_PRODUCT, blob_to_bstr(entry.blob));
443             break;
444         case KM_TAG_ATTESTATION_ID_SERIAL:
445             submod->add(EatClaim::ATTESTATION_ID_SERIAL, blob_to_bstr(entry.blob));
446             break;
447         case KM_TAG_ATTESTATION_ID_IMEI: {
448             cppbor::Bstr ueid("");
449             keymaster_error_t error = imei_to_ueid(entry.blob, &ueid);
450             if (error != KM_ERROR_OK) return error;
451             submod->add(EatClaim::UEID, ueid);
452             break;
453         }
454         case KM_TAG_ATTESTATION_ID_MEID:
455             submod->add(EatClaim::ATTESTATION_ID_MEID, blob_to_bstr(entry.blob));
456             break;
457         case KM_TAG_ATTESTATION_ID_MANUFACTURER:
458             submod->add(EatClaim::ATTESTATION_ID_MANUFACTURER, blob_to_bstr(entry.blob));
459             break;
460         case KM_TAG_ATTESTATION_ID_MODEL:
461             submod->add(EatClaim::ATTESTATION_ID_MODEL, blob_to_bstr(entry.blob));
462             break;
463         case KM_TAG_CONFIRMATION_TOKEN:
464             submod->add(EatClaim::CONFIRMATION_TOKEN, blob_to_bstr(entry.blob));
465             break;
466         }
467     }
468 
469     // Move values from repeating enums into the submod map.
470     for (auto const& repeating_field : repeating_fields) {
471         EatClaim key = static_cast<EatClaim>(repeating_field.first);
472         submod->add(key, std::move(repeating_fields.at(key)));
473     }
474 
475     int ec_curve;
476     uint32_t key_size;
477     if (auth_list.Contains(TAG_ALGORITHM, KM_ALGORITHM_EC) && !auth_list.Contains(TAG_EC_CURVE) &&
478         auth_list.GetTagValue(TAG_KEY_SIZE, &key_size)) {
479         // This must be a keymaster1 key. It's an EC key with no curve.  Insert the curve.
480 
481         keymaster_error_t error = ec_key_size_to_eat_curve(key_size, &ec_curve);
482         if (error != KM_ERROR_OK) return error;
483 
484         submod->add(EatClaim::EC_CURVE, ec_curve);
485     }
486 
487     return KM_ERROR_OK;
488 }
489 
490 // Put the contents of the keymaster AuthorizationSet auth_list into the ASN.1 record structure,
491 // record.
build_auth_list(const AuthorizationSet & auth_list,KM_AUTH_LIST * record)492 keymaster_error_t build_auth_list(const AuthorizationSet& auth_list, KM_AUTH_LIST* record) {
493     ASSERT_OR_RETURN_ERROR(record, KM_ERROR_UNEXPECTED_NULL_POINTER);
494 
495     if (auth_list.empty()) return KM_ERROR_OK;
496 
497     for (auto entry : auth_list) {
498 
499         ASN1_INTEGER_SET** integer_set = nullptr;
500         ASN1_INTEGER** integer_ptr = nullptr;
501         ASN1_OCTET_STRING** string_ptr = nullptr;
502         ASN1_NULL** bool_ptr = nullptr;
503 
504         switch (entry.tag) {
505 
506         /* Tags ignored because they should never exist */
507         case KM_TAG_INVALID:
508 
509         /* Tags ignored because they're not used. */
510         case KM_TAG_ALL_USERS:
511         case KM_TAG_EXPORTABLE:
512         case KM_TAG_ECIES_SINGLE_HASH_MODE:
513 
514         /* Tags ignored because they're used only to provide information to operations */
515         case KM_TAG_ASSOCIATED_DATA:
516         case KM_TAG_NONCE:
517         case KM_TAG_AUTH_TOKEN:
518         case KM_TAG_MAC_LENGTH:
519         case KM_TAG_ATTESTATION_CHALLENGE:
520         case KM_TAG_KDF:
521 
522         /* Tags ignored because they're used only to provide for certificate generation */
523         case KM_TAG_CERTIFICATE_SERIAL:
524         case KM_TAG_CERTIFICATE_SUBJECT:
525         case KM_TAG_CERTIFICATE_NOT_BEFORE:
526         case KM_TAG_CERTIFICATE_NOT_AFTER:
527         case KM_TAG_INCLUDE_UNIQUE_ID:
528         case KM_TAG_RESET_SINCE_ID_ROTATION:
529 
530         /* Tags ignored because they have no meaning off-device */
531         case KM_TAG_USER_ID:
532         case KM_TAG_USER_SECURE_ID:
533         case KM_TAG_BLOB_USAGE_REQUIREMENTS:
534 
535         /* Tags ignored because they're not usable by app keys */
536         case KM_TAG_BOOTLOADER_ONLY:
537         case KM_TAG_MAX_BOOT_LEVEL:
538         case KM_TAG_MAX_USES_PER_BOOT:
539         case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
540         case KM_TAG_STORAGE_KEY:
541         case KM_TAG_UNIQUE_ID:
542 
543         /* Tags ignored because they contain data that should not be exported */
544         case KM_TAG_APPLICATION_DATA:
545         case KM_TAG_APPLICATION_ID:
546         case KM_TAG_CONFIRMATION_TOKEN:
547         case KM_TAG_ROOT_OF_TRUST:
548             continue;
549 
550         /* Non-repeating enumerations */
551         case KM_TAG_ALGORITHM:
552             integer_ptr = &record->algorithm;
553             break;
554         case KM_TAG_EC_CURVE:
555             integer_ptr = &record->ec_curve;
556             break;
557         case KM_TAG_USER_AUTH_TYPE:
558             integer_ptr = &record->user_auth_type;
559             break;
560         case KM_TAG_ORIGIN:
561             integer_ptr = &record->origin;
562             break;
563 
564         /* Repeating enumerations */
565         case KM_TAG_PURPOSE:
566             integer_set = &record->purpose;
567             break;
568         case KM_TAG_PADDING:
569             integer_set = &record->padding;
570             break;
571         case KM_TAG_DIGEST:
572             integer_set = &record->digest;
573             break;
574         case KM_TAG_BLOCK_MODE:
575             integer_set = &record->block_mode;
576             break;
577         case KM_TAG_RSA_OAEP_MGF_DIGEST:
578             integer_set = &record->mgf_digest;
579             break;
580 
581         /* Non-repeating unsigned integers */
582         case KM_TAG_KEY_SIZE:
583             integer_ptr = &record->key_size;
584             break;
585         case KM_TAG_AUTH_TIMEOUT:
586             integer_ptr = &record->auth_timeout;
587             break;
588         case KM_TAG_OS_VERSION:
589             integer_ptr = &record->os_version;
590             break;
591         case KM_TAG_OS_PATCHLEVEL:
592             integer_ptr = &record->os_patchlevel;
593             break;
594         case KM_TAG_MIN_MAC_LENGTH:
595             integer_ptr = &record->min_mac_length;
596             break;
597         case KM_TAG_BOOT_PATCHLEVEL:
598             integer_ptr = &record->boot_patch_level;
599             break;
600         case KM_TAG_VENDOR_PATCHLEVEL:
601             integer_ptr = &record->vendor_patchlevel;
602             break;
603         case KM_TAG_USAGE_COUNT_LIMIT:
604             integer_ptr = &record->usage_count_limit;
605             break;
606 
607         /* Non-repeating long unsigned integers */
608         case KM_TAG_RSA_PUBLIC_EXPONENT:
609             integer_ptr = &record->rsa_public_exponent;
610             break;
611 
612         /* Dates */
613         case KM_TAG_ACTIVE_DATETIME:
614             integer_ptr = &record->active_date_time;
615             break;
616         case KM_TAG_ORIGINATION_EXPIRE_DATETIME:
617             integer_ptr = &record->origination_expire_date_time;
618             break;
619         case KM_TAG_USAGE_EXPIRE_DATETIME:
620             integer_ptr = &record->usage_expire_date_time;
621             break;
622         case KM_TAG_CREATION_DATETIME:
623             integer_ptr = &record->creation_date_time;
624             break;
625 
626         /* Booleans */
627         case KM_TAG_NO_AUTH_REQUIRED:
628             bool_ptr = &record->no_auth_required;
629             break;
630         case KM_TAG_ALL_APPLICATIONS:
631             bool_ptr = &record->all_applications;
632             break;
633         case KM_TAG_ROLLBACK_RESISTANT:
634             bool_ptr = &record->rollback_resistant;
635             break;
636         case KM_TAG_ROLLBACK_RESISTANCE:
637             bool_ptr = &record->rollback_resistance;
638             break;
639         case KM_TAG_ALLOW_WHILE_ON_BODY:
640             bool_ptr = &record->allow_while_on_body;
641             break;
642         case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
643             bool_ptr = &record->unlocked_device_required;
644             break;
645         case KM_TAG_CALLER_NONCE:
646             bool_ptr = &record->caller_nonce;
647             break;
648         case KM_TAG_TRUSTED_CONFIRMATION_REQUIRED:
649             bool_ptr = &record->trusted_confirmation_required;
650             break;
651         case KM_TAG_EARLY_BOOT_ONLY:
652             bool_ptr = &record->early_boot_only;
653             break;
654         case KM_TAG_DEVICE_UNIQUE_ATTESTATION:
655             bool_ptr = &record->device_unique_attestation;
656             break;
657         case KM_TAG_IDENTITY_CREDENTIAL_KEY:
658             bool_ptr = &record->identity_credential_key;
659             break;
660         case KM_TAG_TRUSTED_USER_PRESENCE_REQUIRED:
661             bool_ptr = &record->trusted_user_presence_required;
662             break;
663 
664         /* Byte arrays*/
665         case KM_TAG_ATTESTATION_APPLICATION_ID:
666             string_ptr = &record->attestation_application_id;
667             break;
668         case KM_TAG_ATTESTATION_ID_BRAND:
669             string_ptr = &record->attestation_id_brand;
670             break;
671         case KM_TAG_ATTESTATION_ID_DEVICE:
672             string_ptr = &record->attestation_id_device;
673             break;
674         case KM_TAG_ATTESTATION_ID_PRODUCT:
675             string_ptr = &record->attestation_id_product;
676             break;
677         case KM_TAG_ATTESTATION_ID_SERIAL:
678             string_ptr = &record->attestation_id_serial;
679             break;
680         case KM_TAG_ATTESTATION_ID_IMEI:
681             string_ptr = &record->attestation_id_imei;
682             break;
683         case KM_TAG_ATTESTATION_ID_SECOND_IMEI:
684             string_ptr = &record->attestation_id_second_imei;
685             break;
686         case KM_TAG_ATTESTATION_ID_MEID:
687             string_ptr = &record->attestation_id_meid;
688             break;
689         case KM_TAG_ATTESTATION_ID_MANUFACTURER:
690             string_ptr = &record->attestation_id_manufacturer;
691             break;
692         case KM_TAG_ATTESTATION_ID_MODEL:
693             string_ptr = &record->attestation_id_model;
694             break;
695         case KM_TAG_MODULE_HASH:
696             string_ptr = &record->module_hash;
697             break;
698         }
699 
700         keymaster_tag_type_t type = keymaster_tag_get_type(entry.tag);
701         switch (type) {
702         case KM_ENUM:
703         case KM_ENUM_REP:
704         case KM_UINT:
705         case KM_UINT_REP: {
706             ASSERT_OR_RETURN_ERROR((keymaster_tag_repeatable(entry.tag) && integer_set) ||
707                                        (!keymaster_tag_repeatable(entry.tag) && integer_ptr),
708                                    KM_ERROR_INVALID_TAG);
709 
710             UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> value(ASN1_INTEGER_new());
711             if (!value.get()) {
712                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
713             }
714             if (!ASN1_INTEGER_set(value.get(), get_uint32_value(entry))) {
715                 return TranslateLastOpenSslError();
716             }
717 
718             insert_integer(value.release(), integer_ptr, integer_set);
719             break;
720         }
721 
722         case KM_ULONG:
723         case KM_ULONG_REP:
724         case KM_DATE: {
725             ASSERT_OR_RETURN_ERROR((keymaster_tag_repeatable(entry.tag) && integer_set) ||
726                                        (!keymaster_tag_repeatable(entry.tag) && integer_ptr),
727                                    KM_ERROR_INVALID_TAG);
728 
729             UniquePtr<BIGNUM, BIGNUM_Delete> bn_value(BN_new());
730             if (!bn_value.get()) {
731                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
732             }
733 
734             if (type == KM_DATE) {
735                 if (!BN_set_u64(bn_value.get(), entry.date_time)) {
736                     return TranslateLastOpenSslError();
737                 }
738             } else {
739                 if (!BN_set_u64(bn_value.get(), entry.long_integer)) {
740                     return TranslateLastOpenSslError();
741                 }
742             }
743 
744             UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> value(
745                 BN_to_ASN1_INTEGER(bn_value.get(), nullptr));
746             if (!value.get()) {
747                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
748             }
749 
750             insert_integer(value.release(), integer_ptr, integer_set);
751             break;
752         }
753 
754         case KM_BOOL:
755             ASSERT_OR_RETURN_ERROR(bool_ptr, KM_ERROR_INVALID_TAG);
756             if (!*bool_ptr) *bool_ptr = ASN1_NULL_new();
757             if (!*bool_ptr) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
758             break;
759 
760         /* Byte arrays*/
761         case KM_BYTES:
762             ASSERT_OR_RETURN_ERROR(string_ptr, KM_ERROR_INVALID_TAG);
763             if (!*string_ptr) {
764                 *string_ptr = ASN1_OCTET_STRING_new();
765             }
766             if (!*string_ptr) {
767                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
768             }
769             if (!ASN1_OCTET_STRING_set(*string_ptr, entry.blob.data, entry.blob.data_length)) {
770                 return TranslateLastOpenSslError();
771             }
772             break;
773 
774         default:
775             return KM_ERROR_UNIMPLEMENTED;
776         }
777     }
778 
779     keymaster_ec_curve_t ec_curve;
780     uint32_t key_size;
781     if (auth_list.Contains(TAG_ALGORITHM, KM_ALGORITHM_EC) &&  //
782         !auth_list.Contains(TAG_EC_CURVE) &&                   //
783         auth_list.GetTagValue(TAG_KEY_SIZE, &key_size)) {
784         // This must be a keymaster1 key. It's an EC key with no curve.  Insert the curve if we
785         // can unambiguously figure it out.
786 
787         keymaster_error_t error = EcKeySizeToCurve(key_size, &ec_curve);
788         if (error != KM_ERROR_OK) return error;
789 
790         UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> value(ASN1_INTEGER_new());
791         if (!value.get()) {
792             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
793         }
794 
795         if (!ASN1_INTEGER_set(value.get(), ec_curve)) {
796             return TranslateLastOpenSslError();
797         }
798 
799         insert_integer(value.release(), &record->ec_curve, nullptr);
800     }
801 
802     return KM_ERROR_OK;
803 }
804 
805 // Construct a CBOR-encoded attestation record containing the values from sw_enforced
806 // and tee_enforced.
build_eat_record(const AuthorizationSet & attestation_params,AuthorizationSet sw_enforced,AuthorizationSet tee_enforced,const AttestationContext & context,std::vector<uint8_t> * eat_token)807 keymaster_error_t build_eat_record(const AuthorizationSet& attestation_params,
808                                    AuthorizationSet sw_enforced, AuthorizationSet tee_enforced,
809                                    const AttestationContext& context,
810                                    std::vector<uint8_t>* eat_token) {
811     ASSERT_OR_RETURN_ERROR(eat_token, KM_ERROR_UNEXPECTED_NULL_POINTER);
812 
813     cppbor::Map eat_record;
814     switch (context.GetSecurityLevel()) {
815     case KM_SECURITY_LEVEL_SOFTWARE:
816         eat_record.add(EatClaim::SECURITY_LEVEL, get_uint32_value(EatSecurityLevel::UNRESTRICTED));
817         break;
818     case KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT:
819         eat_record.add(EatClaim::SECURITY_LEVEL,
820                        get_uint32_value(EatSecurityLevel::SECURE_RESTRICTED));
821         break;
822     case KM_SECURITY_LEVEL_STRONGBOX:
823         eat_record.add(EatClaim::SECURITY_LEVEL, get_uint32_value(EatSecurityLevel::HARDWARE));
824         break;
825     default:
826         return KM_ERROR_UNKNOWN_ERROR;
827     }
828 
829     keymaster_error_t error;
830     const AttestationContext::VerifiedBootParams* vb_params = context.GetVerifiedBootParams(&error);
831     if (error != KM_ERROR_OK) return error;
832 
833     if (vb_params->verified_boot_key.data_length) {
834         eat_record.add(EatClaim::VERIFIED_BOOT_KEY, blob_to_bstr(vb_params->verified_boot_key));
835     }
836     if (vb_params->verified_boot_hash.data_length) {
837         eat_record.add(EatClaim::VERIFIED_BOOT_HASH, blob_to_bstr(vb_params->verified_boot_hash));
838     }
839     if (vb_params->device_locked) {
840         eat_record.add(EatClaim::DEVICE_LOCKED, vb_params->device_locked);
841     }
842 
843     bool verified_or_self_signed = (vb_params->verified_boot_state == KM_VERIFIED_BOOT_VERIFIED ||
844                                     vb_params->verified_boot_state == KM_VERIFIED_BOOT_SELF_SIGNED);
845     auto eat_boot_state = cppbor::Array()
846                               .add(verified_or_self_signed)  // secure-boot-enabled
847                               .add(verified_or_self_signed)  // debug-disabled
848                               .add(verified_or_self_signed)  // debug-disabled-since-boot
849                               .add(verified_or_self_signed)  // debug-permanent-disable
850                               .add(false);  // debug-full-permanent-disable (no way to verify)
851     eat_record.add(EatClaim::BOOT_STATE, std::move(eat_boot_state));
852     eat_record.add(EatClaim::OFFICIAL_BUILD,
853                    vb_params->verified_boot_state == KM_VERIFIED_BOOT_VERIFIED);
854 
855     eat_record.add(EatClaim::ATTESTATION_VERSION,
856                    version_to_attestation_version(context.GetKmVersion()));
857     eat_record.add(EatClaim::KEYMASTER_VERSION,
858                    version_to_attestation_km_version(context.GetKmVersion()));
859 
860     keymaster_blob_t attestation_challenge = {nullptr, 0};
861     if (!attestation_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge)) {
862         return KM_ERROR_ATTESTATION_CHALLENGE_MISSING;
863     }
864 
865     if (!is_valid_attestation_challenge(attestation_challenge)) {
866         return KM_ERROR_INVALID_INPUT_LENGTH;
867     }
868 
869     eat_record.add(EatClaim::NONCE, blob_to_bstr(attestation_challenge));
870 
871     keymaster_blob_t attestation_app_id;
872     if (!attestation_params.GetTagValue(TAG_ATTESTATION_APPLICATION_ID, &attestation_app_id)) {
873         return KM_ERROR_ATTESTATION_APPLICATION_ID_MISSING;
874     }
875     // TODO: what should happen when sw_enforced already contains TAG_ATTESTATION_APPLICATION_ID?
876     // (as is the case in android_keymaster_test.cpp). For now, we will ignore the provided one in
877     // attestation_params if that's the case.
878     keymaster_blob_t existing_app_id;
879     if (!sw_enforced.GetTagValue(TAG_ATTESTATION_APPLICATION_ID, &existing_app_id)) {
880         sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_app_id);
881     }
882 
883     error = context.VerifyAndCopyDeviceIds(
884         attestation_params,
885         context.GetSecurityLevel() == KM_SECURITY_LEVEL_SOFTWARE ? &sw_enforced : &tee_enforced);
886     if (error == KM_ERROR_UNIMPLEMENTED) {
887         // The KeymasterContext implementation does not support device ID attestation. Bail out if
888         // device ID attestation is being attempted.
889         for (const auto& tag : kDeviceAttestationTags) {
890             if (attestation_params.find(tag) != -1) {
891                 return KM_ERROR_CANNOT_ATTEST_IDS;
892             }
893         }
894     } else if (error != KM_ERROR_OK) {
895         return error;
896     }
897 
898     if (attestation_params.Contains(TAG_DEVICE_UNIQUE_ATTESTATION) &&
899         context.GetSecurityLevel() == KM_SECURITY_LEVEL_STRONGBOX) {
900         eat_record.add(EatClaim::DEVICE_UNIQUE_ATTESTATION, true);
901     }
902 
903     cppbor::Map software_submod;
904     error = build_eat_submod(sw_enforced, EatSecurityLevel::UNRESTRICTED, &software_submod);
905     if (error != KM_ERROR_OK) return error;
906 
907     cppbor::Map tee_submod;
908     error = build_eat_submod(tee_enforced, EatSecurityLevel::SECURE_RESTRICTED, &tee_submod);
909     if (error != KM_ERROR_OK) return error;
910 
911     if (software_submod.size() + tee_submod.size() > 0) {
912         cppbor::Map submods;
913         if (software_submod.size() > 0) {
914             submods.add(kEatSubmodNameSoftware, std::move(software_submod));
915         }
916         if (tee_submod.size() > 0) {
917             submods.add(kEatSubmodNameTee, std::move(tee_submod));
918         }
919 
920         eat_record.add(EatClaim::SUBMODS, std::move(submods));
921     }
922 
923     if (attestation_params.GetTagValue(TAG_INCLUDE_UNIQUE_ID)) {
924         uint64_t creation_datetime;
925         // Only check sw_enforced for TAG_CREATION_DATETIME, since it shouldn't be in tee_enforced,
926         // since this implementation has no secure wall clock.
927         if (!sw_enforced.GetTagValue(TAG_CREATION_DATETIME, &creation_datetime)) {
928             LOG_E("Unique ID cannot be created without creation datetime");
929             return KM_ERROR_INVALID_KEY_BLOB;
930         }
931 
932         Buffer unique_id = context.GenerateUniqueId(
933             creation_datetime, attestation_app_id,
934             attestation_params.GetTagValue(TAG_RESET_SINCE_ID_ROTATION), &error);
935         if (error != KM_ERROR_OK) return error;
936 
937         eat_record.add(EatClaim::CTI,
938                        cppbor::Bstr(std::pair(unique_id.begin(), unique_id.available_read())));
939     }
940 
941     *eat_token = eat_record.encode();
942 
943     return KM_ERROR_OK;
944 }
945 
build_unique_id_input(uint64_t creation_date_time,const keymaster_blob_t & application_id,bool reset_since_rotation,Buffer * input_data)946 keymaster_error_t build_unique_id_input(uint64_t creation_date_time,
947                                         const keymaster_blob_t& application_id,
948                                         bool reset_since_rotation, Buffer* input_data) {
949     if (input_data == nullptr) {
950         return KM_ERROR_UNEXPECTED_NULL_POINTER;
951     }
952     uint64_t rounded_date = creation_date_time / 2592000000LLU;
953     uint8_t* serialized_date = reinterpret_cast<uint8_t*>(&rounded_date);
954     uint8_t reset_byte = (reset_since_rotation ? 1 : 0);
955 
956     if (!input_data->Reinitialize(sizeof(rounded_date) + application_id.data_length + 1) ||
957         !input_data->write(serialized_date, sizeof(rounded_date)) ||
958         !input_data->write(application_id.data, application_id.data_length) ||
959         !input_data->write(&reset_byte, 1)) {
960         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
961     }
962     return KM_ERROR_OK;
963 }
964 
generate_unique_id(const std::vector<uint8_t> & hbk,uint64_t creation_date_time,const keymaster_blob_t & application_id,bool reset_since_rotation,Buffer * unique_id)965 keymaster_error_t generate_unique_id(const std::vector<uint8_t>& hbk, uint64_t creation_date_time,
966                                      const keymaster_blob_t& application_id,
967                                      bool reset_since_rotation, Buffer* unique_id) {
968     if (unique_id == nullptr) {
969         return KM_ERROR_UNEXPECTED_NULL_POINTER;
970     }
971     HmacSha256 hmac;
972     hmac.Init(hbk.data(), hbk.size());
973 
974     Buffer input;
975     keymaster_error_t error =
976         build_unique_id_input(creation_date_time, application_id, reset_since_rotation, &input);
977     if (error != KM_ERROR_OK) {
978         return error;
979     }
980     if (!unique_id->Reinitialize(UNIQUE_ID_SIZE)) {
981         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
982     }
983     hmac.Sign(input.peek_read(), input.available_read(), unique_id->peek_write(),
984               unique_id->available_write());
985     unique_id->advance_write(UNIQUE_ID_SIZE);
986     return KM_ERROR_OK;
987 }
988 
989 // Construct an ASN1.1 DER-encoded attestation record containing the values from sw_enforced and
990 // tee_enforced.
build_attestation_record(const AuthorizationSet & attestation_params,AuthorizationSet sw_enforced,AuthorizationSet tee_enforced,const AttestationContext & context,UniquePtr<uint8_t[]> * asn1_key_desc,size_t * asn1_key_desc_len)991 keymaster_error_t build_attestation_record(const AuthorizationSet& attestation_params,  //
992                                            AuthorizationSet sw_enforced,
993                                            AuthorizationSet tee_enforced,
994                                            const AttestationContext& context,
995                                            UniquePtr<uint8_t[]>* asn1_key_desc,
996                                            size_t* asn1_key_desc_len) {
997     ASSERT_OR_RETURN_ERROR(asn1_key_desc && asn1_key_desc_len, KM_ERROR_UNEXPECTED_NULL_POINTER);
998 
999     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> key_desc(KM_KEY_DESCRIPTION_new());
1000     if (!key_desc.get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1001 
1002     KM_ROOT_OF_TRUST* root_of_trust = nullptr;
1003     if (context.GetSecurityLevel() == KM_SECURITY_LEVEL_SOFTWARE) {
1004         key_desc->software_enforced->root_of_trust = KM_ROOT_OF_TRUST_new();
1005         root_of_trust = key_desc->software_enforced->root_of_trust;
1006     } else {
1007         key_desc->tee_enforced->root_of_trust = KM_ROOT_OF_TRUST_new();
1008         root_of_trust = key_desc->tee_enforced->root_of_trust;
1009     }
1010 
1011     keymaster_error_t error;
1012     auto vb_params = context.GetVerifiedBootParams(&error);
1013     if (error != KM_ERROR_OK) return error;
1014     if (vb_params->verified_boot_key.data_length &&
1015         !ASN1_OCTET_STRING_set(root_of_trust->verified_boot_key, vb_params->verified_boot_key.data,
1016                                vb_params->verified_boot_key.data_length)) {
1017         return TranslateLastOpenSslError();
1018     }
1019     if (vb_params->verified_boot_hash.data_length &&
1020         !ASN1_OCTET_STRING_set(root_of_trust->verified_boot_hash,
1021                                vb_params->verified_boot_hash.data,
1022                                vb_params->verified_boot_hash.data_length)) {
1023         return TranslateLastOpenSslError();
1024     }
1025 
1026     root_of_trust->device_locked = vb_params->device_locked ? 0xFF : 0x00;
1027     if (!ASN1_ENUMERATED_set(root_of_trust->verified_boot_state, vb_params->verified_boot_state)) {
1028         return TranslateLastOpenSslError();
1029     }
1030 
1031     if (!ASN1_INTEGER_set(key_desc->attestation_version,
1032                           version_to_attestation_version(context.GetKmVersion())) ||
1033         !ASN1_ENUMERATED_set(key_desc->attestation_security_level, context.GetSecurityLevel()) ||
1034         !ASN1_INTEGER_set(key_desc->keymaster_version,
1035                           version_to_attestation_km_version(context.GetKmVersion())) ||
1036         !ASN1_ENUMERATED_set(key_desc->keymaster_security_level, context.GetSecurityLevel())) {
1037         return TranslateLastOpenSslError();
1038     }
1039 
1040     keymaster_blob_t attestation_challenge = {nullptr, 0};
1041     if (!attestation_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge)) {
1042         return KM_ERROR_ATTESTATION_CHALLENGE_MISSING;
1043     }
1044 
1045     if (!is_valid_attestation_challenge(attestation_challenge)) {
1046         return KM_ERROR_INVALID_INPUT_LENGTH;
1047     }
1048 
1049     if (!ASN1_OCTET_STRING_set(key_desc->attestation_challenge, attestation_challenge.data,
1050                                attestation_challenge.data_length)) {
1051         return TranslateLastOpenSslError();
1052     }
1053 
1054     keymaster_blob_t attestation_app_id;
1055     if (!attestation_params.GetTagValue(TAG_ATTESTATION_APPLICATION_ID, &attestation_app_id)) {
1056         return KM_ERROR_ATTESTATION_APPLICATION_ID_MISSING;
1057     }
1058     sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_app_id);
1059 
1060     error = context.VerifyAndCopyDeviceIds(
1061         attestation_params,
1062         context.GetSecurityLevel() == KM_SECURITY_LEVEL_SOFTWARE ? &sw_enforced : &tee_enforced);
1063     if (error == KM_ERROR_UNIMPLEMENTED) {
1064         // The KeymasterContext implementation does not support device ID attestation. Bail out if
1065         // device ID attestation is being attempted.
1066         for (const auto& tag : kDeviceAttestationTags) {
1067             if (attestation_params.find(tag) != -1) {
1068                 return KM_ERROR_CANNOT_ATTEST_IDS;
1069             }
1070         }
1071     } else if (error != KM_ERROR_OK) {
1072         return error;
1073     }
1074 
1075     if (attestation_params.Contains(TAG_DEVICE_UNIQUE_ATTESTATION) &&
1076         context.GetSecurityLevel() == KM_SECURITY_LEVEL_STRONGBOX) {
1077         tee_enforced.push_back(TAG_DEVICE_UNIQUE_ATTESTATION);
1078     };
1079 
1080     error = build_auth_list(sw_enforced, key_desc->software_enforced);
1081     if (error != KM_ERROR_OK) return error;
1082 
1083     error = build_auth_list(tee_enforced, key_desc->tee_enforced);
1084     if (error != KM_ERROR_OK) return error;
1085 
1086     if (attestation_params.GetTagValue(TAG_INCLUDE_UNIQUE_ID)) {
1087         uint64_t creation_datetime;
1088         // Only check sw_enforced for TAG_CREATION_DATETIME, since it shouldn't be in tee_enforced,
1089         // since this implementation has no secure wall clock.
1090         if (!sw_enforced.GetTagValue(TAG_CREATION_DATETIME, &creation_datetime)) {
1091             LOG_E("Unique ID cannot be created without creation datetime");
1092             return KM_ERROR_INVALID_KEY_BLOB;
1093         }
1094 
1095         Buffer unique_id = context.GenerateUniqueId(
1096             creation_datetime, attestation_app_id,
1097             attestation_params.GetTagValue(TAG_RESET_SINCE_ID_ROTATION), &error);
1098         if (error != KM_ERROR_OK) return error;
1099 
1100         if (!ASN1_OCTET_STRING_set(key_desc->unique_id, unique_id.peek_read(),
1101                                    unique_id.available_read()))
1102             return TranslateLastOpenSslError();
1103     }
1104 
1105     int len = i2d_KM_KEY_DESCRIPTION(key_desc.get(), nullptr);
1106     if (len < 0) return TranslateLastOpenSslError();
1107     *asn1_key_desc_len = len;
1108     asn1_key_desc->reset(new (std::nothrow) uint8_t[*asn1_key_desc_len]);
1109     if (!asn1_key_desc->get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1110     uint8_t* p = asn1_key_desc->get();
1111     len = i2d_KM_KEY_DESCRIPTION(key_desc.get(), &p);
1112     if (len < 0) return TranslateLastOpenSslError();
1113 
1114     return KM_ERROR_OK;
1115 }
1116 
1117 // 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)1118 static bool get_repeated_enums(const ASN1_INTEGER_SET* stack, keymaster_tag_t tag,
1119                                AuthorizationSet* auth_list) {
1120     ASSERT_OR_RETURN_ERROR(keymaster_tag_get_type(tag) == KM_ENUM_REP, KM_ERROR_INVALID_TAG);
1121     for (size_t i = 0; i < sk_ASN1_INTEGER_num(stack); ++i) {
1122         if (!auth_list->push_back(
1123                 keymaster_param_enum(tag, ASN1_INTEGER_get(sk_ASN1_INTEGER_value(stack, i)))))
1124             return false;
1125     }
1126     return true;
1127 }
1128 
1129 // Add the specified integer tag/value pair to auth_list.
1130 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)1131 static bool get_enum(const ASN1_INTEGER* asn1_int, TypedEnumTag<Type, Tag, KeymasterEnum> tag,
1132                      AuthorizationSet* auth_list) {
1133     if (!asn1_int) return true;
1134     return auth_list->push_back(tag, static_cast<KeymasterEnum>(ASN1_INTEGER_get(asn1_int)));
1135 }
1136 
1137 // Add the specified ulong tag/value pair to auth_list.
get_ulong(const ASN1_INTEGER * asn1_int,keymaster_tag_t tag,AuthorizationSet * auth_list)1138 static bool get_ulong(const ASN1_INTEGER* asn1_int, keymaster_tag_t tag,
1139                       AuthorizationSet* auth_list) {
1140     if (!asn1_int) return true;
1141     UniquePtr<BIGNUM, BIGNUM_Delete> bn(ASN1_INTEGER_to_BN(asn1_int, nullptr));
1142     if (!bn.get()) return false;
1143     uint64_t ulong = 0;
1144     BN_get_u64(bn.get(), &ulong);
1145     return auth_list->push_back(keymaster_param_long(tag, ulong));
1146 }
1147 
1148 // 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)1149 keymaster_error_t extract_auth_list(const KM_AUTH_LIST* record, AuthorizationSet* auth_list) {
1150     if (!record) return KM_ERROR_OK;
1151 
1152     // Purpose
1153     if (!get_repeated_enums(record->purpose, TAG_PURPOSE, auth_list)) {
1154         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1155     }
1156 
1157     // Algorithm
1158     if (!get_enum(record->algorithm, TAG_ALGORITHM, auth_list)) {
1159         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1160     }
1161 
1162     // Key size
1163     if (record->key_size &&
1164         !auth_list->push_back(TAG_KEY_SIZE, ASN1_INTEGER_get(record->key_size))) {
1165         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1166     }
1167 
1168     // Block mode
1169     if (!get_repeated_enums(record->block_mode, TAG_BLOCK_MODE, auth_list)) {
1170         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1171     }
1172 
1173     // Digest
1174     if (!get_repeated_enums(record->digest, TAG_DIGEST, auth_list)) {
1175         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1176     }
1177 
1178     // Padding
1179     if (!get_repeated_enums(record->padding, TAG_PADDING, auth_list)) {
1180         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1181     }
1182 
1183     // Caller nonce
1184     if (record->caller_nonce && !auth_list->push_back(TAG_CALLER_NONCE)) {
1185         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1186     }
1187 
1188     // Min mac length
1189     if (!get_ulong(record->min_mac_length, TAG_MIN_MAC_LENGTH, auth_list)) {
1190         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1191     }
1192 
1193     // EC curve
1194     if (!get_enum(record->ec_curve, TAG_EC_CURVE, auth_list)) {
1195         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1196     }
1197 
1198     // RSA public exponent
1199     if (!get_ulong(record->rsa_public_exponent, TAG_RSA_PUBLIC_EXPONENT, auth_list)) {
1200         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1201     }
1202 
1203     // Rsa Oaep Mgf Digest
1204     if (!get_repeated_enums(record->mgf_digest, TAG_RSA_OAEP_MGF_DIGEST, auth_list)) {
1205         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1206     }
1207 
1208     // Rollback resistance
1209     if (record->rollback_resistance && !auth_list->push_back(TAG_ROLLBACK_RESISTANCE)) {
1210         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1211     }
1212 
1213     // Early boot only
1214     if (record->early_boot_only && !auth_list->push_back(TAG_EARLY_BOOT_ONLY)) {
1215         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1216     }
1217 
1218     // Active date time
1219     if (!get_ulong(record->active_date_time, TAG_ACTIVE_DATETIME, auth_list)) {
1220         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1221     }
1222 
1223     // Origination expire date time
1224     if (!get_ulong(record->origination_expire_date_time, TAG_ORIGINATION_EXPIRE_DATETIME,
1225                    auth_list)) {
1226         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1227     }
1228 
1229     // Usage Expire date time
1230     if (!get_ulong(record->usage_expire_date_time, TAG_USAGE_EXPIRE_DATETIME, auth_list)) {
1231         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1232     }
1233 
1234     // Usage count limit
1235     if (record->usage_count_limit &&
1236         !auth_list->push_back(TAG_USAGE_COUNT_LIMIT, ASN1_INTEGER_get(record->usage_count_limit))) {
1237         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1238     }
1239 
1240     // No auth required
1241     if (record->no_auth_required && !auth_list->push_back(TAG_NO_AUTH_REQUIRED)) {
1242         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1243     }
1244 
1245     // User auth type
1246     if (!get_enum(record->user_auth_type, TAG_USER_AUTH_TYPE, auth_list)) {
1247         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1248     }
1249 
1250     // Auth timeout
1251     if (record->auth_timeout &&
1252         !auth_list->push_back(TAG_AUTH_TIMEOUT, ASN1_INTEGER_get(record->auth_timeout))) {
1253         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1254     }
1255 
1256     // Allow while on body
1257     if (record->allow_while_on_body && !auth_list->push_back(TAG_ALLOW_WHILE_ON_BODY)) {
1258         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1259     }
1260 
1261     // trusted user presence required
1262     if (record->trusted_user_presence_required &&
1263         !auth_list->push_back(TAG_TRUSTED_USER_PRESENCE_REQUIRED)) {
1264         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1265     }
1266 
1267     // trusted confirmation required
1268     if (record->trusted_confirmation_required &&
1269         !auth_list->push_back(TAG_TRUSTED_CONFIRMATION_REQUIRED)) {
1270         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1271     }
1272 
1273     // Unlocked device required
1274     if (record->unlocked_device_required && !auth_list->push_back(TAG_UNLOCKED_DEVICE_REQUIRED)) {
1275         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1276     }
1277 
1278     // All applications
1279     if (record->all_applications && !auth_list->push_back(TAG_ALL_APPLICATIONS)) {
1280         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1281     }
1282 
1283     // Application ID
1284     if (record->application_id &&
1285         !auth_list->push_back(TAG_APPLICATION_ID, record->application_id->data,
1286                               record->application_id->length)) {
1287         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1288     }
1289 
1290     // Creation date time
1291     if (!get_ulong(record->creation_date_time, TAG_CREATION_DATETIME, auth_list)) {
1292         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1293     }
1294 
1295     // Origin
1296     if (!get_enum(record->origin, TAG_ORIGIN, auth_list)) {
1297         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1298     }
1299 
1300     // Rollback resistant
1301     if (record->rollback_resistant && !auth_list->push_back(TAG_ROLLBACK_RESISTANT)) {
1302         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1303     }
1304 
1305     // Root of trust
1306     if (record->root_of_trust) {
1307         KM_ROOT_OF_TRUST* rot = record->root_of_trust;
1308         if (!rot->verified_boot_key) return KM_ERROR_INVALID_KEY_BLOB;
1309 
1310         // Other root of trust fields are not mapped to auth set entries.
1311     }
1312 
1313     // OS Version
1314     if (record->os_version &&
1315         !auth_list->push_back(TAG_OS_VERSION, ASN1_INTEGER_get(record->os_version))) {
1316         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1317     }
1318 
1319     // OS Patch level
1320     if (record->os_patchlevel &&
1321         !auth_list->push_back(TAG_OS_PATCHLEVEL, ASN1_INTEGER_get(record->os_patchlevel))) {
1322         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1323     }
1324 
1325     // attestation application Id
1326     if (record->attestation_application_id &&
1327         !auth_list->push_back(TAG_ATTESTATION_APPLICATION_ID,
1328                               record->attestation_application_id->data,
1329                               record->attestation_application_id->length)) {
1330         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1331     }
1332 
1333     // Brand name
1334     if (record->attestation_id_brand &&
1335         !auth_list->push_back(TAG_ATTESTATION_ID_BRAND, record->attestation_id_brand->data,
1336                               record->attestation_id_brand->length)) {
1337         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1338     }
1339 
1340     // Device name
1341     if (record->attestation_id_device &&
1342         !auth_list->push_back(TAG_ATTESTATION_ID_DEVICE, record->attestation_id_device->data,
1343                               record->attestation_id_device->length)) {
1344         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1345     }
1346 
1347     // Product name
1348     if (record->attestation_id_product &&
1349         !auth_list->push_back(TAG_ATTESTATION_ID_PRODUCT, record->attestation_id_product->data,
1350                               record->attestation_id_product->length)) {
1351         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1352     }
1353 
1354     // Serial number
1355     if (record->attestation_id_serial &&
1356         !auth_list->push_back(TAG_ATTESTATION_ID_SERIAL, record->attestation_id_serial->data,
1357                               record->attestation_id_serial->length)) {
1358         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1359     }
1360 
1361     // IMEI
1362     if (record->attestation_id_imei &&
1363         !auth_list->push_back(TAG_ATTESTATION_ID_IMEI, record->attestation_id_imei->data,
1364                               record->attestation_id_imei->length)) {
1365         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1366     }
1367 
1368     // MEID
1369     if (record->attestation_id_meid &&
1370         !auth_list->push_back(TAG_ATTESTATION_ID_MEID, record->attestation_id_meid->data,
1371                               record->attestation_id_meid->length)) {
1372         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1373     }
1374 
1375     // Manufacturer name
1376     if (record->attestation_id_manufacturer &&
1377         !auth_list->push_back(TAG_ATTESTATION_ID_MANUFACTURER,
1378                               record->attestation_id_manufacturer->data,
1379                               record->attestation_id_manufacturer->length)) {
1380         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1381     }
1382 
1383     // Model name
1384     if (record->attestation_id_model &&
1385         !auth_list->push_back(TAG_ATTESTATION_ID_MODEL, record->attestation_id_model->data,
1386                               record->attestation_id_model->length)) {
1387         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1388     }
1389 
1390     // vendor patch level
1391     if (record->vendor_patchlevel &&
1392         !auth_list->push_back(TAG_VENDOR_PATCHLEVEL, ASN1_INTEGER_get(record->vendor_patchlevel))) {
1393         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1394     }
1395 
1396     // boot patch level
1397     if (record->boot_patch_level &&
1398         !auth_list->push_back(TAG_BOOT_PATCHLEVEL, ASN1_INTEGER_get(record->boot_patch_level))) {
1399         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1400     }
1401 
1402     // device unique attestation
1403     if (record->device_unique_attestation && !auth_list->push_back(TAG_DEVICE_UNIQUE_ATTESTATION)) {
1404         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1405     }
1406 
1407     // identity credential key
1408     if (record->identity_credential_key && !auth_list->push_back(TAG_IDENTITY_CREDENTIAL_KEY)) {
1409         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1410     }
1411 
1412     // Second IMEI
1413     if (record->attestation_id_second_imei &&
1414         !auth_list->push_back(TAG_ATTESTATION_ID_SECOND_IMEI,
1415                               record->attestation_id_second_imei->data,
1416                               record->attestation_id_second_imei->length)) {
1417         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1418     }
1419 
1420     // Module hash
1421     if (record->module_hash && !auth_list->push_back(TAG_MODULE_HASH, record->module_hash->data,
1422                                                      record->module_hash->length)) {
1423         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1424     }
1425 
1426     return KM_ERROR_OK;
1427 }
1428 
1429 // Parse the DER-encoded attestation record, placing the results in keymaster_version,
1430 // 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)1431 keymaster_error_t parse_attestation_record(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
1432                                            uint32_t* attestation_version,  //
1433                                            keymaster_security_level_t* attestation_security_level,
1434                                            uint32_t* keymaster_version,
1435                                            keymaster_security_level_t* keymaster_security_level,
1436                                            keymaster_blob_t* attestation_challenge,
1437                                            AuthorizationSet* software_enforced,
1438                                            AuthorizationSet* tee_enforced,
1439                                            keymaster_blob_t* unique_id) {
1440     const uint8_t* p = asn1_key_desc;
1441     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> record(
1442         d2i_KM_KEY_DESCRIPTION(nullptr, &p, asn1_key_desc_len));
1443     if (!record.get()) return TranslateLastOpenSslError();
1444 
1445     *attestation_version = ASN1_INTEGER_get(record->attestation_version);
1446     *attestation_security_level = static_cast<keymaster_security_level_t>(
1447         ASN1_ENUMERATED_get(record->attestation_security_level));
1448     *keymaster_version = ASN1_INTEGER_get(record->keymaster_version);
1449     *keymaster_security_level = static_cast<keymaster_security_level_t>(
1450         ASN1_ENUMERATED_get(record->keymaster_security_level));
1451 
1452     attestation_challenge->data =
1453         dup_buffer(record->attestation_challenge->data, record->attestation_challenge->length);
1454     attestation_challenge->data_length = record->attestation_challenge->length;
1455 
1456     unique_id->data = dup_buffer(record->unique_id->data, record->unique_id->length);
1457     unique_id->data_length = record->unique_id->length;
1458 
1459     keymaster_error_t error = extract_auth_list(record->software_enforced, software_enforced);
1460     if (error != KM_ERROR_OK) return error;
1461 
1462     return extract_auth_list(record->tee_enforced, tee_enforced);
1463 }
1464 
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)1465 keymaster_error_t parse_root_of_trust(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
1466                                       keymaster_blob_t* verified_boot_key,
1467                                       keymaster_verified_boot_t* verified_boot_state,
1468                                       bool* device_locked) {
1469     const uint8_t* p = asn1_key_desc;
1470     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> record(
1471         d2i_KM_KEY_DESCRIPTION(nullptr, &p, asn1_key_desc_len));
1472     if (!record.get()) {
1473         return TranslateLastOpenSslError();
1474     }
1475     if (!record->tee_enforced) {
1476         return KM_ERROR_INVALID_ARGUMENT;
1477     }
1478     if (!record->tee_enforced->root_of_trust) {
1479         return KM_ERROR_INVALID_ARGUMENT;
1480     }
1481     if (!record->tee_enforced->root_of_trust->verified_boot_key) {
1482         return KM_ERROR_INVALID_ARGUMENT;
1483     }
1484     KM_ROOT_OF_TRUST* root_of_trust = record->tee_enforced->root_of_trust;
1485     verified_boot_key->data = dup_buffer(root_of_trust->verified_boot_key->data,
1486                                          root_of_trust->verified_boot_key->length);
1487     verified_boot_key->data_length = root_of_trust->verified_boot_key->length;
1488     *verified_boot_state = static_cast<keymaster_verified_boot_t>(
1489         ASN1_ENUMERATED_get(root_of_trust->verified_boot_state));
1490     *device_locked = root_of_trust->device_locked;
1491     return KM_ERROR_OK;
1492 }
1493 
1494 // Parse the EAT-encoded attestation record, placing the results in keymaster_version,
1495 // attestation_challenge, software_enforced, tee_enforced and unique_id.
parse_eat_record(const uint8_t * eat_key_desc,size_t eat_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,keymaster_blob_t * verified_boot_key,keymaster_verified_boot_t * verified_boot_state,bool * device_locked,std::vector<int64_t> * unexpected_claims)1496 keymaster_error_t parse_eat_record(
1497     const uint8_t* eat_key_desc, size_t eat_key_desc_len, uint32_t* attestation_version,
1498     keymaster_security_level_t* attestation_security_level, uint32_t* keymaster_version,
1499     keymaster_security_level_t* keymaster_security_level, keymaster_blob_t* attestation_challenge,
1500     AuthorizationSet* software_enforced, AuthorizationSet* tee_enforced,
1501     keymaster_blob_t* unique_id, keymaster_blob_t* verified_boot_key,
1502     keymaster_verified_boot_t* verified_boot_state, bool* device_locked,
1503     std::vector<int64_t>* unexpected_claims) {
1504     auto [top_level_item, next_pos, error] = cppbor::parse(eat_key_desc, eat_key_desc_len);
1505     ASSERT_OR_RETURN_ERROR(top_level_item, KM_ERROR_INVALID_TAG);
1506     const cppbor::Map* eat_map = top_level_item->asMap();
1507     ASSERT_OR_RETURN_ERROR(eat_map, KM_ERROR_INVALID_TAG);
1508     bool verified_or_self_signed = false;
1509 
1510     for (size_t i = 0; i < eat_map->size(); i++) {
1511         auto& [key_item, value_item] = (*eat_map)[i];
1512         const cppbor::Int* key = key_item->asInt();
1513         ASSERT_OR_RETURN_ERROR(key, (KM_ERROR_INVALID_TAG));
1514 
1515         // The following values will either hold the typed value, or be null (if not the right
1516         // type).
1517         const cppbor::Int* int_value = value_item->asInt();
1518         const cppbor::Bstr* bstr_value = value_item->asBstr();
1519         const cppbor::Simple* simple_value = value_item->asSimple();
1520         const cppbor::Array* array_value = value_item->asArray();
1521         const cppbor::Map* map_value = value_item->asMap();
1522 
1523         keymaster_error_t error;
1524         switch ((EatClaim)key->value()) {
1525         default:
1526             unexpected_claims->push_back(key->value());
1527             break;
1528         case EatClaim::ATTESTATION_VERSION:
1529             ASSERT_OR_RETURN_ERROR(int_value, KM_ERROR_INVALID_TAG);
1530             *attestation_version = int_value->value();
1531             break;
1532         case EatClaim::SECURITY_LEVEL:
1533             ASSERT_OR_RETURN_ERROR(int_value, KM_ERROR_INVALID_TAG);
1534             switch ((EatSecurityLevel)int_value->value()) {
1535             // TODO: Is my assumption correct that the security level of the attestation data should
1536             // always be equal to the security level of keymint, as the attestation data always
1537             // lives in the top-level module?
1538             case EatSecurityLevel::UNRESTRICTED:
1539                 *keymaster_security_level = *attestation_security_level =
1540                     KM_SECURITY_LEVEL_SOFTWARE;
1541                 break;
1542             case EatSecurityLevel::SECURE_RESTRICTED:
1543                 *keymaster_security_level = *attestation_security_level =
1544                     KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
1545                 break;
1546             case EatSecurityLevel::HARDWARE:
1547                 *keymaster_security_level = *attestation_security_level =
1548                     KM_SECURITY_LEVEL_STRONGBOX;
1549                 break;
1550             default:
1551                 return KM_ERROR_INVALID_TAG;
1552             }
1553             break;
1554         case EatClaim::KEYMASTER_VERSION:
1555             ASSERT_OR_RETURN_ERROR(int_value, KM_ERROR_INVALID_TAG);
1556             *keymaster_version = int_value->value();
1557             break;
1558         case EatClaim::SUBMODS:
1559             ASSERT_OR_RETURN_ERROR(map_value, KM_ERROR_INVALID_TAG);
1560             for (size_t j = 0; j < map_value->size(); j++) {
1561                 auto& [submod_key, submod_value] = (*map_value)[j];
1562                 const cppbor::Map* submod_map = submod_value->asMap();
1563                 ASSERT_OR_RETURN_ERROR(submod_map, KM_ERROR_INVALID_TAG);
1564                 error = parse_eat_submod(submod_map, software_enforced, tee_enforced);
1565                 if (error != KM_ERROR_OK) return error;
1566             }
1567             break;
1568         case EatClaim::CTI:
1569             error = bstr_to_blob(bstr_value, unique_id);
1570             if (error != KM_ERROR_OK) return error;
1571             break;
1572         case EatClaim::NONCE:
1573             error = bstr_to_blob(bstr_value, attestation_challenge);
1574             if (error != KM_ERROR_OK) return error;
1575             break;
1576         case EatClaim::VERIFIED_BOOT_KEY:
1577             error = bstr_to_blob(bstr_value, verified_boot_key);
1578             if (error != KM_ERROR_OK) return error;
1579             break;
1580         case EatClaim::VERIFIED_BOOT_HASH:
1581             // Not parsing this for now.
1582             break;
1583         case EatClaim::DEVICE_UNIQUE_ATTESTATION:
1584             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1585                 return KM_ERROR_INVALID_TAG;
1586             }
1587             // Not parsing this for now.
1588             break;
1589         case EatClaim::DEVICE_LOCKED:
1590             ASSERT_OR_RETURN_ERROR(simple_value->asBool(), KM_ERROR_INVALID_TAG);
1591             *device_locked = simple_value->asBool()->value();
1592             break;
1593         case EatClaim::BOOT_STATE:
1594             ASSERT_OR_RETURN_ERROR(array_value, KM_ERROR_INVALID_TAG);
1595             ASSERT_OR_RETURN_ERROR(array_value->size() == 5, KM_ERROR_INVALID_TAG);
1596             ASSERT_OR_RETURN_ERROR((*array_value)[4]->asSimple()->asBool()->value() == false,
1597                                    KM_ERROR_INVALID_TAG);
1598             verified_or_self_signed = (*array_value)[0]->asSimple()->asBool()->value();
1599             ASSERT_OR_RETURN_ERROR(verified_or_self_signed ==
1600                                        (*array_value)[1]->asSimple()->asBool()->value(),
1601                                    KM_ERROR_INVALID_TAG);
1602             ASSERT_OR_RETURN_ERROR(verified_or_self_signed ==
1603                                        (*array_value)[2]->asSimple()->asBool()->value(),
1604                                    KM_ERROR_INVALID_TAG);
1605             ASSERT_OR_RETURN_ERROR(verified_or_self_signed ==
1606                                        (*array_value)[3]->asSimple()->asBool()->value(),
1607                                    KM_ERROR_INVALID_TAG);
1608             break;
1609         case EatClaim::OFFICIAL_BUILD:
1610             *verified_boot_state = KM_VERIFIED_BOOT_VERIFIED;
1611             break;
1612         }
1613     }
1614 
1615     if (*verified_boot_state == KM_VERIFIED_BOOT_VERIFIED) {
1616         (void)(verified_boot_state);
1617         // TODO: re-enable this
1618         // ASSERT_OR_RETURN_ERROR(verified_or_self_signed, KM_ERROR_INVALID_TAG);
1619     } else {
1620         *verified_boot_state =
1621             verified_or_self_signed ? KM_VERIFIED_BOOT_SELF_SIGNED : KM_VERIFIED_BOOT_UNVERIFIED;
1622     }
1623 
1624     return KM_ERROR_OK;
1625 }
1626 
parse_submod_values(AuthorizationSetBuilder * set_builder,int * auth_set_security_level,const cppbor::Map * submod_map)1627 keymaster_error_t parse_submod_values(AuthorizationSetBuilder* set_builder,
1628                                       int* auth_set_security_level, const cppbor::Map* submod_map) {
1629     ASSERT_OR_RETURN_ERROR(set_builder, KM_ERROR_UNEXPECTED_NULL_POINTER);
1630     for (size_t i = 0; i < submod_map->size(); i++) {
1631         auto& [key_item, value_item] = (*submod_map)[i];
1632         const cppbor::Int* key_int = key_item->asInt();
1633         ASSERT_OR_RETURN_ERROR(key_int, KM_ERROR_INVALID_TAG);
1634         int key = key_int->value();
1635         keymaster_error_t error;
1636         keymaster_blob_t blob;
1637 
1638         switch ((EatClaim)key) {
1639         default:
1640             return KM_ERROR_INVALID_TAG;
1641         case EatClaim::ALGORITHM:
1642             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1643             set_builder->Authorization(
1644                 TAG_ALGORITHM, static_cast<keymaster_algorithm_t>(value_item->asInt()->value()));
1645             break;
1646         case EatClaim::EC_CURVE:
1647             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1648             set_builder->Authorization(
1649                 TAG_EC_CURVE, static_cast<keymaster_ec_curve_t>(value_item->asInt()->value()));
1650             break;
1651         case EatClaim::USER_AUTH_TYPE:
1652             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1653             set_builder->Authorization(TAG_USER_AUTH_TYPE, static_cast<hw_authenticator_type_t>(
1654                                                                value_item->asInt()->value()));
1655             break;
1656         case EatClaim::ORIGIN:
1657             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1658             set_builder->Authorization(
1659                 TAG_ORIGIN, static_cast<keymaster_key_origin_t>(value_item->asInt()->value()));
1660             break;
1661         case EatClaim::PURPOSE:
1662             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1663                 set_builder->Authorization(TAG_PURPOSE,
1664                                            static_cast<keymaster_purpose_t>(
1665                                                (*value_item->asArray())[j]->asInt()->value()));
1666             }
1667             break;
1668         case EatClaim::PADDING:
1669             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1670                 set_builder->Authorization(TAG_PADDING,
1671                                            static_cast<keymaster_padding_t>(
1672                                                (*value_item->asArray())[j]->asInt()->value()));
1673             }
1674             break;
1675         case EatClaim::DIGEST:
1676             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1677                 set_builder->Authorization(
1678                     TAG_DIGEST,
1679                     static_cast<keymaster_digest_t>((*value_item->asArray())[j]->asInt()->value()));
1680             }
1681             break;
1682         case EatClaim::BLOCK_MODE:
1683             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1684                 set_builder->Authorization(TAG_BLOCK_MODE,
1685                                            static_cast<keymaster_block_mode_t>(
1686                                                (*value_item->asArray())[j]->asInt()->value()));
1687             }
1688             break;
1689         case EatClaim::KEY_SIZE:
1690             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1691             set_builder->Authorization(TAG_KEY_SIZE, value_item->asInt()->value());
1692             break;
1693         case EatClaim::AUTH_TIMEOUT:
1694             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1695             set_builder->Authorization(TAG_AUTH_TIMEOUT, value_item->asInt()->value());
1696             break;
1697         case EatClaim::OS_VERSION:
1698             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1699             set_builder->Authorization(TAG_OS_VERSION, value_item->asInt()->value());
1700             break;
1701         case EatClaim::OS_PATCHLEVEL:
1702             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1703             set_builder->Authorization(TAG_OS_PATCHLEVEL, value_item->asInt()->value());
1704             break;
1705         case EatClaim::MIN_MAC_LENGTH:
1706             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1707             set_builder->Authorization(TAG_MIN_MAC_LENGTH, value_item->asInt()->value());
1708             break;
1709         case EatClaim::BOOT_PATCHLEVEL:
1710             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1711             set_builder->Authorization(TAG_BOOT_PATCHLEVEL, value_item->asInt()->value());
1712             break;
1713         case EatClaim::VENDOR_PATCHLEVEL:
1714             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1715             set_builder->Authorization(TAG_VENDOR_PATCHLEVEL, value_item->asInt()->value());
1716             break;
1717         case EatClaim::RSA_PUBLIC_EXPONENT:
1718             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1719             set_builder->Authorization(TAG_RSA_PUBLIC_EXPONENT, value_item->asInt()->value());
1720             break;
1721         case EatClaim::ACTIVE_DATETIME:
1722             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1723             set_builder->Authorization(TAG_ACTIVE_DATETIME, value_item->asInt()->value());
1724             break;
1725         case EatClaim::ORIGINATION_EXPIRE_DATETIME:
1726             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1727             set_builder->Authorization(TAG_ORIGINATION_EXPIRE_DATETIME,
1728                                        value_item->asInt()->value());
1729             break;
1730         case EatClaim::USAGE_EXPIRE_DATETIME:
1731             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1732             set_builder->Authorization(TAG_USAGE_EXPIRE_DATETIME, value_item->asInt()->value());
1733             break;
1734         case EatClaim::IAT:
1735             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1736             set_builder->Authorization(TAG_CREATION_DATETIME, value_item->asInt()->value());
1737             break;
1738         case EatClaim::NO_AUTH_REQUIRED:
1739             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1740                 return KM_ERROR_INVALID_TAG;
1741             }
1742             set_builder->Authorization(TAG_NO_AUTH_REQUIRED);
1743             break;
1744         case EatClaim::ALL_APPLICATIONS:
1745             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1746                 return KM_ERROR_INVALID_TAG;
1747             }
1748             set_builder->Authorization(TAG_ALL_APPLICATIONS);
1749             break;
1750         case EatClaim::ROLLBACK_RESISTANT:
1751             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1752                 return KM_ERROR_INVALID_TAG;
1753             }
1754             set_builder->Authorization(TAG_ROLLBACK_RESISTANT);
1755             break;
1756         case EatClaim::ALLOW_WHILE_ON_BODY:
1757             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1758                 return KM_ERROR_INVALID_TAG;
1759             }
1760             set_builder->Authorization(TAG_ALLOW_WHILE_ON_BODY);
1761             break;
1762         case EatClaim::UNLOCKED_DEVICE_REQUIRED:
1763             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1764                 return KM_ERROR_INVALID_TAG;
1765             }
1766             set_builder->Authorization(TAG_UNLOCKED_DEVICE_REQUIRED);
1767             break;
1768         case EatClaim::CALLER_NONCE:
1769             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1770                 return KM_ERROR_INVALID_TAG;
1771             }
1772             set_builder->Authorization(TAG_CALLER_NONCE);
1773             break;
1774         case EatClaim::TRUSTED_CONFIRMATION_REQUIRED:
1775             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1776                 return KM_ERROR_INVALID_TAG;
1777             }
1778             set_builder->Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED);
1779             break;
1780         case EatClaim::EARLY_BOOT_ONLY:
1781             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1782                 return KM_ERROR_INVALID_TAG;
1783             }
1784             set_builder->Authorization(TAG_EARLY_BOOT_ONLY);
1785             break;
1786         case EatClaim::IDENTITY_CREDENTIAL_KEY:
1787             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1788                 return KM_ERROR_INVALID_TAG;
1789             }
1790             set_builder->Authorization(TAG_IDENTITY_CREDENTIAL_KEY);
1791             break;
1792         case EatClaim::STORAGE_KEY:
1793             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1794                 return KM_ERROR_INVALID_TAG;
1795             }
1796             set_builder->Authorization(TAG_STORAGE_KEY);
1797             break;
1798         case EatClaim::TRUSTED_USER_PRESENCE_REQUIRED:
1799             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1800                 return KM_ERROR_INVALID_TAG;
1801             }
1802             set_builder->Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED);
1803             break;
1804         case EatClaim::DEVICE_UNIQUE_ATTESTATION:
1805             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1806                 return KM_ERROR_INVALID_TAG;
1807             }
1808             set_builder->Authorization(TAG_DEVICE_UNIQUE_ATTESTATION);
1809             break;
1810         case EatClaim::APPLICATION_ID:
1811             error = bstr_to_blob(value_item->asBstr(), &blob);
1812             if (error != KM_ERROR_OK) return error;
1813             set_builder->Authorization(TAG_APPLICATION_ID, blob);
1814             break;
1815         case EatClaim::ATTESTATION_APPLICATION_ID:
1816             error = bstr_to_blob(value_item->asBstr(), &blob);
1817             if (error != KM_ERROR_OK) return error;
1818             set_builder->Authorization(TAG_ATTESTATION_APPLICATION_ID, blob);
1819             break;
1820         case EatClaim::ATTESTATION_ID_BRAND:
1821             error = bstr_to_blob(value_item->asBstr(), &blob);
1822             if (error != KM_ERROR_OK) return error;
1823             set_builder->Authorization(TAG_ATTESTATION_ID_BRAND, blob);
1824             break;
1825         case EatClaim::ATTESTATION_ID_DEVICE:
1826             error = bstr_to_blob(value_item->asBstr(), &blob);
1827             if (error != KM_ERROR_OK) return error;
1828             set_builder->Authorization(TAG_ATTESTATION_ID_DEVICE, blob);
1829             break;
1830         case EatClaim::ATTESTATION_ID_PRODUCT:
1831             error = bstr_to_blob(value_item->asBstr(), &blob);
1832             if (error != KM_ERROR_OK) return error;
1833             set_builder->Authorization(TAG_ATTESTATION_ID_PRODUCT, blob);
1834             break;
1835         case EatClaim::ATTESTATION_ID_SERIAL:
1836             error = bstr_to_blob(value_item->asBstr(), &blob);
1837             if (error != KM_ERROR_OK) return error;
1838             set_builder->Authorization(TAG_ATTESTATION_ID_SERIAL, blob);
1839             break;
1840         case EatClaim::UEID:
1841             error = ueid_to_imei_blob(value_item->asBstr(), &blob);
1842             if (error != KM_ERROR_OK) return error;
1843             set_builder->Authorization(TAG_ATTESTATION_ID_IMEI, blob);
1844             break;
1845         case EatClaim::ATTESTATION_ID_MEID:
1846             error = bstr_to_blob(value_item->asBstr(), &blob);
1847             if (error != KM_ERROR_OK) return error;
1848             set_builder->Authorization(TAG_ATTESTATION_ID_MEID, blob);
1849             break;
1850         case EatClaim::ATTESTATION_ID_MANUFACTURER:
1851             error = bstr_to_blob(value_item->asBstr(), &blob);
1852             if (error != KM_ERROR_OK) return error;
1853             set_builder->Authorization(TAG_ATTESTATION_ID_MANUFACTURER, blob);
1854             break;
1855         case EatClaim::ATTESTATION_ID_MODEL:
1856             error = bstr_to_blob(value_item->asBstr(), &blob);
1857             if (error != KM_ERROR_OK) return error;
1858             set_builder->Authorization(TAG_ATTESTATION_ID_MODEL, blob);
1859             break;
1860         case EatClaim::CONFIRMATION_TOKEN:
1861             error = bstr_to_blob(value_item->asBstr(), &blob);
1862             if (error != KM_ERROR_OK) return error;
1863             set_builder->Authorization(TAG_CONFIRMATION_TOKEN, blob);
1864             break;
1865         case EatClaim::SECURITY_LEVEL:
1866             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1867             *auth_set_security_level = value_item->asInt()->value();
1868         }
1869     }
1870 
1871     return KM_ERROR_OK;
1872 }
1873 
parse_eat_submod(const cppbor::Map * submod_values,AuthorizationSet * software_enforced,AuthorizationSet * tee_enforced)1874 keymaster_error_t parse_eat_submod(const cppbor::Map* submod_values,
1875                                    AuthorizationSet* software_enforced,
1876                                    AuthorizationSet* tee_enforced) {
1877     AuthorizationSetBuilder auth_set_builder;
1878     int auth_set_security_level = 0;
1879     keymaster_error_t error =
1880         parse_submod_values(&auth_set_builder, &auth_set_security_level, submod_values);
1881     if (error) return error;
1882     switch ((EatSecurityLevel)auth_set_security_level) {
1883     case EatSecurityLevel::HARDWARE:
1884         // Hardware attestation should never occur in a submod of another EAT.
1885         [[fallthrough]];
1886     default:
1887         return KM_ERROR_INVALID_TAG;
1888     case EatSecurityLevel::UNRESTRICTED:
1889         *software_enforced = AuthorizationSet(auth_set_builder);
1890         break;
1891     case EatSecurityLevel::SECURE_RESTRICTED:
1892         *tee_enforced = AuthorizationSet(auth_set_builder);
1893         break;
1894     }
1895 
1896     return KM_ERROR_OK;
1897 }
1898 }  // namespace keymaster
1899