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