• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 //! Attestation parsing.
16 
17 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
18     Algorithm::Algorithm, BlockMode::BlockMode, Digest::Digest, EcCurve::EcCurve,
19     HardwareAuthenticatorType::HardwareAuthenticatorType, KeyOrigin::KeyOrigin,
20     KeyParameter::KeyParameter, KeyParameterValue::KeyParameterValue as KPV,
21     KeyPurpose::KeyPurpose, PaddingMode::PaddingMode, Tag::Tag, TagType::TagType,
22 };
23 use der::asn1::{Null, ObjectIdentifier, OctetStringRef, SetOfVec};
24 use der::{oid::AssociatedOid, DerOrd, Enumerated, Reader, Sequence, SliceReader};
25 use der::{Decode, EncodeValue, Length};
26 use std::borrow::Cow;
27 
28 /// Determine the tag type for a tag, based on the top 4 bits of the tag number.
tag_type(tag: Tag) -> TagType29 fn tag_type(tag: Tag) -> TagType {
30     let raw_type = (tag.0 as u32) & 0xf0000000;
31     TagType(raw_type as i32)
32 }
33 
34 /// Determine the raw tag value with tag type information stripped out.
raw_tag_value(tag: Tag) -> u3235 fn raw_tag_value(tag: Tag) -> u32 {
36     (tag.0 as u32) & 0x0fffffffu32
37 }
38 
39 /// OID value for the Android Attestation extension.
40 pub const ATTESTATION_EXTENSION_OID: ObjectIdentifier =
41     ObjectIdentifier::new_unwrap("1.3.6.1.4.1.11129.2.1.17");
42 
43 /// Attestation extension contents
44 #[derive(Debug, Clone, Sequence, PartialEq)]
45 pub struct AttestationExtension<'a> {
46     /// Attestation version.
47     pub attestation_version: i32,
48     /// Security level that created the attestation.
49     pub attestation_security_level: SecurityLevel,
50     /// Keymint version.
51     pub keymint_version: i32,
52     /// Security level of the KeyMint instance holding the key.
53     pub keymint_security_level: SecurityLevel,
54     /// Attestation challenge.
55     #[asn1(type = "OCTET STRING")]
56     pub attestation_challenge: &'a [u8],
57     /// Unique ID.
58     #[asn1(type = "OCTET STRING")]
59     pub unique_id: &'a [u8],
60     /// Software-enforced key characteristics.
61     pub sw_enforced: AuthorizationList<'a>,
62     /// Hardware-enforced key characteristics.
63     pub hw_enforced: AuthorizationList<'a>,
64 }
65 
66 impl AssociatedOid for AttestationExtension<'_> {
67     const OID: ObjectIdentifier = ATTESTATION_EXTENSION_OID;
68 }
69 
70 /// Security level enumeration
71 #[repr(u32)]
72 #[derive(Debug, Clone, Copy, Enumerated, PartialEq)]
73 pub enum SecurityLevel {
74     /// Software.
75     Software = 0,
76     /// TEE.
77     TrustedEnvironment = 1,
78     /// StrongBox.
79     Strongbox = 2,
80 }
81 
82 /// Root of Trust ASN.1 structure
83 #[derive(Debug, Clone, Sequence)]
84 pub struct RootOfTrust<'a> {
85     /// Verified boot key hash.
86     #[asn1(type = "OCTET STRING")]
87     pub verified_boot_key: &'a [u8],
88     /// Device bootloader lock state.
89     pub device_locked: bool,
90     /// Verified boot state.
91     pub verified_boot_state: VerifiedBootState,
92     /// Verified boot hash
93     #[asn1(type = "OCTET STRING")]
94     pub verified_boot_hash: &'a [u8],
95 }
96 
97 /// Attestation Application ID ASN.1 structure
98 #[derive(Debug, Clone, Sequence)]
99 pub struct AttestationApplicationId<'a> {
100     /// Package info.
101     pub package_info_records: SetOfVec<PackageInfoRecord<'a>>,
102     /// Signatures.
103     pub signature_digests: SetOfVec<OctetStringRef<'a>>,
104 }
105 
106 /// Package record
107 #[derive(Debug, Clone, Sequence)]
108 pub struct PackageInfoRecord<'a> {
109     /// Package name
110     pub package_name: OctetStringRef<'a>,
111     /// Package version
112     pub version: i64,
113 }
114 
115 impl DerOrd for PackageInfoRecord<'_> {
der_cmp(&self, other: &Self) -> Result<std::cmp::Ordering, der::Error>116     fn der_cmp(&self, other: &Self) -> Result<std::cmp::Ordering, der::Error> {
117         self.package_name.der_cmp(&other.package_name)
118     }
119 }
120 
121 /// Verified Boot State as ASN.1 ENUMERATED type.
122 #[repr(u32)]
123 #[derive(Debug, Clone, Copy, Enumerated)]
124 pub enum VerifiedBootState {
125     /// Verified.
126     Verified = 0,
127     /// Self-signed.
128     SelfSigned = 1,
129     /// Unverified.
130     Unverified = 2,
131     /// Failed.
132     Failed = 3,
133 }
134 
135 /// Struct corresponding to an ASN.1 DER-serialized `AuthorizationList`.
136 #[derive(Debug, Clone, PartialEq, Eq, Default)]
137 pub struct AuthorizationList<'a> {
138     /// Key authorizations.
139     pub auths: Cow<'a, [KeyParameter]>,
140 }
141 
142 impl From<Vec<KeyParameter>> for AuthorizationList<'_> {
143     /// Build an `AuthorizationList` using a set of key parameters.
from(auths: Vec<KeyParameter>) -> Self144     fn from(auths: Vec<KeyParameter>) -> Self {
145         AuthorizationList { auths: auths.into() }
146     }
147 }
148 
149 impl<'a> Sequence<'a> for AuthorizationList<'a> {}
150 
151 /// Stub (non-)implementation of DER-encoding, needed to implement [`Sequence`].
152 impl EncodeValue for AuthorizationList<'_> {
value_len(&self) -> der::Result<Length>153     fn value_len(&self) -> der::Result<Length> {
154         unimplemented!("Only decoding is implemented");
155     }
encode_value(&self, _writer: &mut impl der::Writer) -> der::Result<()>156     fn encode_value(&self, _writer: &mut impl der::Writer) -> der::Result<()> {
157         unimplemented!("Only decoding is implemented");
158     }
159 }
160 
161 /// Implementation of [`der::DecodeValue`] which constructs an [`AuthorizationList`] from bytes.
162 impl<'a> der::DecodeValue<'a> for AuthorizationList<'a> {
decode_value<R: der::Reader<'a>>(decoder: &mut R, header: der::Header) -> der::Result<Self>163     fn decode_value<R: der::Reader<'a>>(decoder: &mut R, header: der::Header) -> der::Result<Self> {
164         // Decode tags in the expected order.
165         let contents = decoder.read_slice(header.length)?;
166         let mut reader = SliceReader::new(contents)?;
167         let decoder = &mut reader;
168         let mut auths = Vec::new();
169         let mut next: Option<u32> = None;
170         next = decode_opt_field(decoder, next, &mut auths, Tag::PURPOSE)?;
171         next = decode_opt_field(decoder, next, &mut auths, Tag::ALGORITHM)?;
172         next = decode_opt_field(decoder, next, &mut auths, Tag::KEY_SIZE)?;
173         next = decode_opt_field(decoder, next, &mut auths, Tag::BLOCK_MODE)?;
174         next = decode_opt_field(decoder, next, &mut auths, Tag::DIGEST)?;
175         next = decode_opt_field(decoder, next, &mut auths, Tag::PADDING)?;
176         next = decode_opt_field(decoder, next, &mut auths, Tag::CALLER_NONCE)?;
177         next = decode_opt_field(decoder, next, &mut auths, Tag::MIN_MAC_LENGTH)?;
178         next = decode_opt_field(decoder, next, &mut auths, Tag::EC_CURVE)?;
179         next = decode_opt_field(decoder, next, &mut auths, Tag::RSA_PUBLIC_EXPONENT)?;
180         next = decode_opt_field(decoder, next, &mut auths, Tag::RSA_OAEP_MGF_DIGEST)?;
181         next = decode_opt_field(decoder, next, &mut auths, Tag::ROLLBACK_RESISTANCE)?;
182         next = decode_opt_field(decoder, next, &mut auths, Tag::EARLY_BOOT_ONLY)?;
183         next = decode_opt_field(decoder, next, &mut auths, Tag::ACTIVE_DATETIME)?;
184         next = decode_opt_field(decoder, next, &mut auths, Tag::ORIGINATION_EXPIRE_DATETIME)?;
185         next = decode_opt_field(decoder, next, &mut auths, Tag::USAGE_EXPIRE_DATETIME)?;
186         next = decode_opt_field(decoder, next, &mut auths, Tag::USAGE_COUNT_LIMIT)?;
187         next = decode_opt_field(decoder, next, &mut auths, Tag::USER_SECURE_ID)?;
188         next = decode_opt_field(decoder, next, &mut auths, Tag::NO_AUTH_REQUIRED)?;
189         next = decode_opt_field(decoder, next, &mut auths, Tag::USER_AUTH_TYPE)?;
190         next = decode_opt_field(decoder, next, &mut auths, Tag::AUTH_TIMEOUT)?;
191         next = decode_opt_field(decoder, next, &mut auths, Tag::ALLOW_WHILE_ON_BODY)?;
192         next = decode_opt_field(decoder, next, &mut auths, Tag::TRUSTED_USER_PRESENCE_REQUIRED)?;
193         next = decode_opt_field(decoder, next, &mut auths, Tag::TRUSTED_CONFIRMATION_REQUIRED)?;
194         next = decode_opt_field(decoder, next, &mut auths, Tag::UNLOCKED_DEVICE_REQUIRED)?;
195         next = decode_opt_field(decoder, next, &mut auths, Tag::CREATION_DATETIME)?;
196         next = decode_opt_field(decoder, next, &mut auths, Tag::CREATION_DATETIME)?;
197         next = decode_opt_field(decoder, next, &mut auths, Tag::ORIGIN)?;
198         next = decode_opt_field(decoder, next, &mut auths, Tag::ROOT_OF_TRUST)?;
199         next = decode_opt_field(decoder, next, &mut auths, Tag::OS_VERSION)?;
200         next = decode_opt_field(decoder, next, &mut auths, Tag::OS_PATCHLEVEL)?;
201         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_APPLICATION_ID)?;
202         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_BRAND)?;
203         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_DEVICE)?;
204         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_PRODUCT)?;
205         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_SERIAL)?;
206         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_SERIAL)?;
207         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_SERIAL)?;
208         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_IMEI)?;
209         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_MEID)?;
210         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_MANUFACTURER)?;
211         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_MODEL)?;
212         next = decode_opt_field(decoder, next, &mut auths, Tag::VENDOR_PATCHLEVEL)?;
213         next = decode_opt_field(decoder, next, &mut auths, Tag::BOOT_PATCHLEVEL)?;
214         next = decode_opt_field(decoder, next, &mut auths, Tag::DEVICE_UNIQUE_ATTESTATION)?;
215         next = decode_opt_field(decoder, next, &mut auths, Tag::ATTESTATION_ID_SECOND_IMEI)?;
216         next = decode_opt_field(decoder, next, &mut auths, Tag::MODULE_HASH)?;
217 
218         if next.is_some() {
219             // Extra tag encountered.
220             return Err(decoder.error(der::ErrorKind::Incomplete {
221                 expected_len: Length::ZERO,
222                 actual_len: decoder.remaining_len(),
223             }));
224         }
225 
226         Ok(auths.into())
227     }
228 }
229 
230 /// Attempt to decode an optional field associated with `expected_tag` from the `decoder`.
231 ///
232 /// If `already_read_asn1_tag` is provided, then that ASN.1 tag has already been read from the
233 /// `decoder` and its associated data is next.
234 ///
235 /// (Because the field is optional, we might not read the tag we expect, but instead a later tag
236 /// from the list.  If this happens, the actual decoded ASN.1 tag value is returned to the caller to
237 /// be passed in on the next call to this function.)
238 ///
239 /// If the decoded or re-used ASN.1 tag is the expected one, continue on to read the associated
240 /// value and populate it in `auths`.
decode_opt_field<'a, R: der::Reader<'a>>( decoder: &mut R, already_read_asn1_tag: Option<u32>, auths: &mut Vec<KeyParameter>, expected_tag: Tag, ) -> Result<Option<u32>, der::Error>241 fn decode_opt_field<'a, R: der::Reader<'a>>(
242     decoder: &mut R,
243     already_read_asn1_tag: Option<u32>,
244     auths: &mut Vec<KeyParameter>,
245     expected_tag: Tag,
246 ) -> Result<Option<u32>, der::Error> {
247     // Decode the ASN.1 tag if no tag is provided
248     let asn1_tag = match already_read_asn1_tag {
249         Some(tag) => Some(tag),
250         None => decode_explicit_tag_from_bytes(decoder)?,
251     };
252     let expected_asn1_tag = raw_tag_value(expected_tag);
253     match asn1_tag {
254         Some(v) if v == expected_asn1_tag => {
255             // Decode the length of the inner encoding
256             let inner_len = Length::decode(decoder)?;
257             if decoder.remaining_len() < inner_len {
258                 return Err(der::ErrorKind::Incomplete {
259                     expected_len: inner_len,
260                     actual_len: decoder.remaining_len(),
261                 }
262                 .into());
263             }
264             let next_tlv = decoder.tlv_bytes()?;
265             decode_value_from_bytes(expected_tag, next_tlv, auths)?;
266             Ok(None)
267         }
268         Some(tag) => Ok(Some(tag)), // Return the tag for which the value is unread.
269         None => Ok(None),
270     }
271 }
272 
273 /// Decode one or more `KeyParameterValue`s of the type associated with `tag` from the `decoder`,
274 /// and add them to `auths`.
decode_value_from_bytes( tag: Tag, data: &[u8], auths: &mut Vec<KeyParameter>, ) -> Result<(), der::Error>275 fn decode_value_from_bytes(
276     tag: Tag,
277     data: &[u8],
278     auths: &mut Vec<KeyParameter>,
279 ) -> Result<(), der::Error> {
280     match tag_type(tag) {
281         TagType::ENUM_REP => {
282             let values = SetOfVec::<i32>::from_der(data)?;
283             for value in values.as_slice() {
284                 auths.push(KeyParameter {
285                     tag,
286                     value: match tag {
287                         Tag::BLOCK_MODE => KPV::BlockMode(BlockMode(*value)),
288                         Tag::PADDING => KPV::PaddingMode(PaddingMode(*value)),
289                         Tag::DIGEST => KPV::Digest(Digest(*value)),
290                         Tag::RSA_OAEP_MGF_DIGEST => KPV::Digest(Digest(*value)),
291                         Tag::PURPOSE => KPV::KeyPurpose(KeyPurpose(*value)),
292                         _ => return Err(der::ErrorKind::TagNumberInvalid.into()),
293                     },
294                 });
295             }
296         }
297         TagType::UINT_REP => {
298             let values = SetOfVec::<i32>::from_der(data)?;
299             for value in values.as_slice() {
300                 auths.push(KeyParameter { tag, value: KPV::Integer(*value) });
301             }
302         }
303         TagType::ENUM => {
304             let value = i32::from_der(data)?;
305             auths.push(KeyParameter {
306                 tag,
307                 value: match tag {
308                     Tag::ALGORITHM => KPV::Algorithm(Algorithm(value)),
309                     Tag::EC_CURVE => KPV::EcCurve(EcCurve(value)),
310                     Tag::ORIGIN => KPV::Origin(KeyOrigin(value)),
311                     Tag::USER_AUTH_TYPE => {
312                         KPV::HardwareAuthenticatorType(HardwareAuthenticatorType(value))
313                     }
314                     _ => return Err(der::ErrorKind::TagNumberInvalid.into()),
315                 },
316             });
317         }
318         TagType::UINT => {
319             let value = i32::from_der(data)?;
320             auths.push(KeyParameter { tag, value: KPV::Integer(value) });
321         }
322         TagType::ULONG => {
323             let value = i64::from_der(data)?;
324             auths.push(KeyParameter { tag, value: KPV::LongInteger(value) });
325         }
326         TagType::DATE => {
327             let value = i64::from_der(data)?;
328             auths.push(KeyParameter { tag, value: KPV::DateTime(value) });
329         }
330         TagType::BOOL => {
331             let _value = Null::from_der(data)?;
332             auths.push(KeyParameter { tag, value: KPV::BoolValue(true) });
333         }
334         TagType::BYTES if tag == Tag::ROOT_OF_TRUST => {
335             // Special case: root of trust is an ASN.1 `SEQUENCE` not an `OCTET STRING` so don't
336             // decode the bytes.
337             auths.push(KeyParameter { tag: Tag::ROOT_OF_TRUST, value: KPV::Blob(data.to_vec()) });
338         }
339         TagType::BYTES | TagType::BIGNUM => {
340             let value = OctetStringRef::from_der(data)?.as_bytes().to_vec();
341             auths.push(KeyParameter { tag, value: KPV::Blob(value) });
342         }
343         _ => {
344             return Err(der::ErrorKind::TagNumberInvalid.into());
345         }
346     }
347     Ok(())
348 }
349 
350 /// Decode an explicit ASN.1 tag value, coping with large (>=31) tag values
351 /// (which the `der` crate doesn't deal with).  Returns `Ok(None)` if the
352 /// decoder is empty.
decode_explicit_tag_from_bytes<'a, R: der::Reader<'a>>( decoder: &mut R, ) -> Result<Option<u32>, der::Error>353 fn decode_explicit_tag_from_bytes<'a, R: der::Reader<'a>>(
354     decoder: &mut R,
355 ) -> Result<Option<u32>, der::Error> {
356     if decoder.remaining_len() == Length::ZERO {
357         return Ok(None);
358     }
359     let b1 = decoder.read_byte()?;
360     let tag = if b1 & 0b00011111 == 0b00011111u8 {
361         // The initial byte of 0xbf indicates a larger (>=31) value for the ASN.1 tag:
362         // - 0bXY...... = class
363         // - 0b..C..... = constructed/primitive bit
364         // - 0b...11111 = marker indicating high tag form, tag value to follow
365         //
366         // The top three bits should be 0b101 = constructed context-specific
367         if b1 & 0b11100000 != 0b10100000 {
368             return Err(der::ErrorKind::TagNumberInvalid.into());
369         }
370 
371         // The subsequent encoded tag value is broken down into 7-bit chunks (in big-endian order),
372         // and each chunk gets a high bit of 1 except the last, which gets a high bit of zero.
373         let mut bit_count = 0;
374         let mut tag: u32 = 0;
375         loop {
376             let b = decoder.read_byte()?;
377             let low_b = b & 0b01111111;
378             if bit_count == 0 && low_b == 0 {
379                 // The first part of the tag number is zero, implying it is not miminally encoded.
380                 return Err(der::ErrorKind::TagNumberInvalid.into());
381             }
382 
383             bit_count += 7;
384             if bit_count > 32 {
385                 // Tag value has more bits than the output type can hold.
386                 return Err(der::ErrorKind::TagNumberInvalid.into());
387             }
388             tag = (tag << 7) | (low_b as u32);
389             if b & 0x80u8 == 0x00u8 {
390                 // Top bit clear => this is the final part of the value.
391                 if tag < 31 {
392                     // Tag is small enough that it should have been in short form.
393                     return Err(der::ErrorKind::TagNumberInvalid.into());
394                 }
395                 break tag;
396             }
397         }
398     } else {
399         // Get the tag value from the low 5 bits.
400         (b1 & 0b00011111u8) as u32
401     };
402     Ok(Some(tag))
403 }
404 
405 #[cfg(test)]
406 mod tests {
407     use super::*;
408     use der::Encode;
409 
410     const SIG: &[u8; 32] = &[
411         0xa4, 0x0d, 0xa8, 0x0a, 0x59, 0xd1, 0x70, 0xca, 0xa9, 0x50, 0xcf, 0x15, 0xc1, 0x8c, 0x45,
412         0x4d, 0x47, 0xa3, 0x9b, 0x26, 0x98, 0x9d, 0x8b, 0x64, 0x0e, 0xcd, 0x74, 0x5b, 0xa7, 0x1b,
413         0xf5, 0xdc,
414     ];
415     const VB_KEY: &[u8; 32] = &[0; 32];
416     const VB_HASH: &[u8; 32] = &[
417         0x6f, 0x84, 0xe6, 0x02, 0x73, 0x9d, 0x86, 0x2c, 0x93, 0x2a, 0x28, 0xf0, 0xa5, 0x27, 0x65,
418         0xa4, 0xae, 0xc2, 0x27, 0x8c, 0xb6, 0x3b, 0xe9, 0xbb, 0x63, 0xc7, 0xa8, 0xc7, 0x03, 0xad,
419         0x8e, 0xc1,
420     ];
421 
422     /// Build a sample `AuthorizationList` suitable for use as `sw_enforced`.
sw_enforced() -> AuthorizationList<'static>423     fn sw_enforced() -> AuthorizationList<'static> {
424         let sig = OctetStringRef::new(SIG).unwrap();
425         let package = PackageInfoRecord {
426             package_name: OctetStringRef::new(b"android.keystore.cts").unwrap(),
427             version: 34,
428         };
429         let mut package_info_records = SetOfVec::new();
430         package_info_records.insert(package).unwrap();
431         let mut signature_digests = SetOfVec::new();
432         signature_digests.insert(sig).unwrap();
433         let aaid = AttestationApplicationId { package_info_records, signature_digests };
434         AuthorizationList {
435             auths: vec![
436                 KeyParameter { tag: Tag::CREATION_DATETIME, value: KPV::DateTime(0x01903116c71f) },
437                 KeyParameter {
438                     tag: Tag::ATTESTATION_APPLICATION_ID,
439                     value: KPV::Blob(aaid.to_der().unwrap()),
440                 },
441             ]
442             .into(),
443         }
444     }
445 
446     /// Build a sample `AuthorizationList` suitable for use as `hw_enforced`.
hw_enforced() -> AuthorizationList<'static>447     fn hw_enforced() -> AuthorizationList<'static> {
448         let rot = RootOfTrust {
449             verified_boot_key: VB_KEY,
450             device_locked: false,
451             verified_boot_state: VerifiedBootState::Unverified,
452             verified_boot_hash: VB_HASH,
453         };
454         AuthorizationList {
455             auths: vec![
456                 KeyParameter { tag: Tag::PURPOSE, value: KPV::KeyPurpose(KeyPurpose::AGREE_KEY) },
457                 KeyParameter { tag: Tag::ALGORITHM, value: KPV::Algorithm(Algorithm::EC) },
458                 KeyParameter { tag: Tag::KEY_SIZE, value: KPV::Integer(256) },
459                 KeyParameter { tag: Tag::DIGEST, value: KPV::Digest(Digest::NONE) },
460                 KeyParameter { tag: Tag::EC_CURVE, value: KPV::EcCurve(EcCurve::CURVE_25519) },
461                 KeyParameter { tag: Tag::NO_AUTH_REQUIRED, value: KPV::BoolValue(true) },
462                 KeyParameter { tag: Tag::ORIGIN, value: KPV::Origin(KeyOrigin::GENERATED) },
463                 KeyParameter { tag: Tag::ROOT_OF_TRUST, value: KPV::Blob(rot.to_der().unwrap()) },
464                 KeyParameter { tag: Tag::OS_VERSION, value: KPV::Integer(140000) },
465                 KeyParameter { tag: Tag::OS_PATCHLEVEL, value: KPV::Integer(202404) },
466                 KeyParameter { tag: Tag::VENDOR_PATCHLEVEL, value: KPV::Integer(20240405) },
467                 KeyParameter { tag: Tag::BOOT_PATCHLEVEL, value: KPV::Integer(20240405) },
468             ]
469             .into(),
470         }
471     }
472 
473     #[test]
test_decode_auth_list_1()474     fn test_decode_auth_list_1() {
475         let want = sw_enforced();
476         let data = hex::decode(concat!(
477             "3055",     //  SEQUENCE
478             "bf853d08", //  [701]
479             "0206",     //  INTEGER
480             "01903116c71f",
481             "bf854545",                                 //  [709]
482             "0443",                                     //  OCTET STRING
483             "3041",                                     //  SEQUENCE
484             "311b",                                     //  SET
485             "3019",                                     //  SEQUENCE
486             "0414",                                     //  OCTET STRING
487             "616e64726f69642e6b657973746f72652e637473", //  "android.keystore.cts"
488             "020122",                                   //  INTEGER
489             "3122",                                     //  SET
490             "0420",                                     //  OCTET STRING
491             "a40da80a59d170caa950cf15c18c454d",
492             "47a39b26989d8b640ecd745ba71bf5dc",
493         ))
494         .unwrap();
495         let got = AuthorizationList::from_der(&data).unwrap();
496         assert_eq!(got, want);
497     }
498 
499     #[test]
test_decode_auth_list_2()500     fn test_decode_auth_list_2() {
501         let want = hw_enforced();
502         let data = hex::decode(concat!(
503             "3081a1",   //  SEQUENCE
504             "a105",     //  [1]
505             "3103",     //  SET
506             "020106",   //  INTEGER
507             "a203",     //  [2]
508             "020103",   //  INTEGER 3
509             "a304",     //  [4]
510             "02020100", //  INTEGER 256
511             "a505",     //  [5]
512             "3103",     //  SET
513             "020100",   //  INTEGER 0
514             "aa03",     //  [10]
515             "020104",   //  INTEGER 4
516             "bf837702", //  [503]
517             "0500",     //  NULL
518             "bf853e03", //  [702]
519             "020100",   //  INTEGER 0
520             "bf85404c", //  [704]
521             "304a",     //  SEQUENCE
522             "0420",     //  OCTET STRING
523             "00000000000000000000000000000000",
524             "00000000000000000000000000000000",
525             "010100", //  BOOLEAN
526             "0a0102", //  ENUMERATED
527             "0420",   //  OCTET STRING
528             "6f84e602739d862c932a28f0a52765a4",
529             "aec2278cb63be9bb63c7a8c703ad8ec1",
530             "bf854105",     //  [705]
531             "02030222e0",   //  INTEGER
532             "bf854205",     //  [706]
533             "02030316a4",   //  INTEGER
534             "bf854e06",     //  [718]
535             "02040134d815", //  INTEGER
536             "bf854f06",     //  [709]
537             "02040134d815", //  INTEGER
538         ))
539         .unwrap();
540         let got = AuthorizationList::from_der(&data).unwrap();
541         assert_eq!(got, want);
542     }
543 
544     #[test]
test_decode_extension()545     fn test_decode_extension() {
546         let zeroes = [0; 128];
547         let want = AttestationExtension {
548             attestation_version: 300,
549             attestation_security_level: SecurityLevel::TrustedEnvironment,
550             keymint_version: 300,
551             keymint_security_level: SecurityLevel::TrustedEnvironment,
552             attestation_challenge: &zeroes,
553             unique_id: &[],
554             sw_enforced: sw_enforced(),
555             hw_enforced: hw_enforced(),
556         };
557 
558         let data = hex::decode(concat!(
559             // Full extension would include the following prefix:
560             // "308201a2",             //  SEQUENCE
561             // "060a",                 //  OBJECT IDENTIFIER
562             // "2b06010401d679020111", //  Android attestation extension (1.3.6.1.4.1.11129.2.1.17)
563             // "04820192",             //  OCTET STRING
564             "3082018e", //  SEQUENCE
565             "0202012c", //  INTEGER 300
566             "0a0101",   //  ENUMERATED 1
567             "0202012c", //  INTEGER 300
568             "0a0101",   //  ENUMERATED 1
569             "048180",   //  OCTET STRING
570             "00000000000000000000000000000000",
571             "00000000000000000000000000000000",
572             "00000000000000000000000000000000",
573             "00000000000000000000000000000000",
574             "00000000000000000000000000000000",
575             "00000000000000000000000000000000",
576             "00000000000000000000000000000000",
577             "00000000000000000000000000000000",
578             "0400", //  OCTET STRING
579             // softwareEnforced
580             "3055",     //  SEQUENCE
581             "bf853d08", //  [701]
582             "0206",     //  INTEGER
583             "01903116c71f",
584             "bf854545",                                 //  [709]
585             "0443",                                     //  OCTET STRING
586             "3041",                                     //  SEQUENCE
587             "311b",                                     //  SET
588             "3019",                                     //  SEQUENCE
589             "0414",                                     //  OCTET STRING
590             "616e64726f69642e6b657973746f72652e637473", //  "android.keystore.cts"
591             "020122",                                   //  INTEGER
592             "3122",                                     //  SET
593             "0420",                                     //  OCTET STRING
594             "a40da80a59d170caa950cf15c18c454d",
595             "47a39b26989d8b640ecd745ba71bf5dc",
596             // softwareEnforced
597             "3081a1",   //  SEQUENCE
598             "a105",     //  [1]
599             "3103",     //  SET
600             "020106",   //  INTEGER
601             "a203",     //  [2]
602             "020103",   //  INTEGER 3
603             "a304",     //  [4]
604             "02020100", //  INTEGER 256
605             "a505",     //  [5]
606             "3103",     //  SET
607             "020100",   //  INTEGER 0
608             "aa03",     //  [10]
609             "020104",   //  INTEGER 4
610             "bf837702", //  [503]
611             "0500",     //  NULL
612             "bf853e03", //  [702]
613             "020100",   //  INTEGER 0
614             "bf85404c", //  [704]
615             "304a",     //  SEQUENCE
616             "0420",     //  OCTET STRING
617             "00000000000000000000000000000000",
618             "00000000000000000000000000000000",
619             "010100", //  BOOLEAN
620             "0a0102", //  ENUMERATED
621             "0420",   //  OCTET STRING
622             "6f84e602739d862c932a28f0a52765a4",
623             "aec2278cb63be9bb63c7a8c703ad8ec1",
624             "bf854105",     //  [705]
625             "02030222e0",   //  INTEGER
626             "bf854205",     //  [706]
627             "02030316a4",   //  INTEGER
628             "bf854e06",     //  [718]
629             "02040134d815", //  INTEGER
630             "bf854f06",     //  [719]
631             "02040134d815", //  INTEGER
632         ))
633         .unwrap();
634         let got = AttestationExtension::from_der(&data).unwrap();
635         assert_eq!(got, want);
636     }
637 
638     #[test]
test_decode_empty_auth_list()639     fn test_decode_empty_auth_list() {
640         let want = AuthorizationList::default();
641         let data = hex::decode(
642             "3000", //  SEQUENCE
643         )
644         .unwrap();
645         let got = AuthorizationList::from_der(&data).unwrap();
646         assert_eq!(got, want);
647     }
648 
649     #[test]
test_decode_explicit_tag()650     fn test_decode_explicit_tag() {
651         let err = Err(der::ErrorKind::TagNumberInvalid.into());
652         let tests = [
653             (vec![], Ok(None)),
654             (vec![0b10100000], Ok(Some(0))),
655             (vec![0b10100001], Ok(Some(1))),
656             (vec![0b10100010], Ok(Some(2))),
657             (vec![0b10111110], Ok(Some(30))),
658             (vec![0b10111111, 0b00011111], Ok(Some(31))),
659             (vec![0b10111111, 0b00100000], Ok(Some(32))),
660             (vec![0b10111111, 0b01111111], Ok(Some(127))),
661             (vec![0b10111111, 0b10000001, 0b00000000], Ok(Some(128))),
662             (vec![0b10111111, 0b10000010, 0b00000000], Ok(Some(256))),
663             (vec![0b10111111, 0b10000001, 0b10000000, 0b00000001], Ok(Some(16385))),
664             (vec![0b10111111, 0b10010000, 0b10000000, 0b10000000, 0b00000000], Ok(Some(33554432))),
665             // Top bits ignored for low tag numbers
666             (vec![0b00000000], Ok(Some(0))),
667             (vec![0b00000001], Ok(Some(1))),
668             // High tag numbers should start with 0b101
669             (vec![0b10011111, 0b00100000], err),
670             (vec![0b11111111, 0b00100000], err),
671             (vec![0b00111111, 0b00100000], err),
672             // High tag numbers should be minimally encoded
673             (vec![0b10111111, 0b10000000, 0b10000001, 0b00000000], err),
674             (vec![0b10111111, 0b00011110], err),
675             // Bigger than u32
676             (
677                 vec![
678                     0b10111111, 0b10000001, 0b10000000, 0b10000000, 0b10000000, 0b10000000,
679                     0b00000000,
680                 ],
681                 err,
682             ),
683             // Incomplete tag
684             (vec![0b10111111, 0b10000001], Err(der::Error::incomplete(der::Length::new(2)))),
685         ];
686 
687         for (input, want) in tests {
688             let mut reader = SliceReader::new(&input).unwrap();
689             let got = decode_explicit_tag_from_bytes(&mut reader);
690             assert_eq!(got, want, "for input {}", hex::encode(input));
691         }
692     }
693 }
694