• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <keymaster/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         }
696 
697         keymaster_tag_type_t type = keymaster_tag_get_type(entry.tag);
698         switch (type) {
699         case KM_ENUM:
700         case KM_ENUM_REP:
701         case KM_UINT:
702         case KM_UINT_REP: {
703             ASSERT_OR_RETURN_ERROR((keymaster_tag_repeatable(entry.tag) && integer_set) ||
704                                        (!keymaster_tag_repeatable(entry.tag) && integer_ptr),
705                                    KM_ERROR_INVALID_TAG);
706 
707             UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> value(ASN1_INTEGER_new());
708             if (!value.get()) {
709                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
710             }
711             if (!ASN1_INTEGER_set(value.get(), get_uint32_value(entry))) {
712                 return TranslateLastOpenSslError();
713             }
714 
715             insert_integer(value.release(), integer_ptr, integer_set);
716             break;
717         }
718 
719         case KM_ULONG:
720         case KM_ULONG_REP:
721         case KM_DATE: {
722             ASSERT_OR_RETURN_ERROR((keymaster_tag_repeatable(entry.tag) && integer_set) ||
723                                        (!keymaster_tag_repeatable(entry.tag) && integer_ptr),
724                                    KM_ERROR_INVALID_TAG);
725 
726             UniquePtr<BIGNUM, BIGNUM_Delete> bn_value(BN_new());
727             if (!bn_value.get()) {
728                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
729             }
730 
731             if (type == KM_DATE) {
732                 if (!BN_set_u64(bn_value.get(), entry.date_time)) {
733                     return TranslateLastOpenSslError();
734                 }
735             } else {
736                 if (!BN_set_u64(bn_value.get(), entry.long_integer)) {
737                     return TranslateLastOpenSslError();
738                 }
739             }
740 
741             UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> value(
742                 BN_to_ASN1_INTEGER(bn_value.get(), nullptr));
743             if (!value.get()) {
744                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
745             }
746 
747             insert_integer(value.release(), integer_ptr, integer_set);
748             break;
749         }
750 
751         case KM_BOOL:
752             ASSERT_OR_RETURN_ERROR(bool_ptr, KM_ERROR_INVALID_TAG);
753             if (!*bool_ptr) *bool_ptr = ASN1_NULL_new();
754             if (!*bool_ptr) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
755             break;
756 
757         /* Byte arrays*/
758         case KM_BYTES:
759             ASSERT_OR_RETURN_ERROR(string_ptr, KM_ERROR_INVALID_TAG);
760             if (!*string_ptr) {
761                 *string_ptr = ASN1_OCTET_STRING_new();
762             }
763             if (!*string_ptr) {
764                 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
765             }
766             if (!ASN1_OCTET_STRING_set(*string_ptr, entry.blob.data, entry.blob.data_length)) {
767                 return TranslateLastOpenSslError();
768             }
769             break;
770 
771         default:
772             return KM_ERROR_UNIMPLEMENTED;
773         }
774     }
775 
776     keymaster_ec_curve_t ec_curve;
777     uint32_t key_size;
778     if (auth_list.Contains(TAG_ALGORITHM, KM_ALGORITHM_EC) &&  //
779         !auth_list.Contains(TAG_EC_CURVE) &&                   //
780         auth_list.GetTagValue(TAG_KEY_SIZE, &key_size)) {
781         // This must be a keymaster1 key. It's an EC key with no curve.  Insert the curve if we
782         // can unambiguously figure it out.
783 
784         keymaster_error_t error = EcKeySizeToCurve(key_size, &ec_curve);
785         if (error != KM_ERROR_OK) return error;
786 
787         UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> value(ASN1_INTEGER_new());
788         if (!value.get()) {
789             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
790         }
791 
792         if (!ASN1_INTEGER_set(value.get(), ec_curve)) {
793             return TranslateLastOpenSslError();
794         }
795 
796         insert_integer(value.release(), &record->ec_curve, nullptr);
797     }
798 
799     return KM_ERROR_OK;
800 }
801 
802 // Construct a CBOR-encoded attestation record containing the values from sw_enforced
803 // 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)804 keymaster_error_t build_eat_record(const AuthorizationSet& attestation_params,
805                                    AuthorizationSet sw_enforced, AuthorizationSet tee_enforced,
806                                    const AttestationContext& context,
807                                    std::vector<uint8_t>* eat_token) {
808     ASSERT_OR_RETURN_ERROR(eat_token, KM_ERROR_UNEXPECTED_NULL_POINTER);
809 
810     cppbor::Map eat_record;
811     switch (context.GetSecurityLevel()) {
812     case KM_SECURITY_LEVEL_SOFTWARE:
813         eat_record.add(EatClaim::SECURITY_LEVEL, get_uint32_value(EatSecurityLevel::UNRESTRICTED));
814         break;
815     case KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT:
816         eat_record.add(EatClaim::SECURITY_LEVEL,
817                        get_uint32_value(EatSecurityLevel::SECURE_RESTRICTED));
818         break;
819     case KM_SECURITY_LEVEL_STRONGBOX:
820         eat_record.add(EatClaim::SECURITY_LEVEL, get_uint32_value(EatSecurityLevel::HARDWARE));
821         break;
822     default:
823         return KM_ERROR_UNKNOWN_ERROR;
824     }
825 
826     keymaster_error_t error;
827     const AttestationContext::VerifiedBootParams* vb_params = context.GetVerifiedBootParams(&error);
828     if (error != KM_ERROR_OK) return error;
829 
830     if (vb_params->verified_boot_key.data_length) {
831         eat_record.add(EatClaim::VERIFIED_BOOT_KEY, blob_to_bstr(vb_params->verified_boot_key));
832     }
833     if (vb_params->verified_boot_hash.data_length) {
834         eat_record.add(EatClaim::VERIFIED_BOOT_HASH, blob_to_bstr(vb_params->verified_boot_hash));
835     }
836     if (vb_params->device_locked) {
837         eat_record.add(EatClaim::DEVICE_LOCKED, vb_params->device_locked);
838     }
839 
840     bool verified_or_self_signed = (vb_params->verified_boot_state == KM_VERIFIED_BOOT_VERIFIED ||
841                                     vb_params->verified_boot_state == KM_VERIFIED_BOOT_SELF_SIGNED);
842     auto eat_boot_state = cppbor::Array()
843                               .add(verified_or_self_signed)  // secure-boot-enabled
844                               .add(verified_or_self_signed)  // debug-disabled
845                               .add(verified_or_self_signed)  // debug-disabled-since-boot
846                               .add(verified_or_self_signed)  // debug-permanent-disable
847                               .add(false);  // debug-full-permanent-disable (no way to verify)
848     eat_record.add(EatClaim::BOOT_STATE, std::move(eat_boot_state));
849     eat_record.add(EatClaim::OFFICIAL_BUILD,
850                    vb_params->verified_boot_state == KM_VERIFIED_BOOT_VERIFIED);
851 
852     eat_record.add(EatClaim::ATTESTATION_VERSION,
853                    version_to_attestation_version(context.GetKmVersion()));
854     eat_record.add(EatClaim::KEYMASTER_VERSION,
855                    version_to_attestation_km_version(context.GetKmVersion()));
856 
857     keymaster_blob_t attestation_challenge = {nullptr, 0};
858     if (!attestation_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge)) {
859         return KM_ERROR_ATTESTATION_CHALLENGE_MISSING;
860     }
861 
862     if (!is_valid_attestation_challenge(attestation_challenge)) {
863         return KM_ERROR_INVALID_INPUT_LENGTH;
864     }
865 
866     eat_record.add(EatClaim::NONCE, blob_to_bstr(attestation_challenge));
867 
868     keymaster_blob_t attestation_app_id;
869     if (!attestation_params.GetTagValue(TAG_ATTESTATION_APPLICATION_ID, &attestation_app_id)) {
870         return KM_ERROR_ATTESTATION_APPLICATION_ID_MISSING;
871     }
872     // TODO: what should happen when sw_enforced already contains TAG_ATTESTATION_APPLICATION_ID?
873     // (as is the case in android_keymaster_test.cpp). For now, we will ignore the provided one in
874     // attestation_params if that's the case.
875     keymaster_blob_t existing_app_id;
876     if (!sw_enforced.GetTagValue(TAG_ATTESTATION_APPLICATION_ID, &existing_app_id)) {
877         sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_app_id);
878     }
879 
880     error = context.VerifyAndCopyDeviceIds(
881         attestation_params,
882         context.GetSecurityLevel() == KM_SECURITY_LEVEL_SOFTWARE ? &sw_enforced : &tee_enforced);
883     if (error == KM_ERROR_UNIMPLEMENTED) {
884         // The KeymasterContext implementation does not support device ID attestation. Bail out if
885         // device ID attestation is being attempted.
886         for (const auto& tag : kDeviceAttestationTags) {
887             if (attestation_params.find(tag) != -1) {
888                 return KM_ERROR_CANNOT_ATTEST_IDS;
889             }
890         }
891     } else if (error != KM_ERROR_OK) {
892         return error;
893     }
894 
895     if (attestation_params.Contains(TAG_DEVICE_UNIQUE_ATTESTATION) &&
896         context.GetSecurityLevel() == KM_SECURITY_LEVEL_STRONGBOX) {
897         eat_record.add(EatClaim::DEVICE_UNIQUE_ATTESTATION, true);
898     }
899 
900     cppbor::Map software_submod;
901     error = build_eat_submod(sw_enforced, EatSecurityLevel::UNRESTRICTED, &software_submod);
902     if (error != KM_ERROR_OK) return error;
903 
904     cppbor::Map tee_submod;
905     error = build_eat_submod(tee_enforced, EatSecurityLevel::SECURE_RESTRICTED, &tee_submod);
906     if (error != KM_ERROR_OK) return error;
907 
908     if (software_submod.size() + tee_submod.size() > 0) {
909         cppbor::Map submods;
910         if (software_submod.size() > 0) {
911             submods.add(kEatSubmodNameSoftware, std::move(software_submod));
912         }
913         if (tee_submod.size() > 0) {
914             submods.add(kEatSubmodNameTee, std::move(tee_submod));
915         }
916 
917         eat_record.add(EatClaim::SUBMODS, std::move(submods));
918     }
919 
920     if (attestation_params.GetTagValue(TAG_INCLUDE_UNIQUE_ID)) {
921         uint64_t creation_datetime;
922         // Only check sw_enforced for TAG_CREATION_DATETIME, since it shouldn't be in tee_enforced,
923         // since this implementation has no secure wall clock.
924         if (!sw_enforced.GetTagValue(TAG_CREATION_DATETIME, &creation_datetime)) {
925             LOG_E("Unique ID cannot be created without creation datetime", 0);
926             return KM_ERROR_INVALID_KEY_BLOB;
927         }
928 
929         Buffer unique_id = context.GenerateUniqueId(
930             creation_datetime, attestation_app_id,
931             attestation_params.GetTagValue(TAG_RESET_SINCE_ID_ROTATION), &error);
932         if (error != KM_ERROR_OK) return error;
933 
934         eat_record.add(EatClaim::CTI,
935                        cppbor::Bstr(std::pair(unique_id.begin(), unique_id.available_read())));
936     }
937 
938     *eat_token = eat_record.encode();
939 
940     return KM_ERROR_OK;
941 }
942 
build_unique_id_input(uint64_t creation_date_time,const keymaster_blob_t & application_id,bool reset_since_rotation,Buffer * input_data)943 keymaster_error_t build_unique_id_input(uint64_t creation_date_time,
944                                         const keymaster_blob_t& application_id,
945                                         bool reset_since_rotation, Buffer* input_data) {
946     if (input_data == nullptr) {
947         return KM_ERROR_UNEXPECTED_NULL_POINTER;
948     }
949     uint64_t rounded_date = creation_date_time / 2592000000LLU;
950     uint8_t* serialized_date = reinterpret_cast<uint8_t*>(&rounded_date);
951     uint8_t reset_byte = (reset_since_rotation ? 1 : 0);
952 
953     if (!input_data->Reinitialize(sizeof(rounded_date) + application_id.data_length + 1) ||
954         !input_data->write(serialized_date, sizeof(rounded_date)) ||
955         !input_data->write(application_id.data, application_id.data_length) ||
956         !input_data->write(&reset_byte, 1)) {
957         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
958     }
959     return KM_ERROR_OK;
960 }
961 
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)962 keymaster_error_t generate_unique_id(const std::vector<uint8_t>& hbk, uint64_t creation_date_time,
963                                      const keymaster_blob_t& application_id,
964                                      bool reset_since_rotation, Buffer* unique_id) {
965     if (unique_id == nullptr) {
966         return KM_ERROR_UNEXPECTED_NULL_POINTER;
967     }
968     HmacSha256 hmac;
969     hmac.Init(hbk.data(), hbk.size());
970 
971     Buffer input;
972     keymaster_error_t error =
973         build_unique_id_input(creation_date_time, application_id, reset_since_rotation, &input);
974     if (error != KM_ERROR_OK) {
975         return error;
976     }
977     if (!unique_id->Reinitialize(UNIQUE_ID_SIZE)) {
978         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
979     }
980     hmac.Sign(input.peek_read(), input.available_read(), unique_id->peek_write(),
981               unique_id->available_write());
982     unique_id->advance_write(UNIQUE_ID_SIZE);
983     return KM_ERROR_OK;
984 }
985 
986 // Construct an ASN1.1 DER-encoded attestation record containing the values from sw_enforced and
987 // 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)988 keymaster_error_t build_attestation_record(const AuthorizationSet& attestation_params,  //
989                                            AuthorizationSet sw_enforced,
990                                            AuthorizationSet tee_enforced,
991                                            const AttestationContext& context,
992                                            UniquePtr<uint8_t[]>* asn1_key_desc,
993                                            size_t* asn1_key_desc_len) {
994     ASSERT_OR_RETURN_ERROR(asn1_key_desc && asn1_key_desc_len, KM_ERROR_UNEXPECTED_NULL_POINTER);
995 
996     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> key_desc(KM_KEY_DESCRIPTION_new());
997     if (!key_desc.get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
998 
999     KM_ROOT_OF_TRUST* root_of_trust = nullptr;
1000     if (context.GetSecurityLevel() == KM_SECURITY_LEVEL_SOFTWARE) {
1001         key_desc->software_enforced->root_of_trust = KM_ROOT_OF_TRUST_new();
1002         root_of_trust = key_desc->software_enforced->root_of_trust;
1003     } else {
1004         key_desc->tee_enforced->root_of_trust = KM_ROOT_OF_TRUST_new();
1005         root_of_trust = key_desc->tee_enforced->root_of_trust;
1006     }
1007 
1008     keymaster_error_t error;
1009     auto vb_params = context.GetVerifiedBootParams(&error);
1010     if (error != KM_ERROR_OK) return error;
1011     if (vb_params->verified_boot_key.data_length &&
1012         !ASN1_OCTET_STRING_set(root_of_trust->verified_boot_key, vb_params->verified_boot_key.data,
1013                                vb_params->verified_boot_key.data_length)) {
1014         return TranslateLastOpenSslError();
1015     }
1016     if (vb_params->verified_boot_hash.data_length &&
1017         !ASN1_OCTET_STRING_set(root_of_trust->verified_boot_hash,
1018                                vb_params->verified_boot_hash.data,
1019                                vb_params->verified_boot_hash.data_length)) {
1020         return TranslateLastOpenSslError();
1021     }
1022 
1023     root_of_trust->device_locked = vb_params->device_locked ? 0xFF : 0x00;
1024     if (!ASN1_ENUMERATED_set(root_of_trust->verified_boot_state, vb_params->verified_boot_state)) {
1025         return TranslateLastOpenSslError();
1026     }
1027 
1028     if (!ASN1_INTEGER_set(key_desc->attestation_version,
1029                           version_to_attestation_version(context.GetKmVersion())) ||
1030         !ASN1_ENUMERATED_set(key_desc->attestation_security_level, context.GetSecurityLevel()) ||
1031         !ASN1_INTEGER_set(key_desc->keymaster_version,
1032                           version_to_attestation_km_version(context.GetKmVersion())) ||
1033         !ASN1_ENUMERATED_set(key_desc->keymaster_security_level, context.GetSecurityLevel())) {
1034         return TranslateLastOpenSslError();
1035     }
1036 
1037     keymaster_blob_t attestation_challenge = {nullptr, 0};
1038     if (!attestation_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge)) {
1039         return KM_ERROR_ATTESTATION_CHALLENGE_MISSING;
1040     }
1041 
1042     if (!is_valid_attestation_challenge(attestation_challenge)) {
1043         return KM_ERROR_INVALID_INPUT_LENGTH;
1044     }
1045 
1046     if (!ASN1_OCTET_STRING_set(key_desc->attestation_challenge, attestation_challenge.data,
1047                                attestation_challenge.data_length)) {
1048         return TranslateLastOpenSslError();
1049     }
1050 
1051     keymaster_blob_t attestation_app_id;
1052     if (!attestation_params.GetTagValue(TAG_ATTESTATION_APPLICATION_ID, &attestation_app_id)) {
1053         return KM_ERROR_ATTESTATION_APPLICATION_ID_MISSING;
1054     }
1055     sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_app_id);
1056 
1057     error = context.VerifyAndCopyDeviceIds(
1058         attestation_params,
1059         context.GetSecurityLevel() == KM_SECURITY_LEVEL_SOFTWARE ? &sw_enforced : &tee_enforced);
1060     if (error == KM_ERROR_UNIMPLEMENTED) {
1061         // The KeymasterContext implementation does not support device ID attestation. Bail out if
1062         // device ID attestation is being attempted.
1063         for (const auto& tag : kDeviceAttestationTags) {
1064             if (attestation_params.find(tag) != -1) {
1065                 return KM_ERROR_CANNOT_ATTEST_IDS;
1066             }
1067         }
1068     } else if (error != KM_ERROR_OK) {
1069         return error;
1070     }
1071 
1072     if (attestation_params.Contains(TAG_DEVICE_UNIQUE_ATTESTATION) &&
1073         context.GetSecurityLevel() == KM_SECURITY_LEVEL_STRONGBOX) {
1074         tee_enforced.push_back(TAG_DEVICE_UNIQUE_ATTESTATION);
1075     };
1076 
1077     error = build_auth_list(sw_enforced, key_desc->software_enforced);
1078     if (error != KM_ERROR_OK) return error;
1079 
1080     error = build_auth_list(tee_enforced, key_desc->tee_enforced);
1081     if (error != KM_ERROR_OK) return error;
1082 
1083     if (attestation_params.GetTagValue(TAG_INCLUDE_UNIQUE_ID)) {
1084         uint64_t creation_datetime;
1085         // Only check sw_enforced for TAG_CREATION_DATETIME, since it shouldn't be in tee_enforced,
1086         // since this implementation has no secure wall clock.
1087         if (!sw_enforced.GetTagValue(TAG_CREATION_DATETIME, &creation_datetime)) {
1088             LOG_E("Unique ID cannot be created without creation datetime", 0);
1089             return KM_ERROR_INVALID_KEY_BLOB;
1090         }
1091 
1092         Buffer unique_id = context.GenerateUniqueId(
1093             creation_datetime, attestation_app_id,
1094             attestation_params.GetTagValue(TAG_RESET_SINCE_ID_ROTATION), &error);
1095         if (error != KM_ERROR_OK) return error;
1096 
1097         key_desc->unique_id = ASN1_OCTET_STRING_new();
1098         if (!key_desc->unique_id ||
1099             !ASN1_OCTET_STRING_set(key_desc->unique_id, unique_id.peek_read(),
1100                                    unique_id.available_read()))
1101             return TranslateLastOpenSslError();
1102     }
1103 
1104     int len = i2d_KM_KEY_DESCRIPTION(key_desc.get(), nullptr);
1105     if (len < 0) return TranslateLastOpenSslError();
1106     *asn1_key_desc_len = len;
1107     asn1_key_desc->reset(new (std::nothrow) uint8_t[*asn1_key_desc_len]);
1108     if (!asn1_key_desc->get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1109     uint8_t* p = asn1_key_desc->get();
1110     len = i2d_KM_KEY_DESCRIPTION(key_desc.get(), &p);
1111     if (len < 0) return TranslateLastOpenSslError();
1112 
1113     return KM_ERROR_OK;
1114 }
1115 
1116 // 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)1117 static bool get_repeated_enums(const ASN1_INTEGER_SET* stack, keymaster_tag_t tag,
1118                                AuthorizationSet* auth_list) {
1119     ASSERT_OR_RETURN_ERROR(keymaster_tag_get_type(tag) == KM_ENUM_REP, KM_ERROR_INVALID_TAG);
1120     for (size_t i = 0; i < sk_ASN1_INTEGER_num(stack); ++i) {
1121         if (!auth_list->push_back(
1122                 keymaster_param_enum(tag, ASN1_INTEGER_get(sk_ASN1_INTEGER_value(stack, i)))))
1123             return false;
1124     }
1125     return true;
1126 }
1127 
1128 // Add the specified integer tag/value pair to auth_list.
1129 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)1130 static bool get_enum(const ASN1_INTEGER* asn1_int, TypedEnumTag<Type, Tag, KeymasterEnum> tag,
1131                      AuthorizationSet* auth_list) {
1132     if (!asn1_int) return true;
1133     return auth_list->push_back(tag, static_cast<KeymasterEnum>(ASN1_INTEGER_get(asn1_int)));
1134 }
1135 
1136 // Add the specified ulong tag/value pair to auth_list.
get_ulong(const ASN1_INTEGER * asn1_int,keymaster_tag_t tag,AuthorizationSet * auth_list)1137 static bool get_ulong(const ASN1_INTEGER* asn1_int, keymaster_tag_t tag,
1138                       AuthorizationSet* auth_list) {
1139     if (!asn1_int) return true;
1140     UniquePtr<BIGNUM, BIGNUM_Delete> bn(ASN1_INTEGER_to_BN(asn1_int, nullptr));
1141     if (!bn.get()) return false;
1142     uint64_t ulong = 0;
1143     BN_get_u64(bn.get(), &ulong);
1144     return auth_list->push_back(keymaster_param_long(tag, ulong));
1145 }
1146 
1147 // 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)1148 keymaster_error_t extract_auth_list(const KM_AUTH_LIST* record, AuthorizationSet* auth_list) {
1149     if (!record) return KM_ERROR_OK;
1150 
1151     // Purpose
1152     if (!get_repeated_enums(record->purpose, TAG_PURPOSE, auth_list)) {
1153         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1154     }
1155 
1156     // Algorithm
1157     if (!get_enum(record->algorithm, TAG_ALGORITHM, auth_list)) {
1158         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1159     }
1160 
1161     // Key size
1162     if (record->key_size &&
1163         !auth_list->push_back(TAG_KEY_SIZE, ASN1_INTEGER_get(record->key_size))) {
1164         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1165     }
1166 
1167     // Block mode
1168     if (!get_repeated_enums(record->block_mode, TAG_BLOCK_MODE, auth_list)) {
1169         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1170     }
1171 
1172     // Digest
1173     if (!get_repeated_enums(record->digest, TAG_DIGEST, auth_list)) {
1174         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1175     }
1176 
1177     // Padding
1178     if (!get_repeated_enums(record->padding, TAG_PADDING, auth_list)) {
1179         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1180     }
1181 
1182     // Caller nonce
1183     if (record->caller_nonce && !auth_list->push_back(TAG_CALLER_NONCE)) {
1184         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1185     }
1186 
1187     // Min mac length
1188     if (!get_ulong(record->min_mac_length, TAG_MIN_MAC_LENGTH, auth_list)) {
1189         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1190     }
1191 
1192     // EC curve
1193     if (!get_enum(record->ec_curve, TAG_EC_CURVE, auth_list)) {
1194         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1195     }
1196 
1197     // RSA public exponent
1198     if (!get_ulong(record->rsa_public_exponent, TAG_RSA_PUBLIC_EXPONENT, auth_list)) {
1199         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1200     }
1201 
1202     // Rsa Oaep Mgf Digest
1203     if (!get_repeated_enums(record->mgf_digest, TAG_RSA_OAEP_MGF_DIGEST, auth_list)) {
1204         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1205     }
1206 
1207     // Rollback resistance
1208     if (record->rollback_resistance && !auth_list->push_back(TAG_ROLLBACK_RESISTANCE)) {
1209         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1210     }
1211 
1212     // Early boot only
1213     if (record->early_boot_only && !auth_list->push_back(TAG_EARLY_BOOT_ONLY)) {
1214         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1215     }
1216 
1217     // Active date time
1218     if (!get_ulong(record->active_date_time, TAG_ACTIVE_DATETIME, auth_list)) {
1219         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1220     }
1221 
1222     // Origination expire date time
1223     if (!get_ulong(record->origination_expire_date_time, TAG_ORIGINATION_EXPIRE_DATETIME,
1224                    auth_list)) {
1225         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1226     }
1227 
1228     // Usage Expire date time
1229     if (!get_ulong(record->usage_expire_date_time, TAG_USAGE_EXPIRE_DATETIME, auth_list)) {
1230         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1231     }
1232 
1233     // Usage count limit
1234     if (record->usage_count_limit &&
1235         !auth_list->push_back(TAG_USAGE_COUNT_LIMIT, ASN1_INTEGER_get(record->usage_count_limit))) {
1236         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1237     }
1238 
1239     // No auth required
1240     if (record->no_auth_required && !auth_list->push_back(TAG_NO_AUTH_REQUIRED)) {
1241         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1242     }
1243 
1244     // User auth type
1245     if (!get_enum(record->user_auth_type, TAG_USER_AUTH_TYPE, auth_list)) {
1246         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1247     }
1248 
1249     // Auth timeout
1250     if (record->auth_timeout &&
1251         !auth_list->push_back(TAG_AUTH_TIMEOUT, ASN1_INTEGER_get(record->auth_timeout))) {
1252         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1253     }
1254 
1255     // Allow while on body
1256     if (record->allow_while_on_body && !auth_list->push_back(TAG_ALLOW_WHILE_ON_BODY)) {
1257         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1258     }
1259 
1260     // trusted user presence required
1261     if (record->trusted_user_presence_required &&
1262         !auth_list->push_back(TAG_TRUSTED_USER_PRESENCE_REQUIRED)) {
1263         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1264     }
1265 
1266     // trusted confirmation required
1267     if (record->trusted_confirmation_required &&
1268         !auth_list->push_back(TAG_TRUSTED_CONFIRMATION_REQUIRED)) {
1269         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1270     }
1271 
1272     // Unlocked device required
1273     if (record->unlocked_device_required && !auth_list->push_back(TAG_UNLOCKED_DEVICE_REQUIRED)) {
1274         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1275     }
1276 
1277     // All applications
1278     if (record->all_applications && !auth_list->push_back(TAG_ALL_APPLICATIONS)) {
1279         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1280     }
1281 
1282     // Application ID
1283     if (record->application_id &&
1284         !auth_list->push_back(TAG_APPLICATION_ID, record->application_id->data,
1285                               record->application_id->length)) {
1286         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1287     }
1288 
1289     // Creation date time
1290     if (!get_ulong(record->creation_date_time, TAG_CREATION_DATETIME, auth_list)) {
1291         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1292     }
1293 
1294     // Origin
1295     if (!get_enum(record->origin, TAG_ORIGIN, auth_list)) {
1296         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1297     }
1298 
1299     // Rollback resistant
1300     if (record->rollback_resistant && !auth_list->push_back(TAG_ROLLBACK_RESISTANT)) {
1301         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1302     }
1303 
1304     // Root of trust
1305     if (record->root_of_trust) {
1306         KM_ROOT_OF_TRUST* rot = record->root_of_trust;
1307         if (!rot->verified_boot_key) return KM_ERROR_INVALID_KEY_BLOB;
1308 
1309         // Other root of trust fields are not mapped to auth set entries.
1310     }
1311 
1312     // OS Version
1313     if (record->os_version &&
1314         !auth_list->push_back(TAG_OS_VERSION, ASN1_INTEGER_get(record->os_version))) {
1315         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1316     }
1317 
1318     // OS Patch level
1319     if (record->os_patchlevel &&
1320         !auth_list->push_back(TAG_OS_PATCHLEVEL, ASN1_INTEGER_get(record->os_patchlevel))) {
1321         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1322     }
1323 
1324     // attestation application Id
1325     if (record->attestation_application_id &&
1326         !auth_list->push_back(TAG_ATTESTATION_APPLICATION_ID,
1327                               record->attestation_application_id->data,
1328                               record->attestation_application_id->length)) {
1329         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1330     }
1331 
1332     // Brand name
1333     if (record->attestation_id_brand &&
1334         !auth_list->push_back(TAG_ATTESTATION_ID_BRAND, record->attestation_id_brand->data,
1335                               record->attestation_id_brand->length)) {
1336         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1337     }
1338 
1339     // Device name
1340     if (record->attestation_id_device &&
1341         !auth_list->push_back(TAG_ATTESTATION_ID_DEVICE, record->attestation_id_device->data,
1342                               record->attestation_id_device->length)) {
1343         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1344     }
1345 
1346     // Product name
1347     if (record->attestation_id_product &&
1348         !auth_list->push_back(TAG_ATTESTATION_ID_PRODUCT, record->attestation_id_product->data,
1349                               record->attestation_id_product->length)) {
1350         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1351     }
1352 
1353     // Serial number
1354     if (record->attestation_id_serial &&
1355         !auth_list->push_back(TAG_ATTESTATION_ID_SERIAL, record->attestation_id_serial->data,
1356                               record->attestation_id_serial->length)) {
1357         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1358     }
1359 
1360     // IMEI
1361     if (record->attestation_id_imei &&
1362         !auth_list->push_back(TAG_ATTESTATION_ID_IMEI, record->attestation_id_imei->data,
1363                               record->attestation_id_imei->length)) {
1364         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1365     }
1366 
1367     // MEID
1368     if (record->attestation_id_meid &&
1369         !auth_list->push_back(TAG_ATTESTATION_ID_MEID, record->attestation_id_meid->data,
1370                               record->attestation_id_meid->length)) {
1371         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1372     }
1373 
1374     // Manufacturer name
1375     if (record->attestation_id_manufacturer &&
1376         !auth_list->push_back(TAG_ATTESTATION_ID_MANUFACTURER,
1377                               record->attestation_id_manufacturer->data,
1378                               record->attestation_id_manufacturer->length)) {
1379         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1380     }
1381 
1382     // Model name
1383     if (record->attestation_id_model &&
1384         !auth_list->push_back(TAG_ATTESTATION_ID_MODEL, record->attestation_id_model->data,
1385                               record->attestation_id_model->length)) {
1386         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1387     }
1388 
1389     // vendor patch level
1390     if (record->vendor_patchlevel &&
1391         !auth_list->push_back(TAG_VENDOR_PATCHLEVEL, ASN1_INTEGER_get(record->vendor_patchlevel))) {
1392         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1393     }
1394 
1395     // boot patch level
1396     if (record->boot_patch_level &&
1397         !auth_list->push_back(TAG_BOOT_PATCHLEVEL, ASN1_INTEGER_get(record->boot_patch_level))) {
1398         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1399     }
1400 
1401     // device unique attestation
1402     if (record->device_unique_attestation && !auth_list->push_back(TAG_DEVICE_UNIQUE_ATTESTATION)) {
1403         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1404     }
1405 
1406     // identity credential key
1407     if (record->identity_credential_key && !auth_list->push_back(TAG_IDENTITY_CREDENTIAL_KEY)) {
1408         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1409     }
1410 
1411     // Second IMEI
1412     if (record->attestation_id_second_imei &&
1413         !auth_list->push_back(TAG_ATTESTATION_ID_SECOND_IMEI,
1414                               record->attestation_id_second_imei->data,
1415                               record->attestation_id_second_imei->length)) {
1416         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1417     }
1418 
1419     return KM_ERROR_OK;
1420 }
1421 
1422 // Parse the DER-encoded attestation record, placing the results in keymaster_version,
1423 // 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)1424 keymaster_error_t parse_attestation_record(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
1425                                            uint32_t* attestation_version,  //
1426                                            keymaster_security_level_t* attestation_security_level,
1427                                            uint32_t* keymaster_version,
1428                                            keymaster_security_level_t* keymaster_security_level,
1429                                            keymaster_blob_t* attestation_challenge,
1430                                            AuthorizationSet* software_enforced,
1431                                            AuthorizationSet* tee_enforced,
1432                                            keymaster_blob_t* unique_id) {
1433     const uint8_t* p = asn1_key_desc;
1434     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> record(
1435         d2i_KM_KEY_DESCRIPTION(nullptr, &p, asn1_key_desc_len));
1436     if (!record.get()) return TranslateLastOpenSslError();
1437 
1438     *attestation_version = ASN1_INTEGER_get(record->attestation_version);
1439     *attestation_security_level = static_cast<keymaster_security_level_t>(
1440         ASN1_ENUMERATED_get(record->attestation_security_level));
1441     *keymaster_version = ASN1_INTEGER_get(record->keymaster_version);
1442     *keymaster_security_level = static_cast<keymaster_security_level_t>(
1443         ASN1_ENUMERATED_get(record->keymaster_security_level));
1444 
1445     attestation_challenge->data =
1446         dup_buffer(record->attestation_challenge->data, record->attestation_challenge->length);
1447     attestation_challenge->data_length = record->attestation_challenge->length;
1448 
1449     unique_id->data = dup_buffer(record->unique_id->data, record->unique_id->length);
1450     unique_id->data_length = record->unique_id->length;
1451 
1452     keymaster_error_t error = extract_auth_list(record->software_enforced, software_enforced);
1453     if (error != KM_ERROR_OK) return error;
1454 
1455     return extract_auth_list(record->tee_enforced, tee_enforced);
1456 }
1457 
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)1458 keymaster_error_t parse_root_of_trust(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
1459                                       keymaster_blob_t* verified_boot_key,
1460                                       keymaster_verified_boot_t* verified_boot_state,
1461                                       bool* device_locked) {
1462     const uint8_t* p = asn1_key_desc;
1463     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> record(
1464         d2i_KM_KEY_DESCRIPTION(nullptr, &p, asn1_key_desc_len));
1465     if (!record.get()) {
1466         return TranslateLastOpenSslError();
1467     }
1468     if (!record->tee_enforced) {
1469         return KM_ERROR_INVALID_ARGUMENT;
1470     }
1471     if (!record->tee_enforced->root_of_trust) {
1472         return KM_ERROR_INVALID_ARGUMENT;
1473     }
1474     if (!record->tee_enforced->root_of_trust->verified_boot_key) {
1475         return KM_ERROR_INVALID_ARGUMENT;
1476     }
1477     KM_ROOT_OF_TRUST* root_of_trust = record->tee_enforced->root_of_trust;
1478     verified_boot_key->data = dup_buffer(root_of_trust->verified_boot_key->data,
1479                                          root_of_trust->verified_boot_key->length);
1480     verified_boot_key->data_length = root_of_trust->verified_boot_key->length;
1481     *verified_boot_state = static_cast<keymaster_verified_boot_t>(
1482         ASN1_ENUMERATED_get(root_of_trust->verified_boot_state));
1483     *device_locked = root_of_trust->device_locked;
1484     return KM_ERROR_OK;
1485 }
1486 
1487 // Parse the EAT-encoded attestation record, placing the results in keymaster_version,
1488 // 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)1489 keymaster_error_t parse_eat_record(
1490     const uint8_t* eat_key_desc, size_t eat_key_desc_len, uint32_t* attestation_version,
1491     keymaster_security_level_t* attestation_security_level, uint32_t* keymaster_version,
1492     keymaster_security_level_t* keymaster_security_level, keymaster_blob_t* attestation_challenge,
1493     AuthorizationSet* software_enforced, AuthorizationSet* tee_enforced,
1494     keymaster_blob_t* unique_id, keymaster_blob_t* verified_boot_key,
1495     keymaster_verified_boot_t* verified_boot_state, bool* device_locked,
1496     std::vector<int64_t>* unexpected_claims) {
1497     auto [top_level_item, next_pos, error] = cppbor::parse(eat_key_desc, eat_key_desc_len);
1498     ASSERT_OR_RETURN_ERROR(top_level_item, KM_ERROR_INVALID_TAG);
1499     const cppbor::Map* eat_map = top_level_item->asMap();
1500     ASSERT_OR_RETURN_ERROR(eat_map, KM_ERROR_INVALID_TAG);
1501     bool verified_or_self_signed = false;
1502 
1503     for (size_t i = 0; i < eat_map->size(); i++) {
1504         auto& [key_item, value_item] = (*eat_map)[i];
1505         const cppbor::Int* key = key_item->asInt();
1506         ASSERT_OR_RETURN_ERROR(key, (KM_ERROR_INVALID_TAG));
1507 
1508         // The following values will either hold the typed value, or be null (if not the right
1509         // type).
1510         const cppbor::Int* int_value = value_item->asInt();
1511         const cppbor::Bstr* bstr_value = value_item->asBstr();
1512         const cppbor::Simple* simple_value = value_item->asSimple();
1513         const cppbor::Array* array_value = value_item->asArray();
1514         const cppbor::Map* map_value = value_item->asMap();
1515 
1516         keymaster_error_t error;
1517         switch ((EatClaim)key->value()) {
1518         default:
1519             unexpected_claims->push_back(key->value());
1520             break;
1521         case EatClaim::ATTESTATION_VERSION:
1522             ASSERT_OR_RETURN_ERROR(int_value, KM_ERROR_INVALID_TAG);
1523             *attestation_version = int_value->value();
1524             break;
1525         case EatClaim::SECURITY_LEVEL:
1526             ASSERT_OR_RETURN_ERROR(int_value, KM_ERROR_INVALID_TAG);
1527             switch ((EatSecurityLevel)int_value->value()) {
1528             // TODO: Is my assumption correct that the security level of the attestation data should
1529             // always be equal to the security level of keymint, as the attestation data always
1530             // lives in the top-level module?
1531             case EatSecurityLevel::UNRESTRICTED:
1532                 *keymaster_security_level = *attestation_security_level =
1533                     KM_SECURITY_LEVEL_SOFTWARE;
1534                 break;
1535             case EatSecurityLevel::SECURE_RESTRICTED:
1536                 *keymaster_security_level = *attestation_security_level =
1537                     KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
1538                 break;
1539             case EatSecurityLevel::HARDWARE:
1540                 *keymaster_security_level = *attestation_security_level =
1541                     KM_SECURITY_LEVEL_STRONGBOX;
1542                 break;
1543             default:
1544                 return KM_ERROR_INVALID_TAG;
1545             }
1546             break;
1547         case EatClaim::KEYMASTER_VERSION:
1548             ASSERT_OR_RETURN_ERROR(int_value, KM_ERROR_INVALID_TAG);
1549             *keymaster_version = int_value->value();
1550             break;
1551         case EatClaim::SUBMODS:
1552             ASSERT_OR_RETURN_ERROR(map_value, KM_ERROR_INVALID_TAG);
1553             for (size_t j = 0; j < map_value->size(); j++) {
1554                 auto& [submod_key, submod_value] = (*map_value)[j];
1555                 const cppbor::Map* submod_map = submod_value->asMap();
1556                 ASSERT_OR_RETURN_ERROR(submod_map, KM_ERROR_INVALID_TAG);
1557                 error = parse_eat_submod(submod_map, software_enforced, tee_enforced);
1558                 if (error != KM_ERROR_OK) return error;
1559             }
1560             break;
1561         case EatClaim::CTI:
1562             error = bstr_to_blob(bstr_value, unique_id);
1563             if (error != KM_ERROR_OK) return error;
1564             break;
1565         case EatClaim::NONCE:
1566             error = bstr_to_blob(bstr_value, attestation_challenge);
1567             if (error != KM_ERROR_OK) return error;
1568             break;
1569         case EatClaim::VERIFIED_BOOT_KEY:
1570             error = bstr_to_blob(bstr_value, verified_boot_key);
1571             if (error != KM_ERROR_OK) return error;
1572             break;
1573         case EatClaim::VERIFIED_BOOT_HASH:
1574             // Not parsing this for now.
1575             break;
1576         case EatClaim::DEVICE_UNIQUE_ATTESTATION:
1577             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1578                 return KM_ERROR_INVALID_TAG;
1579             }
1580             // Not parsing this for now.
1581             break;
1582         case EatClaim::DEVICE_LOCKED:
1583             ASSERT_OR_RETURN_ERROR(simple_value->asBool(), KM_ERROR_INVALID_TAG);
1584             *device_locked = simple_value->asBool()->value();
1585             break;
1586         case EatClaim::BOOT_STATE:
1587             ASSERT_OR_RETURN_ERROR(array_value, KM_ERROR_INVALID_TAG);
1588             ASSERT_OR_RETURN_ERROR(array_value->size() == 5, KM_ERROR_INVALID_TAG);
1589             ASSERT_OR_RETURN_ERROR((*array_value)[4]->asSimple()->asBool()->value() == false,
1590                                    KM_ERROR_INVALID_TAG);
1591             verified_or_self_signed = (*array_value)[0]->asSimple()->asBool()->value();
1592             ASSERT_OR_RETURN_ERROR(verified_or_self_signed ==
1593                                        (*array_value)[1]->asSimple()->asBool()->value(),
1594                                    KM_ERROR_INVALID_TAG);
1595             ASSERT_OR_RETURN_ERROR(verified_or_self_signed ==
1596                                        (*array_value)[2]->asSimple()->asBool()->value(),
1597                                    KM_ERROR_INVALID_TAG);
1598             ASSERT_OR_RETURN_ERROR(verified_or_self_signed ==
1599                                        (*array_value)[3]->asSimple()->asBool()->value(),
1600                                    KM_ERROR_INVALID_TAG);
1601             break;
1602         case EatClaim::OFFICIAL_BUILD:
1603             *verified_boot_state = KM_VERIFIED_BOOT_VERIFIED;
1604             break;
1605         }
1606     }
1607 
1608     if (*verified_boot_state == KM_VERIFIED_BOOT_VERIFIED) {
1609         (void)(verified_boot_state);
1610         // TODO: re-enable this
1611         // ASSERT_OR_RETURN_ERROR(verified_or_self_signed, KM_ERROR_INVALID_TAG);
1612     } else {
1613         *verified_boot_state =
1614             verified_or_self_signed ? KM_VERIFIED_BOOT_SELF_SIGNED : KM_VERIFIED_BOOT_UNVERIFIED;
1615     }
1616 
1617     return KM_ERROR_OK;
1618 }
1619 
parse_submod_values(AuthorizationSetBuilder * set_builder,int * auth_set_security_level,const cppbor::Map * submod_map)1620 keymaster_error_t parse_submod_values(AuthorizationSetBuilder* set_builder,
1621                                       int* auth_set_security_level, const cppbor::Map* submod_map) {
1622     ASSERT_OR_RETURN_ERROR(set_builder, KM_ERROR_UNEXPECTED_NULL_POINTER);
1623     for (size_t i = 0; i < submod_map->size(); i++) {
1624         auto& [key_item, value_item] = (*submod_map)[i];
1625         const cppbor::Int* key_int = key_item->asInt();
1626         ASSERT_OR_RETURN_ERROR(key_int, KM_ERROR_INVALID_TAG);
1627         int key = key_int->value();
1628         keymaster_error_t error;
1629         keymaster_blob_t blob;
1630 
1631         switch ((EatClaim)key) {
1632         default:
1633             return KM_ERROR_INVALID_TAG;
1634         case EatClaim::ALGORITHM:
1635             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1636             set_builder->Authorization(
1637                 TAG_ALGORITHM, static_cast<keymaster_algorithm_t>(value_item->asInt()->value()));
1638             break;
1639         case EatClaim::EC_CURVE:
1640             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1641             set_builder->Authorization(
1642                 TAG_EC_CURVE, static_cast<keymaster_ec_curve_t>(value_item->asInt()->value()));
1643             break;
1644         case EatClaim::USER_AUTH_TYPE:
1645             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1646             set_builder->Authorization(TAG_USER_AUTH_TYPE, static_cast<hw_authenticator_type_t>(
1647                                                                value_item->asInt()->value()));
1648             break;
1649         case EatClaim::ORIGIN:
1650             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1651             set_builder->Authorization(
1652                 TAG_ORIGIN, static_cast<keymaster_key_origin_t>(value_item->asInt()->value()));
1653             break;
1654         case EatClaim::PURPOSE:
1655             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1656                 set_builder->Authorization(TAG_PURPOSE,
1657                                            static_cast<keymaster_purpose_t>(
1658                                                (*value_item->asArray())[j]->asInt()->value()));
1659             }
1660             break;
1661         case EatClaim::PADDING:
1662             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1663                 set_builder->Authorization(TAG_PADDING,
1664                                            static_cast<keymaster_padding_t>(
1665                                                (*value_item->asArray())[j]->asInt()->value()));
1666             }
1667             break;
1668         case EatClaim::DIGEST:
1669             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1670                 set_builder->Authorization(
1671                     TAG_DIGEST,
1672                     static_cast<keymaster_digest_t>((*value_item->asArray())[j]->asInt()->value()));
1673             }
1674             break;
1675         case EatClaim::BLOCK_MODE:
1676             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1677                 set_builder->Authorization(TAG_BLOCK_MODE,
1678                                            static_cast<keymaster_block_mode_t>(
1679                                                (*value_item->asArray())[j]->asInt()->value()));
1680             }
1681             break;
1682         case EatClaim::KEY_SIZE:
1683             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1684             set_builder->Authorization(TAG_KEY_SIZE, value_item->asInt()->value());
1685             break;
1686         case EatClaim::AUTH_TIMEOUT:
1687             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1688             set_builder->Authorization(TAG_AUTH_TIMEOUT, value_item->asInt()->value());
1689             break;
1690         case EatClaim::OS_VERSION:
1691             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1692             set_builder->Authorization(TAG_OS_VERSION, value_item->asInt()->value());
1693             break;
1694         case EatClaim::OS_PATCHLEVEL:
1695             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1696             set_builder->Authorization(TAG_OS_PATCHLEVEL, value_item->asInt()->value());
1697             break;
1698         case EatClaim::MIN_MAC_LENGTH:
1699             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1700             set_builder->Authorization(TAG_MIN_MAC_LENGTH, value_item->asInt()->value());
1701             break;
1702         case EatClaim::BOOT_PATCHLEVEL:
1703             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1704             set_builder->Authorization(TAG_BOOT_PATCHLEVEL, value_item->asInt()->value());
1705             break;
1706         case EatClaim::VENDOR_PATCHLEVEL:
1707             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1708             set_builder->Authorization(TAG_VENDOR_PATCHLEVEL, value_item->asInt()->value());
1709             break;
1710         case EatClaim::RSA_PUBLIC_EXPONENT:
1711             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1712             set_builder->Authorization(TAG_RSA_PUBLIC_EXPONENT, value_item->asInt()->value());
1713             break;
1714         case EatClaim::ACTIVE_DATETIME:
1715             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1716             set_builder->Authorization(TAG_ACTIVE_DATETIME, value_item->asInt()->value());
1717             break;
1718         case EatClaim::ORIGINATION_EXPIRE_DATETIME:
1719             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1720             set_builder->Authorization(TAG_ORIGINATION_EXPIRE_DATETIME,
1721                                        value_item->asInt()->value());
1722             break;
1723         case EatClaim::USAGE_EXPIRE_DATETIME:
1724             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1725             set_builder->Authorization(TAG_USAGE_EXPIRE_DATETIME, value_item->asInt()->value());
1726             break;
1727         case EatClaim::IAT:
1728             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1729             set_builder->Authorization(TAG_CREATION_DATETIME, value_item->asInt()->value());
1730             break;
1731         case EatClaim::NO_AUTH_REQUIRED:
1732             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1733                 return KM_ERROR_INVALID_TAG;
1734             }
1735             set_builder->Authorization(TAG_NO_AUTH_REQUIRED);
1736             break;
1737         case EatClaim::ALL_APPLICATIONS:
1738             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1739                 return KM_ERROR_INVALID_TAG;
1740             }
1741             set_builder->Authorization(TAG_ALL_APPLICATIONS);
1742             break;
1743         case EatClaim::ROLLBACK_RESISTANT:
1744             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1745                 return KM_ERROR_INVALID_TAG;
1746             }
1747             set_builder->Authorization(TAG_ROLLBACK_RESISTANT);
1748             break;
1749         case EatClaim::ALLOW_WHILE_ON_BODY:
1750             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1751                 return KM_ERROR_INVALID_TAG;
1752             }
1753             set_builder->Authorization(TAG_ALLOW_WHILE_ON_BODY);
1754             break;
1755         case EatClaim::UNLOCKED_DEVICE_REQUIRED:
1756             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1757                 return KM_ERROR_INVALID_TAG;
1758             }
1759             set_builder->Authorization(TAG_UNLOCKED_DEVICE_REQUIRED);
1760             break;
1761         case EatClaim::CALLER_NONCE:
1762             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1763                 return KM_ERROR_INVALID_TAG;
1764             }
1765             set_builder->Authorization(TAG_CALLER_NONCE);
1766             break;
1767         case EatClaim::TRUSTED_CONFIRMATION_REQUIRED:
1768             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1769                 return KM_ERROR_INVALID_TAG;
1770             }
1771             set_builder->Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED);
1772             break;
1773         case EatClaim::EARLY_BOOT_ONLY:
1774             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1775                 return KM_ERROR_INVALID_TAG;
1776             }
1777             set_builder->Authorization(TAG_EARLY_BOOT_ONLY);
1778             break;
1779         case EatClaim::IDENTITY_CREDENTIAL_KEY:
1780             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1781                 return KM_ERROR_INVALID_TAG;
1782             }
1783             set_builder->Authorization(TAG_IDENTITY_CREDENTIAL_KEY);
1784             break;
1785         case EatClaim::STORAGE_KEY:
1786             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1787                 return KM_ERROR_INVALID_TAG;
1788             }
1789             set_builder->Authorization(TAG_STORAGE_KEY);
1790             break;
1791         case EatClaim::TRUSTED_USER_PRESENCE_REQUIRED:
1792             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1793                 return KM_ERROR_INVALID_TAG;
1794             }
1795             set_builder->Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED);
1796             break;
1797         case EatClaim::DEVICE_UNIQUE_ATTESTATION:
1798             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1799                 return KM_ERROR_INVALID_TAG;
1800             }
1801             set_builder->Authorization(TAG_DEVICE_UNIQUE_ATTESTATION);
1802             break;
1803         case EatClaim::APPLICATION_ID:
1804             error = bstr_to_blob(value_item->asBstr(), &blob);
1805             if (error != KM_ERROR_OK) return error;
1806             set_builder->Authorization(TAG_APPLICATION_ID, blob);
1807             break;
1808         case EatClaim::ATTESTATION_APPLICATION_ID:
1809             error = bstr_to_blob(value_item->asBstr(), &blob);
1810             if (error != KM_ERROR_OK) return error;
1811             set_builder->Authorization(TAG_ATTESTATION_APPLICATION_ID, blob);
1812             break;
1813         case EatClaim::ATTESTATION_ID_BRAND:
1814             error = bstr_to_blob(value_item->asBstr(), &blob);
1815             if (error != KM_ERROR_OK) return error;
1816             set_builder->Authorization(TAG_ATTESTATION_ID_BRAND, blob);
1817             break;
1818         case EatClaim::ATTESTATION_ID_DEVICE:
1819             error = bstr_to_blob(value_item->asBstr(), &blob);
1820             if (error != KM_ERROR_OK) return error;
1821             set_builder->Authorization(TAG_ATTESTATION_ID_DEVICE, blob);
1822             break;
1823         case EatClaim::ATTESTATION_ID_PRODUCT:
1824             error = bstr_to_blob(value_item->asBstr(), &blob);
1825             if (error != KM_ERROR_OK) return error;
1826             set_builder->Authorization(TAG_ATTESTATION_ID_PRODUCT, blob);
1827             break;
1828         case EatClaim::ATTESTATION_ID_SERIAL:
1829             error = bstr_to_blob(value_item->asBstr(), &blob);
1830             if (error != KM_ERROR_OK) return error;
1831             set_builder->Authorization(TAG_ATTESTATION_ID_SERIAL, blob);
1832             break;
1833         case EatClaim::UEID:
1834             error = ueid_to_imei_blob(value_item->asBstr(), &blob);
1835             if (error != KM_ERROR_OK) return error;
1836             set_builder->Authorization(TAG_ATTESTATION_ID_IMEI, blob);
1837             break;
1838         case EatClaim::ATTESTATION_ID_MEID:
1839             error = bstr_to_blob(value_item->asBstr(), &blob);
1840             if (error != KM_ERROR_OK) return error;
1841             set_builder->Authorization(TAG_ATTESTATION_ID_MEID, blob);
1842             break;
1843         case EatClaim::ATTESTATION_ID_MANUFACTURER:
1844             error = bstr_to_blob(value_item->asBstr(), &blob);
1845             if (error != KM_ERROR_OK) return error;
1846             set_builder->Authorization(TAG_ATTESTATION_ID_MANUFACTURER, blob);
1847             break;
1848         case EatClaim::ATTESTATION_ID_MODEL:
1849             error = bstr_to_blob(value_item->asBstr(), &blob);
1850             if (error != KM_ERROR_OK) return error;
1851             set_builder->Authorization(TAG_ATTESTATION_ID_MODEL, blob);
1852             break;
1853         case EatClaim::CONFIRMATION_TOKEN:
1854             error = bstr_to_blob(value_item->asBstr(), &blob);
1855             if (error != KM_ERROR_OK) return error;
1856             set_builder->Authorization(TAG_CONFIRMATION_TOKEN, blob);
1857             break;
1858         case EatClaim::SECURITY_LEVEL:
1859             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1860             *auth_set_security_level = value_item->asInt()->value();
1861         }
1862     }
1863 
1864     return KM_ERROR_OK;
1865 }
1866 
parse_eat_submod(const cppbor::Map * submod_values,AuthorizationSet * software_enforced,AuthorizationSet * tee_enforced)1867 keymaster_error_t parse_eat_submod(const cppbor::Map* submod_values,
1868                                    AuthorizationSet* software_enforced,
1869                                    AuthorizationSet* tee_enforced) {
1870     AuthorizationSetBuilder auth_set_builder;
1871     int auth_set_security_level = 0;
1872     keymaster_error_t error =
1873         parse_submod_values(&auth_set_builder, &auth_set_security_level, submod_values);
1874     if (error) return error;
1875     switch ((EatSecurityLevel)auth_set_security_level) {
1876     case EatSecurityLevel::HARDWARE:
1877         // Hardware attestation should never occur in a submod of another EAT.
1878         [[fallthrough]];
1879     default:
1880         return KM_ERROR_INVALID_TAG;
1881     case EatSecurityLevel::UNRESTRICTED:
1882         *software_enforced = AuthorizationSet(auth_set_builder);
1883         break;
1884     case EatSecurityLevel::SECURE_RESTRICTED:
1885         *tee_enforced = AuthorizationSet(auth_set_builder);
1886         break;
1887     }
1888 
1889     return KM_ERROR_OK;
1890 }
1891 }  // namespace keymaster
1892