Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dev_tests/src/ratchet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn ratchet_globals() -> Result<()> {
("litebox/", 9),
("litebox_platform_linux_kernel/", 6),
("litebox_platform_linux_userland/", 5),
("litebox_platform_lvbs/", 23),
("litebox_platform_lvbs/", 24),
("litebox_platform_multiplex/", 1),
("litebox_platform_windows_userland/", 8),
("litebox_runner_linux_userland/", 1),
Expand Down
39 changes: 39 additions & 0 deletions litebox_common_optee/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,11 @@ pub enum TeeParamType {
impl UteeParams {
pub const TEE_NUM_PARAMS: usize = TEE_NUM_PARAMS;

/// Return `true` if every parameter matches the expected type.
pub fn has_types(&self, expected: [TeeParamType; Self::TEE_NUM_PARAMS]) -> bool {
(0..Self::TEE_NUM_PARAMS).all(|i| self.get_type(i).is_ok_and(|t| t == expected[i]))
}

pub fn get_type(&self, index: usize) -> Result<TeeParamType, Errno> {
let type_byte = match index {
0 => self.types.type_0(),
Expand Down Expand Up @@ -619,6 +624,16 @@ impl TeeUuid {
bytes[8..16].copy_from_slice(&data[1].to_le_bytes());
Self::from_bytes(bytes)
}

/// Converts the UUID to a 16-byte array with little-endian encoding.
pub fn to_le_bytes(self) -> [u8; 16] {
let mut bytes = [0u8; 16];
bytes[0..4].copy_from_slice(&self.time_low.to_le_bytes());
bytes[4..6].copy_from_slice(&self.time_mid.to_le_bytes());
bytes[6..8].copy_from_slice(&self.time_hi_and_version.to_le_bytes());
bytes[8..16].copy_from_slice(&self.clock_seq_and_node);
bytes
}
}

/// TA flags from `optee_os/lib/libutee/include/user_ta_header.h`.
Expand Down Expand Up @@ -2306,6 +2321,30 @@ pub fn parse_ta_head(elf_data: &[u8]) -> Option<TaHead> {
None
}

/// Hardware Unique Key (HUK) subkey usage identifiers based on OP-TEE's `enum huk_subkey_usage`.
#[derive(Clone, Copy)]
#[repr(u32)]
pub enum HukSubkeyUsage {
/// RPMB key
Rpmb = 0,
/// Secure Storage Key
Ssk = 1,
/// Die ID
DieId = 2,
/// TA unique key
UniqueTa = 3,
/// TA encryption key
TaEnc = 4,
/// SCP03 set of encryption keys
Se050 = 5,
}

/// HUK length in bytes.
pub const HUK_LEN: usize = 32;

/// Maximum length of an HUK subkey in bytes.
pub const HUK_SUBKEY_MAX_LEN: usize = 32;

#[cfg(test)]
mod tests {
use super::*;
Expand Down
40 changes: 40 additions & 0 deletions litebox_platform_lvbs/src/host/lvbs_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,46 @@ impl litebox::platform::CrngProvider for LvbsLinuxKernel {
}
}

/// Length of the Platform Root Key in bytes.
pub const PRK_LEN: usize = 32;

static PRK_ONCE: spin::Once<[u8; PRK_LEN]> = spin::Once::new();

/// Sets the Platform Root Key (PRK) for this platform.
///
/// This should be called once during platform initialization with a key derived
/// from hardware or a boot nonce.
///
/// # Panics
/// Panics if `key` length does not match `PRK_LEN`.
pub fn set_platform_root_key(key: &[u8]) {
assert_eq!(key.len(), PRK_LEN, "Platform Root Key length mismatch");
PRK_ONCE.call_once(|| {
let mut prk = [0u8; PRK_LEN];
prk.copy_from_slice(key);
prk
});
}

impl litebox::platform::DerivedKeyProvider for LvbsLinuxKernel {
fn derive_key<E>(
&self,
shim_kdf: Option<fn(&[u8], litebox::platform::KDFParams) -> Result<(), E>>,
params: litebox::platform::KDFParams,
) -> Result<(), litebox::platform::DerivedKeyError<E>> {
let Some(prk) = PRK_ONCE.get() else {
return Err(litebox::platform::DerivedKeyError::UnsupportedRebootPersistentKey);
};
match shim_kdf {
None => {
// LVBS platform doesn't have its own KDF implementation.
Err(litebox::platform::DerivedKeyError::ShimKDFRequired)
}
Some(shim_kdf) => Ok(shim_kdf(prk, params)?),
}
}
}

pub struct HostLvbsInterface;

impl HostLvbsInterface {}
Expand Down
1 change: 1 addition & 0 deletions litebox_platform_lvbs/src/host/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod lvbs_impl;
pub mod per_cpu_variables;

pub use lvbs_impl::LvbsLinuxKernel;
pub use lvbs_impl::{PRK_LEN, set_platform_root_key};

#[cfg(test)]
pub mod mock;
Expand Down
8 changes: 6 additions & 2 deletions litebox_platform_lvbs/src/mshv/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ pub enum VsmError {
OperationNotSupported(&'static str),

// VTL0 Memory Copy Errors
#[error("failed to copy data to VTL0")]
#[error("failed to copy data from/to VTL0")]
Vtl0CopyFailed,

// Hypercall Errors
Expand Down Expand Up @@ -152,6 +152,9 @@ pub enum VsmError {

#[error("symbol name contains invalid UTF-8")]
SymbolNameInvalidUtf8,

#[error("root key is invalid")]
PlatformRootKeyInvalid,
}

impl From<VerificationError> for VsmError {
Expand Down Expand Up @@ -217,7 +220,8 @@ impl From<VsmError> for Errno {
| VsmError::SymbolNameInvalidUtf8
| VsmError::SymbolNameNoTerminator
| VsmError::CertificateDerLengthInvalid { .. }
| VsmError::CertificateParseFailed => Errno::EINVAL,
| VsmError::CertificateParseFailed
| VsmError::PlatformRootKeyInvalid => Errno::EINVAL,

// Signature verification failures delegate to VerificationError's Errno mapping
VsmError::SignatureVerificationFailed(e) => Errno::from(e),
Expand Down
4 changes: 4 additions & 0 deletions litebox_platform_lvbs/src/mshv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ pub const VSM_VTL_CALL_FUNC_ID_KEXEC_VALIDATE: u32 = 0x1_ffea;
pub const VSM_VTL_CALL_FUNC_ID_PATCH_TEXT: u32 = 0x1_ffeb;
pub const VSM_VTL_CALL_FUNC_ID_ALLOCATE_RINGBUFFER_MEMORY: u32 = 0x1_ffec;

// This VSM function ID for setting the platform root key is subject to change
pub const VSM_VTL_CALL_FUNC_ID_SET_PLATFORM_ROOT_KEY: u32 = 0x1_ffed;

// This VSM function ID for OP-TEE messages is subject to change
pub const VSM_VTL_CALL_FUNC_ID_OPTEE_MESSAGE: u32 = 0x1_fff0;

Expand All @@ -152,6 +155,7 @@ pub enum VsmFunction {
PatchText = VSM_VTL_CALL_FUNC_ID_PATCH_TEXT,
OpteeMessage = VSM_VTL_CALL_FUNC_ID_OPTEE_MESSAGE,
AllocateRingbufferMemory = VSM_VTL_CALL_FUNC_ID_ALLOCATE_RINGBUFFER_MEMORY,
SetPlatformRootKey = VSM_VTL_CALL_FUNC_ID_SET_PLATFORM_ROOT_KEY,
}

pub const MSR_EFER: u32 = 0xc000_0080;
Expand Down
31 changes: 31 additions & 0 deletions litebox_platform_lvbs/src/mshv/vsm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ use crate::mshv::ringbuffer::set_ringbuffer;
use crate::{
debug_serial_println,
host::{
PRK_LEN,
bootparam::get_vtl1_memory_info,
linux::{CpuMask, KEXEC_SEGMENT_MAX, Kimage},
per_cpu_variables::with_per_cpu_variables,
set_platform_root_key,
},
mshv::{
HV_REGISTER_CR_INTERCEPT_CONTROL, HV_REGISTER_CR_INTERCEPT_CR0_MASK,
Expand Down Expand Up @@ -916,6 +918,34 @@ fn mshv_vsm_allocate_ringbuffer_memory(phys_addr: u64, size: usize) -> Result<i6
Ok(0)
}

/// This function sets the platform root key by copying key data from VTL0.
///
/// - `key_pa`: The physical address (VTL0) of the platform root key.
/// - `key_size`: The size of the platform root key.
///
/// This function assumes that the caller stores the key data in a single or
/// contiguous physical memory page(s). If the caller cannot ensure this,
/// we should make this function use `HekiPage`.
fn mshv_vsm_set_platform_root_key(key_pa: u64, key_size: u64) -> Result<i64, VsmError> {
if crate::platform_low().vtl0_kernel_info.check_end_of_boot() {
return Err(VsmError::OperationAfterEndOfBoot("set platform root key"));
}

let key_pa = PhysAddr::try_new(key_pa).map_err(|_| VsmError::InvalidPhysicalAddress)?;
let key_size: usize = key_size.truncate();
if key_size != PRK_LEN {
return Err(VsmError::PlatformRootKeyInvalid);
}

let mut keybuf = [0u8; PRK_LEN];
if unsafe { crate::platform_low().copy_slice_from_vtl0_phys(key_pa, &mut keybuf) } {
set_platform_root_key(&keybuf);
Ok(0)
} else {
Err(VsmError::Vtl0CopyFailed)
}
}

/// VSM function dispatcher
pub fn vsm_dispatch(func_id: VsmFunction, params: &[u64]) -> i64 {
let result: Result<i64, VsmError> = match func_id {
Expand All @@ -939,6 +969,7 @@ pub fn vsm_dispatch(func_id: VsmFunction, params: &[u64]) -> i64 {
let size: usize = params[1].truncate();
mshv_vsm_allocate_ringbuffer_memory(params[0], size)
}
VsmFunction::SetPlatformRootKey => mshv_vsm_set_platform_root_key(params[0], params[1]),
VsmFunction::OpteeMessage => Err(VsmError::OperationNotSupported("OP-TEE communication")),
};
match result {
Expand Down
2 changes: 2 additions & 0 deletions litebox_runner_optee_on_linux_userland/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ pub fn run(cli_args: CliArgs) -> Result<()> {
InterceptionBackend::Rewriter => {}
}

platform.initialize_boot_specific_kdf_support();

if cli_args.command_sequence.is_empty() {
run_ta_with_default_commands(&shim, ldelf_data.as_slice(), prog_data.as_slice());
} else {
Expand Down
4 changes: 4 additions & 0 deletions litebox_shim_optee/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ once_cell = { version = "1.20.2", default-features = false, features = ["alloc",
spin = { version = "0.10.0", default-features = false, features = ["spin_mutex", "once"] }
thiserror = { version = "2.0.6", default-features = false }
zerocopy = { version = "0.8", default-features = false, features = ["derive"] }
hmac = { version = "0.12", default-features = false }
sha2 = { version = "0.10", default-features = false }
zeroize = { version = "1.8", default-features = false, features = ["alloc"] }

[features]
default = ["platform_lvbs"]
Expand All @@ -28,4 +31,5 @@ platform_lvbs = ["litebox_platform_multiplex/platform_lvbs_with_optee_syscall"]
workspace = true

[dev-dependencies]
litebox_platform_linux_userland = { path = "../litebox_platform_linux_userland/", version = "0.1.0", features = ["optee_syscall"] }
litebox_platform_multiplex = { path = "../litebox_platform_multiplex/", version = "0.1.0", default-features = false, features = ["platform_linux_userland_with_optee_syscall"] }
Loading