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