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