1 // Copyright 2022, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Generation of certificates and attestation extensions.
16 
17 use crate::keys::SigningInfo;
18 use alloc::{borrow::Cow, vec::Vec};
19 use core::time::Duration;
20 use der::asn1::{BitString, OctetString, OctetStringRef, SetOfVec};
21 use der::{
22     asn1::{GeneralizedTime, Null, UtcTime},
23     oid::AssociatedOid,
24     Enumerated, Sequence,
25 };
26 use der::{Decode, Encode, EncodeValue, ErrorKind, Length};
27 use flagset::FlagSet;
28 use kmr_common::crypto::KeyMaterial;
29 use kmr_common::{
30     crypto, der_err, get_tag_value, km_err, tag, try_to_vec, vec_try_with_capacity, Error,
31 };
32 use kmr_common::{get_bool_tag_value, get_opt_tag_value, FallibleAllocExt};
33 use kmr_wire::{
34     keymint,
35     keymint::{
36         from_raw_tag_value, raw_tag_value, DateTime, ErrorCode, KeyCharacteristics, KeyParam,
37         KeyPurpose, Tag,
38     },
39     KeySizeInBits, RsaExponent,
40 };
41 use spki::{AlgorithmIdentifier, ObjectIdentifier, SubjectPublicKeyInfoOwned};
42 use x509_cert::serial_number::SerialNumber;
43 use x509_cert::{
44     certificate::{Certificate, TbsCertificate, Version},
45     ext::pkix::{constraints::BasicConstraints, KeyUsage, KeyUsages},
46     ext::Extension,
47     name::RdnSequence,
48     time::Time,
49 };
50 
51 /// OID value for the Android Attestation extension.
52 pub const ATTESTATION_EXTENSION_OID: ObjectIdentifier =
53     ObjectIdentifier::new_unwrap("1.3.6.1.4.1.11129.2.1.17");
54 
55 /// Empty book key value to use in attestations.
56 const EMPTY_BOOT_KEY: [u8; 32] = [0u8; 32];
57 
58 /// Build an ASN.1 DER-encodable `Certificate`.
certificate(tbs_cert: TbsCertificate, sig_val: &[u8]) -> Result<Certificate, Error>59 pub(crate) fn certificate(tbs_cert: TbsCertificate, sig_val: &[u8]) -> Result<Certificate, Error> {
60     Ok(Certificate {
61         signature_algorithm: tbs_cert.signature.clone(),
62         tbs_certificate: tbs_cert,
63         signature: BitString::new(0, sig_val)
64             .map_err(|e| der_err!(e, "failed to build BitString"))?,
65     })
66 }
67 
68 /// Build an ASN.1 DER-encodable `tbsCertificate`.
tbs_certificate<'a>( info: &'a Option<SigningInfo>, spki: SubjectPublicKeyInfoOwned, key_usage_ext_bits: &'a [u8], basic_constraint_ext_val: Option<&'a [u8]>, attestation_ext: Option<&'a [u8]>, chars: &'a [KeyParam], params: &'a [KeyParam], ) -> Result<TbsCertificate, Error>69 pub(crate) fn tbs_certificate<'a>(
70     info: &'a Option<SigningInfo>,
71     spki: SubjectPublicKeyInfoOwned,
72     key_usage_ext_bits: &'a [u8],
73     basic_constraint_ext_val: Option<&'a [u8]>,
74     attestation_ext: Option<&'a [u8]>,
75     chars: &'a [KeyParam],
76     params: &'a [KeyParam],
77 ) -> Result<TbsCertificate, Error> {
78     let cert_serial = tag::get_cert_serial(params)?;
79     let cert_subject = tag::get_cert_subject(params)?;
80     let not_before = get_tag_value!(params, CertificateNotBefore, ErrorCode::MissingNotBefore)?;
81     let not_after = get_tag_value!(params, CertificateNotAfter, ErrorCode::MissingNotAfter)?;
82 
83     // Determine the OID part of the `AlgorithmIdentifier`; we do not support any signing key
84     // types that have parameters in the `AlgorithmIdentifier`
85     let sig_alg_oid = match info {
86         Some(info) => match info.signing_key {
87             KeyMaterial::Rsa(_) => crypto::rsa::SHA256_PKCS1_SIGNATURE_OID,
88             KeyMaterial::Ec(curve, _, _) => crypto::ec::curve_to_signing_oid(curve),
89             _ => {
90                 return Err(km_err!(UnsupportedAlgorithm, "unexpected cert signing key type"));
91             }
92         },
93         None => {
94             // No signing key, so signature will be empty, but we still need a value here.
95             match tag::get_algorithm(params)? {
96                 keymint::Algorithm::Rsa => crypto::rsa::SHA256_PKCS1_SIGNATURE_OID,
97                 keymint::Algorithm::Ec => {
98                     crypto::ec::curve_to_signing_oid(tag::get_ec_curve(chars)?)
99                 }
100                 alg => {
101                     return Err(km_err!(
102                         UnsupportedAlgorithm,
103                         "unexpected algorithm for public key {:?}",
104                         alg
105                     ))
106                 }
107             }
108         }
109     };
110     let cert_issuer = match &info {
111         Some(info) => &info.issuer_subject,
112         None => cert_subject,
113     };
114 
115     // Build certificate extensions
116     let key_usage_extension = Extension {
117         extn_id: KeyUsage::OID,
118         critical: true,
119         extn_value: OctetString::new(key_usage_ext_bits)
120             .map_err(|e| der_err!(e, "failed to build OctetString"))?,
121     };
122 
123     let mut cert_extensions = vec_try_with_capacity!(3)?;
124     cert_extensions.push(key_usage_extension); // capacity enough
125 
126     if let Some(basic_constraint_ext_val) = basic_constraint_ext_val {
127         let basic_constraint_ext = Extension {
128             extn_id: BasicConstraints::OID,
129             critical: true,
130             extn_value: OctetString::new(basic_constraint_ext_val)
131                 .map_err(|e| der_err!(e, "failed to build OctetString"))?,
132         };
133         cert_extensions.push(basic_constraint_ext); // capacity enough
134     }
135 
136     if let Some(attest_extn_val) = attestation_ext {
137         let attest_ext = Extension {
138             extn_id: AttestationExtension::OID,
139             critical: false,
140             extn_value: OctetString::new(attest_extn_val)
141                 .map_err(|e| der_err!(e, "failed to build OctetString"))?,
142         };
143         cert_extensions.push(attest_ext) // capacity enough
144     }
145 
146     Ok(TbsCertificate {
147         version: Version::V3,
148         serial_number: SerialNumber::new(cert_serial)
149             .map_err(|e| der_err!(e, "failed to build serial number for {:?}", cert_serial))?,
150         signature: AlgorithmIdentifier { oid: sig_alg_oid, parameters: None },
151         issuer: RdnSequence::from_der(cert_issuer)
152             .map_err(|e| der_err!(e, "failed to build issuer"))?,
153         validity: x509_cert::time::Validity {
154             not_before: validity_time_from_datetime(not_before)?,
155             not_after: validity_time_from_datetime(not_after)?,
156         },
157         subject: RdnSequence::from_der(cert_subject)
158             .map_err(|e| der_err!(e, "failed to build subject"))?,
159         subject_public_key_info: spki,
160         issuer_unique_id: None,
161         subject_unique_id: None,
162         extensions: Some(cert_extensions),
163     })
164 }
165 
166 /// Extract the Subject field from a `keymint::Certificate` as DER-encoded data.
extract_subject(cert: &keymint::Certificate) -> Result<Vec<u8>, Error>167 pub(crate) fn extract_subject(cert: &keymint::Certificate) -> Result<Vec<u8>, Error> {
168     let cert = x509_cert::Certificate::from_der(&cert.encoded_certificate)
169         .map_err(|e| km_err!(EncodingError, "failed to parse certificate: {:?}", e))?;
170     let subject_data = cert
171         .tbs_certificate
172         .subject
173         .to_der()
174         .map_err(|e| km_err!(EncodingError, "failed to DER-encode subject: {:?}", e))?;
175     Ok(subject_data)
176 }
177 
178 /// Construct x.509-cert::time::Time from `DateTime`.
179 /// RFC 5280 section 4.1.2.5 requires that UtcTime is used up to 2049
180 /// and GeneralizedTime from 2050 onwards
validity_time_from_datetime(when: DateTime) -> Result<Time, Error>181 fn validity_time_from_datetime(when: DateTime) -> Result<Time, Error> {
182     let dt_err = |_| Error::Der(ErrorKind::DateTime);
183     let secs_since_epoch: i64 = when.ms_since_epoch / 1000;
184 
185     if when.ms_since_epoch >= 0 {
186         const MAX_UTC_TIME: Duration = Duration::from_secs(2524608000); // 2050-01-01T00:00:00Z
187 
188         let duration = Duration::from_secs(u64::try_from(secs_since_epoch).map_err(dt_err)?);
189         if duration >= MAX_UTC_TIME {
190             Ok(Time::GeneralTime(
191                 GeneralizedTime::from_unix_duration(duration)
192                     .map_err(|e| der_err!(e, "failed to build GeneralTime for {:?}", when))?,
193             ))
194         } else {
195             Ok(Time::UtcTime(
196                 UtcTime::from_unix_duration(duration)
197                     .map_err(|e| der_err!(e, "failed to build UtcTime for {:?}", when))?,
198             ))
199         }
200     } else {
201         // TODO: cope with negative offsets from Unix Epoch.
202         Ok(Time::GeneralTime(
203             GeneralizedTime::from_unix_duration(Duration::from_secs(0))
204                 .map_err(|e| der_err!(e, "failed to build GeneralizedTime(0) for {:?}", when))?,
205         ))
206     }
207 }
208 
asn1_der_encode<T: Encode>(obj: &T) -> Result<Vec<u8>, der::Error>209 pub(crate) fn asn1_der_encode<T: Encode>(obj: &T) -> Result<Vec<u8>, der::Error> {
210     let mut encoded_data = Vec::<u8>::new();
211     obj.encode_to_vec(&mut encoded_data)?;
212     Ok(encoded_data)
213 }
214 
215 /// Build key usage extension bits.
key_usage_extension_bits(params: &[KeyParam]) -> KeyUsage216 pub(crate) fn key_usage_extension_bits(params: &[KeyParam]) -> KeyUsage {
217     // Build `KeyUsage` bitmask based on allowed purposes for the key.
218     let mut key_usage_bits = FlagSet::<KeyUsages>::default();
219     for param in params {
220         if let KeyParam::Purpose(purpose) = param {
221             match purpose {
222                 KeyPurpose::Sign | KeyPurpose::Verify => {
223                     key_usage_bits |= KeyUsages::DigitalSignature;
224                 }
225                 KeyPurpose::Decrypt | KeyPurpose::Encrypt => {
226                     key_usage_bits |= KeyUsages::DataEncipherment;
227                     key_usage_bits |= KeyUsages::KeyEncipherment;
228                 }
229                 KeyPurpose::WrapKey => {
230                     key_usage_bits |= KeyUsages::KeyEncipherment;
231                 }
232                 KeyPurpose::AgreeKey => {
233                     key_usage_bits |= KeyUsages::KeyAgreement;
234                 }
235                 KeyPurpose::AttestKey => {
236                     key_usage_bits |= KeyUsages::KeyCertSign;
237                 }
238             }
239         }
240     }
241     KeyUsage(key_usage_bits)
242 }
243 
244 /// Build basic constraints extension value
basic_constraints_ext_value(ca_required: bool) -> BasicConstraints245 pub(crate) fn basic_constraints_ext_value(ca_required: bool) -> BasicConstraints {
246     BasicConstraints { ca: ca_required, path_len_constraint: None }
247 }
248 
249 /// Attestation extension contents
250 ///
251 /// ```asn1
252 /// KeyDescription ::= SEQUENCE {
253 ///     attestationVersion         INTEGER, # Value 300
254 ///     attestationSecurityLevel   SecurityLevel, # See below
255 ///     keyMintVersion             INTEGER, # Value 300
256 ///     keymintSecurityLevel       SecurityLevel, # See below
257 ///     attestationChallenge       OCTET_STRING, # Tag::ATTESTATION_CHALLENGE from attestParams
258 ///     uniqueId                   OCTET_STRING, # Empty unless key has Tag::INCLUDE_UNIQUE_ID
259 ///     softwareEnforced           AuthorizationList, # See below
260 ///     hardwareEnforced           AuthorizationList, # See below
261 /// }
262 /// ```
263 #[derive(Debug, Clone, Sequence, PartialEq)]
264 pub struct AttestationExtension<'a> {
265     attestation_version: i32,
266     attestation_security_level: SecurityLevel,
267     keymint_version: i32,
268     keymint_security_level: SecurityLevel,
269     #[asn1(type = "OCTET STRING")]
270     attestation_challenge: &'a [u8],
271     #[asn1(type = "OCTET STRING")]
272     unique_id: &'a [u8],
273     sw_enforced: AuthorizationList<'a>,
274     hw_enforced: AuthorizationList<'a>,
275 }
276 
277 impl<'a> AssociatedOid for AttestationExtension<'a> {
278     const OID: ObjectIdentifier = ATTESTATION_EXTENSION_OID;
279 }
280 
281 /// Security level enumeration
282 /// ```asn1
283 /// SecurityLevel ::= ENUMERATED {
284 ///     Software                   (0),
285 ///     TrustedEnvironment         (1),
286 ///     StrongBox                  (2),
287 /// }
288 /// ```
289 #[repr(u32)]
290 #[derive(Debug, Clone, Copy, Enumerated, PartialEq)]
291 enum SecurityLevel {
292     Software = 0,
293     TrustedEnvironment = 1,
294     Strongbox = 2,
295 }
296 
297 /// Build an ASN.1 DER-encoded attestation extension.
298 #[allow(clippy::too_many_arguments)]
attestation_extension<'a>( keymint_version: i32, challenge: &'a [u8], app_id: &'a [u8], security_level: keymint::SecurityLevel, attestation_ids: Option<&'a crate::AttestationIdInfo>, params: &'a [KeyParam], chars: &'a [KeyCharacteristics], unique_id: &'a Vec<u8>, boot_info: &'a keymint::BootInfo, ) -> Result<AttestationExtension<'a>, Error>299 pub(crate) fn attestation_extension<'a>(
300     keymint_version: i32,
301     challenge: &'a [u8],
302     app_id: &'a [u8],
303     security_level: keymint::SecurityLevel,
304     attestation_ids: Option<&'a crate::AttestationIdInfo>,
305     params: &'a [KeyParam],
306     chars: &'a [KeyCharacteristics],
307     unique_id: &'a Vec<u8>,
308     boot_info: &'a keymint::BootInfo,
309 ) -> Result<AttestationExtension<'a>, Error> {
310     let mut sw_chars: &[KeyParam] = &[];
311     let mut hw_chars: &[KeyParam] = &[];
312     for characteristic in chars.iter() {
313         match characteristic.security_level {
314             keymint::SecurityLevel::Keystore | keymint::SecurityLevel::Software => {
315                 sw_chars = &characteristic.authorizations
316             }
317             l if l == security_level => hw_chars = &characteristic.authorizations,
318             l => {
319                 return Err(km_err!(
320                     InvalidTag,
321                     "found characteristics for unexpected security level {:?}",
322                     l,
323                 ))
324             }
325         }
326     }
327     let (sw_params, hw_params): (&[KeyParam], &[KeyParam]) = match security_level {
328         keymint::SecurityLevel::Software => (params, &[]),
329         _ => (&[], params),
330     };
331     let sw_enforced =
332         AuthorizationList::new(sw_chars, sw_params, attestation_ids, None, Some(app_id))?;
333     let hw_enforced = AuthorizationList::new(
334         hw_chars,
335         hw_params,
336         attestation_ids,
337         Some(RootOfTrust::from(boot_info)),
338         None,
339     )?;
340     let sec_level = SecurityLevel::try_from(security_level as u32)
341         .map_err(|_| km_err!(InvalidArgument, "invalid security level {:?}", security_level))?;
342     let ext = AttestationExtension {
343         attestation_version: keymint_version,
344         attestation_security_level: sec_level,
345         keymint_version,
346         keymint_security_level: sec_level,
347         attestation_challenge: challenge,
348         unique_id,
349         sw_enforced,
350         hw_enforced,
351     };
352     Ok(ext)
353 }
354 
355 /// Struct for creating ASN.1 DER-serialized `AuthorizationList`. The fields in the ASN1
356 /// sequence are categorized into four fields in the struct based on their usage.
357 /// ```asn1
358 /// AuthorizationList ::= SEQUENCE {
359 ///     purpose                    [1] EXPLICIT SET OF INTEGER OPTIONAL,
360 ///     algorithm                  [2] EXPLICIT INTEGER OPTIONAL,
361 ///     keySize                    [3] EXPLICIT INTEGER OPTIONAL,
362 ///     blockMode                  [4] EXPLICIT SET OF INTEGER OPTIONAL, -- symmetric only
363 ///     digest                     [5] EXPLICIT SET OF INTEGER OPTIONAL,
364 ///     padding                    [6] EXPLICIT SET OF INTEGER OPTIONAL,
365 ///     callerNonce                [7] EXPLICIT NULL OPTIONAL, -- symmetric only
366 ///     minMacLength               [8] EXPLICIT INTEGER OPTIONAL, -- symmetric only
367 ///     ecCurve                    [10] EXPLICIT INTEGER OPTIONAL,
368 ///     rsaPublicExponent          [200] EXPLICIT INTEGER OPTIONAL,
369 ///     mgfDigest                  [203] EXPLICIT SET OF INTEGER OPTIONAL,
370 ///     rollbackResistance         [303] EXPLICIT NULL OPTIONAL,
371 ///     earlyBootOnly              [305] EXPLICIT NULL OPTIONAL,
372 ///     activeDateTime             [400] EXPLICIT INTEGER OPTIONAL,
373 ///     originationExpireDateTime  [401] EXPLICIT INTEGER OPTIONAL,
374 ///     usageExpireDateTime        [402] EXPLICIT INTEGER OPTIONAL,
375 ///     usageCountLimit            [405] EXPLICIT INTEGER OPTIONAL,
376 ///     userSecureId               [502] EXPLICIT INTEGER OPTIONAL, -- only used on import
377 ///     noAuthRequired             [503] EXPLICIT NULL OPTIONAL,
378 ///     userAuthType               [504] EXPLICIT INTEGER OPTIONAL,
379 ///     authTimeout                [505] EXPLICIT INTEGER OPTIONAL,
380 ///     allowWhileOnBody           [506] EXPLICIT NULL OPTIONAL,
381 ///     trustedUserPresenceReq     [507] EXPLICIT NULL OPTIONAL,
382 ///     trustedConfirmationReq     [508] EXPLICIT NULL OPTIONAL,
383 ///     unlockedDeviceReq          [509] EXPLICIT NULL OPTIONAL,
384 ///     creationDateTime           [701] EXPLICIT INTEGER OPTIONAL,
385 ///     origin                     [702] EXPLICIT INTEGER OPTIONAL,
386 ///     rootOfTrust                [704] EXPLICIT RootOfTrust OPTIONAL,
387 ///     osVersion                  [705] EXPLICIT INTEGER OPTIONAL,
388 ///     osPatchLevel               [706] EXPLICIT INTEGER OPTIONAL,
389 ///     attestationApplicationId   [709] EXPLICIT OCTET_STRING OPTIONAL,
390 ///     attestationIdBrand         [710] EXPLICIT OCTET_STRING OPTIONAL,
391 ///     attestationIdDevice        [711] EXPLICIT OCTET_STRING OPTIONAL,
392 ///     attestationIdProduct       [712] EXPLICIT OCTET_STRING OPTIONAL,
393 ///     attestationIdSerial        [713] EXPLICIT OCTET_STRING OPTIONAL,
394 ///     attestationIdImei          [714] EXPLICIT OCTET_STRING OPTIONAL,
395 ///     attestationIdMeid          [715] EXPLICIT OCTET_STRING OPTIONAL,
396 ///     attestationIdManufacturer  [716] EXPLICIT OCTET_STRING OPTIONAL,
397 ///     attestationIdModel         [717] EXPLICIT OCTET_STRING OPTIONAL,
398 ///     vendorPatchLevel           [718] EXPLICIT INTEGER OPTIONAL,
399 ///     bootPatchLevel             [719] EXPLICIT INTEGER OPTIONAL,
400 ///     deviceUniqueAttestation    [720] EXPLICIT NULL OPTIONAL,
401 ///     attestationIdSecondImei    [723] EXPLICIT OCTET_STRING OPTIONAL,
402 /// }
403 /// ```
404 #[derive(Debug, Clone, PartialEq, Eq)]
405 pub struct AuthorizationList<'a> {
406     pub auths: Cow<'a, [KeyParam]>,
407     pub keygen_params: Cow<'a, [KeyParam]>,
408     pub rot_info: Option<KeyParam>,
409     pub app_id: Option<KeyParam>,
410 }
411 
412 /// Macro to check that a specified attestation ID matches the provisioned value.
413 macro_rules! check_attestation_id {
414     {
415         $params:expr, $variant:ident, $mustmatch:expr
416     } => {
417         {
418             if let Some(val) = get_opt_tag_value!($params, $variant)? {
419                 match $mustmatch {
420                     None => return Err(km_err!(CannotAttestIds,
421                                                "no attestation IDs provisioned")),
422                     Some(want)  => if val != want {
423                         return Err(km_err!(CannotAttestIds,
424                                            "attestation ID mismatch for {}",
425                                            stringify!($variant)))
426                     }
427                 }
428             }
429         }
430     }
431 }
432 
433 impl<'a> AuthorizationList<'a> {
434     /// Build an `AuthorizationList` ready for serialization. This constructor will fail if device
435     /// ID attestation is required but the relevant IDs are missing or mismatched.
new( auths: &'a [KeyParam], keygen_params: &'a [KeyParam], attestation_ids: Option<&'a crate::AttestationIdInfo>, rot_info: Option<RootOfTrust<'a>>, app_id: Option<&'a [u8]>, ) -> Result<Self, Error>436     fn new(
437         auths: &'a [KeyParam],
438         keygen_params: &'a [KeyParam],
439         attestation_ids: Option<&'a crate::AttestationIdInfo>,
440         rot_info: Option<RootOfTrust<'a>>,
441         app_id: Option<&'a [u8]>,
442     ) -> Result<Self, Error> {
443         check_attestation_id!(keygen_params, AttestationIdBrand, attestation_ids.map(|v| &v.brand));
444         check_attestation_id!(
445             keygen_params,
446             AttestationIdDevice,
447             attestation_ids.map(|v| &v.device)
448         );
449         check_attestation_id!(
450             keygen_params,
451             AttestationIdProduct,
452             attestation_ids.map(|v| &v.product)
453         );
454         check_attestation_id!(
455             keygen_params,
456             AttestationIdSerial,
457             attestation_ids.map(|v| &v.serial)
458         );
459         check_attestation_id!(keygen_params, AttestationIdImei, attestation_ids.map(|v| &v.imei));
460         check_attestation_id!(
461             keygen_params,
462             AttestationIdSecondImei,
463             attestation_ids.map(|v| &v.imei2)
464         );
465         check_attestation_id!(keygen_params, AttestationIdMeid, attestation_ids.map(|v| &v.meid));
466         check_attestation_id!(
467             keygen_params,
468             AttestationIdManufacturer,
469             attestation_ids.map(|v| &v.manufacturer)
470         );
471         check_attestation_id!(keygen_params, AttestationIdModel, attestation_ids.map(|v| &v.model));
472 
473         let encoded_rot = if let Some(rot) = rot_info {
474             Some(rot.to_der().map_err(|e| der_err!(e, "failed to encode RoT"))?)
475         } else {
476             None
477         };
478         Ok(Self {
479             auths: auths.into(),
480             keygen_params: keygen_params.into(),
481             rot_info: encoded_rot.map(KeyParam::RootOfTrust),
482             app_id: match app_id {
483                 Some(app_id) => Some(KeyParam::AttestationApplicationId(try_to_vec(app_id)?)),
484                 None => None,
485             },
486         })
487     }
488 
489     /// Build an `AuthorizationList` using a set of key parameters.
490     /// The checks for the attestation ids are not run here in contrast to `AuthorizationList::new`
491     /// because this method is used to construct an `AuthorizationList` in the decode path rather
492     /// than in the encode path. Note: decode path is currently used only by
493     /// `KeyMintTa::import_wrapped_key` functionality, which only uses `auth` field of
494     /// `AuthorizationList`. Decoding for the whole `AuthorizationList` is added here for the
495     /// completeness and anticipating a future use case of decoding the attestation extension from
496     /// an X.509 certificate.
new_from_key_params(key_params: Vec<KeyParam>) -> Result<Self, der::Error>497     fn new_from_key_params(key_params: Vec<KeyParam>) -> Result<Self, der::Error> {
498         let mut auths = Vec::new();
499         let mut keygen_params = Vec::new();
500         let mut rot: Option<KeyParam> = None;
501         let mut attest_app_id: Option<KeyParam> = None;
502 
503         // Divide key parameters into key characteristics and key generation parameters.
504         for param in key_params {
505             match param {
506                 KeyParam::RootOfTrust(_) => rot = Some(param),
507                 KeyParam::AttestationApplicationId(_) => attest_app_id = Some(param),
508                 KeyParam::AttestationIdBrand(_)
509                 | KeyParam::AttestationIdDevice(_)
510                 | KeyParam::AttestationIdProduct(_)
511                 | KeyParam::AttestationIdSerial(_)
512                 | KeyParam::AttestationIdImei(_)
513                 | KeyParam::AttestationIdSecondImei(_)
514                 | KeyParam::AttestationIdMeid(_)
515                 | KeyParam::AttestationIdManufacturer(_)
516                 | KeyParam::AttestationIdModel(_) => {
517                     keygen_params.try_push(param).map_err(der_alloc_err)?
518                 }
519                 _ => auths.try_push(param).map_err(der_alloc_err)?,
520             }
521         }
522         Ok(AuthorizationList {
523             auths: auths.into(),
524             keygen_params: keygen_params.into(),
525             rot_info: rot,
526             app_id: attest_app_id,
527         })
528     }
529 }
530 
531 /// Convert an error into a `der::Error` indicating allocation failure.
532 #[inline]
der_alloc_err<T>(_e: T) -> der::Error533 fn der_alloc_err<T>(_e: T) -> der::Error {
534     der::Error::new(der::ErrorKind::Overlength, der::Length::ZERO)
535 }
536 
537 /// All the fields of AuthorizationList sequence are optional. Therefore, the expected tag and the
538 /// decoded tag might be different. If they don't match, return the decoded tag to be used in a
539 /// future call to this method. If the two tags match, continue to read the value,
540 /// populate key parameters and return None, so that the next call to this method will
541 /// decode the tag from bytes. See the implementation of [`der::DecodeValue`] trait for
542 /// AuthorizationList.
decode_opt_field<'a, R: der::Reader<'a>>( decoder: &mut R, already_read_tag: Option<keymint::Tag>, expected_tag: keymint::Tag, key_params: &mut Vec<KeyParam>, ) -> Result<Option<keymint::Tag>, der::Error>543 fn decode_opt_field<'a, R: der::Reader<'a>>(
544     decoder: &mut R,
545     already_read_tag: Option<keymint::Tag>,
546     expected_tag: keymint::Tag,
547     key_params: &mut Vec<KeyParam>,
548 ) -> Result<Option<keymint::Tag>, der::Error> {
549     // Decode the tag if no tag is provided
550     let tag =
551         if already_read_tag.is_none() { decode_tag_from_bytes(decoder)? } else { already_read_tag };
552     match tag {
553         Some(tag) if tag == expected_tag => {
554             // Decode the length of the inner encoding
555             let inner_len = Length::decode(decoder)?;
556             if decoder.remaining_len() < inner_len {
557                 return Err(der::ErrorKind::Incomplete {
558                     expected_len: inner_len,
559                     actual_len: decoder.remaining_len(),
560                 }
561                 .into());
562             }
563             let next_tlv = decoder.tlv_bytes()?;
564             decode_value_from_bytes(expected_tag, next_tlv, key_params)?;
565             Ok(None)
566         }
567         Some(tag) => Ok(Some(tag)), // Return the tag for which the value is unread.
568         None => Ok(None),
569     }
570 }
571 
572 macro_rules! process_authz_list_tags {
573     {$decoder:expr, $key_params:expr, ($($tag:ident),*)} => {
574         let mut non_consumed_tag: Option<Tag> = None;
575         ($(non_consumed_tag = decode_opt_field($decoder,
576                                                non_consumed_tag,
577                                                Tag::$tag,
578                                                $key_params)?),*);
579         if non_consumed_tag.is_some(){
580             return Err($decoder.error(der::ErrorKind::Incomplete {
581                 expected_len: Length::ZERO,
582                 actual_len: $decoder.remaining_len(),
583             }));
584         }
585     };
586 }
587 
588 /// Implementation of [`der::DecodeValue`] which constructs an AuthorizationList from bytes.
589 impl<'a> der::DecodeValue<'a> for AuthorizationList<'a> {
decode_value<R: der::Reader<'a>>(decoder: &mut R, header: der::Header) -> der::Result<Self>590     fn decode_value<R: der::Reader<'a>>(decoder: &mut R, header: der::Header) -> der::Result<Self> {
591         // TODO: define a MAX_SIZE for AuthorizationList and check whether the actual length from
592         // the length field of header is less than the MAX_SIZE
593 
594         // Check for an empty sequence
595         if header.length.is_zero() {
596             return Ok(AuthorizationList {
597                 auths: Vec::new().into(),
598                 keygen_params: Vec::new().into(),
599                 rot_info: None,
600                 app_id: None,
601             });
602         }
603         if decoder.remaining_len() < header.length {
604             return Err(der::ErrorKind::Incomplete {
605                 expected_len: header.length,
606                 actual_len: decoder.remaining_len(),
607             })?;
608         }
609         let mut key_params = Vec::new();
610         process_authz_list_tags!(
611             decoder,
612             &mut key_params,
613             (
614                 Purpose,
615                 Algorithm,
616                 KeySize,
617                 BlockMode,
618                 Digest,
619                 Padding,
620                 CallerNonce,
621                 MinMacLength,
622                 EcCurve,
623                 RsaPublicExponent,
624                 RsaOaepMgfDigest,
625                 RollbackResistance,
626                 EarlyBootOnly,
627                 ActiveDatetime,
628                 OriginationExpireDatetime,
629                 UsageExpireDatetime,
630                 UsageCountLimit,
631                 UserSecureId,
632                 NoAuthRequired,
633                 UserAuthType,
634                 AuthTimeout,
635                 AllowWhileOnBody,
636                 TrustedUserPresenceRequired,
637                 TrustedConfirmationRequired,
638                 UnlockedDeviceRequired,
639                 CreationDatetime,
640                 CreationDatetime,
641                 Origin,
642                 RootOfTrust,
643                 OsVersion,
644                 OsPatchlevel,
645                 AttestationApplicationId,
646                 AttestationIdBrand,
647                 AttestationIdDevice,
648                 AttestationIdProduct,
649                 AttestationIdSerial,
650                 AttestationIdSerial,
651                 AttestationIdSerial,
652                 AttestationIdImei,
653                 AttestationIdMeid,
654                 AttestationIdManufacturer,
655                 AttestationIdModel,
656                 VendorPatchlevel,
657                 BootPatchlevel,
658                 DeviceUniqueAttestation,
659                 AttestationIdSecondImei
660             )
661         );
662 
663         // Process the key params and construct the `AuthorizationList`
664         AuthorizationList::new_from_key_params(key_params)
665     }
666 }
667 
668 // Macros to decode key parameters from their ASN.1 encoding in one of the forms:
669 //   field    [<tag>] EXPLICIT SET OF INTEGER OPTIONAL
670 //   field    [<tag>] EXPLICIT INTEGER OPTIONAL
671 //   field    [<tag>] EXPLICIT NULL OPTIONAL
672 //   field    [<tag>] EXPLICIT OCTET STRING OPTIONAL
673 // There are three different variants for the INTEGER type.
674 
675 macro_rules! key_params_from_asn1_set_of_integer {
676     {$variant:ident, $tlv_bytes:expr, $key_params:expr} => {
677         let vals = SetOfVec::<i32>::from_der($tlv_bytes)?;
678         for val in vals.into_vec() {
679             $key_params.try_push(KeyParam::$variant(val.try_into().map_err(
680                 |_e| der::ErrorKind::Value {tag: der::Tag::Set})?)).map_err(der_alloc_err)?;
681         }
682     }
683 }
684 
685 macro_rules! key_param_from_asn1_integer {
686     {$variant:ident, $int_type:ident, $tlv_bytes:expr, $key_params:expr} => {
687         let val = $int_type::from_der($tlv_bytes)?;
688         $key_params.try_push(KeyParam::$variant(val.try_into().map_err(
689                 |_e| der::ErrorKind::Value {tag: der::Tag::Integer})?)).map_err(der_alloc_err)?;
690     }
691 }
692 
693 macro_rules! key_param_from_asn1_integer_newtype {
694     {$variant:ident, $int_type:ident, $newtype:ident, $tlv_bytes:expr, $key_params:expr} => {
695         let val = $int_type::from_der($tlv_bytes)?;
696         $key_params.try_push(KeyParam::$variant($newtype(val.try_into().map_err(
697                 |_e| der::ErrorKind::Value {tag: der::Tag::Integer})?))).map_err(der_alloc_err)?;
698     }
699 }
700 
701 macro_rules! key_param_from_asn1_null {
702     {$variant:ident, $tlv_bytes:expr, $key_params:expr} => {
703         Null::from_der($tlv_bytes)?;
704         $key_params.try_push(KeyParam::$variant).map_err(der_alloc_err)?;
705     };
706 }
707 
708 macro_rules! key_param_from_asn1_integer_datetime {
709     {$variant:ident, $tlv_bytes:expr, $key_params:expr} => {
710         let val = i64::from_der($tlv_bytes)?;
711         $key_params
712             .try_push(KeyParam::$variant(DateTime{ms_since_epoch: val}))
713             .map_err(der_alloc_err)?;
714     };
715 }
716 
717 macro_rules! key_param_from_asn1_octet_string {
718     {$variant:ident, $tlv_bytes:expr, $key_params:expr} => {
719         let val = OctetStringRef::from_der($tlv_bytes)?;
720         $key_params.try_push(KeyParam::$variant(try_to_vec(val.as_bytes())
721                                                 .map_err(der_alloc_err)?)).map_err(der_alloc_err)?;
722     };
723 }
724 
decode_value_from_bytes( tag: keymint::Tag, tlv_bytes: &[u8], key_params: &mut Vec<KeyParam>, ) -> Result<(), der::Error>725 fn decode_value_from_bytes(
726     tag: keymint::Tag,
727     tlv_bytes: &[u8],
728     key_params: &mut Vec<KeyParam>,
729 ) -> Result<(), der::Error> {
730     match tag {
731         Tag::Purpose => {
732             key_params_from_asn1_set_of_integer!(Purpose, tlv_bytes, key_params);
733         }
734         Tag::Algorithm => {
735             key_param_from_asn1_integer!(Algorithm, i32, tlv_bytes, key_params);
736         }
737         Tag::KeySize => {
738             key_param_from_asn1_integer_newtype!(
739                 KeySize,
740                 u32,
741                 KeySizeInBits,
742                 tlv_bytes,
743                 key_params
744             );
745         }
746         Tag::BlockMode => {
747             key_params_from_asn1_set_of_integer!(BlockMode, tlv_bytes, key_params);
748         }
749         Tag::Digest => {
750             key_params_from_asn1_set_of_integer!(Digest, tlv_bytes, key_params);
751         }
752         Tag::Padding => {
753             key_params_from_asn1_set_of_integer!(Padding, tlv_bytes, key_params);
754         }
755         Tag::CallerNonce => {
756             key_param_from_asn1_null!(CallerNonce, tlv_bytes, key_params);
757         }
758         Tag::MinMacLength => {
759             key_param_from_asn1_integer!(MinMacLength, u32, tlv_bytes, key_params);
760         }
761         Tag::EcCurve => {
762             key_param_from_asn1_integer!(EcCurve, i32, tlv_bytes, key_params);
763         }
764         Tag::RsaPublicExponent => {
765             key_param_from_asn1_integer_newtype!(
766                 RsaPublicExponent,
767                 u64,
768                 RsaExponent,
769                 tlv_bytes,
770                 key_params
771             );
772         }
773         Tag::RsaOaepMgfDigest => {
774             key_params_from_asn1_set_of_integer!(RsaOaepMgfDigest, tlv_bytes, key_params);
775         }
776         Tag::RollbackResistance => {
777             key_param_from_asn1_null!(RollbackResistance, tlv_bytes, key_params);
778         }
779         Tag::EarlyBootOnly => {
780             key_param_from_asn1_null!(EarlyBootOnly, tlv_bytes, key_params);
781         }
782         Tag::ActiveDatetime => {
783             key_param_from_asn1_integer_datetime!(ActiveDatetime, tlv_bytes, key_params);
784         }
785         Tag::OriginationExpireDatetime => {
786             key_param_from_asn1_integer_datetime!(OriginationExpireDatetime, tlv_bytes, key_params);
787         }
788         Tag::UsageExpireDatetime => {
789             key_param_from_asn1_integer_datetime!(UsageExpireDatetime, tlv_bytes, key_params);
790         }
791         Tag::UsageCountLimit => {
792             key_param_from_asn1_integer!(UsageCountLimit, u32, tlv_bytes, key_params);
793         }
794         Tag::UserSecureId => {
795             // Note that the `UserSecureId` tag has tag type `ULONG_REP` indicating that it can be
796             // repeated, but the ASN.1 schema for `AuthorizationList` has this field as having type
797             // `INTEGER` not `SET OF INTEGER`. This reflects the special usage of `UserSecureId`
798             // in `importWrappedKey()` processing.
799             key_param_from_asn1_integer!(UserSecureId, u64, tlv_bytes, key_params);
800         }
801         Tag::NoAuthRequired => {
802             key_param_from_asn1_null!(NoAuthRequired, tlv_bytes, key_params);
803         }
804         Tag::UserAuthType => {
805             key_param_from_asn1_integer!(UserAuthType, u32, tlv_bytes, key_params);
806         }
807         Tag::AuthTimeout => {
808             key_param_from_asn1_integer!(AuthTimeout, u32, tlv_bytes, key_params);
809         }
810         Tag::AllowWhileOnBody => {
811             key_param_from_asn1_null!(AllowWhileOnBody, tlv_bytes, key_params);
812         }
813         Tag::TrustedUserPresenceRequired => {
814             key_param_from_asn1_null!(TrustedUserPresenceRequired, tlv_bytes, key_params);
815         }
816         Tag::TrustedConfirmationRequired => {
817             key_param_from_asn1_null!(TrustedConfirmationRequired, tlv_bytes, key_params);
818         }
819         Tag::UnlockedDeviceRequired => {
820             key_param_from_asn1_null!(UnlockedDeviceRequired, tlv_bytes, key_params);
821         }
822         Tag::CreationDatetime => {
823             key_param_from_asn1_integer_datetime!(CreationDatetime, tlv_bytes, key_params);
824         }
825         Tag::Origin => {
826             key_param_from_asn1_integer!(Origin, i32, tlv_bytes, key_params);
827         }
828         Tag::RootOfTrust => {
829             key_params
830                 .try_push(KeyParam::RootOfTrust(try_to_vec(tlv_bytes).map_err(der_alloc_err)?))
831                 .map_err(der_alloc_err)?;
832         }
833         Tag::OsVersion => {
834             key_param_from_asn1_integer!(OsVersion, u32, tlv_bytes, key_params);
835         }
836         Tag::OsPatchlevel => {
837             key_param_from_asn1_integer!(OsPatchlevel, u32, tlv_bytes, key_params);
838         }
839         Tag::AttestationApplicationId => {
840             key_param_from_asn1_octet_string!(AttestationApplicationId, tlv_bytes, key_params);
841         }
842         Tag::AttestationIdBrand => {
843             key_param_from_asn1_octet_string!(AttestationIdBrand, tlv_bytes, key_params);
844         }
845         Tag::AttestationIdDevice => {
846             key_param_from_asn1_octet_string!(AttestationIdDevice, tlv_bytes, key_params);
847         }
848         Tag::AttestationIdProduct => {
849             key_param_from_asn1_octet_string!(AttestationIdProduct, tlv_bytes, key_params);
850         }
851         Tag::AttestationIdSerial => {
852             key_param_from_asn1_octet_string!(AttestationIdSerial, tlv_bytes, key_params);
853         }
854         Tag::AttestationIdImei => {
855             key_param_from_asn1_octet_string!(AttestationIdImei, tlv_bytes, key_params);
856         }
857         Tag::AttestationIdSecondImei => {
858             key_param_from_asn1_octet_string!(AttestationIdSecondImei, tlv_bytes, key_params);
859         }
860         Tag::AttestationIdMeid => {
861             key_param_from_asn1_octet_string!(AttestationIdMeid, tlv_bytes, key_params);
862         }
863         Tag::AttestationIdManufacturer => {
864             key_param_from_asn1_octet_string!(AttestationIdManufacturer, tlv_bytes, key_params);
865         }
866         Tag::AttestationIdModel => {
867             key_param_from_asn1_octet_string!(AttestationIdModel, tlv_bytes, key_params);
868         }
869         Tag::VendorPatchlevel => {
870             key_param_from_asn1_integer!(VendorPatchlevel, u32, tlv_bytes, key_params);
871         }
872         Tag::BootPatchlevel => {
873             key_param_from_asn1_integer!(BootPatchlevel, u32, tlv_bytes, key_params);
874         }
875         Tag::DeviceUniqueAttestation => {
876             key_param_from_asn1_null!(DeviceUniqueAttestation, tlv_bytes, key_params);
877         }
878         _ => {
879             // Note: `der::Error` or `der::ErrorKind` is not expressive enough for decoding
880             // tags in high tag form. Documentation of this error kind does not match this
881             // situation. But we use the `der::ErrorKind` as close as possible.
882             return Err(der::ErrorKind::TagNumberInvalid.into());
883         }
884     }
885     Ok(())
886 }
887 
888 /// Decode the tag of a field in AuthorizationList.
decode_tag_from_bytes<'a, R: der::Reader<'a>>( decoder: &mut R, ) -> Result<Option<keymint::Tag>, der::Error>889 fn decode_tag_from_bytes<'a, R: der::Reader<'a>>(
890     decoder: &mut R,
891 ) -> Result<Option<keymint::Tag>, der::Error> {
892     // Avoid reading for tags beyond the size of the encoded AuthorizationList
893     if decoder.remaining_len() == Length::ZERO {
894         return Ok(None);
895     }
896     let b1 = decoder.read_byte()?;
897     let raw_tag = if b1 & 0xbfu8 == 0xbfu8 {
898         // High tag form, read the next byte
899         let b2 = decoder.read_byte()?;
900         if b2 & 0x80u8 == 0x80u8 {
901             // Encoded tag length is 3, read the next byte
902             let b3 = decoder.read_byte()?;
903             let tag_byte: u16 = ((b2 ^ 0x80u8) as u16) << 7;
904             (tag_byte | b3 as u16) as u32
905         } else {
906             b2 as u32
907         }
908     } else {
909         (b1 ^ 0b10100000u8) as u32
910     };
911     let tag = from_raw_tag_value(raw_tag);
912     if tag == Tag::Invalid {
913         // Note: der::Error or der::ErrorKind is not expressive enough for decoding tags
914         // in high tag form. Documentation of this error kind does not match this situation.
915         // Find a better way to express the error.
916         Err(der::ErrorKind::TagNumberInvalid.into())
917     } else {
918         Ok(Some(tag))
919     }
920 }
921 
922 // Macros to extract key characteristics for ASN.1 encoding into one of the forms:
923 //   field    [<tag>] EXPLICIT SET OF INTEGER OPTIONAL
924 //   field    [<tag>] EXPLICIT INTEGER OPTIONAL
925 //   field    [<tag>] EXPLICIT NULL OPTIONAL
926 //   field    [<tag>] EXPLICIT OCTET STRING OPTIONAL
927 // together with an extra variant that deals with OCTET STRING values that must match
928 // a provisioned attestation ID value.
929 macro_rules! asn1_set_of_integer {
930     { $params:expr, $variant:ident } => {
931         {
932             let mut results = Vec::new();
933             for param in $params.as_ref() {
934                 if let KeyParam::$variant(v) = param {
935                     results.try_push(v.clone()).map_err(der_alloc_err)?;
936                 }
937             }
938             if !results.is_empty() {
939                 // The input key characteristics have been sorted and so are in numerical order, but
940                 // may contain duplicates that need to be weeded out.
941                 let mut set = der::asn1::SetOfVec::new();
942                 let mut prev_val = None;
943                 for val in results {
944                     let val = val as i64;
945                     if let Some(prev) = prev_val {
946                         if prev == val {
947                             continue; // skip duplicate
948                         }
949                     }
950                     set.insert_ordered(val)?;
951                     prev_val = Some(val);
952                 }
953                 Some(ExplicitTaggedValue {
954                     tag: raw_tag_value(Tag::$variant),
955                     val: set,
956                 })
957             } else {
958                 None
959             }
960         }
961     }
962 }
963 macro_rules! asn1_integer {
964     { $params:expr, $variant:ident } => {
965         if let Some(val) = get_opt_tag_value!($params.as_ref(), $variant).map_err(|_e| {
966             log::warn!("failed to get {} value for ext", stringify!($variant));
967             der::Error::new(der::ErrorKind::Failed, der::Length::ZERO)
968         })? {
969             Some(ExplicitTaggedValue {
970                 tag: raw_tag_value(Tag::$variant),
971                 val: *val as i64
972             })
973         } else {
974             None
975         }
976     }
977 }
978 macro_rules! asn1_integer_newtype {
979     { $params:expr, $variant:ident } => {
980         if let Some(val) = get_opt_tag_value!($params.as_ref(), $variant).map_err(|_e| {
981             log::warn!("failed to get {} value for ext", stringify!($variant));
982             der::Error::new(der::ErrorKind::Failed, der::Length::ZERO)
983         })? {
984             Some(ExplicitTaggedValue {
985                 tag: raw_tag_value(Tag::$variant),
986                 val: val.0 as i64
987             })
988         } else {
989             None
990         }
991     }
992 }
993 macro_rules! asn1_integer_datetime {
994     { $params:expr, $variant:ident } => {
995         if let Some(val) = get_opt_tag_value!($params.as_ref(), $variant).map_err(|_e| {
996             log::warn!("failed to get {} value for ext", stringify!($variant));
997             der::Error::new(der::ErrorKind::Failed, der::Length::ZERO)
998         })? {
999             Some(ExplicitTaggedValue {
1000                 tag: raw_tag_value(Tag::$variant),
1001                 val: val.ms_since_epoch
1002             })
1003         } else {
1004             None
1005         }
1006     }
1007 }
1008 macro_rules! asn1_null {
1009     { $params:expr, $variant:ident } => {
1010         if get_bool_tag_value!($params.as_ref(), $variant).map_err(|_e| {
1011             log::warn!("failed to get {} value for ext", stringify!($variant));
1012             der::Error::new(der::ErrorKind::Failed, der::Length::ZERO)
1013         })? {
1014             Some(ExplicitTaggedValue {
1015                 tag: raw_tag_value(Tag::$variant),
1016                 val: ()
1017             })
1018         } else {
1019             None
1020         }
1021     }
1022 }
1023 macro_rules! asn1_octet_string {
1024     { $params:expr, $variant:ident } => {
1025         if let Some(val) = get_opt_tag_value!($params.as_ref(), $variant).map_err(|_e| {
1026             log::warn!("failed to get {} value for ext", stringify!($variant));
1027             der::Error::new(der::ErrorKind::Failed, der::Length::ZERO)
1028         })? {
1029             Some(ExplicitTaggedValue {
1030                 tag: raw_tag_value(Tag::$variant),
1031                 val: der::asn1::OctetStringRef::new(val)?,
1032             })
1033         } else {
1034             None
1035         }
1036     }
1037 }
1038 
asn1_val<T: Encode>( val: Option<ExplicitTaggedValue<T>>, writer: &mut impl der::Writer, ) -> der::Result<()>1039 fn asn1_val<T: Encode>(
1040     val: Option<ExplicitTaggedValue<T>>,
1041     writer: &mut impl der::Writer,
1042 ) -> der::Result<()> {
1043     if let Some(val) = val {
1044         val.encode(writer)
1045     } else {
1046         Ok(())
1047     }
1048 }
1049 
asn1_len<T: Encode>(val: Option<ExplicitTaggedValue<T>>) -> der::Result<Length>1050 fn asn1_len<T: Encode>(val: Option<ExplicitTaggedValue<T>>) -> der::Result<Length> {
1051     match val {
1052         Some(val) => val.encoded_len(),
1053         None => Ok(Length::ZERO),
1054     }
1055 }
1056 
1057 impl<'a> Sequence<'a> for AuthorizationList<'a> {}
1058 
1059 impl<'a> EncodeValue for AuthorizationList<'a> {
value_len(&self) -> der::Result<Length>1060     fn value_len(&self) -> der::Result<Length> {
1061         let mut length = asn1_len(asn1_set_of_integer!(self.auths, Purpose))?
1062             + asn1_len(asn1_integer!(self.auths, Algorithm))?
1063             + asn1_len(asn1_integer_newtype!(self.auths, KeySize))?
1064             + asn1_len(asn1_set_of_integer!(self.auths, BlockMode))?
1065             + asn1_len(asn1_set_of_integer!(self.auths, Digest))?
1066             + asn1_len(asn1_set_of_integer!(self.auths, Padding))?
1067             + asn1_len(asn1_null!(self.auths, CallerNonce))?
1068             + asn1_len(asn1_integer!(self.auths, MinMacLength))?
1069             + asn1_len(asn1_integer!(self.auths, EcCurve))?
1070             + asn1_len(asn1_integer_newtype!(self.auths, RsaPublicExponent))?
1071             + asn1_len(asn1_set_of_integer!(self.auths, RsaOaepMgfDigest))?
1072             + asn1_len(asn1_null!(self.auths, RollbackResistance))?
1073             + asn1_len(asn1_null!(self.auths, EarlyBootOnly))?
1074             + asn1_len(asn1_integer_datetime!(self.auths, ActiveDatetime))?
1075             + asn1_len(asn1_integer_datetime!(self.auths, OriginationExpireDatetime))?
1076             + asn1_len(asn1_integer_datetime!(self.auths, UsageExpireDatetime))?
1077             + asn1_len(asn1_integer!(self.auths, UsageCountLimit))?
1078             + asn1_len(asn1_null!(self.auths, NoAuthRequired))?
1079             + asn1_len(asn1_integer!(self.auths, UserAuthType))?
1080             + asn1_len(asn1_integer!(self.auths, AuthTimeout))?
1081             + asn1_len(asn1_null!(self.auths, AllowWhileOnBody))?
1082             + asn1_len(asn1_null!(self.auths, TrustedUserPresenceRequired))?
1083             + asn1_len(asn1_null!(self.auths, TrustedConfirmationRequired))?
1084             + asn1_len(asn1_null!(self.auths, UnlockedDeviceRequired))?
1085             + asn1_len(asn1_integer_datetime!(self.auths, CreationDatetime))?
1086             + asn1_len(asn1_integer!(self.auths, Origin))?;
1087         if let Some(KeyParam::RootOfTrust(encoded_rot_info)) = &self.rot_info {
1088             length = length
1089                 + ExplicitTaggedValue {
1090                     tag: raw_tag_value(Tag::RootOfTrust),
1091                     val: RootOfTrust::from_der(encoded_rot_info.as_slice())?,
1092                 }
1093                 .encoded_len()?;
1094         }
1095         length = length
1096             + asn1_len(asn1_integer!(self.auths, OsVersion))?
1097             + asn1_len(asn1_integer!(self.auths, OsPatchlevel))?;
1098         if let Some(KeyParam::AttestationApplicationId(app_id)) = &self.app_id {
1099             length = length
1100                 + ExplicitTaggedValue {
1101                     tag: raw_tag_value(Tag::AttestationApplicationId),
1102                     val: der::asn1::OctetStringRef::new(app_id.as_slice())?,
1103                 }
1104                 .encoded_len()?;
1105         }
1106         length = length
1107             + asn1_len(asn1_octet_string!(&self.keygen_params, AttestationIdBrand))?
1108             + asn1_len(asn1_octet_string!(&self.keygen_params, AttestationIdDevice))?
1109             + asn1_len(asn1_octet_string!(&self.keygen_params, AttestationIdProduct))?
1110             + asn1_len(asn1_octet_string!(&self.keygen_params, AttestationIdSerial))?
1111             + asn1_len(asn1_octet_string!(&self.keygen_params, AttestationIdImei))?
1112             + asn1_len(asn1_octet_string!(&self.keygen_params, AttestationIdMeid))?
1113             + asn1_len(asn1_octet_string!(&self.keygen_params, AttestationIdManufacturer))?
1114             + asn1_len(asn1_octet_string!(&self.keygen_params, AttestationIdModel))?
1115             + asn1_len(asn1_integer!(self.auths, VendorPatchlevel))?
1116             + asn1_len(asn1_integer!(self.auths, BootPatchlevel))?
1117             + asn1_len(asn1_null!(self.auths, DeviceUniqueAttestation))?
1118             + asn1_len(asn1_octet_string!(&self.keygen_params, AttestationIdSecondImei))?;
1119         length
1120     }
1121 
encode_value(&self, writer: &mut impl der::Writer) -> der::Result<()>1122     fn encode_value(&self, writer: &mut impl der::Writer) -> der::Result<()> {
1123         asn1_val(asn1_set_of_integer!(self.auths, Purpose), writer)?;
1124         asn1_val(asn1_integer!(self.auths, Algorithm), writer)?;
1125         asn1_val(asn1_integer_newtype!(self.auths, KeySize), writer)?;
1126         asn1_val(asn1_set_of_integer!(self.auths, BlockMode), writer)?;
1127         asn1_val(asn1_set_of_integer!(self.auths, Digest), writer)?;
1128         asn1_val(asn1_set_of_integer!(self.auths, Padding), writer)?;
1129         asn1_val(asn1_null!(self.auths, CallerNonce), writer)?;
1130         asn1_val(asn1_integer!(self.auths, MinMacLength), writer)?;
1131         asn1_val(asn1_integer!(self.auths, EcCurve), writer)?;
1132         asn1_val(asn1_integer_newtype!(self.auths, RsaPublicExponent), writer)?;
1133         asn1_val(asn1_set_of_integer!(self.auths, RsaOaepMgfDigest), writer)?;
1134         asn1_val(asn1_null!(self.auths, RollbackResistance), writer)?;
1135         asn1_val(asn1_null!(self.auths, EarlyBootOnly), writer)?;
1136         asn1_val(asn1_integer_datetime!(self.auths, ActiveDatetime), writer)?;
1137         asn1_val(asn1_integer_datetime!(self.auths, OriginationExpireDatetime), writer)?;
1138         asn1_val(asn1_integer_datetime!(self.auths, UsageExpireDatetime), writer)?;
1139         asn1_val(asn1_integer!(self.auths, UsageCountLimit), writer)?;
1140         // Skip `UserSecureId` as it's only included in the extension for
1141         // importWrappedKey() cases.
1142         asn1_val(asn1_null!(self.auths, NoAuthRequired), writer)?;
1143         asn1_val(asn1_integer!(self.auths, UserAuthType), writer)?;
1144         asn1_val(asn1_integer!(self.auths, AuthTimeout), writer)?;
1145         asn1_val(asn1_null!(self.auths, AllowWhileOnBody), writer)?;
1146         asn1_val(asn1_null!(self.auths, TrustedUserPresenceRequired), writer)?;
1147         asn1_val(asn1_null!(self.auths, TrustedConfirmationRequired), writer)?;
1148         asn1_val(asn1_null!(self.auths, UnlockedDeviceRequired), writer)?;
1149         asn1_val(asn1_integer_datetime!(self.auths, CreationDatetime), writer)?;
1150         asn1_val(asn1_integer!(self.auths, Origin), writer)?;
1151         // Root of trust info is a special case (not in key characteristics).
1152         if let Some(KeyParam::RootOfTrust(encoded_rot_info)) = &self.rot_info {
1153             ExplicitTaggedValue {
1154                 tag: raw_tag_value(Tag::RootOfTrust),
1155                 val: RootOfTrust::from_der(encoded_rot_info.as_slice())?,
1156             }
1157             .encode(writer)?;
1158         }
1159         asn1_val(asn1_integer!(self.auths, OsVersion), writer)?;
1160         asn1_val(asn1_integer!(self.auths, OsPatchlevel), writer)?;
1161         // Attestation application ID is a special case (not in key characteristics).
1162         if let Some(KeyParam::AttestationApplicationId(app_id)) = &self.app_id {
1163             ExplicitTaggedValue {
1164                 tag: raw_tag_value(Tag::AttestationApplicationId),
1165                 val: der::asn1::OctetStringRef::new(app_id.as_slice())?,
1166             }
1167             .encode(writer)?;
1168         }
1169         // Accuracy of attestation IDs has already been checked, so just copy across.
1170         asn1_val(asn1_octet_string!(&self.keygen_params, AttestationIdBrand), writer)?;
1171         asn1_val(asn1_octet_string!(&self.keygen_params, AttestationIdDevice), writer)?;
1172         asn1_val(asn1_octet_string!(&self.keygen_params, AttestationIdProduct), writer)?;
1173         asn1_val(asn1_octet_string!(&self.keygen_params, AttestationIdSerial), writer)?;
1174         asn1_val(asn1_octet_string!(&self.keygen_params, AttestationIdImei), writer)?;
1175         asn1_val(asn1_octet_string!(&self.keygen_params, AttestationIdMeid), writer)?;
1176         asn1_val(asn1_octet_string!(&self.keygen_params, AttestationIdManufacturer), writer)?;
1177         asn1_val(asn1_octet_string!(&self.keygen_params, AttestationIdModel), writer)?;
1178         asn1_val(asn1_integer!(self.auths, VendorPatchlevel), writer)?;
1179         asn1_val(asn1_integer!(self.auths, BootPatchlevel), writer)?;
1180         asn1_val(asn1_null!(self.auths, DeviceUniqueAttestation), writer)?;
1181         asn1_val(asn1_octet_string!(&self.keygen_params, AttestationIdSecondImei), writer)?;
1182 
1183         Ok(())
1184     }
1185 }
1186 
1187 struct ExplicitTaggedValue<T: Encode> {
1188     pub tag: u32,
1189     pub val: T,
1190 }
1191 
1192 impl<T: Encode> ExplicitTaggedValue<T> {
explicit_tag_len(&self) -> der::Result<der::Length>1193     fn explicit_tag_len(&self) -> der::Result<der::Length> {
1194         match self.tag {
1195             0..=0x1e => Ok(der::Length::ONE),
1196             0x1f..=0x7f => Ok(der::Length::new(2)),
1197             0x80..=0x3fff => Ok(der::Length::new(3)),
1198             _ => Err(der::ErrorKind::Overflow.into()),
1199         }
1200     }
1201 
explicit_tag_encode(&self, encoder: &mut dyn der::Writer) -> der::Result<()>1202     fn explicit_tag_encode(&self, encoder: &mut dyn der::Writer) -> der::Result<()> {
1203         match self.tag {
1204             0..=0x1e => {
1205                 // b101vvvvv is context-specific+constructed
1206                 encoder.write_byte(0b10100000u8 | (self.tag as u8))
1207             }
1208             0x1f..=0x7f => {
1209                 // b101 11111 indicates a context-specific+constructed long-form tag number
1210                 encoder.write_byte(0b10111111)?;
1211                 encoder.write_byte(self.tag as u8)
1212             }
1213             0x80..=0x3fff => {
1214                 // b101 11111 indicates a context-specific+constructed long-form tag number
1215                 encoder.write_byte(0b10111111)?;
1216                 encoder.write_byte((self.tag >> 7) as u8 | 0x80u8)?;
1217                 encoder.write_byte((self.tag & 0x007f) as u8)
1218             }
1219             _ => Err(der::ErrorKind::Overflow.into()),
1220         }
1221     }
1222 }
1223 
1224 /// The der library explicitly does not support `TagNumber` values bigger than 31,
1225 /// which are required here.  Work around this by manually providing the encoding functionality.
1226 impl<T: Encode> Encode for ExplicitTaggedValue<T> {
encoded_len(&self) -> der::Result<der::Length>1227     fn encoded_len(&self) -> der::Result<der::Length> {
1228         let inner_len = self.val.encoded_len()?;
1229         self.explicit_tag_len() + inner_len.encoded_len()? + inner_len
1230     }
1231 
encode(&self, encoder: &mut impl der::Writer) -> der::Result<()>1232     fn encode(&self, encoder: &mut impl der::Writer) -> der::Result<()> {
1233         let inner_len = self.val.encoded_len()?;
1234         self.explicit_tag_encode(encoder)?;
1235         inner_len.encode(encoder)?;
1236         self.val.encode(encoder)
1237     }
1238 }
1239 
1240 /// Root of Trust ASN.1 structure
1241 /// ```asn1
1242 ///  * RootOfTrust ::= SEQUENCE {
1243 ///  *     verifiedBootKey            OCTET_STRING,
1244 ///  *     deviceLocked               BOOLEAN,
1245 ///  *     verifiedBootState          VerifiedBootState,
1246 ///  *     # verifiedBootHash must contain 32-byte value that represents the state of all binaries
1247 ///  *     # or other components validated by verified boot.  Updating any verified binary or
1248 ///  *     # component must cause this value to change.
1249 ///  *     verifiedBootHash           OCTET_STRING,
1250 ///  * }
1251 /// ```
1252 #[derive(Debug, Clone, Sequence)]
1253 struct RootOfTrust<'a> {
1254     #[asn1(type = "OCTET STRING")]
1255     verified_boot_key: &'a [u8],
1256     device_locked: bool,
1257     verified_boot_state: VerifiedBootState,
1258     #[asn1(type = "OCTET STRING")]
1259     verified_boot_hash: &'a [u8],
1260 }
1261 
1262 impl<'a> From<&'a keymint::BootInfo> for RootOfTrust<'a> {
from(info: &keymint::BootInfo) -> RootOfTrust1263     fn from(info: &keymint::BootInfo) -> RootOfTrust {
1264         let verified_boot_key: &[u8] = if info.verified_boot_key.is_empty() {
1265             // If an empty verified boot key was passed by the boot loader, set the verified boot
1266             // key in the attestation to all zeroes.
1267             &EMPTY_BOOT_KEY[..]
1268         } else {
1269             &info.verified_boot_key[..]
1270         };
1271         RootOfTrust {
1272             verified_boot_key,
1273             device_locked: info.device_boot_locked,
1274             verified_boot_state: info.verified_boot_state.into(),
1275             verified_boot_hash: &info.verified_boot_hash[..],
1276         }
1277     }
1278 }
1279 
1280 /// Verified Boot State as ASN.1 ENUMERATED type.
1281 ///```asn1
1282 ///  * VerifiedBootState ::= ENUMERATED {
1283 ///  *     Verified                   (0),
1284 ///  *     SelfSigned                 (1),
1285 ///  *     Unverified                 (2),
1286 ///  *     Failed                     (3),
1287 ///  * }
1288 ///```
1289 #[repr(u32)]
1290 #[derive(Debug, Clone, Copy, Enumerated)]
1291 enum VerifiedBootState {
1292     Verified = 0,
1293     SelfSigned = 1,
1294     Unverified = 2,
1295     Failed = 3,
1296 }
1297 
1298 impl From<keymint::VerifiedBootState> for VerifiedBootState {
from(state: keymint::VerifiedBootState) -> VerifiedBootState1299     fn from(state: keymint::VerifiedBootState) -> VerifiedBootState {
1300         match state {
1301             keymint::VerifiedBootState::Verified => VerifiedBootState::Verified,
1302             keymint::VerifiedBootState::SelfSigned => VerifiedBootState::SelfSigned,
1303             keymint::VerifiedBootState::Unverified => VerifiedBootState::Unverified,
1304             keymint::VerifiedBootState::Failed => VerifiedBootState::Failed,
1305         }
1306     }
1307 }
1308 
1309 #[cfg(test)]
1310 mod tests {
1311     use super::*;
1312     use crate::KeyMintHalVersion;
1313 
1314     #[test]
test_attest_ext_encode_decode()1315     fn test_attest_ext_encode_decode() {
1316         let sec_level = SecurityLevel::TrustedEnvironment;
1317         let ext = AttestationExtension {
1318             attestation_version: KeyMintHalVersion::V3 as i32,
1319             attestation_security_level: sec_level,
1320             keymint_version: KeyMintHalVersion::V3 as i32,
1321             keymint_security_level: sec_level,
1322             attestation_challenge: b"abc",
1323             unique_id: b"xxx",
1324             sw_enforced: AuthorizationList::new(&[], &[], None, None, None).unwrap(),
1325             hw_enforced: AuthorizationList::new(
1326                 &[KeyParam::Algorithm(keymint::Algorithm::Ec)],
1327                 &[],
1328                 None,
1329                 Some(RootOfTrust {
1330                     verified_boot_key: &[0xbbu8; 32],
1331                     device_locked: false,
1332                     verified_boot_state: VerifiedBootState::Unverified,
1333                     verified_boot_hash: &[0xee; 32],
1334                 }),
1335                 None,
1336             )
1337             .unwrap(),
1338         };
1339         let got = ext.to_der().unwrap();
1340         let want = concat!(
1341             "3071",   // SEQUENCE
1342             "0202",   // INTEGER len 2
1343             "012c",   // 300
1344             "0a01",   // ENUM len 1
1345             "01",     // 1 (TrustedEnvironment)
1346             "0202",   // INTEGER len 2
1347             "012c",   // 300
1348             "0a01",   // ENUM len 1
1349             "01",     // 1 (TrustedEnvironement)
1350             "0403",   // BYTE STRING len 3
1351             "616263", // b"abc"
1352             "0403",   // BYTE STRING len 3
1353             "787878", // b"xxx"
1354             "3000",   // SEQUENCE len 0
1355             "3055",   // SEQUENCE len 55
1356             "a203",   // EXPLICIT [2]
1357             "0201",   // INTEGER len 1
1358             "03",     // 3 (Algorithm::Ec)
1359             "bf8540",
1360             "4c",   // EXPLICIT [704] len 0x4c
1361             "304a", // SEQUENCE len x4a
1362             "0420", // OCTET STRING len 32
1363             "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
1364             "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
1365             "0101", // BOOLEAN len 1
1366             "00",   // false
1367             "0a01", // ENUMERATED len 1
1368             "02",   // Unverified(2)
1369             "0420", // OCTET STRING len 32
1370             "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
1371             "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
1372         );
1373         assert_eq!(hex::encode(&got), want);
1374         assert_eq!(AttestationExtension::from_der(&got).unwrap(), ext);
1375     }
1376 
1377     #[test]
test_explicit_tagged_value()1378     fn test_explicit_tagged_value() {
1379         assert_eq!(
1380             hex::encode(ExplicitTaggedValue { tag: 2, val: 16 }.to_der().unwrap()),
1381             "a203020110"
1382         );
1383         assert_eq!(
1384             hex::encode(ExplicitTaggedValue { tag: 2, val: () }.to_der().unwrap()),
1385             "a2020500"
1386         );
1387         assert_eq!(
1388             hex::encode(ExplicitTaggedValue { tag: 503, val: 16 }.to_der().unwrap()),
1389             "bf837703020110"
1390         );
1391     }
1392 
1393     #[test]
test_authz_list_encode_decode()1394     fn test_authz_list_encode_decode() {
1395         let authz_list = AuthorizationList::new(
1396             &[KeyParam::Algorithm(keymint::Algorithm::Ec)],
1397             &[],
1398             None,
1399             Some(RootOfTrust {
1400                 verified_boot_key: &[0xbbu8; 32],
1401                 device_locked: false,
1402                 verified_boot_state: VerifiedBootState::Unverified,
1403                 verified_boot_hash: &[0xee; 32],
1404             }),
1405             None,
1406         )
1407         .unwrap();
1408         let got = authz_list.to_der().unwrap();
1409         let want: &str = concat!(
1410             "3055", // SEQUENCE len 55
1411             "a203", // EXPLICIT [2]
1412             "0201", // INTEGER len 1
1413             "03",   // 3 (Algorithm::Ec)
1414             "bf8540",
1415             "4c",   // EXPLICIT [704] len 0x4c
1416             "304a", // SEQUENCE len x4a
1417             "0420", // OCTET STRING len 32
1418             "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
1419             "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
1420             "0101", // BOOLEAN len 1
1421             "00",   // false
1422             "0a01", // ENUMERATED len 1
1423             "02",   // Unverified(2)
1424             "0420", // OCTET STRING len 32
1425             "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
1426             "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
1427         );
1428         // encode
1429         assert_eq!(hex::encode(&got), want);
1430         // decode from encoded
1431         assert_eq!(AuthorizationList::from_der(got.as_slice()).unwrap(), authz_list);
1432     }
1433 
1434     #[test]
test_authz_list_user_secure_id_encode()1435     fn test_authz_list_user_secure_id_encode() {
1436         // Create an authorization list that includes multiple values for SecureUserId.
1437         let authz_list = AuthorizationList::new(
1438             &[
1439                 KeyParam::Algorithm(keymint::Algorithm::Ec),
1440                 KeyParam::UserSecureId(42),
1441                 KeyParam::UserSecureId(43),
1442                 KeyParam::UserSecureId(44),
1443             ],
1444             &[],
1445             None,
1446             Some(RootOfTrust {
1447                 verified_boot_key: &[0xbbu8; 32],
1448                 device_locked: false,
1449                 verified_boot_state: VerifiedBootState::Unverified,
1450                 verified_boot_hash: &[0xee; 32],
1451             }),
1452             None,
1453         )
1454         .unwrap();
1455         let got = authz_list.to_der().unwrap();
1456         // The `SecureUserId` values are *not* included in the generated output.
1457         let want: &str = concat!(
1458             "3055", // SEQUENCE len 55
1459             "a203", // EXPLICIT [2]
1460             "0201", // INTEGER len 1
1461             "03",   // 3 (Algorithm::Ec)
1462             "bf8540",
1463             "4c",   // EXPLICIT [704] len 0x4c
1464             "304a", // SEQUENCE len x4a
1465             "0420", // OCTET STRING len 32
1466             "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
1467             "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
1468             "0101", // BOOLEAN len 1
1469             "00",   // false
1470             "0a01", // ENUMERATED len 1
1471             "02",   // Unverified(2)
1472             "0420", // OCTET STRING len 32
1473             "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
1474             "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
1475         );
1476         // encode
1477         assert_eq!(hex::encode(got), want);
1478     }
1479 
1480     #[test]
test_authz_list_user_secure_id_decode()1481     fn test_authz_list_user_secure_id_decode() {
1482         // Create a DER-encoded `AuthorizationList` that includes a `UserSecureId` value.
1483         let input = hex::decode(concat!(
1484             "305c",   // SEQUENCE
1485             "a203",   // EXPLICIT [2] len 3
1486             "0201",   // INTEGER len 1
1487             "03",     // 3 (Algorithm::Ec)
1488             "bf8376", // EXPLICIT [502]
1489             "03",     // len 3
1490             "0201",   // INTEGER len 1
1491             "02",     // 2
1492             "bf8540", // EXPLICIT [704]
1493             "4c",     // len 0x4c
1494             "304a",   // SEQUENCE len x4a
1495             "0420",   // OCTET STRING len 32
1496             "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
1497             "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
1498             "0101", // BOOLEAN len 1
1499             "00",   // false
1500             "0a01", // ENUMERATED len 1
1501             "02",   // Unverified(2)
1502             "0420", // OCTET STRING len 32
1503             "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
1504             "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
1505         ))
1506         .unwrap();
1507         let got = AuthorizationList::from_der(&input).unwrap();
1508 
1509         let want = AuthorizationList::new(
1510             &[KeyParam::Algorithm(keymint::Algorithm::Ec), KeyParam::UserSecureId(2)],
1511             &[],
1512             None,
1513             Some(RootOfTrust {
1514                 verified_boot_key: &[0xbbu8; 32],
1515                 device_locked: false,
1516                 verified_boot_state: VerifiedBootState::Unverified,
1517                 verified_boot_hash: &[0xee; 32],
1518             }),
1519             None,
1520         )
1521         .unwrap();
1522 
1523         assert_eq!(got, want);
1524     }
1525 
1526     #[test]
test_authz_list_dup_encode()1527     fn test_authz_list_dup_encode() {
1528         use kmr_wire::keymint::Digest;
1529         let authz_list = AuthorizationList::new(
1530             &[
1531                 KeyParam::Digest(Digest::None),
1532                 KeyParam::Digest(Digest::Sha1),
1533                 KeyParam::Digest(Digest::Sha1), // duplicate value
1534             ],
1535             &[],
1536             None,
1537             Some(RootOfTrust {
1538                 verified_boot_key: &[0xbbu8; 32],
1539                 device_locked: false,
1540                 verified_boot_state: VerifiedBootState::Unverified,
1541                 verified_boot_hash: &[0xee; 32],
1542             }),
1543             None,
1544         )
1545         .unwrap();
1546         let got = authz_list.to_der().unwrap();
1547         assert!(AuthorizationList::from_der(got.as_slice()).is_ok());
1548     }
1549 
1550     #[test]
test_authz_list_order_fail()1551     fn test_authz_list_order_fail() {
1552         use kmr_wire::keymint::Digest;
1553         let authz_list = AuthorizationList::new(
1554             &[KeyParam::Digest(Digest::Sha1), KeyParam::Digest(Digest::None)],
1555             &[],
1556             None,
1557             Some(RootOfTrust {
1558                 verified_boot_key: &[0xbbu8; 32],
1559                 device_locked: false,
1560                 verified_boot_state: VerifiedBootState::Unverified,
1561                 verified_boot_hash: &[0xee; 32],
1562             }),
1563             None,
1564         )
1565         .unwrap();
1566         assert!(authz_list.to_der().is_err());
1567     }
1568 }
1569