• 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");
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");
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         if (!ASN1_OCTET_STRING_set(key_desc->unique_id, unique_id.peek_read(),
1098                                    unique_id.available_read()))
1099             return TranslateLastOpenSslError();
1100     }
1101 
1102     int len = i2d_KM_KEY_DESCRIPTION(key_desc.get(), nullptr);
1103     if (len < 0) return TranslateLastOpenSslError();
1104     *asn1_key_desc_len = len;
1105     asn1_key_desc->reset(new (std::nothrow) uint8_t[*asn1_key_desc_len]);
1106     if (!asn1_key_desc->get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1107     uint8_t* p = asn1_key_desc->get();
1108     len = i2d_KM_KEY_DESCRIPTION(key_desc.get(), &p);
1109     if (len < 0) return TranslateLastOpenSslError();
1110 
1111     return KM_ERROR_OK;
1112 }
1113 
1114 // 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)1115 static bool get_repeated_enums(const ASN1_INTEGER_SET* stack, keymaster_tag_t tag,
1116                                AuthorizationSet* auth_list) {
1117     ASSERT_OR_RETURN_ERROR(keymaster_tag_get_type(tag) == KM_ENUM_REP, KM_ERROR_INVALID_TAG);
1118     for (size_t i = 0; i < sk_ASN1_INTEGER_num(stack); ++i) {
1119         if (!auth_list->push_back(
1120                 keymaster_param_enum(tag, ASN1_INTEGER_get(sk_ASN1_INTEGER_value(stack, i)))))
1121             return false;
1122     }
1123     return true;
1124 }
1125 
1126 // Add the specified integer tag/value pair to auth_list.
1127 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)1128 static bool get_enum(const ASN1_INTEGER* asn1_int, TypedEnumTag<Type, Tag, KeymasterEnum> tag,
1129                      AuthorizationSet* auth_list) {
1130     if (!asn1_int) return true;
1131     return auth_list->push_back(tag, static_cast<KeymasterEnum>(ASN1_INTEGER_get(asn1_int)));
1132 }
1133 
1134 // Add the specified ulong tag/value pair to auth_list.
get_ulong(const ASN1_INTEGER * asn1_int,keymaster_tag_t tag,AuthorizationSet * auth_list)1135 static bool get_ulong(const ASN1_INTEGER* asn1_int, keymaster_tag_t tag,
1136                       AuthorizationSet* auth_list) {
1137     if (!asn1_int) return true;
1138     UniquePtr<BIGNUM, BIGNUM_Delete> bn(ASN1_INTEGER_to_BN(asn1_int, nullptr));
1139     if (!bn.get()) return false;
1140     uint64_t ulong = 0;
1141     BN_get_u64(bn.get(), &ulong);
1142     return auth_list->push_back(keymaster_param_long(tag, ulong));
1143 }
1144 
1145 // 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)1146 keymaster_error_t extract_auth_list(const KM_AUTH_LIST* record, AuthorizationSet* auth_list) {
1147     if (!record) return KM_ERROR_OK;
1148 
1149     // Purpose
1150     if (!get_repeated_enums(record->purpose, TAG_PURPOSE, auth_list)) {
1151         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1152     }
1153 
1154     // Algorithm
1155     if (!get_enum(record->algorithm, TAG_ALGORITHM, auth_list)) {
1156         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1157     }
1158 
1159     // Key size
1160     if (record->key_size &&
1161         !auth_list->push_back(TAG_KEY_SIZE, ASN1_INTEGER_get(record->key_size))) {
1162         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1163     }
1164 
1165     // Block mode
1166     if (!get_repeated_enums(record->block_mode, TAG_BLOCK_MODE, auth_list)) {
1167         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1168     }
1169 
1170     // Digest
1171     if (!get_repeated_enums(record->digest, TAG_DIGEST, auth_list)) {
1172         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1173     }
1174 
1175     // Padding
1176     if (!get_repeated_enums(record->padding, TAG_PADDING, auth_list)) {
1177         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1178     }
1179 
1180     // Caller nonce
1181     if (record->caller_nonce && !auth_list->push_back(TAG_CALLER_NONCE)) {
1182         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1183     }
1184 
1185     // Min mac length
1186     if (!get_ulong(record->min_mac_length, TAG_MIN_MAC_LENGTH, auth_list)) {
1187         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1188     }
1189 
1190     // EC curve
1191     if (!get_enum(record->ec_curve, TAG_EC_CURVE, auth_list)) {
1192         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1193     }
1194 
1195     // RSA public exponent
1196     if (!get_ulong(record->rsa_public_exponent, TAG_RSA_PUBLIC_EXPONENT, auth_list)) {
1197         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1198     }
1199 
1200     // Rsa Oaep Mgf Digest
1201     if (!get_repeated_enums(record->mgf_digest, TAG_RSA_OAEP_MGF_DIGEST, auth_list)) {
1202         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1203     }
1204 
1205     // Rollback resistance
1206     if (record->rollback_resistance && !auth_list->push_back(TAG_ROLLBACK_RESISTANCE)) {
1207         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1208     }
1209 
1210     // Early boot only
1211     if (record->early_boot_only && !auth_list->push_back(TAG_EARLY_BOOT_ONLY)) {
1212         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1213     }
1214 
1215     // Active date time
1216     if (!get_ulong(record->active_date_time, TAG_ACTIVE_DATETIME, auth_list)) {
1217         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1218     }
1219 
1220     // Origination expire date time
1221     if (!get_ulong(record->origination_expire_date_time, TAG_ORIGINATION_EXPIRE_DATETIME,
1222                    auth_list)) {
1223         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1224     }
1225 
1226     // Usage Expire date time
1227     if (!get_ulong(record->usage_expire_date_time, TAG_USAGE_EXPIRE_DATETIME, auth_list)) {
1228         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1229     }
1230 
1231     // Usage count limit
1232     if (record->usage_count_limit &&
1233         !auth_list->push_back(TAG_USAGE_COUNT_LIMIT, ASN1_INTEGER_get(record->usage_count_limit))) {
1234         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1235     }
1236 
1237     // No auth required
1238     if (record->no_auth_required && !auth_list->push_back(TAG_NO_AUTH_REQUIRED)) {
1239         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1240     }
1241 
1242     // User auth type
1243     if (!get_enum(record->user_auth_type, TAG_USER_AUTH_TYPE, auth_list)) {
1244         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1245     }
1246 
1247     // Auth timeout
1248     if (record->auth_timeout &&
1249         !auth_list->push_back(TAG_AUTH_TIMEOUT, ASN1_INTEGER_get(record->auth_timeout))) {
1250         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1251     }
1252 
1253     // Allow while on body
1254     if (record->allow_while_on_body && !auth_list->push_back(TAG_ALLOW_WHILE_ON_BODY)) {
1255         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1256     }
1257 
1258     // trusted user presence required
1259     if (record->trusted_user_presence_required &&
1260         !auth_list->push_back(TAG_TRUSTED_USER_PRESENCE_REQUIRED)) {
1261         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1262     }
1263 
1264     // trusted confirmation required
1265     if (record->trusted_confirmation_required &&
1266         !auth_list->push_back(TAG_TRUSTED_CONFIRMATION_REQUIRED)) {
1267         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1268     }
1269 
1270     // Unlocked device required
1271     if (record->unlocked_device_required && !auth_list->push_back(TAG_UNLOCKED_DEVICE_REQUIRED)) {
1272         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1273     }
1274 
1275     // All applications
1276     if (record->all_applications && !auth_list->push_back(TAG_ALL_APPLICATIONS)) {
1277         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1278     }
1279 
1280     // Application ID
1281     if (record->application_id &&
1282         !auth_list->push_back(TAG_APPLICATION_ID, record->application_id->data,
1283                               record->application_id->length)) {
1284         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1285     }
1286 
1287     // Creation date time
1288     if (!get_ulong(record->creation_date_time, TAG_CREATION_DATETIME, auth_list)) {
1289         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1290     }
1291 
1292     // Origin
1293     if (!get_enum(record->origin, TAG_ORIGIN, auth_list)) {
1294         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1295     }
1296 
1297     // Rollback resistant
1298     if (record->rollback_resistant && !auth_list->push_back(TAG_ROLLBACK_RESISTANT)) {
1299         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1300     }
1301 
1302     // Root of trust
1303     if (record->root_of_trust) {
1304         KM_ROOT_OF_TRUST* rot = record->root_of_trust;
1305         if (!rot->verified_boot_key) return KM_ERROR_INVALID_KEY_BLOB;
1306 
1307         // Other root of trust fields are not mapped to auth set entries.
1308     }
1309 
1310     // OS Version
1311     if (record->os_version &&
1312         !auth_list->push_back(TAG_OS_VERSION, ASN1_INTEGER_get(record->os_version))) {
1313         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1314     }
1315 
1316     // OS Patch level
1317     if (record->os_patchlevel &&
1318         !auth_list->push_back(TAG_OS_PATCHLEVEL, ASN1_INTEGER_get(record->os_patchlevel))) {
1319         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1320     }
1321 
1322     // attestation application Id
1323     if (record->attestation_application_id &&
1324         !auth_list->push_back(TAG_ATTESTATION_APPLICATION_ID,
1325                               record->attestation_application_id->data,
1326                               record->attestation_application_id->length)) {
1327         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1328     }
1329 
1330     // Brand name
1331     if (record->attestation_id_brand &&
1332         !auth_list->push_back(TAG_ATTESTATION_ID_BRAND, record->attestation_id_brand->data,
1333                               record->attestation_id_brand->length)) {
1334         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1335     }
1336 
1337     // Device name
1338     if (record->attestation_id_device &&
1339         !auth_list->push_back(TAG_ATTESTATION_ID_DEVICE, record->attestation_id_device->data,
1340                               record->attestation_id_device->length)) {
1341         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1342     }
1343 
1344     // Product name
1345     if (record->attestation_id_product &&
1346         !auth_list->push_back(TAG_ATTESTATION_ID_PRODUCT, record->attestation_id_product->data,
1347                               record->attestation_id_product->length)) {
1348         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1349     }
1350 
1351     // Serial number
1352     if (record->attestation_id_serial &&
1353         !auth_list->push_back(TAG_ATTESTATION_ID_SERIAL, record->attestation_id_serial->data,
1354                               record->attestation_id_serial->length)) {
1355         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1356     }
1357 
1358     // IMEI
1359     if (record->attestation_id_imei &&
1360         !auth_list->push_back(TAG_ATTESTATION_ID_IMEI, record->attestation_id_imei->data,
1361                               record->attestation_id_imei->length)) {
1362         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1363     }
1364 
1365     // MEID
1366     if (record->attestation_id_meid &&
1367         !auth_list->push_back(TAG_ATTESTATION_ID_MEID, record->attestation_id_meid->data,
1368                               record->attestation_id_meid->length)) {
1369         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1370     }
1371 
1372     // Manufacturer name
1373     if (record->attestation_id_manufacturer &&
1374         !auth_list->push_back(TAG_ATTESTATION_ID_MANUFACTURER,
1375                               record->attestation_id_manufacturer->data,
1376                               record->attestation_id_manufacturer->length)) {
1377         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1378     }
1379 
1380     // Model name
1381     if (record->attestation_id_model &&
1382         !auth_list->push_back(TAG_ATTESTATION_ID_MODEL, record->attestation_id_model->data,
1383                               record->attestation_id_model->length)) {
1384         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1385     }
1386 
1387     // vendor patch level
1388     if (record->vendor_patchlevel &&
1389         !auth_list->push_back(TAG_VENDOR_PATCHLEVEL, ASN1_INTEGER_get(record->vendor_patchlevel))) {
1390         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1391     }
1392 
1393     // boot patch level
1394     if (record->boot_patch_level &&
1395         !auth_list->push_back(TAG_BOOT_PATCHLEVEL, ASN1_INTEGER_get(record->boot_patch_level))) {
1396         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1397     }
1398 
1399     // device unique attestation
1400     if (record->device_unique_attestation && !auth_list->push_back(TAG_DEVICE_UNIQUE_ATTESTATION)) {
1401         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1402     }
1403 
1404     // identity credential key
1405     if (record->identity_credential_key && !auth_list->push_back(TAG_IDENTITY_CREDENTIAL_KEY)) {
1406         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1407     }
1408 
1409     // Second IMEI
1410     if (record->attestation_id_second_imei &&
1411         !auth_list->push_back(TAG_ATTESTATION_ID_SECOND_IMEI,
1412                               record->attestation_id_second_imei->data,
1413                               record->attestation_id_second_imei->length)) {
1414         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
1415     }
1416 
1417     return KM_ERROR_OK;
1418 }
1419 
1420 // Parse the DER-encoded attestation record, placing the results in keymaster_version,
1421 // 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)1422 keymaster_error_t parse_attestation_record(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
1423                                            uint32_t* attestation_version,  //
1424                                            keymaster_security_level_t* attestation_security_level,
1425                                            uint32_t* keymaster_version,
1426                                            keymaster_security_level_t* keymaster_security_level,
1427                                            keymaster_blob_t* attestation_challenge,
1428                                            AuthorizationSet* software_enforced,
1429                                            AuthorizationSet* tee_enforced,
1430                                            keymaster_blob_t* unique_id) {
1431     const uint8_t* p = asn1_key_desc;
1432     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> record(
1433         d2i_KM_KEY_DESCRIPTION(nullptr, &p, asn1_key_desc_len));
1434     if (!record.get()) return TranslateLastOpenSslError();
1435 
1436     *attestation_version = ASN1_INTEGER_get(record->attestation_version);
1437     *attestation_security_level = static_cast<keymaster_security_level_t>(
1438         ASN1_ENUMERATED_get(record->attestation_security_level));
1439     *keymaster_version = ASN1_INTEGER_get(record->keymaster_version);
1440     *keymaster_security_level = static_cast<keymaster_security_level_t>(
1441         ASN1_ENUMERATED_get(record->keymaster_security_level));
1442 
1443     attestation_challenge->data =
1444         dup_buffer(record->attestation_challenge->data, record->attestation_challenge->length);
1445     attestation_challenge->data_length = record->attestation_challenge->length;
1446 
1447     unique_id->data = dup_buffer(record->unique_id->data, record->unique_id->length);
1448     unique_id->data_length = record->unique_id->length;
1449 
1450     keymaster_error_t error = extract_auth_list(record->software_enforced, software_enforced);
1451     if (error != KM_ERROR_OK) return error;
1452 
1453     return extract_auth_list(record->tee_enforced, tee_enforced);
1454 }
1455 
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)1456 keymaster_error_t parse_root_of_trust(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
1457                                       keymaster_blob_t* verified_boot_key,
1458                                       keymaster_verified_boot_t* verified_boot_state,
1459                                       bool* device_locked) {
1460     const uint8_t* p = asn1_key_desc;
1461     UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> record(
1462         d2i_KM_KEY_DESCRIPTION(nullptr, &p, asn1_key_desc_len));
1463     if (!record.get()) {
1464         return TranslateLastOpenSslError();
1465     }
1466     if (!record->tee_enforced) {
1467         return KM_ERROR_INVALID_ARGUMENT;
1468     }
1469     if (!record->tee_enforced->root_of_trust) {
1470         return KM_ERROR_INVALID_ARGUMENT;
1471     }
1472     if (!record->tee_enforced->root_of_trust->verified_boot_key) {
1473         return KM_ERROR_INVALID_ARGUMENT;
1474     }
1475     KM_ROOT_OF_TRUST* root_of_trust = record->tee_enforced->root_of_trust;
1476     verified_boot_key->data = dup_buffer(root_of_trust->verified_boot_key->data,
1477                                          root_of_trust->verified_boot_key->length);
1478     verified_boot_key->data_length = root_of_trust->verified_boot_key->length;
1479     *verified_boot_state = static_cast<keymaster_verified_boot_t>(
1480         ASN1_ENUMERATED_get(root_of_trust->verified_boot_state));
1481     *device_locked = root_of_trust->device_locked;
1482     return KM_ERROR_OK;
1483 }
1484 
1485 // Parse the EAT-encoded attestation record, placing the results in keymaster_version,
1486 // 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)1487 keymaster_error_t parse_eat_record(
1488     const uint8_t* eat_key_desc, size_t eat_key_desc_len, uint32_t* attestation_version,
1489     keymaster_security_level_t* attestation_security_level, uint32_t* keymaster_version,
1490     keymaster_security_level_t* keymaster_security_level, keymaster_blob_t* attestation_challenge,
1491     AuthorizationSet* software_enforced, AuthorizationSet* tee_enforced,
1492     keymaster_blob_t* unique_id, keymaster_blob_t* verified_boot_key,
1493     keymaster_verified_boot_t* verified_boot_state, bool* device_locked,
1494     std::vector<int64_t>* unexpected_claims) {
1495     auto [top_level_item, next_pos, error] = cppbor::parse(eat_key_desc, eat_key_desc_len);
1496     ASSERT_OR_RETURN_ERROR(top_level_item, KM_ERROR_INVALID_TAG);
1497     const cppbor::Map* eat_map = top_level_item->asMap();
1498     ASSERT_OR_RETURN_ERROR(eat_map, KM_ERROR_INVALID_TAG);
1499     bool verified_or_self_signed = false;
1500 
1501     for (size_t i = 0; i < eat_map->size(); i++) {
1502         auto& [key_item, value_item] = (*eat_map)[i];
1503         const cppbor::Int* key = key_item->asInt();
1504         ASSERT_OR_RETURN_ERROR(key, (KM_ERROR_INVALID_TAG));
1505 
1506         // The following values will either hold the typed value, or be null (if not the right
1507         // type).
1508         const cppbor::Int* int_value = value_item->asInt();
1509         const cppbor::Bstr* bstr_value = value_item->asBstr();
1510         const cppbor::Simple* simple_value = value_item->asSimple();
1511         const cppbor::Array* array_value = value_item->asArray();
1512         const cppbor::Map* map_value = value_item->asMap();
1513 
1514         keymaster_error_t error;
1515         switch ((EatClaim)key->value()) {
1516         default:
1517             unexpected_claims->push_back(key->value());
1518             break;
1519         case EatClaim::ATTESTATION_VERSION:
1520             ASSERT_OR_RETURN_ERROR(int_value, KM_ERROR_INVALID_TAG);
1521             *attestation_version = int_value->value();
1522             break;
1523         case EatClaim::SECURITY_LEVEL:
1524             ASSERT_OR_RETURN_ERROR(int_value, KM_ERROR_INVALID_TAG);
1525             switch ((EatSecurityLevel)int_value->value()) {
1526             // TODO: Is my assumption correct that the security level of the attestation data should
1527             // always be equal to the security level of keymint, as the attestation data always
1528             // lives in the top-level module?
1529             case EatSecurityLevel::UNRESTRICTED:
1530                 *keymaster_security_level = *attestation_security_level =
1531                     KM_SECURITY_LEVEL_SOFTWARE;
1532                 break;
1533             case EatSecurityLevel::SECURE_RESTRICTED:
1534                 *keymaster_security_level = *attestation_security_level =
1535                     KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
1536                 break;
1537             case EatSecurityLevel::HARDWARE:
1538                 *keymaster_security_level = *attestation_security_level =
1539                     KM_SECURITY_LEVEL_STRONGBOX;
1540                 break;
1541             default:
1542                 return KM_ERROR_INVALID_TAG;
1543             }
1544             break;
1545         case EatClaim::KEYMASTER_VERSION:
1546             ASSERT_OR_RETURN_ERROR(int_value, KM_ERROR_INVALID_TAG);
1547             *keymaster_version = int_value->value();
1548             break;
1549         case EatClaim::SUBMODS:
1550             ASSERT_OR_RETURN_ERROR(map_value, KM_ERROR_INVALID_TAG);
1551             for (size_t j = 0; j < map_value->size(); j++) {
1552                 auto& [submod_key, submod_value] = (*map_value)[j];
1553                 const cppbor::Map* submod_map = submod_value->asMap();
1554                 ASSERT_OR_RETURN_ERROR(submod_map, KM_ERROR_INVALID_TAG);
1555                 error = parse_eat_submod(submod_map, software_enforced, tee_enforced);
1556                 if (error != KM_ERROR_OK) return error;
1557             }
1558             break;
1559         case EatClaim::CTI:
1560             error = bstr_to_blob(bstr_value, unique_id);
1561             if (error != KM_ERROR_OK) return error;
1562             break;
1563         case EatClaim::NONCE:
1564             error = bstr_to_blob(bstr_value, attestation_challenge);
1565             if (error != KM_ERROR_OK) return error;
1566             break;
1567         case EatClaim::VERIFIED_BOOT_KEY:
1568             error = bstr_to_blob(bstr_value, verified_boot_key);
1569             if (error != KM_ERROR_OK) return error;
1570             break;
1571         case EatClaim::VERIFIED_BOOT_HASH:
1572             // Not parsing this for now.
1573             break;
1574         case EatClaim::DEVICE_UNIQUE_ATTESTATION:
1575             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1576                 return KM_ERROR_INVALID_TAG;
1577             }
1578             // Not parsing this for now.
1579             break;
1580         case EatClaim::DEVICE_LOCKED:
1581             ASSERT_OR_RETURN_ERROR(simple_value->asBool(), KM_ERROR_INVALID_TAG);
1582             *device_locked = simple_value->asBool()->value();
1583             break;
1584         case EatClaim::BOOT_STATE:
1585             ASSERT_OR_RETURN_ERROR(array_value, KM_ERROR_INVALID_TAG);
1586             ASSERT_OR_RETURN_ERROR(array_value->size() == 5, KM_ERROR_INVALID_TAG);
1587             ASSERT_OR_RETURN_ERROR((*array_value)[4]->asSimple()->asBool()->value() == false,
1588                                    KM_ERROR_INVALID_TAG);
1589             verified_or_self_signed = (*array_value)[0]->asSimple()->asBool()->value();
1590             ASSERT_OR_RETURN_ERROR(verified_or_self_signed ==
1591                                        (*array_value)[1]->asSimple()->asBool()->value(),
1592                                    KM_ERROR_INVALID_TAG);
1593             ASSERT_OR_RETURN_ERROR(verified_or_self_signed ==
1594                                        (*array_value)[2]->asSimple()->asBool()->value(),
1595                                    KM_ERROR_INVALID_TAG);
1596             ASSERT_OR_RETURN_ERROR(verified_or_self_signed ==
1597                                        (*array_value)[3]->asSimple()->asBool()->value(),
1598                                    KM_ERROR_INVALID_TAG);
1599             break;
1600         case EatClaim::OFFICIAL_BUILD:
1601             *verified_boot_state = KM_VERIFIED_BOOT_VERIFIED;
1602             break;
1603         }
1604     }
1605 
1606     if (*verified_boot_state == KM_VERIFIED_BOOT_VERIFIED) {
1607         (void)(verified_boot_state);
1608         // TODO: re-enable this
1609         // ASSERT_OR_RETURN_ERROR(verified_or_self_signed, KM_ERROR_INVALID_TAG);
1610     } else {
1611         *verified_boot_state =
1612             verified_or_self_signed ? KM_VERIFIED_BOOT_SELF_SIGNED : KM_VERIFIED_BOOT_UNVERIFIED;
1613     }
1614 
1615     return KM_ERROR_OK;
1616 }
1617 
parse_submod_values(AuthorizationSetBuilder * set_builder,int * auth_set_security_level,const cppbor::Map * submod_map)1618 keymaster_error_t parse_submod_values(AuthorizationSetBuilder* set_builder,
1619                                       int* auth_set_security_level, const cppbor::Map* submod_map) {
1620     ASSERT_OR_RETURN_ERROR(set_builder, KM_ERROR_UNEXPECTED_NULL_POINTER);
1621     for (size_t i = 0; i < submod_map->size(); i++) {
1622         auto& [key_item, value_item] = (*submod_map)[i];
1623         const cppbor::Int* key_int = key_item->asInt();
1624         ASSERT_OR_RETURN_ERROR(key_int, KM_ERROR_INVALID_TAG);
1625         int key = key_int->value();
1626         keymaster_error_t error;
1627         keymaster_blob_t blob;
1628 
1629         switch ((EatClaim)key) {
1630         default:
1631             return KM_ERROR_INVALID_TAG;
1632         case EatClaim::ALGORITHM:
1633             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1634             set_builder->Authorization(
1635                 TAG_ALGORITHM, static_cast<keymaster_algorithm_t>(value_item->asInt()->value()));
1636             break;
1637         case EatClaim::EC_CURVE:
1638             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1639             set_builder->Authorization(
1640                 TAG_EC_CURVE, static_cast<keymaster_ec_curve_t>(value_item->asInt()->value()));
1641             break;
1642         case EatClaim::USER_AUTH_TYPE:
1643             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1644             set_builder->Authorization(TAG_USER_AUTH_TYPE, static_cast<hw_authenticator_type_t>(
1645                                                                value_item->asInt()->value()));
1646             break;
1647         case EatClaim::ORIGIN:
1648             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1649             set_builder->Authorization(
1650                 TAG_ORIGIN, static_cast<keymaster_key_origin_t>(value_item->asInt()->value()));
1651             break;
1652         case EatClaim::PURPOSE:
1653             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1654                 set_builder->Authorization(TAG_PURPOSE,
1655                                            static_cast<keymaster_purpose_t>(
1656                                                (*value_item->asArray())[j]->asInt()->value()));
1657             }
1658             break;
1659         case EatClaim::PADDING:
1660             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1661                 set_builder->Authorization(TAG_PADDING,
1662                                            static_cast<keymaster_padding_t>(
1663                                                (*value_item->asArray())[j]->asInt()->value()));
1664             }
1665             break;
1666         case EatClaim::DIGEST:
1667             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1668                 set_builder->Authorization(
1669                     TAG_DIGEST,
1670                     static_cast<keymaster_digest_t>((*value_item->asArray())[j]->asInt()->value()));
1671             }
1672             break;
1673         case EatClaim::BLOCK_MODE:
1674             for (size_t j = 0; j < value_item->asArray()->size(); j++) {
1675                 set_builder->Authorization(TAG_BLOCK_MODE,
1676                                            static_cast<keymaster_block_mode_t>(
1677                                                (*value_item->asArray())[j]->asInt()->value()));
1678             }
1679             break;
1680         case EatClaim::KEY_SIZE:
1681             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1682             set_builder->Authorization(TAG_KEY_SIZE, value_item->asInt()->value());
1683             break;
1684         case EatClaim::AUTH_TIMEOUT:
1685             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1686             set_builder->Authorization(TAG_AUTH_TIMEOUT, value_item->asInt()->value());
1687             break;
1688         case EatClaim::OS_VERSION:
1689             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1690             set_builder->Authorization(TAG_OS_VERSION, value_item->asInt()->value());
1691             break;
1692         case EatClaim::OS_PATCHLEVEL:
1693             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1694             set_builder->Authorization(TAG_OS_PATCHLEVEL, value_item->asInt()->value());
1695             break;
1696         case EatClaim::MIN_MAC_LENGTH:
1697             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1698             set_builder->Authorization(TAG_MIN_MAC_LENGTH, value_item->asInt()->value());
1699             break;
1700         case EatClaim::BOOT_PATCHLEVEL:
1701             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1702             set_builder->Authorization(TAG_BOOT_PATCHLEVEL, value_item->asInt()->value());
1703             break;
1704         case EatClaim::VENDOR_PATCHLEVEL:
1705             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1706             set_builder->Authorization(TAG_VENDOR_PATCHLEVEL, value_item->asInt()->value());
1707             break;
1708         case EatClaim::RSA_PUBLIC_EXPONENT:
1709             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1710             set_builder->Authorization(TAG_RSA_PUBLIC_EXPONENT, value_item->asInt()->value());
1711             break;
1712         case EatClaim::ACTIVE_DATETIME:
1713             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1714             set_builder->Authorization(TAG_ACTIVE_DATETIME, value_item->asInt()->value());
1715             break;
1716         case EatClaim::ORIGINATION_EXPIRE_DATETIME:
1717             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1718             set_builder->Authorization(TAG_ORIGINATION_EXPIRE_DATETIME,
1719                                        value_item->asInt()->value());
1720             break;
1721         case EatClaim::USAGE_EXPIRE_DATETIME:
1722             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1723             set_builder->Authorization(TAG_USAGE_EXPIRE_DATETIME, value_item->asInt()->value());
1724             break;
1725         case EatClaim::IAT:
1726             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1727             set_builder->Authorization(TAG_CREATION_DATETIME, value_item->asInt()->value());
1728             break;
1729         case EatClaim::NO_AUTH_REQUIRED:
1730             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1731                 return KM_ERROR_INVALID_TAG;
1732             }
1733             set_builder->Authorization(TAG_NO_AUTH_REQUIRED);
1734             break;
1735         case EatClaim::ALL_APPLICATIONS:
1736             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1737                 return KM_ERROR_INVALID_TAG;
1738             }
1739             set_builder->Authorization(TAG_ALL_APPLICATIONS);
1740             break;
1741         case EatClaim::ROLLBACK_RESISTANT:
1742             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1743                 return KM_ERROR_INVALID_TAG;
1744             }
1745             set_builder->Authorization(TAG_ROLLBACK_RESISTANT);
1746             break;
1747         case EatClaim::ALLOW_WHILE_ON_BODY:
1748             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1749                 return KM_ERROR_INVALID_TAG;
1750             }
1751             set_builder->Authorization(TAG_ALLOW_WHILE_ON_BODY);
1752             break;
1753         case EatClaim::UNLOCKED_DEVICE_REQUIRED:
1754             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1755                 return KM_ERROR_INVALID_TAG;
1756             }
1757             set_builder->Authorization(TAG_UNLOCKED_DEVICE_REQUIRED);
1758             break;
1759         case EatClaim::CALLER_NONCE:
1760             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1761                 return KM_ERROR_INVALID_TAG;
1762             }
1763             set_builder->Authorization(TAG_CALLER_NONCE);
1764             break;
1765         case EatClaim::TRUSTED_CONFIRMATION_REQUIRED:
1766             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1767                 return KM_ERROR_INVALID_TAG;
1768             }
1769             set_builder->Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED);
1770             break;
1771         case EatClaim::EARLY_BOOT_ONLY:
1772             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1773                 return KM_ERROR_INVALID_TAG;
1774             }
1775             set_builder->Authorization(TAG_EARLY_BOOT_ONLY);
1776             break;
1777         case EatClaim::IDENTITY_CREDENTIAL_KEY:
1778             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1779                 return KM_ERROR_INVALID_TAG;
1780             }
1781             set_builder->Authorization(TAG_IDENTITY_CREDENTIAL_KEY);
1782             break;
1783         case EatClaim::STORAGE_KEY:
1784             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1785                 return KM_ERROR_INVALID_TAG;
1786             }
1787             set_builder->Authorization(TAG_STORAGE_KEY);
1788             break;
1789         case EatClaim::TRUSTED_USER_PRESENCE_REQUIRED:
1790             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1791                 return KM_ERROR_INVALID_TAG;
1792             }
1793             set_builder->Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED);
1794             break;
1795         case EatClaim::DEVICE_UNIQUE_ATTESTATION:
1796             if (value_item->asSimple() == nullptr || !value_item->asSimple()->asBool()->value()) {
1797                 return KM_ERROR_INVALID_TAG;
1798             }
1799             set_builder->Authorization(TAG_DEVICE_UNIQUE_ATTESTATION);
1800             break;
1801         case EatClaim::APPLICATION_ID:
1802             error = bstr_to_blob(value_item->asBstr(), &blob);
1803             if (error != KM_ERROR_OK) return error;
1804             set_builder->Authorization(TAG_APPLICATION_ID, blob);
1805             break;
1806         case EatClaim::ATTESTATION_APPLICATION_ID:
1807             error = bstr_to_blob(value_item->asBstr(), &blob);
1808             if (error != KM_ERROR_OK) return error;
1809             set_builder->Authorization(TAG_ATTESTATION_APPLICATION_ID, blob);
1810             break;
1811         case EatClaim::ATTESTATION_ID_BRAND:
1812             error = bstr_to_blob(value_item->asBstr(), &blob);
1813             if (error != KM_ERROR_OK) return error;
1814             set_builder->Authorization(TAG_ATTESTATION_ID_BRAND, blob);
1815             break;
1816         case EatClaim::ATTESTATION_ID_DEVICE:
1817             error = bstr_to_blob(value_item->asBstr(), &blob);
1818             if (error != KM_ERROR_OK) return error;
1819             set_builder->Authorization(TAG_ATTESTATION_ID_DEVICE, blob);
1820             break;
1821         case EatClaim::ATTESTATION_ID_PRODUCT:
1822             error = bstr_to_blob(value_item->asBstr(), &blob);
1823             if (error != KM_ERROR_OK) return error;
1824             set_builder->Authorization(TAG_ATTESTATION_ID_PRODUCT, blob);
1825             break;
1826         case EatClaim::ATTESTATION_ID_SERIAL:
1827             error = bstr_to_blob(value_item->asBstr(), &blob);
1828             if (error != KM_ERROR_OK) return error;
1829             set_builder->Authorization(TAG_ATTESTATION_ID_SERIAL, blob);
1830             break;
1831         case EatClaim::UEID:
1832             error = ueid_to_imei_blob(value_item->asBstr(), &blob);
1833             if (error != KM_ERROR_OK) return error;
1834             set_builder->Authorization(TAG_ATTESTATION_ID_IMEI, blob);
1835             break;
1836         case EatClaim::ATTESTATION_ID_MEID:
1837             error = bstr_to_blob(value_item->asBstr(), &blob);
1838             if (error != KM_ERROR_OK) return error;
1839             set_builder->Authorization(TAG_ATTESTATION_ID_MEID, blob);
1840             break;
1841         case EatClaim::ATTESTATION_ID_MANUFACTURER:
1842             error = bstr_to_blob(value_item->asBstr(), &blob);
1843             if (error != KM_ERROR_OK) return error;
1844             set_builder->Authorization(TAG_ATTESTATION_ID_MANUFACTURER, blob);
1845             break;
1846         case EatClaim::ATTESTATION_ID_MODEL:
1847             error = bstr_to_blob(value_item->asBstr(), &blob);
1848             if (error != KM_ERROR_OK) return error;
1849             set_builder->Authorization(TAG_ATTESTATION_ID_MODEL, blob);
1850             break;
1851         case EatClaim::CONFIRMATION_TOKEN:
1852             error = bstr_to_blob(value_item->asBstr(), &blob);
1853             if (error != KM_ERROR_OK) return error;
1854             set_builder->Authorization(TAG_CONFIRMATION_TOKEN, blob);
1855             break;
1856         case EatClaim::SECURITY_LEVEL:
1857             ASSERT_OR_RETURN_ERROR(value_item->asInt(), KM_ERROR_INVALID_TAG);
1858             *auth_set_security_level = value_item->asInt()->value();
1859         }
1860     }
1861 
1862     return KM_ERROR_OK;
1863 }
1864 
parse_eat_submod(const cppbor::Map * submod_values,AuthorizationSet * software_enforced,AuthorizationSet * tee_enforced)1865 keymaster_error_t parse_eat_submod(const cppbor::Map* submod_values,
1866                                    AuthorizationSet* software_enforced,
1867                                    AuthorizationSet* tee_enforced) {
1868     AuthorizationSetBuilder auth_set_builder;
1869     int auth_set_security_level = 0;
1870     keymaster_error_t error =
1871         parse_submod_values(&auth_set_builder, &auth_set_security_level, submod_values);
1872     if (error) return error;
1873     switch ((EatSecurityLevel)auth_set_security_level) {
1874     case EatSecurityLevel::HARDWARE:
1875         // Hardware attestation should never occur in a submod of another EAT.
1876         [[fallthrough]];
1877     default:
1878         return KM_ERROR_INVALID_TAG;
1879     case EatSecurityLevel::UNRESTRICTED:
1880         *software_enforced = AuthorizationSet(auth_set_builder);
1881         break;
1882     case EatSecurityLevel::SECURE_RESTRICTED:
1883         *tee_enforced = AuthorizationSet(auth_set_builder);
1884         break;
1885     }
1886 
1887     return KM_ERROR_OK;
1888 }
1889 }  // namespace keymaster
1890