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