• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! KeyMint trusted application (TA) implementation.
2 
3 #![no_std]
4 extern crate alloc;
5 
6 use alloc::{boxed::Box, collections::BTreeMap, rc::Rc, string::ToString, vec::Vec};
7 use core::cmp::Ordering;
8 use core::mem::size_of;
9 use core::{cell::RefCell, convert::TryFrom};
10 use device::DiceInfo;
11 use kmr_common::{
12     crypto::{self, hmac, OpaqueOr},
13     get_bool_tag_value,
14     keyblob::{self, RootOfTrustInfo, SecureDeletionSlot},
15     km_err, tag, vec_try, vec_try_with_capacity, Error, FallibleAllocExt,
16 };
17 use kmr_wire::{
18     coset::TaggedCborSerializable,
19     keymint::{
20         Digest, ErrorCode, HardwareAuthToken, KeyCharacteristics, KeyMintHardwareInfo, KeyOrigin,
21         KeyParam, SecurityLevel, VerifiedBootState, NEXT_MESSAGE_SIGNAL_FALSE,
22         NEXT_MESSAGE_SIGNAL_TRUE,
23     },
24     rpc,
25     rpc::{EekCurve, IRPC_V2, IRPC_V3},
26     secureclock::{TimeStampToken, Timestamp},
27     sharedsecret::SharedSecretParameters,
28     *,
29 };
30 use log::{error, info, trace, warn};
31 
32 mod cert;
33 mod clock;
34 pub mod device;
35 mod keys;
36 mod operation;
37 pub mod rkp;
38 mod secret;
39 
40 use keys::KeyImport;
41 use operation::{OpHandle, Operation};
42 
43 #[cfg(test)]
44 mod tests;
45 
46 /// Maximum number of parallel operations supported when running as TEE.
47 const MAX_TEE_OPERATIONS: usize = 16;
48 
49 /// Maximum number of parallel operations supported when running as StrongBox.
50 const MAX_STRONGBOX_OPERATIONS: usize = 4;
51 
52 /// Maximum number of keys whose use count can be tracked.
53 const MAX_USE_COUNTED_KEYS: usize = 32;
54 
55 /// Per-key ID use count.
56 struct UseCount {
57     key_id: KeyId,
58     count: u64,
59 }
60 
61 /// Attestation chain information.
62 struct AttestationChainInfo {
63     /// Chain of certificates from intermediate to root.
64     chain: Vec<keymint::Certificate>,
65     /// Subject field from the first certificate in the chain, as an ASN.1 DER encoded `Name` (cf
66     /// RFC 5280 s4.1.2.4).
67     issuer: Vec<u8>,
68 }
69 
70 /// KeyMint device implementation, running in secure environment.
71 pub struct KeyMintTa<'a> {
72     /**
73      * State that is fixed on construction.
74      */
75 
76     /// Trait objects that hold this device's implementations of the abstract cryptographic
77     /// functionality traits.
78     imp: crypto::Implementation<'a>,
79 
80     /// Trait objects that hold this device's implementations of per-device functionality.
81     dev: device::Implementation<'a>,
82 
83     /// Information about this particular KeyMint implementation's hardware.
84     hw_info: HardwareInfo,
85 
86     /// Information about the implementation of the IRemotelyProvisionedComponent (IRPC) HAL.
87     rpc_info: RpcInfo,
88 
89     /**
90      * State that is set after the TA starts, but latched thereafter.
91      */
92 
93     /// Parameters for shared secret negotiation.
94     shared_secret_params: Option<SharedSecretParameters>,
95 
96     /// Information provided by the bootloader once at start of day.
97     boot_info: Option<keymint::BootInfo>,
98     rot_data: Option<Vec<u8>>,
99 
100     /// Information provided by the HAL service once at start of day.
101     hal_info: Option<HalInfo>,
102 
103     /// Attestation chain information, retrieved on first use.
104     attestation_chain_info: RefCell<BTreeMap<device::SigningKeyType, AttestationChainInfo>>,
105 
106     /// Attestation ID information, fixed forever for a device, but retrieved on first use.
107     attestation_id_info: RefCell<Option<Rc<AttestationIdInfo>>>,
108 
109     // Public DICE artifacts (UDS certs and the DICE chain) included in the certificate signing
110     // requests (CSR) and the algorithm used to sign the CSR for IRemotelyProvisionedComponent
111     // (IRPC) HAL. Fixed for a device. Retrieved on first use.
112     //
113     // Note: This information is cached only in the implementations of IRPC HAL V3 and
114     // IRPC HAL V2 in production mode.
115     dice_info: RefCell<Option<Rc<DiceInfo>>>,
116 
117     /// Whether the device is still in early-boot.
118     in_early_boot: bool,
119 
120     /// Device HMAC implementation which uses the `ISharedSecret` negotiated key.
121     device_hmac: Option<Box<dyn device::DeviceHmac>>,
122 
123     /**
124      * State that changes during operation.
125      */
126 
127     /// Whether the device's screen is locked.
128     device_locked: RefCell<LockState>,
129 
130     /// Challenge for root-of-trust transfer (StrongBox only).
131     rot_challenge: [u8; 16],
132 
133     /// The operation table.
134     operations: Vec<Option<Operation>>,
135 
136     /// Use counts for keys where this is tracked.
137     use_count: [Option<UseCount>; MAX_USE_COUNTED_KEYS],
138 
139     /// Operation handle of the (single) in-flight operation that requires trusted user presence.
140     presence_required_op: Option<OpHandle>,
141 }
142 
143 /// A helper method that can be used by the TA for processing the responses to be sent to the
144 /// HAL service. Splits large response messages into multiple parts based on the capacity of the
145 /// channel from the TA to the HAL. One element in the returned response array consists of:
146 /// <next_msg_signal + response data> where next_msg_signal is a byte whose value is 1 if there are
147 /// more messages in the response array following this one. This signal should be used by the HAL
148 /// side to decide whether or not to wait for more messages. Implementation of this method must be
149 /// in sync with its counterpart in the `kmr-hal` crate.
split_rsp(mut rsp_data: &[u8], max_size: usize) -> Result<Vec<Vec<u8>>, Error>150 pub fn split_rsp(mut rsp_data: &[u8], max_size: usize) -> Result<Vec<Vec<u8>>, Error> {
151     if rsp_data.is_empty() || max_size < 2 {
152         return Err(km_err!(
153             InvalidArgument,
154             "response data is empty or max size: {} is invalid",
155             max_size
156         ));
157     }
158     // Need to allocate one byte for the more_msg_signal.
159     let allowed_msg_length = max_size - 1;
160     let mut num_of_splits = rsp_data.len() / allowed_msg_length;
161     if rsp_data.len() % allowed_msg_length > 0 {
162         num_of_splits += 1;
163     }
164     let mut split_rsp = vec_try_with_capacity!(num_of_splits)?;
165     while rsp_data.len() > allowed_msg_length {
166         let mut rsp = vec_try_with_capacity!(allowed_msg_length + 1)?;
167         rsp.push(NEXT_MESSAGE_SIGNAL_TRUE);
168         rsp.extend_from_slice(&rsp_data[..allowed_msg_length]);
169         trace!("Current response size with signalling byte: {}", rsp.len());
170         split_rsp.push(rsp);
171         rsp_data = &rsp_data[allowed_msg_length..];
172     }
173     let mut last_rsp = vec_try_with_capacity!(rsp_data.len() + 1)?;
174     last_rsp.push(NEXT_MESSAGE_SIGNAL_FALSE);
175     last_rsp.extend_from_slice(rsp_data);
176     split_rsp.push(last_rsp);
177     Ok(split_rsp)
178 }
179 
180 /// Device lock state
181 #[derive(Clone, Copy, Debug)]
182 enum LockState {
183     /// Device is unlocked.
184     Unlocked,
185     /// Device has been locked since the given time.
186     LockedSince(Timestamp),
187     /// Device has been locked since the given time, and can only be unlocked with a password
188     /// (rather than a biometric).
189     PasswordLockedSince(Timestamp),
190 }
191 
192 /// Hardware information.
193 #[derive(Clone, Debug)]
194 pub struct HardwareInfo {
195     // Fields that correspond to the HAL `KeyMintHardwareInfo` type.
196     pub security_level: SecurityLevel,
197     pub version_number: i32,
198     pub impl_name: &'static str,
199     pub author_name: &'static str,
200     pub unique_id: &'static str,
201     // The `timestamp_token_required` field in `KeyMintHardwareInfo` is skipped here because it gets
202     // set depending on whether a local clock is available.
203 }
204 
205 /// Information required to construct the structures defined in RpcHardwareInfo.aidl
206 /// and DeviceInfo.aidl, for IRemotelyProvisionedComponent (IRPC) HAL V2.
207 #[derive(Debug)]
208 pub struct RpcInfoV2 {
209     // Used in RpcHardwareInfo.aidl
210     pub author_name: &'static str,
211     pub supported_eek_curve: EekCurve,
212     pub unique_id: &'static str,
213     // Used as `DeviceInfo.fused`.
214     // Indication of whether secure boot is enforced for the processor running this code.
215     pub fused: bool,
216 }
217 
218 /// Information required to construct the structures defined in RpcHardwareInfo.aidl
219 /// and DeviceInfo.aidl, for IRemotelyProvisionedComponent (IRPC) HAL V3.
220 #[derive(Debug)]
221 pub struct RpcInfoV3 {
222     // Used in RpcHardwareInfo.aidl
223     pub author_name: &'static str,
224     pub unique_id: &'static str,
225     // Used as `DeviceInfo.fused`.
226     // Indication of whether secure boot is enforced for the processor running this code.
227     pub fused: bool,
228     pub supported_num_of_keys_in_csr: i32,
229 }
230 
231 /// Enum to distinguish the set of information required for different versions of IRPC HAL
232 /// implementations
233 pub enum RpcInfo {
234     V2(RpcInfoV2),
235     V3(RpcInfoV3),
236 }
237 
238 impl RpcInfo {
get_version(&self) -> i32239     pub fn get_version(&self) -> i32 {
240         match self {
241             RpcInfo::V2(_) => IRPC_V2,
242             RpcInfo::V3(_) => IRPC_V3,
243         }
244     }
245 }
246 
247 /// Information provided once at service start by the HAL service, describing
248 /// the state of the userspace operating system (which may change from boot to
249 /// boot, e.g. for running GSI).
250 #[derive(Clone, Copy, Debug)]
251 pub struct HalInfo {
252     pub os_version: u32,
253     pub os_patchlevel: u32,     // YYYYMM format
254     pub vendor_patchlevel: u32, // YYYYMMDD format
255 }
256 
257 /// Identifier for a keyblob.
258 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
259 struct KeyId([u8; 32]);
260 
261 impl<'a> KeyMintTa<'a> {
262     /// Create a new [`KeyMintTa`] instance.
new( hw_info: HardwareInfo, rpc_info: RpcInfo, imp: crypto::Implementation<'a>, dev: device::Implementation<'a>, ) -> Self263     pub fn new(
264         hw_info: HardwareInfo,
265         rpc_info: RpcInfo,
266         imp: crypto::Implementation<'a>,
267         dev: device::Implementation<'a>,
268     ) -> Self {
269         let max_operations = if hw_info.security_level == SecurityLevel::Strongbox {
270             MAX_STRONGBOX_OPERATIONS
271         } else {
272             MAX_TEE_OPERATIONS
273         };
274         Self {
275             imp,
276             dev,
277             in_early_boot: true,
278             // Note: Keystore currently doesn't trigger the `deviceLocked()` KeyMint entrypoint,
279             // so treat the device as not-locked at start-of-day.
280             device_locked: RefCell::new(LockState::Unlocked),
281             device_hmac: None,
282             rot_challenge: [0; 16],
283             // Work around Rust limitation that `vec![None; n]` doesn't work.
284             operations: (0..max_operations).map(|_| None).collect(),
285             use_count: Default::default(),
286             presence_required_op: None,
287             shared_secret_params: None,
288             hw_info,
289             rpc_info,
290             boot_info: None,
291             rot_data: None,
292             hal_info: None,
293             attestation_chain_info: RefCell::new(BTreeMap::new()),
294             attestation_id_info: RefCell::new(None),
295             dice_info: RefCell::new(None),
296         }
297     }
298 
299     /// Returns key used to sign auth tokens
get_hmac_key(&self) -> Option<hmac::Key>300     pub fn get_hmac_key(&self) -> Option<hmac::Key> {
301         match &self.device_hmac {
302             Some(device_hmac) => device_hmac.get_hmac_key(),
303             None => None,
304         }
305     }
306 
307     /// Indicate whether the current device is acting as a StrongBox instance.
is_strongbox(&self) -> bool308     pub fn is_strongbox(&self) -> bool {
309         self.hw_info.security_level == SecurityLevel::Strongbox
310     }
311 
312     /// Indicate whether the current device has secure storage available.
secure_storage_available(&self) -> kmr_common::tag::SecureStorage313     fn secure_storage_available(&self) -> kmr_common::tag::SecureStorage {
314         if self.dev.sdd_mgr.is_some() {
315             kmr_common::tag::SecureStorage::Available
316         } else {
317             kmr_common::tag::SecureStorage::Unavailable
318         }
319     }
320 
321     /// Return the device's boot information.
boot_info(&self) -> Result<&keymint::BootInfo, Error>322     fn boot_info(&self) -> Result<&keymint::BootInfo, Error> {
323         self.boot_info
324             .as_ref()
325             .ok_or_else(|| km_err!(HardwareNotYetAvailable, "no boot info available"))
326     }
327 
328     /// Parse and decrypt an encrypted key blob, allowing through keys that require upgrade due to
329     /// patchlevel updates.  Keys that appear to be in a legacy format may still emit a
330     /// [`ErrorCode::KeyRequiresUpgrade`] error.
keyblob_parse_decrypt_backlevel( &self, key_blob: &[u8], params: &[KeyParam], ) -> Result<(keyblob::PlaintextKeyBlob, Option<SecureDeletionSlot>), Error>331     fn keyblob_parse_decrypt_backlevel(
332         &self,
333         key_blob: &[u8],
334         params: &[KeyParam],
335     ) -> Result<(keyblob::PlaintextKeyBlob, Option<SecureDeletionSlot>), Error> {
336         let encrypted_keyblob = match keyblob::EncryptedKeyBlob::new(key_blob) {
337             Ok(k) => k,
338             Err(e) => {
339                 // We might have failed to parse the keyblob because it is in some prior format.
340                 if let Some(old_key) = self.dev.legacy_key.as_ref() {
341                     if old_key.is_legacy_key(key_blob, params, self.boot_info()?) {
342                         return Err(km_err!(
343                             KeyRequiresUpgrade,
344                             "legacy key detected, request upgrade"
345                         ));
346                     }
347                 }
348                 return Err(e);
349             }
350         };
351         let hidden = tag::hidden(params, self.root_of_trust()?)?;
352         let sdd_slot = encrypted_keyblob.secure_deletion_slot();
353         let root_kek = self.root_kek(encrypted_keyblob.kek_context())?;
354         let keyblob = keyblob::decrypt(
355             match &self.dev.sdd_mgr {
356                 None => None,
357                 Some(mr) => Some(*mr),
358             },
359             self.imp.aes,
360             self.imp.hkdf,
361             &root_kek,
362             encrypted_keyblob,
363             hidden,
364         )?;
365         Ok((keyblob, sdd_slot))
366     }
367 
368     /// Parse and decrypt an encrypted key blob, detecting keys that require upgrade.
keyblob_parse_decrypt( &self, key_blob: &[u8], params: &[KeyParam], ) -> Result<(keyblob::PlaintextKeyBlob, Option<SecureDeletionSlot>), Error>369     fn keyblob_parse_decrypt(
370         &self,
371         key_blob: &[u8],
372         params: &[KeyParam],
373     ) -> Result<(keyblob::PlaintextKeyBlob, Option<SecureDeletionSlot>), Error> {
374         let (keyblob, slot) = self.keyblob_parse_decrypt_backlevel(key_blob, params)?;
375 
376         // Check all of the patchlevels and versions to see if key upgrade is required.
377         fn check(v: &u32, curr: u32, name: &str) -> Result<(), Error> {
378             match (*v).cmp(&curr) {
379                 Ordering::Less => Err(km_err!(
380                     KeyRequiresUpgrade,
381                     "keyblob with old {} {} needs upgrade to current {}",
382                     name,
383                     v,
384                     curr
385                 )),
386                 Ordering::Equal => Ok(()),
387                 Ordering::Greater => Err(km_err!(
388                     InvalidKeyBlob,
389                     "keyblob with future {} {} (current {})",
390                     name,
391                     v,
392                     curr
393                 )),
394             }
395         }
396 
397         let key_chars = keyblob.characteristics_at(self.hw_info.security_level)?;
398         for param in key_chars {
399             match param {
400                 KeyParam::OsVersion(v) => {
401                     if let Some(hal_info) = &self.hal_info {
402                         if hal_info.os_version == 0 {
403                             // Special case: upgrades to OS version zero are always allowed.
404                             if *v != 0 {
405                                 warn!("requesting upgrade to OS version 0");
406                                 return Err(km_err!(
407                                     KeyRequiresUpgrade,
408                                     "keyblob with OS version {} needs upgrade to current version 0",
409                                     v,
410                                 ));
411                             }
412                         } else {
413                             check(v, hal_info.os_version, "OS version")?;
414                         }
415                     } else {
416                         error!("OS version not available, can't check for upgrade from {}", v);
417                     }
418                 }
419                 KeyParam::OsPatchlevel(v) => {
420                     if let Some(hal_info) = &self.hal_info {
421                         check(v, hal_info.os_patchlevel, "OS patchlevel")?;
422                     } else {
423                         error!("OS patchlevel not available, can't check for upgrade from {}", v);
424                     }
425                 }
426                 KeyParam::VendorPatchlevel(v) => {
427                     if let Some(hal_info) = &self.hal_info {
428                         check(v, hal_info.vendor_patchlevel, "vendor patchlevel")?;
429                     } else {
430                         error!(
431                             "vendor patchlevel not available, can't check for upgrade from {}",
432                             v
433                         );
434                     }
435                 }
436                 KeyParam::BootPatchlevel(v) => {
437                     if let Some(boot_info) = &self.boot_info {
438                         check(v, boot_info.boot_patchlevel, "boot patchlevel")?;
439                     } else {
440                         error!("boot patchlevel not available, can't check for upgrade from {}", v);
441                     }
442                 }
443                 _ => {}
444             }
445         }
446         Ok((keyblob, slot))
447     }
448 
449     /// Generate a unique identifier for a keyblob.
key_id(&self, keyblob: &[u8]) -> Result<KeyId, Error>450     fn key_id(&self, keyblob: &[u8]) -> Result<KeyId, Error> {
451         let mut hmac_op =
452             self.imp.hmac.begin(crypto::hmac::Key(vec_try![0; 16]?).into(), Digest::Sha256)?;
453         hmac_op.update(keyblob)?;
454         let tag = hmac_op.finish()?;
455 
456         Ok(KeyId(
457             tag.try_into()
458                 .map_err(|_e| km_err!(UnknownError, "wrong size output from HMAC-SHA256"))?,
459         ))
460     }
461 
462     /// Increment the use count for the given key ID, failing if `max_uses` is reached.
update_use_count(&mut self, key_id: KeyId, max_uses: u32) -> Result<(), Error>463     fn update_use_count(&mut self, key_id: KeyId, max_uses: u32) -> Result<(), Error> {
464         let mut free_idx = None;
465         let mut slot_idx = None;
466         for idx in 0..self.use_count.len() {
467             match &self.use_count[idx] {
468                 None if free_idx.is_none() => free_idx = Some(idx),
469                 None => {}
470                 Some(UseCount { key_id: k, count: _count }) if *k == key_id => {
471                     slot_idx = Some(idx);
472                     break;
473                 }
474                 Some(_) => {}
475             }
476         }
477         if slot_idx.is_none() {
478             // First use of this key ID; use a free slot if available.
479             if let Some(idx) = free_idx {
480                 self.use_count[idx] = Some(UseCount { key_id, count: 0 });
481                 slot_idx = Some(idx);
482             }
483         }
484 
485         if let Some(idx) = slot_idx {
486             let c = self.use_count[idx].as_mut().unwrap(); // safe: code above guarantees
487             if c.count >= max_uses as u64 {
488                 Err(km_err!(KeyMaxOpsExceeded, "use count {} >= limit {}", c.count, max_uses))
489             } else {
490                 c.count += 1;
491                 Ok(())
492             }
493         } else {
494             Err(km_err!(TooManyOperations, "too many use-counted keys already in play"))
495         }
496     }
497 
498     /// Configure the boot-specific root of trust info.  KeyMint implementors should call this
499     /// method when this information arrives from the bootloader (which happens in an
500     /// implementation-specific manner).
set_boot_info(&mut self, boot_info: keymint::BootInfo) -> Result<(), Error>501     pub fn set_boot_info(&mut self, boot_info: keymint::BootInfo) -> Result<(), Error> {
502         if !self.in_early_boot {
503             error!("Rejecting attempt to set boot info {:?} after early boot", boot_info);
504         }
505         if let Some(existing_boot_info) = &self.boot_info {
506             if *existing_boot_info == boot_info {
507                 warn!(
508                     "Boot info already set, ignoring second attempt to set same values {:?}",
509                     boot_info
510                 );
511             } else {
512                 return Err(km_err!(
513                     InvalidArgument,
514                     "attempt to set boot info to {:?} but already set to {:?}",
515                     boot_info,
516                     existing_boot_info
517                 ));
518             }
519         } else {
520             info!("Setting boot_info to {:?}", boot_info);
521             let rot_info = RootOfTrustInfo {
522                 verified_boot_key: boot_info.verified_boot_key.clone(),
523                 device_boot_locked: boot_info.device_boot_locked,
524                 verified_boot_state: boot_info.verified_boot_state,
525             };
526             self.boot_info = Some(boot_info);
527             self.rot_data =
528                 Some(rot_info.into_vec().map_err(|e| {
529                     km_err!(UnknownError, "failed to encode root-of-trust: {:?}", e)
530                 })?);
531         }
532         Ok(())
533     }
534 
535     /// Check if HAL-derived information has been set. This is used as an
536     /// indication that we are past the boot stage.
is_hal_info_set(&self) -> bool537     pub fn is_hal_info_set(&self) -> bool {
538         self.hal_info.is_some()
539     }
540 
541     /// Configure the HAL-derived information, learnt from the userspace
542     /// operating system.
set_hal_info(&mut self, hal_info: HalInfo)543     pub fn set_hal_info(&mut self, hal_info: HalInfo) {
544         if self.hal_info.is_none() {
545             info!("Setting hal_info to {:?}", hal_info);
546             self.hal_info = Some(hal_info);
547         } else {
548             warn!(
549                 "Hal info already set to {:?}, ignoring new values {:?}",
550                 self.hal_info, hal_info
551             );
552         }
553     }
554 
555     /// Configure attestation IDs externally.
set_attestation_ids(&self, ids: AttestationIdInfo)556     pub fn set_attestation_ids(&self, ids: AttestationIdInfo) {
557         if self.dev.attest_ids.is_some() {
558             error!("Attempt to set attestation IDs externally");
559         } else if self.attestation_id_info.borrow().is_some() {
560             error!("Attempt to set attestation IDs when already set");
561         } else {
562             warn!("Setting attestation IDs directly");
563             *self.attestation_id_info.borrow_mut() = Some(Rc::new(ids));
564         }
565     }
566 
567     /// Retrieve the attestation ID information for the device, if available.
get_attestation_ids(&self) -> Option<Rc<AttestationIdInfo>>568     fn get_attestation_ids(&self) -> Option<Rc<AttestationIdInfo>> {
569         if self.attestation_id_info.borrow().is_none() {
570             if let Some(get_ids_impl) = self.dev.attest_ids.as_ref() {
571                 // Attestation IDs are not populated, but we have a trait implementation that
572                 // may provide them.
573                 match get_ids_impl.get() {
574                     Ok(ids) => *self.attestation_id_info.borrow_mut() = Some(Rc::new(ids)),
575                     Err(e) => error!("Failed to retrieve attestation IDs: {:?}", e),
576                 }
577             }
578         }
579         self.attestation_id_info.borrow().as_ref().cloned()
580     }
581 
582     /// Retrieve the DICE info for the device, if available.
get_dice_info(&self) -> Option<Rc<DiceInfo>>583     fn get_dice_info(&self) -> Option<Rc<DiceInfo>> {
584         if self.dice_info.borrow().is_none() {
585             // DICE info is not populated, but we have a trait method that
586             // may provide them.
587             match self.dev.rpc.get_dice_info(rpc::TestMode(false)) {
588                 Ok(dice_info) => *self.dice_info.borrow_mut() = Some(Rc::new(dice_info)),
589                 Err(e) => error!("Failed to retrieve DICE info: {:?}", e),
590             }
591         }
592         self.dice_info.borrow().as_ref().cloned()
593     }
594 
595     /// Process a single serialized request, returning a serialized response.
process(&mut self, req_data: &[u8]) -> Vec<u8>596     pub fn process(&mut self, req_data: &[u8]) -> Vec<u8> {
597         let (req_code, rsp) = match PerformOpReq::from_slice(req_data) {
598             Ok(req) => {
599                 trace!("-> TA: received request {:?}", req.code());
600                 (Some(req.code()), self.process_req(req))
601             }
602             Err(e) => {
603                 error!("failed to decode CBOR request: {:?}", e);
604                 // We need to report the error to the HAL, but we don't know whether the request was
605                 // for the `IRemotelyProvisionedComponent` or for one of the other HALs, so we don't
606                 // know what numbering space the error codes are expected to be in.  Assume the
607                 // shared KeyMint `ErrorCode` space.
608                 (None, error_rsp(ErrorCode::UnknownError as i32))
609             }
610         };
611         trace!("<- TA: send response {:?} rc {}", req_code, rsp.error_code);
612         match rsp.into_vec() {
613             Ok(rsp_data) => rsp_data,
614             Err(e) => {
615                 error!("failed to encode CBOR response: {:?}", e);
616                 invalid_cbor_rsp_data().to_vec()
617             }
618         }
619     }
620 
621     /// Process a single request, returning a [`PerformOpResponse`].
622     ///
623     /// Select the appropriate method based on the request type, and use the
624     /// request fields as parameters to the method.  In the opposite direction,
625     /// build a response message from the values returned by the method.
process_req(&mut self, req: PerformOpReq) -> PerformOpResponse626     fn process_req(&mut self, req: PerformOpReq) -> PerformOpResponse {
627         match req {
628             // Internal messages.
629             PerformOpReq::SetBootInfo(req) => {
630                 let verified_boot_state = match VerifiedBootState::try_from(req.verified_boot_state)
631                 {
632                     Ok(state) => state,
633                     Err(e) => return op_error_rsp(SetBootInfoRequest::CODE, Error::Cbor(e)),
634                 };
635                 match self.set_boot_info(keymint::BootInfo {
636                     verified_boot_key: req.verified_boot_key,
637                     device_boot_locked: req.device_boot_locked,
638                     verified_boot_state,
639                     verified_boot_hash: req.verified_boot_hash,
640                     boot_patchlevel: req.boot_patchlevel,
641                 }) {
642                     Ok(_) => op_ok_rsp(PerformOpRsp::SetBootInfo(SetBootInfoResponse {})),
643                     Err(e) => op_error_rsp(SetBootInfoRequest::CODE, e),
644                 }
645             }
646             PerformOpReq::SetHalInfo(req) => {
647                 self.set_hal_info(HalInfo {
648                     os_version: req.os_version,
649                     os_patchlevel: req.os_patchlevel,
650                     vendor_patchlevel: req.vendor_patchlevel,
651                 });
652                 op_ok_rsp(PerformOpRsp::SetHalInfo(SetHalInfoResponse {}))
653             }
654             PerformOpReq::SetAttestationIds(req) => {
655                 self.set_attestation_ids(req.ids);
656                 op_ok_rsp(PerformOpRsp::SetAttestationIds(SetAttestationIdsResponse {}))
657             }
658 
659             // ISharedSecret messages.
660             PerformOpReq::SharedSecretGetSharedSecretParameters(_req) => {
661                 match self.get_shared_secret_params() {
662                     Ok(ret) => op_ok_rsp(PerformOpRsp::SharedSecretGetSharedSecretParameters(
663                         GetSharedSecretParametersResponse { ret },
664                     )),
665                     Err(e) => op_error_rsp(GetSharedSecretParametersRequest::CODE, e),
666                 }
667             }
668             PerformOpReq::SharedSecretComputeSharedSecret(req) => {
669                 match self.compute_shared_secret(&req.params) {
670                     Ok(ret) => op_ok_rsp(PerformOpRsp::SharedSecretComputeSharedSecret(
671                         ComputeSharedSecretResponse { ret },
672                     )),
673                     Err(e) => op_error_rsp(ComputeSharedSecretRequest::CODE, e),
674                 }
675             }
676 
677             // ISecureClock messages.
678             PerformOpReq::SecureClockGenerateTimeStamp(req) => {
679                 match self.generate_timestamp(req.challenge) {
680                     Ok(ret) => op_ok_rsp(PerformOpRsp::SecureClockGenerateTimeStamp(
681                         GenerateTimeStampResponse { ret },
682                     )),
683                     Err(e) => op_error_rsp(GenerateTimeStampRequest::CODE, e),
684                 }
685             }
686 
687             // IKeyMintDevice messages.
688             PerformOpReq::DeviceGetHardwareInfo(_req) => match self.get_hardware_info() {
689                 Ok(ret) => {
690                     op_ok_rsp(PerformOpRsp::DeviceGetHardwareInfo(GetHardwareInfoResponse { ret }))
691                 }
692                 Err(e) => op_error_rsp(GetHardwareInfoRequest::CODE, e),
693             },
694             PerformOpReq::DeviceAddRngEntropy(req) => match self.add_rng_entropy(&req.data) {
695                 Ok(_ret) => op_ok_rsp(PerformOpRsp::DeviceAddRngEntropy(AddRngEntropyResponse {})),
696                 Err(e) => op_error_rsp(AddRngEntropyRequest::CODE, e),
697             },
698             PerformOpReq::DeviceGenerateKey(req) => {
699                 match self.generate_key(&req.key_params, req.attestation_key) {
700                     Ok(ret) => {
701                         op_ok_rsp(PerformOpRsp::DeviceGenerateKey(GenerateKeyResponse { ret }))
702                     }
703                     Err(e) => op_error_rsp(GenerateKeyRequest::CODE, e),
704                 }
705             }
706             PerformOpReq::DeviceImportKey(req) => {
707                 match self.import_key(
708                     &req.key_params,
709                     req.key_format,
710                     &req.key_data,
711                     req.attestation_key,
712                     KeyImport::NonWrapped,
713                 ) {
714                     Ok(ret) => op_ok_rsp(PerformOpRsp::DeviceImportKey(ImportKeyResponse { ret })),
715                     Err(e) => op_error_rsp(ImportKeyRequest::CODE, e),
716                 }
717             }
718             PerformOpReq::DeviceImportWrappedKey(req) => {
719                 match self.import_wrapped_key(
720                     &req.wrapped_key_data,
721                     &req.wrapping_key_blob,
722                     &req.masking_key,
723                     &req.unwrapping_params,
724                     req.password_sid,
725                     req.biometric_sid,
726                 ) {
727                     Ok(ret) => {
728                         op_ok_rsp(PerformOpRsp::DeviceImportWrappedKey(ImportWrappedKeyResponse {
729                             ret,
730                         }))
731                     }
732                     Err(e) => op_error_rsp(ImportWrappedKeyRequest::CODE, e),
733                 }
734             }
735             PerformOpReq::DeviceUpgradeKey(req) => {
736                 match self.upgrade_key(&req.key_blob_to_upgrade, req.upgrade_params) {
737                     Ok(ret) => {
738                         op_ok_rsp(PerformOpRsp::DeviceUpgradeKey(UpgradeKeyResponse { ret }))
739                     }
740                     Err(e) => op_error_rsp(UpgradeKeyRequest::CODE, e),
741                 }
742             }
743             PerformOpReq::DeviceDeleteKey(req) => match self.delete_key(&req.key_blob) {
744                 Ok(_ret) => op_ok_rsp(PerformOpRsp::DeviceDeleteKey(DeleteKeyResponse {})),
745                 Err(e) => op_error_rsp(DeleteKeyRequest::CODE, e),
746             },
747             PerformOpReq::DeviceDeleteAllKeys(_req) => match self.delete_all_keys() {
748                 Ok(_ret) => op_ok_rsp(PerformOpRsp::DeviceDeleteAllKeys(DeleteAllKeysResponse {})),
749                 Err(e) => op_error_rsp(DeleteAllKeysRequest::CODE, e),
750             },
751             PerformOpReq::DeviceDestroyAttestationIds(_req) => match self.destroy_attestation_ids()
752             {
753                 Ok(_ret) => op_ok_rsp(PerformOpRsp::DeviceDestroyAttestationIds(
754                     DestroyAttestationIdsResponse {},
755                 )),
756                 Err(e) => op_error_rsp(DestroyAttestationIdsRequest::CODE, e),
757             },
758             PerformOpReq::DeviceBegin(req) => {
759                 match self.begin_operation(req.purpose, &req.key_blob, req.params, req.auth_token) {
760                     Ok(ret) => op_ok_rsp(PerformOpRsp::DeviceBegin(BeginResponse { ret })),
761                     Err(e) => op_error_rsp(BeginRequest::CODE, e),
762                 }
763             }
764             PerformOpReq::DeviceDeviceLocked(req) => {
765                 match self.device_locked(req.password_only, req.timestamp_token) {
766                     Ok(_ret) => {
767                         op_ok_rsp(PerformOpRsp::DeviceDeviceLocked(DeviceLockedResponse {}))
768                     }
769                     Err(e) => op_error_rsp(DeviceLockedRequest::CODE, e),
770                 }
771             }
772             PerformOpReq::DeviceEarlyBootEnded(_req) => match self.early_boot_ended() {
773                 Ok(_ret) => {
774                     op_ok_rsp(PerformOpRsp::DeviceEarlyBootEnded(EarlyBootEndedResponse {}))
775                 }
776                 Err(e) => op_error_rsp(EarlyBootEndedRequest::CODE, e),
777             },
778             PerformOpReq::DeviceConvertStorageKeyToEphemeral(req) => {
779                 match self.convert_storage_key_to_ephemeral(&req.storage_key_blob) {
780                     Ok(ret) => op_ok_rsp(PerformOpRsp::DeviceConvertStorageKeyToEphemeral(
781                         ConvertStorageKeyToEphemeralResponse { ret },
782                     )),
783                     Err(e) => op_error_rsp(ConvertStorageKeyToEphemeralRequest::CODE, e),
784                 }
785             }
786             PerformOpReq::DeviceGetKeyCharacteristics(req) => {
787                 match self.get_key_characteristics(&req.key_blob, req.app_id, req.app_data) {
788                     Ok(ret) => op_ok_rsp(PerformOpRsp::DeviceGetKeyCharacteristics(
789                         GetKeyCharacteristicsResponse { ret },
790                     )),
791                     Err(e) => op_error_rsp(GetKeyCharacteristicsRequest::CODE, e),
792                 }
793             }
794             PerformOpReq::GetRootOfTrustChallenge(_req) => match self.get_root_of_trust_challenge()
795             {
796                 Ok(ret) => op_ok_rsp(PerformOpRsp::GetRootOfTrustChallenge(
797                     GetRootOfTrustChallengeResponse { ret },
798                 )),
799                 Err(e) => op_error_rsp(GetRootOfTrustChallengeRequest::CODE, e),
800             },
801             PerformOpReq::GetRootOfTrust(req) => match self.get_root_of_trust(&req.challenge) {
802                 Ok(ret) => op_ok_rsp(PerformOpRsp::GetRootOfTrust(GetRootOfTrustResponse { ret })),
803                 Err(e) => op_error_rsp(GetRootOfTrustRequest::CODE, e),
804             },
805             PerformOpReq::SendRootOfTrust(req) => {
806                 match self.send_root_of_trust(&req.root_of_trust) {
807                     Ok(_ret) => {
808                         op_ok_rsp(PerformOpRsp::SendRootOfTrust(SendRootOfTrustResponse {}))
809                     }
810                     Err(e) => op_error_rsp(SendRootOfTrustRequest::CODE, e),
811                 }
812             }
813 
814             // IKeyMintOperation messages.
815             PerformOpReq::OperationUpdateAad(req) => match self.op_update_aad(
816                 OpHandle(req.op_handle),
817                 &req.input,
818                 req.auth_token,
819                 req.timestamp_token,
820             ) {
821                 Ok(_ret) => op_ok_rsp(PerformOpRsp::OperationUpdateAad(UpdateAadResponse {})),
822                 Err(e) => op_error_rsp(UpdateAadRequest::CODE, e),
823             },
824             PerformOpReq::OperationUpdate(req) => {
825                 match self.op_update(
826                     OpHandle(req.op_handle),
827                     &req.input,
828                     req.auth_token,
829                     req.timestamp_token,
830                 ) {
831                     Ok(ret) => op_ok_rsp(PerformOpRsp::OperationUpdate(UpdateResponse { ret })),
832                     Err(e) => op_error_rsp(UpdateRequest::CODE, e),
833                 }
834             }
835             PerformOpReq::OperationFinish(req) => {
836                 match self.op_finish(
837                     OpHandle(req.op_handle),
838                     req.input.as_deref(),
839                     req.signature.as_deref(),
840                     req.auth_token,
841                     req.timestamp_token,
842                     req.confirmation_token.as_deref(),
843                 ) {
844                     Ok(ret) => op_ok_rsp(PerformOpRsp::OperationFinish(FinishResponse { ret })),
845                     Err(e) => op_error_rsp(FinishRequest::CODE, e),
846                 }
847             }
848             PerformOpReq::OperationAbort(req) => match self.op_abort(OpHandle(req.op_handle)) {
849                 Ok(_ret) => op_ok_rsp(PerformOpRsp::OperationAbort(AbortResponse {})),
850                 Err(e) => op_error_rsp(AbortRequest::CODE, e),
851             },
852 
853             // IRemotelyProvisionedComponentOperation messages.
854             PerformOpReq::RpcGetHardwareInfo(_req) => match self.get_rpc_hardware_info() {
855                 Ok(ret) => {
856                     op_ok_rsp(PerformOpRsp::RpcGetHardwareInfo(GetRpcHardwareInfoResponse { ret }))
857                 }
858                 Err(e) => op_error_rsp(GetRpcHardwareInfoRequest::CODE, e),
859             },
860             PerformOpReq::RpcGenerateEcdsaP256KeyPair(req) => {
861                 match self.generate_ecdsa_p256_keypair(rpc::TestMode(req.test_mode)) {
862                     Ok((pubkey, ret)) => op_ok_rsp(PerformOpRsp::RpcGenerateEcdsaP256KeyPair(
863                         GenerateEcdsaP256KeyPairResponse { maced_public_key: pubkey, ret },
864                     )),
865                     Err(e) => op_error_rsp(GenerateEcdsaP256KeyPairRequest::CODE, e),
866                 }
867             }
868             PerformOpReq::RpcGenerateCertificateRequest(req) => {
869                 match self.generate_cert_req(
870                     rpc::TestMode(req.test_mode),
871                     req.keys_to_sign,
872                     &req.endpoint_encryption_cert_chain,
873                     &req.challenge,
874                 ) {
875                     Ok((device_info, protected_data, ret)) => {
876                         op_ok_rsp(PerformOpRsp::RpcGenerateCertificateRequest(
877                             GenerateCertificateRequestResponse { device_info, protected_data, ret },
878                         ))
879                     }
880                     Err(e) => op_error_rsp(GenerateCertificateRequestRequest::CODE, e),
881                 }
882             }
883             PerformOpReq::RpcGenerateCertificateV2Request(req) => {
884                 match self.generate_cert_req_v2(req.keys_to_sign, &req.challenge) {
885                     Ok(ret) => op_ok_rsp(PerformOpRsp::RpcGenerateCertificateV2Request(
886                         GenerateCertificateRequestV2Response { ret },
887                     )),
888                     Err(e) => op_error_rsp(GenerateCertificateRequestV2Request::CODE, e),
889                 }
890             }
891         }
892     }
893 
add_rng_entropy(&mut self, data: &[u8]) -> Result<(), Error>894     fn add_rng_entropy(&mut self, data: &[u8]) -> Result<(), Error> {
895         if data.len() > 2048 {
896             return Err(km_err!(InvalidInputLength, "entropy size {} too large", data.len()));
897         };
898 
899         info!("add {} bytes of entropy", data.len());
900         self.imp.rng.add_entropy(data);
901         Ok(())
902     }
903 
early_boot_ended(&mut self) -> Result<(), Error>904     fn early_boot_ended(&mut self) -> Result<(), Error> {
905         info!("early boot ended");
906         self.in_early_boot = false;
907         Ok(())
908     }
909 
device_locked( &mut self, password_only: bool, timestamp_token: Option<TimeStampToken>, ) -> Result<(), Error>910     fn device_locked(
911         &mut self,
912         password_only: bool,
913         timestamp_token: Option<TimeStampToken>,
914     ) -> Result<(), Error> {
915         info!(
916             "device locked, password-required={}, timestamp={:?}",
917             password_only, timestamp_token
918         );
919 
920         let now = if let Some(clock) = &self.imp.clock {
921             clock.now().into()
922         } else if let Some(token) = timestamp_token {
923             // Note that any `challenge` value in the `TimeStampToken` cannot be checked, because
924             // there is nothing to check it against.
925             let mac_input = clock::timestamp_token_mac_input(&token)?;
926             if !self.verify_device_hmac(&mac_input, &token.mac)? {
927                 return Err(km_err!(InvalidArgument, "timestamp MAC not verified"));
928             }
929             token.timestamp
930         } else {
931             return Err(km_err!(InvalidArgument, "no clock and no external timestamp provided!"));
932         };
933 
934         *self.device_locked.borrow_mut() = if password_only {
935             LockState::PasswordLockedSince(now)
936         } else {
937             LockState::LockedSince(now)
938         };
939         Ok(())
940     }
941 
get_hardware_info(&self) -> Result<KeyMintHardwareInfo, Error>942     fn get_hardware_info(&self) -> Result<KeyMintHardwareInfo, Error> {
943         Ok(KeyMintHardwareInfo {
944             version_number: self.hw_info.version_number,
945             security_level: self.hw_info.security_level,
946             key_mint_name: self.hw_info.impl_name.to_string(),
947             key_mint_author_name: self.hw_info.author_name.to_string(),
948             timestamp_token_required: self.imp.clock.is_none(),
949         })
950     }
951 
delete_key(&mut self, keyblob: &[u8]) -> Result<(), Error>952     fn delete_key(&mut self, keyblob: &[u8]) -> Result<(), Error> {
953         // Parse the keyblob. It cannot be decrypted, because hidden parameters are not available
954         // (there is no `params` for them to arrive in).
955         if let Ok(keyblob::EncryptedKeyBlob::V1(encrypted_keyblob)) =
956             keyblob::EncryptedKeyBlob::new(keyblob)
957         {
958             // We have to trust that any secure deletion slot in the keyblob is valid, because the
959             // key can't be decrypted.
960             if let (Some(sdd_mgr), Some(slot)) =
961                 (&mut self.dev.sdd_mgr, encrypted_keyblob.secure_deletion_slot)
962             {
963                 if let Err(e) = sdd_mgr.delete_secret(slot) {
964                     error!("failed to delete secure deletion slot: {:?}", e);
965                 }
966             }
967         } else {
968             // We might have failed to parse the keyblob because it is in some prior format.
969             if let Some(old_key) = self.dev.legacy_key.as_mut() {
970                 if let Err(e) = old_key.delete_legacy_key(keyblob) {
971                     error!("failed to parse keyblob as legacy : {:?}, ignoring", e);
972                 }
973             } else {
974                 error!("failed to parse keyblob, ignoring");
975             }
976         }
977 
978         Ok(())
979     }
980 
delete_all_keys(&mut self) -> Result<(), Error>981     fn delete_all_keys(&mut self) -> Result<(), Error> {
982         if let Some(sdd_mgr) = &mut self.dev.sdd_mgr {
983             error!("secure deleting all keys! device unlikely to survive reboot!");
984             sdd_mgr.delete_all();
985         }
986         Ok(())
987     }
988 
destroy_attestation_ids(&mut self) -> Result<(), Error>989     fn destroy_attestation_ids(&mut self) -> Result<(), Error> {
990         match self.dev.attest_ids.as_mut() {
991             Some(attest_ids) => {
992                 error!("destroying all device attestation IDs!");
993                 attest_ids.destroy_all()
994             }
995             None => {
996                 error!("destroying device attestation IDs requested but not supported");
997                 Err(km_err!(Unimplemented, "no attestation ID functionality available"))
998             }
999         }
1000     }
1001 
get_root_of_trust_challenge(&mut self) -> Result<[u8; 16], Error>1002     fn get_root_of_trust_challenge(&mut self) -> Result<[u8; 16], Error> {
1003         if !self.is_strongbox() {
1004             return Err(km_err!(Unimplemented, "root-of-trust challenge only for StrongBox"));
1005         }
1006         self.imp.rng.fill_bytes(&mut self.rot_challenge[..]);
1007         Ok(self.rot_challenge)
1008     }
1009 
get_root_of_trust(&mut self, challenge: &[u8]) -> Result<Vec<u8>, Error>1010     fn get_root_of_trust(&mut self, challenge: &[u8]) -> Result<Vec<u8>, Error> {
1011         if self.is_strongbox() {
1012             return Err(km_err!(Unimplemented, "root-of-trust retrieval not for StrongBox"));
1013         }
1014         let payload = self
1015             .boot_info()?
1016             .clone()
1017             .to_tagged_vec()
1018             .map_err(|_e| km_err!(UnknownError, "Failed to CBOR-encode RootOfTrust"))?;
1019 
1020         let mac0 = coset::CoseMac0Builder::new()
1021             .protected(
1022                 coset::HeaderBuilder::new().algorithm(coset::iana::Algorithm::HMAC_256_256).build(),
1023             )
1024             .payload(payload)
1025             .try_create_tag(challenge, |data| self.device_hmac(data))?
1026             .build();
1027         mac0.to_tagged_vec()
1028             .map_err(|_e| km_err!(UnknownError, "Failed to CBOR-encode RootOfTrust"))
1029     }
1030 
send_root_of_trust(&mut self, root_of_trust: &[u8]) -> Result<(), Error>1031     fn send_root_of_trust(&mut self, root_of_trust: &[u8]) -> Result<(), Error> {
1032         if !self.is_strongbox() {
1033             return Err(km_err!(Unimplemented, "root-of-trust delivery only for StrongBox"));
1034         }
1035         let mac0 = coset::CoseMac0::from_tagged_slice(root_of_trust)
1036             .map_err(|_e| km_err!(InvalidArgument, "Failed to CBOR-decode CoseMac0"))?;
1037         mac0.verify_tag(&self.rot_challenge, |tag, data| {
1038             match self.verify_device_hmac(data, tag) {
1039                 Ok(true) => Ok(()),
1040                 Ok(false) => {
1041                     Err(km_err!(VerificationFailed, "HMAC verification of RootOfTrust failed"))
1042                 }
1043                 Err(e) => Err(e),
1044             }
1045         })?;
1046         let payload =
1047             mac0.payload.ok_or_else(|| km_err!(InvalidArgument, "Missing payload in CoseMac0"))?;
1048         let boot_info = keymint::BootInfo::from_tagged_slice(&payload)
1049             .map_err(|_e| km_err!(InvalidArgument, "Failed to CBOR-decode RootOfTrust"))?;
1050         if self.boot_info.is_none() {
1051             info!("Setting boot_info to TEE-provided {:?}", boot_info);
1052             self.boot_info = Some(boot_info);
1053         } else {
1054             info!("Ignoring TEE-provided RootOfTrust {:?} as already set", boot_info);
1055         }
1056         Ok(())
1057     }
1058 
convert_storage_key_to_ephemeral(&self, keyblob: &[u8]) -> Result<Vec<u8>, Error>1059     fn convert_storage_key_to_ephemeral(&self, keyblob: &[u8]) -> Result<Vec<u8>, Error> {
1060         if let Some(sk_wrapper) = self.dev.sk_wrapper {
1061             // Parse and decrypt the keyblob. Note that there is no way to provide extra hidden
1062             // params on the API.
1063             let (keyblob, _) = self.keyblob_parse_decrypt(keyblob, &[])?;
1064 
1065             // Check that the keyblob is indeed a storage key.
1066             let chars = keyblob.characteristics_at(self.hw_info.security_level)?;
1067             if !get_bool_tag_value!(chars, StorageKey)? {
1068                 return Err(km_err!(InvalidArgument, "attempting to convert non-storage key"));
1069             }
1070 
1071             // Now that we've got the key material, use a device-specific method to re-wrap it
1072             // with an ephemeral key.
1073             sk_wrapper.ephemeral_wrap(&keyblob.key_material)
1074         } else {
1075             Err(km_err!(Unimplemented, "storage key wrapping unavailable"))
1076         }
1077     }
1078 
get_key_characteristics( &self, key_blob: &[u8], app_id: Vec<u8>, app_data: Vec<u8>, ) -> Result<Vec<KeyCharacteristics>, Error>1079     fn get_key_characteristics(
1080         &self,
1081         key_blob: &[u8],
1082         app_id: Vec<u8>,
1083         app_data: Vec<u8>,
1084     ) -> Result<Vec<KeyCharacteristics>, Error> {
1085         // Parse and decrypt the keyblob, which requires extra hidden params.
1086         let mut params = vec_try_with_capacity!(2)?;
1087         if !app_id.is_empty() {
1088             params.push(KeyParam::ApplicationId(app_id)); // capacity enough
1089         }
1090         if !app_data.is_empty() {
1091             params.push(KeyParam::ApplicationData(app_data)); // capacity enough
1092         }
1093         let (keyblob, _) = self.keyblob_parse_decrypt(key_blob, &params)?;
1094         Ok(keyblob.characteristics)
1095     }
1096 
1097     /// Generate an HMAC-SHA256 value over the data using the device's HMAC key (if available).
device_hmac(&self, data: &[u8]) -> Result<Vec<u8>, Error>1098     fn device_hmac(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
1099         match &self.device_hmac {
1100             Some(traitobj) => traitobj.hmac(self.imp.hmac, data),
1101             None => {
1102                 error!("HMAC requested but no key available!");
1103                 Err(km_err!(HardwareNotYetAvailable, "HMAC key not agreed"))
1104             }
1105         }
1106     }
1107 
1108     /// Verify an HMAC-SHA256 value over the data using the device's HMAC key (if available).
verify_device_hmac(&self, data: &[u8], mac: &[u8]) -> Result<bool, Error>1109     fn verify_device_hmac(&self, data: &[u8], mac: &[u8]) -> Result<bool, Error> {
1110         let remac = self.device_hmac(data)?;
1111         Ok(self.imp.compare.eq(mac, &remac))
1112     }
1113 
1114     /// Return the root of trust that is bound into keyblobs.
root_of_trust(&self) -> Result<&[u8], Error>1115     fn root_of_trust(&self) -> Result<&[u8], Error> {
1116         match &self.rot_data {
1117             Some(data) => Ok(data),
1118             None => Err(km_err!(HardwareNotYetAvailable, "No root-of-trust info available")),
1119         }
1120     }
1121 
1122     /// Return the root key used for key encryption.
root_kek(&self, context: &[u8]) -> Result<OpaqueOr<hmac::Key>, Error>1123     fn root_kek(&self, context: &[u8]) -> Result<OpaqueOr<hmac::Key>, Error> {
1124         self.dev.keys.root_kek(context)
1125     }
1126 
1127     /// Add KeyMint-generated tags to the provided [`KeyCharacteristics`].
add_keymint_tags( &self, chars: &mut Vec<KeyCharacteristics>, origin: KeyOrigin, ) -> Result<(), Error>1128     fn add_keymint_tags(
1129         &self,
1130         chars: &mut Vec<KeyCharacteristics>,
1131         origin: KeyOrigin,
1132     ) -> Result<(), Error> {
1133         for kc in chars {
1134             if kc.security_level == self.hw_info.security_level {
1135                 kc.authorizations.try_push(KeyParam::Origin(origin))?;
1136                 if let Some(hal_info) = &self.hal_info {
1137                     kc.authorizations.try_extend_from_slice(&[
1138                         KeyParam::OsVersion(hal_info.os_version),
1139                         KeyParam::OsPatchlevel(hal_info.os_patchlevel),
1140                         KeyParam::VendorPatchlevel(hal_info.vendor_patchlevel),
1141                     ])?;
1142                 }
1143                 if let Some(boot_info) = &self.boot_info {
1144                     kc.authorizations
1145                         .try_push(KeyParam::BootPatchlevel(boot_info.boot_patchlevel))?;
1146                 }
1147                 return Ok(());
1148             }
1149         }
1150         Err(km_err!(
1151             UnknownError,
1152             "no characteristics at our security level {:?}",
1153             self.hw_info.security_level
1154         ))
1155     }
1156 }
1157 
1158 /// Create an OK response structure with the given inner response message.
op_ok_rsp(rsp: PerformOpRsp) -> PerformOpResponse1159 fn op_ok_rsp(rsp: PerformOpRsp) -> PerformOpResponse {
1160     // Zero is OK in any context.
1161     PerformOpResponse { error_code: 0, rsp: Some(rsp) }
1162 }
1163 
1164 /// Create a response structure with the given error code.
error_rsp(error_code: i32) -> PerformOpResponse1165 fn error_rsp(error_code: i32) -> PerformOpResponse {
1166     PerformOpResponse { error_code, rsp: None }
1167 }
1168 
1169 /// Create a response structure with the given error.
op_error_rsp(op: KeyMintOperation, err: Error) -> PerformOpResponse1170 fn op_error_rsp(op: KeyMintOperation, err: Error) -> PerformOpResponse {
1171     warn!("failing {:?} request with error {:?}", op, err);
1172     if kmr_wire::is_rpc_operation(op) {
1173         // The IRemotelyProvisionedComponent HAL uses a different error space than the
1174         // other HALs.
1175         let rpc_err: rpc::ErrorCode = match err {
1176             Error::Cbor(_) | Error::Der(_) | Error::Alloc(_) => rpc::ErrorCode::Failed,
1177             Error::Hal(_, _) => {
1178                 error!("encountered non-RKP error on RKP method! {:?}", err);
1179                 rpc::ErrorCode::Failed
1180             }
1181             Error::Rpc(e, _) => e,
1182         };
1183         error_rsp(rpc_err as i32)
1184     } else {
1185         let hal_err = match err {
1186             Error::Cbor(_) | Error::Der(_) => ErrorCode::InvalidArgument,
1187             Error::Hal(e, _) => e,
1188             Error::Rpc(_, _) => {
1189                 error!("encountered RKP error on non-RKP method! {:?}", err);
1190                 ErrorCode::UnknownError
1191             }
1192             Error::Alloc(_) => ErrorCode::MemoryAllocationFailed,
1193         };
1194         error_rsp(hal_err as i32)
1195     }
1196 }
1197 
1198 /// Hand-encoded [`PerformOpResponse`] data for [`ErrorCode::UNKNOWN_ERROR`].
1199 /// Does not perform CBOR serialization (and so is suitable for error reporting if/when
1200 /// CBOR serialization fails).
invalid_cbor_rsp_data() -> [u8; 5]1201 fn invalid_cbor_rsp_data() -> [u8; 5] {
1202     [
1203         0x82, // 2-arr
1204         0x39, // nint, len 2
1205         0x03, // 0x3e7(999)
1206         0xe7, // = -1000
1207         0x80, // 0-arr
1208     ]
1209 }
1210 
1211 /// Build the HMAC input for a [`HardwareAuthToken`]
hardware_auth_token_mac_input(token: &HardwareAuthToken) -> Result<Vec<u8>, Error>1212 pub fn hardware_auth_token_mac_input(token: &HardwareAuthToken) -> Result<Vec<u8>, Error> {
1213     let mut result = vec_try_with_capacity!(
1214         size_of::<u8>() + // version=0 (BE)
1215         size_of::<i64>() + // challenge (Host)
1216         size_of::<i64>() + // user_id (Host)
1217         size_of::<i64>() + // authenticator_id (Host)
1218         size_of::<i32>() + // authenticator_type (BE)
1219         size_of::<i64>() // timestamp (BE)
1220     )?;
1221     result.extend_from_slice(&0u8.to_be_bytes()[..]);
1222     result.extend_from_slice(&token.challenge.to_ne_bytes()[..]);
1223     result.extend_from_slice(&token.user_id.to_ne_bytes()[..]);
1224     result.extend_from_slice(&token.authenticator_id.to_ne_bytes()[..]);
1225     result.extend_from_slice(&(token.authenticator_type as i32).to_be_bytes()[..]);
1226     result.extend_from_slice(&token.timestamp.milliseconds.to_be_bytes()[..]);
1227     Ok(result)
1228 }
1229