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