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