xref: /aosp_15_r20/system/keymint/ta/src/keys.rs (revision 9860b7637a5f185913c70aa0caabe3ecb78441e4)
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 //! TA functionality related to key generation/import/upgrade.
16 
17 use crate::{cert, device, AttestationChainInfo};
18 use alloc::collections::btree_map::Entry;
19 use alloc::vec::Vec;
20 use core::{borrow::Borrow, cmp::Ordering, convert::TryFrom};
21 use der::{referenced::RefToOwned, Decode, Sequence};
22 use kmr_common::{
23     crypto::{self, aes, rsa, KeyMaterial, OpaqueOr},
24     der_err, get_bool_tag_value, get_opt_tag_value, get_tag_value, keyblob, km_err, tag,
25     try_to_vec, vec_try_with_capacity, Error, FallibleAllocExt,
26 };
27 use kmr_wire::{
28     keymint::{
29         AttestationKey, Digest, EcCurve, ErrorCode, HardwareAuthenticatorType, KeyCharacteristics,
30         KeyCreationResult, KeyFormat, KeyOrigin, KeyParam, KeyPurpose, SecurityLevel,
31         UNDEFINED_NOT_AFTER, UNDEFINED_NOT_BEFORE,
32     },
33     *,
34 };
35 use log::{error, warn};
36 use spki::SubjectPublicKeyInfoOwned;
37 use x509_cert::ext::pkix::KeyUsages;
38 
39 /// Maximum size of an attestation challenge value.
40 const MAX_ATTESTATION_CHALLENGE_LEN: usize = 128;
41 
42 /// Contents of wrapping key data
43 ///
44 /// ```asn1
45 /// SecureKeyWrapper ::= SEQUENCE {
46 ///     version                   INTEGER, # Value 0
47 ///     encryptedTransportKey     OCTET_STRING,
48 ///     initializationVector      OCTET_STRING,
49 ///     keyDescription            KeyDescription, # See below
50 ///     encryptedKey              OCTET_STRING,
51 ///     tag                       OCTET_STRING,
52 /// }
53 /// ```
54 #[derive(Debug, Clone, Sequence)]
55 pub struct SecureKeyWrapper<'a> {
56     /// Version of this structure.
57     pub version: i32,
58     /// Encrypted transport key.
59     #[asn1(type = "OCTET STRING")]
60     pub encrypted_transport_key: &'a [u8],
61     /// IV to use for decryption.
62     #[asn1(type = "OCTET STRING")]
63     pub initialization_vector: &'a [u8],
64     /// Key parameters and description.
65     pub key_description: KeyDescription<'a>,
66     /// Ciphertext of the imported key.
67     #[asn1(type = "OCTET STRING")]
68     pub encrypted_key: &'a [u8],
69     /// Tag value.
70     #[asn1(type = "OCTET STRING")]
71     pub tag: &'a [u8],
72 }
73 
74 const SECURE_KEY_WRAPPER_VERSION: i32 = 0;
75 
76 /// Contents of key description.
77 ///
78 /// ```asn1
79 /// KeyDescription ::= SEQUENCE {
80 ///     keyFormat    INTEGER, # Values from KeyFormat enum
81 ///     keyParams    AuthorizationList, # See cert.rs
82 /// }
83 /// ```
84 #[derive(Debug, Clone, Sequence)]
85 pub struct KeyDescription<'a> {
86     /// Format of imported key.
87     pub key_format: i32,
88     /// Key parameters.
89     pub key_params: cert::AuthorizationList<'a>,
90 }
91 
92 /// Indication of whether key import has a secure wrapper.
93 #[derive(Debug, Clone, Copy)]
94 pub(crate) enum KeyImport {
95     Wrapped,
96     NonWrapped,
97 }
98 
99 /// Combined information needed for signing a fresh public key.
100 #[derive(Clone)]
101 pub(crate) struct SigningInfo<'a> {
102     pub attestation_info: Option<(&'a [u8], &'a [u8])>, // (challenge, app_id)
103     pub signing_key: KeyMaterial,
104     /// ASN.1 DER encoding of subject field from first cert.
105     pub issuer_subject: Vec<u8>,
106     /// Cert chain starting with public key for `signing_key`.
107     pub chain: Vec<keymint::Certificate>,
108 }
109 
110 impl crate::KeyMintTa {
111     /// Retrieve the signing information.
get_signing_info( &self, key_type: device::SigningKeyType, ) -> Result<SigningInfo, Error>112     pub(crate) fn get_signing_info(
113         &self,
114         key_type: device::SigningKeyType,
115     ) -> Result<SigningInfo, Error> {
116         let sign_info = self.dev.sign_info.as_ref().ok_or_else(|| {
117             km_err!(AttestationKeysNotProvisioned, "batch attestation keys not available")
118         })?;
119         // Retrieve the chain and issuer information, which is cached after first retrieval.
120         let mut attestation_chain_info = self.attestation_chain_info.borrow_mut();
121         let chain_info = match attestation_chain_info.entry(key_type) {
122             Entry::Occupied(e) => e.into_mut(),
123             Entry::Vacant(e) => {
124                 // Retrieve and store the cert chain information (as this is public).
125                 let chain = sign_info.cert_chain(key_type)?;
126                 let issuer =
127                     cert::extract_subject(chain.first().ok_or_else(|| {
128                         km_err!(KeymintNotConfigured, "empty attestation chain")
129                     })?)?;
130                 e.insert(AttestationChainInfo { chain, issuer })
131             }
132         };
133 
134         // Retrieve the signing key information (which will be dropped when signing is done).
135         let signing_key = sign_info.signing_key(key_type)?;
136         Ok(SigningInfo {
137             attestation_info: None,
138             signing_key,
139             issuer_subject: chain_info.issuer.clone(),
140             chain: chain_info.chain.clone(),
141         })
142     }
143 
144     /// Generate an X.509 leaf certificate.
generate_cert( &self, info: Option<SigningInfo>, spki: SubjectPublicKeyInfoOwned, params: &[KeyParam], chars: &[KeyCharacteristics], ) -> Result<keymint::Certificate, Error>145     pub(crate) fn generate_cert(
146         &self,
147         info: Option<SigningInfo>,
148         spki: SubjectPublicKeyInfoOwned,
149         params: &[KeyParam],
150         chars: &[KeyCharacteristics],
151     ) -> Result<keymint::Certificate, Error> {
152         // Build and encode key usage extension value
153         let key_usage_ext_bits = cert::key_usage_extension_bits(params);
154         let key_usage_ext_val = cert::asn1_der_encode(&key_usage_ext_bits)
155             .map_err(|e| der_err!(e, "failed to encode KeyUsage {:?}", key_usage_ext_bits))?;
156 
157         // Build and encode basic constraints extension value, based on the key usage extension
158         // value
159         let basic_constraints_ext_val =
160             if (key_usage_ext_bits.0 & KeyUsages::KeyCertSign).bits().count_ones() != 0 {
161                 let basic_constraints = cert::basic_constraints_ext_value(true);
162                 Some(cert::asn1_der_encode(&basic_constraints).map_err(|e| {
163                     der_err!(e, "failed to encode basic constraints {:?}", basic_constraints)
164                 })?)
165             } else {
166                 None
167             };
168 
169         // Build and encode attestation extension if present
170         let id_info = self.get_attestation_ids();
171         let attest_ext_val =
172             if let Some(SigningInfo { attestation_info: Some((challenge, app_id)), .. }) = &info {
173                 let unique_id = self.calculate_unique_id(app_id, params)?;
174                 let boot_info = self.boot_info_hashed_key()?;
175                 let attest_ext = cert::attestation_extension(
176                     self.aidl_version as i32,
177                     challenge,
178                     app_id,
179                     self.hw_info.security_level,
180                     id_info.as_ref().map(|v| v.borrow()),
181                     params,
182                     chars,
183                     &unique_id,
184                     &boot_info,
185                     &self.additional_attestation_info,
186                 )?;
187                 Some(
188                     cert::asn1_der_encode(&attest_ext)
189                         .map_err(|e| der_err!(e, "failed to encode attestation extension"))?,
190                 )
191             } else {
192                 None
193             };
194 
195         let tbs_cert = cert::tbs_certificate(
196             &info,
197             spki,
198             &key_usage_ext_val,
199             basic_constraints_ext_val.as_deref(),
200             attest_ext_val.as_deref(),
201             tag::characteristics_at(chars, self.hw_info.security_level)?,
202             params,
203         )?;
204         let tbs_data = cert::asn1_der_encode(&tbs_cert)
205             .map_err(|e| der_err!(e, "failed to encode tbsCert"))?;
206         // If key does not have ATTEST_KEY or SIGN purpose, the certificate has empty signature
207         let sig_data = match info.as_ref() {
208             Some(info) => self.sign_cert_data(info.signing_key.clone(), tbs_data.as_slice())?,
209             None => Vec::new(),
210         };
211 
212         let cert = cert::certificate(tbs_cert, &sig_data)?;
213         let cert_data = cert::asn1_der_encode(&cert)
214             .map_err(|e| der_err!(e, "failed to encode certificate"))?;
215         Ok(keymint::Certificate { encoded_certificate: cert_data })
216     }
217 
218     /// Perform a complete signing operation using default modes.
sign_cert_data(&self, signing_key: KeyMaterial, tbs_data: &[u8]) -> Result<Vec<u8>, Error>219     fn sign_cert_data(&self, signing_key: KeyMaterial, tbs_data: &[u8]) -> Result<Vec<u8>, Error> {
220         match signing_key {
221             KeyMaterial::Rsa(key) => {
222                 let mut op = self
223                     .imp
224                     .rsa
225                     .begin_sign(key, rsa::SignMode::Pkcs1_1_5Padding(Digest::Sha256))?;
226                 op.update(tbs_data)?;
227                 op.finish()
228             }
229             KeyMaterial::Ec(curve, _, key) => {
230                 let digest = if curve == EcCurve::Curve25519 {
231                     // Ed25519 includes an internal digest and so does not use an external digest.
232                     Digest::None
233                 } else {
234                     Digest::Sha256
235                 };
236                 let mut op = self.imp.ec.begin_sign(key, digest)?;
237                 op.update(tbs_data)?;
238                 op.finish()
239             }
240             _ => Err(km_err!(IncompatibleAlgorithm, "unexpected cert signing key type")),
241         }
242     }
243 
244     /// Calculate the `UNIQUE_ID` value for the parameters, if needed.
calculate_unique_id(&self, app_id: &[u8], params: &[KeyParam]) -> Result<Vec<u8>, Error>245     fn calculate_unique_id(&self, app_id: &[u8], params: &[KeyParam]) -> Result<Vec<u8>, Error> {
246         if !get_bool_tag_value!(params, IncludeUniqueId)? {
247             return Ok(Vec::new());
248         }
249         let creation_datetime =
250             get_tag_value!(params, CreationDatetime, ErrorCode::InvalidArgument)?;
251         let rounded_datetime = creation_datetime.ms_since_epoch / 2_592_000_000i64;
252         let datetime_data = rounded_datetime.to_ne_bytes();
253 
254         let mut combined_input = vec_try_with_capacity!(datetime_data.len() + app_id.len() + 1)?;
255         combined_input.extend_from_slice(&datetime_data[..]);
256         combined_input.extend_from_slice(app_id);
257         combined_input.push(u8::from(get_bool_tag_value!(params, ResetSinceIdRotation)?));
258 
259         let hbk = self.dev.keys.unique_id_hbk(&*self.imp.ckdf)?;
260 
261         let mut hmac_op = self.imp.hmac.begin(hbk.into(), Digest::Sha256)?;
262         hmac_op.update(&combined_input)?;
263         let tag = hmac_op.finish()?;
264         try_to_vec(&tag[..16])
265     }
266 
generate_key( &mut self, params: &[KeyParam], attestation_key: Option<AttestationKey>, ) -> Result<KeyCreationResult, Error>267     pub(crate) fn generate_key(
268         &mut self,
269         params: &[KeyParam],
270         attestation_key: Option<AttestationKey>,
271     ) -> Result<KeyCreationResult, Error> {
272         let (key_material, chars) = self.generate_key_material(params)?;
273         self.finish_keyblob_creation(
274             params,
275             attestation_key,
276             chars,
277             key_material,
278             keyblob::SlotPurpose::KeyGeneration,
279         )
280     }
281 
generate_key_material( &mut self, params: &[KeyParam], ) -> Result<(KeyMaterial, Vec<KeyCharacteristics>), Error>282     pub(crate) fn generate_key_material(
283         &mut self,
284         params: &[KeyParam],
285     ) -> Result<(KeyMaterial, Vec<KeyCharacteristics>), Error> {
286         let (mut chars, keygen_info) = tag::extract_key_gen_characteristics(
287             self.secure_storage_available(),
288             params,
289             self.hw_info.security_level,
290         )?;
291         self.add_keymint_tags(&mut chars, KeyOrigin::Generated)?;
292         let key_material = match keygen_info {
293             crypto::KeyGenInfo::Aes(variant) => {
294                 self.imp.aes.generate_key(&mut *self.imp.rng, variant, params)?
295             }
296             crypto::KeyGenInfo::TripleDes => {
297                 self.imp.des.generate_key(&mut *self.imp.rng, params)?
298             }
299             crypto::KeyGenInfo::Hmac(key_size) => {
300                 self.imp.hmac.generate_key(&mut *self.imp.rng, key_size, params)?
301             }
302             crypto::KeyGenInfo::Rsa(key_size, pub_exponent) => {
303                 self.imp.rsa.generate_key(&mut *self.imp.rng, key_size, pub_exponent, params)?
304             }
305             crypto::KeyGenInfo::NistEc(curve) => {
306                 self.imp.ec.generate_nist_key(&mut *self.imp.rng, curve, params)?
307             }
308             crypto::KeyGenInfo::Ed25519 => {
309                 self.imp.ec.generate_ed25519_key(&mut *self.imp.rng, params)?
310             }
311             crypto::KeyGenInfo::X25519 => {
312                 self.imp.ec.generate_x25519_key(&mut *self.imp.rng, params)?
313             }
314         };
315         Ok((key_material, chars))
316     }
317 
import_key( &mut self, params: &[KeyParam], key_format: KeyFormat, key_data: &[u8], attestation_key: Option<AttestationKey>, import_type: KeyImport, ) -> Result<KeyCreationResult, Error>318     pub(crate) fn import_key(
319         &mut self,
320         params: &[KeyParam],
321         key_format: KeyFormat,
322         key_data: &[u8],
323         attestation_key: Option<AttestationKey>,
324         import_type: KeyImport,
325     ) -> Result<KeyCreationResult, Error> {
326         if !self.in_early_boot && get_bool_tag_value!(params, EarlyBootOnly)? {
327             return Err(km_err!(EarlyBootEnded, "attempt to use EARLY_BOOT key after early boot"));
328         }
329 
330         let (mut chars, key_material) = tag::extract_key_import_characteristics(
331             &self.imp,
332             self.secure_storage_available(),
333             params,
334             self.hw_info.security_level,
335             key_format,
336             key_data,
337         )?;
338         match import_type {
339             KeyImport::NonWrapped => {
340                 self.add_keymint_tags(&mut chars, KeyOrigin::Imported)?;
341             }
342             KeyImport::Wrapped => {
343                 self.add_keymint_tags(&mut chars, KeyOrigin::SecurelyImported)?;
344             }
345         }
346 
347         self.finish_keyblob_creation(
348             params,
349             attestation_key,
350             chars,
351             key_material,
352             keyblob::SlotPurpose::KeyImport,
353         )
354     }
355 
356     /// Perform common processing for keyblob creation (for both generation and import).
finish_keyblob_creation( &mut self, params: &[KeyParam], attestation_key: Option<AttestationKey>, chars: Vec<KeyCharacteristics>, key_material: KeyMaterial, purpose: keyblob::SlotPurpose, ) -> Result<KeyCreationResult, Error>357     pub fn finish_keyblob_creation(
358         &mut self,
359         params: &[KeyParam],
360         attestation_key: Option<AttestationKey>,
361         chars: Vec<KeyCharacteristics>,
362         key_material: KeyMaterial,
363         purpose: keyblob::SlotPurpose,
364     ) -> Result<KeyCreationResult, Error> {
365         let keyblob = keyblob::PlaintextKeyBlob {
366             // Don't include any `SecurityLevel::Keystore` characteristics in the set that is bound
367             // to the key.
368             characteristics: chars
369                 .iter()
370                 .filter(|c| c.security_level != SecurityLevel::Keystore)
371                 .cloned()
372                 .collect(),
373             key_material: key_material.clone(),
374         };
375         let attest_keyblob;
376         let mut certificate_chain = Vec::new();
377         if let Some(spki) = keyblob.key_material.subject_public_key_info(
378             &mut Vec::<u8>::new(),
379             &*self.imp.ec,
380             &*self.imp.rsa,
381         )? {
382             // Asymmetric keys return the public key inside an X.509 certificate.
383             // Need to determine:
384             // - a key to sign the cert with (may be absent), together with any associated
385             //   cert chain to append
386             // - whether to include an attestation extension
387             let attest_challenge = get_opt_tag_value!(params, AttestationChallenge)?;
388 
389             let signing_info = if let Some(attest_challenge) = attest_challenge {
390                 // Attestation requested.
391                 if attest_challenge.len() > MAX_ATTESTATION_CHALLENGE_LEN {
392                     return Err(km_err!(
393                         InvalidInputLength,
394                         "attestation challenge too large: {} bytes",
395                         attest_challenge.len()
396                     ));
397                 }
398                 let attest_app_id = get_opt_tag_value!(params, AttestationApplicationId)?
399                     .ok_or_else(|| {
400                         km_err!(AttestationApplicationIdMissing, "attestation requested")
401                     })?;
402                 let attestation_info: Option<(&[u8], &[u8])> =
403                     Some((attest_challenge, attest_app_id));
404 
405                 if let Some(attest_keyinfo) = attestation_key.as_ref() {
406                     // User-specified attestation key provided.
407                     (attest_keyblob, _) = self.keyblob_parse_decrypt(
408                         &attest_keyinfo.key_blob,
409                         &attest_keyinfo.attest_key_params,
410                     )?;
411                     attest_keyblob
412                         .suitable_for(KeyPurpose::AttestKey, self.hw_info.security_level)?;
413                     if attest_keyinfo.issuer_subject_name.is_empty() {
414                         return Err(km_err!(InvalidArgument, "empty subject name"));
415                     }
416                     Some(SigningInfo {
417                         attestation_info,
418                         signing_key: attest_keyblob.key_material,
419                         issuer_subject: attest_keyinfo.issuer_subject_name.clone(),
420                         chain: Vec::new(),
421                     })
422                 } else {
423                     // Need to use a device key for attestation. Look up the relevant device key and
424                     // chain.
425                     let which_key = match (
426                         get_bool_tag_value!(params, DeviceUniqueAttestation)?,
427                         self.is_strongbox(),
428                     ) {
429                         (false, _) => device::SigningKey::Batch,
430                         (true, true) => device::SigningKey::DeviceUnique,
431                         (true, false) => {
432                             return Err(km_err!(
433                                 InvalidArgument,
434                                 "device unique attestation supported only by Strongbox TA"
435                             ))
436                         }
437                     };
438                     // Provide an indication of what's going to be signed, to allow the
439                     // implementation to switch between EC and RSA signing keys if it so chooses.
440                     let algo_hint = match &keyblob.key_material {
441                         crypto::KeyMaterial::Rsa(_) => device::SigningAlgorithm::Rsa,
442                         crypto::KeyMaterial::Ec(_, _, _) => device::SigningAlgorithm::Ec,
443                         _ => return Err(km_err!(InvalidArgument, "unexpected key type!")),
444                     };
445 
446                     let mut info = self
447                         .get_signing_info(device::SigningKeyType { which: which_key, algo_hint })?;
448                     info.attestation_info = attestation_info;
449                     Some(info)
450                 }
451             } else {
452                 // No attestation challenge, so no attestation.
453                 if attestation_key.is_some() {
454                     return Err(km_err!(
455                         AttestationChallengeMissing,
456                         "got attestation key but no challenge"
457                     ));
458                 }
459 
460                 // See if the generated key can self-sign.
461                 let is_signing_key = params.iter().any(|param| {
462                     matches!(
463                         param,
464                         KeyParam::Purpose(KeyPurpose::Sign)
465                             | KeyParam::Purpose(KeyPurpose::AttestKey)
466                     )
467                 });
468                 if is_signing_key {
469                     Some(SigningInfo {
470                         attestation_info: None,
471                         signing_key: key_material,
472                         issuer_subject: try_to_vec(tag::get_cert_subject(params)?)?,
473                         chain: Vec::new(),
474                     })
475                 } else {
476                     None
477                 }
478             };
479 
480             // Build the X.509 leaf certificate.
481             let leaf_cert =
482                 self.generate_cert(signing_info.clone(), spki.ref_to_owned(), params, &chars)?;
483             certificate_chain.try_push(leaf_cert)?;
484 
485             // Append the rest of the chain.
486             if let Some(info) = signing_info {
487                 for cert in info.chain {
488                     certificate_chain.try_push(cert)?;
489                 }
490             }
491         }
492 
493         // Now build the keyblob.
494         let kek_context = self.dev.keys.kek_context()?;
495         let root_kek = self.root_kek(&kek_context)?;
496         let hidden = tag::hidden(params, self.root_of_trust()?)?;
497         let encrypted_keyblob = keyblob::encrypt(
498             self.hw_info.security_level,
499             match &mut self.dev.sdd_mgr {
500                 None => None,
501                 Some(mr) => Some(&mut **mr),
502             },
503             &*self.imp.aes,
504             &*self.imp.hkdf,
505             &mut *self.imp.rng,
506             &root_kek,
507             &kek_context,
508             keyblob,
509             hidden,
510             purpose,
511         )?;
512         let serialized_keyblob = encrypted_keyblob.into_vec()?;
513 
514         Ok(KeyCreationResult {
515             key_blob: serialized_keyblob,
516             key_characteristics: chars,
517             certificate_chain,
518         })
519     }
520 
import_wrapped_key( &mut self, wrapped_key_data: &[u8], wrapping_key_blob: &[u8], masking_key: &[u8], unwrapping_params: &[KeyParam], password_sid: i64, biometric_sid: i64, ) -> Result<KeyCreationResult, Error>521     pub(crate) fn import_wrapped_key(
522         &mut self,
523         wrapped_key_data: &[u8],
524         wrapping_key_blob: &[u8],
525         masking_key: &[u8],
526         unwrapping_params: &[KeyParam],
527         password_sid: i64,
528         biometric_sid: i64,
529     ) -> Result<KeyCreationResult, Error> {
530         // Decrypt the wrapping key blob
531         let (wrapping_key, _) = self.keyblob_parse_decrypt(wrapping_key_blob, unwrapping_params)?;
532         let keyblob::PlaintextKeyBlob { characteristics, key_material } = wrapping_key;
533 
534         // Decode the ASN.1 DER encoded `SecureKeyWrapper`.
535         let mut secure_key_wrapper = SecureKeyWrapper::from_der(wrapped_key_data)
536             .map_err(|e| der_err!(e, "failed to parse SecureKeyWrapper"))?;
537 
538         if secure_key_wrapper.version != SECURE_KEY_WRAPPER_VERSION {
539             return Err(km_err!(InvalidArgument, "invalid version in Secure Key Wrapper."));
540         }
541 
542         // Decrypt the masked transport key, using an RSA key. (Only RSA wrapping keys are supported
543         // by the spec, as RSA is the only algorithm supporting asymmetric decryption.)
544         let masked_transport_key = match key_material {
545             KeyMaterial::Rsa(key) => {
546                 // Check the requirements on the wrapping key characterisitcs
547                 let decrypt_mode = tag::check_rsa_wrapping_key_params(
548                     tag::characteristics_at(&characteristics, self.hw_info.security_level)?,
549                     unwrapping_params,
550                 )?;
551 
552                 // Decrypt the masked and encrypted transport key
553                 let mut crypto_op = self.imp.rsa.begin_decrypt(key, decrypt_mode)?;
554                 crypto_op.as_mut().update(secure_key_wrapper.encrypted_transport_key)?;
555                 crypto_op.finish()?
556             }
557             _ => {
558                 return Err(km_err!(InvalidArgument, "invalid key algorithm for transport key"));
559             }
560         };
561 
562         if masked_transport_key.len() != masking_key.len() {
563             return Err(km_err!(
564                 InvalidArgument,
565                 "masked transport key is {} bytes, but masking key is {} bytes",
566                 masked_transport_key.len(),
567                 masking_key.len()
568             ));
569         }
570 
571         let unmasked_transport_key: Vec<u8> =
572             masked_transport_key.iter().zip(masking_key).map(|(x, y)| x ^ y).collect();
573 
574         let aes_transport_key =
575             aes::Key::Aes256(unmasked_transport_key.try_into().map_err(|_e| {
576                 km_err!(
577                     InvalidArgument,
578                     "transport key len {} not correct for AES-256 key",
579                     masked_transport_key.len()
580                 )
581             })?);
582 
583         // Validate the size of the IV and match the `aes::GcmMode` based on the tag size.
584         let iv_len = secure_key_wrapper.initialization_vector.len();
585         if iv_len != aes::GCM_NONCE_SIZE {
586             return Err(km_err!(
587                 InvalidArgument,
588                 "IV length is of {} bytes, which should be of {} bytes",
589                 iv_len,
590                 aes::GCM_NONCE_SIZE
591             ));
592         }
593         let tag_len = secure_key_wrapper.tag.len();
594         let gcm_mode = match tag_len {
595             12 => crypto::aes::GcmMode::GcmTag12 {
596                 nonce: secure_key_wrapper.initialization_vector.try_into()
597                 .unwrap(/* safe: len checked */),
598             },
599             13 => crypto::aes::GcmMode::GcmTag13 {
600                 nonce: secure_key_wrapper.initialization_vector.try_into()
601                 .unwrap(/* safe: len checked */),
602             },
603             14 => crypto::aes::GcmMode::GcmTag14 {
604                 nonce: secure_key_wrapper.initialization_vector.try_into()
605                 .unwrap(/* safe: len checked */),
606             },
607             15 => crypto::aes::GcmMode::GcmTag15 {
608                 nonce: secure_key_wrapper.initialization_vector.try_into()
609                 .unwrap(/* safe: len checked */),
610             },
611             16 => crypto::aes::GcmMode::GcmTag16 {
612                 nonce: secure_key_wrapper.initialization_vector.try_into()
613                 .unwrap(/* safe: len checked */),
614             },
615             v => {
616                 return Err(km_err!(
617                     InvalidMacLength,
618                     "want 12-16 byte tag for AES-GCM not {} bytes",
619                     v
620                 ))
621             }
622         };
623 
624         // Decrypt the encrypted key to be imported, using the ASN.1 DER (re-)encoding of the key
625         // description as the AAD.
626         let mut op = self.imp.aes.begin_aead(
627             OpaqueOr::Explicit(aes_transport_key),
628             gcm_mode,
629             crypto::SymmetricOperation::Decrypt,
630         )?;
631         op.update_aad(
632             &cert::asn1_der_encode(&secure_key_wrapper.key_description)
633                 .map_err(|e| der_err!(e, "failed to re-encode SecureKeyWrapper"))?,
634         )?;
635 
636         let mut imported_key_data = op.update(secure_key_wrapper.encrypted_key)?;
637         imported_key_data.try_extend_from_slice(&op.update(secure_key_wrapper.tag)?)?;
638         imported_key_data.try_extend_from_slice(&op.finish()?)?;
639 
640         // The `Cow::to_mut()` call will not clone, because `from_der()` invokes
641         // `AuthorizationList::decode_value()` which creates the owned variant.
642         let imported_key_params: &mut Vec<KeyParam> =
643             secure_key_wrapper.key_description.key_params.auths.to_mut();
644         if let Some(secure_id) = get_opt_tag_value!(&*imported_key_params, UserSecureId)? {
645             let secure_id = *secure_id;
646             // If both the Password and Fingerprint bits are set in UserSecureId, the password SID
647             // should be used, because biometric auth tokens contain both password and fingerprint
648             // SIDs, but password auth tokens only contain the password SID.
649             if (secure_id & (HardwareAuthenticatorType::Password as u64)
650                 == (HardwareAuthenticatorType::Password as u64))
651                 && (secure_id & (HardwareAuthenticatorType::Fingerprint as u64)
652                     == (HardwareAuthenticatorType::Fingerprint as u64))
653             {
654                 imported_key_params
655                     .retain(|key_param| !matches!(key_param, KeyParam::UserSecureId(_)));
656                 imported_key_params.try_push(KeyParam::UserSecureId(password_sid as u64))?;
657             } else if secure_id & (HardwareAuthenticatorType::Password as u64)
658                 == (HardwareAuthenticatorType::Password as u64)
659             {
660                 imported_key_params
661                     .retain(|key_param| !matches!(key_param, KeyParam::UserSecureId(_)));
662                 imported_key_params.try_push(KeyParam::UserSecureId(password_sid as u64))?;
663             } else if secure_id & (HardwareAuthenticatorType::Fingerprint as u64)
664                 == (HardwareAuthenticatorType::Fingerprint as u64)
665             {
666                 imported_key_params
667                     .retain(|key_param| !matches!(key_param, KeyParam::UserSecureId(_)));
668                 imported_key_params.try_push(KeyParam::UserSecureId(biometric_sid as u64))?;
669             }
670         };
671 
672         // There is no way for clients to pass CERTIFICATE_NOT_BEFORE and CERTIFICATE_NOT_AFTER.
673         // importWrappedKey must use validity with no well-defined expiration date.
674         imported_key_params.try_push(KeyParam::CertificateNotBefore(UNDEFINED_NOT_BEFORE))?;
675         imported_key_params.try_push(KeyParam::CertificateNotAfter(UNDEFINED_NOT_AFTER))?;
676 
677         self.import_key(
678             imported_key_params,
679             KeyFormat::try_from(secure_key_wrapper.key_description.key_format).map_err(|_e| {
680                 km_err!(
681                     UnsupportedKeyFormat,
682                     "could not convert the provided keyformat {}",
683                     secure_key_wrapper.key_description.key_format
684                 )
685             })?,
686             &imported_key_data,
687             None,
688             KeyImport::Wrapped,
689         )
690     }
691 
upgrade_key( &mut self, keyblob_to_upgrade: &[u8], upgrade_params: Vec<KeyParam>, ) -> Result<Vec<u8>, Error>692     pub(crate) fn upgrade_key(
693         &mut self,
694         keyblob_to_upgrade: &[u8],
695         upgrade_params: Vec<KeyParam>,
696     ) -> Result<Vec<u8>, Error> {
697         let (mut keyblob, mut modified) =
698             match self.keyblob_parse_decrypt_backlevel(keyblob_to_upgrade, &upgrade_params) {
699                 Ok(v) => (v.0, false),
700                 Err(Error::Hal(ErrorCode::KeyRequiresUpgrade, _)) => {
701                     // Because `keyblob_parse_decrypt_backlevel` explicitly allows back-level
702                     // versioned keys, a `KeyRequiresUpgrade` error indicates that the keyblob looks
703                     // to be in legacy format.  Try to convert it.
704                     let legacy_handler =
705                         self.dev.legacy_key.as_mut().ok_or_else(|| {
706                             km_err!(KeymintNotConfigured, "no legacy key handler")
707                         })?;
708                     (
709                         legacy_handler.convert_legacy_key(
710                             keyblob_to_upgrade,
711                             &upgrade_params,
712                             self.boot_info
713                                 .as_ref()
714                                 .ok_or_else(|| km_err!(HardwareNotYetAvailable, "no boot info"))?,
715                             self.hw_info.security_level,
716                         )?,
717                         // Force the emission of a new keyblob even if versions are the same.
718                         true,
719                     )
720                 }
721                 Err(e) => return Err(e),
722             };
723 
724         fn upgrade(v: &mut u32, curr: u32, name: &str) -> Result<bool, Error> {
725             match (*v).cmp(&curr) {
726                 Ordering::Less => {
727                     *v = curr;
728                     Ok(true)
729                 }
730                 Ordering::Equal => Ok(false),
731                 Ordering::Greater => {
732                     error!("refusing to downgrade {} from {} to {}", name, v, curr);
733                     Err(km_err!(
734                         InvalidArgument,
735                         "keyblob with future {} {} (current {})",
736                         name,
737                         v,
738                         curr
739                     ))
740                 }
741             }
742         }
743 
744         for chars in &mut keyblob.characteristics {
745             if chars.security_level != self.hw_info.security_level {
746                 continue;
747             }
748             for param in &mut chars.authorizations {
749                 match param {
750                     KeyParam::OsVersion(v) => {
751                         if let Some(hal_info) = &self.hal_info {
752                             if hal_info.os_version == 0 {
753                                 // Special case: upgrades to OS version zero are always allowed.
754                                 warn!("forcing upgrade to OS version 0");
755                                 modified |= *v != 0;
756                                 *v = 0;
757                             } else {
758                                 modified |= upgrade(v, hal_info.os_version, "OS version")?;
759                             }
760                         } else {
761                             error!("OS version not available, can't upgrade from {}", v);
762                         }
763                     }
764                     KeyParam::OsPatchlevel(v) => {
765                         if let Some(hal_info) = &self.hal_info {
766                             modified |= upgrade(v, hal_info.os_patchlevel, "OS patchlevel")?;
767                         } else {
768                             error!("OS patchlevel not available, can't upgrade from {}", v);
769                         }
770                     }
771                     KeyParam::VendorPatchlevel(v) => {
772                         if let Some(hal_info) = &self.hal_info {
773                             modified |=
774                                 upgrade(v, hal_info.vendor_patchlevel, "vendor patchlevel")?;
775                         } else {
776                             error!("vendor patchlevel not available, can't upgrade from {}", v);
777                         }
778                     }
779                     KeyParam::BootPatchlevel(v) => {
780                         if let Some(boot_info) = &self.boot_info {
781                             modified |= upgrade(v, boot_info.boot_patchlevel, "boot patchlevel")?;
782                         } else {
783                             error!("boot patchlevel not available, can't upgrade from {}", v);
784                         }
785                     }
786                     _ => {}
787                 }
788             }
789         }
790 
791         if !modified {
792             // No upgrade needed, return empty data to indicate existing keyblob can still be used.
793             return Ok(Vec::new());
794         }
795 
796         // Now re-build the keyblob. Use a potentially fresh key encryption key, and potentially a
797         // new secure deletion secret slot. (The old slot will be released when Keystore performs
798         // the corresponding `deleteKey` operation on the old keyblob.
799         let kek_context = self.dev.keys.kek_context()?;
800         let root_kek = self.root_kek(&kek_context)?;
801         let hidden = tag::hidden(&upgrade_params, self.root_of_trust()?)?;
802         let encrypted_keyblob = keyblob::encrypt(
803             self.hw_info.security_level,
804             match &mut self.dev.sdd_mgr {
805                 None => None,
806                 Some(mr) => Some(&mut **mr),
807             },
808             &*self.imp.aes,
809             &*self.imp.hkdf,
810             &mut *self.imp.rng,
811             &root_kek,
812             &kek_context,
813             keyblob,
814             hidden,
815             keyblob::SlotPurpose::KeyUpgrade,
816         )?;
817         Ok(encrypted_keyblob.into_vec()?)
818     }
819 }
820