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