repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/src/flow/cold_reset/fw_processor/report_hek_metadata.rs | rom/dev/src/flow/cold_reset/fw_processor/report_hek_metadata.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
report_hek_metadata.rs
Abstract:
File contains OCP_LOCK_REPORT_HEK_METADATA mailbox command.
--*/
use caliptra_api::mailbox::OcpLockReportHekMetadataReq;
use caliptra_drivers::{CaliptraError, CaliptraResult, PersistentData, SocIfc};
use zerocopy::{FromBytes, IntoBytes};
use crate::flow::cold_reset::ocp_lock;
pub struct OcpLockReportHekMetadataCmd;
impl OcpLockReportHekMetadataCmd {
#[inline(always)]
pub(crate) fn execute(
cmd_bytes: &[u8],
soc_ifc: &mut SocIfc,
persistent_data: &mut PersistentData,
resp: &mut [u8],
) -> CaliptraResult<usize> {
let request = OcpLockReportHekMetadataReq::ref_from_bytes(cmd_bytes)
.map_err(|_| CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
if !soc_ifc.ocp_lock_enabled() {
Err(CaliptraError::FW_PROC_OCP_LOCK_UNSUPPORTED)?;
}
// Use the response buffer directly as OcpLockReportHekMetadataResp.
// The buffer is zeroized at the start of the loop
let resp_buffer_size =
core::mem::size_of::<caliptra_api::mailbox::OcpLockReportHekMetadataResp>();
let resp = resp
.get_mut(..resp_buffer_size)
.ok_or(CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
let hek_resp = caliptra_api::mailbox::OcpLockReportHekMetadataResp::mut_from_bytes(resp)
.map_err(|_| CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
let hek_resp_data = ocp_lock::handle_report_hek_metadata(
soc_ifc.lifecycle(),
persistent_data,
request,
&soc_ifc.fuse_bank().ocp_hek_seed(),
)?;
// Copy the data from the response
hek_resp.flags = hek_resp_data.flags;
hek_resp.hdr = hek_resp_data.hdr;
let resp_bytes = hek_resp.as_bytes();
Ok(resp_bytes.len())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/src/flow/cold_reset/fw_processor/get_ldev_cert.rs | rom/dev/src/flow/cold_reset/fw_processor/get_ldev_cert.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
get_ldev_cert.rs
Abstract:
File contains GET_LDEV_ECC384_CERT and GET_LDEV_MLDSA87_CERT mailbox commands.
--*/
use caliptra_api::mailbox::{AlgorithmType, GetLdevCertResp};
use caliptra_common::dice::GetLdevCertCmd as CommonGetLdevCertCmd;
use caliptra_common::mailbox_api::{MailboxReqHeader, ResponseVarSize};
use caliptra_drivers::{CaliptraError, CaliptraResult, PersistentData};
use zerocopy::{FromBytes, IntoBytes};
pub struct GetLdevCertCmd;
impl GetLdevCertCmd {
#[inline(always)]
pub(crate) fn execute(
cmd_bytes: &[u8],
persistent_data: &mut PersistentData,
algorithm_type: AlgorithmType,
resp: &mut [u8],
) -> CaliptraResult<usize> {
MailboxReqHeader::ref_from_bytes(cmd_bytes)
.map_err(|_| CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
// Use the response buffer directly as GetLdevCertResp.
// The buffer is zeroized at the start of the loop
let resp_buffer_size = core::mem::size_of::<GetLdevCertResp>();
let resp = resp
.get_mut(..resp_buffer_size)
.ok_or(CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
let ldev_resp = GetLdevCertResp::mut_from_bytes(resp)
.map_err(|_| CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
CommonGetLdevCertCmd::execute(persistent_data, algorithm_type, ldev_resp.as_mut_bytes())?;
let resp_bytes = ldev_resp.as_bytes_partial()?;
Ok(resp_bytes.len())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/src/flow/cold_reset/fw_processor/install_owner_pk_hash.rs | rom/dev/src/flow/cold_reset/fw_processor/install_owner_pk_hash.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
install_owner_pk_hash.rs
Abstract:
File contains INSTALL_OWNER_PK_HASH mailbox command.
--*/
use caliptra_api::mailbox::{InstallOwnerPkHashReq, InstallOwnerPkHashResp};
use caliptra_drivers::{CaliptraError, CaliptraResult, PersistentData};
use zerocopy::FromBytes;
pub struct InstallOwnerPkHashCmd;
impl InstallOwnerPkHashCmd {
#[inline(always)]
pub(crate) fn execute(
cmd_bytes: &[u8],
persistent_data: &mut PersistentData,
_resp: &mut [u8],
) -> CaliptraResult<usize> {
let request = InstallOwnerPkHashReq::ref_from_bytes(cmd_bytes)
.map_err(|_| CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
// Save the owner public key hash in persistent data.
persistent_data
.rom
.dot_owner_pk_hash
.owner_pk_hash
.copy_from_slice(&request.digest);
persistent_data.rom.dot_owner_pk_hash.valid = true;
// Zero value of response buffer is good
Ok(core::mem::size_of::<InstallOwnerPkHashResp>())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/src/flow/cold_reset/fw_processor/cm_random_generate.rs | rom/dev/src/flow/cold_reset/fw_processor/cm_random_generate.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
cm_random_generate.rs
Abstract:
File contains CM_RANDOM_GENERATE mailbox command.
--*/
use caliptra_api::mailbox::{CmRandomGenerateReq, CmRandomGenerateResp};
use caliptra_common::mailbox_api::ResponseVarSize;
use caliptra_drivers::CaliptraResult;
use caliptra_drivers::Trng;
use zerocopy::FromBytes;
pub struct CmRandomGenerateCmd;
impl CmRandomGenerateCmd {
#[inline(always)]
pub(crate) fn execute(
cmd_bytes: &[u8],
trng: &mut Trng,
resp: &mut [u8],
) -> CaliptraResult<usize> {
let request = CmRandomGenerateReq::ref_from_bytes(cmd_bytes)
.map_err(|_| caliptra_drivers::CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
let size = request.size as usize;
// Use the response buffer directly as CmRandomGenerateResp.
// The buffer is zeroized at the start of the loop
let resp_buffer_size = core::mem::size_of::<CmRandomGenerateResp>();
let resp = resp
.get_mut(..resp_buffer_size)
.ok_or(caliptra_drivers::CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
let rand_resp = CmRandomGenerateResp::mut_from_bytes(resp)
.map_err(|_| caliptra_drivers::CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
if size > rand_resp.data.len() {
// Return 0 to indicate failure
return Ok(0);
}
for i in (0..size).step_by(48) {
let rand: [u8; 48] = trng.generate()?.into();
let len = rand.len().min(rand_resp.data.len() - i);
// check to prevent panic even though this is impossible
if i > rand_resp.data.len() {
break;
}
rand_resp.data[i..i + len].copy_from_slice(&rand[..len]);
}
rand_resp.hdr.data_len = size as u32;
let resp_bytes = rand_resp.as_bytes_partial()?;
Ok(resp_bytes.len())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/src/flow/cold_reset/fw_processor/self_test.rs | rom/dev/src/flow/cold_reset/fw_processor/self_test.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
self_test.rs
Abstract:
File contains SELF_TEST_START and SELF_TEST_GET_RESULTS mailbox commands.
--*/
use caliptra_common::mailbox_api::{MailboxReqHeader, MailboxRespHeader};
use caliptra_drivers::{CaliptraError, CaliptraResult};
use caliptra_kat::KatsEnv;
use zerocopy::FromBytes;
use crate::run_fips_tests;
pub struct SelfTestStartCmd;
impl SelfTestStartCmd {
#[inline(always)]
pub(crate) fn execute(
cmd_bytes: &[u8],
env: &mut KatsEnv,
self_test_in_progress: bool,
_resp: &mut [u8],
) -> CaliptraResult<(bool, usize)> {
MailboxReqHeader::ref_from_bytes(cmd_bytes)
.map_err(|_| CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
if self_test_in_progress {
// TODO: set non-fatal error register?
// Return 0 for response length, will cause txn.complete(false)
Ok((false, 0))
} else {
run_fips_tests(env)?;
// Zero value of response buffer is good
Ok((true, core::mem::size_of::<MailboxRespHeader>()))
}
}
}
pub struct SelfTestGetResultsCmd;
impl SelfTestGetResultsCmd {
#[inline(always)]
pub(crate) fn execute(
cmd_bytes: &[u8],
self_test_in_progress: bool,
_resp: &mut [u8],
) -> CaliptraResult<(bool, usize)> {
MailboxReqHeader::ref_from_bytes(cmd_bytes)
.map_err(|_| CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
if !self_test_in_progress {
// TODO: set non-fatal error register?
// Return 0 for response length, will cause txn.complete(false)
Ok((false, 0))
} else {
// Zero value of response buffer is good
Ok((false, core::mem::size_of::<MailboxRespHeader>()))
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/src/flow/cold_reset/fw_processor/capabilities.rs | rom/dev/src/flow/cold_reset/fw_processor/capabilities.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
capabilities.rs
Abstract:
File contains CAPABILITIES mailbox command.
--*/
use caliptra_common::capabilities::Capabilities;
use caliptra_common::mailbox_api::{CapabilitiesResp, MailboxReqHeader, MailboxRespHeader};
use caliptra_drivers::{CaliptraError, CaliptraResult, SocIfc};
use zerocopy::{FromBytes, IntoBytes};
pub struct CapabilitiesCmd;
impl CapabilitiesCmd {
#[inline(always)]
pub(crate) fn execute(
cmd_bytes: &[u8],
soc_ifc: &mut SocIfc,
resp: &mut [u8],
) -> CaliptraResult<usize> {
MailboxReqHeader::ref_from_bytes(cmd_bytes)
.map_err(|_| CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
// Use the response buffer directly as CapabilitiesResp.
// The buffer is zeroized at the start of the loop
let resp_buffer_size = core::mem::size_of::<CapabilitiesResp>();
let resp = resp
.get_mut(..resp_buffer_size)
.ok_or(CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
let capabilities_resp = CapabilitiesResp::mut_from_bytes(resp)
.map_err(|_| CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH)?;
let mut capabilities = Capabilities::default();
capabilities |= Capabilities::ROM_BASE;
if soc_ifc.ocp_lock_enabled() {
capabilities |= Capabilities::ROM_OCP_LOCK;
}
capabilities_resp.hdr = MailboxRespHeader::default();
capabilities_resp.capabilities = capabilities.to_bytes();
let resp_bytes = capabilities_resp.as_bytes();
Ok(resp_bytes.len())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_symbols.rs | rom/dev/tests/rom_integration_tests/test_symbols.rs | // Licensed under the Apache-2.0 license
use std::{collections::HashMap, mem};
use caliptra_builder::Symbol;
use caliptra_cfi_lib::CfiState;
use caliptra_drivers::memory_layout;
#[test]
fn test_linker_symbols_match_memory_layout() {
let elf_bytes = caliptra_builder::build_firmware_elf(crate::helpers::rom_from_env()).unwrap();
let symbols = caliptra_builder::elf_symbols(&elf_bytes).unwrap();
let symbols: HashMap<&str, Symbol> = symbols.into_iter().map(|s| (s.name, s)).collect();
fn assert_symbol_addr(symbols: &HashMap<&str, Symbol>, name: &str, expected_val: u32) {
let sym = symbols
.get(name)
.unwrap_or_else(|| panic!("Unknown symbol {name}"));
if sym.value != u64::from(expected_val) {
panic!(
"Unexpected value for symbol {name}: was 0x{:x} expected 0x{expected_val:x}",
sym.value
);
}
}
assert_symbol_addr(&symbols, "ROM_ORG", memory_layout::ROM_ORG);
assert_symbol_addr(&symbols, "ICCM_ORG", memory_layout::ICCM_ORG);
assert_symbol_addr(&symbols, "DCCM_ORG", memory_layout::DCCM_ORG);
assert_symbol_addr(&symbols, "DATA_ORG", memory_layout::ROM_DATA_ORG);
assert_symbol_addr(&symbols, "STACK_ORG", memory_layout::ROM_STACK_ORG);
assert_symbol_addr(&symbols, "ESTACK_ORG", memory_layout::ROM_ESTACK_ORG);
assert_symbol_addr(&symbols, "NSTACK_ORG", memory_layout::ROM_NSTACK_ORG);
assert_symbol_addr(
&symbols,
"_sstack",
memory_layout::ROM_STACK_ORG + memory_layout::ROM_STACK_SIZE,
);
assert_symbol_addr(&symbols, "CFI_STATE_ORG", memory_layout::CFI_STATE_ORG);
assert_eq!(
memory_layout::ROM_DATA_ORG + memory_layout::ROM_DATA_RESERVED_SIZE,
memory_layout::CFI_STATE_ORG
);
assert_eq!(
memory_layout::CFI_STATE_ORG + mem::size_of::<CfiState>() as u32,
memory_layout::BOOT_STATUS_ORG
);
assert_symbol_addr(&symbols, "ROM_SIZE", memory_layout::ROM_SIZE);
assert_symbol_addr(&symbols, "ICCM_SIZE", memory_layout::ICCM_SIZE);
assert_symbol_addr(&symbols, "DCCM_SIZE", memory_layout::DCCM_SIZE);
assert_symbol_addr(&symbols, "DATA_SIZE", memory_layout::ROM_DATA_SIZE);
assert_symbol_addr(&symbols, "STACK_SIZE", memory_layout::ROM_STACK_SIZE);
assert_symbol_addr(&symbols, "ESTACK_SIZE", memory_layout::ROM_ESTACK_SIZE);
assert_symbol_addr(&symbols, "NSTACK_SIZE", memory_layout::ROM_NSTACK_SIZE);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_pmp.rs | rom/dev/tests/rom_integration_tests/test_pmp.rs | // Licensed under the Apache-2.0 license
use caliptra_api::SocManager;
use caliptra_builder::{
firmware::{self, rom_tests::TEST_FMC_INTERACTIVE, APP_WITH_UART},
ImageOptions,
};
use caliptra_common::RomBootStatus::*;
use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams};
use caliptra_image_types::FwVerificationPqcKeyType;
// From RISC-V_VeeR_EL2_PRM.pdf
// Exception causes
pub const EXCEPTION_CAUSE_STORE_ACCESS_FAULT: u32 = 0x0000_0007;
#[test]
fn test_pmp_enforced() {
let rom = caliptra_builder::build_firmware_rom(&firmware::rom_tests::TEST_PMP_TESTS).unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
..Default::default()
},
BootParams::default(),
)
.unwrap();
hw.step_until_exit_failure().unwrap();
}
#[test]
fn test_datavault_pmp_enforcement_region_start() {
let image_options = ImageOptions {
pqc_key_type: FwVerificationPqcKeyType::MLDSA,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: 1,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode: false,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
// Test PMP enforcement by writing to start of Data Vault.
let result = hw.mailbox_execute(0x1000_0010, &[]);
assert!(result.is_ok());
hw.step_until(|m| m.soc_ifc().cptra_fw_extended_error_info().at(0).read() != 0);
let mcause = hw.soc_ifc().cptra_fw_extended_error_info().at(0).read();
assert_eq!(mcause, EXCEPTION_CAUSE_STORE_ACCESS_FAULT);
}
#[test]
fn test_datavault_pmp_enforcement_region_end() {
let image_options = ImageOptions {
pqc_key_type: FwVerificationPqcKeyType::MLDSA,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: 1,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode: false,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
// Test PMP enforcement by writing to end of Data Vault.
let result = hw.mailbox_execute(0x1000_0011, &[]);
assert!(result.is_ok());
hw.step_until(|m| m.soc_ifc().cptra_fw_extended_error_info().at(0).read() != 0);
let mcause = hw.soc_ifc().cptra_fw_extended_error_info().at(0).read();
assert_eq!(mcause, EXCEPTION_CAUSE_STORE_ACCESS_FAULT);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/rv32_unit_tests.rs | rom/dev/tests/rom_integration_tests/rv32_unit_tests.rs | // Licensed under the Apache-2.0 license
use caliptra_builder::firmware;
use caliptra_hw_model::{BootParams, HwModel, InitParams};
#[test]
fn test_asm() {
let rom = caliptra_builder::build_firmware_rom(&firmware::rom_tests::ASM_TESTS).unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
iccm: &vec![0x55u8; 256 * 1024],
dccm: &vec![0x66u8; 256 * 1024],
..Default::default()
},
BootParams::default(),
)
.unwrap();
let mut output = vec![];
hw.copy_output_until_exit_success(&mut output).unwrap();
assert_eq!(
std::str::from_utf8(&output),
Ok("test_mem: [1, 1, 1, 1, 0, 0, 0, 0, \
0, 0, 0, 0, 1, 0, 0, 0, \
0, 0, 0, 0, 0, 0, 0, 0, \
0, 0, 0, 0, 0, 1, 1, 1, \
1, 0, 0, 0, 0, 0, 0, 0, \
0, 1, 1, 1, 1, 1122867, 1146447479, 2291772091, \
1, 1, 1122867, 1146447479, 2291772091, 1, 1, 1, \
1, 1, 1, 1, 1, 1, 1, 1]\n")
)
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_debug_unlock.rs | rom/dev/tests/rom_integration_tests/test_debug_unlock.rs | // Licensed under the Apache-2.0 license
use std::mem::size_of;
use caliptra_api::mailbox::MailboxRespHeader;
use caliptra_api::mailbox::{
CommandId, MailboxReqHeader, ManufDebugUnlockTokenReq, ProductionAuthDebugUnlockChallenge,
ProductionAuthDebugUnlockReq, ProductionAuthDebugUnlockToken,
};
use caliptra_api::SocManager;
use caliptra_builder::firmware::{self};
use caliptra_error::CaliptraError;
use caliptra_hw_model::{
DbgManufServiceRegReq, DeviceLifecycle, HwModel, ModelError, SecurityState, SubsystemInitParams,
};
use fips204::traits::{SerDes, Signer};
use p384::ecdsa::VerifyingKey;
use rand::{rngs::StdRng, SeedableRng};
use sha2::Digest;
use zerocopy::{FromBytes, IntoBytes};
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_manuf_req_in_passive_mode() {
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Manufacturing);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_manuf_dbg_unlock_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
debug_intent: true,
subsystem_mode: false,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
let token = ManufDebugUnlockTokenReq {
token: caliptra_hw_model_types::DEFAULT_MANUF_DEBUG_UNLOCK_TOKEN
.as_bytes()
.try_into()
.unwrap(),
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::MANUF_DEBUG_UNLOCK_REQ_TOKEN),
&token.as_bytes()[4..],
);
let token = ManufDebugUnlockTokenReq {
hdr: MailboxReqHeader { chksum: checksum },
..token
};
assert_eq!(
hw.mailbox_execute(
CommandId::MANUF_DEBUG_UNLOCK_REQ_TOKEN.into(),
token.as_bytes(),
),
Err(ModelError::MailboxCmdFailed(
CaliptraError::SS_DBG_UNLOCK_REQ_IN_PASSIVE_MODE.into()
))
);
}
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_manuf_success() {
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Manufacturing);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_manuf_dbg_unlock_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
debug_intent: true,
subsystem_mode: true,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
let token_req = ManufDebugUnlockTokenReq {
token: caliptra_hw_model_types::DEFAULT_MANUF_DEBUG_UNLOCK_TOKEN
.as_bytes()
.try_into()
.unwrap(),
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::MANUF_DEBUG_UNLOCK_REQ_TOKEN),
&token_req.as_bytes()[4..],
);
let token = ManufDebugUnlockTokenReq {
hdr: MailboxReqHeader { chksum: checksum },
..token_req
};
let _ = hw
.mailbox_execute(
CommandId::MANUF_DEBUG_UNLOCK_REQ_TOKEN.into(),
token.as_bytes(),
)
.unwrap()
.unwrap();
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
!resp.manuf_dbg_unlock_in_progress()
});
assert!(hw
.soc_ifc()
.ss_dbg_service_reg_rsp()
.read()
.manuf_dbg_unlock_success());
}
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_manuf_wrong_cmd() {
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Manufacturing);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_manuf_dbg_unlock_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
debug_intent: true,
subsystem_mode: true,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
let token = ManufDebugUnlockTokenReq {
token: caliptra_hw_model_types::DEFAULT_MANUF_DEBUG_UNLOCK_TOKEN
.as_bytes()
.try_into()
.unwrap(),
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::MANUF_DEBUG_UNLOCK_REQ_TOKEN),
&token.as_bytes()[4..],
);
let token = ManufDebugUnlockTokenReq {
hdr: MailboxReqHeader { chksum: checksum },
..token
};
assert_eq!(
hw.mailbox_execute(0, token.as_bytes(),),
Err(ModelError::MailboxCmdFailed(
CaliptraError::SS_DBG_UNLOCK_MANUF_INVALID_MBOX_CMD.into()
))
);
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
!resp.manuf_dbg_unlock_in_progress()
});
}
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_manuf_invalid_token() {
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Manufacturing);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_manuf_dbg_unlock_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
debug_intent: true,
subsystem_mode: true,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Defaults to 0 token
let token = ManufDebugUnlockTokenReq {
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::MANUF_DEBUG_UNLOCK_REQ_TOKEN),
&token.as_bytes()[4..],
);
let token = ManufDebugUnlockTokenReq {
hdr: MailboxReqHeader { chksum: checksum },
..token
};
let _ = hw
.mailbox_execute(
CommandId::MANUF_DEBUG_UNLOCK_REQ_TOKEN.into(),
token.as_bytes(),
)
.unwrap()
.unwrap();
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
!resp.manuf_dbg_unlock_in_progress()
});
assert!(hw
.soc_ifc()
.ss_dbg_service_reg_rsp()
.read()
.manuf_dbg_unlock_fail());
}
fn u8_to_u32_be(input: &[u8]) -> Vec<u32> {
input
.chunks(4)
.map(|chunk| {
let mut array = [0u8; 4];
array.copy_from_slice(chunk);
u32::from_be_bytes(array)
})
.collect()
}
fn u8_to_u32_le(input: &[u8]) -> Vec<u32> {
input
.chunks(4)
.map(|chunk| {
let mut array = [0u8; 4];
array.copy_from_slice(chunk);
u32::from_le_bytes(array)
})
.collect()
}
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_prod_success() {
let signing_ecc_key = p384::ecdsa::SigningKey::random(&mut StdRng::from_entropy());
let verifying_ecc_key = VerifyingKey::from(&signing_ecc_key);
let ecc_pub_key_bytes = {
let mut pk = [0; 96];
let ecc_key = verifying_ecc_key.to_encoded_point(false);
pk[..48].copy_from_slice(ecc_key.x().unwrap());
pk[48..].copy_from_slice(ecc_key.y().unwrap());
pk
};
// Convert to hardware format i.e. big endian for ECC.
let ecc_pub_key = u8_to_u32_be(&ecc_pub_key_bytes);
let ecc_pub_key_bytes = ecc_pub_key.as_bytes();
let (verifying_mldsa_key, signing_mldsa_key) = fips204::ml_dsa_87::try_keygen().unwrap();
let mldsa_pub_key_bytes = verifying_mldsa_key.into_bytes();
// Convert to hardware format i.e. little endian for MLDSA.
let mldsa_pub_key = u8_to_u32_le(&mldsa_pub_key_bytes);
let mldsa_pub_key_bytes = mldsa_pub_key.as_bytes();
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Production);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_prod_dbg_unlock_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let unlock_level = 5u8;
let mut prod_dbg_unlock_keypairs: Vec<(&[u8; 96], &[u8; 2592])> =
vec![(&[0; 96], &[0; 2592]); 8];
prod_dbg_unlock_keypairs[(unlock_level - 1) as usize] = (
ecc_pub_key_bytes.try_into().unwrap(),
mldsa_pub_key_bytes.try_into().unwrap(),
);
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
prod_dbg_unlock_keypairs,
debug_intent: true,
subsystem_mode: true,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// [TODO][CAP2] With wrong len mbox err 0 gets returned which is not right
let request = ProductionAuthDebugUnlockReq {
length: {
let req_len = size_of::<ProductionAuthDebugUnlockReq>() - size_of::<MailboxReqHeader>();
(req_len / size_of::<u32>()) as u32
},
unlock_level,
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ),
&request.as_bytes()[4..],
);
let request = ProductionAuthDebugUnlockReq {
hdr: MailboxReqHeader { chksum: checksum },
..request
};
let resp = hw
.mailbox_execute(
CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ.into(),
request.as_bytes(),
)
.unwrap()
.unwrap();
let challenge = ProductionAuthDebugUnlockChallenge::read_from_bytes(resp.as_slice()).unwrap();
assert_eq!(
challenge.length,
((size_of::<ProductionAuthDebugUnlockChallenge>() - size_of::<MailboxRespHeader>())
/ size_of::<u32>()) as u32
);
let reserved = [0u8; 3];
let mut sha384 = sha2::Sha384::new();
sha384.update(challenge.unique_device_identifier);
sha384.update([unlock_level]);
sha384.update(reserved);
sha384.update(challenge.challenge);
let sha384_digest = sha384.finalize();
let (ecc_signature, _id) = signing_ecc_key
.sign_prehash_recoverable(sha384_digest.as_slice())
.unwrap();
let ecc_signature = ecc_signature.to_bytes();
let ecc_signature = ecc_signature.as_slice();
// Convert to hardware format i.e. big endian for ECC.
let ecc_signature = u8_to_u32_be(ecc_signature);
let mut sha512 = sha2::Sha512::new();
sha512.update(challenge.unique_device_identifier);
sha512.update([unlock_level]);
sha512.update(reserved);
sha512.update(challenge.challenge);
let sha512_digest = sha512.finalize();
// Sign the digest in the little endian format, as required by the hardware.
let mldsa_signature = signing_mldsa_key
.try_sign_with_seed(&[0; 32], &sha512_digest, &[])
.unwrap();
// Convert the signature slice to little endian dwords, as required by the hardware.
let mldsa_signature = {
let mut sig = [0; 4628];
sig[..4627].copy_from_slice(&mldsa_signature);
u8_to_u32_le(&sig)
};
let token = ProductionAuthDebugUnlockToken {
length: {
let req_len =
size_of::<ProductionAuthDebugUnlockToken>() - size_of::<MailboxReqHeader>();
(req_len / size_of::<u32>()) as u32
},
unique_device_identifier: challenge.unique_device_identifier,
unlock_level,
challenge: challenge.challenge,
ecc_public_key: ecc_pub_key.try_into().unwrap(),
mldsa_public_key: mldsa_pub_key.try_into().unwrap(),
ecc_signature: ecc_signature.try_into().unwrap(),
mldsa_signature: mldsa_signature.try_into().unwrap(),
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN),
&token.as_bytes()[4..],
);
let token = ProductionAuthDebugUnlockToken {
hdr: MailboxReqHeader { chksum: checksum },
..token
};
let _resp = hw
.mailbox_execute(
CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN.into(),
token.as_bytes(),
)
.unwrap();
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
!resp.prod_dbg_unlock_in_progress()
});
assert!(hw
.soc_ifc()
.ss_dbg_service_reg_rsp()
.read()
.prod_dbg_unlock_success());
let mut value = hw
.soc_ifc()
.ss_soc_dbg_unlock_level()
.get(0)
.unwrap()
.read();
let mut soc_debug_level = 0;
while value > 1 {
value >>= 1;
soc_debug_level += 1;
}
soc_debug_level += 1;
assert!(soc_debug_level == unlock_level);
}
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_prod_invalid_length() {
let signing_ecc_key = p384::ecdsa::SigningKey::random(&mut StdRng::from_entropy());
let verifying_ecc_key = VerifyingKey::from(&signing_ecc_key);
let ecc_pub_key_bytes = {
let mut pk = [0; 96];
let ecc_key = verifying_ecc_key.to_encoded_point(false);
pk[..48].copy_from_slice(ecc_key.x().unwrap());
pk[48..].copy_from_slice(ecc_key.y().unwrap());
pk
};
// Convert to hardware format i.e. big endian for ECC.
let ecc_pub_key = u8_to_u32_be(&ecc_pub_key_bytes);
let ecc_pub_key_bytes = ecc_pub_key.as_bytes();
let (verifying_mldsa_key, _signing_mldsa_key) = fips204::ml_dsa_87::try_keygen().unwrap();
let mldsa_pub_key_bytes = verifying_mldsa_key.into_bytes();
// Convert to hardware format i.e. little endian for MLDSA.
let mldsa_pub_key = u8_to_u32_le(&mldsa_pub_key_bytes);
let mldsa_pub_key_bytes = mldsa_pub_key.as_bytes();
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Production);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_prod_dbg_unlock_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
prod_dbg_unlock_keypairs: vec![(
ecc_pub_key_bytes.try_into().unwrap(),
&mldsa_pub_key_bytes.try_into().unwrap(),
)],
debug_intent: true,
subsystem_mode: true,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
let unlock_level = 2u8;
let request = ProductionAuthDebugUnlockReq {
length: 123u32, // Set an incorrect length
unlock_level,
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ),
&request.as_bytes()[4..],
);
let request = ProductionAuthDebugUnlockReq {
hdr: MailboxReqHeader { chksum: checksum },
..request
};
let _ = hw.mailbox_execute(
CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ.into(),
request.as_bytes(),
);
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
!resp.prod_dbg_unlock_in_progress()
});
assert!(hw
.soc_ifc()
.ss_dbg_service_reg_rsp()
.read()
.prod_dbg_unlock_fail());
}
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_prod_invalid_token_challenge() {
let signing_ecc_key = p384::ecdsa::SigningKey::random(&mut StdRng::from_entropy());
let verifying_ecc_key = VerifyingKey::from(&signing_ecc_key);
let ecc_pub_key_bytes = {
let mut pk = [0; 96];
let ecc_key = verifying_ecc_key.to_encoded_point(false);
pk[..48].copy_from_slice(ecc_key.x().unwrap());
pk[48..].copy_from_slice(ecc_key.y().unwrap());
pk
};
// Convert to hardware format i.e. little endian.
let ecc_pub_key = u8_to_u32_be(&ecc_pub_key_bytes);
let ecc_pub_key_bytes = ecc_pub_key.as_bytes();
let (verifying_mldsa_key, _signing_mldsa_key) = fips204::ml_dsa_87::try_keygen().unwrap();
let mldsa_pub_key_bytes = verifying_mldsa_key.into_bytes();
let mldsa_pub_key = u8_to_u32_be(&mldsa_pub_key_bytes);
let mldsa_pub_key_bytes = mldsa_pub_key.as_bytes();
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Production);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_prod_dbg_unlock_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
prod_dbg_unlock_keypairs: vec![(
ecc_pub_key_bytes.try_into().unwrap(),
mldsa_pub_key_bytes.try_into().unwrap(),
)],
subsystem_mode: true,
debug_intent: true,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
let unlock_level = 3u8;
let request = ProductionAuthDebugUnlockReq {
length: {
let req_len = size_of::<ProductionAuthDebugUnlockReq>() - size_of::<MailboxReqHeader>();
(req_len / size_of::<u32>()) as u32
},
unlock_level,
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ),
&request.as_bytes()[4..],
);
let request = ProductionAuthDebugUnlockReq {
hdr: MailboxReqHeader { chksum: checksum },
..request
};
let resp = hw
.mailbox_execute(
CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ.into(),
request.as_bytes(),
)
.unwrap()
.unwrap();
let challenge = ProductionAuthDebugUnlockChallenge::read_from_bytes(resp.as_slice()).unwrap();
// Create an invalid token by using a different challenge than what was received
let invalid_challenge = [0u8; 48];
let token = ProductionAuthDebugUnlockToken {
length: {
let req_len =
size_of::<ProductionAuthDebugUnlockToken>() - size_of::<MailboxReqHeader>();
(req_len / size_of::<u32>()) as u32
},
unique_device_identifier: challenge.unique_device_identifier,
unlock_level,
challenge: invalid_challenge, // Use invalid challenge
ecc_public_key: ecc_pub_key.try_into().unwrap(),
mldsa_public_key: mldsa_pub_key.try_into().unwrap(),
ecc_signature: [0u32; 24], // Invalid signature
mldsa_signature: [0u32; 1157], // Invalid signature
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN),
&token.as_bytes()[4..],
);
let token = ProductionAuthDebugUnlockToken {
hdr: MailboxReqHeader { chksum: checksum },
..token
};
let _ = hw.mailbox_execute(
CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN.into(),
token.as_bytes(),
);
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
!resp.prod_dbg_unlock_in_progress()
});
assert!(hw
.soc_ifc()
.ss_dbg_service_reg_rsp()
.read()
.prod_dbg_unlock_fail());
}
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_prod_invalid_signature() {
let signing_ecc_key = p384::ecdsa::SigningKey::random(&mut StdRng::from_entropy());
let verifying_ecc_key = VerifyingKey::from(&signing_ecc_key);
let ecc_pub_key_bytes = {
let mut pk = [0; 96];
let ecc_key = verifying_ecc_key.to_encoded_point(false);
pk[..48].copy_from_slice(ecc_key.x().unwrap());
pk[48..].copy_from_slice(ecc_key.y().unwrap());
pk
};
// Convert to hardware format i.e. little endian.
let ecc_pub_key = u8_to_u32_be(&ecc_pub_key_bytes);
let ecc_pub_key_bytes = ecc_pub_key.as_bytes();
let (verifying_mldsa_key, signing_mldsa_key) = fips204::ml_dsa_87::try_keygen().unwrap();
let mldsa_pub_key_bytes = verifying_mldsa_key.into_bytes();
// Convert to hardware format i.e. little endian.
let mldsa_pub_key = u8_to_u32_be(&mldsa_pub_key_bytes);
let mldsa_pub_key_bytes = mldsa_pub_key.as_bytes();
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Production);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_prod_dbg_unlock_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
prod_dbg_unlock_keypairs: vec![(
ecc_pub_key_bytes.try_into().unwrap(),
mldsa_pub_key_bytes.try_into().unwrap(),
)],
debug_intent: true,
subsystem_mode: true,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
let unlock_level = 4u8;
// [TODO][CAP2] With wrong len mbox err 0 gets returned which is not right
let request = ProductionAuthDebugUnlockReq {
length: {
let req_len = size_of::<ProductionAuthDebugUnlockReq>() - size_of::<MailboxReqHeader>();
(req_len / size_of::<u32>()) as u32
},
unlock_level,
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ),
&request.as_bytes()[4..],
);
let request = ProductionAuthDebugUnlockReq {
hdr: MailboxReqHeader { chksum: checksum },
..request
};
let resp = hw
.mailbox_execute(
CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ.into(),
request.as_bytes(),
)
.unwrap()
.unwrap();
let challenge = ProductionAuthDebugUnlockChallenge::read_from_bytes(resp.as_slice()).unwrap();
let mut sha512 = sha2::Sha512::new();
sha512.update(challenge.challenge);
sha512.update(challenge.unique_device_identifier);
let mut sha512_digest = sha512.finalize();
let msg = {
let msg: &mut [u8] = sha512_digest.as_mut_slice();
msg
};
let mldsa_signature = signing_mldsa_key
.try_sign_with_seed(&[0; 32], msg, &[])
.unwrap();
let mldsa_signature = {
let mut sig = [0; 4628];
sig[..4627].copy_from_slice(&mldsa_signature);
u8_to_u32_le(&sig)
};
let token = ProductionAuthDebugUnlockToken {
length: {
let req_len =
size_of::<ProductionAuthDebugUnlockToken>() - size_of::<MailboxReqHeader>();
(req_len / size_of::<u32>()) as u32
},
unique_device_identifier: challenge.unique_device_identifier,
unlock_level,
challenge: challenge.challenge,
ecc_public_key: ecc_pub_key.try_into().unwrap(),
mldsa_public_key: mldsa_pub_key.try_into().unwrap(),
ecc_signature: [0xab; 24], // Invalid signature
mldsa_signature: mldsa_signature.try_into().unwrap(),
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN),
&token.as_bytes()[4..],
);
let token = ProductionAuthDebugUnlockToken {
hdr: MailboxReqHeader { chksum: checksum },
..token
};
let _ = hw.mailbox_execute(
CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN.into(),
token.as_bytes(),
);
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
!resp.prod_dbg_unlock_in_progress()
});
assert!(hw
.soc_ifc()
.ss_dbg_service_reg_rsp()
.read()
.prod_dbg_unlock_fail());
}
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_prod_wrong_public_keys() {
let signing_ecc_key = p384::ecdsa::SigningKey::random(&mut StdRng::from_entropy());
let verifying_ecc_key = VerifyingKey::from(&signing_ecc_key);
let ecc_pub_key_bytes = {
let mut pk = [0; 96];
let ecc_key = verifying_ecc_key.to_encoded_point(false);
pk[..48].copy_from_slice(ecc_key.x().unwrap());
pk[48..].copy_from_slice(ecc_key.y().unwrap());
pk
};
// Convert to hardware format i.e. big endian for ECC.
let ecc_pub_key = u8_to_u32_be(&ecc_pub_key_bytes);
let ecc_pub_key_bytes = ecc_pub_key.as_bytes();
let (verifying_mldsa_key, _signing_mldsa_key) = fips204::ml_dsa_87::try_keygen().unwrap();
let mldsa_pub_key_bytes = verifying_mldsa_key.into_bytes();
// Convert to hardware format i.e. little endian for MLDSA.
let mldsa_pub_key = u8_to_u32_le(&mldsa_pub_key_bytes);
let mldsa_pub_key_bytes = mldsa_pub_key.as_bytes();
// Generate a different set of keys that aren't registered with the hardware
let different_signing_ecc_key = p384::ecdsa::SigningKey::random(&mut StdRng::from_entropy());
let different_verifying_ecc_key = VerifyingKey::from(&different_signing_ecc_key);
let different_ecc_pub_key_bytes = {
let mut pk = [0; 96];
let ecc_key = different_verifying_ecc_key.to_encoded_point(false);
pk[..48].copy_from_slice(ecc_key.x().unwrap());
pk[48..].copy_from_slice(ecc_key.y().unwrap());
pk
};
let different_ecc_pub_key = u8_to_u32_be(&different_ecc_pub_key_bytes);
let (different_verifying_mldsa_key, _) = fips204::ml_dsa_87::try_keygen().unwrap();
let different_mldsa_pub_key_bytes = different_verifying_mldsa_key.into_bytes();
let different_mldsa_pub_key = u8_to_u32_be(&different_mldsa_pub_key_bytes);
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Production);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_prod_dbg_unlock_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
prod_dbg_unlock_keypairs: vec![(
ecc_pub_key_bytes.try_into().unwrap(),
mldsa_pub_key_bytes.try_into().unwrap(),
)],
debug_intent: true,
subsystem_mode: true,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
let unlock_level = 5u8;
let request = ProductionAuthDebugUnlockReq {
length: {
let req_len = size_of::<ProductionAuthDebugUnlockReq>() - size_of::<MailboxReqHeader>();
(req_len / size_of::<u32>()) as u32
},
unlock_level,
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ),
&request.as_bytes()[4..],
);
let request = ProductionAuthDebugUnlockReq {
hdr: MailboxReqHeader { chksum: checksum },
..request
};
let resp = hw
.mailbox_execute(
CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ.into(),
request.as_bytes(),
)
.unwrap()
.unwrap();
let challenge = ProductionAuthDebugUnlockChallenge::read_from_bytes(resp.as_slice()).unwrap();
let token = ProductionAuthDebugUnlockToken {
length: {
let req_len =
size_of::<ProductionAuthDebugUnlockToken>() - size_of::<MailboxReqHeader>();
(req_len / size_of::<u32>()) as u32
},
unique_device_identifier: challenge.unique_device_identifier,
unlock_level,
challenge: challenge.challenge,
// Use the different public keys that weren't registered with the hardware
ecc_public_key: different_ecc_pub_key.try_into().unwrap(),
mldsa_public_key: different_mldsa_pub_key.try_into().unwrap(),
ecc_signature: [0u32; 24], // Signature doesn't matter since keys will fail first
mldsa_signature: [0u32; 1157], // Signature doesn't matter since keys will fail first
..Default::default()
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN),
&token.as_bytes()[4..],
);
let token = ProductionAuthDebugUnlockToken {
hdr: MailboxReqHeader { chksum: checksum },
..token
};
let _ = hw.mailbox_execute(
CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN.into(),
token.as_bytes(),
);
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
!resp.prod_dbg_unlock_in_progress()
});
assert!(hw
.soc_ifc()
.ss_dbg_service_reg_rsp()
.read()
.prod_dbg_unlock_fail());
}
//TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070
#[test]
#[cfg(not(feature = "fpga_realtime"))]
fn test_dbg_unlock_prod_wrong_cmd() {
let signing_ecc_key = p384::ecdsa::SigningKey::random(&mut StdRng::from_entropy());
let verifying_ecc_key = VerifyingKey::from(&signing_ecc_key);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_uds_fe.rs | rom/dev/tests/rom_integration_tests/test_uds_fe.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
uds_programming.rs
Abstract:
File contains the implementation of UDS programming flow test.
--*/
use caliptra_api::{
mailbox::{MailboxReqHeader, ZeroizeUdsFeReq, ZEROIZE_UDS_FLAG},
SocManager,
};
use caliptra_builder::firmware::{self};
use caliptra_error::CaliptraError;
use caliptra_hw_model::{DbgManufServiceRegReq, DeviceLifecycle, HwModel, SecurityState};
use zerocopy::IntoBytes;
const UDS_FE_PROGRAMMING_SHUTDOWN_SUCCESS: u32 = 0xa006_0004;
#[cfg_attr(any(feature = "fpga_subsystem", feature = "fpga_realtime"), ignore)] // No fuse controller in FPGA without MCI
#[test]
fn test_uds_programming_no_active_mode() {
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Manufacturing);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_uds_program_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
subsystem_mode: false,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Wait for fatal error
hw.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() != 0);
// Verify fatal code is correct
assert_eq!(
hw.soc_ifc().cptra_fw_error_fatal().read(),
u32::from(CaliptraError::ROM_UDS_PROG_IN_PASSIVE_MODE)
);
}
#[cfg_attr(feature = "fpga_realtime", ignore)] // No fuse controller in FPGA without MCI
#[test]
fn test_uds_programming_granularity_64bit() {
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Manufacturing);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_uds_program_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
subsystem_mode: true,
uds_fuse_row_granularity_64: true,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Wait for ROM to complete
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
resp.uds_program_success()
});
let config_val = hw.soc_ifc().cptra_generic_input_wires().read()[0];
assert_eq!((config_val >> 31) & 1, 0);
}
#[cfg_attr(feature = "fpga_realtime", ignore)] // No fuse controller in FPGA without MCI
#[test]
fn test_uds_programming_granularity_32bit() {
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Manufacturing);
let dbg_manuf_service = *DbgManufServiceRegReq::default().set_uds_program_req(true);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
dbg_manuf_service,
subsystem_mode: true,
uds_fuse_row_granularity_64: false,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Wait for ROM to complete
hw.step_until(|m| {
let resp = m.soc_ifc().ss_dbg_service_reg_rsp().read();
resp.uds_program_success()
});
let config_val = hw.soc_ifc().cptra_generic_input_wires().read()[0];
assert_eq!((config_val >> 31) & 1, 1);
}
#[cfg_attr(feature = "fpga_realtime", ignore)] // No fuse controller in FPGA without MCI
#[test]
fn test_uds_zeroization_64bit() {
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Manufacturing);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
subsystem_mode: true,
uds_fuse_row_granularity_64: true,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Prepare ZEROIZE_UDS_FE command to zeroize UDS partition
let mut cmd = ZeroizeUdsFeReq {
hdr: MailboxReqHeader { chksum: 0 },
flags: ZEROIZE_UDS_FLAG,
};
// Calculate checksum
let chksum_size = core::mem::size_of_val(&cmd.hdr.chksum);
cmd.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE),
&cmd.as_mut_bytes()[chksum_size..],
);
// Execute mailbox command
let _ = hw.mailbox_execute(
caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE.into(),
cmd.as_bytes(),
);
// Ignore the response as UDS zeroization causes shutdown.
// Wait till fatal error is raised
hw.step_until(|m| {
m.soc_ifc().cptra_fw_error_fatal().read() == UDS_FE_PROGRAMMING_SHUTDOWN_SUCCESS
});
}
#[cfg_attr(feature = "fpga_realtime", ignore)] // No fuse controller in FPGA without MCI
#[test]
fn test_uds_zeroization_32bit() {
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Manufacturing);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
subsystem_mode: true,
uds_fuse_row_granularity_64: false,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Prepare ZEROIZE_UDS_FE command to zeroize UDS partition (flag 0x01)
let mut cmd = ZeroizeUdsFeReq {
hdr: MailboxReqHeader { chksum: 0 },
flags: ZEROIZE_UDS_FLAG,
};
// Calculate checksum
let chksum_size = core::mem::size_of_val(&cmd.hdr.chksum);
cmd.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE),
&cmd.as_mut_bytes()[chksum_size..],
);
// Execute mailbox command
let _ = hw.mailbox_execute(
caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE.into(),
cmd.as_bytes(),
);
// Ignore the response as UDS zeroization causes shutdown.
// Wait till fatal error is raised
hw.step_until(|m| {
m.soc_ifc().cptra_fw_error_fatal().read() == UDS_FE_PROGRAMMING_SHUTDOWN_SUCCESS
});
}
#[cfg_attr(feature = "fpga_realtime", ignore)] // No fuse controller in FPGA without MCI
#[test]
fn test_zeroize_fe_partitions_one_at_a_time_64bit() {
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Manufacturing);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
// FE partition flags in order: FE0, FE1, FE2, FE3
let fe_flags = [
caliptra_api::mailbox::ZEROIZE_FE0_FLAG,
caliptra_api::mailbox::ZEROIZE_FE1_FLAG,
caliptra_api::mailbox::ZEROIZE_FE2_FLAG,
caliptra_api::mailbox::ZEROIZE_FE3_FLAG,
];
// Loop through and zeroize each FE partition one at a time
for &flag in fe_flags.iter() {
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
subsystem_mode: true,
uds_fuse_row_granularity_64: true,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Prepare ZEROIZE_UDS_FE command for this partition
let mut cmd = ZeroizeUdsFeReq {
hdr: MailboxReqHeader { chksum: 0 },
flags: flag,
};
// Calculate checksum
let chksum_size = core::mem::size_of_val(&cmd.hdr.chksum);
cmd.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE),
&cmd.as_mut_bytes()[chksum_size..],
);
// Execute mailbox command
let _ = hw.mailbox_execute(
caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE.into(),
cmd.as_bytes(),
);
// Ignore the response as UDS zeroization causes shutdown.
// Wait till fatal error is raised
hw.step_until(|m| {
m.soc_ifc().cptra_fw_error_fatal().read() == UDS_FE_PROGRAMMING_SHUTDOWN_SUCCESS
});
}
}
#[cfg_attr(feature = "fpga_realtime", ignore)] // No fuse controller in FPGA without MCI
#[test]
fn test_zeroize_fe_partitions_one_at_a_time_32bit() {
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Manufacturing);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
// FE partition flags in order: FE0, FE1, FE2, FE3
let fe_flags = [
caliptra_api::mailbox::ZEROIZE_FE0_FLAG,
caliptra_api::mailbox::ZEROIZE_FE1_FLAG,
caliptra_api::mailbox::ZEROIZE_FE2_FLAG,
caliptra_api::mailbox::ZEROIZE_FE3_FLAG,
];
// Loop through and zeroize each FE partition one at a time
for &flag in fe_flags.iter() {
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
subsystem_mode: true,
uds_fuse_row_granularity_64: false,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Prepare ZEROIZE_UDS_FE command for this partition
let mut cmd = ZeroizeUdsFeReq {
hdr: MailboxReqHeader { chksum: 0 },
flags: flag,
};
// Calculate checksum
let chksum_size = core::mem::size_of_val(&cmd.hdr.chksum);
cmd.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE),
&cmd.as_mut_bytes()[chksum_size..],
);
// Execute mailbox command
let _ = hw.mailbox_execute(
caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE.into(),
cmd.as_bytes(),
);
// Ignore the response as FE zeroization causes shutdown.
// Wait till fatal error is raised
hw.step_until(|m| {
m.soc_ifc().cptra_fw_error_fatal().read() == UDS_FE_PROGRAMMING_SHUTDOWN_SUCCESS
});
}
}
#[cfg_attr(feature = "fpga_realtime", ignore)] // No fuse controller in FPGA without MCI
#[test]
fn test_zeroize_all_partitions_single_shot() {
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Manufacturing);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
subsystem_mode: true,
uds_fuse_row_granularity_64: true,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Prepare ZEROIZE_UDS_FE command to zeroize all partitions in a single shot
// UDS (0x01) + FE0 (0x02) + FE1 (0x04) + FE2 (0x08) + FE3 (0x10) = 0x1F
let all_flags = caliptra_api::mailbox::ZEROIZE_UDS_FLAG
| caliptra_api::mailbox::ZEROIZE_FE0_FLAG
| caliptra_api::mailbox::ZEROIZE_FE1_FLAG
| caliptra_api::mailbox::ZEROIZE_FE2_FLAG
| caliptra_api::mailbox::ZEROIZE_FE3_FLAG;
let mut cmd = ZeroizeUdsFeReq {
hdr: MailboxReqHeader { chksum: 0 },
flags: all_flags,
};
// Calculate checksum
let chksum_size = core::mem::size_of_val(&cmd.hdr.chksum);
cmd.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE),
&cmd.as_mut_bytes()[chksum_size..],
);
// Execute mailbox command
let _ = hw.mailbox_execute(
caliptra_common::mailbox_api::CommandId::ZEROIZE_UDS_FE.into(),
cmd.as_bytes(),
);
// Ignore the response as UDS/FE zeroization causes shutdown.
// Wait till fatal error is raised
hw.step_until(|m| {
m.soc_ifc().cptra_fw_error_fatal().read() == UDS_FE_PROGRAMMING_SHUTDOWN_SUCCESS
});
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/tests_get_idev_csr.rs | rom/dev/tests/rom_integration_tests/tests_get_idev_csr.rs | // Licensed under the Apache-2.0 license
use caliptra_api::SocManager;
use caliptra_builder::ImageOptions;
use caliptra_common::mailbox_api::{CommandId, GetIdevCsrResp, MailboxReqHeader};
use caliptra_drivers::{InitDevIdCsrEnvelope, MfgFlags};
use caliptra_error::CaliptraError;
use caliptra_hw_model::{DeviceLifecycle, Fuses, HwModel, ModelError};
use core::mem::offset_of;
use openssl::{hash::MessageDigest, memcmp, pkey::PKey, sign::Signer};
use zerocopy::IntoBytes;
use crate::helpers;
const DEFAULT_CSR_HMAC_KEY: [u8; 64] = [
0x01, 0x45, 0x52, 0xAD, 0x19, 0x55, 0x07, 0x57, 0x50, 0xC6, 0x02, 0xDD, 0x85, 0xDE, 0x4E, 0x9B,
0x81, 0x5C, 0xC9, 0xEF, 0x0B, 0xA8, 0x1A, 0x35, 0x7A, 0x05, 0xD7, 0xC0, 0x7F, 0x5E, 0xFA, 0xEB,
0xF7, 0x6D, 0xD9, 0xD2, 0x9E, 0x38, 0x19, 0x7F, 0x04, 0x05, 0x25, 0x37, 0x25, 0xB5, 0x68, 0xF4,
0x43, 0x26, 0x65, 0xF1, 0xD1, 0x1D, 0x02, 0xA7, 0xBF, 0xB9, 0x27, 0x9F, 0xA2, 0xEB, 0x96, 0xD7,
];
#[test]
fn test_get_ecc_csr() {
let (mut hw, _) = helpers::build_hw_model_and_image_bundle(
Fuses {
life_cycle: DeviceLifecycle::Manufacturing,
debug_locked: true,
..Default::default()
},
ImageOptions::default(),
);
let ecc_csr_bytes = {
let flags = MfgFlags::GENERATE_IDEVID_CSR;
hw.soc_ifc()
.cptra_dbg_manuf_service_reg()
.write(|_| flags.bits());
let csr_envelop = helpers::get_csr_envelop(&mut hw).unwrap();
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
csr_envelop.ecc_csr.csr[..csr_envelop.ecc_csr.csr_len as usize].to_vec()
};
let payload = MailboxReqHeader {
chksum: caliptra_common::checksum::calc_checksum(
u32::from(CommandId::GET_IDEV_ECC384_CSR),
&[],
),
};
let response = hw
.mailbox_execute(CommandId::GET_IDEV_ECC384_CSR.into(), payload.as_bytes())
.unwrap()
.unwrap();
let mut get_idv_csr_resp = GetIdevCsrResp::default();
get_idv_csr_resp.as_mut_bytes()[..response.len()].copy_from_slice(&response);
assert!(caliptra_common::checksum::verify_checksum(
get_idv_csr_resp.hdr.chksum,
0x0,
&get_idv_csr_resp.as_bytes()[core::mem::size_of_val(&get_idv_csr_resp.hdr.chksum)..],
));
assert_eq!(ecc_csr_bytes.len() as u32, get_idv_csr_resp.data_size);
assert_eq!(
ecc_csr_bytes,
get_idv_csr_resp.data[..get_idv_csr_resp.data_size as usize]
);
}
#[test]
fn test_get_csr_generate_csr_flag_not_set() {
let (mut hw, _) = helpers::build_hw_model_and_image_bundle(
Fuses {
life_cycle: DeviceLifecycle::Manufacturing,
debug_locked: true,
..Default::default()
},
ImageOptions::default(),
);
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
let payload = MailboxReqHeader {
chksum: caliptra_common::checksum::calc_checksum(
u32::from(CommandId::GET_IDEV_ECC384_CSR),
&[],
),
};
let response = hw.mailbox_execute(CommandId::GET_IDEV_ECC384_CSR.into(), payload.as_bytes());
let expected_error = ModelError::MailboxCmdFailed(
CaliptraError::FW_PROC_MAILBOX_GET_IDEV_CSR_UNPROVISIONED_CSR.into(),
);
assert_eq!(expected_error, response.unwrap_err());
}
#[test]
fn test_validate_csr_mac() {
let (mut hw, _) = helpers::build_hw_model_and_image_bundle(
Fuses {
life_cycle: DeviceLifecycle::Manufacturing,
debug_locked: true,
..Default::default()
},
ImageOptions::default(),
);
let csr_envelop = {
let flags = MfgFlags::GENERATE_IDEVID_CSR;
hw.soc_ifc()
.cptra_dbg_manuf_service_reg()
.write(|_| flags.bits());
let csr_envelop = helpers::get_csr_envelop(&mut hw).unwrap();
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
csr_envelop
};
let hmac = {
let offset = offset_of!(InitDevIdCsrEnvelope, csr_mac);
let envelope_slice = csr_envelop.as_bytes().get(..offset).unwrap().to_vec();
let key = PKey::hmac(&DEFAULT_CSR_HMAC_KEY).unwrap();
let mut signer = Signer::new(MessageDigest::sha512(), &key).unwrap();
signer.update(&envelope_slice).unwrap();
signer.sign_to_vec().unwrap()
};
assert!(memcmp::eq(&hmac, &csr_envelop.csr_mac));
}
#[test]
fn test_get_mldsa_csr() {
let (mut hw, _) = helpers::build_hw_model_and_image_bundle(
Fuses {
life_cycle: DeviceLifecycle::Manufacturing,
debug_locked: true,
..Default::default()
},
ImageOptions::default(),
);
let mldsa_csr_bytes = {
let flags = MfgFlags::GENERATE_IDEVID_CSR;
hw.soc_ifc()
.cptra_dbg_manuf_service_reg()
.write(|_| flags.bits());
let csr_envelop = helpers::get_csr_envelop(&mut hw).unwrap();
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
csr_envelop.mldsa_csr.csr[..csr_envelop.mldsa_csr.csr_len as usize].to_vec()
};
let payload = MailboxReqHeader {
chksum: caliptra_common::checksum::calc_checksum(
u32::from(CommandId::GET_IDEV_MLDSA87_CSR),
&[],
),
};
let response = hw
.mailbox_execute(CommandId::GET_IDEV_MLDSA87_CSR.into(), payload.as_bytes())
.unwrap()
.unwrap();
let mut get_idv_csr_resp = GetIdevCsrResp::default();
get_idv_csr_resp.as_mut_bytes()[..response.len()].copy_from_slice(&response);
assert!(caliptra_common::checksum::verify_checksum(
get_idv_csr_resp.hdr.chksum,
0x0,
&get_idv_csr_resp.as_bytes()[core::mem::size_of_val(&get_idv_csr_resp.hdr.chksum)..],
));
assert_eq!(mldsa_csr_bytes.len() as u32, get_idv_csr_resp.data_size);
assert_eq!(
mldsa_csr_bytes,
get_idv_csr_resp.data[..get_idv_csr_resp.data_size as usize]
);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_capabilities.rs | rom/dev/tests/rom_integration_tests/test_capabilities.rs | // Licensed under the Apache-2.0 license
use caliptra_builder::ImageOptions;
use caliptra_common::capabilities::Capabilities;
use caliptra_common::mailbox_api::{
CapabilitiesResp, CommandId, MailboxReqHeader, MailboxRespHeader,
};
use caliptra_hw_model::{Fuses, HwModel};
use zerocopy::{FromBytes, IntoBytes};
use crate::helpers;
#[test]
fn test_capabilities() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
let payload = MailboxReqHeader {
chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::CAPABILITIES), &[]),
};
let response = hw
.mailbox_execute(CommandId::CAPABILITIES.into(), payload.as_bytes())
.unwrap()
.unwrap();
let capabilities_resp = CapabilitiesResp::ref_from_bytes(response.as_bytes()).unwrap();
// Verify response checksum
assert!(caliptra_common::checksum::verify_checksum(
capabilities_resp.hdr.chksum,
0x0,
&capabilities_resp.as_bytes()[core::mem::size_of_val(&capabilities_resp.hdr.chksum)..],
));
// Verify FIPS status
assert_eq!(
capabilities_resp.hdr.fips_status,
MailboxRespHeader::FIPS_STATUS_APPROVED
);
// Verify Capabilities
let caps = Capabilities::try_from(capabilities_resp.capabilities.as_bytes()).unwrap();
assert!(caps.contains(Capabilities::ROM_BASE));
// `Capabilities::ROM_OCP_LOCK` should only be set if using a subsystem fpga with a ROM
// compiled with the `ocp-lock` feature.
if hw.subsystem_mode() && hw.supports_ocp_lock() {
assert!(caps.contains(Capabilities::ROM_OCP_LOCK));
} else {
assert!(!caps.contains(Capabilities::ROM_OCP_LOCK));
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_cpu_fault.rs | rom/dev/tests/rom_integration_tests/test_cpu_fault.rs | // Licensed under the Apache-2.0 license
use caliptra_api::SocManager;
use caliptra_hw_model::{BootParams, HwModel, InitParams};
use elf::{endian::LittleEndian, ElfBytes};
#[test]
fn test_cpu_fault() {
const GLOBAL_EXCEPTION: u32 = 0x01050002;
let rom_fwid = crate::helpers::rom_from_env();
let elf_bytes = caliptra_builder::build_firmware_elf(rom_fwid).unwrap();
let mut rom = caliptra_builder::elf2rom(&elf_bytes).unwrap();
let elf = ElfBytes::<LittleEndian>::minimal_parse(&elf_bytes).unwrap();
let symbol_table = elf.symbol_table().unwrap().unwrap().0;
let string_table = elf.symbol_table().unwrap().unwrap().1;
let rom_entry_offset = symbol_table
.iter()
.find(|symbol| string_table.get(symbol.st_name as usize).unwrap() == "rom_entry")
.unwrap()
.st_value as usize;
println!("rom_entry_offset is {}", rom_entry_offset);
// Write an instruction that causes a cpu fault to the rom_entry offset
let illegal_instruction = [0xFF, 0xFF, 0xFF, 0xFF];
rom[rom_entry_offset..rom_entry_offset + illegal_instruction.len()]
.copy_from_slice(&illegal_instruction);
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
..Default::default()
},
BootParams::default(),
)
.unwrap();
hw.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() == GLOBAL_EXCEPTION);
let mcause = hw.soc_ifc().cptra_fw_extended_error_info().at(0).read();
let mscause = hw.soc_ifc().cptra_fw_extended_error_info().at(1).read();
let mepc = hw.soc_ifc().cptra_fw_extended_error_info().at(2).read();
let ra = hw.soc_ifc().cptra_fw_extended_error_info().at(3).read();
println!(
"ROM Global Exception mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X} ra=0x{:08X}",
mcause, mscause, mepc, ra,
);
// mcause must be illegal instruction
assert_eq!(mcause, 0x2);
// no mscause
assert_eq!(mscause, 0);
// mepc must be the value of the program counter at the failing instruction at rom_entry_offset
assert_eq!(mepc as usize, rom_entry_offset);
// return address won't be 0
assert_ne!(ra, 0);
#[cfg(feature = "verilator")]
assert!(hw.v.output.cptra_error_fatal);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_mldsa_verify.rs | rom/dev/tests/rom_integration_tests/test_mldsa_verify.rs | // Licensed under the Apache-2.0 license
use caliptra_common::mailbox_api::{
CommandId, MailboxReqHeader, MailboxRespHeader, MldsaVerifyReq,
};
use caliptra_hw_model::{Fuses, HwModel, ModelError};
use caliptra_kat::CaliptraError;
use ml_dsa::signature::Signer;
use ml_dsa::{KeyGen, MlDsa87};
use rand::thread_rng;
use zerocopy::{FromBytes, IntoBytes};
use crate::helpers;
#[test]
fn test_mldsa_verify_cmd() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), Default::default());
// Generate keypair and sign a message using ml-dsa
let mut rng = thread_rng();
let keypair = MlDsa87::key_gen(&mut rng);
let message = b"Hello, MLDSA verification test!";
let signature = keypair.signing_key().sign(message);
// Extract raw bytes for the public key and signature
let public_key_bytes = keypair.verifying_key().encode();
let signature_bytes = signature.encode();
// Pad signature to match expected size (4628 bytes)
let mut padded_signature = [0u8; 4628];
padded_signature[..signature_bytes.len()].copy_from_slice(&signature_bytes);
// First test: bad signature - should fail
let mut bad_signature = padded_signature;
bad_signature[0] ^= 0x01; // Flip one bit in the first byte
let mut bad_cmd = MldsaVerifyReq {
hdr: MailboxReqHeader { chksum: 0 },
pub_key: public_key_bytes.into(),
signature: bad_signature,
message_size: message.len() as u32,
message: {
let mut msg_array = [0u8; 4096]; // MAX_CMB_DATA_SIZE
msg_array[..message.len()].copy_from_slice(message);
msg_array
},
};
// Calculate checksum for bad signature test
bad_cmd.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::MLDSA87_SIGNATURE_VERIFY),
&bad_cmd.as_bytes()[core::mem::size_of_val(&bad_cmd.hdr.chksum)..],
);
// This should fail because the signature is invalid
let bad_response = hw
.mailbox_execute(
CommandId::MLDSA87_SIGNATURE_VERIFY.into(),
bad_cmd.as_bytes(),
)
.unwrap_err();
assert_eq!(
bad_response,
ModelError::MailboxCmdFailed(CaliptraError::ROM_MLDSA_VERIFY_FAILED.into())
);
// Second test: good signature - should succeed
let mut cmd = MldsaVerifyReq {
hdr: MailboxReqHeader { chksum: 0 },
pub_key: public_key_bytes.into(),
signature: padded_signature,
message_size: message.len() as u32,
message: {
let mut msg_array = [0u8; 4096]; // MAX_CMB_DATA_SIZE
msg_array[..message.len()].copy_from_slice(message);
msg_array
},
};
// Calculate checksum
cmd.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::MLDSA87_SIGNATURE_VERIFY),
&cmd.as_bytes()[core::mem::size_of_val(&cmd.hdr.chksum)..],
);
let response = hw
.mailbox_execute(CommandId::MLDSA87_SIGNATURE_VERIFY.into(), cmd.as_bytes())
.unwrap()
.unwrap();
let resp_hdr = MailboxRespHeader::ref_from_bytes(response.as_bytes()).unwrap();
// Verify response checksum
assert!(caliptra_common::checksum::verify_checksum(
resp_hdr.chksum,
0x0,
&response.as_bytes()[core::mem::size_of_val(&resp_hdr.chksum)..],
));
// Verify FIPS status
assert_eq!(
resp_hdr.fips_status,
MailboxRespHeader::FIPS_STATUS_APPROVED
);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/helpers.rs | rom/dev/tests/rom_integration_tests/helpers.rs | // Licensed under the Apache-2.0 license
use std::mem;
use caliptra_api::SocManager;
use caliptra_builder::{firmware, FwId, ImageOptions};
use caliptra_common::mailbox_api::CommandId;
use caliptra_common::{
memory_layout::{ROM_ORG, ROM_SIZE, ROM_STACK_ORG, ROM_STACK_SIZE, STACK_ORG, STACK_SIZE},
FMC_ORG, FMC_SIZE, RUNTIME_ORG, RUNTIME_SIZE,
};
use caliptra_drivers::InitDevIdCsrEnvelope;
use caliptra_error::CaliptraError;
use caliptra_hw_model::{
BootParams, CodeRange, Fuses, HwModel, ImageInfo, InitParams, SecurityState, StackInfo,
StackRange, SubsystemInitParams,
};
use caliptra_hw_model::{DefaultHwModel, DeviceLifecycle, ModelError};
use caliptra_image_types::{FwVerificationPqcKeyType, ImageBundle};
use zerocopy::TryFromBytes;
pub use caliptra_test::{default_soc_manifest_bytes, test_upload_firmware, DEFAULT_MCU_FW};
pub const PQC_KEY_TYPE: [FwVerificationPqcKeyType; 2] = [
FwVerificationPqcKeyType::LMS,
FwVerificationPqcKeyType::MLDSA,
];
pub const LIFECYCLES_PROVISIONED: [DeviceLifecycle; 2] =
[DeviceLifecycle::Manufacturing, DeviceLifecycle::Production];
pub const LIFECYCLES_ALL: [DeviceLifecycle; 3] = [
DeviceLifecycle::Unprovisioned,
DeviceLifecycle::Manufacturing,
DeviceLifecycle::Production,
];
pub fn wait_until_runtime(model: &mut DefaultHwModel) {
model.step_until(|m| m.soc_ifc().cptra_flow_status().read().ready_for_runtime());
}
pub fn assert_fatal_fw_load(
hw: &mut DefaultHwModel,
pqc_key_type: FwVerificationPqcKeyType,
data: &[u8],
err: CaliptraError,
) {
if hw.subsystem_mode() {
test_upload_firmware(hw, data, pqc_key_type);
hw.step_until_fatal_error(err.into(), 1000000)
} else {
assert_eq!(
ModelError::MailboxCmdFailed(err.into()),
hw.upload_firmware(data).unwrap_err()
);
}
}
pub fn rom_from_env() -> &'static FwId<'static> {
firmware::rom_from_env_fpga(cfg!(any(
feature = "fpga_subsystem",
feature = "fpga_realtime"
)))
}
// Start a firmware load via mailbox (non-blocking), used in tests that
// need to observe intermediate boot statuses during FIRMWARE_LOAD.
pub fn test_start_firmware_load(model: &mut DefaultHwModel, fw_image: &[u8]) {
model
.start_mailbox_execute(CommandId::FIRMWARE_LOAD.into(), fw_image)
.unwrap();
}
pub fn build_hw_model_and_image_bundle(
fuses: Fuses,
image_options: ImageOptions,
) -> (DefaultHwModel, ImageBundle) {
let image = build_image_bundle(image_options);
(build_hw_model(fuses), image)
}
pub fn build_hw_model(fuses: Fuses) -> DefaultHwModel {
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let image_info = vec![
ImageInfo::new(
StackRange::new(ROM_STACK_ORG + ROM_STACK_SIZE, ROM_STACK_ORG),
CodeRange::new(ROM_ORG, ROM_ORG + ROM_SIZE),
),
ImageInfo::new(
StackRange::new(STACK_ORG + STACK_SIZE, STACK_ORG),
CodeRange::new(FMC_ORG, FMC_ORG + FMC_SIZE),
),
ImageInfo::new(
StackRange::new(STACK_ORG + STACK_SIZE, STACK_ORG),
CodeRange::new(RUNTIME_ORG, RUNTIME_ORG + RUNTIME_SIZE),
),
];
let mut security_state = SecurityState::from(fuses.life_cycle as u32);
security_state.set_debug_locked(fuses.debug_locked);
caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state,
stack_info: Some(StackInfo::new(image_info)),
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: cfg!(feature = "fpga_subsystem"),
..Default::default()
},
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap()
}
pub fn build_image_bundle(image_options: ImageOptions) -> ImageBundle {
caliptra_builder::build_and_sign_image(
&firmware::FMC_WITH_UART,
if cfg!(feature = "fpga_subsystem") {
&firmware::APP_WITH_UART_FPGA
} else {
&firmware::APP_WITH_UART
},
image_options,
)
.unwrap()
}
/// This function matches the to_match string in the haystack string and returns the data
/// after the match until the next newline character.
///
/// # Arguments
///
/// * `to_match` - String to search for
/// * `haystack` - String to search in
pub fn get_data<'a>(to_match: &str, haystack: &'a str) -> &'a str {
let index = haystack
.find(to_match)
.unwrap_or_else(|| panic!("unable to find substr {to_match:?}"));
haystack[index + to_match.len()..]
.split('\n')
.next()
.unwrap_or("")
}
pub fn get_csr_envelop(hw: &mut DefaultHwModel) -> Result<InitDevIdCsrEnvelope, ModelError> {
hw.step_until(|m| m.soc_ifc().cptra_flow_status().read().idevid_csr_ready());
let mut txn = hw.wait_for_mailbox_receive()?;
let result = mem::take(&mut txn.req.data);
txn.respond_success();
hw.soc_ifc().cptra_dbg_manuf_service_reg().write(|_| 0);
let (csr_envelop, _) = InitDevIdCsrEnvelope::try_read_from_prefix(&result).unwrap();
Ok(csr_envelop)
}
pub fn change_dword_endianess(data: &mut [u8]) {
for idx in (0..data.len()).step_by(4) {
data.swap(idx, idx + 3);
data.swap(idx + 1, idx + 2);
}
}
#[cfg(test)]
mod tests {
use super::*;
const LOG: &str = "Foo bar baz \n\
[idev] ECC CSR = foo bar\n\
[idev] ECC CSR = wrong";
#[test]
fn test_get_data() {
assert_eq!("foo bar", get_data("[idev] ECC CSR = ", LOG));
assert_eq!("", get_data("CSR = wrong", LOG));
}
#[test]
#[should_panic(expected = "unable to find substr \"[idev] FOO = \"")]
fn test_get_data_not_found() {
assert_eq!("", get_data("[idev] FOO = ", LOG));
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_fips_hooks.rs | rom/dev/tests/rom_integration_tests/test_fips_hooks.rs | // Licensed under the Apache-2.0 license
use crate::helpers;
use caliptra_api::SocManager;
use caliptra_builder::firmware::{
APP_WITH_UART, APP_WITH_UART_FPGA, FMC_WITH_UART, ROM_WITH_FIPS_TEST_HOOKS,
ROM_WITH_FIPS_TEST_HOOKS_FPGA,
};
use caliptra_builder::ImageOptions;
use caliptra_drivers::CaliptraError;
use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams};
#[test]
fn test_fips_hook_exit() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let fpga = cfg!(any(feature = "fpga_realtime", feature = "fpga_subsystem"));
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(if fpga {
&ROM_WITH_FIPS_TEST_HOOKS_FPGA
} else {
&ROM_WITH_FIPS_TEST_HOOKS
})
.unwrap();
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let image_bundle = caliptra_builder::build_and_sign_image(
&FMC_WITH_UART,
if fpga {
&APP_WITH_UART
} else {
&APP_WITH_UART_FPGA
},
image_options,
)
.unwrap()
.to_bytes()
.unwrap();
let init_params = InitParams {
fuses,
rom: &rom,
..Default::default()
};
let boot_params = BootParams {
fw_image: Some(&image_bundle),
..Default::default()
};
let mut hw = caliptra_hw_model::new(init_params, boot_params).unwrap();
// Wait for fatal error
hw.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() != 0);
// Verify fatal code is correct
assert_eq!(
hw.soc_ifc().cptra_fw_error_fatal().read(),
u32::from(CaliptraError::ROM_GLOBAL_FIPS_HOOKS_ROM_EXIT)
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_wdt_activation_and_stoppage.rs | rom/dev/tests/rom_integration_tests/test_wdt_activation_and_stoppage.rs | // Licensed under the Apache-2.0 license
use crate::helpers;
use caliptra_api::SocManager;
use caliptra_builder::{
firmware::rom_tests::TEST_FMC_INTERACTIVE, firmware::APP_WITH_UART, ImageOptions,
};
use caliptra_common::RomBootStatus::{self, KatStarted};
use caliptra_hw_model::{BootParams, DeviceLifecycle, Fuses, HwModel, SecurityState};
#[test]
fn test_wdt_activation_and_stoppage() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Unprovisioned);
// Build the image we are going to send to ROM to load
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
image_options,
)
.unwrap();
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
fuses,
rom: &rom,
security_state,
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap();
if cfg!(feature = "fpga_realtime") {
// timer1_restart is only high for a few cycles; the realtime model
// timing is too imprecise that sort of check.
hw.step_until(|m| m.ready_for_fw());
} else {
// Ensure we are starting to count from zero.
hw.step_until(|m| m.soc_ifc().cptra_wdt_timer1_ctrl().read().timer1_restart());
}
// Make sure the wdt1 timer is enabled.
assert!(hw.soc_ifc().cptra_wdt_timer1_en().read().timer1_en());
// Upload the FW once ROM is at the right point
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
helpers::test_upload_firmware(&mut hw, &image_bundle.to_bytes().unwrap(), *pqc_key_type);
// Keep going until we jump to fake FMC
hw.step_until_output_contains("Running Caliptra FMC ...")
.unwrap();
// Make sure the wdt1 timer is enabled.
assert!(hw.soc_ifc().cptra_wdt_timer1_en().read().timer1_en());
}
}
#[test]
fn test_wdt_not_enabled_on_debug_part() {
let security_state = *SecurityState::default()
.set_debug_locked(false)
.set_device_lifecycle(DeviceLifecycle::Unprovisioned);
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Confirm security state is as expected.
assert!(!hw.soc_ifc().cptra_security_state().read().debug_locked());
hw.step_until_boot_status(RomBootStatus::CfiInitialized.into(), false);
hw.step_until_boot_status(KatStarted.into(), false);
// Make sure the wdt1 timer is disabled.
assert!(!hw.soc_ifc().cptra_wdt_timer1_en().read().timer1_en());
}
#[test]
fn test_rom_wdt_timeout() {
const WDT_EXPIRED: u32 = 0x0105000C;
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Unprovisioned);
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state,
..Default::default()
},
caliptra_hw_model::BootParams {
wdt_timeout_cycles: 1_000_000,
..Default::default()
},
)
.unwrap();
hw.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() == WDT_EXPIRED);
let mcause = hw.soc_ifc().cptra_fw_extended_error_info().at(0).read();
let mscause = hw.soc_ifc().cptra_fw_extended_error_info().at(1).read();
let mepc = hw.soc_ifc().cptra_fw_extended_error_info().at(2).read();
let ra = hw.soc_ifc().cptra_fw_extended_error_info().at(3).read();
let error_internal_intr_r = hw.soc_ifc().cptra_fw_extended_error_info().at(4).read();
println!(
"WDT Expiry mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X} ra=0x{:08X} error_internal_intr_r={:08X}",
mcause,
mscause,
mepc,
ra,
error_internal_intr_r,
);
// no mcause if wdt times out
assert_eq!(mcause, 0);
// no mscause if wdt times out
assert_eq!(mscause, 0);
// mepc is a memory address so won't be 0
assert_ne!(mepc, 0);
// return address won't be 0
assert_ne!(ra, 0);
// error_internal_intr_r must be 0b01000000 since the error_wdt_timer1_timeout_sts bit must be set
assert_eq!(error_internal_intr_r, 0b01000000);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_mailbox_errors.rs | rom/dev/tests/rom_integration_tests/test_mailbox_errors.rs | // Licensed under the Apache-2.0 license
use caliptra_builder::ImageOptions;
use caliptra_common::mailbox_api::{CommandId, MailboxReqHeader, StashMeasurementReq};
use caliptra_error::CaliptraError;
use caliptra_hw_model::{Fuses, HwModel, ModelError};
use zerocopy::IntoBytes;
use crate::helpers;
// Since the boot takes less than 30M cycles, we know something is wrong if
// we're stuck at the same state for that duration.
const MAX_WAIT_CYCLES: u32 = 30_000_000;
#[test]
fn test_unknown_command_is_fatal() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
// This command does not exist
// Calculate checksum for unknown command with empty payload (no bytes after header)
let checksum = caliptra_common::checksum::calc_checksum(
0xabcd_1234,
&[], // No payload after header
);
// Create final header with correct checksum
let header = MailboxReqHeader { chksum: checksum };
// This command does not exist
assert_eq!(
hw.mailbox_execute(0xabcd_1234, header.as_bytes()),
Err(ModelError::MailboxCmdFailed(
CaliptraError::FW_PROC_MAILBOX_INVALID_COMMAND.into()
))
);
hw.step_until_fatal_error(
CaliptraError::FW_PROC_MAILBOX_INVALID_COMMAND.into(),
MAX_WAIT_CYCLES,
);
}
#[test]
#[cfg(not(feature = "fpga_subsystem"))]
fn test_mailbox_command_aborted_after_handle_fatal_error() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
assert_eq!(
Err(ModelError::MailboxCmdFailed(
CaliptraError::FW_PROC_INVALID_IMAGE_SIZE.into()
)),
hw.upload_firmware(&[])
);
// Make sure a new attempt to upload firmware is rejected (even though this
// command would otherwise succeed)
//
// The original failure reason should still be in the register
assert_eq!(
hw.upload_firmware(&image_bundle.to_bytes().unwrap()),
Err(ModelError::MailboxCmdFailed(
CaliptraError::FW_PROC_INVALID_IMAGE_SIZE.into()
))
);
}
}
#[test]
fn test_mailbox_invalid_checksum() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
// Upload measurement.
let payload = StashMeasurementReq {
measurement: [0xdeadbeef_u32; 12].as_bytes().try_into().unwrap(),
hdr: MailboxReqHeader { chksum: 0 },
metadata: [0xAB; 4],
context: [0xCD; 48],
svn: 0xEF01,
};
// Calc and update checksum
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::STASH_MEASUREMENT),
&payload.as_bytes()[4..],
);
// Corrupt the checksum
let checksum = checksum - 1;
let payload = StashMeasurementReq {
hdr: MailboxReqHeader { chksum: checksum },
..payload
};
assert_eq!(
hw.mailbox_execute(CommandId::STASH_MEASUREMENT.into(), payload.as_bytes()),
Err(ModelError::MailboxCmdFailed(
CaliptraError::FW_PROC_MAILBOX_INVALID_CHECKSUM.into()
))
);
}
#[test]
fn test_mailbox_invalid_req_size_large() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
// Upload measurement.
let payload = StashMeasurementReq {
measurement: [0xdeadbeef_u32; 12].as_bytes().try_into().unwrap(),
hdr: MailboxReqHeader { chksum: 0 },
metadata: [0xAB; 4],
context: [0xCD; 48],
svn: 0xEF01,
};
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::CAPABILITIES),
&payload.as_bytes()[4..],
);
let payload = StashMeasurementReq {
hdr: MailboxReqHeader { chksum: checksum },
..payload
};
// Send too much data (stash measurement is bigger than capabilities)
assert_eq!(
hw.mailbox_execute(CommandId::CAPABILITIES.into(), payload.as_bytes()),
Err(ModelError::MailboxCmdFailed(
CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH.into()
))
);
}
#[test]
fn test_mailbox_invalid_req_size_small() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
// Upload measurement.
let payload = StashMeasurementReq {
measurement: [0xdeadbeef_u32; 12].as_bytes().try_into().unwrap(),
hdr: MailboxReqHeader { chksum: 0 },
metadata: [0xAB; 4],
context: [0xCD; 48],
svn: 0xEF01,
};
let payload_size = core::mem::size_of::<StashMeasurementReq>();
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::STASH_MEASUREMENT),
&payload.as_bytes()[4..payload_size - 4],
);
let payload = StashMeasurementReq {
hdr: MailboxReqHeader { chksum: checksum },
..payload
};
// Drop a dword
assert_eq!(
hw.mailbox_execute(
CommandId::STASH_MEASUREMENT.into(),
&payload.as_bytes()[..payload_size - 4]
),
Err(ModelError::MailboxCmdFailed(
CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH.into()
))
);
}
#[test]
fn test_mailbox_invalid_req_size_zero() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
assert_eq!(
hw.mailbox_execute(CommandId::CAPABILITIES.into(), &[]),
Err(ModelError::MailboxCmdFailed(
CaliptraError::FW_PROC_MAILBOX_INVALID_REQUEST_LENGTH.into()
))
);
}
#[test]
// Changing PAUSER not supported on sw emulator
#[cfg(any(feature = "verilator", feature = "fpga_realtime"))]
fn test_mailbox_reserved_pauser() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
// Set pauser to the reserved value
hw.set_axi_user(0xffffffff);
// Send anything
assert_eq!(
hw.mailbox_execute(0x0, &[]),
Err(ModelError::MailboxCmdFailed(
CaliptraError::FW_PROC_MAILBOX_RESERVED_PAUSER.into()
))
);
hw.step_until_fatal_error(
CaliptraError::FW_PROC_MAILBOX_RESERVED_PAUSER.into(),
MAX_WAIT_CYCLES,
);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_fmcalias_derivation.rs | rom/dev/tests/rom_integration_tests/test_fmcalias_derivation.rs | // Licensed under the Apache-2.0 license
use caliptra_api::SocManager;
use caliptra_builder::{
firmware::{
rom_tests::{TEST_FMC_INTERACTIVE, TEST_FMC_WITH_UART},
APP_WITH_UART,
},
ImageOptions,
};
use caliptra_common::mailbox_api::{CommandId, MailboxReqHeader, StashMeasurementReq};
use caliptra_common::RomBootStatus::ColdResetComplete;
use caliptra_common::RomBootStatus::*;
use caliptra_common::{FirmwareHandoffTable, FuseLogEntry, FuseLogEntryId};
use caliptra_common::{PcrLogEntry, PcrLogEntryId};
use caliptra_drivers::{pcr_log::MeasurementLogEntry, DataVault, PcrId};
use caliptra_error::CaliptraError;
use caliptra_hw_model::{
BootParams, Fuses, HwModel, InitParams, ModelError, SecurityState, SubsystemInitParams,
};
use caliptra_image_crypto::OsslCrypto as Crypto;
use caliptra_image_fake_keys::{OWNER_CONFIG, VENDOR_CONFIG_KEY_1};
use caliptra_image_gen::ImageGenerator;
use caliptra_image_types::{FwVerificationPqcKeyType, IMAGE_BYTE_SIZE};
use caliptra_test::swap_word_bytes;
use openssl::hash::{Hasher, MessageDigest};
use zerocopy::{FromBytes, IntoBytes, TryFromBytes};
use crate::helpers::{self, assert_fatal_fw_load};
const PCR0_AND_PCR1_EXTENDED_ID: u32 = (1 << PcrId::PcrId0 as u8) | (1 << PcrId::PcrId1 as u8);
const PCR31_EXTENDED_ID: u32 = 1 << PcrId::PcrId31 as u8;
#[test]
fn test_zero_firmware_size() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
// Zero-sized firmware.
let error = if hw.subsystem_mode() {
CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_MARKER_MISMATCH
} else {
CaliptraError::FW_PROC_INVALID_IMAGE_SIZE
};
assert_fatal_fw_load(&mut hw, FwVerificationPqcKeyType::LMS, &[], error);
assert_eq!(hw.soc_ifc().cptra_fw_error_fatal().read(), u32::from(error));
if !hw.subsystem_mode() {
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(LDevIdDerivationComplete)
);
}
}
#[test]
#[cfg(not(feature = "fpga_subsystem"))]
fn test_firmware_gt_max_size() {
// Firmware size > 128 KB.
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
// Manually put the oversize data in the mailbox because
// HwModel::upload_firmware won't let us.
assert!(!hw.soc_mbox().lock().read().lock());
hw.soc_mbox()
.cmd()
.write(|_| CommandId::FIRMWARE_LOAD.into());
hw.soc_mbox().dlen().write(|_| (IMAGE_BYTE_SIZE + 1) as u32);
for i in 0..((IMAGE_BYTE_SIZE + 1 + 3) / 4) {
hw.soc_mbox().datain().write(|_| i as u32);
}
hw.soc_mbox().execute().write(|w| w.execute(true));
while hw.soc_mbox().status().read().status().cmd_busy() {
hw.step();
}
hw.soc_mbox().execute().write(|w| w.execute(false));
assert_eq!(
hw.soc_ifc().cptra_fw_error_fatal().read(),
u32::from(CaliptraError::FW_PROC_INVALID_IMAGE_SIZE)
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(LDevIdDerivationComplete)
);
}
const PCR_COUNT: usize = 32;
const PCR_ENTRY_SIZE: usize = core::mem::size_of::<PcrLogEntry>();
const MEASUREMENT_ENTRY_SIZE: usize = core::mem::size_of::<MeasurementLogEntry>();
const MEASUREMENT_MAX_COUNT: usize = 8;
fn check_pcr_log_entry(
pcr_entry_arr: &[u8],
pcr_entry_index: usize,
entry_id: PcrLogEntryId,
pcr_ids: u32,
pcr_data: &[u8],
) {
let offset = pcr_entry_index * PCR_ENTRY_SIZE;
let (entry, _) = PcrLogEntry::ref_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap();
assert_eq!(entry.id, entry_id as u16);
assert_eq!(entry.pcr_ids, pcr_ids);
assert_eq!(entry.measured_data(), pcr_data);
}
fn check_measurement_log_entry(
measurement_entry_arr: &[u8],
measurement_entry_index: usize,
measurement_req: &StashMeasurementReq,
) {
let offset = measurement_entry_index * MEASUREMENT_ENTRY_SIZE;
let (entry, _) =
MeasurementLogEntry::ref_from_prefix(measurement_entry_arr[offset..].as_bytes()).unwrap();
assert_eq!(entry.pcr_entry.id, PcrLogEntryId::StashMeasurement as u16);
assert_eq!(entry.pcr_entry.pcr_ids, PCR31_EXTENDED_ID);
assert_eq!(
entry.pcr_entry.measured_data(),
&measurement_req.measurement
);
assert_eq!(entry.metadata, measurement_req.metadata);
assert_eq!(entry.context.as_bytes(), &measurement_req.context);
assert_eq!(entry.svn, measurement_req.svn);
}
#[test]
fn test_pcr_log() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options);
let vendor_pubkey_info_digest = gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap();
let owner_pubkey_digest = gen
.owner_pubkey_digest(&image_bundle.manifest.preamble)
.unwrap();
let fuses = Fuses {
anti_rollback_disable: true,
vendor_pk_hash: vendor_pubkey_info_digest,
owner_pk_hash: owner_pubkey_digest,
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
..Default::default()
},
BootParams::default(),
)
.unwrap();
const FW_SVN: u32 = 1;
let image_options = ImageOptions {
vendor_config: VENDOR_CONFIG_KEY_1,
fw_svn: FW_SVN,
pqc_key_type: *pqc_key_type,
..Default::default()
};
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
image_options,
)
.unwrap();
helpers::test_upload_firmware(&mut hw, &image_bundle.to_bytes().unwrap(), *pqc_key_type);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
let pcr_entry_arr = hw.mailbox_execute(0x1000_0000, &[]).unwrap().unwrap();
let device_lifecycle = hw
.soc_ifc()
.cptra_security_state()
.read()
.device_lifecycle();
let debug_locked = hw.soc_ifc().cptra_security_state().read().debug_locked();
let anti_rollback_disable = hw.soc_ifc().fuse_anti_rollback_disable().read().dis();
check_pcr_log_entry(
&pcr_entry_arr,
0,
PcrLogEntryId::DeviceStatus,
PCR0_AND_PCR1_EXTENDED_ID,
&[
device_lifecycle as u8,
debug_locked as u8,
anti_rollback_disable as u8,
VENDOR_CONFIG_KEY_1.ecc_key_idx as u8,
FW_SVN as u8,
0_u8,
VENDOR_CONFIG_KEY_1.pqc_key_idx as u8,
*pqc_key_type as u8,
true as u8,
],
);
check_pcr_log_entry(
&pcr_entry_arr,
1,
PcrLogEntryId::VendorPubKeyInfoHash,
PCR0_AND_PCR1_EXTENDED_ID,
swap_word_bytes(&vendor_pubkey_info_digest).as_bytes(),
);
check_pcr_log_entry(
&pcr_entry_arr,
2,
PcrLogEntryId::OwnerPubKeyHash,
PCR0_AND_PCR1_EXTENDED_ID,
swap_word_bytes(&owner_pubkey_digest).as_bytes(),
);
check_pcr_log_entry(
&pcr_entry_arr,
3,
PcrLogEntryId::FmcTci,
PCR0_AND_PCR1_EXTENDED_ID,
swap_word_bytes(&image_bundle.manifest.fmc.digest).as_bytes(),
);
}
}
#[test]
fn test_pcr_log_no_owner_key_digest_fuse() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options);
let owner_pubkey_digest = gen
.owner_pubkey_digest(&image_bundle.manifest.preamble)
.unwrap();
let fuses = Fuses {
anti_rollback_disable: true,
vendor_pk_hash: gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap(),
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap();
let image_options = ImageOptions {
vendor_config: VENDOR_CONFIG_KEY_1,
pqc_key_type: *pqc_key_type,
..Default::default()
};
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
image_options,
)
.unwrap();
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
*pqc_key_type,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
let pcr_entry_arr = hw.mailbox_execute(0x1000_0000, &[]).unwrap().unwrap();
let device_lifecycle = hw
.soc_ifc()
.cptra_security_state()
.read()
.device_lifecycle();
let debug_locked = hw.soc_ifc().cptra_security_state().read().debug_locked();
let anti_rollback_disable = hw.soc_ifc().fuse_anti_rollback_disable().read().dis();
check_pcr_log_entry(
&pcr_entry_arr,
0,
PcrLogEntryId::DeviceStatus,
PCR0_AND_PCR1_EXTENDED_ID,
&[
device_lifecycle as u8,
debug_locked as u8,
anti_rollback_disable as u8,
VENDOR_CONFIG_KEY_1.ecc_key_idx as u8,
0_u8,
0_u8,
VENDOR_CONFIG_KEY_1.pqc_key_idx as u8,
*pqc_key_type as u8,
false as u8,
],
);
check_pcr_log_entry(
&pcr_entry_arr,
2,
PcrLogEntryId::OwnerPubKeyHash,
PCR0_AND_PCR1_EXTENDED_ID,
swap_word_bytes(&owner_pubkey_digest).as_bytes(),
);
}
}
#[test]
fn test_pcr_log_fmc_fuse_svn() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options);
let vendor_pubkey_info_digest = gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap();
let owner_pubkey_digest = gen
.owner_pubkey_digest(&image_bundle.manifest.preamble)
.unwrap();
const FW_SVN: u32 = 3;
const FW_FUSE_SVN: u32 = 2;
let fuses = Fuses {
anti_rollback_disable: false,
vendor_pk_hash: vendor_pubkey_info_digest,
owner_pk_hash: owner_pubkey_digest,
fw_svn: [0x3, 0, 0, 0], // TODO: add tooling to make this more ergonomic.
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
fuses,
security_state: SecurityState::from(life_cycle as u32),
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
BootParams::default(),
)
.unwrap();
let image_options = ImageOptions {
vendor_config: VENDOR_CONFIG_KEY_1,
fw_svn: FW_SVN,
pqc_key_type: *pqc_key_type,
..Default::default()
};
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
image_options,
)
.unwrap();
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
*pqc_key_type,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
let pcr_entry_arr = hw.mailbox_execute(0x1000_0000, &[]).unwrap().unwrap();
let device_lifecycle = hw
.soc_ifc()
.cptra_security_state()
.read()
.device_lifecycle();
let debug_locked = hw.soc_ifc().cptra_security_state().read().debug_locked();
let anti_rollback_disable = hw.soc_ifc().fuse_anti_rollback_disable().read().dis();
check_pcr_log_entry(
&pcr_entry_arr,
0,
PcrLogEntryId::DeviceStatus,
PCR0_AND_PCR1_EXTENDED_ID,
&[
device_lifecycle as u8,
debug_locked as u8,
anti_rollback_disable as u8,
VENDOR_CONFIG_KEY_1.ecc_key_idx as u8,
FW_SVN as u8,
FW_FUSE_SVN as u8,
VENDOR_CONFIG_KEY_1.pqc_key_idx as u8,
*pqc_key_type as u8,
true as u8,
],
);
}
}
fn hash_pcr_log_entry(entry: &PcrLogEntry, pcr: &mut [u8; 48]) {
let mut hasher = Hasher::new(MessageDigest::sha384()).unwrap();
hasher.update(pcr).unwrap();
hasher.update(entry.measured_data()).unwrap();
let digest: &[u8] = &hasher.finish().unwrap();
pcr.copy_from_slice(digest);
}
// Computes the PCR from the log.
fn hash_pcr_log_entries(initial_pcr: &[u8; 48], pcr_entry_arr: &[u8], pcr_id: PcrId) -> [u8; 48] {
let mut offset: usize = 0;
let mut pcr: [u8; 48] = *initial_pcr;
assert_eq!(pcr_entry_arr.len() % PCR_ENTRY_SIZE, 0);
loop {
if offset == pcr_entry_arr.len() {
break;
}
let (entry, _) = PcrLogEntry::ref_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap();
offset += PCR_ENTRY_SIZE;
if (entry.pcr_ids & (1 << pcr_id as u8)) == 0 {
continue;
}
hash_pcr_log_entry(entry, &mut pcr);
}
pcr
}
fn hash_measurement_log_entries(measurement_entry_arr: &[u8]) -> [u8; 48] {
let mut offset: usize = 0;
let mut pcr = [0u8; 48];
assert_eq!(measurement_entry_arr.len() % MEASUREMENT_ENTRY_SIZE, 0);
loop {
if offset == measurement_entry_arr.len() {
break;
}
let (entry, _) =
MeasurementLogEntry::ref_from_prefix(measurement_entry_arr[offset..].as_bytes())
.unwrap();
offset += MEASUREMENT_ENTRY_SIZE;
hash_pcr_log_entry(&entry.pcr_entry, &mut pcr);
}
pcr
}
#[test]
fn test_pcr_log_across_update_reset() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options);
let vendor_pubkey_info_digest = gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap();
let owner_pubkey_digest = gen
.owner_pubkey_digest(&image_bundle.manifest.preamble)
.unwrap();
const FW_SVN: u32 = 2;
let fuses = Fuses {
anti_rollback_disable: false,
fw_svn: [1, 0, 0, 0],
vendor_pk_hash: vendor_pubkey_info_digest,
owner_pk_hash: owner_pubkey_digest,
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
BootParams::default(),
)
.unwrap();
let image_options = ImageOptions {
vendor_config: VENDOR_CONFIG_KEY_1,
fw_svn: FW_SVN,
pqc_key_type: *pqc_key_type,
..Default::default()
};
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
image_options,
)
.unwrap();
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
*pqc_key_type,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
let pcr_entry_arr = hw.mailbox_execute(0x1000_0000, &[]).unwrap().unwrap();
// Fetch and validate PCR values against the log.
let pcrs = hw.mailbox_execute(0x1000_0006, &[]).unwrap().unwrap();
assert_eq!(pcrs.len(), PCR_COUNT * 48);
let mut pcr0_from_hw: [u8; 48] = pcrs[0..48].try_into().unwrap();
let mut pcr1_from_hw: [u8; 48] = pcrs[48..96].try_into().unwrap();
helpers::change_dword_endianess(&mut pcr0_from_hw);
helpers::change_dword_endianess(&mut pcr1_from_hw);
let pcr0_from_log = hash_pcr_log_entries(&[0; 48], &pcr_entry_arr, PcrId::PcrId0);
let pcr1_from_log = hash_pcr_log_entries(&[0; 48], &pcr_entry_arr, PcrId::PcrId1);
assert_eq!(pcr0_from_log, pcr0_from_hw);
assert_eq!(pcr1_from_log, pcr1_from_hw);
// Ensure all other PCRs, except PCR0, PCR1 and PCR31, are empty.
for i in 2..(PCR_COUNT - 1) {
let offset = i * 48;
assert_eq!(pcrs[offset..offset + 48], [0; 48]);
}
// Trigger an update reset.
hw.mailbox_execute(
CommandId::FIRMWARE_LOAD.into(),
&image_bundle.to_bytes().unwrap(),
)
.unwrap();
hw.step_until_boot_status(UpdateResetComplete.into(), true);
let pcr_entry_arr = hw.mailbox_execute(0x1000_0000, &[]).unwrap().unwrap();
// Fetch and validate PCR values against the log. PCR0 should represent the
// latest boot, while PCR1 should represent the whole journey.
let pcrs_after_reset = hw.mailbox_execute(0x1000_0006, &[]).unwrap().unwrap();
assert_eq!(pcrs_after_reset.len(), PCR_COUNT * 48);
let mut new_pcr0_from_hw: [u8; 48] = pcrs_after_reset[0..48].try_into().unwrap();
let mut new_pcr1_from_hw: [u8; 48] = pcrs_after_reset[48..96].try_into().unwrap();
helpers::change_dword_endianess(&mut new_pcr0_from_hw);
helpers::change_dword_endianess(&mut new_pcr1_from_hw);
let new_pcr0_from_log = hash_pcr_log_entries(&[0; 48], &pcr_entry_arr, PcrId::PcrId0);
let new_pcr1_from_log = hash_pcr_log_entries(&pcr1_from_log, &pcr_entry_arr, PcrId::PcrId1);
assert_eq!(new_pcr0_from_log, new_pcr0_from_hw);
assert_eq!(new_pcr1_from_log, new_pcr1_from_hw);
// Also ensure PCR locks are configured correctly.
let reset_checks = hw.mailbox_execute(0x1000_0007, &[]).unwrap().unwrap();
assert_eq!(reset_checks, [0; 4]);
let pcrs_after_clear = hw.mailbox_execute(0x1000_0006, &[]).unwrap().unwrap();
assert_eq!(pcrs_after_clear, pcrs_after_reset);
}
}
#[test]
#[allow(deprecated)]
fn test_fuse_log() {
const FW_SVN: u32 = 4;
const FW_FUSE_SVN: u32 = 3;
let fuses = Fuses {
anti_rollback_disable: true,
fw_svn: [0x7, 0, 0, 0], // Value of FW_FUSE_SVN
fuse_pqc_key_type: FwVerificationPqcKeyType::LMS as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
..Default::default()
},
BootParams::default(),
)
.unwrap();
let image_options = ImageOptions {
vendor_config: VENDOR_CONFIG_KEY_1,
owner_config: Some(OWNER_CONFIG),
fmc_version: 0,
app_version: 0,
pqc_key_type: FwVerificationPqcKeyType::LMS,
fw_svn: FW_SVN,
};
let image_bundle =
caliptra_builder::build_and_sign_image(&TEST_FMC_WITH_UART, &APP_WITH_UART, image_options)
.unwrap();
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
FwVerificationPqcKeyType::LMS,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
let fuse_entry_arr = hw.mailbox_execute(0x1000_0002, &[]).unwrap().unwrap();
let mut fuse_log_entry_offset = 0;
// Check entry for VendorPubKeyIndex.
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(
fuse_log_entry.entry_id,
FuseLogEntryId::VendorEccPubKeyIndex as u32
);
assert_eq!(fuse_log_entry.log_data[0], VENDOR_CONFIG_KEY_1.ecc_key_idx);
// Validate that the ID is VendorPubKeyRevocation
fuse_log_entry_offset += core::mem::size_of::<FuseLogEntry>();
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(
fuse_log_entry.entry_id,
FuseLogEntryId::VendorEccPubKeyRevocation as u32
);
assert_eq!(fuse_log_entry.log_data[0], 0,);
// Validate the ColdBootFwSvn
fuse_log_entry_offset += core::mem::size_of::<FuseLogEntry>();
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(
fuse_log_entry.entry_id,
FuseLogEntryId::ColdBootFwSvn as u32
);
assert_eq!(fuse_log_entry.log_data[0], FW_SVN);
// Validate the ManifestReserved0
fuse_log_entry_offset += core::mem::size_of::<FuseLogEntry>();
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(
fuse_log_entry.entry_id,
FuseLogEntryId::ManifestReserved0 as u32
);
assert_eq!(fuse_log_entry.log_data[0], 0);
// Validate the _DeprecatedFuseFmcSvn
fuse_log_entry_offset += core::mem::size_of::<FuseLogEntry>();
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(
fuse_log_entry.entry_id,
FuseLogEntryId::_DeprecatedFuseFmcSvn as u32
);
assert_eq!(fuse_log_entry.log_data[0], FW_FUSE_SVN);
// Validate the ManifestFwSvn
fuse_log_entry_offset += core::mem::size_of::<FuseLogEntry>();
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(
fuse_log_entry.entry_id,
FuseLogEntryId::ManifestFwSvn as u32
);
assert_eq!(fuse_log_entry.log_data[0], FW_SVN);
// Validate the ManifestReserved1
fuse_log_entry_offset += core::mem::size_of::<FuseLogEntry>();
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(
fuse_log_entry.entry_id,
FuseLogEntryId::ManifestReserved1 as u32
);
assert_eq!(fuse_log_entry.log_data[0], 0);
// Validate the FuseFwSvn
fuse_log_entry_offset += core::mem::size_of::<FuseLogEntry>();
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(fuse_log_entry.entry_id, FuseLogEntryId::FuseFwSvn as u32);
assert_eq!(fuse_log_entry.log_data[0], FW_FUSE_SVN);
// Validate the VendorPqcPubKeyIndex
fuse_log_entry_offset += core::mem::size_of::<FuseLogEntry>();
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(
fuse_log_entry.entry_id,
FuseLogEntryId::VendorPqcPubKeyIndex as u32
);
assert_eq!(fuse_log_entry.log_data[0], VENDOR_CONFIG_KEY_1.pqc_key_idx);
// Validate that the ID is VendorPubKeyRevocation
fuse_log_entry_offset += core::mem::size_of::<FuseLogEntry>();
let (fuse_log_entry, _) =
FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap();
assert_eq!(
fuse_log_entry.entry_id,
FuseLogEntryId::VendorPqcPubKeyRevocation as u32
);
assert_eq!(fuse_log_entry.log_data[0], 0,);
}
#[test]
fn test_fht_info() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_WITH_UART,
&APP_WITH_UART,
image_options,
)
.unwrap();
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
*pqc_key_type,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
let data = hw.mailbox_execute(0x1000_0003, &[]).unwrap().unwrap();
let fht = FirmwareHandoffTable::try_ref_from_bytes(data.as_bytes()).unwrap();
assert_eq!(fht.ecc_ldevid_tbs_size, 566);
assert_eq!(fht.ecc_fmcalias_tbs_size, 767);
}
}
#[test]
fn test_check_rom_cold_boot_status_reg() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_WITH_UART,
&APP_WITH_UART,
image_options,
)
.unwrap();
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
*pqc_key_type,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
let data_vault = hw.mailbox_execute(0x1000_0005, &[]).unwrap().unwrap();
let (data_vault, _) = DataVault::ref_from_prefix(data_vault.as_bytes()).unwrap();
assert_eq!(
data_vault.rom_cold_boot_status(),
u32::from(ColdResetComplete)
);
}
}
#[test]
fn test_upload_single_measurement() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
image_options,
)
.unwrap();
// Upload measurement.
let measurement = StashMeasurementReq {
measurement: [0xdeadbeef_u32; 12].as_bytes().try_into().unwrap(),
hdr: MailboxReqHeader { chksum: 0 },
metadata: [0xAB; 4],
context: [0xCD; 48],
svn: 0xEF01,
};
// Calc and update checksum
let checksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::STASH_MEASUREMENT),
&measurement.as_bytes()[4..],
);
let measurement = StashMeasurementReq {
hdr: MailboxReqHeader { chksum: checksum },
..measurement
};
hw.upload_measurement(measurement.as_bytes()).unwrap();
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
*pqc_key_type,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
// Check if the measurement was present in the measurement log.
let measurement_log = hw.mailbox_execute(0x1000_000A, &[]).unwrap().unwrap();
assert_eq!(measurement_log.len(), MEASUREMENT_ENTRY_SIZE);
check_measurement_log_entry(&measurement_log, 0, &measurement);
// Get PCR31
let pcr31 = hw.mailbox_execute(0x1000_0009, &[]).unwrap().unwrap();
// Check that the measurement was extended to PCR31.
let expected_pcr = hash_measurement_log_entries(&measurement_log);
assert_eq!(pcr31.as_bytes(), expected_pcr);
let data = hw.mailbox_execute(0x1000_0003, &[]).unwrap().unwrap();
let (fht, _) = FirmwareHandoffTable::try_ref_from_prefix(data.as_bytes()).unwrap();
assert_eq!(fht.meas_log_index, 1);
}
}
#[test]
fn test_upload_measurement_limit() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap();
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_ldev_cert_cmd.rs | rom/dev/tests/rom_integration_tests/test_ldev_cert_cmd.rs | // Licensed under the Apache-2.0 license
use caliptra_api::mailbox::GetLdevCertResp;
use caliptra_api::SocManager;
use caliptra_common::mailbox_api::{CommandId, MailboxReqHeader};
use caliptra_hw_model::{DefaultHwModel, Fuses, HwModel};
use caliptra_image_types::FwVerificationPqcKeyType;
use openssl::x509::X509;
use zerocopy::IntoBytes;
use crate::helpers;
const RT_READY_FOR_COMMANDS: u32 = 0x600;
fn get_ldev_ecc_cert(model: &mut DefaultHwModel) -> GetLdevCertResp {
let payload = MailboxReqHeader {
chksum: caliptra_common::checksum::calc_checksum(
u32::from(CommandId::GET_LDEV_ECC384_CERT),
&[],
),
};
let resp = model
.mailbox_execute(
u32::from(CommandId::GET_LDEV_ECC384_CERT),
payload.as_bytes(),
)
.unwrap()
.unwrap();
assert!(resp.len() <= std::mem::size_of::<GetLdevCertResp>());
let mut ldev_resp = GetLdevCertResp::default();
ldev_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp);
ldev_resp
}
fn get_ldev_mldsa_cert(model: &mut DefaultHwModel) -> GetLdevCertResp {
let payload = MailboxReqHeader {
chksum: caliptra_common::checksum::calc_checksum(
u32::from(CommandId::GET_LDEV_MLDSA87_CERT),
&[],
),
};
let resp = model
.mailbox_execute(
u32::from(CommandId::GET_LDEV_MLDSA87_CERT),
payload.as_bytes(),
)
.unwrap()
.unwrap();
assert!(resp.len() <= std::mem::size_of::<GetLdevCertResp>());
let mut ldev_resp = GetLdevCertResp::default();
ldev_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp);
ldev_resp
}
#[test]
fn test_ldev_ecc384_cert() {
let (mut hw, image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), Default::default());
// Step till we are ready for mailbox processing
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
// Get LDev ECC384 cert from ROM
let ldev_resp = get_ldev_ecc_cert(&mut hw);
let ldev_cert_rom: X509 =
X509::from_der(&ldev_resp.data[..ldev_resp.data_size as usize]).unwrap();
// Step till RT is ready for commands
helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
FwVerificationPqcKeyType::MLDSA,
);
hw.step_until_boot_status(RT_READY_FOR_COMMANDS, true);
// Get the LDev ECC384 cert from RT
let ldev_resp = get_ldev_ecc_cert(&mut hw);
let ldev_cert_rt: X509 =
X509::from_der(&ldev_resp.data[..ldev_resp.data_size as usize]).unwrap();
// Compare the two certs
assert_eq!(
ldev_cert_rom.to_der().unwrap(),
ldev_cert_rt.to_der().unwrap()
);
}
#[test]
fn test_ldev_mldsa87_cert() {
let (mut hw, image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), Default::default());
// Step till we are ready for mailbox processing
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
// Get LDev MLDSA87 cert from ROM
let ldev_resp = get_ldev_mldsa_cert(&mut hw);
let ldev_cert_rom: X509 =
X509::from_der(&ldev_resp.data[..ldev_resp.data_size as usize]).unwrap();
// Step till RT is ready for commands
helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
FwVerificationPqcKeyType::MLDSA,
);
hw.step_until_boot_status(RT_READY_FOR_COMMANDS, true);
// Get the LDev MLDSA87 cert from RT
let ldev_resp = get_ldev_mldsa_cert(&mut hw);
let ldev_cert_rt: X509 =
X509::from_der(&ldev_resp.data[..ldev_resp.data_size as usize]).unwrap();
// Compare the two certs
assert_eq!(
ldev_cert_rom.to_der().unwrap(),
ldev_cert_rt.to_der().unwrap()
);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_panic_missing.rs | rom/dev/tests/rom_integration_tests/test_panic_missing.rs | // Licensed under the Apache-2.0 license
#[test]
fn test_panic_missing() {
let rom_elf = caliptra_builder::build_firmware_elf(crate::helpers::rom_from_env()).unwrap();
let symbols = caliptra_builder::elf_symbols(&rom_elf).unwrap();
if symbols.iter().any(|s| s.name.contains("panic_is_possible")) {
panic!(
"The caliptra ROM contains the panic_is_possible symbol, which is not allowed. \
Please remove any code that might panic."
)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_derive_stable_key.rs | rom/dev/tests/rom_integration_tests/test_derive_stable_key.rs | // Licensed under the Apache-2.0 license
use crate::helpers;
use aes_gcm::{aead::AeadMutInPlace, Key};
use caliptra_api::mailbox::{
CmDeriveStableKeyReq, CmDeriveStableKeyResp, CmHashAlgorithm, CmHmacReq, CmHmacResp,
CmRandomGenerateReq, CmRandomGenerateResp, CmStableKeyType, MailboxReq,
MailboxRespHeaderVarSize, CMK_SIZE_BYTES, CM_STABLE_KEY_INFO_SIZE_BYTES, MAX_CMB_DATA_SIZE,
};
use caliptra_builder::{
firmware::{rom_tests::TEST_FMC_INTERACTIVE, APP_WITH_UART},
ImageOptions,
};
use caliptra_common::{
crypto::{EncryptedCmk, UnencryptedCmk, UNENCRYPTED_CMK_SIZE_BYTES},
mailbox_api::{CommandId, MailboxReqHeader, MailboxRespHeader},
RomBootStatus::ColdResetComplete,
};
use caliptra_error::CaliptraError;
use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams, ModelError};
use caliptra_image_types::FwVerificationPqcKeyType;
use hmac::{Hmac, Mac};
use rand::{rngs::StdRng, RngCore, SeedableRng};
use sha2::Sha512;
use zerocopy::{FromBytes, IntoBytes};
const DOT_KEY_TYPES: [CmStableKeyType; 2] = [CmStableKeyType::IDevId, CmStableKeyType::LDevId];
#[cfg(feature = "fpga_subsystem")]
pub(crate) const HW_MODEL_MODES_SUBSYSTEM: [bool; 1] = [true];
#[cfg(feature = "fpga_realtime")]
pub(crate) const HW_MODEL_MODES_SUBSYSTEM: [bool; 1] = [false];
#[cfg(not(any(feature = "fpga_realtime", feature = "fpga_subsystem")))]
pub(crate) const HW_MODEL_MODES_SUBSYSTEM: [bool; 2] = [false, true];
fn decrypt_cmk(key: &[u8], cmk: &EncryptedCmk) -> Option<UnencryptedCmk> {
use aes_gcm::KeyInit;
let key: &Key<aes_gcm::Aes256Gcm> = key.into();
let mut cipher = aes_gcm::Aes256Gcm::new(key);
let mut buffer = cmk.ciphertext.to_vec();
let iv: &[u8; 12] = cmk.iv.as_bytes().try_into().unwrap();
let gcm_tag: &[u8; 16] = cmk.gcm_tag.as_bytes().try_into().unwrap();
match cipher.decrypt_in_place_detached(iv.into(), &[], &mut buffer, gcm_tag.into()) {
Ok(_) => UnencryptedCmk::ref_from_bytes(&buffer).ok().cloned(),
Err(_) => None,
}
}
fn hmac512(key: &[u8], data: &[u8]) -> [u8; 64] {
let mut mac = Hmac::<Sha512>::new_from_slice(key).unwrap();
mac.update(data);
let result = mac.finalize();
result.into_bytes().into()
}
fn parse_encrypted_cmk(bytes: &[u8]) -> EncryptedCmk {
assert!(
bytes.len() >= size_of::<EncryptedCmk>(),
"Byte slice too small"
);
let domain = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
let domain_metadata = bytes[4..20].try_into().unwrap();
let iv: [u8; 12] = bytes[20..32].try_into().unwrap();
let ciphertext = bytes[32..(32 + UNENCRYPTED_CMK_SIZE_BYTES)]
.try_into()
.unwrap();
let gcm_tag_start = 32 + UNENCRYPTED_CMK_SIZE_BYTES;
let gcm_tag: [u8; 16] = bytes[gcm_tag_start..(gcm_tag_start + 16)]
.try_into()
.unwrap();
EncryptedCmk {
domain,
domain_metadata,
iv: iv.into(),
ciphertext,
gcm_tag: gcm_tag.into(),
}
}
#[test]
fn test_derive_stable_key() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
for key_type in DOT_KEY_TYPES.iter() {
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
ImageOptions::default(),
)
.unwrap()
.to_bytes()
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams::default(),
)
.unwrap();
if subsystem_mode != hw.subsystem_mode() {
// skip this combination if the FPGA doesn't support this mode
continue;
}
let mut request = CmDeriveStableKeyReq {
hdr: MailboxReqHeader { chksum: 0 },
key_type: (*key_type).into(),
info: [0u8; CM_STABLE_KEY_INFO_SIZE_BYTES],
};
request.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::CM_DERIVE_STABLE_KEY),
&request.as_bytes()[core::mem::size_of_val(&request.hdr.chksum)..],
);
let response = hw
.mailbox_execute(CommandId::CM_DERIVE_STABLE_KEY.into(), request.as_bytes())
.unwrap()
.unwrap();
let resp = CmDeriveStableKeyResp::ref_from_bytes(response.as_bytes()).unwrap();
let expected_fips_status = MailboxRespHeader::FIPS_STATUS_APPROVED;
assert_eq!(resp.hdr.fips_status, expected_fips_status);
// Verify response checksum
assert!(caliptra_common::checksum::verify_checksum(
resp.hdr.chksum,
0x0,
&resp.as_bytes()[core::mem::size_of_val(&resp.hdr.chksum)..],
));
// Verify FIPS status
assert_eq!(resp.hdr.fips_status, expected_fips_status);
let cmk = resp.cmk.0;
assert_ne!(cmk, [0u8; CMK_SIZE_BYTES]);
let seed_bytes = [1u8; 32];
let mut seeded_rng = StdRng::from_seed(seed_bytes);
let mut data = vec![0u8; MAX_CMB_DATA_SIZE];
seeded_rng.fill_bytes(&mut data);
let mut cm_hmac = CmHmacReq {
cmk: resp.cmk.clone(),
hash_algorithm: CmHashAlgorithm::Sha512.into(),
data_size: MAX_CMB_DATA_SIZE as u32,
..Default::default()
};
cm_hmac.data[..MAX_CMB_DATA_SIZE].copy_from_slice(&data);
cm_hmac.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::CM_HMAC),
&cm_hmac.as_bytes()[core::mem::size_of_val(&cm_hmac.hdr.chksum)..],
);
let response = hw
.mailbox_execute(CommandId::CM_HMAC.into(), cm_hmac.as_bytes())
.unwrap()
.unwrap();
let resp = CmHmacResp::ref_from_bytes(response.as_bytes()).unwrap();
assert_eq!(resp.hdr.hdr.fips_status, expected_fips_status);
let expected_mac = resp.mac;
crate::helpers::test_upload_firmware(
&mut hw,
image_bundle.as_bytes(),
FwVerificationPqcKeyType::MLDSA,
);
hw.step_until_output_contains("Running Caliptra FMC ...")
.unwrap();
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
let result = hw.mailbox_execute(0x1000_0012, &[]);
assert!(result.is_ok(), "{:?}", result);
let aes_key = result.unwrap().unwrap();
let cmk = parse_encrypted_cmk(&cmk);
let cmk = decrypt_cmk(&aes_key, &cmk).unwrap();
let computed_mac = hmac512(&cmk.key_material, &data);
assert_eq!(computed_mac, expected_mac);
}
}
}
#[test]
fn test_derive_stable_key_invalid_key_type() {
let (mut hw, _) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
let mut request = CmDeriveStableKeyReq {
hdr: MailboxReqHeader { chksum: 0 },
key_type: CmStableKeyType::Reserved.into(),
info: [0u8; CM_STABLE_KEY_INFO_SIZE_BYTES],
};
request.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::CM_DERIVE_STABLE_KEY),
&request.as_bytes()[core::mem::size_of_val(&request.hdr.chksum)..],
);
assert_eq!(
hw.mailbox_execute(CommandId::CM_DERIVE_STABLE_KEY.into(), request.as_bytes()),
Err(ModelError::MailboxCmdFailed(
CaliptraError::DOT_INVALID_KEY_TYPE.into()
))
);
}
#[test]
fn test_random_generate() {
let (mut model, _) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
// check too large of an input
let mut cm_random_generate = MailboxReq::CmRandomGenerate(CmRandomGenerateReq {
hdr: MailboxReqHeader::default(),
size: u32::MAX,
});
cm_random_generate.populate_chksum().unwrap();
model
.mailbox_execute(
u32::from(CommandId::CM_RANDOM_GENERATE),
cm_random_generate.as_bytes().unwrap(),
)
.expect_err("Should have been an error");
// 0 bytes
let mut cm_random_generate = MailboxReq::CmRandomGenerate(CmRandomGenerateReq {
hdr: MailboxReqHeader::default(),
size: 0,
});
cm_random_generate.populate_chksum().unwrap();
let resp_bytes = model
.mailbox_execute(
u32::from(CommandId::CM_RANDOM_GENERATE),
cm_random_generate.as_bytes().unwrap(),
)
.unwrap()
.expect("We should have received a response");
let mut resp = CmRandomGenerateResp::default();
const VAR_HEADER_SIZE: usize = size_of::<MailboxRespHeaderVarSize>();
resp.hdr = MailboxRespHeaderVarSize::read_from_bytes(&resp_bytes[..VAR_HEADER_SIZE]).unwrap();
assert_eq!(resp.hdr.data_len, 0);
assert!(resp_bytes[VAR_HEADER_SIZE..].iter().all(|&x| x == 0));
// 1 byte
let mut cm_random_generate = MailboxReq::CmRandomGenerate(CmRandomGenerateReq {
hdr: MailboxReqHeader::default(),
size: 1,
});
cm_random_generate.populate_chksum().unwrap();
let resp_bytes = model
.mailbox_execute(
u32::from(CommandId::CM_RANDOM_GENERATE),
cm_random_generate.as_bytes().unwrap(),
)
.unwrap()
.expect("We should have received a response");
let mut resp = CmRandomGenerateResp {
hdr: MailboxRespHeaderVarSize::read_from_bytes(&resp_bytes[..VAR_HEADER_SIZE]).unwrap(),
..Default::default()
};
let len = resp.hdr.data_len as usize;
assert_eq!(len, 1);
resp.data[..len].copy_from_slice(&resp_bytes[VAR_HEADER_SIZE..VAR_HEADER_SIZE + len]);
// We can't check if it is non-zero because it will randomly be 0 sometimes.
for req_len in [47usize, 48, 1044] {
let mut cm_random_generate = MailboxReq::CmRandomGenerate(CmRandomGenerateReq {
hdr: MailboxReqHeader::default(),
size: req_len as u32,
});
cm_random_generate.populate_chksum().unwrap();
let resp_bytes = model
.mailbox_execute(
u32::from(CommandId::CM_RANDOM_GENERATE),
cm_random_generate.as_bytes().unwrap(),
)
.unwrap()
.expect("We should have received a response");
let mut resp = CmRandomGenerateResp {
hdr: MailboxRespHeaderVarSize::read_from_bytes(&resp_bytes[..VAR_HEADER_SIZE]).unwrap(),
..Default::default()
};
let len = resp.hdr.data_len as usize;
assert_eq!(len, req_len);
resp.data[..len].copy_from_slice(&resp_bytes[VAR_HEADER_SIZE..VAR_HEADER_SIZE + len]);
assert!(
resp.data[..len]
.iter()
.copied()
.reduce(|a, b| (a | b))
.unwrap()
!= 0
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_ocp_lock.rs | rom/dev/tests/rom_integration_tests/test_ocp_lock.rs | // Licensed under the Apache-2.0 license
use caliptra_api::mailbox::{
MailboxReq, OcpLockReportHekMetadataReq, OcpLockReportHekMetadataResp,
OcpLockReportHekMetadataRespFlags,
};
use caliptra_builder::firmware::ROM_FPGA_WITH_UART;
use caliptra_common::mailbox_api::{CommandId, MailboxReqHeader};
use caliptra_drivers::{CaliptraError, HekSeedState};
use caliptra_hw_model::{DeviceLifecycle, Fuses, HwModel, ModelError, SecurityState};
use zerocopy::{FromBytes, IntoBytes};
const ALL_HEK_SEED_STATES: &[HekSeedState] = &[
HekSeedState::Empty,
HekSeedState::Zeroized,
HekSeedState::Corrupted,
HekSeedState::Programmed,
HekSeedState::Unerasable,
];
/// NOTE: These tests assume that `ss_ocp_lock_en` is set to true in the Caliptra bitstream.
#[test]
fn test_hek_seed_states() {
// Split by lifecycle to avoid booting Caliptra for each test iteration.
// Test PROD HEK seed states that allow HEK usage
hek_seed_state_helper(
DeviceLifecycle::Production,
&[HekSeedState::Programmed, HekSeedState::Unerasable],
true,
[0xABDEu32; 8],
);
// Test PROD HEK seed states that disallow HEK usage
hek_seed_state_helper(
DeviceLifecycle::Production,
&[
HekSeedState::Empty,
HekSeedState::Zeroized,
HekSeedState::Corrupted,
],
false,
[0xABDEu32; 8],
);
// Manufacturing and Unprovisioned LC should allow HEK usage in all HEK seed states.
hek_seed_state_helper(
DeviceLifecycle::Manufacturing,
ALL_HEK_SEED_STATES,
true,
[0xABDEu32; 8],
);
hek_seed_state_helper(
DeviceLifecycle::Unprovisioned,
ALL_HEK_SEED_STATES,
true,
[0xABDEu32; 8],
);
// A programmed HEK seed cannot be all zeros
hek_seed_state_helper(
DeviceLifecycle::Production,
&[HekSeedState::Programmed],
false,
[0; 8],
);
// A programmed HEK seed cannot be all 1s
hek_seed_state_helper(
DeviceLifecycle::Production,
&[HekSeedState::Programmed],
false,
[u32::MAX; 8],
);
}
#[test]
fn test_invalid_hek_seed_state() {
let rom = caliptra_builder::build_firmware_rom(&ROM_FPGA_WITH_UART).unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Skip this test if HW does not support OCP LOCK.
if !hw.subsystem_mode() || !hw.supports_ocp_lock() {
return;
}
let first_invalid_hek_seed_state: u16 = u16::from(HekSeedState::Unerasable) + 1;
// Check that an unknown HEK Seed state returns an error
for seed_state in first_invalid_hek_seed_state..first_invalid_hek_seed_state + 3 {
let mut cmd = MailboxReq::OcpLockReportHekMetadata(OcpLockReportHekMetadataReq {
hdr: MailboxReqHeader { chksum: 0 },
seed_state,
..Default::default()
});
cmd.populate_chksum().unwrap();
let response = hw.mailbox_execute(
CommandId::OCP_LOCK_REPORT_HEK_METADATA.into(),
cmd.as_bytes().unwrap(),
);
assert_eq!(
response.unwrap_err(),
ModelError::MailboxCmdFailed(
CaliptraError::DRIVER_OCP_LOCK_COLD_RESET_INVALID_HEK_SEED.into(),
)
);
}
}
fn hek_seed_state_helper(
lifecycle: DeviceLifecycle,
seed_states: &[HekSeedState],
expects_hek_available: bool,
hek_seed: [u32; 8],
) {
let rom = caliptra_builder::build_firmware_rom(&ROM_FPGA_WITH_UART).unwrap();
let mut hw = caliptra_hw_model::new(
caliptra_hw_model::InitParams {
rom: &rom,
security_state: *SecurityState::default().set_device_lifecycle(lifecycle),
fuses: Fuses {
hek_seed,
..Default::default()
},
..Default::default()
},
caliptra_hw_model::BootParams::default(),
)
.unwrap();
// Skip this test if HW does not support OCP LOCK.
if !hw.subsystem_mode() || !hw.supports_ocp_lock() {
return;
}
for seed_state in seed_states {
let mut cmd = MailboxReq::OcpLockReportHekMetadata(OcpLockReportHekMetadataReq {
hdr: MailboxReqHeader { chksum: 0 },
seed_state: seed_state.into(),
..Default::default()
});
cmd.populate_chksum().unwrap();
let response = hw
.mailbox_execute(
CommandId::OCP_LOCK_REPORT_HEK_METADATA.into(),
cmd.as_bytes().unwrap(),
)
.unwrap()
.unwrap();
let response = OcpLockReportHekMetadataResp::ref_from_bytes(response.as_bytes()).unwrap();
assert_eq!(
response
.flags
.contains(OcpLockReportHekMetadataRespFlags::HEK_AVAILABLE),
expects_hek_available
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_dice_derivations.rs | rom/dev/tests/rom_integration_tests/test_dice_derivations.rs | // Licensed under the Apache-2.0 license
use caliptra_api::SocManager;
use caliptra_builder::firmware::rom_tests::TEST_FMC_WITH_UART;
use caliptra_builder::firmware::APP_WITH_UART;
use caliptra_builder::ImageOptions;
use caliptra_common::mailbox_api::CommandId;
use caliptra_common::RomBootStatus::*;
use caliptra_hw_model::BootParams;
use caliptra_hw_model::Fuses;
use caliptra_hw_model::HwModel;
use caliptra_hw_model::InitParams;
use crate::helpers;
#[cfg_attr(any(feature = "fpga_realtime", feature = "fpga_subsystem"), ignore)] // The FPGA is too fast for the host to catch these state transitions.
#[test]
fn test_cold_reset_status_reporting() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
hw.step_until_boot_status(CfiInitialized.into(), false);
hw.step_until_boot_status(KatStarted.into(), false);
hw.step_until_boot_status(KatComplete.into(), false);
hw.step_until_boot_status(ColdResetStarted.into(), false);
hw.step_until_boot_status(IDevIdDecryptUdsComplete.into(), false);
hw.step_until_boot_status(IDevIdDecryptFeComplete.into(), false);
hw.step_until_boot_status(IDevIdClearDoeSecretsComplete.into(), false);
hw.step_until_boot_status(IDevIdCdiDerivationComplete.into(), false);
hw.step_until_boot_status(IDevIdKeyPairDerivationComplete.into(), false);
hw.step_until_boot_status(IDevIdSubjIdSnGenerationComplete.into(), false);
hw.step_until_boot_status(IDevIdSubjKeyIdGenerationComplete.into(), false);
hw.step_until_boot_status(IDevIdDerivationComplete.into(), false);
hw.step_until_boot_status(LDevIdCdiDerivationComplete.into(), false);
hw.step_until_boot_status(LDevIdKeyPairDerivationComplete.into(), false);
hw.step_until_boot_status(LDevIdSubjIdSnGenerationComplete.into(), false);
hw.step_until_boot_status(LDevIdSubjKeyIdGenerationComplete.into(), false);
hw.step_until_boot_status(LDevIdCertSigGenerationComplete.into(), false);
hw.step_until_boot_status(LDevIdDerivationComplete.into(), false);
// Wait for uploading firmware.
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
// Manually put the firmware in the mailbox because
// HwModel::upload_firmware returns only when the transaction is complete.
// This is too late for this test.
let buf: &[u8] = &image_bundle.to_bytes().unwrap();
assert!(!hw.soc_mbox().lock().read().lock());
hw.soc_mbox()
.cmd()
.write(|_| CommandId::FIRMWARE_LOAD.into());
hw.soc_mbox().dlen().write(|_| buf.len() as u32);
let mut remaining = buf;
while remaining.len() >= 4 {
// Panic is impossible because the subslice is always 4 bytes
let word = u32::from_le_bytes(remaining[..4].try_into().unwrap());
hw.soc_mbox().datain().write(|_| word);
remaining = &remaining[4..];
}
if !remaining.is_empty() {
let mut word_bytes = [0u8; 4];
word_bytes[..remaining.len()].copy_from_slice(remaining);
let word = u32::from_le_bytes(word_bytes);
hw.soc_mbox().datain().write(|_| word);
}
hw.soc_mbox().execute().write(|w| w.execute(true));
hw.step_until_boot_status(FwProcessorDownloadImageComplete.into(), false);
hw.step_until_boot_status(FwProcessorManifestLoadComplete.into(), false);
hw.step_until_boot_status(FwProcessorImageVerificationComplete.into(), false);
hw.step_until_boot_status(FwProcessorPopulateDataVaultComplete.into(), false);
hw.step_until_boot_status(FwProcessorExtendPcrComplete.into(), false);
hw.step_until_boot_status(FwProcessorLoadImageComplete.into(), false);
hw.step_until_boot_status(FwProcessorFirmwareDownloadTxComplete.into(), false);
hw.step_until_boot_status(FwProcessorCalculateKeyLadderComplete.into(), false);
hw.step_until_boot_status(FwProcessorComplete.into(), false);
hw.step_until_boot_status(FmcAliasDeriveCdiComplete.into(), false);
hw.step_until_boot_status(FmcAliasKeyPairDerivationComplete.into(), false);
hw.step_until_boot_status(FmcAliasSubjIdSnGenerationComplete.into(), false);
hw.step_until_boot_status(FmcAliasSubjKeyIdGenerationComplete.into(), false);
hw.step_until_boot_status(FmcAliasCertSigGenerationComplete.into(), false);
hw.step_until_boot_status(FmcAliasDerivationComplete.into(), false);
hw.step_until_boot_status(ColdResetComplete.into(), false);
}
}
#[test]
fn test_cold_reset_success() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_WITH_UART,
&APP_WITH_UART,
image_options,
)
.unwrap();
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
hw.step_until_exit_success().unwrap();
}
}
#[test]
fn test_cold_reset_no_rng() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_WITH_UART,
&APP_WITH_UART,
image_options,
)
.unwrap();
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
initial_dbg_manuf_service_reg: 0x2, // Disable RNG
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
hw.step_until_exit_success().unwrap();
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_warm_reset.rs | rom/dev/tests/rom_integration_tests/test_warm_reset.rs | // Licensed under the Apache-2.0 license
use caliptra_api::{
mailbox::{FipsVersionResp, MailboxReqHeader, MailboxRespHeader},
SocManager,
};
#[allow(unused_imports)]
use caliptra_builder::{
firmware::{self, APP_WITH_UART, APP_WITH_UART_FPGA, FMC_WITH_UART},
version, ImageOptions,
};
use caliptra_common::{fips::FipsVersionCmd, mailbox_api::CommandId, RomBootStatus::*};
use caliptra_drivers::CaliptraError;
use caliptra_hw_model::{
BootParams, DefaultHwModel, DeviceLifecycle, Fuses, HwModel, InitParams, SecurityState,
SubsystemInitParams,
};
use caliptra_image_types::FwVerificationPqcKeyType;
use caliptra_test::image_pk_desc_hash;
use zerocopy::{FromBytes, IntoBytes};
use crate::helpers;
#[test]
fn test_warm_reset_success() {
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Production);
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let fw_svn = 9;
let image = caliptra_builder::build_and_sign_image(
&FMC_WITH_UART,
if cfg!(feature = "fpga_subsystem") {
&firmware::APP_WITH_UART_FPGA
} else {
&firmware::APP_WITH_UART
},
ImageOptions {
fw_svn,
..Default::default()
},
)
.unwrap();
let (vendor_pk_desc_hash, owner_pk_hash) = image_pk_desc_hash(&image.manifest);
let binding = image.to_bytes().unwrap();
let soc_manifest = &crate::helpers::default_soc_manifest_bytes(Default::default(), fw_svn);
let boot_params = BootParams {
fw_image: Some(&binding),
soc_manifest: Some(soc_manifest),
mcu_fw_image: Some(&crate::helpers::DEFAULT_MCU_FW),
..Default::default()
};
let mut hw = caliptra_hw_model::new(
InitParams {
fuses: Fuses {
vendor_pk_hash: vendor_pk_desc_hash,
owner_pk_hash,
fw_svn: [0x7F, 0, 0, 0], // Equals 7
..Default::default()
},
rom: &rom,
security_state,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: cfg!(feature = "fpga_subsystem"),
..Default::default()
},
..Default::default()
},
boot_params.clone(),
)
.unwrap();
// Wait for boot
while !hw.soc_ifc().cptra_flow_status().read().ready_for_runtime() {
hw.step();
}
// Perform warm reset
hw.warm_reset_flow().unwrap();
// Wait for boot
while !hw.soc_ifc().cptra_flow_status().read().ready_for_runtime() {
hw.step();
}
}
#[test]
fn test_warm_reset_during_cold_boot_before_image_validation() {
let fuses = Fuses {
life_cycle: DeviceLifecycle::Production,
..Default::default()
};
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, ImageOptions::default());
// Step till Cold boot starts
hw.step_until(|m| m.ready_for_fw());
// Perform a warm reset
hw.warm_reset_flow().unwrap();
// Wait for error
while hw.soc_ifc().cptra_fw_error_fatal().read() == 0 {
hw.step();
}
assert_eq!(
hw.soc_ifc().cptra_fw_error_fatal().read(),
u32::from(CaliptraError::ROM_WARM_RESET_UNSUCCESSFUL_PREVIOUS_COLD_RESET)
);
}
#[test]
#[cfg(not(feature = "fpga_subsystem"))]
fn test_warm_reset_during_cold_boot_during_image_validation() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
life_cycle: DeviceLifecycle::Unprovisioned,
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
helpers::test_start_firmware_load(&mut hw, &image_bundle.to_bytes().unwrap());
hw.step_until_boot_status(FwProcessorManifestLoadComplete.into(), true);
// Step for few times to land in image validation
for _ in 0..1000 {
hw.step();
}
// Perform a warm reset
hw.warm_reset_flow().unwrap();
// Wait for error
while hw.soc_ifc().cptra_fw_error_fatal().read() == 0 {
hw.step();
}
assert_eq!(
hw.soc_ifc().cptra_fw_error_fatal().read(),
u32::from(CaliptraError::ROM_WARM_RESET_UNSUCCESSFUL_PREVIOUS_COLD_RESET)
);
}
}
#[test]
#[cfg(not(feature = "fpga_subsystem"))]
fn test_warm_reset_during_cold_boot_after_image_validation() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
life_cycle: DeviceLifecycle::Unprovisioned,
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
helpers::test_upload_firmware(&mut hw, &image_bundle.to_bytes().unwrap(), *pqc_key_type);
// Step till after last step in cold boot is complete
hw.step_until_boot_status(FmcAliasDerivationComplete.into(), true);
// Perform a warm reset
hw.warm_reset_flow().unwrap();
// Wait for error
while hw.soc_ifc().cptra_fw_error_fatal().read() == 0 {
hw.step();
}
assert_eq!(
hw.soc_ifc().cptra_fw_error_fatal().read(),
u32::from(CaliptraError::ROM_WARM_RESET_UNSUCCESSFUL_PREVIOUS_COLD_RESET)
);
}
}
#[test]
fn test_warm_reset_during_update_reset() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
life_cycle: DeviceLifecycle::Unprovisioned,
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
helpers::test_upload_firmware(&mut hw, &image_bundle.to_bytes().unwrap(), *pqc_key_type);
helpers::wait_until_runtime(&mut hw);
// Trigger an update reset with "new" firmware
helpers::test_start_firmware_load(&mut hw, &image_bundle.to_bytes().unwrap());
if cfg!(not(feature = "fpga_realtime")) {
hw.step_until_boot_status(KatStarted.into(), true);
hw.step_until_boot_status(KatComplete.into(), true);
hw.step_until_boot_status(UpdateResetStarted.into(), false);
}
assert_eq!(hw.finish_mailbox_execute(), Ok(None));
// Step till after last step in update reset is complete
hw.step_until(|model| {
model.soc_ifc().cptra_boot_status().read() >= UpdateResetLoadImageComplete.into()
});
// Perform a warm reset
hw.warm_reset_flow().unwrap();
// Wait for error
while hw.soc_ifc().cptra_fw_error_fatal().read() == 0 {
hw.step();
}
assert_eq!(
hw.soc_ifc().cptra_fw_error_fatal().read(),
u32::from(CaliptraError::ROM_WARM_RESET_UNSUCCESSFUL_PREVIOUS_UPDATE_RESET)
);
}
}
const HW_REV_ID: u32 = 0x112;
fn test_version(
hw: &mut DefaultHwModel,
hw_rev: u32,
rom_version: u32,
fmc_version: u32,
app_version: u32,
) {
let payload = MailboxReqHeader {
chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::VERSION), &[]),
};
let response = hw
.mailbox_execute(CommandId::VERSION.into(), payload.as_bytes())
.unwrap()
.unwrap();
let version_resp = FipsVersionResp::ref_from_bytes(response.as_bytes()).unwrap();
// Verify response checksum
assert!(caliptra_common::checksum::verify_checksum(
version_resp.hdr.chksum,
0x0,
&version_resp.as_bytes()[core::mem::size_of_val(&version_resp.hdr.chksum)..],
));
// Verify FIPS status
assert_eq!(
version_resp.hdr.fips_status,
MailboxRespHeader::FIPS_STATUS_APPROVED
);
// Verify Version Info
assert_eq!(version_resp.mode, FipsVersionCmd::MODE);
// fips_rev[0] is hw_rev_id
// fips_rev[1] is FMC version at 31:16 and ROM version at 15:0
// fips_rev[2] is app (fw) version
let received_hw_rev = version_resp.fips_rev[0];
let received_rom_version = version_resp.fips_rev[1] & 0x0000FFFF;
let received_fmc_version = (version_resp.fips_rev[1] & 0xFFFF0000) >> 16;
let received_app_version = version_resp.fips_rev[2];
assert_eq!(received_hw_rev, hw_rev);
assert_eq!(received_rom_version, rom_version);
assert_eq!(received_fmc_version, fmc_version);
assert_eq!(received_app_version, app_version);
let name = &version_resp.name[..];
assert_eq!(name, FipsVersionCmd::NAME.as_bytes());
}
#[test]
fn test_warm_reset_version() {
let security_state = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Production);
let fmc_version = 3;
let app_version = 5;
let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env_fpga(cfg!(
feature = "fpga_subsystem"
)))
.unwrap();
let image = caliptra_builder::build_and_sign_image(
&FMC_WITH_UART,
if cfg!(feature = "fpga_subsystem") {
&firmware::APP_WITH_UART_FPGA
} else {
&firmware::APP_WITH_UART
},
ImageOptions {
fmc_version,
app_version,
fw_svn: 9,
..Default::default()
},
)
.unwrap();
let (vendor_pk_desc_hash, owner_pk_hash) = image_pk_desc_hash(&image.manifest);
let (soc_manifest, mcu_fw_image) = if cfg!(feature = "fpga_subsystem") {
(
Some(crate::helpers::default_soc_manifest_bytes(
FwVerificationPqcKeyType::MLDSA,
1,
)),
Some(&crate::helpers::DEFAULT_MCU_FW),
)
} else {
(None, None)
};
let binding = image.to_bytes().unwrap();
let boot_params = BootParams {
fw_image: Some(&binding),
soc_manifest: soc_manifest.as_deref(),
mcu_fw_image: mcu_fw_image.map(|v| v.as_ref()),
..Default::default()
};
let mut hw = caliptra_hw_model::new(
InitParams {
fuses: Fuses {
vendor_pk_hash: vendor_pk_desc_hash,
owner_pk_hash,
fw_svn: [0x7F, 0, 0, 0], // Equals 7
..Default::default()
},
rom: &rom,
security_state,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: cfg!(feature = "fpga_subsystem"),
..Default::default()
},
..Default::default()
},
boot_params.clone(),
)
.unwrap();
// Wait for boot
while !hw.soc_ifc().cptra_flow_status().read().ready_for_runtime() {
hw.step();
}
test_version(
&mut hw,
HW_REV_ID,
version::get_rom_version().into(),
fmc_version.into(),
app_version,
);
// Perform warm reset
hw.warm_reset_flow().unwrap();
// Wait for boot
while !hw.soc_ifc().cptra_flow_status().read().ready_for_runtime() {
hw.step();
}
test_version(
&mut hw,
HW_REV_ID,
version::get_rom_version().into(),
fmc_version.into(),
app_version,
);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_rom_integrity.rs | rom/dev/tests/rom_integration_tests/test_rom_integrity.rs | // Licensed under the Apache-2.0 license
use crate::helpers;
use caliptra_api::SocManager;
use caliptra_builder::{
firmware::{rom_tests::TEST_FMC_WITH_UART, APP_WITH_UART},
ImageOptions,
};
use caliptra_common::RomBootStatus::ColdResetComplete;
use caliptra_error::CaliptraError;
use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams};
use caliptra_image_types::RomInfo;
use zerocopy::{FromBytes, IntoBytes};
fn find_rom_info_offset(rom: &[u8]) -> usize {
for i in (0..rom.len()).step_by(64).rev() {
if rom[i..][..64] != [0u8; 64] {
return i;
}
}
panic!("Could not find RomInfo");
}
#[test]
fn test_rom_integrity_failure() {
let mut rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let rom_info_offset = find_rom_info_offset(&rom);
println!("rom_info_offset is {}", rom_info_offset);
// Corrupt a bit in the ROM info hash (we don't want to pick an arbitrary
// location in the image as that might make the CPU crazy)
rom[rom_info_offset + 9] ^= 1;
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
..Default::default()
},
BootParams::default(),
)
.unwrap();
loop {
hw.step();
if hw.ready_for_fw() && !hw.subsystem_mode() {
// Subsystem says it's always ready for firmware
panic!("ROM should have had a failure")
}
if let Ok(err) = CaliptraError::try_from(hw.soc_ifc().cptra_fw_error_fatal().read()) {
assert_eq!(err, CaliptraError::ROM_INTEGRITY_FAILURE);
break;
}
}
}
#[test]
fn test_read_rom_info_from_fmc() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let (rom_info_from_image, _) =
RomInfo::ref_from_prefix(&rom[find_rom_info_offset(&rom)..]).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_WITH_UART,
&APP_WITH_UART,
image_options,
)
.unwrap()
.to_bytes()
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
// 0x1000_0008 is test-fmc/read_rom_info()
let rom_info_from_hw = hw.mailbox_execute(0x1000_0008, &[]).unwrap().unwrap();
let rom_info_from_fw = RomInfo::ref_from_bytes(&rom_info_from_hw).unwrap();
assert_eq!(rom_info_from_fw.as_bytes(), rom_info_from_image.as_bytes());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/main.rs | rom/dev/tests/rom_integration_tests/main.rs | // Licensed under the Apache-2.0 license
mod helpers;
mod rv32_unit_tests;
mod test_capabilities;
mod test_cfi;
mod test_cpu_fault;
mod test_debug_unlock;
mod test_derive_stable_key;
mod test_dice_derivations;
mod test_ecdsa_verify;
mod test_fake_rom;
mod test_fips_hooks;
mod test_fmcalias_derivation;
mod test_idevid_derivation;
mod test_image_validation;
mod test_ldev_cert_cmd;
mod test_mailbox_errors;
mod test_mldsa_verify;
mod test_ocp_lock;
mod test_panic_missing;
mod test_pmp;
mod test_rom_integrity;
mod test_symbols;
mod test_uds_fe;
mod test_update_reset;
mod test_version;
mod test_warm_reset;
mod test_wdt_activation_and_stoppage;
mod tests_get_idev_csr;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_image_validation.rs | rom/dev/tests/rom_integration_tests/test_image_validation.rs | // Licensed under the Apache-2.0 license
use caliptra_api::{
mailbox::{CommandId, InstallOwnerPkHashReq, InstallOwnerPkHashResp},
SocManager,
};
use caliptra_builder::{
firmware::{
rom_tests::{TEST_FMC_INTERACTIVE, TEST_FMC_WITH_UART, TEST_RT_WITH_UART},
APP_WITH_UART,
},
ImageOptions,
};
use caliptra_common::{
memory_layout::{ICCM_ORG, ICCM_SIZE},
RomBootStatus::*,
};
use caliptra_drivers::{Array4x12, IdevidCertAttr, MfgFlags};
use caliptra_error::CaliptraError;
use caliptra_hw_model::{
BootParams, DefaultHwModel, DeviceLifecycle, Fuses, HwModel, InitParams, SecurityState,
SubsystemInitParams, U4,
};
use caliptra_image_crypto::OsslCrypto as Crypto;
use caliptra_image_elf::ElfExecutable;
use caliptra_image_fake_keys::{
VENDOR_CONFIG_KEY_0, VENDOR_CONFIG_KEY_1, VENDOR_CONFIG_KEY_2, VENDOR_CONFIG_KEY_3,
};
use caliptra_image_gen::{ImageGenerator, ImageGeneratorConfig, ImageGeneratorVendorConfig};
use caliptra_image_types::{
FwVerificationPqcKeyType, ImageBundle, ImageEccPubKey, ImageLmsPublicKey, ImageLmsSignature,
ImageManifest, ImageMldsaPubKey, ImageMldsaSignature, ImagePqcPubKey, ImageSignData,
MLDSA87_SIGNATURE_WORD_SIZE, PQC_PUB_KEY_BYTE_SIZE, VENDOR_ECC_MAX_KEY_COUNT,
VENDOR_LMS_MAX_KEY_COUNT, VENDOR_MLDSA_MAX_KEY_COUNT,
};
use openssl::{
asn1::{Asn1Integer, Asn1Time},
bn::BigNum,
hash::MessageDigest,
pkey::{PKey, Private},
rsa::Rsa,
x509::{X509Req, X509},
};
use std::str;
use zerocopy::{FromBytes, IntoBytes};
use crate::helpers;
const ICCM_END_ADDR: u32 = ICCM_ORG + ICCM_SIZE - 1;
const PUB_KEY_X: [u8; 48] = [
0xD7, 0x9C, 0x6D, 0x97, 0x2B, 0x34, 0xA1, 0xDF, 0xC9, 0x16, 0xA7, 0xB6, 0xE0, 0xA9, 0x9B, 0x6B,
0x53, 0x87, 0xB3, 0x4D, 0xA2, 0x18, 0x76, 0x07, 0xC1, 0xAD, 0x0A, 0x4D, 0x1A, 0x8C, 0x2E, 0x41,
0x72, 0xAB, 0x5F, 0xA5, 0xD9, 0xAB, 0x58, 0xFE, 0x45, 0xE4, 0x3F, 0x56, 0xBB, 0xB6, 0x6B, 0xA4,
];
const PUB_KEY_Y: [u8; 48] = [
0x5A, 0x73, 0x63, 0x93, 0x2B, 0x06, 0xB4, 0xF2, 0x23, 0xBE, 0xF0, 0xB6, 0x0A, 0x63, 0x90, 0x26,
0x51, 0x12, 0xDB, 0xBD, 0x0A, 0xAE, 0x67, 0xFE, 0xF2, 0x6B, 0x46, 0x5B, 0xE9, 0x35, 0xB4, 0x8E,
0x45, 0x1E, 0x68, 0xD1, 0x6F, 0x11, 0x18, 0xF2, 0xB3, 0x2B, 0x4C, 0x28, 0x60, 0x87, 0x49, 0xED,
];
const SIGNATURE_R: [u8; 48] = [
0x93, 0x79, 0x9d, 0x55, 0x12, 0x26, 0x36, 0x28, 0x34, 0xf6, 0xf, 0x7b, 0x94, 0x52, 0x90, 0xb7,
0xcc, 0xe6, 0xe9, 0x96, 0x1, 0xfb, 0x7e, 0xbd, 0x2, 0x6c, 0x2e, 0x3c, 0x44, 0x5d, 0x3c, 0xd9,
0xb6, 0x50, 0x68, 0xda, 0xc0, 0xa8, 0x48, 0xbe, 0x9f, 0x5, 0x60, 0xaa, 0x75, 0x8f, 0xda, 0x27,
];
const SIGNATURE_S: [u8; 48] = [
0xe5, 0x48, 0xe5, 0x35, 0xa1, 0xcc, 0x60, 0xe, 0x13, 0x3b, 0x55, 0x91, 0xae, 0xba, 0xad, 0x78,
0x5, 0x40, 0x6, 0xd7, 0x52, 0xd0, 0xe1, 0xdf, 0x94, 0xfb, 0xfa, 0x95, 0xd7, 0x8f, 0xb, 0x3f,
0x8e, 0x81, 0xb9, 0x11, 0x9c, 0x2b, 0xe0, 0x8, 0xbf, 0x6d, 0x6f, 0x4e, 0x41, 0x85, 0xf8, 0x7d,
];
#[test]
fn test_invalid_manifest_marker() {
for life_cycle in helpers::LIFECYCLES_ALL.iter() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
println!(
"lifecycle: {:?}, pqc_key_type: {:?}",
life_cycle, pqc_key_type
);
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
life_cycle: *life_cycle,
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
image_bundle.manifest.marker = 0xDEADBEEF;
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_MARKER_MISMATCH,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
}
#[test]
fn test_invalid_manifest_size() {
for life_cycle in helpers::LIFECYCLES_ALL.iter() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
println!(
"lifecycle: {:?}, pqc_key_type: {:?}",
life_cycle, pqc_key_type
);
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
life_cycle: *life_cycle,
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
image_bundle.manifest.size = (core::mem::size_of::<ImageManifest>() - 1) as u32;
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_SIZE_MISMATCH,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
}
#[test]
fn test_invalid_pqc_key_type() {
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
for pqc_key_type in 0..u8::MAX {
if pqc_key_type == FwVerificationPqcKeyType::LMS as u8
|| pqc_key_type == FwVerificationPqcKeyType::MLDSA as u8
{
continue;
}
image_bundle.manifest.pqc_key_type = pqc_key_type;
helpers::assert_fatal_fw_load(
&mut hw,
FwVerificationPqcKeyType::LMS,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_PQC_KEY_TYPE_INVALID,
);
if hw.subsystem_mode() {
// Subsystem fails fatally
break;
}
}
}
#[test]
fn test_pqc_key_type_mismatch() {
for life_cycle in helpers::LIFECYCLES_PROVISIONED.iter() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
println!(
"lifecycle: {:?}, pqc_key_type: {:?}",
life_cycle, pqc_key_type
);
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let incorrect_pqc_key_type = match pqc_key_type {
FwVerificationPqcKeyType::LMS => FwVerificationPqcKeyType::MLDSA,
FwVerificationPqcKeyType::MLDSA => FwVerificationPqcKeyType::LMS,
};
let fuses = caliptra_hw_model::Fuses {
life_cycle: *life_cycle,
fuse_pqc_key_type: incorrect_pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_PQC_KEY_TYPE_MISMATCH,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
}
#[test]
fn test_pqc_key_type_unprovisioned() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = caliptra_hw_model::Fuses {
life_cycle: DeviceLifecycle::Unprovisioned,
// Key type is set to 0 (which is invalid) on unprovisioned builds.
fuse_pqc_key_type: 0,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
*pqc_key_type,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
}
}
#[test]
fn test_preamble_zero_vendor_pubkey_info_digest() {
for life_cycle in helpers::LIFECYCLES_PROVISIONED.iter() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
println!(
"lifecycle: {:?}, pqc_key_type: {:?}",
life_cycle, pqc_key_type
);
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = caliptra_hw_model::Fuses {
life_cycle: *life_cycle,
vendor_pk_hash: [0u32; 12],
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_INVALID,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
}
#[test]
fn test_preamble_vendor_pubkey_info_digest_mismatch() {
for life_cycle in helpers::LIFECYCLES_PROVISIONED.iter() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
println!(
"lifecycle: {:?}, pqc_key_type: {:?}",
life_cycle, pqc_key_type
);
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = caliptra_hw_model::Fuses {
life_cycle: *life_cycle,
vendor_pk_hash: [0xDEADBEEF; 12],
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_MISMATCH,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
}
#[test]
fn test_preamble_vendor_active_ecc_pubkey_digest_mismatch() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options.clone());
let vendor_pubkey_info_digest = gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap();
let fuses = caliptra_hw_model::Fuses {
vendor_pk_hash: vendor_pubkey_info_digest,
life_cycle: DeviceLifecycle::Manufacturing,
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
image_bundle.manifest.preamble.vendor_ecc_active_pub_key = ImageEccPubKey {
x: [0xBE; 12],
y: [0xEF; 12],
};
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_DIGEST_MISMATCH,
);
}
}
#[test]
fn test_preamble_vendor_active_mldsa_pubkey_digest_mismatch() {
for life_cycle in helpers::LIFECYCLES_PROVISIONED.iter() {
println!("lifecycle: {:?}", life_cycle);
let image_options = ImageOptions {
pqc_key_type: FwVerificationPqcKeyType::MLDSA,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options.clone());
let vendor_pubkey_info_digest = gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap();
let fuses = caliptra_hw_model::Fuses {
life_cycle: *life_cycle,
vendor_pk_hash: vendor_pubkey_info_digest,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
image_bundle.manifest.preamble.vendor_pqc_active_pub_key =
ImagePqcPubKey([0xDE; PQC_PUB_KEY_BYTE_SIZE]);
helpers::assert_fatal_fw_load(
&mut hw,
FwVerificationPqcKeyType::MLDSA,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_DIGEST_MISMATCH,
);
}
}
#[test]
fn test_preamble_vendor_lms_pubkey_descriptor_digest_mismatch() {
for life_cycle in helpers::LIFECYCLES_PROVISIONED.iter() {
println!("lifecycle: {:?}", life_cycle);
let image_options = ImageOptions {
pqc_key_type: FwVerificationPqcKeyType::LMS,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options.clone());
let vendor_pubkey_info_digest = gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap();
let fuses = caliptra_hw_model::Fuses {
life_cycle: *life_cycle,
vendor_pk_hash: vendor_pubkey_info_digest,
fuse_pqc_key_type: FwVerificationPqcKeyType::LMS as u32,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
image_bundle.manifest.preamble.vendor_pqc_active_pub_key =
ImagePqcPubKey([0xDE; PQC_PUB_KEY_BYTE_SIZE]);
helpers::assert_fatal_fw_load(
&mut hw,
FwVerificationPqcKeyType::LMS,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_DIGEST_MISMATCH,
);
}
}
#[test]
fn test_preamble_vendor_ecc_pubkey_descriptor_bad_index() {
for life_cycle in helpers::LIFECYCLES_PROVISIONED.iter() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
println!(
"lifecycle: {:?}, pqc_key_type: {:?}",
life_cycle, pqc_key_type
);
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options.clone());
let vendor_pubkey_info_digest = gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap();
let fuses = caliptra_hw_model::Fuses {
life_cycle: *life_cycle,
vendor_pk_hash: vendor_pubkey_info_digest,
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
let pub_key_idx = image_bundle
.manifest
.preamble
.vendor_pub_key_info
.ecc_key_descriptor
.key_hash_count;
image_bundle.manifest.preamble.vendor_ecc_pub_key_idx = pub_key_idx as u32;
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INDEX_OUT_OF_BOUNDS,
);
}
}
}
#[test]
fn test_preamble_vendor_lms_pubkey_descriptor_bad_index() {
for life_cycle in helpers::LIFECYCLES_PROVISIONED.iter() {
println!("lifecycle: {:?}", life_cycle);
let image_options = ImageOptions {
pqc_key_type: FwVerificationPqcKeyType::LMS,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options.clone());
let vendor_pubkey_info_digest = gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap();
let fuses = caliptra_hw_model::Fuses {
life_cycle: *life_cycle,
vendor_pk_hash: vendor_pubkey_info_digest,
fuse_pqc_key_type: FwVerificationPqcKeyType::LMS as u32,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
let pub_key_idx = image_bundle
.manifest
.preamble
.vendor_pub_key_info
.pqc_key_descriptor
.key_hash_count;
image_bundle.manifest.preamble.vendor_pqc_pub_key_idx = pub_key_idx as u32;
helpers::assert_fatal_fw_load(
&mut hw,
FwVerificationPqcKeyType::LMS,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_INDEX_OUT_OF_BOUNDS,
);
}
}
#[test]
fn test_preamble_vendor_mldsa_pubkey_descriptor_bad_index() {
for life_cycle in helpers::LIFECYCLES_PROVISIONED.iter() {
println!("lifecycle: {:?}", life_cycle);
let image_options = ImageOptions {
pqc_key_type: FwVerificationPqcKeyType::MLDSA,
..Default::default()
};
let gen = ImageGenerator::new(Crypto::default());
let image_bundle = helpers::build_image_bundle(image_options.clone());
let vendor_pubkey_info_digest = gen
.vendor_pubkey_info_digest(&image_bundle.manifest.preamble)
.unwrap();
let fuses = caliptra_hw_model::Fuses {
life_cycle: *life_cycle,
vendor_pk_hash: vendor_pubkey_info_digest,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
let pub_key_idx = image_bundle
.manifest
.preamble
.vendor_pub_key_info
.pqc_key_descriptor
.key_hash_count;
image_bundle.manifest.preamble.vendor_pqc_pub_key_idx = pub_key_idx as u32;
helpers::assert_fatal_fw_load(
&mut hw,
FwVerificationPqcKeyType::MLDSA,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_INDEX_OUT_OF_BOUNDS,
);
}
}
#[test]
fn test_preamble_owner_pubkey_digest_mismatch() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = caliptra_hw_model::Fuses {
owner_pk_hash: [0xDEADBEEF; 12],
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_OWNER_PUB_KEY_DIGEST_MISMATCH,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
#[test]
fn test_preamble_dot_owner_pubkey_digest_mismatch() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = caliptra_hw_model::Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
let mut request = InstallOwnerPkHashReq {
digest: [0u32; 12],
..Default::default()
};
request.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::INSTALL_OWNER_PK_HASH),
&request.as_bytes()[core::mem::size_of_val(&request.hdr.chksum)..],
);
let response = hw
.mailbox_execute(CommandId::INSTALL_OWNER_PK_HASH.into(), request.as_bytes())
.unwrap()
.unwrap();
let resp = InstallOwnerPkHashResp::ref_from_bytes(response.as_bytes()).unwrap();
assert_eq!(resp.dpe_result, 0);
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_DOT_OWNER_PUB_KEY_DIGEST_MISMATCH,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
#[test]
fn test_preamble_dot_owner_pubkey_digest_success() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = caliptra_hw_model::Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
let gen = ImageGenerator::new(Crypto::default());
let digest = gen
.owner_pubkey_digest(&image_bundle.manifest.preamble)
.unwrap();
let mut request = InstallOwnerPkHashReq {
digest,
..Default::default()
};
request.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::INSTALL_OWNER_PK_HASH),
&request.as_bytes()[core::mem::size_of_val(&request.hdr.chksum)..],
);
let response = hw
.mailbox_execute(CommandId::INSTALL_OWNER_PK_HASH.into(), request.as_bytes())
.unwrap()
.unwrap();
let resp = InstallOwnerPkHashResp::ref_from_bytes(response.as_bytes()).unwrap();
assert_eq!(resp.dpe_result, 0);
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
*pqc_key_type,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
}
}
#[test]
fn test_preamble_vendor_ecc_pubkey_revocation() {
for life_cycle in helpers::LIFECYCLES_ALL.iter() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
println!(
"lifecycle: {:?}, pqc_key_type: {:?}",
life_cycle, pqc_key_type
);
let mut image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
const LAST_KEY_IDX: u32 = VENDOR_ECC_MAX_KEY_COUNT - 1;
static VENDOR_CONFIG_LIST: [ImageGeneratorVendorConfig;
VENDOR_ECC_MAX_KEY_COUNT as usize] = [
VENDOR_CONFIG_KEY_0,
VENDOR_CONFIG_KEY_1,
VENDOR_CONFIG_KEY_2,
VENDOR_CONFIG_KEY_3,
];
for vendor_config in VENDOR_CONFIG_LIST.clone() {
let key_idx = vendor_config.ecc_key_idx;
image_options.vendor_config = vendor_config;
let fuses = caliptra_hw_model::Fuses {
fuse_ecc_revocation: U4::try_from(
1u32 << image_options.vendor_config.ecc_key_idx,
)
.unwrap(),
fuse_pqc_key_type: *pqc_key_type as u32,
life_cycle: *life_cycle,
..Default::default()
};
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap();
let image_bundle = crate::helpers::build_image_bundle(image_options.clone());
if key_idx == LAST_KEY_IDX {
// Last key is never revoked.
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
*pqc_key_type,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
} else {
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_REVOKED,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
}
}
}
#[test]
fn test_preamble_vendor_lms_pubkey_revocation() {
// this test is too slow to run in the verilator nightly
#![cfg_attr(all(not(feature = "slow_tests"), feature = "verilator"), ignore)]
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
const LAST_KEY_IDX: u32 = VENDOR_LMS_MAX_KEY_COUNT - 1;
for idx in 0..VENDOR_LMS_MAX_KEY_COUNT {
let vendor_config = ImageGeneratorVendorConfig {
ecc_key_idx: 3,
pqc_key_idx: idx,
..VENDOR_CONFIG_KEY_0
};
let mut image_options = ImageOptions::default();
let key_idx = vendor_config.pqc_key_idx;
image_options.vendor_config = vendor_config;
image_options.pqc_key_type = FwVerificationPqcKeyType::LMS;
let fuses = caliptra_hw_model::Fuses {
fuse_lms_revocation: 1u32 << image_options.vendor_config.pqc_key_idx,
fuse_pqc_key_type: FwVerificationPqcKeyType::LMS as u32,
..Default::default()
};
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
ss_init_params: SubsystemInitParams {
enable_mcu_uart_log: true,
..Default::default()
},
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap();
let image_bundle = crate::helpers::build_image_bundle(image_options.clone());
if key_idx == LAST_KEY_IDX {
// Last key is never revoked.
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
FwVerificationPqcKeyType::LMS,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
} else {
helpers::assert_fatal_fw_load(
&mut hw,
FwVerificationPqcKeyType::LMS,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_REVOKED,
);
}
}
}
#[test]
fn test_preamble_vendor_mldsa_pubkey_revocation() {
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
const LAST_KEY_IDX: u32 = VENDOR_MLDSA_MAX_KEY_COUNT - 1;
for idx in 0..VENDOR_MLDSA_MAX_KEY_COUNT {
let vendor_config = ImageGeneratorVendorConfig {
pqc_key_idx: idx,
..VENDOR_CONFIG_KEY_0
};
let image_options = ImageOptions {
vendor_config,
pqc_key_type: FwVerificationPqcKeyType::MLDSA,
..Default::default()
};
let key_idx = image_options.vendor_config.pqc_key_idx;
let fuses = caliptra_hw_model::Fuses {
fuse_mldsa_revocation: 1u32 << key_idx,
..Default::default()
};
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
..Default::default()
},
BootParams {
..Default::default()
},
)
.unwrap();
let image_bundle = crate::helpers::build_image_bundle(image_options.clone());
if key_idx == LAST_KEY_IDX {
// Last key is never revoked.
crate::helpers::test_upload_firmware(
&mut hw,
&image_bundle.to_bytes().unwrap(),
FwVerificationPqcKeyType::MLDSA,
);
hw.step_until_boot_status(u32::from(ColdResetComplete), true);
} else {
helpers::assert_fatal_fw_load(
&mut hw,
FwVerificationPqcKeyType::MLDSA,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_REVOKED,
);
}
}
}
#[test]
fn test_preamble_vendor_ecc_pubkey_out_of_bounds() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options);
image_bundle.manifest.preamble.vendor_ecc_pub_key_idx = VENDOR_ECC_MAX_KEY_COUNT;
helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INDEX_OUT_OF_BOUNDS,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
#[test]
fn test_preamble_vendor_lms_pubkey_out_of_bounds() {
let fuses = caliptra_hw_model::Fuses {
fuse_pqc_key_type: FwVerificationPqcKeyType::LMS as u32,
..Default::default()
};
let image_options = ImageOptions {
pqc_key_type: FwVerificationPqcKeyType::LMS,
..Default::default()
};
let (mut hw, mut image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
image_bundle.manifest.preamble.vendor_pqc_pub_key_idx = VENDOR_LMS_MAX_KEY_COUNT;
helpers::assert_fatal_fw_load(
&mut hw,
FwVerificationPqcKeyType::LMS,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_INDEX_OUT_OF_BOUNDS,
);
}
#[test]
fn test_header_verify_vendor_sig_zero_ecc_pubkey() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, mut image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses.clone(), image_options.clone());
// Set ecc_pub_key.x to zero.
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_update_reset.rs | rom/dev/tests/rom_integration_tests/test_update_reset.rs | // Licensed under the Apache-2.0 license
use crate::helpers;
use crate::test_derive_stable_key::HW_MODEL_MODES_SUBSYSTEM;
use caliptra_api::SocManager;
use caliptra_builder::{
firmware::{
rom_tests::{
FAKE_TEST_FMC_INTERACTIVE, FAKE_TEST_FMC_WITH_UART, TEST_FMC_INTERACTIVE,
TEST_FMC_WITH_UART, TEST_RT_WITH_UART,
},
APP_WITH_UART_FPGA,
},
FwId, ImageOptions,
};
use caliptra_common::mailbox_api::CommandId;
use caliptra_common::RomBootStatus::*;
use caliptra_drivers::DataVault;
use caliptra_error::CaliptraError;
use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams};
use caliptra_image_fake_keys::VENDOR_CONFIG_KEY_0;
use caliptra_image_gen::ImageGeneratorVendorConfig;
use zerocopy::{FromBytes, IntoBytes};
const TEST_FMC_CMD_RESET_FOR_UPDATE: u32 = 0x1000_0004;
const TEST_FMC_CMD_RESET_FOR_UPDATE_KEEP_MBOX_CMD: u32 = 0x1000_000B;
#[test]
fn test_update_reset_success() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
// Trigger an update reset with "new" firmware
hw.start_mailbox_execute(
CommandId::FIRMWARE_LOAD.into(),
&image_bundle.to_bytes().unwrap(),
)
.unwrap();
if cfg!(not(feature = "fpga_realtime")) {
hw.step_until_boot_status(KatStarted.into(), true);
hw.step_until_boot_status(KatComplete.into(), true);
hw.step_until_boot_status(UpdateResetStarted.into(), false);
}
assert_eq!(hw.finish_mailbox_execute(), Ok(None));
hw.step_until_boot_status(UpdateResetComplete.into(), true);
// Exit test-fmc with success
hw.mailbox_execute(0x1000_000C, &[]).unwrap();
hw.step_until_exit_success().unwrap();
}
}
}
#[test]
fn test_update_reset_no_mailbox_cmd() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_WITH_UART,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
// This command tells the test-fmc to do an update reset after clearing
// itself from the mailbox.
hw.mailbox_execute(TEST_FMC_CMD_RESET_FOR_UPDATE, &[])
.unwrap();
if cfg!(not(feature = "fpga_realtime")) {
hw.step_until_boot_status(KatStarted.into(), true);
hw.step_until_boot_status(KatComplete.into(), true);
}
hw.step_until_boot_status(UpdateResetStarted.into(), true);
// No command in the mailbox.
hw.step_until(|m| m.soc_ifc().cptra_fw_error_non_fatal().read() != 0);
assert_eq!(
hw.soc_ifc().cptra_fw_error_non_fatal().read(),
u32::from(CaliptraError::ROM_UPDATE_RESET_FLOW_MAILBOX_ACCESS_FAILURE)
);
let _ = hw.mailbox_execute(0xDEADBEEF, &[]);
hw.step_until_exit_success().unwrap();
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(UpdateResetStarted)
);
}
}
}
#[test]
fn test_update_reset_non_fw_load_cmd() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_WITH_UART,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
// This command tells the test-fmc to do an update reset but leave the
// "unknown" command in the mailbox for the ROM to find
hw.start_mailbox_execute(TEST_FMC_CMD_RESET_FOR_UPDATE_KEEP_MBOX_CMD, &[])
.unwrap();
if cfg!(not(feature = "fpga_realtime")) {
hw.step_until_boot_status(KatStarted.into(), true);
hw.step_until_boot_status(KatComplete.into(), true);
}
hw.step_until_boot_status(UpdateResetStarted.into(), true);
let _ = hw.mailbox_execute(0xDEADBEEF, &[]);
hw.step_until_exit_success().unwrap();
assert_eq!(
hw.soc_ifc().cptra_fw_error_non_fatal().read(),
u32::from(CaliptraError::ROM_UPDATE_RESET_FLOW_INVALID_FIRMWARE_COMMAND)
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(UpdateResetStarted)
);
}
}
}
#[test]
fn test_update_reset_verify_image_failure() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_WITH_UART,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
// Upload invalid manifest
hw.start_mailbox_execute(CommandId::FIRMWARE_LOAD.into(), &[0u8; 4])
.unwrap();
if cfg!(not(any(
feature = "fpga_realtime",
feature = "fpga_subsystem"
))) {
hw.step_until_boot_status(KatStarted.into(), true);
hw.step_until_boot_status(KatComplete.into(), true);
}
hw.step_until(|model| {
model.soc_ifc().cptra_boot_status().read() >= u32::from(UpdateResetStarted)
});
if subsystem_mode {
assert_eq!(
hw.finish_mailbox_execute(),
Err(caliptra_hw_model::ModelError::MailboxCmdFailed(
CaliptraError::ROM_UPDATE_RESET_FLOW_IMAGE_NOT_IN_MCU_SRAM.into()
))
);
// With subsystem mode this fails fatally as MBOX is used and not MCU SRAM
continue;
} else {
assert_eq!(
hw.finish_mailbox_execute(),
Err(caliptra_hw_model::ModelError::MailboxCmdFailed(
CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_MARKER_MISMATCH.into()
))
);
}
hw.step_until_exit_success().unwrap();
assert_eq!(
hw.soc_ifc().cptra_fw_error_non_fatal().read(),
u32::from(CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_MARKER_MISMATCH)
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(UpdateResetLoadManifestComplete)
);
}
}
}
#[test]
fn test_update_reset_boot_status() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
// Start the firmware update process
hw.start_mailbox_execute(
CommandId::FIRMWARE_LOAD.into(),
&image_bundle.to_bytes().unwrap(),
)
.unwrap();
if cfg!(not(any(
feature = "fpga_realtime",
feature = "fpga_subsystem"
))) {
hw.step_until_boot_status(CfiInitialized.into(), false);
hw.step_until_boot_status(KatStarted.into(), false);
hw.step_until_boot_status(KatComplete.into(), false);
hw.step_until_boot_status(UpdateResetStarted.into(), false);
hw.step_until_boot_status(UpdateResetLoadManifestComplete.into(), false);
hw.step_until_boot_status(UpdateResetImageVerificationComplete.into(), false);
hw.step_until_boot_status(UpdateResetPopulateDataVaultComplete.into(), false);
hw.step_until_boot_status(UpdateResetExtendKeyLadderComplete.into(), false);
hw.step_until_boot_status(UpdateResetExtendPcrComplete.into(), false);
hw.step_until_boot_status(UpdateResetLoadImageComplete.into(), false);
hw.step_until_boot_status(UpdateResetOverwriteManifestComplete.into(), false);
hw.step_until_boot_status(UpdateResetComplete.into(), false);
}
hw.step_until_boot_status(UpdateResetComplete.into(), true);
assert_eq!(hw.finish_mailbox_execute(), Ok(None));
// Tell the test-fmc to "exit with success" (necessary because the FMC is in
// interactive mode)
hw.mailbox_execute(0x1000_000C, &[]).unwrap();
hw.step_until_exit_success().unwrap();
}
}
}
#[test]
fn test_update_reset_vendor_ecc_pub_key_idx_dv_mismatch() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let vendor_config_cold_boot = ImageGeneratorVendorConfig {
ecc_key_idx: 3,
..VENDOR_CONFIG_KEY_0
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let image_options = ImageOptions {
vendor_config: vendor_config_cold_boot,
pqc_key_type: *pqc_key_type,
..Default::default()
};
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
// Upload firmware with a different vendor ECC key index.
let vendor_config_update_reset = ImageGeneratorVendorConfig {
ecc_key_idx: 2,
..VENDOR_CONFIG_KEY_0
};
let image_options = ImageOptions {
vendor_config: vendor_config_update_reset,
pqc_key_type: *pqc_key_type,
..Default::default()
};
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_WITH_UART,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
hw.start_mailbox_execute(
CommandId::FIRMWARE_LOAD.into(),
&image_bundle.to_bytes().unwrap(),
)
.unwrap();
hw.step_until_boot_status(UpdateResetStarted.into(), true);
assert_eq!(
hw.finish_mailbox_execute(),
Err(caliptra_hw_model::ModelError::MailboxCmdFailed(
CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_VENDOR_ECC_PUB_KEY_IDX_MISMATCH
.into()
))
);
// Exit test-fmc with success
hw.mailbox_execute(0x1000_000C, &[]).unwrap();
hw.step_until_exit_success().unwrap();
assert_eq!(
hw.soc_ifc().cptra_fw_error_non_fatal().read(),
u32::from(
CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_VENDOR_ECC_PUB_KEY_IDX_MISMATCH
)
);
}
}
}
#[test]
fn test_update_reset_vendor_lms_pub_key_idx_dv_mismatch() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let vendor_config_cold_boot = ImageGeneratorVendorConfig {
pqc_key_idx: 3,
..VENDOR_CONFIG_KEY_0
};
let image_options = ImageOptions {
vendor_config: vendor_config_cold_boot,
..Default::default()
};
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
// Generate firmware with a different vendor LMS key index.
let vendor_config_update_reset = ImageGeneratorVendorConfig {
pqc_key_idx: 2,
..VENDOR_CONFIG_KEY_0
};
let image_options = ImageOptions {
vendor_config: vendor_config_update_reset,
..Default::default()
};
let image_bundle2 = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses: caliptra_hw_model::Fuses {
..Default::default()
},
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
hw.step_until_output_contains("Running Caliptra FMC ...")
.unwrap();
assert_eq!(
hw.mailbox_execute(
u32::from(CommandId::FIRMWARE_LOAD),
&image_bundle2.to_bytes().unwrap()
),
Err(caliptra_hw_model::ModelError::MailboxCmdFailed(
CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_VENDOR_PQC_PUB_KEY_IDX_MISMATCH
.into()
))
);
// Exit test-fmc with success
hw.mailbox_execute(0x1000_000C, &[]).unwrap();
hw.step_until_exit_success().unwrap();
assert_eq!(
hw.soc_ifc().cptra_fw_error_non_fatal().read(),
u32::from(
CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_VENDOR_PQC_PUB_KEY_IDX_MISMATCH
)
);
}
}
#[test]
fn test_check_rom_update_reset_status_reg() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART_FPGA,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
// Trigger an update reset with "new" firmware
hw.start_mailbox_execute(
CommandId::FIRMWARE_LOAD.into(),
&image_bundle.to_bytes().unwrap(),
)
.unwrap();
if cfg!(not(feature = "fpga_realtime")) {
hw.step_until_boot_status(KatStarted.into(), true);
hw.step_until_boot_status(KatComplete.into(), true);
hw.step_until_boot_status(UpdateResetStarted.into(), false);
}
assert_eq!(hw.finish_mailbox_execute(), Ok(None));
hw.step_until_boot_status(UpdateResetComplete.into(), true);
let data_vault = hw.mailbox_execute(0x1000_0005, &[]).unwrap().unwrap();
let (data_vault, _) = DataVault::ref_from_prefix(data_vault.as_bytes()).unwrap();
assert_eq!(
data_vault.rom_update_reset_status(),
u32::from(UpdateResetComplete)
);
}
}
}
#[test]
fn test_fmc_is_16k() {
struct Fmc<'a> {
name: &'a str,
fwid: &'a FwId<'static>,
}
let errs: String = [
Fmc {
name: "TEST_FMC_INTERACTIVE",
fwid: &TEST_FMC_INTERACTIVE,
},
Fmc {
name: "FAKE_TEST_FMC_WITH_UART",
fwid: &FAKE_TEST_FMC_WITH_UART,
},
Fmc {
name: "FAKE_TEST_FMC_INTERACTIVE",
fwid: &FAKE_TEST_FMC_INTERACTIVE,
},
]
.map(|fmc| -> String {
let bundle = caliptra_builder::build_and_sign_image(
fmc.fwid,
&TEST_RT_WITH_UART,
ImageOptions::default(),
)
.unwrap();
let fmc_size = bundle.fmc.len();
let delta = 16 * 1024 - fmc_size as isize;
if delta != 0 {
format!(
"Adjust PAD_LEN in rom/dev/tools/test-fmc/src/main.rs by {} for {}",
delta, fmc.name
)
} else {
String::from("")
}
})
.into_iter()
.filter(|err| !err.is_empty())
.collect::<Vec<String>>()
.join("\n");
println!("{}", errs);
assert!(errs.is_empty());
}
#[test]
fn test_update_reset_max_fw_image() {
for &subsystem_mode in &HW_MODEL_MODES_SUBSYSTEM {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(crate::helpers::rom_from_env()).unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&APP_WITH_UART_FPGA,
image_options.clone(),
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
subsystem_mode,
..Default::default()
},
BootParams {
fw_image: Some(&image_bundle.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(ColdResetComplete.into(), true);
// Trigger an update reset with new firmware
let updated_image_bundle = caliptra_builder::build_and_sign_image(
&TEST_FMC_INTERACTIVE,
&TEST_RT_WITH_UART,
image_options,
)
.unwrap();
let image_bytes = updated_image_bundle.to_bytes().unwrap();
// Sanity-check that the image is 128k
assert_eq!(
128 * 1024 - image_bytes.len() as isize,
0,
"Try adjusting PAD_LEN in rom/dev/tools/test-fmc/src/main.rs"
);
hw.start_mailbox_execute(CommandId::FIRMWARE_LOAD.into(), &image_bytes)
.unwrap();
if cfg!(not(feature = "fpga_realtime")) {
hw.step_until_boot_status(KatStarted.into(), true);
hw.step_until_boot_status(KatComplete.into(), true);
hw.step_until_boot_status(UpdateResetStarted.into(), false);
}
assert_eq!(hw.finish_mailbox_execute(), Ok(None));
hw.step_until_boot_status(UpdateResetComplete.into(), true);
// [TODO][CAP2.1] The following command is to validate fmc/rt load into ICCM. The logic isn't there in the test-fmc
if subsystem_mode {
continue;
}
let mut buf = vec![];
buf.append(
&mut updated_image_bundle
.manifest
.fmc
.image_size()
.to_le_bytes()
.to_vec(),
);
buf.append(
&mut updated_image_bundle
.manifest
.runtime
.image_size()
.to_le_bytes()
.to_vec(),
);
buf.append(&mut updated_image_bundle.fmc.to_vec());
buf.append(&mut updated_image_bundle.runtime.to_vec());
let iccm_cmp: Vec<u8> = hw.mailbox_execute(0x1000_000E, &buf).unwrap().unwrap();
assert_eq!(iccm_cmp.len(), 1);
assert_eq!(iccm_cmp[0], 0);
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_version.rs | rom/dev/tests/rom_integration_tests/test_version.rs | // Licensed under the Apache-2.0 license
use caliptra_builder::{version, ImageOptions};
use caliptra_common::fips::FipsVersionCmd;
use caliptra_common::mailbox_api::{
CommandId, FipsVersionResp, MailboxReqHeader, MailboxRespHeader,
};
use caliptra_hw_model::{Fuses, HwModel};
use zerocopy::{FromBytes, IntoBytes};
use crate::helpers;
// TODO: Find a better way to get this or make it a don't-care for this test
// This is not going to work when we start testing against multiple hw revs
const HW_REV_ID: u32 = 0x112;
#[test]
fn test_version() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default());
let payload = MailboxReqHeader {
chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::VERSION), &[]),
};
let response = hw
.mailbox_execute(CommandId::VERSION.into(), payload.as_bytes())
.unwrap()
.unwrap();
let version_resp = FipsVersionResp::ref_from_bytes(response.as_bytes()).unwrap();
// Verify response checksum
assert!(caliptra_common::checksum::verify_checksum(
version_resp.hdr.chksum,
0x0,
&version_resp.as_bytes()[core::mem::size_of_val(&version_resp.hdr.chksum)..],
));
// Verify FIPS status
assert_eq!(
version_resp.hdr.fips_status,
MailboxRespHeader::FIPS_STATUS_APPROVED
);
// Verify Version Info
assert_eq!(version_resp.mode, FipsVersionCmd::MODE);
// fw_rev[0] is FMC version at 31:16 and ROM version at 15:0
// fw_rev[1] is app (fw) version
// FMC and FW version are expected to be 0x0 before FW load
assert_eq!(
version_resp.fips_rev,
[HW_REV_ID, (version::get_rom_version() as u32), 0x0]
);
let name = &version_resp.name[..];
assert_eq!(name, FipsVersionCmd::NAME.as_bytes());
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_cfi.rs | rom/dev/tests/rom_integration_tests/test_cfi.rs | // Licensed under the Apache-2.0 license
use caliptra_builder::{
elf_symbols,
firmware::{ROM, ROM_WITH_UART},
Symbol,
};
use caliptra_common::RomBootStatus;
use caliptra_emu_cpu::CoverageBitmaps;
use caliptra_hw_model::{BootParams, HwModel, InitParams};
fn find_symbol<'a>(symbols: &'a [Symbol<'a>], name: &str) -> &'a Symbol<'a> {
symbols
.iter()
.find(|s| s.name == name)
.unwrap_or_else(|| panic!("Could not find symbol {name}"))
}
fn find_symbol_containing<'a>(symbols: &'a [Symbol<'a>], search: &str) -> &'a Symbol<'a> {
let mut matching_symbols = symbols.iter().filter(|s| s.name.contains(search));
let Some(result) = matching_symbols.next() else {
panic!("Could not find symbol with substring {search:?}");
};
if let Some(second_match) = matching_symbols.next() {
panic!(
"Multiple symbols matching substring {search:?}: {:?}, {:?}",
result.name, second_match.name
);
}
result
}
fn assert_symbol_not_called(hw: &caliptra_hw_model::ModelEmulated, symbol: &Symbol) {
let CoverageBitmaps { rom, iccm: _iccm } = hw.code_coverage_bitmap();
assert!(
!rom[symbol.value as usize],
"{}() was called before the boot status changed to KatStarted. This is a CFI risk, as glitching a function like that could lead to an out-of-bounds write", symbol.name);
}
#[test]
fn test_memcpy_not_called_before_cfi_init() {
for fwid in &[&ROM_WITH_UART, &ROM] {
println!("Runing with firmware {:?}", fwid);
let elf_bytes = caliptra_builder::build_firmware_elf(fwid).unwrap();
let symbols = elf_symbols(&elf_bytes).unwrap();
let rom = caliptra_builder::elf2rom(&elf_bytes).unwrap();
let mut hw = caliptra_hw_model::ModelEmulated::new(
InitParams {
rom: &rom,
..Default::default()
},
BootParams::default(),
)
.unwrap();
hw.step_until_boot_status(RomBootStatus::CfiInitialized.into(), true);
assert_symbol_not_called(&hw, find_symbol(&symbols, "memcpy"));
assert_symbol_not_called(&hw, find_symbol(&symbols, "memset"));
assert_symbol_not_called(&hw, find_symbol_containing(&symbols, "read_volatile_slice"));
assert_symbol_not_called(
&hw,
find_symbol_containing(&symbols, "write_volatile_slice"),
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_ecdsa_verify.rs | rom/dev/tests/rom_integration_tests/test_ecdsa_verify.rs | // Licensed under the Apache-2.0 license
use caliptra_common::mailbox_api::{
CommandId, EcdsaVerifyReq, MailboxReqHeader, MailboxRespHeader,
};
use caliptra_hw_model::{Fuses, HwModel, ModelError};
use caliptra_kat::CaliptraError;
use openssl::sha::sha384;
use zerocopy::{FromBytes, IntoBytes};
use crate::helpers;
#[test]
fn test_ecdsa_verify_cmd() {
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(Fuses::default(), Default::default());
// Message to hash
let msg: &[u8] = &[
0x9d, 0xd7, 0x89, 0xea, 0x25, 0xc0, 0x47, 0x45, 0xd5, 0x7a, 0x38, 0x1f, 0x22, 0xde, 0x01,
0xfb, 0x0a, 0xbd, 0x3c, 0x72, 0xdb, 0xde, 0xfd, 0x44, 0xe4, 0x32, 0x13, 0xc1, 0x89, 0x58,
0x3e, 0xef, 0x85, 0xba, 0x66, 0x20, 0x44, 0xda, 0x3d, 0xe2, 0xdd, 0x86, 0x70, 0xe6, 0x32,
0x51, 0x54, 0x48, 0x01, 0x55, 0xbb, 0xee, 0xbb, 0x70, 0x2c, 0x75, 0x78, 0x1a, 0xc3, 0x2e,
0x13, 0x94, 0x18, 0x60, 0xcb, 0x57, 0x6f, 0xe3, 0x7a, 0x05, 0xb7, 0x57, 0xda, 0x5b, 0x5b,
0x41, 0x8f, 0x6d, 0xd7, 0xc3, 0x0b, 0x04, 0x2e, 0x40, 0xf4, 0x39, 0x5a, 0x34, 0x2a, 0xe4,
0xdc, 0xe0, 0x56, 0x34, 0xc3, 0x36, 0x25, 0xe2, 0xbc, 0x52, 0x43, 0x45, 0x48, 0x1f, 0x7e,
0x25, 0x3d, 0x95, 0x51, 0x26, 0x68, 0x23, 0x77, 0x1b, 0x25, 0x17, 0x05, 0xb4, 0xa8, 0x51,
0x66, 0x02, 0x2a, 0x37, 0xac, 0x28, 0xf1, 0xbd,
];
let hash = sha384(msg);
// First test: bad signature - should fail
let mut bad_cmd = EcdsaVerifyReq {
hdr: MailboxReqHeader { chksum: 0 },
pub_key_x: [
0xcb, 0x90, 0x8b, 0x1f, 0xd5, 0x16, 0xa5, 0x7b, 0x8e, 0xe1, 0xe1, 0x43, 0x83, 0x57,
0x9b, 0x33, 0xcb, 0x15, 0x4f, 0xec, 0xe2, 0x0c, 0x50, 0x35, 0xe2, 0xb3, 0x76, 0x51,
0x95, 0xd1, 0x95, 0x1d, 0x75, 0xbd, 0x78, 0xfb, 0x23, 0xe0, 0x0f, 0xef, 0x37, 0xd7,
0xd0, 0x64, 0xfd, 0x9a, 0xf1, 0x44,
],
pub_key_y: [
0xcd, 0x99, 0xc4, 0x6b, 0x58, 0x57, 0x40, 0x1d, 0xdc, 0xff, 0x2c, 0xf7, 0xcf, 0x82,
0x21, 0x21, 0xfa, 0xf1, 0xcb, 0xad, 0x9a, 0x01, 0x1b, 0xed, 0x8c, 0x55, 0x1f, 0x6f,
0x59, 0xb2, 0xc3, 0x60, 0xf7, 0x9b, 0xfb, 0xe3, 0x2a, 0xdb, 0xca, 0xa0, 0x95, 0x83,
0xbd, 0xfd, 0xf7, 0xc3, 0x74, 0xbb,
],
// Invalid signature (modified last byte of signature_r)
signature_r: [
0x33, 0xf6, 0x4f, 0xb6, 0x5c, 0xd6, 0xa8, 0x91, 0x85, 0x23, 0xf2, 0x3a, 0xea, 0x0b,
0xbc, 0xf5, 0x6b, 0xba, 0x1d, 0xac, 0xa7, 0xaf, 0xf8, 0x17, 0xc8, 0x79, 0x1d, 0xc9,
0x24, 0x28, 0xd6, 0x05, 0xac, 0x62, 0x9d, 0xe2, 0xe8, 0x47, 0xd4, 0x3c, 0xee, 0x55,
0xba, 0x9e, 0x4a, 0x0e, 0x83, 0xbb, // Changed from 0xba to 0xbb
],
signature_s: [
0x44, 0x28, 0xbb, 0x47, 0x8a, 0x43, 0xac, 0x73, 0xec, 0xd6, 0xde, 0x51, 0xdd, 0xf7,
0xc2, 0x8f, 0xf3, 0xc2, 0x44, 0x16, 0x25, 0xa0, 0x81, 0x71, 0x43, 0x37, 0xdd, 0x44,
0xfe, 0xa8, 0x01, 0x1b, 0xae, 0x71, 0x95, 0x9a, 0x10, 0x94, 0x7b, 0x6e, 0xa3, 0x3f,
0x77, 0xe1, 0x28, 0xd3, 0xc6, 0xae,
],
hash,
};
// Calculate checksum for bad signature test
bad_cmd.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::ECDSA384_SIGNATURE_VERIFY),
&bad_cmd.as_bytes()[core::mem::size_of_val(&bad_cmd.hdr.chksum)..],
);
// This should fail because the signature is invalid
let bad_response = hw
.mailbox_execute(
CommandId::ECDSA384_SIGNATURE_VERIFY.into(),
bad_cmd.as_bytes(),
)
.unwrap_err();
assert_eq!(
bad_response,
ModelError::MailboxCmdFailed(CaliptraError::ROM_ECDSA_VERIFY_FAILED.into())
);
// Second test: good signature - should succeed
// ECDSAVS NIST test vector
let mut cmd = EcdsaVerifyReq {
hdr: MailboxReqHeader { chksum: 0 },
pub_key_x: [
0xcb, 0x90, 0x8b, 0x1f, 0xd5, 0x16, 0xa5, 0x7b, 0x8e, 0xe1, 0xe1, 0x43, 0x83, 0x57,
0x9b, 0x33, 0xcb, 0x15, 0x4f, 0xec, 0xe2, 0x0c, 0x50, 0x35, 0xe2, 0xb3, 0x76, 0x51,
0x95, 0xd1, 0x95, 0x1d, 0x75, 0xbd, 0x78, 0xfb, 0x23, 0xe0, 0x0f, 0xef, 0x37, 0xd7,
0xd0, 0x64, 0xfd, 0x9a, 0xf1, 0x44,
],
pub_key_y: [
0xcd, 0x99, 0xc4, 0x6b, 0x58, 0x57, 0x40, 0x1d, 0xdc, 0xff, 0x2c, 0xf7, 0xcf, 0x82,
0x21, 0x21, 0xfa, 0xf1, 0xcb, 0xad, 0x9a, 0x01, 0x1b, 0xed, 0x8c, 0x55, 0x1f, 0x6f,
0x59, 0xb2, 0xc3, 0x60, 0xf7, 0x9b, 0xfb, 0xe3, 0x2a, 0xdb, 0xca, 0xa0, 0x95, 0x83,
0xbd, 0xfd, 0xf7, 0xc3, 0x74, 0xbb,
],
signature_r: [
0x33, 0xf6, 0x4f, 0xb6, 0x5c, 0xd6, 0xa8, 0x91, 0x85, 0x23, 0xf2, 0x3a, 0xea, 0x0b,
0xbc, 0xf5, 0x6b, 0xba, 0x1d, 0xac, 0xa7, 0xaf, 0xf8, 0x17, 0xc8, 0x79, 0x1d, 0xc9,
0x24, 0x28, 0xd6, 0x05, 0xac, 0x62, 0x9d, 0xe2, 0xe8, 0x47, 0xd4, 0x3c, 0xee, 0x55,
0xba, 0x9e, 0x4a, 0x0e, 0x83, 0xba,
],
signature_s: [
0x44, 0x28, 0xbb, 0x47, 0x8a, 0x43, 0xac, 0x73, 0xec, 0xd6, 0xde, 0x51, 0xdd, 0xf7,
0xc2, 0x8f, 0xf3, 0xc2, 0x44, 0x16, 0x25, 0xa0, 0x81, 0x71, 0x43, 0x37, 0xdd, 0x44,
0xfe, 0xa8, 0x01, 0x1b, 0xae, 0x71, 0x95, 0x9a, 0x10, 0x94, 0x7b, 0x6e, 0xa3, 0x3f,
0x77, 0xe1, 0x28, 0xd3, 0xc6, 0xae,
],
hash,
};
// Calculate checksum
cmd.hdr.chksum = caliptra_common::checksum::calc_checksum(
u32::from(CommandId::ECDSA384_SIGNATURE_VERIFY),
&cmd.as_bytes()[core::mem::size_of_val(&cmd.hdr.chksum)..],
);
let response = hw
.mailbox_execute(CommandId::ECDSA384_SIGNATURE_VERIFY.into(), cmd.as_bytes())
.unwrap()
.unwrap();
let resp_hdr = MailboxRespHeader::ref_from_bytes(response.as_bytes()).unwrap();
// Verify response checksum
assert!(caliptra_common::checksum::verify_checksum(
resp_hdr.chksum,
0x0,
&response.as_bytes()[core::mem::size_of_val(&resp_hdr.chksum)..],
));
// Verify FIPS status
assert_eq!(
resp_hdr.fips_status,
MailboxRespHeader::FIPS_STATUS_APPROVED
);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_fake_rom.rs | rom/dev/tests/rom_integration_tests/test_fake_rom.rs | // Licensed under the Apache-2.0 license
use caliptra_api::SocManager;
use caliptra_builder::{
firmware::{
fake_rom,
rom_tests::{FAKE_TEST_FMC_INTERACTIVE, FAKE_TEST_FMC_WITH_UART},
APP_WITH_UART,
},
ImageOptions,
};
use caliptra_common::{mailbox_api::CommandId, RomBootStatus::*};
use caliptra_drivers::{Array4x12, CaliptraError};
use caliptra_hw_model::{BootParams, DeviceLifecycle, Fuses, HwModel, InitParams, SecurityState};
use crate::helpers;
const PUB_KEY_X: [u8; 48] = [
0xD7, 0x9C, 0x6D, 0x97, 0x2B, 0x34, 0xA1, 0xDF, 0xC9, 0x16, 0xA7, 0xB6, 0xE0, 0xA9, 0x9B, 0x6B,
0x53, 0x87, 0xB3, 0x4D, 0xA2, 0x18, 0x76, 0x07, 0xC1, 0xAD, 0x0A, 0x4D, 0x1A, 0x8C, 0x2E, 0x41,
0x72, 0xAB, 0x5F, 0xA5, 0xD9, 0xAB, 0x58, 0xFE, 0x45, 0xE4, 0x3F, 0x56, 0xBB, 0xB6, 0x6B, 0xA4,
];
const PUB_KEY_Y: [u8; 48] = [
0x5A, 0x73, 0x63, 0x93, 0x2B, 0x06, 0xB4, 0xF2, 0x23, 0xBE, 0xF0, 0xB6, 0x0A, 0x63, 0x90, 0x26,
0x51, 0x12, 0xDB, 0xBD, 0x0A, 0xAE, 0x67, 0xFE, 0xF2, 0x6B, 0x46, 0x5B, 0xE9, 0x35, 0xB4, 0x8E,
0x45, 0x1E, 0x68, 0xD1, 0x6F, 0x11, 0x18, 0xF2, 0xB3, 0x2B, 0x4C, 0x28, 0x60, 0x87, 0x49, 0xED,
];
#[test]
fn test_skip_kats() {
let fpga = cfg!(any(feature = "fpga_realtime", feature = "fpga_subsystem"));
let fuses = Fuses {
life_cycle: DeviceLifecycle::Manufacturing,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(fake_rom(fpga)).unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
..Default::default()
},
BootParams::default(),
)
.unwrap();
if fpga {
// If KatStarted boot status is posted before ColdResetStarted, the statement below will trigger panic.
hw.step_until(|m| {
m.soc_ifc().cptra_boot_status().read()
>= u32::from(caliptra_common::RomBootStatus::ColdResetStarted)
});
} else {
hw.step_until_boot_status(caliptra_common::RomBootStatus::CfiInitialized.into(), false);
// If KatStarted boot status is posted before ColdResetStarted, the statement below will trigger panic.
hw.step_until_boot_status(
caliptra_common::RomBootStatus::ColdResetStarted.into(),
false,
);
}
}
#[test]
fn test_fake_rom_production_error() {
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Production);
let rom =
caliptra_builder::build_firmware_rom(fake_rom(cfg!(feature = "fpga_subsystem"))).unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
security_state,
..Default::default()
},
BootParams::default(),
)
.unwrap();
// Let it run until a fatal error (should fail very early)
hw.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() != 0);
// Make sure we see the right fatal error
assert_eq!(
hw.soc_ifc().cptra_fw_error_fatal().read(),
u32::from(CaliptraError::ROM_GLOBAL_FAKE_ROM_IN_PRODUCTION)
);
}
#[test]
fn test_fake_rom_production_enabled() {
const DBG_MANUF_FAKE_ROM_PROD_EN: u32 = 0x1 << 30; // BIT 30 enables production mode
let security_state =
*SecurityState::default().set_device_lifecycle(DeviceLifecycle::Production);
let rom =
caliptra_builder::build_firmware_rom(fake_rom(cfg!(feature = "fpga_subsystem"))).unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
security_state,
..Default::default()
},
BootParams {
initial_dbg_manuf_service_reg: DBG_MANUF_FAKE_ROM_PROD_EN,
..Default::default()
},
)
.unwrap();
// Wait for ready for FW
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
}
#[test]
fn test_fake_rom_fw_load() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(fake_rom(cfg!(feature = "fpga_subsystem")))
.unwrap();
// Build the image we are going to send to ROM to load
let image_bundle = caliptra_builder::build_and_sign_image(
&FAKE_TEST_FMC_WITH_UART,
&APP_WITH_UART,
image_options,
)
.unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
..Default::default()
},
BootParams::default(),
)
.unwrap();
// Upload the FW once ROM is at the right point
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
helpers::test_upload_firmware(&mut hw, &image_bundle.to_bytes().unwrap(), *pqc_key_type);
// Make sure we actually get into FMC
hw.step_until_output_contains("Running Caliptra FMC")
.unwrap();
}
}
#[test]
fn test_fake_rom_update_reset() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(fake_rom(cfg!(feature = "fpga_subsystem")))
.unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
..Default::default()
},
BootParams::default(),
)
.unwrap();
let image_bundle = caliptra_builder::build_and_sign_image(
&FAKE_TEST_FMC_INTERACTIVE,
&APP_WITH_UART,
image_options,
)
.unwrap();
// Upload FW
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
helpers::test_upload_firmware(&mut hw, &image_bundle.to_bytes().unwrap(), *pqc_key_type);
hw.step_until_boot_status(ColdResetComplete.into(), true);
// Upload FW again
hw.start_mailbox_execute(
CommandId::FIRMWARE_LOAD.into(),
&image_bundle.to_bytes().unwrap(),
)
.unwrap();
if cfg!(not(feature = "fpga_realtime")) {
hw.step_until_boot_status(UpdateResetStarted.into(), true);
}
hw.step_until_boot_status(UpdateResetComplete.into(), true);
assert_eq!(hw.finish_mailbox_execute(), Ok(None));
// Tell the test-fmc to "exit with success" (necessary because the FMC is in
// interactive mode)
hw.mailbox_execute(0x1000_000C, &[]).unwrap();
hw.step_until_exit_success().unwrap();
}
}
#[test]
fn test_image_verify() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
const DBG_MANUF_FAKE_ROM_IMAGE_VERIFY: u32 = 0x1 << 31; // BIT 31 turns on image verify
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let rom = caliptra_builder::build_firmware_rom(fake_rom(cfg!(feature = "fpga_subsystem")))
.unwrap();
let life_cycle = fuses.life_cycle;
let mut hw = caliptra_hw_model::new(
InitParams {
fuses,
rom: &rom,
security_state: SecurityState::from(life_cycle as u32),
..Default::default()
},
BootParams {
initial_dbg_manuf_service_reg: DBG_MANUF_FAKE_ROM_IMAGE_VERIFY,
..Default::default()
},
)
.unwrap();
let mut image_bundle = caliptra_builder::build_and_sign_image(
&FAKE_TEST_FMC_WITH_UART,
&APP_WITH_UART,
image_options,
)
.unwrap();
// Modify the vendor public key.
image_bundle
.manifest
.preamble
.vendor_ecc_active_pub_key
.x
.clone_from_slice(Array4x12::from(PUB_KEY_X).0.as_slice());
image_bundle
.manifest
.preamble
.vendor_ecc_active_pub_key
.y
.clone_from_slice(Array4x12::from(PUB_KEY_Y).0.as_slice());
crate::helpers::assert_fatal_fw_load(
&mut hw,
*pqc_key_type,
&image_bundle.to_bytes().unwrap(),
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_SIGNATURE_INVALID,
);
assert_eq!(
hw.soc_ifc().cptra_boot_status().read(),
u32::from(FwProcessorManifestLoadComplete)
);
}
}
#[test]
fn test_fake_rom_version() {
const FAKE_ROM_VERSION: u16 = 0xFFFF;
let rom =
caliptra_builder::build_firmware_rom(fake_rom(cfg!(feature = "fpga_subsystem"))).unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
..Default::default()
},
BootParams::default(),
)
.unwrap();
// Wait for ready for FW
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
assert_eq!(
hw.soc_ifc().cptra_fw_rev_id().at(0).read() as u16,
FAKE_ROM_VERSION
);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/tests/rom_integration_tests/test_idevid_derivation.rs | rom/dev/tests/rom_integration_tests/test_idevid_derivation.rs | // Licensed under the Apache-2.0 license
use caliptra_api::SocManager;
use caliptra_builder::{firmware, ImageOptions};
use caliptra_common::mailbox_api::{CommandId, GetLdevCertResp, MailboxReqHeader};
use caliptra_drivers::{IdevidCertAttr, InitDevIdCsrEnvelope, MfgFlags, X509KeyIdAlgo};
use caliptra_hw_model::{DefaultHwModel, Fuses, HwModel};
use caliptra_image_types::{FwVerificationPqcKeyType, ImageBundle};
use openssl::pkey::{PKey, Public};
use openssl::x509::X509;
use openssl::{rand::rand_bytes, x509::X509Req};
use zerocopy::IntoBytes;
use crate::helpers;
const RT_READY_FOR_COMMANDS: u32 = 0x600;
const ROM_READY_FOR_FW_PROCESSOR: u32 = 70;
fn generate_csr_envelop(
hw: &mut DefaultHwModel,
image_bundle: &ImageBundle,
pqc_key_type: FwVerificationPqcKeyType,
) -> InitDevIdCsrEnvelope {
// Set gen_idev_id_csr to generate CSR.
let flags = MfgFlags::GENERATE_IDEVID_CSR;
hw.soc_ifc()
.cptra_dbg_manuf_service_reg()
.write(|_| flags.bits());
// Download the CSR Envelope from the mailbox.
let csr_envelop = helpers::get_csr_envelop(hw).unwrap();
// Wait for uploading firmware.
hw.step_until(|m| {
m.soc_ifc()
.cptra_flow_status()
.read()
.ready_for_mb_processing()
});
helpers::test_upload_firmware(hw, &image_bundle.to_bytes().unwrap(), pqc_key_type);
hw.step_until_boot_status(RT_READY_FOR_COMMANDS, true);
let output = hw.output().take(usize::MAX);
if crate::helpers::rom_from_env() == &firmware::ROM_WITH_UART {
let csr_str = helpers::get_data("[idev] ECC CSR = ", &output);
let uploaded = hex::decode(csr_str).unwrap();
assert_eq!(
uploaded,
&csr_envelop.ecc_csr.csr[..csr_envelop.ecc_csr.csr_len as usize]
);
}
csr_envelop
}
#[test]
fn test_generate_csr_envelop() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let (mut hw, image_bundle) = helpers::build_hw_model_and_image_bundle(fuses, image_options);
generate_csr_envelop(&mut hw, &image_bundle, *pqc_key_type);
}
}
#[test]
fn test_idev_subj_key_id_algo() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
for algo in 0..(X509KeyIdAlgo::Fuse as u32 + 1) {
let mut fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
fuses.idevid_cert_attr[IdevidCertAttr::Flags as usize] = algo;
let (mut hw, _image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses, image_options.clone());
hw.step_until_boot_status(ROM_READY_FOR_FW_PROCESSOR, true);
}
}
}
fn fuses_with_random_uds() -> Fuses {
const UDS_LEN: usize = core::mem::size_of::<u32>() * 16;
let mut uds_bytes = [0; UDS_LEN];
rand_bytes(&mut uds_bytes).unwrap();
let mut uds_seed = [0u32; 16];
for (word, bytes) in uds_seed.iter_mut().zip(uds_bytes.chunks_exact(4)) {
*word = u32::from_be_bytes(bytes.try_into().unwrap());
}
Fuses {
uds_seed,
..Default::default()
}
}
#[test]
fn test_generate_csr_envelop_stress() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let num_tests = if cfg!(feature = "slow_tests") { 50 } else { 1 };
for _ in 0..num_tests {
let mut fuses = fuses_with_random_uds();
fuses.fuse_pqc_key_type = *pqc_key_type as u32;
let (mut hw, image_bundle) =
helpers::build_hw_model_and_image_bundle(fuses.clone(), image_options.clone());
let csr_envelop = generate_csr_envelop(&mut hw, &image_bundle, *pqc_key_type);
// Ensure ECC CSR is valid X.509
let req =
X509Req::from_der(&csr_envelop.ecc_csr.csr[..csr_envelop.ecc_csr.csr_len as usize])
.unwrap_or_else(|_| {
panic!(
"Failed to create a valid X509 cert with UDS seed {:?}",
fuses.uds_seed
)
});
let idevid_pubkey = req.public_key().unwrap();
assert!(
req.verify(&idevid_pubkey).unwrap(),
"Invalid public key. Unable to verify CSR with UDS seed {:?}",
fuses.uds_seed
);
let ldev_cert = verify_key(
&mut hw,
u32::from(CommandId::GET_LDEV_ECC384_CERT),
&idevid_pubkey,
&fuses.uds_seed,
);
let fmc_cert = verify_key(
&mut hw,
u32::from(CommandId::GET_FMC_ALIAS_ECC384_CERT),
&ldev_cert.public_key().unwrap(),
&fuses.uds_seed,
);
let _rt_cert = verify_key(
&mut hw,
u32::from(CommandId::GET_RT_ALIAS_ECC384_CERT),
&fmc_cert.public_key().unwrap(),
&fuses.uds_seed,
);
}
}
}
fn verify_key(
hw: &mut DefaultHwModel,
cmd_id: u32,
pubkey: &PKey<Public>,
test_uds: &[u32; 16],
) -> X509 {
let payload = MailboxReqHeader {
chksum: caliptra_common::checksum::calc_checksum(cmd_id, &[]),
};
// Execute the command
let resp = hw
.mailbox_execute(cmd_id, payload.as_bytes())
.unwrap()
.unwrap();
assert!(resp.len() <= std::mem::size_of::<GetLdevCertResp>());
let mut cert_resp = GetLdevCertResp::default();
cert_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp);
// Extract the certificate from the response
let cert_der = &cert_resp.data[..(cert_resp.data_size as usize)];
let cert = openssl::x509::X509::from_der(cert_der).unwrap();
assert!(
cert.verify(pubkey).unwrap(),
"{:?} cert failed to validate with {:?} pubkey with UDS: {test_uds:?}",
cert.subject_name(),
cert.issuer_name(),
);
cert
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/test-fw/asm_tests.rs | rom/dev/test-fw/asm_tests.rs | // Licensed under the Apache-2.0 license
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), no_main)]
#[cfg(feature = "std")]
pub fn main() {}
#[cfg(not(feature = "std"))]
core::arch::global_asm!(include_str!("../src/start.S"));
#[path = "../src/exception.rs"]
mod exception;
use caliptra_common::memory_layout::{DCCM_ORG, DCCM_SIZE, ROM_STACK_SIZE};
use caliptra_drivers::cprintln;
use caliptra_drivers::ExitCtrl;
#[no_mangle]
#[inline(never)]
extern "C" fn exception_handler(exception: &exception::ExceptionRecord) {
cprintln!(
"EXCEPTION mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X}",
exception.mcause,
exception.mscause,
exception.mepc
);
ExitCtrl::exit(1);
}
#[no_mangle]
#[inline(never)]
extern "C" fn nmi_handler(exception: &exception::ExceptionRecord) {
cprintln!(
"NMI mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X}",
exception.mcause,
exception.mscause,
exception.mepc
);
ExitCtrl::exit(1);
}
#[panic_handler]
#[inline(never)]
#[cfg(not(feature = "std"))]
fn handle_panic(pi: &core::panic::PanicInfo) -> ! {
if let Some(loc) = pi.location() {
cprintln!("Panic at file {} line {}", loc.file(), loc.line())
}
ExitCtrl::exit(1);
}
unsafe fn is_zeroed(mut ptr: *const u32, mut size: usize) -> bool {
while size > 0 {
if ptr.read_volatile() != 0 {
cprintln!("Non-zero word found at 0x{:x}" ptr as usize);
return false;
}
size -= 4;
ptr = ptr.offset(1);
}
true
}
extern "C" {
fn _zero_mem256(dest: *mut u32, len: usize);
fn _copy_mem32(dest: *mut u32, src: *const u32, len: usize);
}
#[no_mangle]
pub extern "C" fn rom_entry() -> ! {
const SIZEOF_U32: usize = core::mem::size_of::<u32>();
unsafe {
// Test that memory is cleared at startup
assert!(is_zeroed(0x4000_0000 as *const u32, 1024 * 128));
// Check everything except the stack is zeroed
assert!(is_zeroed(
(DCCM_ORG + ROM_STACK_SIZE) as *const u32,
(DCCM_SIZE - ROM_STACK_SIZE) as usize
));
// Test _zero_mem256
let mut test_mem = [1; 64];
test_mem[4..12].copy_from_slice(&[0x5555_5555u32; 8]);
_zero_mem256(test_mem.as_mut_ptr().offset(4), 8 * SIZEOF_U32);
assert_eq!(test_mem[3..13], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
_zero_mem256(test_mem.as_mut_ptr().offset(13), 16 * SIZEOF_U32);
assert_eq!(
test_mem[12..30],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
);
_zero_mem256(test_mem.as_mut_ptr().offset(33), 1);
// len rounds up to the nearest 32-byte chunk
assert_eq!(test_mem[32..42], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
// Test _copy_mem32
test_mem[45..48].copy_from_slice(&[0x0011_2233, 0x4455_6677, 0x8899_aabb]);
_copy_mem32(
test_mem.as_mut_ptr().offset(50),
test_mem.as_ptr().offset(45),
3 * SIZEOF_U32,
);
assert_eq!(
test_mem[49..54],
[1, 0x0011_2233, 0x4455_6677, 0x8899_aabb, 1]
);
cprintln!("test_mem: {:?}", &test_mem[..]);
}
ExitCtrl::exit(0)
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/rom/dev/test-fw/pmp_tests.rs | rom/dev/test-fw/pmp_tests.rs | // Licensed under the Apache-2.0 license
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), no_main)]
#[cfg(feature = "std")]
pub fn main() {}
#[cfg(not(feature = "std"))]
core::arch::global_asm!(include_str!("../src/start.S"));
#[path = "../src/exception.rs"]
mod exception;
use caliptra_drivers::cprintln;
use caliptra_drivers::ExitCtrl;
#[no_mangle]
#[inline(never)]
extern "C" fn exception_handler(exception: &exception::ExceptionRecord) {
cprintln!(
"EXCEPTION mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X}",
exception.mcause,
exception.mscause,
exception.mepc
);
ExitCtrl::exit(1);
}
#[no_mangle]
#[inline(never)]
extern "C" fn nmi_handler(exception: &exception::ExceptionRecord) {
cprintln!(
"NMI mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X}",
exception.mcause,
exception.mscause,
exception.mepc
);
ExitCtrl::exit(1);
}
#[panic_handler]
#[inline(never)]
#[cfg(not(feature = "std"))]
fn handle_panic(pi: &core::panic::PanicInfo) -> ! {
if let Some(loc) = pi.location() {
cprintln!("Panic at file {} line {}", loc.file(), loc.line())
}
ExitCtrl::exit(1);
}
extern "C" {
fn _zero_mem256(dest: *mut u32, len: usize);
}
#[no_mangle]
#[cfg(not(feature = "std"))]
pub extern "C" fn rom_entry() -> ! {
unsafe {
core::arch::asm!(
"li x28, 0x14000000", // 0x5000_0000 - 0x5000_0003
"csrrw zero, pmpaddr0, x28",
"li x28, 0x90", // lock out all access to the region, naturally aligned power of 2 region >= 8 bytes
"csrrw zero, pmpcfg0, x28",
lateout("x28") _,
);
// this should trigger an exception
_zero_mem256(0x5000_0000 as *mut u32, 1);
}
ExitCtrl::exit(0)
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/build.rs | fmc/build.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
build.rs
Abstract:
Build script for Caliptra FMC
--*/
fn main() {
cfg_if::cfg_if! {
if #[cfg(not(feature = "std"))] {
use std::env;
use std::fs;
use std::path::PathBuf;
use caliptra_gen_linker_scripts::gen_memory_x;
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
fs::write(out_dir.join("memory.x"),gen_memory_x(caliptra_common::FMC_ORG, caliptra_common::FMC_SIZE)
.as_bytes())
.expect("Unable to generate memory.x");
println!("cargo:rustc-link-search={}", out_dir.display());
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg=-Tmemory.x");
println!("cargo:rustc-link-arg=-Tlink.x");
println!("cargo:rerun-if-changed=build.rs");
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/fmc_env.rs | fmc/src/fmc_env.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
fmc_env.rs
Abstract:
File implements a context holding all the services utilized by firmware.
The primary need for this abstraction is to hide the hardware details
from the ROM/FMC/RT flows. The natural side benefit of this abstraction is it
makes authoring mocks and unit tests easy.
--*/
use caliptra_drivers::{
CaliptraResult, Ecc384, Hmac, KeyVault, Mailbox, Mldsa87, PcrBank, PersistentDataAccessor,
Sha1, Sha256, Sha2_512_384, Sha2_512_384Acc, SocIfc, Trng,
};
use caliptra_registers::{
abr::AbrReg, csrng::CsrngReg, ecc::EccReg, entropy_src::EntropySrcReg, hmac::HmacReg,
kv::KvReg, mbox::MboxCsr, pv::PvReg, sha256::Sha256Reg, sha512::Sha512Reg,
sha512_acc::Sha512AccCsr, soc_ifc::SocIfcReg, soc_ifc_trng::SocIfcTrngReg,
};
/// Hardware Context
pub struct FmcEnv {
// SHA1 Engine
pub sha1: Sha1,
// SHA2-256 Engine
pub sha256: Sha256,
// SHA2-512/384 Engine
pub sha2_512_384: Sha2_512_384,
// SHA2-512/384 Accelerator
pub sha2_512_384_acc: Sha2_512_384Acc,
/// Hmac Engine
pub hmac: Hmac,
/// Ecc384 Engine
pub ecc384: Ecc384,
/// Key Vault
pub key_vault: KeyVault,
/// Device state
pub soc_ifc: SocIfc,
/// Mailbox
pub mbox: Mailbox,
/// PCR Bank
pub pcr_bank: PcrBank,
/// Cryptographically Secure Random Number Generator
pub trng: Trng,
/// Persistent Data
pub persistent_data: PersistentDataAccessor,
/// Mldsa87 Engine
pub mldsa: Mldsa87,
}
impl FmcEnv {
/// # Safety
///
/// Callers must ensure that this function is called only once, and that any
/// concurrent access to these register blocks does not conflict with these
/// drivers.
///
///
pub unsafe fn new_from_registers() -> CaliptraResult<Self> {
let trng = Trng::new(
CsrngReg::new(),
EntropySrcReg::new(),
SocIfcTrngReg::new(),
&SocIfcReg::new(),
)?;
Ok(Self {
sha1: Sha1::default(),
sha256: Sha256::new(Sha256Reg::new()),
sha2_512_384: Sha2_512_384::new(Sha512Reg::new()),
sha2_512_384_acc: Sha2_512_384Acc::new(Sha512AccCsr::new()),
hmac: Hmac::new(HmacReg::new()),
ecc384: Ecc384::new(EccReg::new()),
key_vault: KeyVault::new(KvReg::new()),
soc_ifc: SocIfc::new(SocIfcReg::new()),
mbox: Mailbox::new(MboxCsr::new()),
pcr_bank: PcrBank::new(PvReg::new()),
trng,
persistent_data: PersistentDataAccessor::new(),
mldsa: Mldsa87::new(AbrReg::new()),
})
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/main.rs | fmc/src/main.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
main.rs
Abstract:
File contains main entry point for Caliptra ROM Test FMC
--*/
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), no_main)]
use core::hint::black_box;
use caliptra_cfi_lib::{cfi_assert_eq, CfiCounter};
use caliptra_common::{
cprintln, handle_fatal_error,
keyids::{KEY_ID_RT_CDI, KEY_ID_RT_ECDSA_PRIV_KEY},
};
use caliptra_cpu::{log_trap_record, TrapRecord};
use caliptra_drivers::{
hand_off::{DataStore, HandOffDataHandle},
FwPersistentData, ResetReason, RomPersistentData,
};
mod boot_status;
mod flow;
pub mod fmc_env;
mod hand_off;
pub use boot_status::FmcBootStatus;
use caliptra_error::CaliptraError;
use caliptra_registers::soc_ifc::SocIfcReg;
use hand_off::HandOff;
#[cfg(feature = "std")]
pub fn main() {}
const BANNER: &str = r#"
Running Caliptra FMC ...
"#;
// Upon cold reset, fills the reserved field with 0xFFs. Any newly-allocated fields will
// therefore be marked as implicitly invalid.
fn fix_fht(env: &mut fmc_env::FmcEnv) {
if env.soc_ifc.reset_reason() == caliptra_drivers::ResetReason::ColdReset {
cfi_assert_eq(env.soc_ifc.reset_reason(), ResetReason::ColdReset);
env.persistent_data.get_mut().rom.fht.reserved.fill(0xFF);
}
}
#[no_mangle]
pub extern "C" fn entry_point() -> ! {
cprintln!("{}", BANNER);
let mut env = match unsafe { fmc_env::FmcEnv::new_from_registers() } {
Ok(env) => env,
Err(e) => handle_fatal_error(e.into()),
};
if !cfg!(feature = "no-cfi") {
cprintln!("[state] CFI Enabled");
let mut entropy_gen = || env.trng.generate4();
CfiCounter::reset(&mut entropy_gen);
CfiCounter::reset(&mut entropy_gen);
CfiCounter::reset(&mut entropy_gen);
} else {
cprintln!("[state] CFI Disabled");
}
let pdata = env.persistent_data.get();
if pdata.rom.marker != RomPersistentData::MAGIC {
handle_fatal_error(CaliptraError::FMC_INVALID_ROM_PERSISTENT_DATA_MARKER.into())
}
if pdata.rom.major_version != RomPersistentData::MAJOR_VERSION {
handle_fatal_error(CaliptraError::FMC_INVALID_ROM_PERSISTENT_DATA_VERSION.into())
}
fix_fht(&mut env);
if env.persistent_data.get().rom.fht.is_valid() {
// Set FHT fields and jump to RT for val-FMC for now
if cfg!(feature = "fake-fmc") {
let pdata = env.persistent_data.get_mut();
pdata.rom.minor_version = RomPersistentData::MINOR_VERSION;
pdata.fw.marker = FwPersistentData::MAGIC;
pdata.fw.version = FwPersistentData::VERSION;
pdata.rom.fht.rt_cdi_kv_hdl =
HandOffDataHandle::from(DataStore::KeyVaultSlot(KEY_ID_RT_CDI));
pdata.rom.fht.rt_priv_key_kv_hdl =
HandOffDataHandle::from(DataStore::KeyVaultSlot(KEY_ID_RT_ECDSA_PRIV_KEY));
HandOff::to_rt(&env);
}
match flow::run(&mut env) {
Ok(_) => match HandOff::is_ready_for_rt(&env) {
Ok(()) => HandOff::to_rt(&env),
Err(e) => handle_fatal_error(e.into()),
},
Err(e) => handle_fatal_error(e.into()),
}
}
caliptra_drivers::ExitCtrl::exit(0xff)
}
#[no_mangle]
#[inline(never)]
#[allow(clippy::empty_loop)]
extern "C" fn exception_handler(trap_record: &TrapRecord) {
cprintln!(
"FMC EXCEPTION mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X}",
trap_record.mcause,
trap_record.mscause,
trap_record.mepc
);
log_trap_record(trap_record, None);
handle_fatal_error(CaliptraError::FMC_GLOBAL_EXCEPTION.into());
}
#[no_mangle]
#[inline(never)]
#[allow(clippy::empty_loop)]
extern "C" fn nmi_handler(trap_record: &TrapRecord) {
let soc_ifc = unsafe { SocIfcReg::new() };
// If the NMI was fired by caliptra instead of the uC, this register
// contains the reason(s)
let err_interrupt_status = u32::from(
soc_ifc
.regs()
.intr_block_rf()
.error_internal_intr_r()
.read(),
);
log_trap_record(trap_record, Some(err_interrupt_status));
cprintln!(
"FMC NMI mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X}error_internal_intr_r={:08X}",
trap_record.mcause,
trap_record.mscause,
trap_record.mepc,
err_interrupt_status,
);
let mut error = CaliptraError::FMC_GLOBAL_NMI;
let wdt_status = soc_ifc.regs().cptra_wdt_status().read();
if wdt_status.t1_timeout() || wdt_status.t2_timeout() {
cprintln!("WDT Expired");
error = CaliptraError::FMC_GLOBAL_WDT_EXPIRED;
}
handle_fatal_error(error.into());
}
#[no_mangle]
extern "C" fn cfi_panic_handler(code: u32) -> ! {
cprintln!("[FMC] CFI Panic code=0x{:08X}", code);
handle_fatal_error(code);
}
#[panic_handler]
#[inline(never)]
#[cfg(not(feature = "std"))]
#[allow(clippy::empty_loop)]
fn fmc_panic(_: &core::panic::PanicInfo) -> ! {
cprintln!("FMC Panic!!");
panic_is_possible();
handle_fatal_error(CaliptraError::FMC_GLOBAL_PANIC.into());
}
#[no_mangle]
#[inline(never)]
fn panic_is_possible() {
black_box(());
// The existence of this symbol is used to inform test_panic_missing
// that panics are possible. Do not remove or rename this symbol.
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/boot_status.rs | fmc/src/boot_status.rs | // Licensed under the Apache-2.0 license
use core::convert::From;
const RTALIAS_BOOT_STATUS_BASE: u32 = 0x400;
/// Statuses used by ROM to log dice derivation progress.
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FmcBootStatus {
// RtAlias Statuses
RtMeasurementComplete = RTALIAS_BOOT_STATUS_BASE,
RtAliasDeriveCdiComplete = RTALIAS_BOOT_STATUS_BASE + 1,
RtAliasKeyPairDerivationComplete = RTALIAS_BOOT_STATUS_BASE + 2,
RtAliasSubjIdSnGenerationComplete = RTALIAS_BOOT_STATUS_BASE + 3,
RtAliasSubjKeyIdGenerationComplete = RTALIAS_BOOT_STATUS_BASE + 4,
RtAliasCertSigGenerationComplete = RTALIAS_BOOT_STATUS_BASE + 5,
RtAliasDerivationComplete = RTALIAS_BOOT_STATUS_BASE + 6,
}
impl From<FmcBootStatus> for u32 {
/// Converts to this type from the input type.
fn from(status: FmcBootStatus) -> u32 {
status as u32
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/hand_off.rs | fmc/src/hand_off.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
hand_off.rs
Implements handoff behavior of FMC :
- Retrieves FHT table from fixed address in DCCM.
- Transfers control to the runtime firmware.
++*/
use crate::flow::dice::DiceOutput;
use crate::fmc_env::FmcEnv;
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::cfi_impl_fn;
use caliptra_common::{handle_fatal_error, DataStore::*};
use caliptra_common::{DataStore, FirmwareHandoffTable, HandOffDataHandle, Vault};
use caliptra_drivers::{
cprintln, memory_layout, Array4x12, Ecc384Signature, KeyId, Mldsa87Signature,
};
use caliptra_drivers::{Ecc384PubKey, Mldsa87PubKey};
use caliptra_error::{CaliptraError, CaliptraResult};
#[cfg(feature = "riscv")]
core::arch::global_asm!(include_str!("transfer_control.S"));
pub struct IccmBounds {}
impl caliptra_drivers::MemBounds for IccmBounds {
const ORG: usize = memory_layout::ICCM_ORG as usize;
const SIZE: usize = memory_layout::ICCM_SIZE as usize;
const ERROR: CaliptraError = CaliptraError::ADDRESS_NOT_IN_ICCM;
}
pub type IccmAddr<T> = caliptra_drivers::BoundedAddr<T, IccmBounds>;
pub struct HandOff {}
impl HandOff {
fn fht(env: &FmcEnv) -> &FirmwareHandoffTable {
&env.persistent_data.get().rom.fht
}
fn fht_mut(env: &mut FmcEnv) -> &mut FirmwareHandoffTable {
&mut env.persistent_data.get_mut().rom.fht
}
/// Retrieve FMC CDI
pub fn fmc_cdi(env: &FmcEnv) -> KeyId {
let ds: DataStore = Self::fht(env)
.fmc_cdi_kv_hdl
.try_into()
.unwrap_or_else(|e: CaliptraError| handle_fatal_error(e.into()));
match ds {
KeyVaultSlot(key_id) => key_id,
_ => handle_fatal_error(CaliptraError::FMC_HANDOFF_INVALID_PARAM.into()),
}
}
/// Get the fmc ECC public key.
///
/// # Returns
/// * fmc ECC public key
///
pub fn fmc_ecc_pub_key(env: &FmcEnv) -> Ecc384PubKey {
env.persistent_data.get().rom.data_vault.fmc_ecc_pub_key()
}
/// Get the fmc MLDSA public key.
///
/// # Returns
/// * fmc MLDSA public key
///
pub fn fmc_mldsa_pub_key(env: &FmcEnv) -> Mldsa87PubKey {
env.persistent_data.get().rom.data_vault.fmc_mldsa_pub_key()
}
/// Retrieve FMC Alias ECC Private Key
pub fn fmc_ecc_priv_key(env: &FmcEnv) -> KeyId {
let ds: DataStore = Self::fht(env)
.fmc_ecc_priv_key_kv_hdl
.try_into()
.unwrap_or_else(|e: CaliptraError| {
cprintln!("[fht] Invalid FMC Alias ECC Private Key KV handle");
handle_fatal_error(e.into())
});
match ds {
KeyVaultSlot(key_id) => {
cprintln!("[fht] FMC Alias ECC Private Key: {:?}", u32::from(key_id));
key_id
}
_ => {
cprintln!("[fht] Invalid KeySlot DV Entry");
handle_fatal_error(CaliptraError::FMC_HANDOFF_INVALID_PARAM.into())
}
}
}
/// Retrieve FMC Alias MLDSA KeyPair Seed KV Slot
pub fn fmc_mldsa_keypair_seed_key(env: &FmcEnv) -> KeyId {
let ds: DataStore = Self::fht(env)
.fmc_mldsa_keypair_seed_kv_hdl
.try_into()
.unwrap_or_else(|e: CaliptraError| {
cprintln!("[fht] Invalid FMC Alias MLDSA Key Pair Seed KV handle");
handle_fatal_error(e.into())
});
match ds {
KeyVaultSlot(key_id) => {
cprintln!(
"[fht] FMC Alias MLDSA Key Pair Seed KV Slot: {:?}",
u32::from(key_id)
);
key_id
}
_ => {
cprintln!("[fht] Invalid KeySlot DV Entry");
handle_fatal_error(CaliptraError::FMC_HANDOFF_INVALID_PARAM.into())
}
}
}
/// Transfer control to the runtime firmware.
pub fn to_rt(env: &FmcEnv) -> ! {
// Function is defined in start.S
extern "C" {
fn transfer_control(entry: u32) -> !;
}
let rt_entry_point = Self::rt_entry_point(env);
match IccmAddr::<u32>::validate_addr(rt_entry_point) {
Ok(_) => unsafe { transfer_control(rt_entry_point) },
Err(e) => {
cprintln!("[fht] Invalid RT Entry Point");
handle_fatal_error(e.into());
}
}
}
/// Retrieve runtime TCI (digest)
pub fn rt_tci(env: &FmcEnv) -> Array4x12 {
env.persistent_data.get().rom.data_vault.rt_tci()
}
/// Retrieve firmware SVN.
pub fn fw_svn(env: &FmcEnv) -> u32 {
env.persistent_data.get().rom.data_vault.fw_svn()
}
/// Store runtime Dice ECC Signature
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn set_rt_dice_ecc_signature(env: &mut FmcEnv, sig: &Ecc384Signature) {
Self::fht_mut(env).rt_dice_ecc_sign = *sig;
}
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn set_rtalias_ecc_tbs_size(env: &mut FmcEnv, rtalias_tbs_size: usize) {
Self::fht_mut(env).rtalias_ecc_tbs_size = rtalias_tbs_size as u16;
}
/// Store runtime Dice MLDSA Signature
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn set_rt_dice_mldsa_signature(env: &mut FmcEnv, sig: &Mldsa87Signature) {
// Self::fht_mut(env).rt_dice_mldsa_sign = *sig;
env.persistent_data.get_mut().fw.rt_dice_mldsa_sign = *sig;
}
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn set_rtalias_mldsa_tbs_size(env: &mut FmcEnv, rtalias_tbs_size: usize) {
env.persistent_data.get_mut().fw.rtalias_mldsa_tbs_size = rtalias_tbs_size as u16;
}
/// Retrieve the entry point of the runtime firmware.
fn rt_entry_point(env: &FmcEnv) -> u32 {
env.persistent_data.get().rom.data_vault.rt_entry_point()
}
/// The FMC CDI is stored in a 32-bit DataVault sticky register.
fn key_id_to_handle(key_id: KeyId) -> HandOffDataHandle {
HandOffDataHandle(((Vault::KeyVault as u32) << 12) | key_id as u32)
}
/// Update HandOff Table with RT Parameters
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn update(env: &mut FmcEnv, out: DiceOutput) -> CaliptraResult<()> {
// update fht.rt_cdi_kv_hdl
Self::fht_mut(env).rt_cdi_kv_hdl = Self::key_id_to_handle(out.cdi);
Self::fht_mut(env).rt_priv_key_kv_hdl =
Self::key_id_to_handle(out.ecc_subj_key_pair.priv_key);
Self::fht_mut(env).rt_dice_ecc_pub_key = out.ecc_subj_key_pair.pub_key;
Ok(())
}
/// Check if the HandOff Table is ready for RT by ensuring RTAlias CDI and
/// private key handles are valid.
pub fn is_ready_for_rt(env: &FmcEnv) -> CaliptraResult<()> {
let fht = Self::fht(env);
if fht.rt_cdi_kv_hdl.is_valid() && fht.rt_priv_key_kv_hdl.is_valid() {
Ok(())
} else {
Err(CaliptraError::FMC_HANDOFF_NOT_READY_FOR_RT)
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/flow/dice.rs | fmc/src/flow/dice.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
dice.rs
Abstract:
File contains interface and definitions for common Device Identity
Composition Engine (DICE) functionality.
--*/
use caliptra_drivers::KeyId;
use caliptra_common::crypto::{Ecc384KeyPair, MlDsaKeyPair};
/// DICE Layer Input
#[derive(Debug)]
pub struct DiceInput {
/// Composite Device Identity (CDI)
///
/// This field will act as an input and output for the CDI.
/// * On input, this field will be used as a key for CDI derivation function.
/// * On output, this field will hold the CDI of the current layer.
pub cdi: KeyId,
/// Authority Key Pair
pub ecc_auth_key_pair: Ecc384KeyPair,
/// Authority Serial Number
pub ecc_auth_sn: [u8; 64],
/// Authority Key Identifier
pub ecc_auth_key_id: [u8; 20],
/// MLDSA Authority Key Pair
pub mldsa_auth_key_pair: MlDsaKeyPair,
/// MLDSA Authority Serial Number
pub mldsa_auth_sn: [u8; 64],
/// MLDSA Authority Key Identifier
pub mldsa_auth_key_id: [u8; 20],
}
/// DICE Layer Output
#[derive(Debug)]
pub struct DiceOutput {
/// CDI
pub cdi: KeyId,
/// Subject key pair for this layer
pub ecc_subj_key_pair: Ecc384KeyPair,
/// Subject Serial Number
pub ecc_subj_sn: [u8; 64],
/// Subject Key Identifier
pub ecc_subj_key_id: [u8; 20],
/// MLDSA Subject key pair for this layer
pub mldsa_subj_key_pair: MlDsaKeyPair,
/// MLDSA Subject Serial Number
pub mldsa_subj_sn: [u8; 64],
/// MLDSA Subject Key Identifier
pub mldsa_subj_key_id: [u8; 20],
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/flow/tci.rs | fmc/src/flow/tci.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
tci.rs
Abstract:
File contains execution routines for TCI computation
Environment:
FMC
--*/
use crate::fmc_env::FmcEnv;
use caliptra_drivers::{Array4x12, CaliptraResult};
use zerocopy::IntoBytes;
pub struct Tci {}
impl Tci {
/// Compute Image Manifest Digest
///
/// # Arguments
///
/// * `env` - ROM Environment
pub fn image_manifest_digest(env: &mut FmcEnv) -> CaliptraResult<Array4x12> {
let manifest = env.persistent_data.get().rom.manifest1;
env.sha2_512_384.sha384_digest(manifest.as_bytes())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/flow/mod.rs | fmc/src/flow/mod.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
mod.rs
Abstract:
File contains the top level dispatch of various RT Flows.
--*/
pub mod dice;
mod fmc_alias_csr_ecc_384;
mod pcr;
mod rt_alias;
mod tci;
use crate::flow::rt_alias::RtAliasLayer;
use crate::fmc_env::FmcEnv;
use caliptra_cfi_lib::cfi_assert_ne;
use caliptra_drivers::{CaliptraResult, FwPersistentData, RomPersistentData};
use caliptra_error::CaliptraError;
/// Execute FMC Flows based on reset reason
///
/// # Arguments
///
/// * `env` - FMC Environment
pub fn run(env: &mut FmcEnv) -> CaliptraResult<()> {
{
use caliptra_cfi_lib::cfi_assert_eq;
use caliptra_drivers::ResetReason;
let reset_reason = env.soc_ifc.reset_reason();
if reset_reason == ResetReason::ColdReset {
cfi_assert_eq(env.soc_ifc.reset_reason(), ResetReason::ColdReset);
let pdata = env.persistent_data.get_mut();
pdata.rom.minor_version = RomPersistentData::MINOR_VERSION;
pdata.fw.marker = FwPersistentData::MAGIC;
pdata.fw.version = FwPersistentData::VERSION;
// Generate the FMC Alias Certificate Signing Request (CSR)
fmc_alias_csr_ecc_384::generate_csr(env)?;
} else {
cfi_assert_ne(env.soc_ifc.reset_reason(), ResetReason::ColdReset);
let pdata = env.persistent_data.get();
if pdata.rom.minor_version != RomPersistentData::MINOR_VERSION {
return Err(CaliptraError::FMC_INVALID_ROM_PERSISTENT_DATA_VERSION);
}
if pdata.fw.marker != FwPersistentData::MAGIC {
return Err(CaliptraError::FMC_INVALID_FW_PERSISTENT_DATA_MARKER);
}
if pdata.fw.version != FwPersistentData::VERSION {
return Err(CaliptraError::FMC_INVALID_FW_PERSISTENT_DATA_VERSION);
}
}
}
RtAliasLayer::run(env)
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/flow/rt_alias.rs | fmc/src/flow/rt_alias.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
rt_alias.rs
Abstract:
Alias RT DICE Layer & PCR extension
--*/
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::cfi_impl_fn;
use caliptra_cfi_lib::{cfi_assert, cfi_assert_bool, cfi_assert_eq, cfi_launder};
use caliptra_common::x509;
use crate::flow::dice::{DiceInput, DiceOutput};
use crate::flow::pcr::extend_pcr_common;
use crate::flow::tci::Tci;
use crate::fmc_env::FmcEnv;
use crate::FmcBootStatus;
use crate::HandOff;
use caliptra_common::cfi_check;
use caliptra_common::cprintln;
use caliptra_common::crypto::{Crypto, Ecc384KeyPair, MlDsaKeyPair, PubKey};
use caliptra_common::keyids::{
KEY_ID_RT_CDI, KEY_ID_RT_ECDSA_PRIV_KEY, KEY_ID_RT_MLDSA_KEYPAIR_SEED, KEY_ID_TMP,
};
use caliptra_common::HexBytes;
use caliptra_drivers::{
okref, report_boot_status, CaliptraError, CaliptraResult, Ecc384Result, HmacMode, KeyId,
KeyUsage, Mldsa87Result, PersistentData, ResetReason,
};
use caliptra_x509::{
NotAfter, NotBefore, RtAliasCertTbsEcc384, RtAliasCertTbsEcc384Params, RtAliasCertTbsMlDsa87,
RtAliasCertTbsMlDsa87Params,
};
use zerocopy::IntoBytes;
const SHA384_HASH_SIZE: usize = 48;
#[derive(Default)]
pub struct RtAliasLayer {}
impl RtAliasLayer {
/// Perform derivations for the DICE layer
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
fn derive(env: &mut FmcEnv, input: &DiceInput) -> CaliptraResult<DiceOutput> {
if Self::kv_slot_collides(input.cdi) {
return Err(CaliptraError::FMC_CDI_KV_COLLISION);
}
if Self::kv_slot_collides(input.ecc_auth_key_pair.priv_key)
|| Self::kv_slot_collides(input.mldsa_auth_key_pair.key_pair_seed)
{
return Err(CaliptraError::FMC_ALIAS_KV_COLLISION);
}
cprintln!("[alias rt] Derive CDI");
cprintln!("[alias rt] Store it in slot 0x{:x}", KEY_ID_RT_CDI as u8);
// Derive CDI
Self::derive_cdi(env, input.cdi, KEY_ID_RT_CDI)?;
report_boot_status(FmcBootStatus::RtAliasDeriveCdiComplete as u32);
cprintln!("[alias rt] Derive Key Pair");
cprintln!(
"[alias rt] Store ECC priv key in slot 0x{:x} and MLDSA key pair seed in slot 0x{:x}",
KEY_ID_RT_ECDSA_PRIV_KEY as u8,
KEY_ID_RT_MLDSA_KEYPAIR_SEED as u8,
);
// Derive DICE ECC and MLDSA Key Pairs from CDI
let (ecc_key_pair, mldsa_key_pair) = Self::derive_key_pair(
env,
KEY_ID_RT_CDI,
KEY_ID_RT_ECDSA_PRIV_KEY,
KEY_ID_RT_MLDSA_KEYPAIR_SEED,
)?;
cprintln!("[alias rt] Derive Key Pair - Done");
report_boot_status(FmcBootStatus::RtAliasKeyPairDerivationComplete as u32);
// Generate the Subject Serial Number and Subject Key Identifier.
//
// This information will be used by next DICE Layer while generating
// certificates
let ecc_subj_sn = x509::subj_sn(&mut env.sha256, &PubKey::Ecc(&ecc_key_pair.pub_key))?;
let mldsa_subj_sn =
x509::subj_sn(&mut env.sha256, &PubKey::Mldsa(&mldsa_key_pair.pub_key))?;
report_boot_status(FmcBootStatus::RtAliasSubjIdSnGenerationComplete.into());
let ecc_subj_key_id =
x509::subj_key_id(&mut env.sha256, &PubKey::Ecc(&ecc_key_pair.pub_key))?;
let mldsa_subj_key_id =
x509::subj_key_id(&mut env.sha256, &PubKey::Mldsa(&mldsa_key_pair.pub_key))?;
report_boot_status(FmcBootStatus::RtAliasSubjKeyIdGenerationComplete.into());
// Generate the output for next layer
let output = DiceOutput {
cdi: KEY_ID_RT_CDI,
ecc_subj_key_pair: ecc_key_pair,
ecc_subj_sn,
ecc_subj_key_id,
mldsa_subj_key_pair: mldsa_key_pair,
mldsa_subj_sn,
mldsa_subj_key_id,
};
let manifest = &env.persistent_data.get().rom.manifest1;
let (nb, nf) = Self::get_cert_validity_info(manifest);
// Generate Rt Alias Certificate
Self::generate_cert_sig(env, input, &output, &nb.value, &nf.value)?;
Ok(output)
}
fn kv_slot_collides(slot: KeyId) -> bool {
slot == KEY_ID_RT_CDI
|| slot == KEY_ID_RT_ECDSA_PRIV_KEY
|| slot == KEY_ID_RT_MLDSA_KEYPAIR_SEED
|| slot == KEY_ID_TMP
}
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
#[inline(never)]
pub fn run(env: &mut FmcEnv) -> CaliptraResult<()> {
cprintln!("[alias rt] Extend RT PCRs");
Self::extend_pcrs(env)?;
cprintln!("[alias rt] Extend RT PCRs Done");
cprintln!("[alias rt] Lock RT PCRs");
env.pcr_bank
.set_pcr_lock(caliptra_common::RT_FW_CURRENT_PCR);
env.pcr_bank
.set_pcr_lock(caliptra_common::RT_FW_JOURNEY_PCR);
cprintln!("[alias rt] Lock RT PCRs Done");
report_boot_status(crate::FmcBootStatus::RtMeasurementComplete as u32);
// Retrieve Dice Input Layer from Hand Off and Derive Key
match Self::dice_input_from_hand_off(env) {
Ok(input) => {
let out = Self::derive(env, &input)?;
report_boot_status(crate::FmcBootStatus::RtAliasDerivationComplete as u32);
HandOff::update(env, out)
}
_ => Err(CaliptraError::FMC_RT_ALIAS_DERIVE_FAILURE),
}
}
/// Retrieve DICE Input from HandsOff
///
/// # Arguments
///
/// * `hand_off` - HandOff
///
/// # Returns
///
/// * `DiceInput` - DICE Layer Input
fn dice_input_from_hand_off(env: &mut FmcEnv) -> CaliptraResult<DiceInput> {
let ecc_auth_pub = HandOff::fmc_ecc_pub_key(env);
let ecc_auth_sn = x509::subj_sn(&mut env.sha256, &PubKey::Ecc(&ecc_auth_pub))?;
let ecc_auth_key_id = x509::subj_key_id(&mut env.sha256, &PubKey::Ecc(&ecc_auth_pub))?;
let mldsa_auth_pub = HandOff::fmc_mldsa_pub_key(env);
let mldsa_auth_sn = x509::subj_sn(&mut env.sha256, &PubKey::Mldsa(&mldsa_auth_pub))?;
let mldsa_auth_key_id =
x509::subj_key_id(&mut env.sha256, &PubKey::Mldsa(&mldsa_auth_pub))?;
// Create initial output
let input = DiceInput {
cdi: HandOff::fmc_cdi(env),
ecc_auth_key_pair: Ecc384KeyPair {
priv_key: HandOff::fmc_ecc_priv_key(env),
pub_key: ecc_auth_pub,
},
mldsa_auth_key_pair: MlDsaKeyPair {
key_pair_seed: HandOff::fmc_mldsa_keypair_seed_key(env),
pub_key: mldsa_auth_pub,
},
ecc_auth_sn,
ecc_auth_key_id,
mldsa_auth_sn,
mldsa_auth_key_id,
};
Ok(input)
}
/// Extend current and journey PCRs
///
/// # Arguments
///
/// * `env` - FMC Environment
/// * `hand_off` - HandOff
pub fn extend_pcrs(env: &mut FmcEnv) -> CaliptraResult<()> {
let reset_reason = env.soc_ifc.reset_reason();
match reset_reason {
ResetReason::ColdReset => {
cfi_assert_eq(reset_reason, ResetReason::ColdReset);
extend_pcr_common(env)
}
ResetReason::UpdateReset => {
cfi_assert_eq(reset_reason, ResetReason::UpdateReset);
extend_pcr_common(env)
}
ResetReason::WarmReset => {
cfi_assert_eq(reset_reason, ResetReason::WarmReset);
Ok(())
}
ResetReason::Unknown => {
cfi_assert_eq(reset_reason, ResetReason::Unknown);
Err(CaliptraError::FMC_UNKNOWN_RESET)
}
}
}
fn get_cert_validity_info(
manifest: &caliptra_image_types::ImageManifest,
) -> (NotBefore, NotAfter) {
// If there is a valid value in the manifest for the not_before and not_after times,
// use those. Otherwise use the default values.
let mut nb = NotBefore::default();
let mut nf = NotAfter::default();
let null_time = [0u8; 15];
if manifest.header.vendor_data.vendor_not_after != null_time
&& manifest.header.vendor_data.vendor_not_before != null_time
{
nf.value = manifest.header.vendor_data.vendor_not_after;
nb.value = manifest.header.vendor_data.vendor_not_before;
}
// Owner values take preference.
if manifest.header.owner_data.owner_not_after != null_time
&& manifest.header.owner_data.owner_not_before != null_time
{
nf.value = manifest.header.owner_data.owner_not_after;
nb.value = manifest.header.owner_data.owner_not_before;
}
(nb, nf)
}
/// Permute Composite Device Identity (CDI) using Rt TCI and Image Manifest Digest
/// The RT Alias CDI will overwrite the FMC Alias CDI in the KeyVault Slot
///
/// # Arguments
///
/// * `env` - ROM Environment
/// * `fmc_cdi` - Key Slot that holds the current CDI
/// * `rt_cdi` - Key Slot to store the generated CDI
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
fn derive_cdi(env: &mut FmcEnv, fmc_cdi: KeyId, rt_cdi: KeyId) -> CaliptraResult<()> {
// Compose FMC TCI (1. RT TCI, 2. Image Manifest Digest)
let mut tci = [0u8; 2 * SHA384_HASH_SIZE];
let rt_tci: [u8; 48] = HandOff::rt_tci(env).into();
tci[0..SHA384_HASH_SIZE].copy_from_slice(&rt_tci);
let image_manifest_digest: Result<_, CaliptraError> = Tci::image_manifest_digest(env);
let image_manifest_digest: [u8; 48] = okref(&image_manifest_digest)?.into();
tci[SHA384_HASH_SIZE..2 * SHA384_HASH_SIZE].copy_from_slice(&image_manifest_digest);
// Permute CDI from FMC TCI
Crypto::hmac_kdf(
&mut env.hmac,
&mut env.trng,
fmc_cdi,
b"alias_rt_cdi",
Some(&tci),
rt_cdi,
HmacMode::Hmac512,
KeyUsage::default()
.set_ecc_key_gen_seed_en()
.set_mldsa_key_gen_seed_en()
.set_hmac_key_en(),
)?;
report_boot_status(FmcBootStatus::RtAliasDeriveCdiComplete as u32);
Ok(())
}
/// Derive Dice Layer Key Pair
///
/// # Arguments
///
/// * `env` - Fmc Environment
/// * `cdi` - Composite Device Identity
/// * `ecc_priv_key` - Key slot to store the ECC private key into
/// * `mldsa_keypair_seed` - Key slot to store the MLDSA key pair seed
///
/// # Returns
///
/// * `(Ecc384KeyPair, MlDsaKeyPair)` - DICE Layer ECC and MLDSA Key Pairs
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
fn derive_key_pair(
env: &mut FmcEnv,
cdi: KeyId,
ecc_priv_key: KeyId,
mldsa_keypair_seed: KeyId,
) -> CaliptraResult<(Ecc384KeyPair, MlDsaKeyPair)> {
let result = Crypto::ecc384_key_gen(
&mut env.ecc384,
&mut env.hmac,
&mut env.trng,
&mut env.key_vault,
cdi,
b"alias_rt_ecc_key",
ecc_priv_key,
);
cfi_check!(result);
let ecc_keypair = result?;
// Derive the MLDSA Key Pair.
let result = Crypto::mldsa87_key_gen(
&mut env.mldsa,
&mut env.hmac,
&mut env.trng,
cdi,
b"alias_rt_mldsa_key",
mldsa_keypair_seed,
);
cfi_check!(result);
let mldsa_keypair = result?;
Ok((ecc_keypair, mldsa_keypair))
}
/// Generate Local Device ID Certificate Signature
///
/// # Arguments
///
/// * `env` - FMC Environment
/// * `input` - DICE Input
/// * `output` - DICE Output
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
fn generate_cert_sig(
env: &mut FmcEnv,
input: &DiceInput,
output: &DiceOutput,
not_before: &[u8; RtAliasCertTbsEcc384Params::NOT_BEFORE_LEN],
not_after: &[u8; RtAliasCertTbsEcc384Params::NOT_AFTER_LEN],
) -> CaliptraResult<()> {
Self::generate_ecc_cert_sig(env, input, output, not_before, not_after)?;
Self::generate_mldsa_cert_sig(env, input, output, not_before, not_after)?;
report_boot_status(FmcBootStatus::RtAliasCertSigGenerationComplete as u32);
Ok(())
}
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
fn generate_ecc_cert_sig(
env: &mut FmcEnv,
input: &DiceInput,
output: &DiceOutput,
not_before: &[u8; RtAliasCertTbsEcc384Params::NOT_BEFORE_LEN],
not_after: &[u8; RtAliasCertTbsEcc384Params::NOT_AFTER_LEN],
) -> CaliptraResult<()> {
let auth_priv_key = input.ecc_auth_key_pair.priv_key;
let auth_pub_key = &input.ecc_auth_key_pair.pub_key;
let pub_key = &output.ecc_subj_key_pair.pub_key;
let serial_number = &x509::ecc_cert_sn(&mut env.sha256, pub_key)?;
let rt_tci: [u8; 48] = HandOff::rt_tci(env).into();
let fw_svn = HandOff::fw_svn(env) as u8;
// Certificate `To Be Signed` Parameters
let params = RtAliasCertTbsEcc384Params {
// Do we need the UEID here?
ueid: &x509::ueid(&env.soc_ifc)?,
subject_sn: &output.ecc_subj_sn,
subject_key_id: &output.ecc_subj_key_id,
issuer_sn: &input.ecc_auth_sn,
authority_key_id: &input.ecc_auth_key_id,
serial_number,
public_key: &pub_key.to_der(),
not_before,
not_after,
tcb_info_fw_svn: &fw_svn.to_be_bytes(),
tcb_info_rt_tci: &rt_tci,
// Are there any fields missing?
};
// Generate the `To Be Signed` portion of the CSR
let tbs = RtAliasCertTbsEcc384::new(¶ms);
// Sign the `To Be Signed` portion
cprintln!(
"[alias rt] Signing ECC Cert with AUTHORITY.KEYID = {}",
auth_priv_key as u8
);
// Sign the AliasRt To Be Signed DER Blob with AliasFMC Private Key in Key Vault Slot 7
let sig = Crypto::ecdsa384_sign(
&mut env.sha2_512_384,
&mut env.ecc384,
&mut env.trng,
auth_priv_key,
auth_pub_key,
tbs.tbs(),
);
let sig = okref(&sig)?;
// Lock the authority private key and FMC CDI
cprintln!(
"[alias rt] Locking ECC AUTHORITY.KEYID = {} & FMC CDI = {}",
auth_priv_key as u8,
input.cdi as u8
);
// FMC ensures that CDIFMC and PrivateKeyFMC are locked to block further usage until the next boot.
env.key_vault.set_key_use_lock(auth_priv_key);
env.key_vault.set_key_use_lock(input.cdi);
let _pub_x: [u8; 48] = (&pub_key.x).into();
let _pub_y: [u8; 48] = (&pub_key.y).into();
cprintln!("[alias rt] ECC PUB.X = {}", HexBytes(&_pub_x));
cprintln!("[alias rt] ECC PUB.Y = {}", HexBytes(&_pub_y));
let _sig_r: [u8; 48] = (&sig.r).into();
let _sig_s: [u8; 48] = (&sig.s).into();
cprintln!("[alias rt] ECC SIG.R = {}", HexBytes(&_sig_r));
cprintln!("[alias rt] ECC SIG.S = {}", HexBytes(&_sig_s));
// Verify the signature of the `To Be Signed` portion
if Crypto::ecdsa384_verify(
&mut env.sha2_512_384,
&mut env.ecc384,
auth_pub_key,
tbs.tbs(),
sig,
)? != Ecc384Result::Success
{
return Err(CaliptraError::FMC_RT_ALIAS_CERT_VERIFY);
}
HandOff::set_rt_dice_ecc_signature(env, sig);
// Copy TBS to DCCM and set size in FHT.
Self::copy_ecc_tbs(tbs.tbs(), env.persistent_data.get_mut())?;
HandOff::set_rtalias_ecc_tbs_size(env, tbs.tbs().len());
Ok(())
}
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
fn generate_mldsa_cert_sig(
env: &mut FmcEnv,
input: &DiceInput,
output: &DiceOutput,
not_before: &[u8; RtAliasCertTbsMlDsa87Params::NOT_BEFORE_LEN],
not_after: &[u8; RtAliasCertTbsMlDsa87Params::NOT_AFTER_LEN],
) -> CaliptraResult<()> {
let key_pair_seed = input.mldsa_auth_key_pair.key_pair_seed;
let auth_pub_key = &input.mldsa_auth_key_pair.pub_key;
let pub_key = &output.mldsa_subj_key_pair.pub_key;
let serial_number = &x509::mldsa_cert_sn(&mut env.sha256, pub_key)?;
let rt_tci: [u8; 48] = HandOff::rt_tci(env).into();
let fw_svn = HandOff::fw_svn(env) as u8;
// Certificate `To Be Signed` Parameters
let params = RtAliasCertTbsMlDsa87Params {
ueid: &x509::ueid(&env.soc_ifc)?,
subject_sn: &output.mldsa_subj_sn,
subject_key_id: &output.mldsa_subj_key_id,
issuer_sn: &input.mldsa_auth_sn,
authority_key_id: &input.mldsa_auth_key_id,
serial_number,
public_key: pub_key
.as_bytes()
.try_into()
.map_err(|_| CaliptraError::RUNTIME_GET_RT_ALIAS_CERT_FAILED)?,
not_before,
not_after,
tcb_info_fw_svn: &fw_svn.to_be_bytes(),
tcb_info_rt_tci: &rt_tci,
};
// Generate the `To Be Signed` portion of the CSR
let tbs = RtAliasCertTbsMlDsa87::new(¶ms);
// Sign the `To Be Signed` portion
cprintln!(
"[alias rt] Signing MLDSA Cert with AUTHORITY.KEYID = {}",
key_pair_seed as u8
);
// Sign the AliasRt To Be Signed DER Blob with AliasFMC Private Key in Key Vault Slot 7
let sig = Crypto::mldsa87_sign(
&mut env.mldsa,
&mut env.trng,
key_pair_seed,
auth_pub_key,
tbs.tbs(),
);
let sig = okref(&sig)?;
// Lock the authority private key and FMC CDI
cprintln!(
"[alias rt] Locking MLDSA AUTHORITY.KEYID = {} & FMC CDI = {}",
key_pair_seed as u8,
input.cdi as u8
);
// FMC ensures that CDIFMC and PrivateKeyFMC are locked to block further usage until the next boot.
env.key_vault.set_key_use_lock(key_pair_seed);
env.key_vault.set_key_use_lock(input.cdi);
// Verify the signature of the `To Be Signed` portion
if Crypto::mldsa87_verify(&mut env.mldsa, auth_pub_key, tbs.tbs(), sig)?
!= Mldsa87Result::Success
{
return Err(CaliptraError::FMC_RT_ALIAS_CERT_VERIFY);
}
HandOff::set_rt_dice_mldsa_signature(env, sig);
// Copy TBS to DCCM and set size in FHT.
Self::copy_mldsa_tbs(tbs.tbs(), env.persistent_data.get_mut())?;
HandOff::set_rtalias_mldsa_tbs_size(env, tbs.tbs().len());
Ok(())
}
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
fn copy_ecc_tbs(tbs: &[u8], persistent_data: &mut PersistentData) -> CaliptraResult<()> {
let Some(dest) = persistent_data.fw.ecc_rtalias_tbs.get_mut(..tbs.len()) else {
return Err(CaliptraError::FMC_RT_ALIAS_ECC_TBS_SIZE_EXCEEDED);
};
dest.copy_from_slice(tbs);
Ok(())
}
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
fn copy_mldsa_tbs(tbs: &[u8], persistent_data: &mut PersistentData) -> CaliptraResult<()> {
let Some(dest) = persistent_data.fw.mldsa_rtalias_tbs.get_mut(..tbs.len()) else {
return Err(CaliptraError::FMC_RT_ALIAS_MLDSA_TBS_SIZE_EXCEEDED);
};
dest.copy_from_slice(tbs);
Ok(())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/flow/pcr.rs | fmc/src/flow/pcr.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
pcr.rs
Abstract:
File contains execution routines for extending current and journey PCRs.
Environment:
FMC
Note:
PCR2 - Current PCR unlocked and cleared on any reset
PCR3 - Journey PCR unlocked and cleared on cold reset
--*/
use crate::flow::tci::Tci;
use crate::fmc_env::FmcEnv;
use crate::HandOff;
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::cfi_mod_fn;
use caliptra_common::{RT_FW_CURRENT_PCR, RT_FW_JOURNEY_PCR};
use caliptra_drivers::{
okref,
pcr_log::{PcrLogEntry, PcrLogEntryId},
CaliptraResult, PersistentData,
};
use caliptra_error::CaliptraError;
use zerocopy::IntoBytes;
/// Extend common data into the RT current and journey PCRs
///
/// # Arguments
///
/// * `env` - FMC Environment
/// * `pcr_id` - PCR slot to extend the data into
#[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)]
pub fn extend_pcr_common(env: &mut FmcEnv) -> CaliptraResult<()> {
// Calculate RT TCI (Hash over runtime code)
let rt_tci: [u8; 48] = HandOff::rt_tci(env).into();
// Calculate FW Image Manifest digest
let manifest_digest = Tci::image_manifest_digest(env);
let manifest_digest: [u8; 48] = okref(&manifest_digest)?.into();
// Clear current PCR before extending it.
env.pcr_bank.erase_pcr(RT_FW_CURRENT_PCR)?;
extend_and_log(env, PcrLogEntryId::RtTci, &rt_tci)?;
extend_and_log(env, PcrLogEntryId::FwImageManifest, &manifest_digest)?;
Ok(())
}
/// Extend `data` into both the current and journey PCRs, and updates the PCR log.
#[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)]
fn extend_and_log(env: &mut FmcEnv, entry_id: PcrLogEntryId, data: &[u8]) -> CaliptraResult<()> {
env.pcr_bank
.extend_pcr(RT_FW_CURRENT_PCR, &mut env.sha2_512_384, data)?;
env.pcr_bank
.extend_pcr(RT_FW_JOURNEY_PCR, &mut env.sha2_512_384, data)?;
log_pcr(
env.persistent_data.get_mut(),
entry_id,
(1 << RT_FW_CURRENT_PCR as u8) | (1 << RT_FW_JOURNEY_PCR as u8),
data,
)
}
#[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)]
fn log_pcr(
persistent_data: &mut PersistentData,
pcr_entry_id: PcrLogEntryId,
pcr_ids: u32,
data: &[u8],
) -> CaliptraResult<()> {
let fht = &mut persistent_data.rom.fht;
let Some(dst) = persistent_data
.rom
.pcr_log
.get_mut(fht.pcr_log_index as usize)
else {
return Err(CaliptraError::FMC_GLOBAL_PCR_LOG_EXHAUSTED);
};
// Create a PCR log entry
*dst = PcrLogEntry {
id: pcr_entry_id as u16,
pcr_ids,
..Default::default()
};
dst.pcr_data.as_mut_bytes()[..data.len()].copy_from_slice(data);
fht.pcr_log_index += 1;
Ok(())
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/src/flow/fmc_alias_csr_ecc_384.rs | fmc/src/flow/fmc_alias_csr_ecc_384.rs | // Licensed under the Apache-2.0 license
use crate::flow::dice::DiceOutput;
use crate::fmc_env::FmcEnv;
use crate::HandOff;
use caliptra_common::{
crypto::{Crypto, Ecc384KeyPair, MlDsaKeyPair, PubKey},
dice, x509,
};
use caliptra_drivers::{
okmutref, sha2_512_384::Sha2DigestOpTrait, Array4x12, CaliptraError, CaliptraResult,
Ecc384Signature,
};
use caliptra_x509::{
Ecdsa384CsrBuilder, Ecdsa384Signature, FmcAliasCsrTbsEcc384, FmcAliasCsrTbsEcc384Params,
FmcAliasTbsMlDsa87, FmcAliasTbsMlDsa87Params, MlDsa87CsrBuilder,
};
use zerocopy::IntoBytes;
use zeroize::Zeroize;
pub trait Ecdsa384SignatureAdapter {
/// Convert to ECDSA Signature
fn to_ecdsa(&self) -> Ecdsa384Signature;
}
impl Ecdsa384SignatureAdapter for Ecc384Signature {
/// Convert to ECDSA Signature
fn to_ecdsa(&self) -> Ecdsa384Signature {
Ecdsa384Signature {
r: (&self.r).into(),
s: (&self.s).into(),
}
}
}
/// Retrieve DICE Output from HandOff
///
/// # Arguments
///
/// * `env` - FMC Environment
///
/// # Returns
///
/// * `DiceInput` - DICE Layer Input
fn dice_output_from_hand_off(env: &mut FmcEnv) -> CaliptraResult<DiceOutput> {
let ecc_auth_pub = HandOff::fmc_ecc_pub_key(env);
let ecc_subj_sn = x509::subj_sn(&mut env.sha256, &PubKey::Ecc(&ecc_auth_pub))?;
let ecc_subj_key_id = x509::subj_key_id(&mut env.sha256, &PubKey::Ecc(&ecc_auth_pub))?;
let mldsa_auth_pub = HandOff::fmc_mldsa_pub_key(env);
let mldsa_subj_sn = x509::subj_sn(&mut env.sha256, &PubKey::Mldsa(&mldsa_auth_pub))?;
let mldsa_subj_key_id = x509::subj_key_id(&mut env.sha256, &PubKey::Mldsa(&mldsa_auth_pub))?;
// Create initial output
let output = DiceOutput {
cdi: HandOff::fmc_cdi(env),
ecc_subj_key_pair: Ecc384KeyPair {
priv_key: HandOff::fmc_ecc_priv_key(env),
pub_key: ecc_auth_pub,
},
ecc_subj_sn,
ecc_subj_key_id,
mldsa_subj_key_pair: MlDsaKeyPair {
key_pair_seed: HandOff::fmc_mldsa_keypair_seed_key(env),
pub_key: mldsa_auth_pub,
},
mldsa_subj_sn,
mldsa_subj_key_id,
};
Ok(output)
}
#[inline(always)]
pub fn generate_csr(env: &mut FmcEnv) -> CaliptraResult<()> {
dice_output_from_hand_off(env).and_then(|output| make_csr(env, &output))
}
/// Generate FMC Alias ECC and MLDSA CSRs
///
/// # Arguments
///
/// * `env` - FMC Environment
/// * `output` - DICE Output
// Inlined to reduce FMC size
#[inline(always)]
pub fn make_csr(env: &mut FmcEnv, output: &DiceOutput) -> CaliptraResult<()> {
make_ecc_csr(env, output)?;
make_mldsa_csr(env, output)
}
pub struct FmcAliasCsrTbsCommonParams {
pub ueid: [u8; 17],
pub tcb_info_device_info_hash: [u8; 48],
pub tcb_info_fmc_tci: [u8; 48],
pub tcb_info_flags: [u8; 4],
pub tcb_info_fmc_svn: [u8; 1],
pub tcb_info_fmc_svn_fuses: [u8; 1],
}
fn get_tbs_common_params(env: &mut FmcEnv) -> CaliptraResult<FmcAliasCsrTbsCommonParams> {
let data_vault = &env.persistent_data.get().rom.data_vault;
let flags = dice::make_flags(env.soc_ifc.lifecycle(), env.soc_ifc.debug_locked());
let svn = data_vault.cold_boot_fw_svn() as u8;
// This info was not saved from ROM so we need to repeat this check
let fmc_effective_fuse_svn = match env.soc_ifc.fuse_bank().anti_rollback_disable() {
true => 0_u8,
false => env.soc_ifc.fuse_bank().fw_fuse_svn() as u8,
};
let owner_pub_keys_digest_in_fuses: bool =
env.soc_ifc.fuse_bank().owner_pub_key_hash() != Array4x12::default();
let mut fuse_info_digest = Array4x12::default();
let mut hasher = env.sha2_512_384.sha384_digest_init()?;
hasher.update(&[
env.soc_ifc.lifecycle() as u8,
env.soc_ifc.debug_locked() as u8,
env.soc_ifc.fuse_bank().anti_rollback_disable() as u8,
data_vault.vendor_ecc_pk_index() as u8,
data_vault.vendor_pqc_pk_index() as u8,
env.soc_ifc.fuse_bank().pqc_key_type() as u8,
owner_pub_keys_digest_in_fuses as u8,
])?;
hasher.update(&<[u8; 48]>::from(
env.soc_ifc.fuse_bank().vendor_pub_key_info_hash(),
))?;
hasher.update(&<[u8; 48]>::from(data_vault.owner_pk_hash()))?;
hasher.finalize(&mut fuse_info_digest)?;
// CSR `To Be Signed` Parameters
let params = FmcAliasCsrTbsCommonParams {
ueid: x509::ueid(&env.soc_ifc)?,
tcb_info_fmc_tci: (&data_vault.fmc_tci()).into(),
tcb_info_device_info_hash: fuse_info_digest.into(),
tcb_info_flags: flags,
tcb_info_fmc_svn: svn.to_be_bytes(),
tcb_info_fmc_svn_fuses: fmc_effective_fuse_svn.to_be_bytes(),
};
Ok(params)
}
fn make_ecc_csr(env: &mut FmcEnv, output: &DiceOutput) -> CaliptraResult<()> {
let key_pair = &output.ecc_subj_key_pair;
let common_params = get_tbs_common_params(env)?;
// CSR `To Be Signed` Parameters
let params = FmcAliasCsrTbsEcc384Params {
ueid: &common_params.ueid,
subject_sn: &output.ecc_subj_sn,
public_key: &key_pair.pub_key.to_der(),
tcb_info_fmc_tci: &common_params.tcb_info_fmc_tci,
tcb_info_device_info_hash: &common_params.tcb_info_device_info_hash,
tcb_info_flags: &common_params.tcb_info_flags,
tcb_info_fmc_svn: &common_params.tcb_info_fmc_svn,
tcb_info_fmc_svn_fuses: &common_params.tcb_info_fmc_svn_fuses,
};
// Generate the `To Be Signed` portion of the CSR
let tbs = FmcAliasCsrTbsEcc384::new(¶ms);
// Sign the `To Be Signed` portion
let mut sig = Crypto::ecdsa384_sign_and_verify(
&mut env.sha2_512_384,
&mut env.ecc384,
&mut env.trng,
key_pair.priv_key,
&key_pair.pub_key,
tbs.tbs(),
);
let sig = okmutref(&mut sig)?;
let sig_ecdsa = sig.to_ecdsa();
let result = Ecdsa384CsrBuilder::new(tbs.tbs(), &sig_ecdsa)
.ok_or(CaliptraError::FMC_ALIAS_CSR_BUILDER_INIT_FAILURE);
sig.zeroize();
let csr_bldr = result?;
let fmc_alias_csr = &mut env.persistent_data.get_mut().fw.fmc_alias_csr;
let csr_len = csr_bldr
.build(&mut fmc_alias_csr.ecc_csr)
.ok_or(CaliptraError::FMC_ALIAS_CSR_BUILDER_BUILD_FAILURE)?;
if csr_len > fmc_alias_csr.ecc_csr.len() {
return Err(CaliptraError::FMC_ALIAS_CSR_OVERFLOW);
}
fmc_alias_csr.ecc_csr_len = csr_len as u32;
Ok(())
}
fn make_mldsa_csr(env: &mut FmcEnv, output: &DiceOutput) -> CaliptraResult<()> {
let key_pair = &output.mldsa_subj_key_pair;
let common_params = get_tbs_common_params(env)?;
// CSR `To Be Signed` Parameters
let params = FmcAliasTbsMlDsa87Params {
ueid: &common_params.ueid,
subject_sn: &output.mldsa_subj_sn,
public_key: &key_pair.pub_key.into(),
tcb_info_fmc_tci: &common_params.tcb_info_fmc_tci,
tcb_info_device_info_hash: &common_params.tcb_info_device_info_hash,
tcb_info_flags: &common_params.tcb_info_flags,
tcb_info_fmc_svn: &common_params.tcb_info_fmc_svn,
tcb_info_fmc_svn_fuses: &common_params.tcb_info_fmc_svn_fuses,
};
// Generate the `To Be Signed` portion of the CSR
let tbs = FmcAliasTbsMlDsa87::new(¶ms);
// Sign the `To Be Signed` portion
let mut sig = Crypto::mldsa87_sign_and_verify(
&mut env.mldsa,
&mut env.trng,
key_pair.key_pair_seed,
&key_pair.pub_key,
tbs.tbs(),
)?;
// Build the CSR with `To Be Signed` & `Signature`
let mldsa87_signature = caliptra_x509::MlDsa87Signature {
sig: sig.as_bytes()[..4627].try_into().unwrap(),
};
let result = MlDsa87CsrBuilder::new(tbs.tbs(), &mldsa87_signature)
.ok_or(CaliptraError::ROM_IDEVID_CSR_BUILDER_INIT_FAILURE);
sig.zeroize();
let csr_bldr = result?;
let fmc_alias_csr = &mut env.persistent_data.get_mut().fw.fmc_alias_csr;
let csr_len = csr_bldr
.build(&mut fmc_alias_csr.mldsa_csr)
.ok_or(CaliptraError::ROM_IDEVID_CSR_BUILDER_BUILD_FAILURE)?;
if csr_len > fmc_alias_csr.mldsa_csr.len() {
return Err(CaliptraError::FMC_ALIAS_CSR_OVERFLOW);
}
fmc_alias_csr.mldsa_csr_len = csr_len as u32;
Ok(())
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/tests/fmc_integration_tests/helpers.rs | fmc/tests/fmc_integration_tests/helpers.rs | // Licensed under the Apache-2.0 license
use caliptra_image_types::FwVerificationPqcKeyType;
pub const PQC_KEY_TYPE: [FwVerificationPqcKeyType; 2] = [
FwVerificationPqcKeyType::LMS,
FwVerificationPqcKeyType::MLDSA,
];
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/tests/fmc_integration_tests/test_panic_missing.rs | fmc/tests/fmc_integration_tests/test_panic_missing.rs | // Licensed under the Apache-2.0 license
use caliptra_builder::firmware;
#[test]
fn test_panic_missing() {
let fmc_elf = caliptra_builder::build_firmware_elf(&firmware::FMC_WITH_UART).unwrap();
let symbols = caliptra_builder::elf_symbols(&fmc_elf).unwrap();
if symbols.iter().any(|s| s.name.contains("panic_is_possible")) {
panic!(
"The caliptra FMC contains the panic_is_possible symbol, which is not allowed. \
Please remove any code that might panic."
)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/tests/fmc_integration_tests/test_rtalias.rs | fmc/tests/fmc_integration_tests/test_rtalias.rs | // Licensed under the Apache-2.0 license
use caliptra_api::soc_mgr::SocManager;
use caliptra_auth_man_gen::default_test_manifest::DEFAULT_MCU_FW;
use caliptra_builder::{
firmware::{
self,
runtime_tests::{MOCK_RT_INTERACTIVE, MOCK_RT_INTERACTIVE_FPGA},
FMC_WITH_UART,
},
ImageOptions,
};
use caliptra_common::RomBootStatus::*;
use caliptra_common::mailbox_api::CommandId;
use caliptra_drivers::{
pcr_log::{PcrLogEntry, PcrLogEntryId},
FirmwareHandoffTable, PcrId,
};
use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams};
use caliptra_test::{default_soc_manifest_bytes, swap_word_bytes};
use zerocopy::{FromBytes, IntoBytes, TryFromBytes};
use crate::helpers;
use openssl::hash::{Hasher, MessageDigest};
const TEST_CMD_READ_PCR_LOG: u32 = 0x1000_0000;
const TEST_CMD_READ_FHT: u32 = 0x1000_0001;
const TEST_CMD_PCRS_LOCKED: u32 = 0x1000_0004;
const RT_ALIAS_MEASUREMENT_COMPLETE: u32 = 0x400;
const RT_ALIAS_DERIVED_CDI_COMPLETE: u32 = 0x401;
const RT_ALIAS_KEY_PAIR_DERIVATION_COMPLETE: u32 = 0x402;
const RT_ALIAS_SUBJ_ID_SN_GENERATION_COMPLETE: u32 = 0x403;
const RT_ALIAS_SUBJ_KEY_ID_GENERATION_COMPLETE: u32 = 0x404;
const RT_ALIAS_CERT_SIG_GENERATION_COMPLETE: u32 = 0x405;
const RT_ALIAS_DERIVATION_COMPLETE: u32 = 0x406;
const PCR_COUNT: usize = 32;
const PCR_ENTRY_SIZE: usize = core::mem::size_of::<PcrLogEntry>();
const PCR2_AND_PCR3_EXTENDED_ID: u32 = (1 << PcrId::PcrId2 as u8) | (1 << PcrId::PcrId3 as u8);
#[test]
fn test_boot_status_reporting() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let rom =
caliptra_builder::rom_for_fw_integration_tests_fpga(cfg!(feature = "fpga_subsystem"))
.unwrap();
let image = caliptra_builder::build_and_sign_image(
&firmware::FMC_WITH_UART,
&firmware::runtime_tests::BOOT,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
fuses,
..Default::default()
},
BootParams {
fw_image: Some(&image.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
hw.step_until_boot_status(RT_ALIAS_MEASUREMENT_COMPLETE, true);
hw.step_until_boot_status(RT_ALIAS_DERIVED_CDI_COMPLETE, true);
hw.step_until_boot_status(RT_ALIAS_KEY_PAIR_DERIVATION_COMPLETE, true);
hw.step_until_boot_status(RT_ALIAS_SUBJ_ID_SN_GENERATION_COMPLETE, true);
hw.step_until_boot_status(RT_ALIAS_SUBJ_KEY_ID_GENERATION_COMPLETE, true);
hw.step_until_boot_status(RT_ALIAS_CERT_SIG_GENERATION_COMPLETE, true);
hw.step_until_boot_status(RT_ALIAS_DERIVATION_COMPLETE, true);
}
}
#[test]
fn test_fht_info() {
for &pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let fuses = Fuses {
fuse_pqc_key_type: pqc_key_type as u32,
..Default::default()
};
let image_options = ImageOptions {
pqc_key_type,
..Default::default()
};
let rom =
caliptra_builder::rom_for_fw_integration_tests_fpga(cfg!(feature = "fpga_subsystem"))
.unwrap();
let image = caliptra_builder::build_and_sign_image(
&FMC_WITH_UART,
&if cfg!(feature = "fpga_subsystem") {
MOCK_RT_INTERACTIVE_FPGA
} else {
MOCK_RT_INTERACTIVE
},
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
fuses,
..Default::default()
},
BootParams {
fw_image: Some(&image.to_bytes().unwrap()),
soc_manifest: Some(&default_soc_manifest_bytes(pqc_key_type, 1)),
mcu_fw_image: Some(&DEFAULT_MCU_FW),
..Default::default()
},
)
.unwrap();
hw.step_until(|m| m.soc_ifc().cptra_flow_status().read().ready_for_runtime());
let data = hw.mailbox_execute(TEST_CMD_READ_FHT, &[]).unwrap().unwrap();
let fht = FirmwareHandoffTable::try_ref_from_bytes(data.as_bytes()).unwrap();
assert_eq!(fht.ecc_ldevid_tbs_size, 566);
assert_eq!(fht.ecc_fmcalias_tbs_size, 767);
assert_ne!(fht.mldsa_ldevid_tbs_size, 0);
assert_ne!(fht.mldsa_fmcalias_tbs_size, 0);
}
}
#[test]
fn test_pcr_log() {
for &pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let fuses = Fuses {
fuse_pqc_key_type: pqc_key_type as u32,
..Default::default()
};
let rom =
caliptra_builder::rom_for_fw_integration_tests_fpga(cfg!(feature = "fpga_subsystem"))
.unwrap();
let image1 = caliptra_builder::build_and_sign_image(
&FMC_WITH_UART,
&if cfg!(feature = "fpga_subsystem") {
MOCK_RT_INTERACTIVE_FPGA
} else {
MOCK_RT_INTERACTIVE
},
ImageOptions {
app_version: 1,
pqc_key_type,
..Default::default()
},
)
.unwrap();
let image2 = caliptra_builder::build_and_sign_image(
&FMC_WITH_UART,
&if cfg!(feature = "fpga_subsystem") {
MOCK_RT_INTERACTIVE_FPGA
} else {
MOCK_RT_INTERACTIVE
},
ImageOptions {
app_version: 2,
pqc_key_type,
..Default::default()
},
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
fuses,
..Default::default()
},
BootParams {
fw_image: Some(&image1.to_bytes().unwrap()),
soc_manifest: Some(&default_soc_manifest_bytes(pqc_key_type, 1)),
mcu_fw_image: Some(&DEFAULT_MCU_FW),
..Default::default()
},
)
.unwrap();
hw.step_until(|m| m.soc_ifc().cptra_flow_status().read().ready_for_runtime());
let data = hw.mailbox_execute(TEST_CMD_READ_FHT, &[]).unwrap().unwrap();
let fht = FirmwareHandoffTable::try_ref_from_bytes(data.as_bytes()).unwrap();
let pcr_entry_arr = hw
.mailbox_execute(TEST_CMD_READ_PCR_LOG, &[])
.unwrap()
.unwrap();
assert_eq!(
pcr_entry_arr.len(),
(fht.pcr_log_index as usize) * PCR_ENTRY_SIZE
);
let rt_tci1 = swap_word_bytes(&image1.manifest.runtime.digest);
let manifest_digest1 = openssl::sha::sha384(image1.manifest.as_bytes());
check_pcr_log_entry(
&pcr_entry_arr,
fht.pcr_log_index - 2,
PcrLogEntryId::RtTci,
PCR2_AND_PCR3_EXTENDED_ID,
rt_tci1.as_bytes(),
);
check_pcr_log_entry(
&pcr_entry_arr,
fht.pcr_log_index - 1,
PcrLogEntryId::FwImageManifest,
PCR2_AND_PCR3_EXTENDED_ID,
&manifest_digest1,
);
// Fetch and validate PCR values against the log.
let pcrs = hw.mailbox_execute(0x1000_0002, &[]).unwrap().unwrap();
assert_eq!(pcrs.len(), PCR_COUNT * 48);
let mut pcr2_from_hw: [u8; 48] = pcrs[(2 * 48)..(3 * 48)].try_into().unwrap();
let mut pcr3_from_hw: [u8; 48] = pcrs[(3 * 48)..(4 * 48)].try_into().unwrap();
change_dword_endianess(&mut pcr2_from_hw);
change_dword_endianess(&mut pcr3_from_hw);
let pcr2_from_log = hash_pcr_log_entries(&[0; 48], &pcr_entry_arr, PcrId::PcrId2);
let pcr3_from_log = hash_pcr_log_entries(&[0; 48], &pcr_entry_arr, PcrId::PcrId3);
assert_eq!(pcr2_from_log, pcr2_from_hw);
assert_eq!(pcr3_from_log, pcr3_from_hw);
// Trigger an update reset with "new" firmware
hw.start_mailbox_execute(CommandId::FIRMWARE_LOAD.into(), &image2.to_bytes().unwrap())
.unwrap();
if cfg!(not(feature = "fpga_realtime")) {
hw.step_until_boot_status(KatStarted.into(), true);
hw.step_until_boot_status(KatComplete.into(), true);
}
hw.step_until_boot_status(UpdateResetStarted.into(), true);
assert_eq!(hw.finish_mailbox_execute(), Ok(None));
hw.step_until_boot_status(RT_ALIAS_DERIVATION_COMPLETE, true);
let pcr_entry_arr = hw
.mailbox_execute(TEST_CMD_READ_PCR_LOG, &[])
.unwrap()
.unwrap();
assert_eq!(
pcr_entry_arr.len(),
(fht.pcr_log_index as usize) * PCR_ENTRY_SIZE
);
let rt_tci2 = swap_word_bytes(&image2.manifest.runtime.digest);
let manifest_digest2 = openssl::sha::sha384(image2.manifest.as_bytes());
check_pcr_log_entry(
&pcr_entry_arr,
fht.pcr_log_index - 2,
PcrLogEntryId::RtTci,
PCR2_AND_PCR3_EXTENDED_ID,
rt_tci2.as_bytes(),
);
check_pcr_log_entry(
&pcr_entry_arr,
fht.pcr_log_index - 1,
PcrLogEntryId::FwImageManifest,
PCR2_AND_PCR3_EXTENDED_ID,
&manifest_digest2,
);
let pcr2_from_log = hash_pcr_log_entries(&[0; 48], &pcr_entry_arr, PcrId::PcrId2);
let pcr3_from_log = hash_pcr_log_entries(&pcr3_from_log, &pcr_entry_arr, PcrId::PcrId3);
// Fetch and validate PCR values against the log.
let pcrs = hw.mailbox_execute(0x1000_0002, &[]).unwrap().unwrap();
assert_eq!(pcrs.len(), PCR_COUNT * 48);
let mut pcr2_from_hw: [u8; 48] = pcrs[(2 * 48)..(3 * 48)].try_into().unwrap();
let mut pcr3_from_hw: [u8; 48] = pcrs[(3 * 48)..(4 * 48)].try_into().unwrap();
change_dword_endianess(&mut pcr2_from_hw);
change_dword_endianess(&mut pcr3_from_hw);
assert_eq!(pcr2_from_log, pcr2_from_hw);
assert_eq!(pcr3_from_log, pcr3_from_hw);
// Also ensure PCR locks are configured correctly.
let result = hw.mailbox_execute(TEST_CMD_PCRS_LOCKED, &[]);
assert!(result.is_ok());
}
}
fn check_pcr_log_entry(
pcr_entry_arr: &[u8],
pcr_entry_index: u32,
entry_id: PcrLogEntryId,
pcr_ids: u32,
pcr_data: &[u8],
) {
let offset = pcr_entry_index as usize * PCR_ENTRY_SIZE;
let (entry, _) = PcrLogEntry::read_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap();
assert_eq!(entry.id, entry_id as u16);
assert_eq!(entry.pcr_ids, pcr_ids);
assert_eq!(entry.measured_data(), pcr_data);
}
// Computes the PCR from the log.
fn hash_pcr_log_entries(initial_pcr: &[u8; 48], pcr_entry_arr: &[u8], pcr_id: PcrId) -> [u8; 48] {
let mut offset: usize = 0;
let mut pcr: [u8; 48] = *initial_pcr;
assert_eq!(pcr_entry_arr.len() % PCR_ENTRY_SIZE, 0);
loop {
if offset == pcr_entry_arr.len() {
break;
}
let (entry, _) = PcrLogEntry::read_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap();
offset += PCR_ENTRY_SIZE;
if (entry.pcr_ids & (1 << pcr_id as u8)) == 0 {
continue;
}
let mut hasher = Hasher::new(MessageDigest::sha384()).unwrap();
hasher.update(&pcr).unwrap();
hasher.update(entry.measured_data()).unwrap();
let digest: &[u8] = &hasher.finish().unwrap();
pcr.copy_from_slice(digest);
}
pcr
}
fn change_dword_endianess(data: &mut [u8]) {
for idx in (0..data.len()).step_by(4) {
data.swap(idx, idx + 3);
data.swap(idx + 1, idx + 2);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/tests/fmc_integration_tests/main.rs | fmc/tests/fmc_integration_tests/main.rs | // Licensed under the Apache-2.0 license
mod helpers;
mod test_hand_off;
mod test_panic_missing;
mod test_rtalias;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/fmc/tests/fmc_integration_tests/test_hand_off.rs | fmc/tests/fmc_integration_tests/test_hand_off.rs | // Licensed under the Apache-2.0 license
use crate::helpers;
use caliptra_builder::{firmware, ImageOptions};
use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams};
#[test]
fn test_hand_off() {
for pqc_key_type in helpers::PQC_KEY_TYPE.iter() {
let fuses = Fuses {
fuse_pqc_key_type: *pqc_key_type as u32,
..Default::default()
};
let image_options = ImageOptions {
pqc_key_type: *pqc_key_type,
..Default::default()
};
let rom =
caliptra_builder::rom_for_fw_integration_tests_fpga(cfg!(feature = "fpga_subsystem"))
.unwrap();
let image = caliptra_builder::build_and_sign_image(
&firmware::FMC_WITH_UART,
&firmware::runtime_tests::BOOT,
image_options,
)
.unwrap();
let mut hw = caliptra_hw_model::new(
InitParams {
rom: &rom,
fuses,
..Default::default()
},
BootParams {
fw_image: Some(&image.to_bytes().unwrap()),
..Default::default()
},
)
.unwrap();
let mut output = vec![];
hw.copy_output_until_exit_success(&mut output).unwrap();
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/api/src/mailbox.rs | api/src/mailbox.rs | // Licensed under the Apache-2.0 license
use crate::CaliptraApiError;
use bitflags::bitflags;
use caliptra_error::{CaliptraError, CaliptraResult};
use caliptra_image_types::{
ECC384_SCALAR_BYTE_SIZE, MLDSA87_PUB_KEY_BYTE_SIZE, MLDSA87_SIGNATURE_BYTE_SIZE,
SHA512_DIGEST_BYTE_SIZE,
};
use caliptra_registers::mbox;
use core::mem::size_of;
use ureg::MmioMut;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Ref};
/// Maximum input data size for cryptographic mailbox commands.
pub const MAX_CMB_DATA_SIZE: usize = 4096;
/// Maximum output size for AES GCM encrypt or decrypt operations.
pub const MAX_CMB_AES_GCM_OUTPUT_SIZE: usize = MAX_CMB_DATA_SIZE + 16;
/// Maximum mailbox size when subsystem staging area is available.
pub const SUBSYSTEM_MAILBOX_SIZE_LIMIT: usize = 16 * 1024; // 16K
/// Context size for CMB SHA commands.
pub const CMB_SHA_CONTEXT_SIZE: usize = 200;
/// Maximum response data size
pub const MAX_RESP_DATA_SIZE: usize = 9216; // 9K
/// Unencrypted context size for the CMB AES generic commands.
pub const _CMB_AES_CONTEXT_SIZE: usize = 128;
/// Encrypted context size for the CMB AES generic commands.
pub const CMB_AES_ENCRYPTED_CONTEXT_SIZE: usize = 156; // = unencrypted size + 12 bytes IV + 16 bytes tag
const _: () = assert!(_CMB_AES_CONTEXT_SIZE + 12 + 16 == CMB_AES_ENCRYPTED_CONTEXT_SIZE);
/// Encrypted context size for the CMB AES GCM commands.
pub const CMB_AES_GCM_ENCRYPTED_CONTEXT_SIZE: usize = 128;
// ECDH context (unencrypted) size
pub const CMB_ECDH_CONTEXT_SIZE: usize = 48;
/// Context size for CMB ECDH commands.
pub const CMB_ECDH_ENCRYPTED_CONTEXT_SIZE: usize = 76; // = unencrypted size + 12 bytes IV + 16 bytes tag
const _: () = assert!(CMB_ECDH_CONTEXT_SIZE + 12 + 16 == CMB_ECDH_ENCRYPTED_CONTEXT_SIZE);
/// CMB ECDH exchange data maximum size is the size of two coordinates + 1 byte, rounded up.
pub const CMB_ECDH_EXCHANGE_DATA_MAX_SIZE: usize = 96; // = 48 * 2;
const _: () = assert!(CMB_ECDH_CONTEXT_SIZE * 2 == CMB_ECDH_EXCHANGE_DATA_MAX_SIZE);
pub const CMB_HMAC_MAX_SIZE: usize = 64; // SHA512 digest size
#[derive(PartialEq, Eq)]
pub struct CommandId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlgorithmType {
Ecc384,
Mldsa87,
}
impl CommandId {
pub const ACTIVATE_FIRMWARE: Self = Self(0x41435446); // "ACTF"
pub const FIRMWARE_LOAD: Self = Self(0x46574C44); // "FWLD"
pub const FIRMWARE_VERIFY: Self = Self(0x46575652); // "FWVR"
pub const GET_IDEV_ECC384_CERT: Self = Self(0x49444543); // "IDEC"
pub const GET_IDEV_ECC384_INFO: Self = Self(0x49444549); // "IDEI"
pub const POPULATE_IDEV_ECC384_CERT: Self = Self(0x49444550); // "IDEP"
pub const GET_LDEV_ECC384_CERT: Self = Self(0x4C444556); // "LDEV"
pub const GET_FMC_ALIAS_ECC384_CERT: Self = Self(0x43455246); // "CERF"
pub const GET_RT_ALIAS_ECC384_CERT: Self = Self(0x43455252); // "CERR"
// MLDSA87 versions
pub const GET_IDEV_MLDSA87_CERT: Self = Self(0x49444D43); // "IDMC"
pub const POPULATE_IDEV_MLDSA87_CERT: Self = Self(0x49444D50); // "IDMP"
pub const GET_LDEV_MLDSA87_CERT: Self = Self(0x4C444D43); // "LDMC"
pub const GET_FMC_ALIAS_MLDSA87_CERT: Self = Self(0x434D4346); // "CMCF"
pub const GET_RT_ALIAS_MLDSA87_CERT: Self = Self(0x434D4352); // "CMCR"
pub const GET_IDEV_MLDSA87_INFO: Self = Self(0x49444D49); // "IDMI"
pub const ECDSA384_SIGNATURE_VERIFY: Self = Self(0x45435632); // "ECV2"
pub const LMS_SIGNATURE_VERIFY: Self = Self(0x4C4D5632); // "LMV2"
pub const MLDSA87_SIGNATURE_VERIFY: Self = Self(0x4d4c5632); // "MLV2"
pub const STASH_MEASUREMENT: Self = Self(0x4D454153); // "MEAS"
pub const INVOKE_DPE: Self = Self(0x44504543); // "DPEC"
pub const DISABLE_ATTESTATION: Self = Self(0x4453424C); // "DSBL"
pub const FW_INFO: Self = Self(0x494E464F); // "INFO"
pub const DPE_TAG_TCI: Self = Self(0x54514754); // "TAGT"
pub const DPE_GET_TAGGED_TCI: Self = Self(0x47544744); // "GTGD"
pub const INCREMENT_PCR_RESET_COUNTER: Self = Self(0x50435252); // "PCRR"
pub const QUOTE_PCRS_ECC384: Self = Self(0x50435251); // "PCRQ"
pub const QUOTE_PCRS_MLDSA87: Self = Self(0x5043524D); // "PCRM"
pub const EXTEND_PCR: Self = Self(0x50435245); // "PCRE"
pub const ADD_SUBJECT_ALT_NAME: Self = Self(0x414C544E); // "ALTN"
pub const CERTIFY_KEY_EXTENDED: Self = Self(0x434B4558); // "CKEX"
pub const ZEROIZE_UDS_FE: Self = Self(0x5A455546); // "ZEUF"
/// FIPS module commands.
/// The status command.
pub const VERSION: Self = Self(0x4650_5652); // "FPVR"
/// The self-test command.
pub const SELF_TEST_START: Self = Self(0x4650_4C54); // "FPST"
/// The self-test get results.
pub const SELF_TEST_GET_RESULTS: Self = Self(0x4650_4C67); // "FPGR"
/// The shutdown command.
pub const SHUTDOWN: Self = Self(0x4650_5344); // "FPSD"
// The capabilities command.
pub const CAPABILITIES: Self = Self(0x4341_5053); // "CAPS"
// The authorization manifest set command.
pub const SET_AUTH_MANIFEST: Self = Self(0x4154_4D4E); // "ATMN"
// Verify the authorization manifest command.
pub const VERIFY_AUTH_MANIFEST: Self = Self(0x4154_564D); // "ATVM"
// The authorize and stash command.
pub const AUTHORIZE_AND_STASH: Self = Self(0x4154_5348); // "ATSH"
// The download firmware from recovery interface command.
pub const RI_DOWNLOAD_FIRMWARE: Self = Self(0x5249_4644); // "RIFD"
// The get IDevID ECC CSR command.
pub const GET_IDEV_ECC384_CSR: Self = Self(0x4944_4352); // "IDCR"
// The get IDevID MLDSA CSR command.
pub const GET_IDEV_MLDSA87_CSR: Self = Self(0x4944_4d52); // "IDMR"
// The get FMC Alias ECC CSR command.
pub const GET_FMC_ALIAS_ECC384_CSR: Self = Self(0x464D_4352); // "FMCR"
// The get FMC Alias MLDSA CSR command.
pub const GET_FMC_ALIAS_MLDSA87_CSR: Self = Self(0x464d_4452); // "FMDR"
// The sign with exported ecdsa command.
pub const SIGN_WITH_EXPORTED_ECDSA: Self = Self(0x5357_4545); // "SWEE"
// The revoke exported CDI handle command.
pub const REVOKE_EXPORTED_CDI_HANDLE: Self = Self(0x5256_4348); // "RVCH"
// The sign with exported mldsa command.
pub const SIGN_WITH_EXPORTED_MLDSA: Self = Self(0x5357_4D4C); // "SWML"
// The FE programming command.
pub const FE_PROG: Self = Self(0x4645_5052); // "FEPR"
// Get PCR log command.
pub const GET_PCR_LOG: Self = Self(0x504C_4F47); // "PLOG"
// External mailbox command
pub const EXTERNAL_MAILBOX_CMD: Self = Self(0x4558_544D); // "EXTM"
// Debug unlock commands
pub const MANUF_DEBUG_UNLOCK_REQ_TOKEN: Self = Self(0x4d445554); // "MDUT"
pub const PRODUCTION_AUTH_DEBUG_UNLOCK_REQ: Self = Self(0x50445552); // "PDUR"
pub const PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN: Self = Self(0x50445554); // "PDUT"
// Image metadata commands
pub const GET_IMAGE_INFO: Self = Self(0x494D_4530); // "IME0"
// Device Ownership Transfer command
pub const INSTALL_OWNER_PK_HASH: Self = Self(0x4F574E50); // "OWNP"
// Cryptographic mailbox commands
pub const CM_IMPORT: Self = Self(0x434D_494D); // "CMIM"
pub const CM_DELETE: Self = Self(0x434D_444C); // "CMDL"
pub const CM_CLEAR: Self = Self(0x434D_434C); // "CMCL"
pub const CM_STATUS: Self = Self(0x434D_5354); // "CMST"
pub const CM_SHA_INIT: Self = Self(0x434D_5349); // "CMSI"
pub const CM_SHA_UPDATE: Self = Self(0x434D_5355); // "CMSU"
pub const CM_SHA_FINAL: Self = Self(0x434D_5346); // "CMSF"
pub const CM_RANDOM_GENERATE: Self = Self(0x434D_5247); // "CMRG"
pub const CM_RANDOM_STIR: Self = Self(0x434D_5253); // "CMRS"
pub const CM_AES_ENCRYPT_INIT: Self = Self(0x434D_4149); // "CMAI"
pub const CM_AES_ENCRYPT_UPDATE: Self = Self(0x434D_4155); // "CMAU"
pub const CM_AES_DECRYPT_INIT: Self = Self(0x434D_414A); // "CMAJ"
pub const CM_AES_DECRYPT_UPDATE: Self = Self(0x434D_4156); // "CMAV"
pub const CM_AES_GCM_ENCRYPT_INIT: Self = Self(0x434D_4749); // "CMGI"
pub const CM_AES_GCM_SPDM_ENCRYPT_INIT: Self = Self(0x434D_5345); // "CMSE"
pub const CM_AES_GCM_ENCRYPT_UPDATE: Self = Self(0x434D_4755); // "CMGU"
pub const CM_AES_GCM_ENCRYPT_FINAL: Self = Self(0x434D_4746); // "CMGF"
pub const CM_AES_GCM_DECRYPT_INIT: Self = Self(0x434D_4449); // "CMDI"
pub const CM_AES_GCM_SPDM_DECRYPT_INIT: Self = Self(0x434D_5344); // "CMSD"
pub const CM_AES_GCM_DECRYPT_UPDATE: Self = Self(0x434D_4455); // "CMDU"
pub const CM_AES_GCM_DECRYPT_FINAL: Self = Self(0x434D_4446); // "CMDF"
pub const CM_ECDH_GENERATE: Self = Self(0x434D_4547); // "CMEG"
pub const CM_ECDH_FINISH: Self = Self(0x434D_4546); // "CMEF"
pub const CM_HMAC: Self = Self(0x434D_484D); // "CMHM"
pub const CM_HMAC_KDF_COUNTER: Self = Self(0x434D_4B43); // "CMKC"
pub const CM_HKDF_EXTRACT: Self = Self(0x434D_4B54); // "CMKT"
pub const CM_HKDF_EXPAND: Self = Self(0x434D_4B50); // "CMKP"
pub const CM_MLDSA_PUBLIC_KEY: Self = Self(0x434D_4D50); // "CMMP"
pub const CM_MLDSA_SIGN: Self = Self(0x434D_4D53); // "CMMS"
pub const CM_MLDSA_VERIFY: Self = Self(0x434D_4D56); // "CMMV"
pub const CM_ECDSA_PUBLIC_KEY: Self = Self(0x434D_4550); // "CMEP"
pub const CM_ECDSA_SIGN: Self = Self(0x434D_4553); // "CMES"
pub const CM_ECDSA_VERIFY: Self = Self(0x434D_4556); // "CMEV"
pub const CM_DERIVE_STABLE_KEY: Self = Self(0x494D_4453); // "CMDS"
// OCP LOCK Commands
pub const OCP_LOCK_REPORT_HEK_METADATA: Self = Self(0x5248_4D54); // "RHMT"
pub const OCP_LOCK_GET_ALGORITHMS: Self = Self(0x4741_4C47); // "GALG"
pub const OCP_LOCK_INITIALIZE_MEK_SECRET: Self = Self(0x494D_4B53); // "IMKS"
pub const OCP_LOCK_DERIVE_MEK: Self = Self(0x444D_454B); // "DMEK"
pub const REALLOCATE_DPE_CONTEXT_LIMITS: Self = Self(0x5243_5458); // "RCTX"
}
impl From<u32> for CommandId {
fn from(value: u32) -> Self {
Self(value)
}
}
impl From<CommandId> for u32 {
fn from(value: CommandId) -> Self {
value.0
}
}
/// A trait implemented by request types. Describes the associated command ID
/// and response type.
pub trait Request: IntoBytes + FromBytes + Immutable + KnownLayout {
const ID: CommandId;
type Resp: Response;
}
pub trait Response: IntoBytes + FromBytes
where
Self: Sized,
{
/// The minimum size (in bytes) of this response. Transports that receive at
/// least this much data should pad the missing data with zeroes. If they
/// receive fewer bytes than MIN_SIZE, they should error.
const MIN_SIZE: usize = core::mem::size_of::<Self>();
fn populate_chksum(&mut self) {
// Note: This will panic if sizeof::<Self>() < 4
populate_checksum(self.as_mut_bytes());
}
}
#[repr(C)]
#[derive(Debug, IntoBytes, Default, FromBytes, Immutable, KnownLayout, PartialEq, Eq)]
pub struct MailboxRespHeaderVarSize {
pub hdr: MailboxRespHeader,
pub data_len: u32,
}
pub trait ResponseVarSize: IntoBytes + FromBytes + Immutable + KnownLayout {
fn data(&self) -> CaliptraResult<&[u8]> {
// Will panic if sizeof<Self>() is smaller than MailboxRespHeaderVarSize
// or Self doesn't have compatible alignment with
// MailboxRespHeaderVarSize (should be impossible if MailboxRespHeaderVarSiz is the first field) ..
let (hdr, data) = MailboxRespHeaderVarSize::ref_from_prefix(self.as_bytes())
.map_err(|_| CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE)?;
data.get(..hdr.data_len as usize)
.ok_or(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE)
}
fn partial_len(&self) -> CaliptraResult<usize> {
let (hdr, _) = MailboxRespHeaderVarSize::ref_from_prefix(self.as_bytes())
.map_err(|_| CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE)?;
Ok(size_of::<MailboxRespHeaderVarSize>() + hdr.data_len as usize)
}
fn as_bytes_partial(&self) -> CaliptraResult<&[u8]> {
self.as_bytes()
.get(..self.partial_len()?)
.ok_or(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE)
}
fn as_bytes_partial_mut(&mut self) -> CaliptraResult<&mut [u8]> {
let partial_len = self.partial_len()?;
self.as_mut_bytes()
.get_mut(..partial_len)
.ok_or(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE)
}
}
impl<T: ResponseVarSize> Response for T {
const MIN_SIZE: usize = size_of::<MailboxRespHeaderVarSize>();
}
pub fn populate_checksum(msg: &mut [u8]) {
let (checksum_bytes, payload_bytes) = msg.split_at_mut(size_of::<u32>());
let checksum = crate::checksum::calc_checksum(0, payload_bytes);
checksum_bytes.copy_from_slice(&checksum.to_le_bytes());
}
// Contains all the possible mailbox response structs
#[cfg_attr(test, derive(PartialEq, Debug, Eq))]
#[allow(clippy::large_enum_variant)]
pub enum MailboxResp {
Header(MailboxRespHeader),
GetIdevCert(GetIdevCertResp),
GetIdevEcc384Info(GetIdevEcc384InfoResp),
GetIdevMldsa87Info(GetIdevMldsa87InfoResp),
GetLdevCert(GetLdevCertResp),
StashMeasurement(StashMeasurementResp),
InvokeDpeCommand(InvokeDpeResp),
GetFmcAliasEcc384Cert(GetFmcAliasEcc384CertResp),
GetFmcAliasMlDsa87Cert(GetFmcAliasMlDsa87CertResp),
FipsVersion(FipsVersionResp),
FwInfo(FwInfoResp),
Capabilities(CapabilitiesResp),
GetTaggedTci(GetTaggedTciResp),
GetRtAliasCert(GetRtAliasCertResp),
QuotePcrsEcc384(QuotePcrsEcc384Resp),
QuotePcrsMldsa87(QuotePcrsMldsa87Resp),
CertifyKeyExtended(CertifyKeyExtendedResp),
AuthorizeAndStash(AuthorizeAndStashResp),
GetIdevEccCsr(GetIdevCsrResp),
GetIdevMldsaCsr(GetIdevCsrResp),
GetFmcAliasCsr(GetFmcAliasCsrResp),
SignWithExportedEcdsa(SignWithExportedEcdsaResp),
RevokeExportedCdiHandle(RevokeExportedCdiHandleResp),
GetImageInfo(GetImageInfoResp),
CmImport(CmImportResp),
CmStatus(CmStatusResp),
CmShaInit(CmShaInitResp),
CmShaFinal(CmShaFinalResp),
CmRandomGenerate(CmRandomGenerateResp),
CmAesEncryptInit(CmAesEncryptInitResp),
CmAesEncryptUpdate(CmAesResp),
CmAesDecryptInit(CmAesResp),
CmAesDecryptUpdate(CmAesResp),
CmAesGcmEncryptInit(CmAesGcmEncryptInitResp),
CmAesGcmSpdmEncryptInit(CmAesGcmSpdmEncryptInitResp),
CmAesGcmEncryptUpdate(CmAesGcmEncryptUpdateResp),
CmAesGcmEncryptFinal(CmAesGcmEncryptFinalResp),
CmAesGcmDecryptInit(CmAesGcmDecryptInitResp),
CmAesGcmSpdmDecryptInit(CmAesGcmSpdmDecryptInitResp),
CmAesGcmDecryptUpdate(CmAesGcmDecryptUpdateResp),
CmAesGcmDecryptFinal(CmAesGcmDecryptFinalResp),
CmEcdhGenerate(CmEcdhGenerateResp),
CmEcdhFinish(CmEcdhFinishResp),
CmHmac(CmHmacResp),
CmHmacKdfCounter(CmHmacKdfCounterResp),
CmHkdfExtract(CmHkdfExtractResp),
CmHkdfExpand(CmHkdfExpandResp),
CmMldsaPublicKey(CmMldsaPublicKeyResp),
CmMldsaSign(CmMldsaSignResp),
CmEcdsaPublicKey(CmEcdsaPublicKeyResp),
CmEcdsaSign(CmEcdsaSignResp),
CmDeriveStableKey(CmDeriveStableKeyResp),
ProductionAuthDebugUnlockChallenge(ProductionAuthDebugUnlockChallenge),
GetPcrLog(GetPcrLogResp),
ReallocateDpeContextLimits(ReallocateDpeContextLimitsResp),
}
pub const MAX_RESP_SIZE: usize = size_of::<MailboxResp>();
impl MailboxResp {
pub fn as_bytes(&self) -> CaliptraResult<&[u8]> {
match self {
MailboxResp::Header(resp) => Ok(resp.as_bytes()),
MailboxResp::GetIdevCert(resp) => resp.as_bytes_partial(),
MailboxResp::GetIdevEcc384Info(resp) => Ok(resp.as_bytes()),
MailboxResp::GetIdevMldsa87Info(resp) => Ok(resp.as_bytes()),
MailboxResp::GetLdevCert(resp) => resp.as_bytes_partial(),
MailboxResp::StashMeasurement(resp) => Ok(resp.as_bytes()),
MailboxResp::InvokeDpeCommand(resp) => resp.as_bytes_partial(),
MailboxResp::FipsVersion(resp) => Ok(resp.as_bytes()),
MailboxResp::FwInfo(resp) => Ok(resp.as_bytes()),
MailboxResp::Capabilities(resp) => Ok(resp.as_bytes()),
MailboxResp::GetTaggedTci(resp) => Ok(resp.as_bytes()),
MailboxResp::GetFmcAliasEcc384Cert(resp) => resp.as_bytes_partial(),
MailboxResp::GetFmcAliasMlDsa87Cert(resp) => resp.as_bytes_partial(),
MailboxResp::GetRtAliasCert(resp) => resp.as_bytes_partial(),
MailboxResp::QuotePcrsEcc384(resp) => Ok(resp.as_bytes()),
MailboxResp::QuotePcrsMldsa87(resp) => Ok(resp.as_bytes()),
MailboxResp::CertifyKeyExtended(resp) => Ok(resp.as_bytes()),
MailboxResp::AuthorizeAndStash(resp) => Ok(resp.as_bytes()),
MailboxResp::GetIdevEccCsr(resp) => resp.as_bytes_partial(),
MailboxResp::GetIdevMldsaCsr(resp) => Ok(resp.as_bytes()),
MailboxResp::GetFmcAliasCsr(resp) => resp.as_bytes_partial(),
MailboxResp::SignWithExportedEcdsa(resp) => Ok(resp.as_bytes()),
MailboxResp::RevokeExportedCdiHandle(resp) => Ok(resp.as_bytes()),
MailboxResp::GetImageInfo(resp) => Ok(resp.as_bytes()),
MailboxResp::CmImport(resp) => Ok(resp.as_bytes()),
MailboxResp::CmStatus(resp) => Ok(resp.as_bytes()),
MailboxResp::CmShaInit(resp) => Ok(resp.as_bytes()),
MailboxResp::CmShaFinal(resp) => resp.as_bytes_partial(),
MailboxResp::CmRandomGenerate(resp) => resp.as_bytes_partial(),
MailboxResp::CmAesEncryptInit(resp) => resp.as_bytes_partial(),
MailboxResp::CmAesEncryptUpdate(resp) => resp.as_bytes_partial(),
MailboxResp::CmAesDecryptInit(resp) => resp.as_bytes_partial(),
MailboxResp::CmAesDecryptUpdate(resp) => resp.as_bytes_partial(),
MailboxResp::CmAesGcmEncryptInit(resp) => Ok(resp.as_bytes()),
MailboxResp::CmAesGcmSpdmEncryptInit(resp) => Ok(resp.as_bytes()),
MailboxResp::CmAesGcmEncryptUpdate(resp) => resp.as_bytes_partial(),
MailboxResp::CmAesGcmEncryptFinal(resp) => resp.as_bytes_partial(),
MailboxResp::CmAesGcmDecryptInit(resp) => Ok(resp.as_bytes()),
MailboxResp::CmAesGcmSpdmDecryptInit(resp) => Ok(resp.as_bytes()),
MailboxResp::CmAesGcmDecryptUpdate(resp) => resp.as_bytes_partial(),
MailboxResp::CmAesGcmDecryptFinal(resp) => resp.as_bytes_partial(),
MailboxResp::CmEcdhGenerate(resp) => Ok(resp.as_bytes()),
MailboxResp::CmEcdhFinish(resp) => Ok(resp.as_bytes()),
MailboxResp::CmHmac(resp) => resp.as_bytes_partial(),
MailboxResp::CmHmacKdfCounter(resp) => Ok(resp.as_bytes()),
MailboxResp::CmHkdfExtract(resp) => Ok(resp.as_bytes()),
MailboxResp::CmHkdfExpand(resp) => Ok(resp.as_bytes()),
MailboxResp::CmMldsaPublicKey(resp) => Ok(resp.as_bytes()),
MailboxResp::CmMldsaSign(resp) => Ok(resp.as_bytes()),
MailboxResp::CmEcdsaPublicKey(resp) => Ok(resp.as_bytes()),
MailboxResp::CmEcdsaSign(resp) => Ok(resp.as_bytes()),
MailboxResp::CmDeriveStableKey(resp) => Ok(resp.as_bytes()),
MailboxResp::ProductionAuthDebugUnlockChallenge(resp) => Ok(resp.as_bytes()),
MailboxResp::GetPcrLog(resp) => Ok(resp.as_bytes()),
MailboxResp::ReallocateDpeContextLimits(resp) => Ok(resp.as_bytes()),
}
}
pub fn as_mut_bytes(&mut self) -> CaliptraResult<&mut [u8]> {
match self {
MailboxResp::Header(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::GetIdevCert(resp) => resp.as_bytes_partial_mut(),
MailboxResp::GetIdevEcc384Info(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::GetIdevMldsa87Info(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::GetLdevCert(resp) => resp.as_bytes_partial_mut(),
MailboxResp::StashMeasurement(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::InvokeDpeCommand(resp) => resp.as_bytes_partial_mut(),
MailboxResp::FipsVersion(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::FwInfo(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::Capabilities(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::GetTaggedTci(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::GetFmcAliasEcc384Cert(resp) => resp.as_bytes_partial_mut(),
MailboxResp::GetFmcAliasMlDsa87Cert(resp) => resp.as_bytes_partial_mut(),
MailboxResp::GetRtAliasCert(resp) => resp.as_bytes_partial_mut(),
MailboxResp::QuotePcrsEcc384(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::QuotePcrsMldsa87(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CertifyKeyExtended(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::AuthorizeAndStash(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::GetIdevEccCsr(resp) => resp.as_bytes_partial_mut(),
MailboxResp::GetIdevMldsaCsr(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::GetFmcAliasCsr(resp) => resp.as_bytes_partial_mut(),
MailboxResp::SignWithExportedEcdsa(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::RevokeExportedCdiHandle(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::GetImageInfo(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmImport(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmStatus(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmShaInit(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmShaFinal(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmRandomGenerate(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmAesEncryptInit(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmAesEncryptUpdate(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmAesDecryptInit(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmAesDecryptUpdate(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmAesGcmEncryptInit(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmAesGcmSpdmEncryptInit(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmAesGcmEncryptUpdate(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmAesGcmEncryptFinal(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmAesGcmDecryptInit(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmAesGcmSpdmDecryptInit(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmAesGcmDecryptUpdate(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmAesGcmDecryptFinal(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmEcdhGenerate(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmEcdhFinish(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmHmac(resp) => resp.as_bytes_partial_mut(),
MailboxResp::CmHmacKdfCounter(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmHkdfExtract(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmHkdfExpand(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmMldsaPublicKey(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmMldsaSign(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmEcdsaPublicKey(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmEcdsaSign(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::CmDeriveStableKey(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::ProductionAuthDebugUnlockChallenge(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::GetPcrLog(resp) => Ok(resp.as_mut_bytes()),
MailboxResp::ReallocateDpeContextLimits(resp) => Ok(resp.as_mut_bytes()),
}
}
/// Calculate and set the checksum for a response payload
/// Takes into account the size override for variable-length payloads
pub fn populate_chksum(&mut self) -> CaliptraResult<()> {
// Calc checksum, use the size override if provided
let resp_bytes = self.as_bytes()?;
if size_of::<u32>() >= resp_bytes.len() {
return Err(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE);
}
let checksum = crate::checksum::calc_checksum(0, &resp_bytes[size_of::<u32>()..]);
let mut_resp_bytes = self.as_mut_bytes()?;
if size_of::<MailboxRespHeader>() > mut_resp_bytes.len() {
return Err(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE);
}
let hdr: &mut MailboxRespHeader = MailboxRespHeader::mut_from_bytes(
&mut mut_resp_bytes[..size_of::<MailboxRespHeader>()],
)
.map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?;
// Set the chksum field
hdr.chksum = checksum;
Ok(())
}
}
impl Default for MailboxResp {
fn default() -> Self {
MailboxResp::Header(MailboxRespHeader::default())
}
}
#[cfg_attr(test, derive(PartialEq, Debug, Eq))]
#[allow(clippy::large_enum_variant)]
pub enum RomMailboxResp {
Header(MailboxRespHeader),
FipsVersion(FipsVersionResp),
Capabilities(CapabilitiesResp),
StashMeasurement(StashMeasurementResp),
GetIdevCsr(GetIdevCsrResp),
CmDeriveStableKey(CmDeriveStableKeyResp),
CmRandomGenerate(CmRandomGenerateResp),
CmHmac(CmHmacResp),
OcpLockReportHekMetaData(OcpLockReportHekMetadataReq),
InstallOwnerPkHash(InstallOwnerPkHashResp),
GetLdevCert(GetLdevCertResp),
ZeroizeUdsFe(ZeroizeUdsFeResp),
}
pub const MAX_ROM_RESP_SIZE: usize = size_of::<RomMailboxResp>();
#[cfg_attr(test, derive(PartialEq, Debug, Eq))]
#[allow(clippy::large_enum_variant)]
pub enum MailboxReq {
ActivateFirmware(ActivateFirmwareReq),
EcdsaVerify(EcdsaVerifyReq),
LmsVerify(LmsVerifyReq),
MldsaVerify(MldsaVerifyReq),
GetLdevEcc384Cert(GetLdevEcc384CertReq),
GetLdevMldsa87Cert(GetLdevMldsa87CertReq),
StashMeasurement(StashMeasurementReq),
InvokeDpeCommand(InvokeDpeReq),
FipsVersion(MailboxReqHeader),
FwInfo(MailboxReqHeader),
PopulateIdevEcc384Cert(PopulateIdevEcc384CertReq),
PopulateIdevMldsa87Cert(PopulateIdevMldsa87CertReq),
GetIdevEcc384Cert(GetIdevEcc384CertReq),
GetIdevMldsa87Cert(GetIdevMldsa87CertReq),
TagTci(TagTciReq),
GetTaggedTci(GetTaggedTciReq),
GetFmcAliasEcc384Cert(GetFmcAliasEcc384CertReq),
GetRtAliasEcc384Cert(GetRtAliasEcc384CertReq),
GetRtAliasMlDsa87Cert(GetRtAliasMlDsa87CertReq),
IncrementPcrResetCounter(IncrementPcrResetCounterReq),
QuotePcrsEcc384(QuotePcrsEcc384Req),
QuotePcrsMldsa87(QuotePcrsMldsa87Req),
ExtendPcr(ExtendPcrReq),
AddSubjectAltName(AddSubjectAltNameReq),
CertifyKeyExtended(CertifyKeyExtendedReq),
SetAuthManifest(SetAuthManifestReq),
VerifyAuthManifest(VerifyAuthManifestReq),
AuthorizeAndStash(AuthorizeAndStashReq),
SignWithExportedEcdsa(SignWithExportedEcdsaReq),
RevokeExportedCdiHandle(RevokeExportedCdiHandleReq),
GetImageInfo(GetImageInfoReq),
CmStatus(MailboxReqHeader),
CmImport(CmImportReq),
CmDelete(CmDeleteReq),
CmClear(MailboxReqHeader),
CmShaInit(CmShaInitReq),
CmShaUpdate(CmShaUpdateReq),
CmShaFinal(CmShaFinalReq),
CmRandomGenerate(CmRandomGenerateReq),
CmRandomStir(CmRandomStirReq),
CmAesEncryptInit(CmAesEncryptInitReq),
CmAesEncryptUpdate(CmAesEncryptUpdateReq),
CmAesDecryptInit(CmAesDecryptInitReq),
CmAesDecryptUpdate(CmAesDecryptUpdateReq),
CmAesGcmEncryptInit(CmAesGcmEncryptInitReq),
CmAesGcmSpdmEncryptInit(CmAesGcmSpdmEncryptInitReq),
CmAesGcmEncryptUpdate(CmAesGcmEncryptUpdateReq),
CmAesGcmEncryptFinal(CmAesGcmEncryptFinalReq),
CmAesGcmDecryptInit(CmAesGcmDecryptInitReq),
CmAesGcmSpdmDecryptInit(CmAesGcmSpdmDecryptInitReq),
CmAesGcmDecryptUpdate(CmAesGcmDecryptUpdateReq),
CmAesGcmDecryptFinal(CmAesGcmDecryptFinalReq),
CmEcdhGenerate(CmEcdhGenerateReq),
CmEcdhFinish(CmEcdhFinishReq),
CmHmac(CmHmacReq),
CmHmacKdfCounter(CmHmacKdfCounterReq),
CmHkdfExtract(CmHkdfExtractReq),
CmHkdfExpand(CmHkdfExpandReq),
CmMldsaPublicKey(CmMldsaPublicKeyReq),
CmMldsaSign(CmMldsaSignReq),
CmMldsaVerify(CmMldsaVerifyReq),
CmEcdsaPublicKey(CmEcdsaPublicKeyReq),
CmEcdsaSign(CmEcdsaSignReq),
CmEcdsaVerify(CmEcdsaVerifyReq),
CmDeriveStableKey(CmDeriveStableKeyReq),
OcpLockReportHekMetadata(OcpLockReportHekMetadataReq),
OcpLockGetAlgorithms(OcpLockGetAlgorithmsReq),
OcpLockInitializeMekSecret(OcpLockInitializeMekSecretReq),
OcpLockDeriveMek(OcpLockDeriveMekReq),
ProductionAuthDebugUnlockReq(ProductionAuthDebugUnlockReq),
ProductionAuthDebugUnlockToken(ProductionAuthDebugUnlockToken),
GetPcrLog(MailboxReqHeader),
ExternalMailboxCmd(ExternalMailboxCmdReq),
FeProg(FeProgReq),
ReallocateDpeContextLimits(ReallocateDpeContextLimitsReq),
}
pub const MAX_REQ_SIZE: usize = size_of::<MailboxReq>();
impl MailboxReq {
pub fn as_bytes(&self) -> CaliptraResult<&[u8]> {
match self {
MailboxReq::ActivateFirmware(req) => Ok(req.as_bytes()),
MailboxReq::EcdsaVerify(req) => Ok(req.as_bytes()),
MailboxReq::LmsVerify(req) => Ok(req.as_bytes()),
MailboxReq::MldsaVerify(req) => req.as_bytes_partial(),
MailboxReq::StashMeasurement(req) => Ok(req.as_bytes()),
MailboxReq::InvokeDpeCommand(req) => req.as_bytes_partial(),
MailboxReq::FipsVersion(req) => Ok(req.as_bytes()),
MailboxReq::FwInfo(req) => Ok(req.as_bytes()),
MailboxReq::GetLdevEcc384Cert(req) => Ok(req.as_bytes()),
MailboxReq::GetLdevMldsa87Cert(req) => Ok(req.as_bytes()),
MailboxReq::PopulateIdevEcc384Cert(req) => req.as_bytes_partial(),
MailboxReq::PopulateIdevMldsa87Cert(req) => req.as_bytes_partial(),
MailboxReq::GetIdevEcc384Cert(req) => req.as_bytes_partial(),
MailboxReq::GetIdevMldsa87Cert(req) => req.as_bytes_partial(),
MailboxReq::TagTci(req) => Ok(req.as_bytes()),
MailboxReq::GetTaggedTci(req) => Ok(req.as_bytes()),
MailboxReq::GetFmcAliasEcc384Cert(req) => Ok(req.as_bytes()),
MailboxReq::GetRtAliasEcc384Cert(req) => Ok(req.as_bytes()),
MailboxReq::GetRtAliasMlDsa87Cert(req) => Ok(req.as_bytes()),
MailboxReq::IncrementPcrResetCounter(req) => Ok(req.as_bytes()),
MailboxReq::QuotePcrsEcc384(req) => Ok(req.as_bytes()),
MailboxReq::QuotePcrsMldsa87(req) => Ok(req.as_bytes()),
MailboxReq::ExtendPcr(req) => Ok(req.as_bytes()),
MailboxReq::AddSubjectAltName(req) => req.as_bytes_partial(),
MailboxReq::CertifyKeyExtended(req) => Ok(req.as_bytes()),
MailboxReq::SetAuthManifest(req) => Ok(req.as_bytes()),
MailboxReq::VerifyAuthManifest(req) => Ok(req.as_bytes()),
MailboxReq::AuthorizeAndStash(req) => Ok(req.as_bytes()),
MailboxReq::SignWithExportedEcdsa(req) => Ok(req.as_bytes()),
MailboxReq::RevokeExportedCdiHandle(req) => Ok(req.as_bytes()),
MailboxReq::GetImageInfo(req) => Ok(req.as_bytes()),
MailboxReq::CmStatus(req) => Ok(req.as_bytes()),
MailboxReq::CmImport(req) => req.as_bytes_partial(),
MailboxReq::CmDelete(req) => Ok(req.as_bytes()),
MailboxReq::CmClear(req) => Ok(req.as_bytes()),
MailboxReq::CmShaInit(req) => req.as_bytes_partial(),
MailboxReq::CmShaUpdate(req) => req.as_bytes_partial(),
MailboxReq::CmShaFinal(req) => req.as_bytes_partial(),
MailboxReq::CmRandomGenerate(req) => Ok(req.as_bytes()),
MailboxReq::CmRandomStir(req) => req.as_bytes_partial(),
MailboxReq::CmAesEncryptInit(req) => req.as_bytes_partial(),
MailboxReq::CmAesEncryptUpdate(req) => req.as_bytes_partial(),
MailboxReq::CmAesDecryptInit(req) => req.as_bytes_partial(),
MailboxReq::CmAesDecryptUpdate(req) => req.as_bytes_partial(),
MailboxReq::CmAesGcmEncryptInit(req) => req.as_bytes_partial(),
MailboxReq::CmAesGcmSpdmEncryptInit(req) => req.as_bytes_partial(),
MailboxReq::CmAesGcmEncryptUpdate(req) => req.as_bytes_partial(),
MailboxReq::CmAesGcmEncryptFinal(req) => req.as_bytes_partial(),
MailboxReq::CmAesGcmDecryptInit(req) => req.as_bytes_partial(),
MailboxReq::CmAesGcmSpdmDecryptInit(req) => req.as_bytes_partial(),
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/api/src/lib.rs | api/src/lib.rs | // Licensed under the Apache-2.0 license
#![cfg_attr(not(test), no_std)]
mod capabilities;
pub mod checksum;
pub mod mailbox;
pub mod soc_mgr;
pub use caliptra_error as error;
pub use capabilities::Capabilities;
pub use checksum::{calc_checksum, verify_checksum};
pub use soc_mgr::SocManager;
#[derive(Debug, Eq, PartialEq)]
pub enum CaliptraApiError {
UnableToSetPauser,
UnableToLockMailbox,
UnableToReadMailbox,
BufferTooLargeForMailbox,
UnknownCommandStatus(u32),
MailboxTimeout,
MailboxCmdFailed(u32),
UnexpectedMailboxFsmStatus {
expected: u32,
actual: u32,
},
MailboxRespInvalidFipsStatus(u32),
MailboxRespInvalidChecksum {
expected: u32,
actual: u32,
},
MailboxRespTypeTooSmall,
MailboxReqTypeTooSmall,
MailboxNoResponseData,
MailboxUnexpectedResponseLen {
expected_min: u32,
expected_max: u32,
actual: u32,
},
UploadFirmwareUnexpectedResponse,
UploadMeasurementResponseError,
ReadBuffTooSmall,
FusesAlreadyIniitalized,
FuseDoneNotSet,
StashMeasurementFailed,
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/api/src/checksum.rs | api/src/checksum.rs | // Licensed under the Apache-2.0 license
/// Verify checksum
pub fn verify_checksum(checksum: u32, cmd: u32, data: &[u8]) -> bool {
calc_checksum(cmd, data) == checksum
}
/// Calculate the checksum
/// 0 - (SUM(command code bytes) + SUM(request/response bytes))
pub fn calc_checksum(cmd: u32, data: &[u8]) -> u32 {
let mut checksum = 0u32;
for c in cmd.to_le_bytes().iter() {
checksum = checksum.wrapping_add(*c as u32);
}
for d in data {
checksum = checksum.wrapping_add(*d as u32);
}
0u32.wrapping_sub(checksum)
}
#[cfg(all(test, target_family = "unix"))]
mod tests {
use super::*;
#[test]
fn test_calc_checksum() {
assert_eq!(calc_checksum(0xe8dc3994, &[0x83, 0xe7, 0x25]), 0xfffffbe0);
}
#[test]
fn test_checksum_overflow() {
let data = vec![0xff; 16843007];
assert_eq!(calc_checksum(0xe8dc3994, &data), 0xffffff6e);
assert!(verify_checksum(0xffffff6e, 0xe8dc3994, &data));
}
#[test]
fn test_verify_checksum() {
assert!(verify_checksum(0xfffffbe0, 0xe8dc3994, &[0x83, 0xe7, 0x25]));
assert!(!verify_checksum(
0xfffffbdf,
0xe8dc3994,
&[0x83, 0xe7, 0x25]
));
assert!(!verify_checksum(
0xfffffbe1,
0xe8dc3994,
&[0x83, 0xe7, 0x25]
));
// subtraction overflow; would panic in debug mode if non-wrapping
// subtraction was used.
assert!(!verify_checksum(
0xffffffff,
0xe8dc3994,
&[0x83, 0xe7, 0x25]
));
}
#[test]
fn test_round_trip() {
let cmd = 0x00000001u32;
let data = [0x00000000u32; 1];
let checksum = calc_checksum(cmd, data[0].to_le_bytes().as_ref());
assert!(verify_checksum(checksum, cmd, &data[0].to_le_bytes()));
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/api/src/soc_mgr.rs | api/src/soc_mgr.rs | // Licensed under the Apache-2.0 license
use crate::{
calc_checksum,
mailbox::{
mbox_read_response, mbox_write_fifo, MailboxReqHeader, MailboxRespHeader, Request,
Response, StashMeasurementReq,
},
CaliptraApiError,
};
use caliptra_api_types::Fuses;
use core::mem;
use ureg::MmioMut;
use zerocopy::{FromBytes, FromZeros, IntoBytes};
pub const NUM_PAUSERS: usize = 5;
/// Implementation of the `SocManager` trait for a `RealSocManager`.
///
/// # Example
///
/// ```rust
/// use caliptra_api::SocManager;
/// use ureg::RealMmioMut;
/// struct RealSocManager;
/// const CPTRA_SOC_IFC_ADDR: u32 = 0x3003_0000;
/// const CPTRA_SOC_IFC_TRNG_ADDR: u32 = 0x3003_0000;
/// const CPTRA_SOC_MBOX_ADDR: u32 = 0x3002_0000;
/// const fn caliptra_address_remap(addr : u32) -> u32 {
/// addr
/// }
/// impl SocManager for RealSocManager {
/// /// Address of the mailbox, remapped for the SoC.
/// const SOC_MBOX_ADDR: u32 = caliptra_address_remap(CPTRA_SOC_MBOX_ADDR);
///
/// /// Address of the SoC interface, remapped for the SoC.
/// const SOC_IFC_ADDR: u32 = caliptra_address_remap(CPTRA_SOC_IFC_ADDR);
///
/// /// Address of the SoC TRNG interface, remapped for the SoC.
/// const SOC_IFC_TRNG_ADDR: u32 = caliptra_address_remap(CPTRA_SOC_IFC_TRNG_ADDR);
///
/// /// Maximum number of wait cycles.
/// const MAX_WAIT_CYCLES: u32 = 400000;
///
/// /// Type alias for mutable memory-mapped I/O.
/// type TMmio<'a> = RealMmioMut<'a>;
///
/// /// Returns a mutable reference to the memory-mapped I/O.
/// fn mmio_mut(&mut self) -> Self::TMmio<'_> {
/// ureg::RealMmioMut::default()
/// }
///
/// /// Provides a delay function to be invoked when polling mailbox status.
/// fn delay(&mut self) {
/// //real_soc_delay_fn(1);
/// }
/// }
/// ```
pub trait SocManager {
const SOC_IFC_ADDR: u32;
const SOC_MBOX_ADDR: u32;
const SOC_IFC_TRNG_ADDR: u32;
const MAX_WAIT_CYCLES: u32;
type TMmio<'a>: MmioMut
where
Self: 'a;
fn mmio_mut(&mut self) -> Self::TMmio<'_>;
// Provide a time base for mailbox status polling loop.
fn delay(&mut self);
/// Set up valid PAUSERs for mailbox access.
fn setup_mailbox_users(&mut self, apb_pausers: &[u32]) -> Result<(), CaliptraApiError> {
if apb_pausers.len() > NUM_PAUSERS {
return Err(CaliptraApiError::UnableToSetPauser);
}
for (idx, apb_pauser) in apb_pausers.iter().enumerate() {
if self
.soc_ifc()
.cptra_mbox_axi_user_lock()
.at(idx)
.read()
.lock()
{
return Err(CaliptraApiError::UnableToSetPauser);
}
self.soc_ifc()
.cptra_mbox_valid_axi_user()
.at(idx)
.write(|_| *apb_pauser);
self.soc_ifc()
.cptra_mbox_axi_user_lock()
.at(idx)
.write(|w| w.lock(true));
}
Ok(())
}
/// Initializes the fuse values and locks them in until the next reset.
///
/// # Errors
///
/// If the cptra_fuse_wr_done has already been written, or the
/// hardware prevents cptra_fuse_wr_done from being set.
fn init_fuses(&mut self, fuses: &Fuses) -> Result<(), CaliptraApiError> {
if !self.soc_ifc().cptra_reset_reason().read().warm_reset()
&& self.soc_ifc().cptra_fuse_wr_done().read().done()
{
return Err(CaliptraApiError::FusesAlreadyIniitalized);
}
self.soc_ifc().fuse_uds_seed().write(&fuses.uds_seed);
self.soc_ifc()
.fuse_field_entropy()
.write(&fuses.field_entropy);
self.soc_ifc()
.fuse_vendor_pk_hash()
.write(&fuses.vendor_pk_hash);
self.soc_ifc()
.fuse_ecc_revocation()
.write(|w| w.ecc_revocation(fuses.fuse_ecc_revocation.into()));
self.soc_ifc()
.cptra_owner_pk_hash()
.write(&fuses.owner_pk_hash);
self.soc_ifc().fuse_runtime_svn().write(&fuses.fw_svn);
self.soc_ifc()
.fuse_anti_rollback_disable()
.write(|w| w.dis(fuses.anti_rollback_disable));
self.soc_ifc()
.fuse_idevid_cert_attr()
.write(&fuses.idevid_cert_attr);
self.soc_ifc()
.fuse_idevid_manuf_hsm_id()
.write(&fuses.idevid_manuf_hsm_id);
self.soc_ifc()
.fuse_lms_revocation()
.write(|_| fuses.fuse_lms_revocation);
self.soc_ifc()
.fuse_mldsa_revocation()
.write(|_| fuses.fuse_mldsa_revocation.into());
self.soc_ifc()
.fuse_soc_stepping_id()
.write(|w| w.soc_stepping_id(fuses.soc_stepping_id.into()));
self.soc_ifc()
.fuse_manuf_dbg_unlock_token()
.write(&fuses.manuf_dbg_unlock_token);
self.soc_ifc()
.fuse_pqc_key_type()
.write(|w| w.key_type(fuses.fuse_pqc_key_type));
self.soc_ifc()
.fuse_soc_manifest_svn()
.write(&fuses.soc_manifest_svn);
self.soc_ifc()
.fuse_soc_manifest_max_svn()
.write(|w| w.svn(fuses.soc_manifest_max_svn as u32));
self.soc_ifc().fuse_hek_seed().write(&fuses.hek_seed);
self.soc_ifc().cptra_fuse_wr_done().write(|w| w.done(true));
if !self.soc_ifc().cptra_fuse_wr_done().read().done() {
return Err(CaliptraApiError::FuseDoneNotSet);
}
Ok(())
}
/// A register block that can be used to manipulate the soc_ifc peripheral
/// over the simulated SoC->Caliptra APB bus.
fn soc_ifc(&mut self) -> caliptra_registers::soc_ifc::RegisterBlock<Self::TMmio<'_>> {
unsafe {
caliptra_registers::soc_ifc::RegisterBlock::new_with_mmio(
Self::SOC_IFC_ADDR as *mut u32,
self.mmio_mut(),
)
}
}
/// A register block that can be used to manipulate the soc_ifc peripheral TRNG registers
/// over the simulated SoC->Caliptra APB bus.
fn soc_ifc_trng(&mut self) -> caliptra_registers::soc_ifc_trng::RegisterBlock<Self::TMmio<'_>> {
unsafe {
caliptra_registers::soc_ifc_trng::RegisterBlock::new_with_mmio(
Self::SOC_IFC_TRNG_ADDR as *mut u32,
self.mmio_mut(),
)
}
}
/// A register block that can be used to manipulate the mbox peripheral
/// over the simulated SoC->Caliptra APB bus.
fn soc_mbox(&mut self) -> caliptra_registers::mbox::RegisterBlock<Self::TMmio<'_>> {
unsafe {
caliptra_registers::mbox::RegisterBlock::new_with_mmio(
Self::SOC_MBOX_ADDR as *mut u32,
self.mmio_mut(),
)
}
}
/// Executes `cmd` with request data `buf`. Returns `Ok(Some(_))` if
/// the uC responded with data, `Ok(None)` if the uC indicated success
/// without data, Err(CaliptraApiError::MailboxCmdFailed) if the microcontroller
/// responded with an error, or other errors if there was a problem
/// communicating with the mailbox.
fn mailbox_exec<'r>(
&mut self,
cmd: u32,
buf: &[u8],
resp_data: &'r mut [u8],
) -> core::result::Result<Option<&'r [u8]>, CaliptraApiError> {
self.start_mailbox_exec(cmd, buf)?;
self.finish_mailbox_exec(resp_data)
}
/// Send a command to the mailbox but don't wait for the response
fn start_mailbox_exec(
&mut self,
cmd: u32,
buf: &[u8],
) -> core::result::Result<(), CaliptraApiError> {
// Read a 0 to get the lock
if self.soc_mbox().lock().read().lock() {
return Err(CaliptraApiError::UnableToLockMailbox);
}
// Mailbox lock value should read 1 now
// If not, the reads are likely being blocked by the PAUSER check or some other issue
if !(self.soc_mbox().lock().read().lock()) {
return Err(CaliptraApiError::UnableToReadMailbox);
}
self.soc_mbox().cmd().write(|_| cmd);
mbox_write_fifo(&self.soc_mbox(), buf)?;
// Ask the microcontroller to execute this command
self.soc_mbox().execute().write(|w| w.execute(true));
Ok(())
}
fn finish_mailbox_exec<'r>(
&mut self,
resp_data: &'r mut [u8],
) -> core::result::Result<Option<&'r [u8]>, CaliptraApiError> {
// Wait for the microcontroller to finish executing
let mut timeout_cycles = Self::MAX_WAIT_CYCLES; // 100ms @400MHz
while self.soc_mbox().status().read().status().cmd_busy() {
self.delay();
timeout_cycles -= 1;
if timeout_cycles == 0 {
return Err(CaliptraApiError::MailboxTimeout);
}
}
let status = self.soc_mbox().status().read().status();
if status.cmd_failure() {
self.soc_mbox().execute().write(|w| w.execute(false));
let soc_ifc = self.soc_ifc();
return Err(CaliptraApiError::MailboxCmdFailed(
if soc_ifc.cptra_fw_error_fatal().read() != 0 {
soc_ifc.cptra_fw_error_fatal().read()
} else {
soc_ifc.cptra_fw_error_non_fatal().read()
},
));
}
if status.cmd_complete() {
self.soc_mbox().execute().write(|w| w.execute(false));
return Ok(None);
}
if !status.data_ready() {
return Err(CaliptraApiError::UnknownCommandStatus(status as u32));
}
let res = mbox_read_response(self.soc_mbox(), resp_data);
self.soc_mbox().execute().write(|w| w.execute(false));
let buf = res?;
Ok(Some(buf))
}
/// Executes a typed request and (if success), returns the typed response.
/// The checksum field of the request is calculated, and the checksum of the
/// response is validated.
fn mailbox_exec_req<R: Request>(
&mut self,
mut req: R,
resp_bytes: &mut [u8],
) -> core::result::Result<R::Resp, CaliptraApiError> {
if mem::size_of::<R>() < mem::size_of::<MailboxReqHeader>() {
return Err(CaliptraApiError::MailboxReqTypeTooSmall);
}
if mem::size_of::<R::Resp>() < mem::size_of::<MailboxRespHeader>() {
return Err(CaliptraApiError::MailboxRespTypeTooSmall);
}
if R::Resp::MIN_SIZE < mem::size_of::<MailboxRespHeader>() {
return Err(CaliptraApiError::MailboxRespTypeTooSmall);
}
let (header_bytes, payload_bytes) = req
.as_mut_bytes()
.split_at_mut(mem::size_of::<MailboxReqHeader>());
let header = MailboxReqHeader::mut_from_bytes(header_bytes as &mut [u8]).unwrap();
header.chksum = calc_checksum(R::ID.into(), payload_bytes);
let Some(data) = SocManager::mailbox_exec(self, R::ID.into(), req.as_bytes(), resp_bytes)?
else {
return Err(CaliptraApiError::MailboxNoResponseData);
};
if data.len() < R::Resp::MIN_SIZE || data.len() > mem::size_of::<R::Resp>() {
return Err(CaliptraApiError::MailboxUnexpectedResponseLen {
expected_min: R::Resp::MIN_SIZE as u32,
expected_max: mem::size_of::<R::Resp>() as u32,
actual: data.len() as u32,
});
}
let mut response = R::Resp::new_zeroed();
response.as_mut_bytes()[..data.len()].copy_from_slice(data);
let (response_header, _) = MailboxRespHeader::read_from_prefix(data).unwrap();
let actual_checksum = calc_checksum(0, &data[4..]);
if actual_checksum != response_header.chksum {
return Err(CaliptraApiError::MailboxRespInvalidChecksum {
expected: response_header.chksum,
actual: actual_checksum,
});
}
if response_header.fips_status != MailboxRespHeader::FIPS_STATUS_APPROVED {
return Err(CaliptraApiError::MailboxRespInvalidFipsStatus(
response_header.fips_status,
));
}
Ok(response)
}
fn send_stash_measurement_req(
&mut self,
req: StashMeasurementReq,
response_packet: &mut [u8],
) -> Result<(), CaliptraApiError> {
let resp = self.mailbox_exec_req(req, response_packet)?;
if resp.dpe_result == 0 {
return Ok(());
}
Err(CaliptraApiError::StashMeasurementFailed)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/api/src/capabilities.rs | api/src/capabilities.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
capabilities.rs
Abstract:
Capability bits
--*/
bitflags::bitflags! {
/// First 64 bits are reserved for RT, next 32 bits are reserved for FMC, and final 32 bits are reserved for ROM
#[derive(Default, Copy, Clone, Debug)]
pub struct Capabilities : u128 {
// Represents base capabilities present in Caliptra ROM v1.0
const ROM_BASE = 0b1;
// ROM and hardware support for OCP LOCK
const ROM_OCP_LOCK = 0b1 << 1;
// Represents base capabilities present in Caliptra Runtime v1.0
const RT_BASE = 0b1 << 64;
// RT firmware and hardware supports OCP LOCK
const RT_OCP_LOCK = 0b1 << 65;
}
}
impl Capabilities {
pub const SIZE_IN_BYTES: usize = 16;
pub fn to_bytes(&self) -> [u8; Capabilities::SIZE_IN_BYTES] {
self.bits().to_be_bytes()
}
}
impl TryFrom<&[u8]> for Capabilities {
type Error = ();
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
if value.len() != Capabilities::SIZE_IN_BYTES {
Err(())
} else {
let capabilities = u128::from_be_bytes(value.try_into().unwrap());
let caps = Capabilities::from_bits(capabilities);
caps.ok_or(())
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/api/types/src/lib.rs | api/types/src/lib.rs | // Licensed under the Apache-2.0 license
#![cfg_attr(not(test), no_std)]
use caliptra_image_types::FwVerificationPqcKeyType;
// Rationale behind this choice
//
// * The constant should be easily recognizable in waveforms and debug logs
// * Every word must be different to ensure that a "stuck word" bug is noticed.
// * Each byte in a word must be unique to ensure an endianness bug is noticed.
pub const DEFAULT_UDS_SEED: [u32; 16] = [
0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, 0x10111213, 0x14151617, 0x18191a1b, 0x1c1d1e1f,
0x20212223, 0x24252627, 0x28292a2b, 0x2c2d2e2f, 0x30313233, 0x34353637, 0x38393a3b, 0x3c3d3e3f,
];
pub const DEFAULT_FIELD_ENTROPY: [u32; 8] = [
0x80818283, 0x84858687, 0x88898a8b, 0x8c8d8e8f, 0x90919293, 0x94959697, 0x98999a9b, 0x9c9d9e9f,
];
pub const DEFAULT_CPTRA_OBF_KEY: [u32; 8] = [
0xa0a1a2a3, 0xb0b1b2b3, 0xc0c1c2c3, 0xd0d1d2d3, 0xe0e1e2e3, 0xf0f1f2f3, 0xa4a5a6a7, 0xb4b5b6b7,
];
pub const DEFAULT_CSR_HMAC_KEY: [u32; 16] = [
0x14552AD, 0x19550757, 0x50C602DD, 0x85DE4E9B, 0x815CC9EF, 0xBA81A35, 0x7A05D7C0, 0x7F5EFAEB,
0xF76DD9D2, 0x9E38197F, 0x4052537, 0x25B568F4, 0x432665F1, 0xD11D02A7, 0xBFB9279F, 0xA2EB96D7,
];
pub const DEFAULT_MANUF_DEBUG_UNLOCK_TOKEN: [u32; 8] = [
0x552c92d8, 0x7f732b79, 0xe5f31329, 0x7554e6cb, 0x6e015262, 0xa163e9ae, 0x3a754edd, 0x96f087f7,
];
// This is in the hardware format (little-endian)
pub const DEFAULT_MANUF_DEBUG_UNLOCK_TOKEN_HASH: [u32; 16] = [
0x869ba8d5, 0xad0fcf82, 0x02e56080, 0x3281da65, 0x9812ffa2, 0xfc28c2d5, 0x154cb645, 0xee0c38ec,
0x4fd9dd8b, 0xb0be7deb, 0x193f6253, 0x81383a91, 0xab40bd92, 0x0fcd9425, 0x919e6372, 0x3c0bf7a8,
];
pub const DEFAULT_PQC_KEY_TYPE: u32 = FwVerificationPqcKeyType::MLDSA as u32;
// Based on device_lifecycle_e from RTL
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum DeviceLifecycle {
#[default]
Unprovisioned = 0b00,
Manufacturing = 0b01,
Reserved2 = 0b10,
Production = 0b11,
}
impl TryFrom<u32> for DeviceLifecycle {
type Error = ();
fn try_from(value: u32) -> Result<Self, Self::Error> {
match value {
0b00 => Ok(Self::Unprovisioned),
0b01 => Ok(Self::Manufacturing),
0b10 => Ok(Self::Reserved2),
0b11 => Ok(Self::Production),
_ => Err(()),
}
}
}
impl From<DeviceLifecycle> for u32 {
fn from(value: DeviceLifecycle) -> Self {
value as u32
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct SecurityState(u32);
impl From<u32> for SecurityState {
fn from(value: u32) -> Self {
Self(value)
}
}
impl From<SecurityState> for u32 {
fn from(value: SecurityState) -> Self {
value.0
}
}
impl SecurityState {
pub fn debug_locked(self) -> bool {
(self.0 & (1 << 2)) != 0
}
pub fn set_debug_locked(&mut self, val: bool) -> &mut Self {
let mask = 1 << 2;
if val {
self.0 |= mask;
} else {
self.0 &= !mask
};
self
}
pub fn device_lifecycle(self) -> DeviceLifecycle {
DeviceLifecycle::try_from(self.0 & 0x3).unwrap()
}
pub fn set_device_lifecycle(&mut self, val: DeviceLifecycle) -> &mut Self {
self.0 |= (val as u32) & 0x3;
self
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct DbgManufServiceRegReq(u32);
impl From<u32> for DbgManufServiceRegReq {
fn from(value: u32) -> Self {
Self(value)
}
}
impl From<DbgManufServiceRegReq> for u32 {
fn from(value: DbgManufServiceRegReq) -> Self {
value.0
}
}
impl DbgManufServiceRegReq {
pub fn set_manuf_dbg_unlock_req(&mut self, val: bool) -> &mut Self {
let mask = 1 << 0;
if val {
self.0 |= mask;
} else {
self.0 &= !mask
};
self
}
pub fn set_prod_dbg_unlock_req(&mut self, val: bool) -> &mut Self {
let mask = 1 << 1;
if val {
self.0 |= mask;
} else {
self.0 &= !mask
};
self
}
pub fn set_uds_program_req(&mut self, val: bool) -> &mut Self {
let mask = 1 << 2;
if val {
self.0 |= mask;
} else {
self.0 &= !mask
};
self
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum U4 {
#[default]
X0 = 0x0,
X1 = 0x1,
X2 = 0x2,
X3 = 0x3,
X4 = 0x4,
X5 = 0x5,
X6 = 0x6,
X7 = 0x7,
X8 = 0x8,
X9 = 0x9,
Xa = 0xa,
Xb = 0xb,
Xc = 0xc,
Xd = 0xd,
Xe = 0xe,
Xf = 0xf,
}
impl U4 {
pub const B0000: Self = Self::X0;
pub const B0001: Self = Self::X1;
pub const B0010: Self = Self::X2;
pub const B0011: Self = Self::X3;
pub const B0100: Self = Self::X4;
pub const B0101: Self = Self::X5;
pub const B0110: Self = Self::X6;
pub const B0111: Self = Self::X7;
pub const B1000: Self = Self::X8;
pub const B1001: Self = Self::X9;
pub const B1010: Self = Self::Xa;
pub const B1011: Self = Self::Xb;
pub const B1100: Self = Self::Xc;
pub const B1101: Self = Self::Xd;
pub const B1110: Self = Self::Xe;
pub const B1111: Self = Self::Xf;
}
impl From<U4> for u32 {
fn from(value: U4) -> Self {
value as u32
}
}
impl TryFrom<u32> for U4 {
type Error = ();
fn try_from(value: u32) -> Result<Self, Self::Error> {
match value {
0b0000 => Ok(Self::X0),
0b0001 => Ok(Self::X1),
0b0010 => Ok(Self::X2),
0b0011 => Ok(Self::X3),
0b0100 => Ok(Self::X4),
0b0101 => Ok(Self::X5),
0b0110 => Ok(Self::X6),
0b0111 => Ok(Self::X7),
0b1000 => Ok(Self::X8),
0b1001 => Ok(Self::X9),
0b1010 => Ok(Self::Xa),
0b1011 => Ok(Self::Xb),
0b1100 => Ok(Self::Xc),
0b1101 => Ok(Self::Xd),
0b1110 => Ok(Self::Xe),
0b1111 => Ok(Self::Xf),
16_u32..=u32::MAX => Err(()),
}
}
}
#[derive(Clone, Debug)]
pub struct Fuses {
pub uds_seed: [u32; 16],
pub field_entropy: [u32; 8],
pub hek_seed: [u32; 8],
pub vendor_pk_hash: [u32; 12],
pub fuse_ecc_revocation: U4,
pub owner_pk_hash: [u32; 12],
pub fw_svn: [u32; 4],
pub anti_rollback_disable: bool,
pub idevid_cert_attr: [u32; 24],
pub idevid_manuf_hsm_id: [u32; 4],
pub life_cycle: DeviceLifecycle,
pub fuse_lms_revocation: u32,
pub fuse_mldsa_revocation: u32,
pub soc_stepping_id: u16,
pub fuse_pqc_key_type: u32,
pub manuf_dbg_unlock_token: [u32; 16],
pub debug_locked: bool,
pub soc_manifest_svn: [u32; 4],
pub soc_manifest_max_svn: u8,
}
impl Default for Fuses {
fn default() -> Self {
Self {
uds_seed: DEFAULT_UDS_SEED,
field_entropy: DEFAULT_FIELD_ENTROPY,
hek_seed: [0; 8],
vendor_pk_hash: Default::default(),
fuse_ecc_revocation: Default::default(),
owner_pk_hash: Default::default(),
fw_svn: Default::default(),
anti_rollback_disable: Default::default(),
idevid_cert_attr: Default::default(),
idevid_manuf_hsm_id: Default::default(),
life_cycle: Default::default(),
fuse_lms_revocation: Default::default(),
fuse_mldsa_revocation: Default::default(),
soc_stepping_id: Default::default(),
fuse_pqc_key_type: DEFAULT_PQC_KEY_TYPE,
manuf_dbg_unlock_token: DEFAULT_MANUF_DEBUG_UNLOCK_TOKEN_HASH,
debug_locked: false,
soc_manifest_max_svn: 128,
soc_manifest_svn: Default::default(),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_security_state() {
let mut ss = *SecurityState::default()
.set_debug_locked(true)
.set_device_lifecycle(DeviceLifecycle::Manufacturing);
assert_eq!(0x5u32, ss.into());
assert!(ss.debug_locked());
assert_eq!(ss.device_lifecycle(), DeviceLifecycle::Manufacturing);
ss.set_debug_locked(false);
assert_eq!(0x1u32, ss.into());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/fips.rs | common/src/fips.rs | // Licensed under the Apache-2.0 license
use crate::cprintln;
use crate::mailbox_api::{FipsVersionResp, MailboxRespHeader};
use caliptra_drivers::SocIfc;
pub struct FipsVersionCmd;
impl FipsVersionCmd {
pub const NAME: [u8; 12] = *b"Caliptra RTM";
pub const MODE: u32 = 0x46495053;
#[cfg_attr(feature = "runtime", inline(never))]
pub fn execute(soc_ifc: &SocIfc) -> FipsVersionResp {
cprintln!("[rt] FIPS Version");
FipsVersionResp {
hdr: MailboxRespHeader::default(),
mode: Self::MODE,
fips_rev: soc_ifc.get_version(),
name: Self::NAME,
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/pmp.rs | common/src/pmp.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
pmp.rs
Abstract:
PMP support routine for locking the DataVault.
--*/
use riscv::register::{pmpaddr0, pmpaddr1, pmpaddr2, pmpaddr3, pmpcfg0, Permission, Range};
/// Lock the DataVault region using PMP configuration.
///
/// # Arguments
/// * `base_address` - Base address of the region
/// * `region_size` - Size of the region
/// * `cold_reset_region` - True if the region is for Cold Reset, false for Warm Reset
///
/// Note: If a PMP entry is locked, writes to the configuration register and
/// associated address registers are ignored.
///
pub fn lock_datavault_region(base_address: usize, region_size: usize, cold_reset_region: bool) {
unsafe {
// Calculate the end address of the region
let end_address = base_address + region_size;
// PMP address register encodes Bits 33:2 of a 34-bit physical address.
let base_address = base_address >> 2;
let end_address = end_address >> 2;
let index: usize = if cold_reset_region {
// Use pmp1cfg for Cold Reset region.
pmpaddr0::write(base_address);
pmpaddr1::write(end_address);
1
} else {
// Use pmp3cfg for Warm Reset region.
pmpaddr2::write(base_address);
pmpaddr3::write(end_address);
3
};
// Set the PMP configuration.
pmpcfg0::set_pmp(index, Range::TOR, Permission::R, true);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/lib.rs | common/src/lib.rs | // Licensed under the Apache-2.0 license.
#![cfg_attr(not(feature = "std"), no_std)]
pub mod boot_status;
pub mod capabilities {
pub use caliptra_api::Capabilities;
}
pub mod checksum {
pub use caliptra_api::{calc_checksum, verify_checksum};
}
pub mod crypto;
pub mod debug_unlock;
pub mod dice;
pub mod error_handler;
pub mod fips;
pub mod hmac_cm;
pub mod keyids;
pub mod macros;
pub mod pmp;
pub mod uds_fe_programming;
pub mod verifier;
pub mod verify;
pub mod wdt;
pub mod x509;
///merge imports
pub use hand_off::{
DataStore, DataVaultRegister, FirmwareHandoffTable, HandOffDataHandle, Vault,
FHT_INVALID_HANDLE, FHT_MARKER,
};
pub use boot_status::RomBootStatus;
pub use caliptra_api::mailbox as mailbox_api;
pub use caliptra_drivers::cprint;
pub use caliptra_drivers::cprintln;
pub use caliptra_drivers::fuse_log as fuse;
pub use caliptra_drivers::hand_off;
pub use caliptra_drivers::memory_layout;
pub use caliptra_drivers::pcr_log as pcr;
pub use caliptra_drivers::printer::HexBytes;
pub use caliptra_drivers::printer::Printer;
pub use caliptra_drivers::CptraGeneration;
pub use error_handler::handle_fatal_error;
pub use fuse::{FuseLogEntry, FuseLogEntryId};
pub use pcr::{PcrLogEntry, PcrLogEntryId, RT_FW_CURRENT_PCR, RT_FW_JOURNEY_PCR};
pub use pmp::lock_datavault_region;
pub const FMC_ORG: u32 = 0x40000000;
pub const FMC_SIZE: u32 = 36 * 1024; // Must be 4k aligned
pub const RUNTIME_ORG: u32 = FMC_ORG + FMC_SIZE;
pub const RUNTIME_SIZE: u32 = 160 * 1024;
pub use memory_layout::{EXTRA_MEMORY_ORG, PERSISTENT_DATA_ORG};
pub use wdt::{restart_wdt, start_wdt, stop_wdt, WdtTimeout};
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/dice.rs | common/src/dice.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
dice.rs
Abstract:
DICE-related
--*/
use caliptra_api::mailbox::{AlgorithmType, GetLdevCertResp, MailboxRespHeader, ResponseVarSize};
use caliptra_drivers::{
CaliptraError, CaliptraResult, Ecc384Signature, Lifecycle, Mldsa87Signature, PersistentData,
};
use caliptra_x509::{Ecdsa384CertBuilder, Ecdsa384Signature, MlDsa87CertBuilder};
use crate::hmac_cm::mutrefbytes;
pub const FLAG_BIT_NOT_CONFIGURED: u32 = 1 << 0;
pub const FLAG_BIT_NOT_SECURE: u32 = 1 << 1;
pub const FLAG_BIT_DEBUG: u32 = 1 << 3;
pub const FLAG_BIT_FIXED_WIDTH: u32 = 1 << 31;
/// Return the LDevId ECC cert signature
///
/// # Arguments
///
/// * `persistent_data` - PersistentData
///
/// # Returns
///
/// * `Ecc384Signature` - The formed signature
pub fn ldevid_dice_sign(persistent_data: &PersistentData) -> Ecc384Signature {
persistent_data.rom.data_vault.ldev_dice_ecc_signature()
}
/// Return the LDevId MLDSA87 cert signature
///
/// # Arguments
///
/// * `persistent_data` - PersistentData
///
/// # Returns
///
/// * `Mldsa87Signature` - The formed signature
pub fn ldevid_dice_mldsa87_sign(persistent_data: &PersistentData) -> Mldsa87Signature {
persistent_data.rom.data_vault.ldev_dice_mldsa_signature()
}
pub struct GetLdevCertCmd;
impl GetLdevCertCmd {
#[inline(never)]
pub fn execute(
persistent_data: &PersistentData,
alg_type: AlgorithmType,
resp: &mut [u8],
) -> CaliptraResult<usize> {
let resp = mutrefbytes::<GetLdevCertResp>(resp)?;
resp.hdr = MailboxRespHeader::default();
match alg_type {
AlgorithmType::Ecc384 => {
resp.data_size = copy_ldevid_ecc384_cert(persistent_data, &mut resp.data)? as u32;
}
AlgorithmType::Mldsa87 => {
resp.data_size = copy_ldevid_mldsa87_cert(persistent_data, &mut resp.data)? as u32;
}
}
resp.partial_len()
}
}
/// Create a certificate from a tbs and a signature and write the output to `cert`
///
/// # Arguments
///
/// * `tbs` - ToBeSigned portion
/// * `sig` - Ecc384Signature
/// * `cert` - Buffer to copy LDevID certificate to
///
/// # Returns
/// * `usize` - The number of bytes written to `cert`
pub fn ecc384_cert_from_tbs_and_sig(
tbs: Option<&[u8]>,
sig: &Ecc384Signature,
cert: &mut [u8],
) -> CaliptraResult<usize> {
let Some(tbs) = tbs else {
return Err(CaliptraError::CALIPTRA_INTERNAL);
};
// Convert from Ecc384Signature to Ecdsa384Signature
let bldr_sig = Ecdsa384Signature {
r: sig.r.into(),
s: sig.s.into(),
};
let Some(builder) = Ecdsa384CertBuilder::new(tbs, &bldr_sig) else {
return Err(CaliptraError::CALIPTRA_INTERNAL);
};
let Some(size) = builder.build(cert) else {
return Err(CaliptraError::CALIPTRA_INTERNAL);
};
Ok(size)
}
/// Create a certificate from a tbs and a signature and write the output to `cert`
///
/// # Arguments
///
/// * `tbs` - ToBeSigned portion
/// * `sig` - MlDsa87Signature
/// * `cert` - Buffer to copy LDevID certificate to
///
/// # Returns
/// * `usize` - The number of bytes written to `cert`
pub fn mldsa87_cert_from_tbs_and_sig(
tbs: Option<&[u8]>,
sig: &Mldsa87Signature,
cert: &mut [u8],
) -> CaliptraResult<usize> {
let Some(tbs) = tbs else {
return Err(CaliptraError::CALIPTRA_INTERNAL);
};
let sig_bytes = <[u8; 4628]>::from(sig)[..4627].try_into().unwrap();
let signature = caliptra_x509::MlDsa87Signature { sig: sig_bytes };
let Some(builder) = MlDsa87CertBuilder::new(tbs, &signature) else {
return Err(CaliptraError::CALIPTRA_INTERNAL);
};
let Some(size) = builder.build(cert) else {
return Err(CaliptraError::CALIPTRA_INTERNAL);
};
Ok(size)
}
/// Copy ECC LDevID certificate produced by ROM to `cert` buffer
///
/// # Arguments
///
/// * `persistent_data` - PersistentData
/// * `cert` - Buffer to copy LDevID certificate to
///
/// # Returns
///
/// * `usize` - The number of bytes written to `cert`
#[inline(never)]
pub fn copy_ldevid_ecc384_cert(
persistent_data: &PersistentData,
cert: &mut [u8],
) -> CaliptraResult<usize> {
let tbs = persistent_data
.rom
.ecc_ldevid_tbs
.get(..persistent_data.rom.fht.ecc_ldevid_tbs_size.into());
let sig = ldevid_dice_sign(persistent_data);
ecc384_cert_from_tbs_and_sig(tbs, &sig, cert).map_err(|_| CaliptraError::GET_LDEVID_CERT_FAILED)
}
/// Copy MLDSA LDevID certificate produced by ROM to `cert` buffer
///
/// # Arguments
///
/// * `persistent_data` - PersistentData
/// * `cert` - Buffer to copy LDevID certificate to
///
/// # Returns
///
/// * `usize` - The number of bytes written to `cert`
#[inline(never)]
pub fn copy_ldevid_mldsa87_cert(
persistent_data: &PersistentData,
cert: &mut [u8],
) -> CaliptraResult<usize> {
let tbs = persistent_data
.rom
.mldsa_ldevid_tbs
.get(..persistent_data.rom.fht.mldsa_ldevid_tbs_size.into());
let sig = ldevid_dice_mldsa87_sign(persistent_data);
mldsa87_cert_from_tbs_and_sig(tbs, &sig, cert)
.map_err(|_| CaliptraError::GET_LDEVID_CERT_FAILED)
}
/// Generate flags for DICE evidence
///
/// # Arguments
///
/// * `device_lifecycle` - Device lifecycle
/// * `debug_locked` - Debug locked
pub fn make_flags(device_lifecycle: Lifecycle, debug_locked: bool) -> [u8; 4] {
let mut flags: u32 = FLAG_BIT_FIXED_WIDTH;
flags |= match device_lifecycle {
Lifecycle::Unprovisioned => FLAG_BIT_NOT_CONFIGURED,
Lifecycle::Manufacturing => FLAG_BIT_NOT_SECURE,
_ => 0,
};
if !debug_locked {
flags |= FLAG_BIT_DEBUG;
}
flags.reverse_bits().to_be_bytes()
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/hmac_cm.rs | common/src/hmac_cm.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
hmac_cm.rs
Abstract:
HMAC Cryptographic Mailbox command processing.
--*/
use crate::crypto::{Crypto, EncryptedCmk, UnencryptedCmk};
use caliptra_api::mailbox::{
CmHashAlgorithm, CmHmacReq, CmHmacResp, CmKeyUsage, Cmk, MailboxRespHeaderVarSize,
ResponseVarSize,
};
use caliptra_drivers::{Aes, Array4x12, Array4x16, Hmac, HmacData, HmacMode, LEArray4x8, Trng};
use caliptra_error::{CaliptraError, CaliptraResult};
use caliptra_image_types::{SHA384_DIGEST_BYTE_SIZE, SHA512_DIGEST_BYTE_SIZE};
use zerocopy::{FromBytes, IntoBytes, KnownLayout};
#[inline(always)]
pub(crate) fn mutrefbytes<R: FromBytes + IntoBytes + KnownLayout>(
resp: &mut [u8],
) -> CaliptraResult<&mut R> {
// the error should be impossible but check to avoid panic
let (resp, _) = R::mut_from_prefix(resp).map_err(|_| CaliptraError::RUNTIME_INTERNAL)?;
Ok(resp)
}
pub fn decrypt_hmac_key(
aes: &mut Aes,
trng: &mut Trng,
kek: (LEArray4x8, LEArray4x8),
cmk: &Cmk,
) -> CaliptraResult<UnencryptedCmk> {
let encrypted_cmk = EncryptedCmk::ref_from_bytes(&cmk.0[..])
.map_err(|_| CaliptraError::CMB_HMAC_INVALID_ENC_CMK)?;
let cmk = Crypto::decrypt_cmk(aes, trng, kek, encrypted_cmk)?;
match (cmk.length, CmKeyUsage::from(cmk.key_usage as u32)) {
(48 | 64, CmKeyUsage::Hmac) => Ok(cmk),
_ => Err(CaliptraError::CMB_HMAC_INVALID_KEY_USAGE),
}
}
#[inline(always)]
pub fn hmac(
hmac: &mut Hmac,
aes: &mut Aes,
trng: &mut Trng,
kek: (LEArray4x8, LEArray4x8),
cmd_bytes: &[u8],
resp: &mut [u8],
) -> CaliptraResult<usize> {
if cmd_bytes.len() > core::mem::size_of::<CmHmacReq>() {
Err(CaliptraError::CMB_HMAC_INVALID_REQ_SIZE)?;
}
let mut cmd = CmHmacReq::default();
cmd.as_mut_bytes()[..cmd_bytes.len()].copy_from_slice(cmd_bytes);
let cm_hash_algorithm = CmHashAlgorithm::from(cmd.hash_algorithm);
if cmd.data_size as usize > cmd.data.len() {
Err(CaliptraError::CMB_HMAC_INVALID_REQ_SIZE)?;
}
let data = &cmd.data[..cmd.data_size as usize];
let cmk = decrypt_hmac_key(aes, trng, kek, &cmd.cmk)?;
// the hardware will fail if a 384-bit key is used with SHA512
if cmk.length == 48 && cm_hash_algorithm != CmHashAlgorithm::Sha384 {
Err(CaliptraError::CMB_HMAC_INVALID_KEY_USAGE_AND_SIZE)?;
}
let resp = mutrefbytes::<CmHmacResp>(resp)?;
resp.hdr = MailboxRespHeaderVarSize::default();
resp.hdr.data_len = match cm_hash_algorithm {
CmHashAlgorithm::Sha384 => SHA384_DIGEST_BYTE_SIZE as u32,
CmHashAlgorithm::Sha512 => SHA512_DIGEST_BYTE_SIZE as u32,
_ => return Err(CaliptraError::CMB_HMAC_UNSUPPORTED_HASH_ALGORITHM)?,
};
match cm_hash_algorithm {
CmHashAlgorithm::Sha384 => {
let hmac_mode = HmacMode::Hmac384;
let arr: [u8; 48] = cmk.key_material[..48].try_into().unwrap();
let key: Array4x12 = arr.into();
let mut tag = Array4x12::default();
hmac.hmac(
(&key).into(),
HmacData::Slice(data),
trng,
(&mut tag).into(),
hmac_mode,
)?;
// convert out of HW format
tag.0.iter_mut().for_each(|x| {
*x = x.swap_bytes();
});
resp.mac[..tag.as_bytes().len()].copy_from_slice(tag.as_bytes())
}
CmHashAlgorithm::Sha512 => {
let hmac_mode = HmacMode::Hmac512;
let arr: [u8; 64] = cmk.key_material[..64].try_into().unwrap();
let key: Array4x16 = arr.into();
let mut tag = Array4x16::default();
hmac.hmac(
(&key).into(),
HmacData::Slice(data),
trng,
(&mut tag).into(),
hmac_mode,
)?;
// convert out of HW format
tag.0.iter_mut().for_each(|x| {
*x = x.swap_bytes();
});
resp.mac[..tag.as_bytes().len()].copy_from_slice(tag.as_bytes())
}
_ => return Err(CaliptraError::CMB_HMAC_UNSUPPORTED_HASH_ALGORITHM)?,
};
resp.partial_len()
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/wdt.rs | common/src/wdt.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
wdt.rs
Abstract:
File contains execution routines for programming the Watchdog Timer.
--*/
use caliptra_drivers::SocIfc;
pub struct WdtTimeout(pub core::num::NonZeroU64);
impl Default for WdtTimeout {
fn default() -> WdtTimeout {
WdtTimeout::new_const(WDT1_MIN_TIMEOUT_IN_CYCLES)
}
}
impl WdtTimeout {
pub const ROM_WDT1_TIMEOUT_IN_CYCLES: WdtTimeout =
WdtTimeout::new_const(10 * EXPECTED_CALIPTRA_BOOT_TIME_IN_CYCLES);
pub const fn new_const(timeout_cycles: u64) -> Self {
match core::num::NonZeroU64::new(timeout_cycles) {
Some(val) => Self(val),
None => panic!("WdtTimeout cannot be 0"),
}
}
}
impl From<core::num::NonZeroU64> for WdtTimeout {
fn from(val: core::num::NonZeroU64) -> Self {
WdtTimeout(val)
}
}
impl From<WdtTimeout> for core::num::NonZeroU64 {
fn from(val: WdtTimeout) -> Self {
val.0
}
}
impl From<WdtTimeout> for u64 {
fn from(val: WdtTimeout) -> Self {
core::num::NonZeroU64::from(val).get()
}
}
const EXPECTED_CALIPTRA_BOOT_TIME_IN_CYCLES: u64 = 20_000_000; // 20 million cycles
const WDT2_TIMEOUT_CYCLES: u64 = 1; // Fire immediately after WDT1 expiry
const WDT1_MIN_TIMEOUT_IN_CYCLES: u64 = EXPECTED_CALIPTRA_BOOT_TIME_IN_CYCLES;
/// Start the Watchdog Timer
///
/// # Arguments
///
/// * `soc_ifc` - SOC Interface
///
///
pub fn start_wdt(soc_ifc: &mut SocIfc, wdt1_timeout_cycles: WdtTimeout) {
if !soc_ifc.debug_locked() {
return;
}
// Set WDT1 period.
soc_ifc.set_wdt1_timeout(wdt1_timeout_cycles.into());
// Set WDT2 period.
soc_ifc.set_wdt2_timeout(WDT2_TIMEOUT_CYCLES);
// Enable WDT1 only. WDT2 is automatically scheduled (since it is disabled) on WDT1 expiry.
soc_ifc.configure_wdt1(true);
restart_wdt(soc_ifc);
}
/// Restart the Watchdog Timer
///
/// # Arguments
///
/// * `env` - ROM Environment
///
pub fn restart_wdt(soc_ifc: &mut SocIfc) {
// Only restart WDT1. WDT2 is automatically scheduled (since it is disabled) on WDT1 expiry.
soc_ifc.reset_wdt1();
}
/// Stop the Watchdog Timer
///
/// # Arguments
///
/// * `soc_ifc` - SOC Interface
///
pub fn stop_wdt(soc_ifc: &mut SocIfc) {
if !soc_ifc.debug_locked() {
return;
}
soc_ifc.configure_wdt1(false);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/verify.rs | common/src/verify.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
verify.rs
Abstract:
File contains EcdsaVerify mailbox command.
--*/
use caliptra_api::mailbox::{EcdsaVerifyReq, MldsaVerifyReq};
use caliptra_cfi_derive_git::cfi_impl_fn;
use caliptra_drivers::{
Array4x12, CaliptraError, CaliptraResult, Ecc384, Ecc384PubKey, Ecc384Result, Ecc384Scalar,
Ecc384Signature, Mldsa87, Mldsa87PubKey, Mldsa87Result, Mldsa87Signature,
};
use zerocopy::FromBytes;
pub struct EcdsaVerifyCmd;
impl EcdsaVerifyCmd {
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
#[inline(never)]
pub fn execute(ecc384: &mut Ecc384, cmd_args: &[u8]) -> CaliptraResult<usize> {
let cmd = EcdsaVerifyReq::ref_from_bytes(cmd_args)
.map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?;
let digest = Array4x12::from(cmd.hash);
let pubkey = Ecc384PubKey {
x: Ecc384Scalar::from(cmd.pub_key_x),
y: Ecc384Scalar::from(cmd.pub_key_y),
};
let sig = Ecc384Signature {
r: Ecc384Scalar::from(cmd.signature_r),
s: Ecc384Scalar::from(cmd.signature_s),
};
let success = ecc384.verify(&pubkey, &digest, &sig)?;
if success != Ecc384Result::Success {
if cfg!(feature = "rom") {
return Err(CaliptraError::ROM_ECDSA_VERIFY_FAILED);
} else if cfg!(feature = "runtime") {
return Err(CaliptraError::RUNTIME_ECDSA_VERIFY_FAILED);
}
}
Ok(0)
}
}
pub struct MldsaVerifyCmd;
impl MldsaVerifyCmd {
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
#[inline(never)]
pub fn execute(mldsa87: &mut Mldsa87, cmd_args: &[u8]) -> CaliptraResult<usize> {
let pubkey_bytes = MldsaVerifyReq::pub_key(cmd_args)
.ok_or(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?;
let pubkey = &Mldsa87PubKey::from(pubkey_bytes);
let signature_bytes = MldsaVerifyReq::signature(cmd_args)
.ok_or(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?;
let signature = Mldsa87Signature::from(*signature_bytes);
let message = MldsaVerifyReq::message(cmd_args)
.ok_or(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?;
let success = mldsa87.verify_var(pubkey, message, &signature)?;
if success != Mldsa87Result::Success {
if cfg!(feature = "rom") {
return Err(CaliptraError::ROM_MLDSA_VERIFY_FAILED);
} else if cfg!(feature = "runtime") {
return Err(CaliptraError::RUNTIME_MLDSA_VERIFY_FAILED);
}
}
Ok(0)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/macros.rs | common/src/macros.rs | // Licensed under the Apache-2.0 license.
#[macro_export]
macro_rules! cfi_check {
($result:expr) => {
if cfi_launder($result.is_ok()) {
cfi_assert!($result.is_ok());
} else {
cfi_assert!($result.is_err());
}
};
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/keyids.rs | common/src/keyids.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
keyids.rs
Abstract:
Key IDs
--*/
use caliptra_drivers::KeyId;
#[cfg(feature = "rom")]
pub const KEY_ID_UDS: KeyId = KeyId::KeyId0;
#[cfg(feature = "rom")]
pub const KEY_ID_FE: KeyId = KeyId::KeyId1;
#[cfg(feature = "rom")]
pub const KEY_ID_IDEVID_ECDSA_PRIV_KEY: KeyId = KeyId::KeyId7;
#[cfg(feature = "rom")]
pub const KEY_ID_IDEVID_MLDSA_KEYPAIR_SEED: KeyId = KeyId::KeyId8;
#[cfg(feature = "rom")]
pub const KEY_ID_LDEVID_MLDSA_KEYPAIR_SEED: KeyId = KeyId::KeyId4;
#[cfg(feature = "rom")]
pub const KEY_ID_LDEVID_ECDSA_PRIV_KEY: KeyId = KeyId::KeyId5;
#[cfg(feature = "rom")]
pub const KEY_ID_ROM_FMC_CDI: KeyId = KeyId::KeyId6;
#[cfg(feature = "rom")]
pub const KEY_ID_FMC_ECDSA_PRIV_KEY: KeyId = KeyId::KeyId7;
#[cfg(feature = "rom")]
pub const KEY_ID_FMC_MLDSA_KEYPAIR_SEED: KeyId = KeyId::KeyId8;
#[cfg(feature = "rom")]
pub const KEY_ID_FW_KEY_LADDER: KeyId = KeyId::KeyId2;
#[cfg(feature = "fmc")]
pub const KEY_ID_RT_CDI: KeyId = KeyId::KeyId4;
#[cfg(feature = "fmc")]
pub const KEY_ID_RT_ECDSA_PRIV_KEY: KeyId = KeyId::KeyId5;
#[cfg(feature = "fmc")]
pub const KEY_ID_RT_MLDSA_KEYPAIR_SEED: KeyId = KeyId::KeyId9;
#[cfg(feature = "runtime")]
pub const KEY_ID_DPE_CDI: KeyId = KeyId::KeyId10;
#[cfg(feature = "runtime")]
pub const KEY_ID_DPE_PRIV_KEY: KeyId = KeyId::KeyId11;
#[cfg(feature = "runtime")]
pub const KEY_ID_EXPORTED_DPE_CDI: KeyId = KeyId::KeyId12;
pub const KEY_ID_STABLE_IDEV: KeyId = KeyId::KeyId0;
pub const KEY_ID_STABLE_LDEV: KeyId = KeyId::KeyId1;
pub const KEY_ID_TMP: KeyId = KeyId::KeyId3;
pub mod ocp_lock {
use super::KeyId;
pub const KEY_ID_MDK: KeyId = KeyId::KeyId16;
pub const KEY_ID_EPK: KeyId = KeyId::KeyId17;
pub const KEY_ID_MEK_SECRETS: KeyId = KeyId::KeyId21;
pub const KEY_ID_HEK: KeyId = KeyId::KeyId22;
pub const KEY_ID_HEK_SEED: KeyId = KeyId::KeyId22;
pub const KEY_ID_MEK: KeyId = KeyId::KeyId23;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/debug_unlock.rs | common/src/debug_unlock.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
debug_unlock.rs
Abstract:
File contains common code for debug unlock validation.
--*/
use core::mem::size_of;
use caliptra_api::mailbox::{
MailboxReqHeader, MailboxRespHeader, ProductionAuthDebugUnlockChallenge,
ProductionAuthDebugUnlockReq, ProductionAuthDebugUnlockToken,
};
use caliptra_cfi_lib::{cfi_assert_eq_12_words, cfi_launder};
use caliptra_drivers::{
sha2_512_384::Sha2DigestOpTrait, Array4x12, Array4x16, AxiAddr, Dma, Ecc384, Ecc384PubKey,
Ecc384Result, Ecc384Scalar, Ecc384Signature, LEArray4x16, Mldsa87, Mldsa87PubKey,
Mldsa87Result, Mldsa87Signature, Sha2_512_384, Sha2_512_384Acc, ShaAccLockState, SocIfc,
StreamEndianness, Trng,
};
use caliptra_error::{CaliptraError, CaliptraResult};
use memoffset::{offset_of, span_of};
use zerocopy::IntoBytes;
/// Create a challenge for production debug unlock
///
/// # Arguments
///
/// * `trng` - TRNG driver for generating challenge
/// * `soc_ifc` - SOC interface for accessing fuse bank
/// * `request` - The debug unlock request
///
/// # Returns
///
/// * `CaliptraResult<ProductionAuthDebugUnlockChallenge>` - The challenge response
pub fn create_debug_unlock_challenge(
trng: &mut Trng,
soc_ifc: &SocIfc,
request: &ProductionAuthDebugUnlockReq,
) -> CaliptraResult<ProductionAuthDebugUnlockChallenge> {
// Validate payload
if request.length as usize * size_of::<u32>()
!= size_of::<ProductionAuthDebugUnlockReq>() - size_of::<MailboxReqHeader>()
{
crate::cprintln!(
"Invalid ProductionAuthDebugUnlockReq payload length: {}",
request.length
);
Err(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_REQ)?;
}
// Check if the debug level is valid.
let dbg_level = request.unlock_level as u32;
if dbg_level > soc_ifc.debug_unlock_pk_hash_count() {
crate::cprintln!(
"Invalid debug level: Received level: {}, Fuse PK Hash Count: {}",
dbg_level,
soc_ifc.debug_unlock_pk_hash_count()
);
Err(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_REQ)?;
}
let length = ((size_of::<ProductionAuthDebugUnlockChallenge>()
- size_of::<MailboxRespHeader>())
/ size_of::<u32>()) as u32;
let challenge = trng.generate()?.as_bytes().try_into().unwrap();
let challenge_resp: ProductionAuthDebugUnlockChallenge = ProductionAuthDebugUnlockChallenge {
length,
unique_device_identifier: {
let mut id = [0u8; 32];
id[..17].copy_from_slice(&soc_ifc.fuse_bank().ueid());
id
},
challenge,
..Default::default()
};
Ok(challenge_resp)
}
/// Validates a production debug unlock token
#[allow(clippy::too_many_arguments)]
pub fn validate_debug_unlock_token(
soc_ifc: &SocIfc,
sha2_512_384: &mut Sha2_512_384,
sha2_512_384_acc: &mut Sha2_512_384Acc,
ecc384: &mut Ecc384,
mldsa87: &mut Mldsa87,
dma: &mut Dma,
request: &ProductionAuthDebugUnlockReq,
challenge: &ProductionAuthDebugUnlockChallenge,
token: &ProductionAuthDebugUnlockToken,
) -> CaliptraResult<()> {
// Validate the payload size.
if token.length as usize * size_of::<u32>()
!= size_of::<ProductionAuthDebugUnlockToken>() - size_of::<MailboxReqHeader>()
{
crate::cprintln!(
"Invalid ProductionAuthDebugUnlockToken payload length: {}",
token.length
);
Err(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_TOKEN_CHALLENGE)?
}
// Check if the debug level is same as the request.
if token.unlock_level != request.unlock_level {
crate::cprintln!("Invalid unlock level: {}", token.unlock_level);
Err(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_TOKEN_CHALLENGE)?;
}
// Check if the challenge is same as the request.
if cfi_launder(token.challenge) != challenge.challenge {
crate::cprintln!("Challenge mismatch");
Err(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_TOKEN_CHALLENGE)?;
} else {
cfi_assert_eq_12_words(
&Array4x12::from(token.challenge).0,
&Array4x12::from(challenge.challenge).0,
);
}
// Hash the ECC and MLDSA public keys in the payload.
let pub_keys_digest = {
let ecc_public_key_offset = offset_of!(ProductionAuthDebugUnlockToken, ecc_public_key);
let combined_len = span_of!(
ProductionAuthDebugUnlockToken,
ecc_public_key..=mldsa_public_key
)
.len();
let mut request_digest = Array4x12::default();
let lock_state = if cfg!(feature = "rom") {
ShaAccLockState::AssumedLocked
} else {
ShaAccLockState::NotAcquired
};
let mut acc_op = sha2_512_384_acc
.try_start_operation(lock_state)?
.ok_or(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_TOKEN_WRONG_PUBLIC_KEYS)?;
acc_op.digest_384(
combined_len as u32,
ecc_public_key_offset as u32,
StreamEndianness::Reorder,
&mut request_digest,
)?;
request_digest
};
let debug_auth_pk_offset =
soc_ifc.debug_unlock_pk_hash_offset(token.unlock_level as u32)? as u64;
let mci_base: AxiAddr = soc_ifc.mci_base_addr().into();
let debug_auth_pk_hash_base = mci_base + debug_auth_pk_offset;
let mut fuse_digest: [u32; 12] = [0; 12];
dma.read_buffer(debug_auth_pk_hash_base, &mut fuse_digest);
// Verify the fuse digest matches with the ECC and MLDSA public key digest.
let fuse_digest = Array4x12::from(fuse_digest);
if cfi_launder(pub_keys_digest) != fuse_digest {
crate::cprintln!("Public keys hash mismatch");
Err(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_TOKEN_WRONG_PUBLIC_KEYS)?;
} else {
cfi_assert_eq_12_words(&pub_keys_digest.0, &fuse_digest.0);
}
// Verify that the Unique Device Identifier, Unlock Category and Challenge signature is valid.
let pubkey = Ecc384PubKey {
x: Ecc384Scalar::from(<[u32; 12]>::try_from(&token.ecc_public_key[..12]).unwrap()),
y: Ecc384Scalar::from(<[u32; 12]>::try_from(&token.ecc_public_key[12..]).unwrap()),
};
let signature = Ecc384Signature {
r: Ecc384Scalar::from(<[u32; 12]>::try_from(&token.ecc_signature[..12]).unwrap()),
s: Ecc384Scalar::from(<[u32; 12]>::try_from(&token.ecc_signature[12..]).unwrap()),
};
// Create ECC message hash
let mut digest_op = sha2_512_384.sha384_digest_init()?;
digest_op.update(&token.unique_device_identifier)?;
digest_op.update(&[token.unlock_level])?;
digest_op.update(&token.reserved)?;
digest_op.update(&token.challenge)?;
let mut ecc_msg = Array4x12::default();
digest_op.finalize(&mut ecc_msg)?;
let result = ecc384.verify(&pubkey, &ecc_msg, &signature)?;
if result == Ecc384Result::SigVerifyFailed {
crate::cprintln!("ECC Signature verification failed");
Err(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_TOKEN_INVALID_SIGNATURE)?;
}
// Create MLDSA message hash
let mut digest_op = sha2_512_384.sha512_digest_init()?;
digest_op.update(&token.unique_device_identifier)?;
digest_op.update(&[token.unlock_level])?;
digest_op.update(&token.reserved)?;
digest_op.update(&token.challenge)?;
let mut mldsa_msg = Array4x16::default();
digest_op.finalize(&mut mldsa_msg)?;
// Convert the digest to little endian format for MLDSA.
let mldsa_msg: LEArray4x16 = mldsa_msg.into();
let result = mldsa87.verify(
&Mldsa87PubKey::from(&token.mldsa_public_key),
&mldsa_msg,
&Mldsa87Signature::from(&token.mldsa_signature),
)?;
if result == Mldsa87Result::SigVerifyFailed {
crate::cprintln!("MLDSA Signature verification failed");
Err(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_TOKEN_INVALID_SIGNATURE)?;
}
Ok(())
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/crypto.rs | common/src/crypto.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
crypto.rs
Abstract:
Crypto helper routines
--*/
use crate::keyids::KEY_ID_TMP;
use caliptra_drivers::{
okmutref, okref, Aes, AesGcmIv, AesKey, Array4x12, CaliptraResult, Ecc384, Ecc384PrivKeyIn,
Ecc384PrivKeyOut, Ecc384PubKey, Ecc384Result, Ecc384Signature, Hmac, HmacData, HmacMode, KeyId,
KeyReadArgs, KeyUsage, KeyVault, KeyWriteArgs, LEArray4x3, LEArray4x4, LEArray4x8, Mldsa87,
Mldsa87PubKey, Mldsa87Result, Mldsa87Seed, Mldsa87SignRnd, Mldsa87Signature, PersistentData,
Sha2_512_384, Trng,
};
use caliptra_error::CaliptraError;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
use zeroize::Zeroize;
/// DICE Layer ECC Key Pair
#[derive(Debug, Zeroize)]
pub struct Ecc384KeyPair {
/// Private Key KV Slot Id
#[zeroize(skip)]
pub priv_key: KeyId,
/// Public Key
pub pub_key: Ecc384PubKey,
}
/// DICE Layer MLDSA Key Pair
#[derive(Debug, Zeroize)]
pub struct MlDsaKeyPair {
/// Key Pair Generation KV Slot Id
#[zeroize(skip)]
pub key_pair_seed: KeyId,
/// Public Key
pub pub_key: Mldsa87PubKey,
}
#[derive(Debug)]
pub enum PubKey<'a> {
Ecc(&'a Ecc384PubKey),
Mldsa(&'a Mldsa87PubKey),
}
pub const CMK_MAX_KEY_SIZE_BITS: usize = 512;
pub const UNENCRYPTED_CMK_SIZE_BYTES: usize = 80;
#[repr(C)]
#[derive(Clone, FromBytes, Immutable, IntoBytes, KnownLayout)]
pub struct UnencryptedCmk {
pub version: u16,
pub length: u16,
pub key_usage: u8,
pub id: [u8; 3],
pub usage_counter: u64,
pub key_material: [u8; CMK_MAX_KEY_SIZE_BITS / 8],
}
impl UnencryptedCmk {
#[allow(unused)]
pub fn key_id(&self) -> u32 {
self.id[0] as u32 | ((self.id[1] as u32) << 8) | ((self.id[2] as u32) << 16)
}
}
#[repr(C)]
#[derive(Clone, FromBytes, Immutable, IntoBytes, KnownLayout)]
pub struct EncryptedCmk {
pub domain: u32,
pub domain_metadata: [u8; 16],
pub iv: LEArray4x3,
pub ciphertext: [u8; UNENCRYPTED_CMK_SIZE_BYTES],
pub gcm_tag: LEArray4x4,
}
pub struct Crypto {}
impl Crypto {
/// Calculate HMAC
///
/// # Arguments
///
/// * `env` - ROM Environment
/// * `key` - HMAC key slot
/// * `data` - Input data to hash
/// * `tag` - Key slot to store the tag
/// * `mode` - HMAC Mode
/// * `key_usage` - Key usage flags for the output key
#[inline(always)]
pub fn hmac_mac(
hmac: &mut Hmac,
trng: &mut Trng,
key: KeyId,
data: HmacData,
tag: KeyId,
mode: HmacMode,
key_usage: KeyUsage,
) -> CaliptraResult<()> {
hmac.hmac(
KeyReadArgs::new(key).into(),
data,
trng,
KeyWriteArgs::new(tag, key_usage).into(),
mode,
)
}
/// Calculate HMAC KDF
///
/// # Arguments
///
/// * `hmac` - HMAC driver
/// * `trng` - TRNG driver
/// * `key` - HMAC key slot
/// * `label` - Input label
/// * `context` - Input context
/// * `output` - Key slot to store the output
/// * `mode` - HMAC Mode
/// * `key_usage` - Key usage flags for the output key
#[inline(always)]
#[allow(clippy::too_many_arguments)]
pub fn hmac_kdf(
hmac: &mut Hmac,
trng: &mut Trng,
key: KeyId,
label: &[u8],
context: Option<&[u8]>,
output: KeyId,
mode: HmacMode,
key_usage: KeyUsage,
) -> CaliptraResult<()> {
caliptra_drivers::hmac_kdf(
hmac,
KeyReadArgs::new(key).into(),
label,
context,
trng,
KeyWriteArgs::new(output, key_usage).into(),
mode,
)
}
/// Generate ECC Key Pair
///
/// # Arguments
///
/// * `ecc384` - ECC384 driver
/// * `hmac` - HMAC driver
/// * `trng` - TRNG driver
/// * `key_vault` - Caliptra key vault
/// * `cdi` - Key slot to retrieve the CDI from
/// * `label` - Diversification label
/// * `priv_key` - Key slot to store the private key
///
/// # Returns
///
/// * `Ecc384KeyPair` - Private Key slot id and public key pairs
#[inline(always)]
pub fn ecc384_key_gen(
ecc384: &mut Ecc384,
hmac: &mut Hmac,
trng: &mut Trng,
key_vault: &mut KeyVault,
cdi: KeyId,
label: &[u8],
priv_key: KeyId,
) -> CaliptraResult<Ecc384KeyPair> {
Self::hmac_kdf(
hmac,
trng,
cdi,
label,
None,
KEY_ID_TMP,
HmacMode::Hmac512,
KeyUsage::default().set_ecc_key_gen_seed_en(),
)?;
let key_out = Ecc384PrivKeyOut::Key(KeyWriteArgs::new(
priv_key,
KeyUsage::default().set_ecc_private_key_en(),
));
let pub_key = ecc384.key_pair(
KeyReadArgs::new(KEY_ID_TMP).into(),
&Array4x12::default(),
trng,
key_out,
);
key_vault.erase_key(KEY_ID_TMP)?;
Ok(Ecc384KeyPair {
priv_key,
pub_key: pub_key?,
})
}
/// Sign data using ECC Private Key
///
/// This routine calculates the digest of the `data` and signs the hash
///
/// # Arguments
///
/// * `sha2_512_384` - SHA384 driver
/// * `ecc384` - ECC384 driver
/// * `trng` - TRNG driver
/// * `priv_key` - Key slot to retrieve the private key
/// * `data` - Input data to hash
///
/// # Returns
///
/// * `Ecc384Signature` - Signature
#[inline(always)]
pub fn ecdsa384_sign(
sha2_512_384: &mut Sha2_512_384,
ecc384: &mut Ecc384,
trng: &mut Trng,
priv_key: KeyId,
pub_key: &Ecc384PubKey,
data: &[u8],
) -> CaliptraResult<Ecc384Signature> {
let digest = sha2_512_384.sha384_digest(data);
let digest = okref(&digest)?;
let priv_key_args = KeyReadArgs::new(priv_key);
let priv_key = Ecc384PrivKeyIn::Key(priv_key_args);
ecc384.sign(priv_key, pub_key, digest, trng)
}
/// Verify the ECC Signature
///
/// This routine calculates the digest and verifies the signature
///
/// # Arguments
///
/// * `sha2_512_384` - Sha2_512_384 driver
/// * `ecc384` - ECC384 driver
/// * `pub_key` - Public key to verify the signature
/// * `data` - Input data to hash
/// * `sig` - Signature to verify
///
/// # Returns
///
/// * `Ecc384Result` - Ecc384Result::Success if the signature verification passed else an error code.
#[inline(always)]
pub fn ecdsa384_verify(
sha2_512_384: &mut Sha2_512_384,
ecc384: &mut Ecc384,
pub_key: &Ecc384PubKey,
data: &[u8],
sig: &Ecc384Signature,
) -> CaliptraResult<Ecc384Result> {
let digest = sha2_512_384.sha384_digest(data);
let digest = okref(&digest)?;
ecc384.verify(pub_key, digest, sig)
}
/// Sign the data using ECC Private Key.
/// Verify the signature using the ECC Public Key.
///
/// This routine calculates the digest of the `data`, signs the hash and returns the signature.
/// This routine also verifies the signature using the public key.
///
/// # Arguments
///
/// * `sha2_512_384` - Sha2_512_384 driver
/// * `ecc384` - ECC384 driver
/// * `trng` - TRNG driver
/// * `priv_key` - Key slot to retrieve the private key
/// * `pub_key` - Public key to verify with
/// * `data` - Input data to hash
///
/// # Returns
///
/// * `Ecc384Signature` - Signature
#[inline(always)]
pub fn ecdsa384_sign_and_verify(
sha2_512_384: &mut Sha2_512_384,
ecc384: &mut Ecc384,
trng: &mut Trng,
priv_key: KeyId,
pub_key: &Ecc384PubKey,
data: &[u8],
) -> CaliptraResult<Ecc384Signature> {
let mut digest = sha2_512_384.sha384_digest(data);
let digest = okmutref(&mut digest)?;
let priv_key_args = KeyReadArgs::new(priv_key);
let priv_key = Ecc384PrivKeyIn::Key(priv_key_args);
let result = ecc384.sign(priv_key, pub_key, digest, trng);
digest.0.zeroize();
result
}
/// Generate MLDSA Key Pair
///
/// # Arguments
///
/// * `mldsa` - MLDSA87 driver
/// * `hmac` - HMAC driver
/// * `trng` - TRNG driver
/// * `cdi` - Key slot to retrieve the CDI from
/// * `label` - Diversification label
/// * `key_pair_seed` - Key slot to store the keypair generation seed.
///
/// # Returns
///
/// * `MlDsaKeyPair` - Public Key and keypair generation seed
#[inline(always)]
pub fn mldsa87_key_gen(
mldsa87: &mut Mldsa87,
hmac: &mut Hmac,
trng: &mut Trng,
cdi: KeyId,
label: &[u8],
key_pair_seed: KeyId,
) -> CaliptraResult<MlDsaKeyPair> {
// Generate the seed for key pair generation.
Self::hmac_kdf(
hmac,
trng,
cdi,
label,
None,
key_pair_seed,
HmacMode::Hmac512,
KeyUsage::default().set_mldsa_key_gen_seed_en(),
)?;
// Generate the public key.
let pub_key = mldsa87.key_pair(
Mldsa87Seed::Key(KeyReadArgs::new(key_pair_seed)),
trng,
None,
)?;
Ok(MlDsaKeyPair {
key_pair_seed,
pub_key,
})
}
/// Sign data using MLDSA Private Key
///
/// # Arguments
///
/// * `mldsa` - MLDSA87 driver
/// * `trng` - TRNG driver
/// * `key_pair_seed` - Key slot to retrieve the keypair generation seed
/// * `pub_key` - Public key to verify the signature
/// * `data` - Input data to sign
///
/// # Returns
///
/// * `Mldsa87Signature` - Signature
#[inline(always)]
pub fn mldsa87_sign(
mldsa87: &mut Mldsa87,
trng: &mut Trng,
key_pair_seed: KeyId,
pub_key: &Mldsa87PubKey,
data: &[u8],
) -> CaliptraResult<Mldsa87Signature> {
mldsa87.sign_var(
Mldsa87Seed::Key(KeyReadArgs::new(key_pair_seed)),
pub_key,
data,
&Mldsa87SignRnd::default(),
trng,
)
}
/// Verify the MLDSA Signature
///
/// # Arguments
///
/// * `mldsa` - MLDSA87 driver
/// * `pub_key` - Public key to verify the signature
/// * `data` - Input data to verify the signature on
/// * `sig` - Signature to verify
///
/// # Returns
///
/// * `Mldsa87Result` - Mldsa87Result::Success if the signature verification passed else an error code.
#[inline(always)]
pub fn mldsa87_verify(
mldsa87: &mut Mldsa87,
pub_key: &Mldsa87PubKey,
data: &[u8],
sig: &Mldsa87Signature,
) -> CaliptraResult<Mldsa87Result> {
mldsa87.verify_var(pub_key, data, sig)
}
/// Sign the data using MLDSA Private Key.
/// Verify the signature using the MLDSA Public Key.
///
/// # Arguments
///
/// * `mldsa` - MLDSA87 driver
/// * `trng` - TRNG driver
/// * `key_pair_seed` - Key slot to retrieve the keypair generation seed
/// * `pub_key` - Public key to verify the signature
/// * `data` - Input data to sign
///
/// # Returns
///
/// * `Mldsa384Signature` - Signature
#[inline(always)]
pub fn mldsa87_sign_and_verify(
mldsa87: &mut Mldsa87,
trng: &mut Trng,
key_pair_seed: KeyId,
pub_key: &Mldsa87PubKey,
data: &[u8],
) -> CaliptraResult<Mldsa87Signature> {
mldsa87.sign_var(
Mldsa87Seed::Key(KeyReadArgs::new(key_pair_seed)),
pub_key,
data,
&Mldsa87SignRnd::default(),
trng,
)
}
pub fn get_cmb_aes_key(pdata: &PersistentData) -> (LEArray4x8, LEArray4x8) {
(pdata.rom.cmb_aes_key_share0, pdata.rom.cmb_aes_key_share1)
}
/// Encrypt the Cryptographic Mailbox Key (CML) using the Key Encryption Key (KEK)
///
/// # Arguments
/// * `aes` - AES driver
/// * `trng` - TRNG driver
/// * `unencrypted_cmk` - Unencrypted CMK to encrypt
/// * `kek_iv` - Initialization vector for the KEK
/// * `kek` - Key Encrption Key (AES key)
///
/// # Returns
/// * `EncryptedCmk` - Encrypted CMK
///
#[inline(always)]
pub fn encrypt_cmk(
aes: &mut Aes,
trng: &mut Trng,
unencrypted_cmk: &UnencryptedCmk,
kek_iv: LEArray4x3,
kek: (LEArray4x8, LEArray4x8),
) -> CaliptraResult<EncryptedCmk> {
let plaintext = unencrypted_cmk.as_bytes();
let mut ciphertext = [0u8; UNENCRYPTED_CMK_SIZE_BYTES];
// Encrypt the CMK using the KEK
let (iv, gcm_tag) = aes.aes_256_gcm_encrypt(
trng,
AesGcmIv::Array(&kek_iv),
AesKey::Split(&kek.0, &kek.1),
&[],
plaintext,
&mut ciphertext[..],
16,
)?;
Ok(EncryptedCmk {
domain: 0,
domain_metadata: [0u8; 16],
iv,
ciphertext,
gcm_tag,
})
}
/// Decrypt the Cryptographic Mailbox Key (CMK) using the Key Encryption Key (KEK)
///
/// # Arguments
/// * `aes` - AES driver
/// * `trng` - TRNG driver
/// * `kek` - Key Encryption Key (AES key)
/// * `encrypted_cmk` - Encrypted CMK to decrypt
///
/// # Returns
/// * `UnencryptedCmk` - Decrypted CMK
///
#[inline(always)]
pub fn decrypt_cmk(
aes: &mut Aes,
trng: &mut Trng,
kek: (LEArray4x8, LEArray4x8),
encrypted_cmk: &EncryptedCmk,
) -> CaliptraResult<UnencryptedCmk> {
let ciphertext = &encrypted_cmk.ciphertext;
let mut plaintext = [0u8; UNENCRYPTED_CMK_SIZE_BYTES];
aes.aes_256_gcm_decrypt(
trng,
&encrypted_cmk.iv,
AesKey::Split(&kek.0, &kek.1),
&[],
ciphertext,
&mut plaintext,
&encrypted_cmk.gcm_tag,
)?;
UnencryptedCmk::read_from_bytes(&plaintext)
.map_err(|_| CaliptraError::CMB_HMAC_INVALID_DEC_CMK)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/error_handler.rs | common/src/error_handler.rs | // Licensed under the Apache-2.0 license
use caliptra_drivers::{
cprintln, report_fw_error_fatal, report_fw_error_non_fatal, Aes, Ecc384, Hmac, KeyVault,
Mailbox, MlKem1024, Mldsa87, Sha256, Sha2_512_384, Sha2_512_384Acc, Sha3, SocIfc,
};
#[allow(clippy::empty_loop)]
pub fn handle_fatal_error(code: u32) -> ! {
cprintln!("Fatal Error: 0x{:08X}", code);
report_fw_error_fatal(code);
// Populate the non-fatal error code too; if there was a
// non-fatal error stored here before we don't want somebody
// mistakenly thinking that was the reason for their mailbox
// command failure.
report_fw_error_non_fatal(code);
unsafe {
// Zeroize the crypto blocks.
Aes::zeroize();
Ecc384::zeroize();
Hmac::zeroize();
Mldsa87::zeroize_no_wait();
MlKem1024::zeroize_no_wait();
Sha256::zeroize();
Sha2_512_384::zeroize();
Sha2_512_384Acc::zeroize();
Sha3::zeroize();
// Zeroize the key vault.
KeyVault::zeroize();
// Lock the SHA Accelerator.
Sha2_512_384Acc::lock();
// Stop the watchdog timer.
// Note: This is an idempotent operation.
SocIfc::stop_wdt1();
}
loop {
// SoC firmware might be stuck waiting for Caliptra to finish
// executing this pending mailbox transaction. Notify them that
// we've failed.
unsafe { Mailbox::abort_pending_soc_to_uc_transactions() };
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/boot_status.rs | common/src/boot_status.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
boot_status.rs
Abstract:
ROM boot status codes.
--*/
const IDEVID_BOOT_STATUS_BASE: u32 = 1;
const LDEVID_BOOT_STATUS_BASE: u32 = 65;
const FWPROCESSOR_BOOT_STATUS_BASE: u32 = 129;
const FMCALIAS_BOOT_STATUS_BASE: u32 = 193;
const COLD_RESET_BOOT_STATUS_BASE: u32 = 257;
const UPDATE_RESET_BOOT_STATUS_BASE: u32 = 321;
const ROM_GLOBAL_BOOT_STATUS_BASE: u32 = 385;
/// Statuses used by ROM to log dice derivation progress.
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RomBootStatus {
// Idevid Statuses
IDevIdDecryptUdsComplete = IDEVID_BOOT_STATUS_BASE,
IDevIdDecryptFeComplete = IDEVID_BOOT_STATUS_BASE + 1,
IDevIdClearDoeSecretsComplete = IDEVID_BOOT_STATUS_BASE + 2,
IDevIdCdiDerivationComplete = IDEVID_BOOT_STATUS_BASE + 3,
IDevIdKeyPairDerivationComplete = IDEVID_BOOT_STATUS_BASE + 4,
IDevIdSubjIdSnGenerationComplete = IDEVID_BOOT_STATUS_BASE + 5,
IDevIdSubjKeyIdGenerationComplete = IDEVID_BOOT_STATUS_BASE + 6,
IDevIdMakeCsrEnvelopeComplete = IDEVID_BOOT_STATUS_BASE + 7,
IDevIdSendCsrEnvelopeComplete = IDEVID_BOOT_STATUS_BASE + 8,
IDevIdDerivationComplete = IDEVID_BOOT_STATUS_BASE + 9,
// Ldevid Statuses
LDevIdCdiDerivationComplete = LDEVID_BOOT_STATUS_BASE,
LDevIdKeyPairDerivationComplete = LDEVID_BOOT_STATUS_BASE + 1,
LDevIdSubjIdSnGenerationComplete = LDEVID_BOOT_STATUS_BASE + 2,
LDevIdSubjKeyIdGenerationComplete = LDEVID_BOOT_STATUS_BASE + 3,
LDevIdCertSigGenerationComplete = LDEVID_BOOT_STATUS_BASE + 4,
LDevIdDerivationComplete = LDEVID_BOOT_STATUS_BASE + 5,
// Firmware Processor Statuses
FwProcessorDownloadImageComplete = FWPROCESSOR_BOOT_STATUS_BASE,
FwProcessorManifestLoadComplete = FWPROCESSOR_BOOT_STATUS_BASE + 1,
FwProcessorImageVerificationComplete = FWPROCESSOR_BOOT_STATUS_BASE + 2,
FwProcessorPopulateDataVaultComplete = FWPROCESSOR_BOOT_STATUS_BASE + 3,
FwProcessorExtendPcrComplete = FWPROCESSOR_BOOT_STATUS_BASE + 4,
FwProcessorLoadImageComplete = FWPROCESSOR_BOOT_STATUS_BASE + 5,
FwProcessorFirmwareDownloadTxComplete = FWPROCESSOR_BOOT_STATUS_BASE + 6,
FwProcessorCalculateKeyLadderComplete = FWPROCESSOR_BOOT_STATUS_BASE + 7,
FwProcessorComplete = FWPROCESSOR_BOOT_STATUS_BASE + 8,
// FmcAlias Statuses
FmcAliasDeriveCdiComplete = FMCALIAS_BOOT_STATUS_BASE,
FmcAliasKeyPairDerivationComplete = FMCALIAS_BOOT_STATUS_BASE + 1,
FmcAliasSubjIdSnGenerationComplete = FMCALIAS_BOOT_STATUS_BASE + 2,
FmcAliasSubjKeyIdGenerationComplete = FMCALIAS_BOOT_STATUS_BASE + 3,
FmcAliasCertSigGenerationComplete = FMCALIAS_BOOT_STATUS_BASE + 4,
FmcAliasDerivationComplete = FMCALIAS_BOOT_STATUS_BASE + 5,
// Cold Reset Statuses
ColdResetStarted = COLD_RESET_BOOT_STATUS_BASE,
ColdResetComplete = UPDATE_RESET_BOOT_STATUS_BASE - 1,
// Update Reset Statuses
UpdateResetStarted = UPDATE_RESET_BOOT_STATUS_BASE,
UpdateResetLoadManifestComplete = UPDATE_RESET_BOOT_STATUS_BASE + 1,
UpdateResetImageVerificationComplete = UPDATE_RESET_BOOT_STATUS_BASE + 2,
UpdateResetPopulateDataVaultComplete = UPDATE_RESET_BOOT_STATUS_BASE + 3,
UpdateResetExtendKeyLadderComplete = UPDATE_RESET_BOOT_STATUS_BASE + 4,
UpdateResetExtendPcrComplete = UPDATE_RESET_BOOT_STATUS_BASE + 5,
UpdateResetLoadImageComplete = UPDATE_RESET_BOOT_STATUS_BASE + 6,
UpdateResetOverwriteManifestComplete = UPDATE_RESET_BOOT_STATUS_BASE + 7,
UpdateResetComplete = UPDATE_RESET_BOOT_STATUS_BASE + 8,
// ROM Global Boot Statues
CfiInitialized = ROM_GLOBAL_BOOT_STATUS_BASE,
KatStarted = ROM_GLOBAL_BOOT_STATUS_BASE + 1,
KatComplete = ROM_GLOBAL_BOOT_STATUS_BASE + 2,
}
impl From<RomBootStatus> for u32 {
/// Converts to this type from the input type.
fn from(status: RomBootStatus) -> u32 {
status as u32
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/x509.rs | common/src/x509.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
x509.rs
Abstract:
File contains X509 Certificate & CSR related utility functions
--*/
use caliptra_drivers::*;
use core::mem::size_of;
use zerocopy::IntoBytes;
use crate::crypto::PubKey;
/// Get device serial number
///
/// # Arguments
///
/// * `soc_ifc` - SOC Interface object
///
/// # Returns
///
/// `[u8; 17]` - Byte 0 - Ueid Type, Bytes 1-16 Unique Endpoint Identifier
pub fn ueid(soc_ifc: &SocIfc) -> CaliptraResult<[u8; 17]> {
let ueid = soc_ifc.fuse_bank().ueid();
Ok(ueid)
}
/// Get public key bytes. Reverses the endianness of each dword in the public key.
///
/// # Arguments
///
/// * `pub_key` - ECC or MLDSA Public Key
/// * `pub_key_bytes` - Buffer to hold the public key bytes
///
/// # Returns
///
/// `usize` - Number of bytes written to the buffer
#[inline(always)]
#[allow(clippy::cast_ptr_alignment)]
pub fn get_pubkey_bytes(pub_key: &PubKey, pub_key_bytes: &mut [u8]) -> usize {
match pub_key {
PubKey::Ecc(pub_key) => {
let ecc_pubkey_der = pub_key.to_der();
pub_key_bytes[..ecc_pubkey_der.len()].copy_from_slice(&ecc_pubkey_der);
ecc_pubkey_der.len()
}
PubKey::Mldsa(pub_key) => {
let mldsa_pubkey: &[u8; 2592] = &(*pub_key).into();
pub_key_bytes.copy_from_slice(mldsa_pubkey);
pub_key_bytes.len()
}
}
}
fn pub_key_digest(sha256: &mut Sha256, pub_key: &PubKey) -> CaliptraResult<Array4x8> {
// Define an array large enough to hold the largest public key.
let mut pub_key_bytes: [u8; size_of::<Mldsa87PubKey>()] = [0; size_of::<Mldsa87PubKey>()];
let pub_key_size = get_pubkey_bytes(pub_key, &mut pub_key_bytes);
sha256.digest(&pub_key_bytes[..pub_key_size])
}
/// Get X509 Subject Serial Number from public key
///
/// # Arguments
///
/// * `sha256` - SHA256 Driver
/// * `pub_key` - ECC or MLDSA Public Key
///
/// # Returns
///
/// `[u8; 64]` - X509 Subject Identifier serial number
pub fn subj_sn(sha256: &mut Sha256, pub_key: &PubKey) -> CaliptraResult<[u8; 64]> {
let digest = pub_key_digest(sha256, pub_key);
let digest = okref(&digest)?;
Ok(hex(&digest.into()))
}
/// Get Cert Subject Key Identifier
///
/// # Arguments
///
/// * `sha256` - SHA256 Driver
/// * `pub_key` - Public Key
///
/// # Returns
///
/// `[u8; 20]` - X509 Subject Key Identifier
pub fn subj_key_id(sha256: &mut Sha256, pub_key: &PubKey) -> CaliptraResult<[u8; 20]> {
let digest = pub_key_digest(sha256, pub_key);
let digest: [u8; 32] = okref(&digest)?.into();
Ok(digest[..20].try_into().unwrap())
}
/// Get Serial Number for ECC certificate.
///
/// # Arguments
///
/// * `sha256` - SHA256 Driver
/// * `pub_key` - ECC Public Key
///
/// # Returns
///
/// `[u8; 20]` - X509 Serial Number
pub fn ecc_cert_sn(sha256: &mut Sha256, pub_key: &Ecc384PubKey) -> CaliptraResult<[u8; 20]> {
let data = pub_key.to_der();
let digest = sha256.digest(&data);
let mut digest: [u8; 32] = okref(&digest)?.into();
// Ensure the encoded integer is positive, and that the first octet
// is non-zero (otherwise it will be considered padding, and the integer
// will fail to parse if the MSB of the second octet is zero).
digest[0] &= !0x80;
digest[0] |= 0x04;
Ok(digest[..20].try_into().unwrap())
}
/// Get Serial Number for Mldsa certificate.
///
/// # Arguments
///
/// * `sha256` - SHA256 Driver
/// * `pub_key` - MLDSA Public Key
///
/// # Returns
///
/// `[u8; 20]` - X509 Serial Number
pub fn mldsa_cert_sn(sha256: &mut Sha256, pub_key: &Mldsa87PubKey) -> CaliptraResult<[u8; 20]> {
let digest = sha256.digest(pub_key.as_bytes());
let mut digest: [u8; 32] = okref(&digest)?.into();
// Ensure the encoded integer is positive, and that the first octet
// is non-zero (otherwise it will be considered padding, and the integer
// will fail to parse if the MSB of the second octet is zero).
digest[0] &= !0x80;
digest[0] |= 0x04;
Ok(digest[..20].try_into().unwrap())
}
/// Retrieve the TBS from DER encoded vector
///
/// Note: Rust OpenSSL binding is missing the extensions to retrieve TBS portion of the X509
/// artifact
#[cfg(feature = "std")]
pub fn get_tbs(der: Vec<u8>) -> Vec<u8> {
if der[0] != 0x30 {
panic!("Invalid DER start tag");
}
let der_len_offset = 1;
let tbs_offset = match der[der_len_offset] {
0..=0x7F => der_len_offset + 1,
0x81 => der_len_offset + 2,
0x82 => der_len_offset + 3,
_ => panic!("Unsupported DER Length"),
};
if der[tbs_offset] != 0x30 {
panic!("Invalid TBS start tag");
}
let tbs_len_offset = tbs_offset + 1;
let tbs_len = match der[tbs_len_offset] {
0..=0x7F => der[tbs_len_offset] as usize + 2,
0x81 => (der[tbs_len_offset + 1]) as usize + 3,
0x82 => {
(((der[tbs_len_offset + 1]) as usize) << u8::BITS)
| (((der[tbs_len_offset + 2]) as usize) + 4)
}
_ => panic!("Invalid DER Length"),
};
der[tbs_offset..tbs_offset + tbs_len].to_vec()
}
/// Return the hex representation of the input `buf`
///
/// # Arguments
///
/// `buf` - Buffer
///
/// # Returns
///
/// `[u8; 64]` - Hex representation of the buffer
fn hex(buf: &[u8; 32]) -> [u8; 64] {
fn ch(byte: u8) -> u8 {
match byte & 0x0F {
b @ 0..=9 => 48 + b,
b @ 10..=15 => 55 + b,
_ => unreachable!(),
}
}
let mut hex = [0u8; 64];
for (index, byte) in buf.iter().enumerate() {
hex[index << 1] = ch((byte & 0xF0) >> 4);
hex[(index << 1) + 1] = ch(byte & 0x0F);
}
hex
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/verifier.rs | common/src/verifier.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
verifier.rs
Abstract:
Image Verification support routines.
--*/
use caliptra_drivers::*;
use caliptra_image_types::*;
use caliptra_image_verify::ImageVerificationEnv;
use core::ops::Range;
use dma::AesDmaMode;
use zerocopy::{FromBytes, IntoBytes};
use caliptra_drivers::memory_layout::ICCM_RANGE;
/// Image source for verification
pub enum ImageSource<'a, 'b> {
/// Image is in memory (accessible as a byte slice)
MboxMemory(&'b [u8]),
/// Image is in MCU SRAM (requires DMA access)
McuSram(&'a Dma),
/// Image is in ICCM/DCCM for FIPS self-test (manifest, FMC, and runtime in their loaded locations)
FipsTest {
manifest: &'b [u8],
fmc: &'b [u8],
runtime: &'b [u8],
},
}
/// ROM Verification Environemnt
pub struct FirmwareImageVerificationEnv<'a, 'b> {
pub sha256: &'a mut Sha256,
pub sha2_512_384: &'a mut Sha2_512_384,
pub sha2_512_384_acc: &'a mut Sha2_512_384Acc,
pub soc_ifc: &'a mut SocIfc,
pub ecc384: &'a mut Ecc384,
pub mldsa87: &'a mut Mldsa87,
pub data_vault: &'a DataVault,
pub pcr_bank: &'a mut PcrBank,
pub image_source: ImageSource<'a, 'b>,
pub persistent_data: &'a PersistentData,
}
impl FirmwareImageVerificationEnv<'_, '_> {
fn create_dma_recovery<'a>(soc_ifc: &'a SocIfc, dma: &'a Dma) -> DmaRecovery<'a> {
DmaRecovery::new(
soc_ifc.recovery_interface_base_addr().into(),
soc_ifc.caliptra_base_axi_addr().into(),
soc_ifc.mci_base_addr().into(),
dma,
)
}
/// Helper to read from composite FipsTest image without copying
fn read_fips_test_slice<'a>(
manifest: &'a [u8],
fmc: &'a [u8],
runtime: &'a [u8],
offset: usize,
len: usize,
) -> CaliptraResult<&'a [u8]> {
let manifest_len = manifest.len();
let fmc_len = fmc.len();
let total_len = manifest_len + fmc_len + runtime.len();
if offset >= total_len || offset + len > total_len {
return Err(CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS);
}
// Determine which image(s) the requested range spans
if offset + len <= manifest_len {
// Entirely in manifest
manifest
.get(offset..offset + len)
.ok_or(CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS)
} else if offset >= manifest_len && offset + len <= manifest_len + fmc_len {
// Entirely in FMC
let fmc_offset = offset - manifest_len;
fmc.get(fmc_offset..fmc_offset + len)
.ok_or(CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS)
} else if offset >= manifest_len + fmc_len {
// Entirely in runtime
let rt_offset = offset - manifest_len - fmc_len;
runtime
.get(rt_offset..rt_offset + len)
.ok_or(CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS)
} else {
// Spans multiple images - not supported for zero-copy
Err(CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS)
}
}
}
impl ImageVerificationEnv for &mut FirmwareImageVerificationEnv<'_, '_> {
/// Calculate 384 digest using SHA2 Engine
fn sha384_digest(&mut self, offset: u32, len: u32) -> CaliptraResult<ImageDigest384> {
let err = CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS;
match &self.image_source {
ImageSource::McuSram(dma) => {
let dma_recovery =
FirmwareImageVerificationEnv::create_dma_recovery(self.soc_ifc, dma);
let result = dma_recovery.sha384_mcu_sram(
self.sha2_512_384_acc,
offset,
len,
dma::AesDmaMode::None,
)?;
Ok(result.into())
}
ImageSource::MboxMemory(image) => {
let data = image
.get(offset as usize..)
.ok_or(err)?
.get(..len as usize)
.ok_or(err)?;
let result = self.sha2_512_384.sha384_digest(data)?.0;
Ok(result)
}
ImageSource::FipsTest {
manifest,
fmc,
runtime,
} => {
// For FipsTest, the data must be within a single component for non-accelerator digest.
// Multi-component spans are not supported here - use sha384_acc_digest instead.
let data = FirmwareImageVerificationEnv::read_fips_test_slice(
manifest,
fmc,
runtime,
offset as usize,
len as usize,
)
.map_err(|_| CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS)?;
let result = self.sha2_512_384.sha384_digest(data)?.0;
Ok(result)
}
}
}
/// Calculate 512 digest using SHA2 Engine
fn sha512_digest(&mut self, offset: u32, len: u32) -> CaliptraResult<ImageDigest512> {
let err = CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS;
match &self.image_source {
ImageSource::McuSram(dma) => {
let dma_recovery =
FirmwareImageVerificationEnv::create_dma_recovery(self.soc_ifc, dma);
let result = dma_recovery.sha512_mcu_sram(
self.sha2_512_384_acc,
offset,
len,
AesDmaMode::None,
)?;
Ok(result.into())
}
ImageSource::MboxMemory(image) => {
let data = image
.get(offset as usize..)
.ok_or(err)?
.get(..len as usize)
.ok_or(err)?;
Ok(self.sha2_512_384.sha512_digest(data)?.0)
}
ImageSource::FipsTest {
manifest,
fmc,
runtime,
} => {
// For FipsTest, the data must be within a single component for non-accelerator digest.
// Multi-component spans are not supported here - use sha512_acc_digest instead.
let data = FirmwareImageVerificationEnv::read_fips_test_slice(
manifest,
fmc,
runtime,
offset as usize,
len as usize,
)
.map_err(|_| CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS)?;
Ok(self.sha2_512_384.sha512_digest(data)?.0)
}
}
}
fn sha384_acc_digest(
&mut self,
offset: u32,
len: u32,
digest_failure: CaliptraError,
) -> CaliptraResult<ImageDigest384> {
match &self.image_source {
ImageSource::McuSram(_) => {
// For MCU case, use the existing sha384_digest function
self.sha384_digest(offset, len).map_err(|_| digest_failure)
}
ImageSource::MboxMemory(_) => {
let mut digest = Array4x12::default();
if let Some(mut sha_acc_op) = self
.sha2_512_384_acc
.try_start_operation(ShaAccLockState::NotAcquired)?
{
sha_acc_op
.digest_384(len, offset, StreamEndianness::Reorder, &mut digest)
.map_err(|_| digest_failure)?;
} else {
Err(CaliptraError::DRIVER_SHA2_512_384_ACC_DIGEST_START_OP_FAILURE)?;
};
Ok(digest.0)
}
ImageSource::FipsTest {
manifest,
fmc,
runtime,
} => {
// For FIPS test, the data must be within a single component.
// Multi-component spans are not supported.
let data = FirmwareImageVerificationEnv::read_fips_test_slice(
manifest,
fmc,
runtime,
offset as usize,
len as usize,
)
.map_err(|_| digest_failure)?;
let mut digest = Array4x12::default();
if let Some(mut sha_acc_op) = self
.sha2_512_384_acc
.try_start_operation(ShaAccLockState::NotAcquired)?
{
sha_acc_op
.digest_384_slice(data, StreamEndianness::Reorder, &mut digest)
.map_err(|_| digest_failure)?;
} else {
Err(CaliptraError::DRIVER_SHA2_512_384_ACC_DIGEST_START_OP_FAILURE)?;
};
Ok(digest.0)
}
}
}
fn sha512_acc_digest(
&mut self,
offset: u32,
len: u32,
digest_failure: CaliptraError,
) -> CaliptraResult<ImageDigest512> {
match &self.image_source {
ImageSource::McuSram(_) => {
// For MCU case, use the existing sha512_digest function
self.sha512_digest(offset, len).map_err(|_| digest_failure)
}
ImageSource::MboxMemory(_) => {
let mut digest = Array4x16::default();
if let Some(mut sha_acc_op) = self
.sha2_512_384_acc
.try_start_operation(ShaAccLockState::NotAcquired)?
{
sha_acc_op
.digest_512(len, offset, StreamEndianness::Reorder, &mut digest)
.map_err(|_| digest_failure)?;
} else {
Err(CaliptraError::DRIVER_SHA2_512_384_ACC_DIGEST_START_OP_FAILURE)?;
};
Ok(digest.0)
}
ImageSource::FipsTest {
manifest,
fmc,
runtime,
} => {
// For FIPS test, the data must be within a single component.
// Multi-component spans are not supported.
let data = FirmwareImageVerificationEnv::read_fips_test_slice(
manifest,
fmc,
runtime,
offset as usize,
len as usize,
)
.map_err(|_| digest_failure)?;
let mut digest = Array4x16::default();
if let Some(mut sha_acc_op) = self
.sha2_512_384_acc
.try_start_operation(ShaAccLockState::NotAcquired)?
{
sha_acc_op
.digest_512_slice(data, StreamEndianness::Reorder, &mut digest)
.map_err(|_| digest_failure)?;
} else {
Err(CaliptraError::DRIVER_SHA2_512_384_ACC_DIGEST_START_OP_FAILURE)?;
};
Ok(digest.0)
}
}
}
/// ECC-384 Verification routine
fn ecc384_verify(
&mut self,
digest: &ImageDigest384,
pub_key: &ImageEccPubKey,
sig: &ImageEccSignature,
) -> CaliptraResult<Array4xN<12, 48>> {
let pub_key = Ecc384PubKey {
x: pub_key.x.into(),
y: pub_key.y.into(),
};
let digest: Array4x12 = digest.into();
let sig = Ecc384Signature {
r: sig.r.into(),
s: sig.s.into(),
};
self.ecc384.verify_r(&pub_key, &digest, &sig)
}
fn lms_verify(
&mut self,
digest: &ImageDigest384,
pub_key: &ImageLmsPublicKey,
sig: &ImageLmsSignature,
) -> CaliptraResult<HashValue<SHA192_DIGEST_WORD_SIZE>> {
let mut message = [0u8; SHA384_DIGEST_BYTE_SIZE];
for i in 0..digest.len() {
message[i * 4..][..4].copy_from_slice(&digest[i].to_be_bytes());
}
Lms::default().verify_lms_signature_cfi(self.sha256, &message, pub_key, sig)
}
fn mldsa87_verify(
&mut self,
msg: &[u8],
pub_key: &ImageMldsaPubKey,
sig: &ImageMldsaSignature,
) -> CaliptraResult<Mldsa87Result> {
// Public Key is received in hw format from the image. No conversion needed.
let pub_key_bytes: [u8; MLDSA87_PUB_KEY_BYTE_SIZE] = pub_key
.0
.as_bytes()
.try_into()
.map_err(|_| CaliptraError::IMAGE_VERIFIER_ERR_MLDSA_TYPE_CONVERSION_FAILED)?;
let pub_key = Mldsa87PubKey::read_from_bytes(pub_key_bytes.as_bytes()).or(Err(
CaliptraError::IMAGE_VERIFIER_ERR_MLDSA_TYPE_CONVERSION_FAILED,
))?;
// Signature is received in hw format from the image. No conversion needed.
let sig_bytes: [u8; MLDSA87_SIGNATURE_BYTE_SIZE] = sig
.0
.as_bytes()
.try_into()
.map_err(|_| CaliptraError::IMAGE_VERIFIER_ERR_MLDSA_TYPE_CONVERSION_FAILED)?;
let sig = Mldsa87Signature::read_from_bytes(sig_bytes.as_bytes()).or(Err(
CaliptraError::IMAGE_VERIFIER_ERR_MLDSA_TYPE_CONVERSION_FAILED,
))?;
self.mldsa87.verify_var(&pub_key, msg, &sig)
}
/// Retrieve Vendor Public Key Info Digest
fn vendor_pub_key_info_digest_fuses(&self) -> ImageDigest384 {
self.soc_ifc.fuse_bank().vendor_pub_key_info_hash().into()
}
/// Retrieve Vendor ECC Public Key Revocation Bitmask
fn vendor_ecc_pub_key_revocation(&self) -> VendorEccPubKeyRevocation {
self.soc_ifc.fuse_bank().vendor_ecc_pub_key_revocation()
}
/// Retrieve Vendor LMS Public Key Revocation Bitmask
fn vendor_lms_pub_key_revocation(&self) -> u32 {
self.soc_ifc.fuse_bank().vendor_lms_pub_key_revocation()
}
/// Retrieve Vendor MLDSA Public Key Revocation Bitmask
fn vendor_mldsa_pub_key_revocation(&self) -> u32 {
self.soc_ifc.fuse_bank().vendor_mldsa_pub_key_revocation()
}
/// Retrieve Owner Public Key Digest from fuses
fn owner_pub_key_digest_fuses(&self) -> ImageDigest384 {
self.soc_ifc.fuse_bank().owner_pub_key_hash().into()
}
/// Retrieve Anti-Rollback disable fuse value
fn anti_rollback_disable(&self) -> bool {
self.soc_ifc.fuse_bank().anti_rollback_disable()
}
/// Retrieve Device Lifecycle state
fn dev_lifecycle(&self) -> Lifecycle {
self.soc_ifc.lifecycle()
}
/// Get the vendor ECC key index saved in data vault on cold boot
fn vendor_ecc_pub_key_idx_dv(&self) -> u32 {
self.data_vault.vendor_ecc_pk_index()
}
/// Get the vendor PQC key index saved in data vault on cold boot
fn vendor_pqc_pub_key_idx_dv(&self) -> u32 {
self.data_vault.vendor_pqc_pk_index()
}
/// Get the owner public keys digest saved in the dv on cold boot
fn owner_pub_key_digest_dv(&self) -> ImageDigest384 {
self.data_vault.owner_pk_hash().into()
}
// Get the fmc digest from the data vault on cold boot
fn get_fmc_digest_dv(&self) -> ImageDigest384 {
self.data_vault.fmc_tci().into()
}
// Get firmware fuse SVN
fn fw_fuse_svn(&self) -> u32 {
self.soc_ifc.fuse_bank().fw_fuse_svn()
}
fn iccm_range(&self) -> Range<u32> {
ICCM_RANGE
}
fn set_fw_extended_error(&mut self, err: u32) {
self.soc_ifc.set_fw_extended_error(err);
}
fn pqc_key_type_fuse(&self) -> CaliptraResult<FwVerificationPqcKeyType> {
let pqc_key_type =
FwVerificationPqcKeyType::from_u8(self.soc_ifc.fuse_bank().pqc_key_type() as u8)
.ok_or(CaliptraError::IMAGE_VERIFIER_ERR_INVALID_PQC_KEY_TYPE_IN_FUSE)?;
Ok(pqc_key_type)
}
fn dot_owner_pk_hash(&self) -> Option<&ImageDigest384> {
if self.persistent_data.rom.dot_owner_pk_hash.valid {
Some(&self.persistent_data.rom.dot_owner_pk_hash.owner_pk_hash)
} else {
None
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/common/src/uds_fe_programming.rs | common/src/uds_fe_programming.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
uds_fe_programming.rs
Abstract:
File contains the implementation of UDS/FE programming flow that can be
used by both ROM and Runtime.
--*/
use crate::cprintln;
use caliptra_drivers::{AxiAddr, CaliptraError, CaliptraResult, Dma, DmaOtpCtrl, SocIfc, Trng};
/// UDS/FE Programming Flow
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UdsFeProgrammingFlow {
/// UDS (Unique Device Secret) programming mode - 64 bytes
Uds,
/// FE (Field Entropy) programming mode - 8 bytes per partition
/// Valid partition numbers: 0, 1, 2, 3 (4 total partitions)
Fe { partition: u32 },
}
const UDS_SEED_SIZE_BYTES: usize = 64;
const DIGEST_SIZE_BYTES: usize = 8;
const FE_PARTITION_SEED_SIZE_BYTES: usize = 8;
const ZEROIZATION_MARKER_SIZE_BYTES: usize = 8;
const FE_PARTITION_SIZE_BYTES: usize =
FE_PARTITION_SEED_SIZE_BYTES + DIGEST_SIZE_BYTES + ZEROIZATION_MARKER_SIZE_BYTES;
pub const FE_MAX_PARTITIONS: u32 = 4;
// OTP Direct Access Register Offsets (relative to DIRECT_ACCESS_CMD)
const DIRECT_ACCESS_ADDRESS_OFFSET: u64 = 0x4;
const DIRECT_ACCESS_WDATA_0_OFFSET: u64 = 0x8;
const DIRECT_ACCESS_WDATA_1_OFFSET: u64 = 0xC;
const DIRECT_ACCESS_RDATA_0_OFFSET: u64 = 0x10;
const DIRECT_ACCESS_RDATA_1_OFFSET: u64 = 0x14;
#[derive(Default)]
struct SeedConfig {
address: u32,
length_bytes: u32,
}
/// OTP Controller configuration for UDS/FE programming operations
#[derive(Default)]
struct OtpCtrlConfig {
uds_fuse_row_granularity_64: bool,
fuse_controller_base_addr: u64,
seed_config: SeedConfig,
dai_idle_bit_num: u32,
direct_access_cmd_reg_addr: u64,
direct_access_address_reg_addr: u64,
direct_access_wdata_0_reg_addr: u64,
direct_access_wdata_1_reg_addr: u64,
direct_access_rdata_0_reg_addr: u64,
direct_access_rdata_1_reg_addr: u64,
}
impl UdsFeProgrammingFlow {
/// Initialize OTP controller configuration from SoC interface
fn init_otp_config(&self, soc_ifc: &SocIfc) -> OtpCtrlConfig {
let uds_fuse_row_granularity_64 = soc_ifc.uds_fuse_row_granularity_64();
let fuse_controller_base_addr = soc_ifc.fuse_controller_base_addr();
let seed_config = self.get_seed_config(soc_ifc);
let dai_idle_bit_num = soc_ifc.otp_dai_idle_bit_num();
let direct_access_cmd_reg_addr =
fuse_controller_base_addr + soc_ifc.otp_direct_access_cmd_reg_offset() as u64;
let direct_access_address_reg_addr =
direct_access_cmd_reg_addr + DIRECT_ACCESS_ADDRESS_OFFSET;
let direct_access_wdata_0_reg_addr =
direct_access_cmd_reg_addr + DIRECT_ACCESS_WDATA_0_OFFSET;
let direct_access_wdata_1_reg_addr =
direct_access_cmd_reg_addr + DIRECT_ACCESS_WDATA_1_OFFSET;
let direct_access_rdata_0_reg_addr =
direct_access_cmd_reg_addr + DIRECT_ACCESS_RDATA_0_OFFSET;
let direct_access_rdata_1_reg_addr =
direct_access_cmd_reg_addr + DIRECT_ACCESS_RDATA_1_OFFSET;
OtpCtrlConfig {
uds_fuse_row_granularity_64,
fuse_controller_base_addr,
seed_config,
dai_idle_bit_num,
direct_access_cmd_reg_addr,
direct_access_address_reg_addr,
direct_access_wdata_0_reg_addr,
direct_access_wdata_1_reg_addr,
direct_access_rdata_0_reg_addr,
direct_access_rdata_1_reg_addr,
}
}
/// Validates the programming flow parameters
pub fn validate(self) -> CaliptraResult<()> {
match self {
UdsFeProgrammingFlow::Uds => Ok(()),
UdsFeProgrammingFlow::Fe { partition } => {
if partition >= FE_MAX_PARTITIONS {
Err(CaliptraError::RUNTIME_FE_PROG_INVALID_PARTITION)
} else {
Ok(())
}
}
}
}
/// Returns true if this is UDS programming mode
fn is_uds(self) -> bool {
matches!(self, UdsFeProgrammingFlow::Uds)
}
/// Returns the seed length in 32-bit words for this mode
fn seed_length_words(self) -> usize {
match self {
UdsFeProgrammingFlow::Uds => UDS_SEED_SIZE_BYTES / size_of::<u32>(), // 64 bytes = 16 u32 words
UdsFeProgrammingFlow::Fe { partition: _ } => {
FE_PARTITION_SEED_SIZE_BYTES / size_of::<u32>()
} // 8 bytes = 2 u32 words
}
}
/// Returns the prefix string for logging
fn prefix(self) -> &'static str {
match self {
UdsFeProgrammingFlow::Uds => "uds",
UdsFeProgrammingFlow::Fe { partition: _ } => "fe",
}
}
//
// OTP Controller Memory Map
//
// +-------------------------------------+ <- uds_seed_dest_base_addr_low()
// | UDS Region (64 bytes) |
// +-------------------------------------+
// | UDS Digest (8 bytes) |
// +-------------------------------------+
// | Zeroization Marker (8 bytes) |
// +-------------------------------------+
// +-------------------------------------+ <- FE Base = uds_seed_dest_base_addr_low() + UDS Region + UDS Digest + Zeroization Marker
// | FE Partition 0 (8 bytes) |
// +-------------------------------------+ <- FE Base + 8
// | FE Partition 0 Digest (8 bytes) |
// +-------------------------------------+ <- FE Base + 16
// | Zeroization Marker (8 bytes) |
// +-------------------------------------+
// +-------------------------------------+ <- FE Base + (1 * 24)
// | FE Partition 1 (8 bytes) |
// +-------------------------------------+ <- FE Base + (1 * 24) + 8
// | FE Partition 1 Digest (8 bytes) |
// +-------------------------------------+ <- FE Base + (1 * 24) + 16
// | Zeroization Marker (8 bytes) |
// +-------------------------------------+
// +-------------------------------------+ <- FE Base + (2 * 24)
// | FE Partition 2 (8 bytes) |
// +-------------------------------------+ <- FE Base + (2 * 24) + 8
// | FE Partition 2 Digest (8 bytes) |
// +-------------------------------------+ <- FE Base + (2 * 24) + 16
// | Zeroization Marker (8 bytes) |
// +-------------------------------------+
// +-------------------------------------+ <- FE Base + (3 * 24)
// | FE Partition 3 (8 bytes) |
// +-------------------------------------+ <- FE Base + (3 * 24) + 8
// | FE Partition 3 Digest (8 bytes) |
// +-------------------------------------+ <- FE Base + (3 * 24) + 16
// | Zeroization Marker (8 bytes) |
// +-------------------------------------+
fn get_seed_config(&self, soc_ifc: &SocIfc) -> SeedConfig {
let uds_seed_dest = soc_ifc.uds_seed_dest_base_addr_low();
match self {
Self::Uds => SeedConfig {
address: uds_seed_dest,
length_bytes: UDS_SEED_SIZE_BYTES as u32,
},
Self::Fe { partition } => SeedConfig {
address: uds_seed_dest
+ UDS_SEED_SIZE_BYTES as u32
+ DIGEST_SIZE_BYTES as u32
+ ZEROIZATION_MARKER_SIZE_BYTES as u32
+ (partition * FE_PARTITION_SIZE_BYTES as u32),
length_bytes: FE_PARTITION_SEED_SIZE_BYTES as u32,
},
}
}
/// Programs either UDS (64 bytes) or FE (32 bytes) based on the enum variant
///
/// # Arguments
/// * `soc_ifc` - SoC interface for accessing fuse controller and related registers
/// * `trng` - TRNG for generating random seeds
/// * `dma` - DMA engine for OTP control
pub fn program(&self, soc_ifc: &mut SocIfc, trng: &mut Trng, dma: &Dma) -> CaliptraResult<()> {
// Validate parameters first
self.validate()?;
cprintln!("[{}] ++", self.prefix());
if self.is_uds() {
// Update the programming state.
soc_ifc.set_uds_programming_flow_state(true);
}
let result = {
// Generate a 512-bit random value.
let seed: [u32; 16] = trng.generate16()?.into();
let config = self.init_otp_config(soc_ifc);
let otp_ctrl = DmaOtpCtrl::new(AxiAddr::from(config.fuse_controller_base_addr), dma);
let _ = otp_ctrl.with_regs_mut(|regs| {
// Helper function to check if DAI is idle using the configurable bit number
let is_dai_idle = || -> bool {
let status: u32 = regs.status().read().into();
(status & (1 << config.dai_idle_bit_num)) != 0
};
let seed = &seed[..self.seed_length_words()]; // Get random bytes of desired size
let chunk_size = if config.uds_fuse_row_granularity_64 {
2
} else {
1
};
let chunked_seed = seed.chunks(chunk_size);
for (index, seed_part) in chunked_seed.enumerate() {
let dest =
config.seed_config.address + (index * chunk_size * size_of::<u32>()) as u32;
// Poll the STATUS register until the DAI state returns to idle
while !is_dai_idle() {}
// Write seed data to WDATA registers using DMA
let wdata_0 = seed_part[0];
dma.write_dword(
AxiAddr::from(config.direct_access_wdata_0_reg_addr),
wdata_0,
);
if let Some(&wdata_1) = seed_part.get(1) {
dma.write_dword(
AxiAddr::from(config.direct_access_wdata_1_reg_addr),
wdata_1,
);
}
// Write the Seed destination address to the DIRECT_ACCESS_ADDRESS register
dma.write_dword(
AxiAddr::from(config.direct_access_address_reg_addr),
dest & 0xFFF,
);
// Trigger the seed write command
dma.write_dword(AxiAddr::from(config.direct_access_cmd_reg_addr), 0b10);
// bit 1 = 1 for WR
}
// Trigger the partition digest operation
// Poll the STATUS register until the DAI state returns to idle
while !is_dai_idle() {}
// Write the Seed base address to the DIRECT_ACCESS_ADDRESS register for digest operation.
dma.write_dword(
AxiAddr::from(config.direct_access_address_reg_addr),
config.seed_config.address & 0xFFF,
);
// Trigger the digest calculation command
dma.write_dword(AxiAddr::from(config.direct_access_cmd_reg_addr), 0b100); // bit 2 = 1 for DIGEST
// Poll the STATUS register until the DAI state returns to idle
while !is_dai_idle() {}
Ok::<(), CaliptraError>(())
})?;
Ok(())
};
if self.is_uds() {
// Set the programming result.
soc_ifc.set_uds_programming_flow_status(result.is_ok());
// Update the programming state.
soc_ifc.set_uds_programming_flow_state(false);
}
cprintln!(
"[{}] Programming flow completed with status: {}",
self.prefix(),
if result.is_ok() { "SUCCESS" } else { "FAILURE" }
);
cprintln!("[{}] --", self.prefix());
result
}
/// Zeroize either UDS (64 bytes) or an FE partition (8 bytes) based on the enum variant
///
/// # Arguments
/// * `soc_ifc` - SoC interface for accessing fuse controller and related registers
/// * `dma` - DMA engine for OTP control
pub fn zeroize(&self, soc_ifc: &mut SocIfc, dma: &Dma) -> CaliptraResult<()> {
let mut result: CaliptraResult<()> = Ok(());
// Validate parameters first
self.validate()?;
cprintln!("[{}] ++ Zeroization", self.prefix());
const DAI_CMD_ZEROIZE: u32 = 0b1000;
let config = self.init_otp_config(soc_ifc);
let otp_ctrl = DmaOtpCtrl::new(AxiAddr::from(config.fuse_controller_base_addr), dma);
let digest_address = config.seed_config.address + config.seed_config.length_bytes;
let zeroization_marker_address = digest_address + DIGEST_SIZE_BYTES as u32;
let granularity_step_bytes = if config.uds_fuse_row_granularity_64 {
8
} else {
4
};
let _ = otp_ctrl.with_regs_mut(|regs| {
// Helper to wait for DAI idle state
let wait_dai_idle = || loop {
let status: u32 = regs.status().read().into();
if (status & (1 << config.dai_idle_bit_num)) != 0 {
break;
}
};
// Helper to write address and execute DAI command
let execute_dai_cmd = |address: u32, cmd: u32| {
wait_dai_idle();
dma.write_dword(
AxiAddr::from(config.direct_access_address_reg_addr),
address & 0xFFF,
);
dma.write_dword(AxiAddr::from(config.direct_access_cmd_reg_addr), cmd);
wait_dai_idle();
};
// Helper to verify both rdata registers are 0xFFFFFFFF
let verify_cleared = |error: CaliptraError| -> CaliptraResult<()> {
let rdata_0 = dma.read_dword(AxiAddr::from(config.direct_access_rdata_0_reg_addr));
let rdata_1 = dma.read_dword(AxiAddr::from(config.direct_access_rdata_1_reg_addr));
if rdata_0 != 0xFFFFFFFF || rdata_1 != 0xFFFFFFFF {
Err(error)
} else {
Ok(())
}
};
// Step 1: Clear the Partition Zeroization Marker (64-bit)
// This step is critical - it masks potential ECC or integrity errors
// if the process is interrupted by a power failure
execute_dai_cmd(zeroization_marker_address, DAI_CMD_ZEROIZE);
verify_cleared(CaliptraError::UDS_FE_ZEROIZATION_MARKER_NOT_CLEARED)?;
// Step 2: Zeroize all data words in the partition
let start_addr = config.seed_config.address;
let end_addr = start_addr + config.seed_config.length_bytes;
for addr in (start_addr..end_addr).step_by(granularity_step_bytes) {
execute_dai_cmd(addr, DAI_CMD_ZEROIZE);
// Verify zeroization - should return 0xFFFFFFFF for all bits
let rdata_0 = dma.read_dword(AxiAddr::from(config.direct_access_rdata_0_reg_addr));
if rdata_0 != 0xFFFFFFFF {
result = Err(CaliptraError::UDS_FE_ZEROIZATION_SEED_NOT_CLEARED);
// Continue even if error to attempt full zeroization
}
if config.uds_fuse_row_granularity_64 {
let rdata_1 =
dma.read_dword(AxiAddr::from(config.direct_access_rdata_1_reg_addr));
if rdata_1 != 0xFFFFFFFF {
result = Err(CaliptraError::UDS_FE_ZEROIZATION_SEED_NOT_CLEARED);
// Continue even if error to attempt full zeroization
}
}
}
// Step 3: Clear the partition digest (always 64-bit)
execute_dai_cmd(digest_address, DAI_CMD_ZEROIZE);
verify_cleared(CaliptraError::UDS_FE_ZEROIZATION_DIGEST_NOT_CLEARED)?;
// Return the accumulated result
result
})?;
cprintln!("[{}] -- Zeroization completed", self.prefix());
Ok(())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/hkdf.rs | drivers/src/hkdf.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
hkdf.rs
Abstract:
An HKDF implementation that is compliant with RFC 5869 and NIST SP 800-56Cr2 Section 5 (Two-Step Derivation).
--*/
use crate::{Array4x12, Array4x16, Hmac, HmacKey, HmacMode, HmacTag, Trng};
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::cfi_mod_fn;
use caliptra_error::{CaliptraError, CaliptraResult};
/// Calculate HKDF-Extract.
///
/// # Arguments
///
/// * `hmac` - HMAC context
/// * `ikm` - the input keying material or shared secret, sometimes called Z
/// * `salt` - salt used to strengthen the extraction
/// * `trng` - TRNG driver instance
/// * `prk` - Location to store the output PRK
/// * `mode` - HMAC Mode
#[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)]
pub fn hkdf_extract(
hmac: &mut Hmac,
ikm: &[u8],
salt: &[u8],
trng: &mut Trng,
prk: HmacTag,
mode: HmacMode,
) -> CaliptraResult<()> {
#[cfg(feature = "fips-test-hooks")]
unsafe {
crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::HMAC384_FAILURE)?
}
// NIST SP 800-56Cr2 says that salts less than the block length (1024 bits) should be
// padded and larger than the block length should be hashed.
// However, the hardware only supports HMAC keys up to the HMAC length (384 or 512 bits),
// not the full block length.
match mode {
HmacMode::Hmac384 => {
if salt.len() > 48 {
Err(CaliptraError::DRIVER_HKDF_SALT_TOO_LONG)?;
}
let mut padded_salt = [0u8; 48];
padded_salt[..salt.len()].copy_from_slice(salt);
let padded_salt = Array4x12::from(padded_salt);
let mut hmac_op = hmac.hmac_init((&padded_salt).into(), trng, prk, mode)?;
hmac_op.update(ikm)?;
hmac_op.finalize()
}
HmacMode::Hmac512 => {
if salt.len() > 64 {
return Err(CaliptraError::DRIVER_HKDF_SALT_TOO_LONG);
}
let mut padded_salt = [0u8; 64];
padded_salt[..salt.len()].copy_from_slice(salt);
let padded_salt = Array4x16::from(padded_salt);
let mut hmac_op = hmac.hmac_init((&padded_salt).into(), trng, prk, mode)?;
hmac_op.update(ikm)?;
hmac_op.finalize()
}
}
}
/// Calculate HKDF-Expand.
///
/// # Arguments
///
/// * `hmac` - HMAC context
/// * `prk` - the pseudor random key material
/// * `label` - label used when expanding the key material. Sometimes called fixed info.
/// * `trng` - TRNG driver instance
/// * `okm` - Location to store the output key material
/// * `mode` - HMAC Mode
#[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)]
pub fn hkdf_expand(
hmac: &mut Hmac,
prk: HmacKey,
label: &[u8],
trng: &mut Trng,
okm: HmacTag,
mode: HmacMode,
) -> CaliptraResult<()> {
#[cfg(feature = "fips-test-hooks")]
unsafe {
crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::HMAC384_FAILURE)?
}
let mut hmac_op = hmac.hmac_init(prk, trng, okm, mode)?;
hmac_op.update(label)?;
hmac_op.update(&[0x01])?;
hmac_op.finalize()
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/exit_ctrl.rs | drivers/src/exit_ctrl.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
exit_ctrl.rs
Abstract:
File contains API for Caliptra Exit control
--*/
use caliptra_registers::soc_ifc::SocIfcReg;
use crate::Mailbox;
/// Exit control
pub enum ExitCtrl {}
impl ExitCtrl {
/// Exit the emulator
///
/// # Arguments
///
/// * `exit_code`: Code to exit the emulator process with
///
/// # Returns
///
/// This method does not return
pub fn exit(exit_code: u32) -> ! {
if cfg!(feature = "emu") {
let mut reg = unsafe { SocIfcReg::new() };
reg.regs_mut()
.cptra_generic_output_wires()
.at(0)
.write(|_| if exit_code == 0 { 0xff } else { 0x01 });
}
loop {
unsafe { Mailbox::abort_pending_soc_to_uc_transactions() };
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/hmac.rs | drivers/src/hmac.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
hmac.rs
Abstract:
File contains API for HMAC-384 and HMAC-512 Cryptography operations
--*/
use crate::kv_access::{KvAccess, KvAccessErr};
use crate::{
array::Array4x32, wait, Array4x12, Array4x16, CaliptraError, CaliptraResult, KeyReadArgs,
KeyWriteArgs, Trng,
};
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::cfi_impl_fn;
use caliptra_registers::hmac::HmacReg;
const HMAC_BLOCK_SIZE_BYTES: usize = 128;
const HMAC_BLOCK_LEN_OFFSET: usize = 112;
const HMAC_MAX_DATA_SIZE: usize = 1024 * 1024;
/// HMAC Data
#[derive(Debug, Copy, Clone)]
pub enum HmacData<'a> {
/// Slice
Slice(&'a [u8]),
/// Key
Key(KeyReadArgs),
}
impl<'a> From<&'a [u8]> for HmacData<'a> {
/// Converts to this type from the input type.
///
fn from(value: &'a [u8]) -> Self {
Self::Slice(value)
}
}
impl<'a, const N: usize> From<&'a [u8; N]> for HmacData<'a> {
/// Converts to this type from the input type.
fn from(value: &'a [u8; N]) -> Self {
Self::Slice(value)
}
}
impl From<KeyReadArgs> for HmacData<'_> {
/// Converts to this type from the input type.
fn from(value: KeyReadArgs) -> Self {
Self::Key(value)
}
}
/// Hmac Tag
#[derive(Debug)]
pub enum HmacTag<'a> {
/// Array - 48 Bytes
Array4x12(&'a mut Array4x12),
/// Array - 64 Bytes
Array4x16(&'a mut Array4x16),
/// Key output
Key(KeyWriteArgs),
}
impl<'a> From<&'a mut Array4x12> for HmacTag<'a> {
/// Converts to this type from the input type.
fn from(value: &'a mut Array4x12) -> Self {
Self::Array4x12(value)
}
}
impl<'a> From<&'a mut Array4x16> for HmacTag<'a> {
/// Converts to this type from the input type.
fn from(value: &'a mut Array4x16) -> Self {
Self::Array4x16(value)
}
}
impl From<KeyWriteArgs> for HmacTag<'_> {
/// Converts to this type from the input type.
fn from(value: KeyWriteArgs) -> Self {
Self::Key(value)
}
}
///
/// Hmac Key
///
#[derive(Debug, Copy, Clone)]
pub enum HmacKey<'a> {
/// Array - 48 Bytes
Array4x12(&'a Array4x12),
/// Array - 64 Bytes
Array4x16(&'a Array4x16),
// Key
Key(KeyReadArgs),
// CSR mode key
CsrMode(),
}
impl<'a> From<&'a Array4x12> for HmacKey<'a> {
///
/// Converts to this type from the input type.
///
fn from(value: &'a Array4x12) -> Self {
Self::Array4x12(value)
}
}
impl<'a> From<&'a Array4x16> for HmacKey<'a> {
///
/// Converts to this type from the input type.
///
fn from(value: &'a Array4x16) -> Self {
Self::Array4x16(value)
}
}
impl From<KeyReadArgs> for HmacKey<'_> {
/// Converts to this type from the input type.
fn from(value: KeyReadArgs) -> Self {
Self::Key(value)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum HmacMode {
Hmac384 = 0,
Hmac512 = 1,
}
struct HmacParams<'a> {
slice: &'a [u8],
first: bool,
buf_size: usize,
key: Option<KeyReadArgs>,
dest_key: Option<KeyWriteArgs>,
hmac_mode: HmacMode,
csr_mode: bool,
}
pub struct Hmac {
hmac: HmacReg,
}
impl Hmac {
pub fn new(hmac: HmacReg) -> Self {
Self { hmac }
}
/// Initialize multi step HMAC operation
///
/// # Arguments
///
/// * `key` - HMAC Key
/// * `trng` - TRNG driver instance
///
/// * `tag` - The calculated tag
/// * `hmac_mode` - Hmac mode to use
///
/// # Returns
/// * `HmacOp` - Hmac operation
pub fn hmac_init<'a>(
&'a mut self,
key: HmacKey,
trng: &mut Trng,
mut tag: HmacTag<'a>,
hmac_mode: HmacMode,
) -> CaliptraResult<HmacOp<'a>> {
let hmac = self.hmac.regs_mut();
let mut csr_mode = false;
// Configure the hardware so that the output tag is stored at a location specified by the
// caller.
if matches!(&mut tag, HmacTag::Array4x12(_) | HmacTag::Array4x16(_)) {
KvAccess::begin_copy_to_arr(hmac.hmac512_kv_wr_status(), hmac.hmac512_kv_wr_ctrl())?;
}
// Configure the hardware to use key to use for the HMAC operation
let key = match key {
HmacKey::Array4x12(arr) => {
KvAccess::copy_from_arr(arr, hmac.hmac512_key().truncate::<12>())?;
None
}
HmacKey::Array4x16(arr) => {
KvAccess::copy_from_arr(arr, hmac.hmac512_key())?;
None
}
HmacKey::Key(key) => Some(key),
HmacKey::CsrMode() => {
csr_mode = true;
None
}
};
// Generate an LFSR seed and copy to key vault.
self.gen_lfsr_seed(trng)?;
let op = HmacOp {
hmac_engine: self,
key,
state: HmacOpState::Init,
buf: [0u8; HMAC_BLOCK_SIZE_BYTES],
buf_idx: 0,
data_size: 0,
tag,
hmac_mode,
csr_mode,
};
Ok(op)
}
/// Generate an LFSR seed and copy to keyvault.
///
/// # Arguments
///
/// * `trng` - TRNG driver instance
fn gen_lfsr_seed(&mut self, trng: &mut Trng) -> CaliptraResult<()> {
let hmac = self.hmac.regs_mut();
let rand_data = trng.generate()?;
let iv: [u32; 12] = rand_data.0[..12].try_into().unwrap();
KvAccess::copy_from_arr(&Array4x12::from(iv), hmac.hmac512_lfsr_seed())?;
Ok(())
}
/// Calculate the hmac for specified data
///
/// # Arguments
///
/// * `key` - HMAC Key
/// * `data` - Data to calculate the HMAC over
/// * `trng` - TRNG driver instance
///
/// * `tag` - The calculated tag
/// * `hmac_mode` - Hmac mode to use
///
/// # Returns
/// * `CaliptraResult<()>` - Result of the operation
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn hmac(
&mut self,
key: HmacKey,
data: HmacData,
trng: &mut Trng,
tag: HmacTag,
hmac_mode: HmacMode,
) -> CaliptraResult<()> {
let hmac = self.hmac.regs_mut();
let mut tag = tag;
let mut csr_mode: bool = false;
// Configure the hardware so that the output tag is stored at a location specified by the
// caller.
let dest_key = match &mut tag {
HmacTag::Array4x12(_) | HmacTag::Array4x16(_) => {
KvAccess::begin_copy_to_arr(
hmac.hmac512_kv_wr_status(),
hmac.hmac512_kv_wr_ctrl(),
)?;
None
}
HmacTag::Key(dest_key) => Some(*dest_key),
};
// Configure the hardware to use key to use for the HMAC operation
let key = match key {
HmacKey::Array4x12(arr) => {
KvAccess::copy_from_arr(arr, hmac.hmac512_key().truncate::<12>())?;
None
}
HmacKey::Array4x16(arr) => {
KvAccess::copy_from_arr(arr, hmac.hmac512_key())?;
None
}
HmacKey::Key(key) => Some(key),
HmacKey::CsrMode() => {
csr_mode = true;
None
}
};
// Generate an LFSR seed and copy to key vault.
self.gen_lfsr_seed(trng)?;
// Calculate the hmac
match data {
HmacData::Slice(buf) => self.hmac_buf(buf, key, dest_key, hmac_mode, csr_mode)?,
HmacData::Key(data_key) => self.hmac_key(data_key, key, dest_key, hmac_mode)?,
}
let hmac = self.hmac.regs();
// Copy the tag to the specified location
let result = match &mut tag {
HmacTag::Array4x12(arr) => {
KvAccess::end_copy_to_arr(hmac.hmac512_tag().truncate::<12>(), arr)
}
HmacTag::Array4x16(arr) => KvAccess::end_copy_to_arr(hmac.hmac512_tag(), arr),
_ => Ok(()),
};
self.zeroize_internal();
result
}
/// Zeroize the hardware registers.
fn zeroize_internal(&mut self) {
Self::zeroize_regs(&mut self.hmac);
}
/// Helper function to zeroize the hardware registers.
fn zeroize_regs(hmac: &mut HmacReg) {
hmac.regs_mut()
.hmac512_ctrl()
.write(|w| w.zeroize(true).mode(false).csr_mode(false));
}
/// Zeroize the hardware registers.
///
/// This is useful to call from a fatal-error-handling routine.
///
/// # Safety
///
/// The caller must be certain that the results of any pending cryptographic
/// operations will not be used after this function is called.
///
/// This function is safe to call from a trap handler.
pub unsafe fn zeroize() {
let mut hmac = HmacReg::new();
Self::zeroize_regs(&mut hmac);
}
///
/// Calculate the hmac of the buffer provided as parameter
///
/// # Arguments
///
/// * `buf` - Buffer to calculate the hmac over
/// * `key` - Key to use for the hmac operation
/// * `dest_key` - Destination key to store the hmac tag
/// * `hmac_mode` - Hmac mode to use
/// * `csr_mode` - Flag indicating if the hmac operation is in CSR mode
///
/// # Returns
/// * `CaliptraResult<()>` - Result of the operation
fn hmac_buf(
&mut self,
buf: &[u8],
key: Option<KeyReadArgs>,
dest_key: Option<KeyWriteArgs>,
hmac_mode: HmacMode,
csr_mode: bool,
) -> CaliptraResult<()> {
// Check if the buffer is within the size that we support
if buf.len() > HMAC_MAX_DATA_SIZE {
return Err(CaliptraError::DRIVER_HMAC_MAX_DATA);
}
let mut first = true;
let mut bytes_remaining = buf.len();
loop {
let offset = buf.len() - bytes_remaining;
match bytes_remaining {
0..=127 => {
// PANIC-FREE: Use buf.get() instead if buf[] as the compiler
// cannot reason about `offset` parameter to optimize out
// the panic.
if let Some(slice) = buf.get(offset..) {
let params = HmacParams {
slice,
first,
buf_size: buf.len(),
key,
dest_key,
hmac_mode,
csr_mode,
};
self.hmac_partial_block(params)?;
break;
} else {
return Err(CaliptraError::DRIVER_HMAC_INVALID_SLICE);
}
}
_ => {
// PANIC-FREE: Use buf.get() instead of buf[] as the compiler
// cannot reason about `offset` parameter to optimize out
// the panic.
if let Some(slice) = buf.get(offset..offset + HMAC_BLOCK_SIZE_BYTES) {
let block = <&[u8; HMAC_BLOCK_SIZE_BYTES]>::try_from(slice).unwrap();
self.hmac_block(block, first, key, dest_key, hmac_mode, csr_mode)?;
bytes_remaining -= HMAC_BLOCK_SIZE_BYTES;
first = false;
} else {
return Err(CaliptraError::DRIVER_HMAC_INVALID_SLICE);
}
}
}
}
Ok(())
}
///
/// Calculate hmac of a key in the Key Vault
///
/// # Arguments
///
/// * `key` - Key to calculate hmac for
/// * `dest_key` - Key vault slot to store the the hmac tag
/// * `hmac_mode` - Hmac mode to use
///
fn hmac_key(
&mut self,
data_key: KeyReadArgs,
key: Option<KeyReadArgs>,
dest_key: Option<KeyWriteArgs>,
hmac_mode: HmacMode,
) -> CaliptraResult<()> {
let hmac = self.hmac.regs_mut();
KvAccess::copy_from_kv(
data_key,
hmac.hmac512_kv_rd_block_status(),
hmac.hmac512_kv_rd_block_ctrl(),
)
.map_err(|err| err.into_read_data_err())?;
self.hmac_op(true, key, dest_key, hmac_mode, false)
}
fn hmac_partial_block(&mut self, params: HmacParams) -> CaliptraResult<()> {
/// Set block length
fn set_block_len(buf_size: usize, block: &mut [u8; HMAC_BLOCK_SIZE_BYTES]) {
let bit_len = ((buf_size + HMAC_BLOCK_SIZE_BYTES) as u128) << 3;
block[HMAC_BLOCK_LEN_OFFSET..].copy_from_slice(&bit_len.to_be_bytes());
}
let slice = params.slice;
// Construct the block
let mut block = [0u8; HMAC_BLOCK_SIZE_BYTES];
// PANIC-FREE: Following check optimizes the out of bounds
// panic in copy_from_slice
if slice.len() > block.len() - 1 {
return Err(CaliptraError::DRIVER_HMAC_INDEX_OUT_OF_BOUNDS);
}
block[..slice.len()].copy_from_slice(slice);
block[slice.len()] = 0b1000_0000;
if slice.len() < HMAC_BLOCK_LEN_OFFSET {
set_block_len(params.buf_size, &mut block);
}
// Calculate the digest of the op
self.hmac_block(
&block,
params.first,
params.key,
params.dest_key,
params.hmac_mode,
params.csr_mode,
)?;
// Add a padding block if one is needed
if slice.len() >= HMAC_BLOCK_LEN_OFFSET {
block.fill(0);
set_block_len(params.buf_size, &mut block);
self.hmac_block(
&block,
false,
params.key,
params.dest_key,
params.hmac_mode,
params.csr_mode,
)?;
}
Ok(())
}
///
/// Calculate digest of the full block
///
/// # Arguments
///
/// * `block`: Block to calculate the digest
/// * `first` - Flag indicating if this is the first block
/// * `key` - Key vault slot to use for the hmac key
/// * `dest_key` - Destination key vault slot to store the hmac tag
/// * `hmac_mode` - Hmac mode to use
/// * `csr_mode` - Flag indicating if the hmac operation is in CSR mode
///
/// # Returns
/// * `CaliptraResult<()>` - Result of the operation
fn hmac_block(
&mut self,
block: &[u8; HMAC_BLOCK_SIZE_BYTES],
first: bool,
key: Option<KeyReadArgs>,
dest_key: Option<KeyWriteArgs>,
hmac_mode: HmacMode,
csr_mode: bool,
) -> CaliptraResult<()> {
let hmac = self.hmac.regs_mut();
Array4x32::from(block).write_to_reg(hmac.hmac512_block());
self.hmac_op(first, key, dest_key, hmac_mode, csr_mode)
}
///
/// Perform the hmac operation in the hardware
///
/// # Arguments
///
/// * `first` - Flag indicating if this is the first block
/// * `key` - Key vault slot to use for the hmac key
/// * `dest_key` - Destination key vault slot to store the hmac tag
/// * `hmac_mode` - Hmac mode to use
/// * `csr_mode` - Flag indicating if the hmac operation is in CSR mode
///
/// # Returns
/// * `CaliptraResult<()>` - Result of the operation
fn hmac_op(
&mut self,
first: bool,
key: Option<KeyReadArgs>,
dest_key: Option<KeyWriteArgs>,
hmac_mode: HmacMode,
csr_mode: bool,
) -> CaliptraResult<()> {
let hmac = self.hmac.regs_mut();
if let Some(key) = key {
KvAccess::copy_from_kv(
key,
hmac.hmac512_kv_rd_key_status(),
hmac.hmac512_kv_rd_key_ctrl(),
)
.map_err(|err| err.into_read_key_err())?
};
if let Some(dest_key) = dest_key {
KvAccess::begin_copy_to_kv(
hmac.hmac512_kv_wr_status(),
hmac.hmac512_kv_wr_ctrl(),
dest_key,
)?;
}
// Wait for the hardware to be ready
wait::until(|| hmac.hmac512_status().read().ready());
if first {
// Submit the first block
hmac.hmac512_ctrl().write(|w| {
w.init(true)
.next(false)
.mode(hmac_mode == HmacMode::Hmac512)
.csr_mode(csr_mode)
});
} else {
// Submit next block in existing hashing chain
hmac.hmac512_ctrl().write(|w| {
w.init(false)
.next(true)
.mode(hmac_mode == HmacMode::Hmac512)
.csr_mode(csr_mode)
});
}
// Wait for the hmac operation to finish
wait::until(|| {
hmac.hmac512_status().read().valid() || hmac.hmac512_status().read().ready()
});
// check for a hardware error
if !hmac.hmac512_status().read().valid() {
return Err(CaliptraError::DRIVER_HMAC_INVALID_STATE);
}
if let Some(dest_key) = dest_key {
KvAccess::end_copy_to_kv(hmac.hmac512_kv_wr_status(), dest_key)
.map_err(|err| err.into_write_tag_err())?;
}
Ok(())
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum HmacOpState {
/// Initial state
Init,
/// Pending state
Pending,
/// Final state
Final,
}
/// HMAC multi step operation
pub struct HmacOp<'a> {
/// Hmac Engine
hmac_engine: &'a mut Hmac,
/// State
state: HmacOpState,
// The keyvault key used to compute the hmac
key: Option<KeyReadArgs>,
/// Staging buffer
buf: [u8; HMAC_BLOCK_SIZE_BYTES],
/// Current staging buffer index
buf_idx: usize,
/// Data size
data_size: usize,
/// Tag
tag: HmacTag<'a>,
/// Hmac Mode
hmac_mode: HmacMode,
/// Indicates if CSR mode is requested
csr_mode: bool,
}
impl HmacOp<'_> {
///
/// Update the digest with data
///
/// # Arguments
///
/// * `data` - Data to used to update the digest
///
pub fn update(&mut self, data: &[u8]) -> CaliptraResult<()> {
if self.state == HmacOpState::Final {
return Err(CaliptraError::DRIVER_HMAC_INVALID_STATE);
}
if self.data_size + data.len() > HMAC_MAX_DATA_SIZE {
return Err(CaliptraError::DRIVER_HMAC_MAX_DATA);
}
for byte in data {
self.data_size += 1;
// PANIC-FREE: Following check optimizes the out of bounds
// panic in indexing the `buf`
if self.buf_idx >= self.buf.len() {
return Err(CaliptraError::DRIVER_HMAC_INDEX_OUT_OF_BOUNDS);
}
// Copy the data to the buffer
self.buf[self.buf_idx] = *byte;
self.buf_idx += 1;
// If the buffer is full calculate the digest of accumulated data
if self.buf_idx == self.buf.len() {
self.hmac_engine.hmac_block(
&self.buf,
self.is_first(),
self.key,
self.dest_key(),
self.hmac_mode,
self.csr_mode,
)?;
self.reset_buf_state();
}
}
Ok(())
}
/// Finalize the digest operations
pub fn finalize(&mut self) -> CaliptraResult<()> {
if self.state == HmacOpState::Final {
return Err(CaliptraError::DRIVER_HMAC_INVALID_STATE);
}
if self.buf_idx > self.buf.len() {
return Err(CaliptraError::DRIVER_HMAC_INVALID_SLICE);
}
// Calculate the hmac of the final block
let buf = &self.buf[..self.buf_idx];
#[cfg(feature = "fips-test-hooks")]
let buf = unsafe {
crate::FipsTestHook::corrupt_data_if_hook_set(
crate::FipsTestHook::HMAC384_CORRUPT_TAG,
&buf,
)
};
let params = HmacParams {
slice: buf,
first: self.is_first(),
buf_size: self.data_size,
key: self.key,
dest_key: self.dest_key(),
hmac_mode: self.hmac_mode,
csr_mode: self.csr_mode,
};
self.hmac_engine.hmac_partial_block(params)?;
// Set the state of the operation to final
self.state = HmacOpState::Final;
let hmac = self.hmac_engine.hmac.regs();
// Copy the tag to the specified location
let result = match &mut self.tag {
HmacTag::Array4x12(arr) => {
KvAccess::end_copy_to_arr(hmac.hmac512_tag().truncate::<12>(), arr)
}
HmacTag::Array4x16(arr) => KvAccess::end_copy_to_arr(hmac.hmac512_tag(), arr),
HmacTag::Key(key) => KvAccess::end_copy_to_kv(hmac.hmac512_kv_wr_status(), *key)
.map_err(|err| err.into_write_tag_err()),
};
self.hmac_engine.zeroize_internal();
result
}
fn dest_key(&self) -> Option<KeyWriteArgs> {
match self.tag {
HmacTag::Key(key) => Some(key),
_ => None,
}
}
/// Check if this the first digest operation
fn is_first(&self) -> bool {
self.state == HmacOpState::Init
}
/// Reset internal buffer state
fn reset_buf_state(&mut self) {
self.buf.fill(0);
self.buf_idx = 0;
self.state = HmacOpState::Pending;
}
}
/// HMAC key access error trait
trait HmacKeyAccessErr {
/// Convert to read key operation error
fn into_read_key_err(self) -> CaliptraError;
/// Convert to read data operation error
fn into_read_data_err(self) -> CaliptraError;
/// Convert to write tag operation error
fn into_write_tag_err(self) -> CaliptraError;
}
impl HmacKeyAccessErr for KvAccessErr {
/// Convert to read seed operation error
fn into_read_key_err(self) -> CaliptraError {
match self {
KvAccessErr::KeyRead => CaliptraError::DRIVER_HMAC_READ_KEY_KV_READ,
KvAccessErr::KeyWrite => CaliptraError::DRIVER_HMAC_READ_KEY_KV_WRITE,
KvAccessErr::Generic => CaliptraError::DRIVER_HMAC_READ_KEY_KV_UNKNOWN,
}
}
/// Convert to read data operation error
fn into_read_data_err(self) -> CaliptraError {
match self {
KvAccessErr::KeyRead => CaliptraError::DRIVER_HMAC_READ_DATA_KV_READ,
KvAccessErr::KeyWrite => CaliptraError::DRIVER_HMAC_READ_DATA_KV_WRITE,
KvAccessErr::Generic => CaliptraError::DRIVER_HMAC_READ_DATA_KV_UNKNOWN,
}
}
/// Convert to write tag operation error
fn into_write_tag_err(self) -> CaliptraError {
match self {
KvAccessErr::KeyRead => CaliptraError::DRIVER_HMAC_WRITE_TAG_KV_READ,
KvAccessErr::KeyWrite => CaliptraError::DRIVER_HMAC_WRITE_TAG_KV_WRITE,
KvAccessErr::Generic => CaliptraError::DRIVER_HMAC_WRITE_TAG_KV_UNKNOWN,
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/pcr_reset.rs | drivers/src/pcr_reset.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
pcr_reset.rs
Abstract:
PCR reset counter.
--*/
use crate::pcr_bank::{PcrBank, PcrId};
use core::ops::{Index, IndexMut};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
use zeroize::Zeroize;
#[repr(C, align(4))]
#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Zeroize)]
pub struct PcrResetCounter {
pub counter: [u32; PcrBank::ALL_PCR_IDS.len()],
}
impl Default for PcrResetCounter {
fn default() -> Self {
PcrResetCounter {
counter: [0; PcrBank::ALL_PCR_IDS.len()],
}
}
}
impl Index<PcrId> for PcrResetCounter {
type Output = u32;
fn index(&self, id: PcrId) -> &Self::Output {
&self.counter[usize::from(id)]
}
}
impl IndexMut<PcrId> for PcrResetCounter {
fn index_mut(&mut self, id: PcrId) -> &mut Self::Output {
&mut self.counter[usize::from(id)]
}
}
impl PcrResetCounter {
pub fn new() -> PcrResetCounter {
PcrResetCounter::default()
}
/// Increment the selected reset counter.
/// Returns `false` in case of a counter overflow
pub fn increment(&mut self, id: PcrId) -> bool {
let old_value = self[id];
if let Some(new_value) = old_value.checked_add(1) {
self[id] = new_value;
true
} else {
false
}
}
pub fn all_counters(&self) -> [u32; PcrBank::ALL_PCR_IDS.len()] {
self.counter
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/array.rs | drivers/src/array.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
array.rs
Abstract:
File contains common array definitions used by Caliptra hardware software
interface.
--*/
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::Launder;
use core::mem::MaybeUninit;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
use zeroize::Zeroize;
macro_rules! static_assert {
($expression:expr) => {
const _: () = assert!($expression);
};
}
/// The `Array4xN` type represents large arrays in the native format of the Caliptra
/// cryptographic hardware, and provides From traits for converting to/from byte arrays.
#[repr(transparent)]
#[derive(
Debug, Clone, Copy, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq, Zeroize,
)]
#[cfg_attr(not(feature = "no-cfi"), derive(Launder))]
pub struct Array4xN<const W: usize, const B: usize>(pub [u32; W]);
impl<const W: usize, const B: usize> Array4xN<W, B> {
pub const fn new(val: [u32; W]) -> Self {
Self(val)
}
}
impl<const W: usize, const B: usize> Default for Array4xN<W, B> {
fn default() -> Self {
Self([0u32; W])
}
}
//// Ensure there is no padding in the struct
static_assert!(core::mem::size_of::<Array4xN<1, 4>>() == 4);
impl<const W: usize, const B: usize> Array4xN<W, B> {
#[inline(always)]
#[allow(unused)]
pub fn read_from_reg<
TReg: ureg::ReadableReg<ReadVal = u32, Raw = u32>,
TMmio: ureg::Mmio + Copy,
>(
reg_array: ureg::Array<W, ureg::RegRef<TReg, TMmio>>,
) -> Self {
reg_array.read().into()
}
#[inline(always)]
#[allow(unused)]
pub fn write_to_reg<
TReg: ureg::ResettableReg + ureg::WritableReg<WriteVal = u32, Raw = u32>,
TMmio: ureg::MmioMut + Copy,
>(
&self,
reg_array: ureg::Array<W, ureg::RegRef<TReg, TMmio>>,
) {
reg_array.write(&self.0);
}
}
impl<const W: usize, const B: usize> From<[u8; B]> for Array4xN<W, B> {
#[inline(always)]
fn from(value: [u8; B]) -> Self {
Self::from(&value)
}
}
#[inline(never)]
unsafe fn u32_be_to_u8_impl<const W: usize, const B: usize>(
dest: &mut MaybeUninit<[u8; B]>,
src: &Array4xN<W, B>,
) {
let ptr = dest.as_mut_ptr() as *mut [u8; 4];
for i in 0..W {
ptr.add(i).write(src.0[i].to_be_bytes());
}
}
impl<const W: usize, const B: usize> From<Array4xN<W, B>> for [u8; B] {
#[inline(always)]
fn from(value: Array4xN<W, B>) -> Self {
Self::from(&value)
}
}
impl<const W: usize, const B: usize> From<&Array4xN<W, B>> for [u8; B] {
#[inline(always)]
fn from(value: &Array4xN<W, B>) -> Self {
unsafe {
let mut result = MaybeUninit::<[u8; B]>::uninit();
u32_be_to_u8_impl(&mut result, value);
result.assume_init()
}
}
}
#[inline(never)]
unsafe fn u8_to_u32_be_impl<const W: usize, const B: usize>(
dest: &mut MaybeUninit<Array4xN<W, B>>,
src: &[u8; B],
) {
let dest = dest.as_mut_ptr() as *mut u32;
for i in 0..W {
dest.add(i)
.write(u32::from_be_bytes(src[i * 4..][..4].try_into().unwrap()));
}
}
impl<const W: usize, const B: usize> From<&[u8; B]> for Array4xN<W, B> {
#[inline(always)]
fn from(value: &[u8; B]) -> Self {
let mut result = MaybeUninit::<Array4xN<W, B>>::uninit();
unsafe {
u8_to_u32_be_impl(&mut result, value);
result.assume_init()
}
}
}
impl<const W: usize, const B: usize> From<&[u32; W]> for Array4xN<W, B> {
fn from(value: &[u32; W]) -> Self {
Self(*value)
}
}
impl<const W: usize, const B: usize> From<[u32; W]> for Array4xN<W, B> {
fn from(value: [u32; W]) -> Self {
Self(value)
}
}
impl<const W: usize, const B: usize> From<Array4xN<W, B>> for [u32; W] {
fn from(value: Array4xN<W, B>) -> Self {
value.0
}
}
/// Conversion from big-endian Array4xN to little-endian LEArray4xN
impl<const W: usize, const B: usize> From<Array4xN<W, B>> for LEArray4xN<W, B> {
fn from(value: Array4xN<W, B>) -> Self {
let result: [u8; B] = value.into();
Self::from(&result)
}
}
/// The `LEArray4xN` type represents large arrays in little-endian format,
/// and provides From traits for converting to/from byte arrays.
#[repr(transparent)]
#[derive(
Debug, Clone, Copy, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq, Zeroize,
)]
#[cfg_attr(not(feature = "no-cfi"), derive(Launder))]
pub struct LEArray4xN<const W: usize, const B: usize>(pub [u32; W]);
impl<const W: usize, const B: usize> LEArray4xN<W, B> {
pub const fn new(val: [u32; W]) -> Self {
Self(val)
}
}
impl<const W: usize, const B: usize> Default for LEArray4xN<W, B> {
fn default() -> Self {
Self([0u32; W])
}
}
//// Ensure there is no padding in the struct
static_assert!(core::mem::size_of::<LEArray4xN<1, 4>>() == 4);
impl<const W: usize, const B: usize> LEArray4xN<W, B> {
#[inline(always)]
#[allow(unused)]
pub fn read_from_reg<
TReg: ureg::ReadableReg<ReadVal = u32, Raw = u32>,
TMmio: ureg::Mmio + Copy,
>(
reg_array: ureg::Array<W, ureg::RegRef<TReg, TMmio>>,
) -> Self {
reg_array.read().into()
}
#[inline(always)]
#[allow(unused)]
pub fn write_to_reg<
TReg: ureg::ResettableReg + ureg::WritableReg<WriteVal = u32, Raw = u32>,
TMmio: ureg::MmioMut + Copy,
>(
&self,
reg_array: ureg::Array<W, ureg::RegRef<TReg, TMmio>>,
) {
reg_array.write(&self.0);
}
}
impl<const W: usize, const B: usize> From<[u8; B]> for LEArray4xN<W, B> {
#[inline(always)]
fn from(value: [u8; B]) -> Self {
Self::from(&value)
}
}
#[inline(never)]
// [CAP2][TODO] does this get optimized away if host is LE?
unsafe fn u32_le_to_u8_impl<const W: usize, const B: usize>(
dest: &mut MaybeUninit<[u8; B]>,
src: &LEArray4xN<W, B>,
) {
let ptr = dest.as_mut_ptr() as *mut [u8; 4];
for i in 0..W {
ptr.add(i).write(src.0[i].to_le_bytes());
}
}
impl<const W: usize, const B: usize> From<LEArray4xN<W, B>> for [u8; B] {
#[inline(always)]
fn from(value: LEArray4xN<W, B>) -> Self {
Self::from(&value)
}
}
impl<const W: usize, const B: usize> From<&LEArray4xN<W, B>> for [u8; B] {
#[inline(always)]
fn from(value: &LEArray4xN<W, B>) -> Self {
unsafe {
let mut result = MaybeUninit::<[u8; B]>::uninit();
u32_le_to_u8_impl(&mut result, value);
result.assume_init()
}
}
}
#[inline(never)]
unsafe fn u8_to_u32_le_impl<const W: usize, const B: usize>(
dest: &mut MaybeUninit<LEArray4xN<W, B>>,
src: &[u8; B],
) {
let dest = dest.as_mut_ptr() as *mut u32;
for i in 0..W {
dest.add(i)
.write(u32::from_le_bytes(src[i * 4..][..4].try_into().unwrap()));
}
}
impl<const W: usize, const B: usize> From<&[u8; B]> for LEArray4xN<W, B> {
#[inline(always)]
fn from(value: &[u8; B]) -> Self {
let mut result = MaybeUninit::<LEArray4xN<W, B>>::uninit();
unsafe {
u8_to_u32_le_impl(&mut result, value);
result.assume_init()
}
}
}
impl<const W: usize, const B: usize> From<&[u32; W]> for LEArray4xN<W, B> {
fn from(value: &[u32; W]) -> Self {
Self(*value)
}
}
impl<const W: usize, const B: usize> From<[u32; W]> for LEArray4xN<W, B> {
fn from(value: [u32; W]) -> Self {
Self(value)
}
}
impl<const W: usize, const B: usize> From<LEArray4xN<W, B>> for [u32; W] {
fn from(value: LEArray4xN<W, B>) -> Self {
value.0
}
}
/// Conversion from little-endian LEArray4xN to big-endian Array4xN
impl<const W: usize, const B: usize> From<&LEArray4xN<W, B>> for Array4xN<W, B> {
fn from(value: &LEArray4xN<W, B>) -> Self {
let result: [u8; B] = value.into();
Self::from(result)
}
}
impl<const W: usize, const B: usize> From<LEArray4xN<W, B>> for Array4xN<W, B> {
fn from(value: LEArray4xN<W, B>) -> Self {
Self::from(&value)
}
}
pub type LEArray4x3 = LEArray4xN<3, 12>;
pub type LEArray4x4 = LEArray4xN<4, 16>;
pub type LEArray4x8 = LEArray4xN<8, 32>;
pub type LEArray4x16 = LEArray4xN<16, 64>;
pub type LEArray4x392 = LEArray4xN<392, 1568>;
pub type LEArray4x648 = LEArray4xN<648, 2592>;
pub type LEArray4x792 = LEArray4xN<792, 3168>;
pub type LEArray4x1157 = LEArray4xN<1157, 4628>;
pub type LEArray4x1224 = LEArray4xN<1224, 4896>;
pub type Array4x4 = Array4xN<4, 16>;
pub type Array4x5 = Array4xN<5, 20>;
pub type Array4x8 = Array4xN<8, 32>;
pub type Array4x12 = Array4xN<12, 48>;
pub type Array4x16 = Array4xN<16, 64>;
pub type Array4x32 = Array4xN<32, 128>;
#[cfg(test)]
mod tests {
use super::*;
// To run inside the MIRI interpreter to detect undefined behavior in the
// unsafe code, run with:
// cargo +nightly miri test -p caliptra-drivers --lib
#[test]
fn test_array_4x4_from_bytes() {
assert_eq!(
Array4x4::from([
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
0xee, 0xff
]),
Array4x4::new([0x0011_2233, 0x4455_6677, 0x8899_aabb, 0xccdd_eeff])
);
assert_eq!(
Array4x4::from(&[
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
0xee, 0xff
]),
Array4x4::new([0x0011_2233, 0x4455_6677, 0x8899_aabb, 0xccdd_eeff])
);
}
#[test]
fn test_array_4x4_to_bytes() {
assert_eq!(
<[u8; 16]>::from(Array4x4::new([
0x0011_2233,
0x4455_6677,
0x8899_aabb,
0xccdd_eeff
])),
[
0x00u8, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
0xdd, 0xee, 0xff
]
);
assert_eq!(
<[u8; 16]>::from(&Array4x4::new([
0x0011_2233,
0x4455_6677,
0x8899_aabb,
0xccdd_eeff
])),
[
0x00u8, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
0xdd, 0xee, 0xff
]
);
}
#[test]
fn test_array_conversion() {
let be_array = Array4x8::new([
0x0011_2233,
0x4455_6677,
0x8899_aabb,
0xccdd_eeff,
0x0123_4567,
0x89ab_cdef,
0xfedc_ba98,
0x7654_3210,
]);
let le_array = LEArray4x8::new([
0x3322_1100,
0x7766_5544,
0xbbaa_9988,
0xffee_ddcc,
0x6745_2301,
0xefcd_ab89,
0x98ba_dcfe,
0x1032_5476,
]);
// Test BE to LE conversion
assert_eq!(LEArray4x8::from(be_array), le_array);
// Test LE to BE conversion
assert_eq!(Array4x8::from(le_array), be_array);
// Test round-trip conversion
assert_eq!(Array4x8::from(LEArray4x8::from(be_array)), be_array);
assert_eq!(LEArray4x8::from(Array4x8::from(le_array)), le_array);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/memory_layout.rs | drivers/src/memory_layout.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
memory_layout.rs
Abstract:
The file contains the layout of memory. The constants defined
in this file define the memory layout.
--*/
use core::mem::size_of;
use crate::PersistentData;
//
// Memory Addresses
//
pub const ROM_ORG: u32 = 0x00000000;
pub const MBOX_ORG: u32 = 0x30040000;
pub const ICCM_ORG: u32 = 0x40000000;
/// DCCM (Data Closely Coupled Memory)
///
/// Layout
///
/// | Partition | Field | Start | End | Size |
/// |-----------------|--------------|-------------|-------------|----------------------|
/// | DCCM | | 0x5000_0000 | 0x5004_0000 | 0x4_0000 |
/// | Stack | | 0x5000_0000 | 0x5002_3800 | 0x2_3800 |
/// | | FW Stack | 0x5000_0000 | 0x5002_3000 | 0x2_3000 |
/// | | ROM Stack | 0x5000_0000 | 0x5001_2c00 | 0x1_2c00 |
/// | | EStack | 0x5002_3000 | 0x5002_3400 | 0x400 |
/// | | NStack | 0x5002_3400 | 0x5002_3800 | 0x400 |
/// | Extra memory | | 0x5002_3800 | Extra end | Extra memory size |
/// | Persistent Data | | Extra end | 0x5003_fc00 | Persistent data size |
/// | ROM Data | | 0x5003_fc00 | 0x5004_0000 | 0x400 |
/// | | Reserved | 0x5003_fc00 | 0x5003_ffe4 | 0x3e4 |
/// | | CFI State | 0x5003_ffe4 | 0x5003_fffc | 0x18 |
/// | | Boot Status | 0x5003_fffc | 0x5004_0000 | 0x4 |
pub const DCCM_ORG: u32 = 0x50000000;
/// Stack is placed at the beginning of DCCM so a stack overflow will cause a hardware fault
pub const STACK_ORG: u32 = DCCM_ORG;
pub const ROM_STACK_ORG: u32 = STACK_ORG;
/// Exception stack
pub const ESTACK_ORG: u32 = STACK_ORG + STACK_SIZE;
pub const ROM_ESTACK_ORG: u32 = ESTACK_ORG;
/// NMI stack
pub const NSTACK_ORG: u32 = ESTACK_ORG + ESTACK_SIZE;
pub const ROM_NSTACK_ORG: u32 = NSTACK_ORG;
/// Extra memory reserved for stack and/or persistent data growth
pub const EXTRA_MEMORY_ORG: u32 = NSTACK_ORG + NSTACK_SIZE;
/// Persistent data shared between boot stages and stored across warm and update resets
pub const PERSISTENT_DATA_ORG: u32 = ROM_DATA_ORG - size_of::<PersistentData>() as u32;
pub const ROM_DATA_ORG: u32 = DCCM_ORG + DCCM_SIZE - ROM_DATA_SIZE;
pub const CFI_STATE_ORG: u32 = ROM_DATA_ORG + 0x3E4; // size = 6 words
pub const BOOT_STATUS_ORG: u32 = ROM_DATA_ORG + 0x3FC;
pub const LAST_REGION_END: u32 = ROM_DATA_ORG + ROM_DATA_SIZE;
//
// Memory Sizes In Bytes
//
pub const ROM_RELAXATION_PADDING: u32 = 4 * 1024;
pub const ROM_SIZE: u32 = 96 * 1024;
pub const MAX_MBOX_SIZE: u32 = 256 * 1024; // Actual size depens on hw revision and subsystem being present
pub const MBOX_SIZE_PASSIVE_MODE: u32 = 16 * 1024;
pub const ICCM_SIZE: u32 = 256 * 1024;
pub const DCCM_SIZE: u32 = 256 * 1024;
pub const ROM_DATA_SIZE: u32 = 1024;
pub const ROM_DATA_RESERVED_SIZE: u32 = 996;
pub const STACK_SIZE: u32 = 140 * 1024;
pub const ROM_STACK_SIZE: u32 = 80 * 1024;
pub const ESTACK_SIZE: u32 = 1024;
pub const ROM_ESTACK_SIZE: u32 = 1024;
pub const NSTACK_SIZE: u32 = 1024;
pub const ROM_NSTACK_SIZE: u32 = 1024;
pub const EXTRA_MEMORY_SIZE: u32 = DCCM_SIZE
- NSTACK_SIZE
- ESTACK_SIZE
- STACK_SIZE
- ROM_DATA_SIZE
- size_of::<PersistentData>() as u32;
pub const ICCM_RANGE: core::ops::Range<u32> = core::ops::Range {
start: ICCM_ORG,
end: ICCM_ORG + ICCM_SIZE,
};
#[test]
#[allow(clippy::assertions_on_constants)]
fn mem_layout_test_stacks_start() {
assert_eq!(DCCM_ORG, STACK_ORG);
assert_eq!(DCCM_ORG, ROM_STACK_ORG);
}
#[test]
#[allow(clippy::assertions_on_constants)]
fn mem_layout_test_stack() {
assert_eq!((ESTACK_ORG - STACK_ORG), STACK_SIZE);
}
#[test]
#[allow(clippy::assertions_on_constants)]
fn mem_layout_test_estack() {
assert_eq!((NSTACK_ORG - ESTACK_ORG), ESTACK_SIZE);
}
#[test]
#[allow(clippy::assertions_on_constants)]
fn mem_layout_test_nstack() {
assert_eq!((EXTRA_MEMORY_ORG - NSTACK_ORG), NSTACK_SIZE);
}
#[test]
#[allow(clippy::assertions_on_constants)]
fn mem_layout_extra_memory() {
assert_eq!((PERSISTENT_DATA_ORG - EXTRA_MEMORY_ORG), EXTRA_MEMORY_SIZE);
}
#[test]
#[allow(clippy::assertions_on_constants)]
fn mem_layout_test_persistent_data() {
assert_eq!(
(ROM_DATA_ORG - PERSISTENT_DATA_ORG),
size_of::<PersistentData>() as u32
);
}
#[test]
#[allow(clippy::assertions_on_constants)]
fn mem_layout_rom_data() {
assert_eq!((DCCM_ORG + DCCM_SIZE - ROM_DATA_ORG), ROM_DATA_SIZE);
}
#[test]
#[allow(clippy::assertions_on_constants)]
fn dccm_overflow() {
assert!(DCCM_ORG + DCCM_SIZE >= LAST_REGION_END);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/ecc384.rs | drivers/src/ecc384.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
ecc384.rs
Abstract:
File contains API for ECC-384 Cryptography operations
--*/
use crate::kv_access::{KvAccess, KvAccessErr};
use crate::{
array_concat3, okmutref, wait, Array4x12, Array4xN, CaliptraError, CaliptraResult, KeyReadArgs,
KeyWriteArgs, Trng,
};
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::cfi_impl_fn;
use caliptra_registers::ecc::{EccReg, RegisterBlock};
use core::cmp::Ordering;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
use zeroize::Zeroize;
/// ECC-384 Coordinate
pub type Ecc384Scalar = Array4x12;
#[must_use]
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ecc384Result {
Success = 0xAAAAAAAA,
SigVerifyFailed = 0x55555555,
}
/// ECC-384 Seed
#[derive(Debug, Copy, Clone)]
pub enum Ecc384Seed<'a> {
/// Array
Array4x12(&'a Ecc384Scalar),
/// Key Vault Key
Key(KeyReadArgs),
}
impl<'a> From<&'a Array4x12> for Ecc384Seed<'a> {
/// Converts to this type from the input type.
fn from(value: &'a Array4x12) -> Self {
Self::Array4x12(value)
}
}
impl From<KeyReadArgs> for Ecc384Seed<'_> {
/// Converts to this type from the input type.
fn from(value: KeyReadArgs) -> Self {
Self::Key(value)
}
}
/// ECC-384 Public Key output
#[derive(Debug)]
pub enum Ecc384PrivKeyOut<'a> {
/// Array
Array4x12(&'a mut Ecc384Scalar),
/// Key Vault Key
Key(KeyWriteArgs),
}
impl<'a> From<&'a mut Array4x12> for Ecc384PrivKeyOut<'a> {
/// Converts to this type from the input type.
fn from(value: &'a mut Array4x12) -> Self {
Self::Array4x12(value)
}
}
impl From<KeyWriteArgs> for Ecc384PrivKeyOut<'_> {
/// Converts to this type from the input type.
fn from(value: KeyWriteArgs) -> Self {
Self::Key(value)
}
}
/// ECC-384 Public Key input
#[derive(Debug, Copy, Clone)]
pub enum Ecc384PrivKeyIn<'a> {
/// Array
Array4x12(&'a Ecc384Scalar),
/// Key Vault Key
Key(KeyReadArgs),
}
impl<'a> From<&'a Array4x12> for Ecc384PrivKeyIn<'a> {
/// Converts to this type from the input type.
fn from(value: &'a Array4x12) -> Self {
Self::Array4x12(value)
}
}
impl From<KeyReadArgs> for Ecc384PrivKeyIn<'_> {
/// Converts to this type from the input type.
fn from(value: KeyReadArgs) -> Self {
Self::Key(value)
}
}
impl<'a> From<Ecc384PrivKeyOut<'a>> for Ecc384PrivKeyIn<'a> {
fn from(value: Ecc384PrivKeyOut<'a>) -> Self {
match value {
Ecc384PrivKeyOut::Array4x12(arr) => Ecc384PrivKeyIn::Array4x12(arr),
Ecc384PrivKeyOut::Key(key) => Ecc384PrivKeyIn::Key(KeyReadArgs { id: key.id }),
}
}
}
/// ECC-384 Public Key
#[repr(C)]
#[derive(
IntoBytes,
FromBytes,
Immutable,
KnownLayout,
Debug,
Default,
Copy,
Clone,
Eq,
PartialEq,
Zeroize,
)]
pub struct Ecc384PubKey {
/// X coordinate
pub x: Ecc384Scalar,
/// Y coordinate
pub y: Ecc384Scalar,
}
impl Ecc384PubKey {
/// Return DER formatted public key in uncompressed form
#[inline(never)]
pub fn to_der(&self) -> [u8; 97] {
array_concat3([0x04], (&self.x).into(), (&self.y).into())
}
}
/// ECC-384 Signature
#[repr(C)]
#[derive(
Debug,
Default,
IntoBytes,
FromBytes,
Immutable,
KnownLayout,
Copy,
Clone,
Eq,
PartialEq,
Zeroize,
)]
pub struct Ecc384Signature {
/// Random point
pub r: Ecc384Scalar,
/// Proof
pub s: Ecc384Scalar,
}
/// Elliptic Curve P-384 API
pub struct Ecc384 {
ecc: EccReg,
}
impl Ecc384 {
pub fn new(ecc: EccReg) -> Self {
Self { ecc }
}
// Check that `scalar` is in the range [1, n-1] for the P-384 curve
fn scalar_range_check(scalar: &Ecc384Scalar) -> bool {
// n-1 for The NIST P-384 curve
const SECP384_ORDER_MIN1: &[u32] = &[
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xc7634d81,
0xf4372ddf, 0x581a0db2, 0x48b0a77a, 0xecec196a, 0xccc52972,
];
// Check scalar <= n-1
for (i, word) in SECP384_ORDER_MIN1.iter().enumerate() {
match scalar.0[i].cmp(word) {
Ordering::Greater => return false,
Ordering::Less => break,
Ordering::Equal => continue,
}
}
// If scalar is non-zero, return true
for word in scalar.0 {
if word != 0 {
return true;
}
}
// scalar is zero
false
}
// Wait on the provided condition OR the error condition defined in this function
// In the event of the error condition being set, clear the error bits and return an error
fn wait<F>(regs: RegisterBlock<ureg::RealMmioMut>, condition: F) -> CaliptraResult<()>
where
F: Fn() -> bool,
{
let err_condition = || {
(u32::from(regs.intr_block_rf().error_global_intr_r().read()) != 0)
|| (u32::from(regs.intr_block_rf().error_internal_intr_r().read()) != 0)
};
// Wait for either the given condition or the error condition
wait::until(|| (condition() || err_condition()));
if err_condition() {
// Clear the errors
// error_global_intr_r is RO
regs.intr_block_rf()
.error_internal_intr_r()
.write(|_| u32::from(regs.intr_block_rf().error_internal_intr_r().read()).into());
return Err(CaliptraError::DRIVER_ECC384_HW_ERROR);
}
Ok(())
}
/// Generate ECC-384 Key Pair
///
/// # Arguments
///
/// * `seed` - Seed for deterministic ECC Key Pair generation
/// * `nonce` - Nonce for deterministic ECC Key Pair generation
/// * `trng` - TRNG driver instance
/// * `priv_key` - Generate ECC-384 Private key
///
/// # Returns
///
/// * `Ecc384PubKey` - Generated ECC-384 Public Key
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn key_pair(
&mut self,
seed: Ecc384Seed,
nonce: &Array4x12,
trng: &mut Trng,
priv_key: Ecc384PrivKeyOut,
) -> CaliptraResult<Ecc384PubKey> {
self.key_pair_base(seed, nonce, trng, priv_key, None)
}
/// Generate ECC-384 Key Pair for FIPS KAT testing
/// ONLY to be used for KAT testing
///
/// # Arguments
///
/// * `trng` - TRNG driver instance
/// * `priv_key` - Generate ECC-384 Private key
/// * `pct_sig` - Ecc 384 signature to return signature generated during the pairwise consistency test
///
/// # Returns
///
/// * `Ecc384PubKey` - Generated ECC-384 Public Key
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn key_pair_for_fips_kat(
&mut self,
trng: &mut Trng,
priv_key: Ecc384PrivKeyOut,
pct_sig: &mut Ecc384Signature,
) -> CaliptraResult<Ecc384PubKey> {
let seed = Array4x12::new([0u32; 12]);
let nonce = Array4x12::new([0u32; 12]);
self.key_pair_base(
Ecc384Seed::from(&seed),
&nonce,
trng,
priv_key,
Some(pct_sig),
)
}
/// Private base function to generate ECC-384 Key Pair
/// pct_sig should only be provided in the KAT use case
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
#[inline(never)]
fn key_pair_base(
&mut self,
seed: Ecc384Seed,
nonce: &Array4x12,
trng: &mut Trng,
priv_key: Ecc384PrivKeyOut,
pct_sig: Option<&mut Ecc384Signature>,
) -> CaliptraResult<Ecc384PubKey> {
#[cfg(feature = "fips-test-hooks")]
unsafe {
crate::FipsTestHook::error_if_hook_set(
crate::FipsTestHook::ECC384_KEY_PAIR_GENERATE_FAILURE,
)?
}
let ecc = self.ecc.regs_mut();
let mut priv_key = priv_key;
// Wait for hardware ready
Ecc384::wait(ecc, || ecc.status().read().ready())?;
// Configure hardware to route keys to user specified hardware blocks
match &mut priv_key {
Ecc384PrivKeyOut::Array4x12(_arr) => {
KvAccess::begin_copy_to_arr(ecc.kv_wr_pkey_status(), ecc.kv_wr_pkey_ctrl())?;
}
Ecc384PrivKeyOut::Key(key) => {
if !key.usage.ecc_private_key() {
// The key MUST be usable as a private key so we can do a
// pairwise consistency test, which is required to prevent
// leakage of secret material if the peripheral is glitched.
return Err(CaliptraError::DRIVER_ECC384_KEYGEN_BAD_USAGE);
}
KvAccess::begin_copy_to_kv(ecc.kv_wr_pkey_status(), ecc.kv_wr_pkey_ctrl(), *key)?;
}
}
// Copy seed to the hardware
match seed {
Ecc384Seed::Array4x12(arr) => KvAccess::copy_from_arr(arr, ecc.seed())?,
Ecc384Seed::Key(key) => {
KvAccess::copy_from_kv(key, ecc.kv_rd_seed_status(), ecc.kv_rd_seed_ctrl())
.map_err(|err| err.into_read_seed_err())?
}
}
// Copy nonce to the hardware
KvAccess::copy_from_arr(nonce, ecc.nonce())?;
// Generate an IV.
let iv = trng.generate()?;
KvAccess::copy_from_arr(&iv, ecc.iv())?;
// Program the command register for key generation
ecc.ctrl().write(|w| w.ctrl(|w| w.keygen()));
// Wait for command to complete
Ecc384::wait(ecc, || ecc.status().read().valid())?;
// Copy the private key
match &mut priv_key {
Ecc384PrivKeyOut::Array4x12(arr) => KvAccess::end_copy_to_arr(ecc.privkey_out(), arr)?,
Ecc384PrivKeyOut::Key(key) => {
KvAccess::end_copy_to_kv(ecc.kv_wr_pkey_status(), *key)
.map_err(|err| err.into_write_priv_key_err())?;
}
}
let pub_key = Ecc384PubKey {
x: Array4x12::read_from_reg(ecc.pubkey_x()),
y: Array4x12::read_from_reg(ecc.pubkey_y()),
};
// Pairwise consistency check.
let digest = Array4x12::new([0u32; 12]);
#[cfg(feature = "fips-test-hooks")]
let pub_key = unsafe {
crate::FipsTestHook::corrupt_data_if_hook_set(
crate::FipsTestHook::ECC384_PAIRWISE_CONSISTENCY_ERROR,
&pub_key,
)
};
match self.sign(priv_key.into(), &pub_key, &digest, trng) {
Ok(mut sig) => {
// Return the signature from this test if requested (only used for KAT)
if let Some(output_sig) = pct_sig {
*output_sig = sig;
}
sig.zeroize();
}
Err(_) => {
// Remap error to a pairwise consistency check failure
return Err(CaliptraError::DRIVER_ECC384_KEYGEN_PAIRWISE_CONSISTENCY_FAILURE);
}
}
self.zeroize_internal();
#[cfg(feature = "fips-test-hooks")]
let pub_key = unsafe {
crate::FipsTestHook::corrupt_data_if_hook_set(
crate::FipsTestHook::ECC384_CORRUPT_KEY_PAIR,
&pub_key,
)
};
Ok(pub_key)
}
/// Sign the PCR digest with PCR signing private key in keyvault slot 7 (KV7).
/// KV7 contains the Alias FMC ECC private key.
///
/// # Arguments
///
/// * `trng` - TRNG driver instance
///
/// # Returns
///
/// * `Ecc384Signature` - Generated signature
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn pcr_sign_flow(&mut self, trng: &mut Trng) -> CaliptraResult<Ecc384Signature> {
let ecc = self.ecc.regs_mut();
// Wait for hardware ready
Ecc384::wait(ecc, || ecc.status().read().ready())?;
// Generate an IV.
let iv = trng.generate()?;
KvAccess::copy_from_arr(&iv, ecc.iv())?;
ecc.ctrl().write(|w| w.pcr_sign(true).ctrl(|w| w.signing()));
// Wait for command to complete
Ecc384::wait(ecc, || ecc.status().read().valid())?;
// Copy signature
let signature = Ecc384Signature {
r: Array4x12::read_from_reg(ecc.sign_r()),
s: Array4x12::read_from_reg(ecc.sign_s()),
};
self.zeroize_internal();
Ok(signature)
}
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
fn sign_internal(
&mut self,
priv_key: Ecc384PrivKeyIn,
data: &Ecc384Scalar,
trng: &mut Trng,
) -> CaliptraResult<Ecc384Signature> {
let ecc = self.ecc.regs_mut();
// Wait for hardware ready
Ecc384::wait(ecc, || ecc.status().read().ready())?;
// Copy private key
match priv_key {
Ecc384PrivKeyIn::Array4x12(arr) => KvAccess::copy_from_arr(arr, ecc.privkey_in())?,
Ecc384PrivKeyIn::Key(key) => {
KvAccess::copy_from_kv(key, ecc.kv_rd_pkey_status(), ecc.kv_rd_pkey_ctrl())
.map_err(|err| err.into_read_priv_key_err())?
}
}
// Copy digest
KvAccess::copy_from_arr(data, ecc.msg())?;
// Generate an IV.
let iv = trng.generate()?;
KvAccess::copy_from_arr(&iv, ecc.iv())?;
// Program the command register
ecc.ctrl().write(|w| w.ctrl(|w| w.signing()));
// Wait for command to complete
Ecc384::wait(ecc, || ecc.status().read().valid())?;
// Copy signature
let signature = Ecc384Signature {
r: Array4x12::read_from_reg(ecc.sign_r()),
s: Array4x12::read_from_reg(ecc.sign_s()),
};
self.zeroize_internal();
Ok(signature)
}
/// Sign the digest with specified private key. To defend against glitching
/// attacks that could expose the private key, this function also verifies
/// the generated signature.
///
/// # Arguments
///
/// * `priv_key` - Private key
/// * `pub_key` - Public key to verify with
/// * `data` - Digest to sign
/// * `trng` - TRNG driver instance
///
/// # Returns
///
/// * `Ecc384Signature` - Generate signature
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn sign(
&mut self,
priv_key: Ecc384PrivKeyIn,
pub_key: &Ecc384PubKey,
data: &Ecc384Scalar,
trng: &mut Trng,
) -> CaliptraResult<Ecc384Signature> {
#[cfg(feature = "fips-test-hooks")]
unsafe {
crate::FipsTestHook::error_if_hook_set(
crate::FipsTestHook::ECC384_SIGNATURE_GENERATE_FAILURE,
)?
}
let mut sig_result = self.sign_internal(priv_key, data, trng);
let sig = okmutref(&mut sig_result)?;
// Verify the signature just created
let _r = self.verify_r(pub_key, data, sig)?;
// Not using standard error flow here for increased CFI safety
// An error here will end up reporting the CFI assert failure
#[cfg(not(feature = "no-cfi"))]
caliptra_cfi_lib::cfi_assert_eq_12_words(&_r.0, &sig.r.0);
#[cfg(feature = "fips-test-hooks")]
let sig_result = Ok(unsafe {
crate::FipsTestHook::corrupt_data_if_hook_set(
crate::FipsTestHook::ECC384_CORRUPT_SIGNATURE,
sig,
)
});
sig_result
}
/// Verify signature with specified public key and digest
///
/// # Arguments
///
/// * `pub_key` - Public key
/// * `digest` - digest to verify
/// * `signature` - Signature to verify
///
/// Note: Use this function only if glitch protection is not needed.
/// If glitch protection is needed, use `verify_r` instead.
///
///
/// # Result
///
/// * `Ecc384Result` - Ecc384Result::Success if the signature verification passed else an error code.
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn verify(
&mut self,
pub_key: &Ecc384PubKey,
digest: &Ecc384Scalar,
signature: &Ecc384Signature,
) -> CaliptraResult<Ecc384Result> {
// Get the verify r result
let mut verify_r = self.verify_r(pub_key, digest, signature)?;
// compare the hardware generate `r` with one in signature
let result = if verify_r == signature.r {
#[cfg(not(feature = "no-cfi"))]
caliptra_cfi_lib::cfi_assert_eq_12_words(&verify_r.0, &signature.r.0);
Ecc384Result::Success
} else {
Ecc384Result::SigVerifyFailed
};
verify_r.0.zeroize();
Ok(result)
}
/// Returns the R value of the signature with specified public key and digest.
/// Caller is expected to compare the returned R value against the provided signature's
/// R value to determine whether the signature is valid.
///
/// # Arguments
///
/// * `pub_key` - Public key
/// * `digest` - digest to verify
/// * `signature` - Signature to verify
///
/// # Result
///
/// * `Array4xN<12, 48>` - verify R value
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn verify_r(
&mut self,
pub_key: &Ecc384PubKey,
digest: &Ecc384Scalar,
signature: &Ecc384Signature,
) -> CaliptraResult<Array4xN<12, 48>> {
#[cfg(feature = "fips-test-hooks")]
unsafe {
crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::ECC384_VERIFY_FAILURE)?
}
// If R or S are not in the range [1, N-1], signature check must fail
if !Self::scalar_range_check(&signature.r) || !Self::scalar_range_check(&signature.s) {
return Err(CaliptraError::DRIVER_ECC384_SCALAR_RANGE_CHECK_FAILED);
}
let ecc = self.ecc.regs_mut();
// Wait for hardware ready
Ecc384::wait(ecc, || ecc.status().read().ready())?;
// Copy public key to registers
pub_key.x.write_to_reg(ecc.pubkey_x());
pub_key.y.write_to_reg(ecc.pubkey_y());
// Copy digest to registers
digest.write_to_reg(ecc.msg());
// Copy signature to registers
signature.r.write_to_reg(ecc.sign_r());
signature.s.write_to_reg(ecc.sign_s());
// Program the command register
ecc.ctrl().write(|w| w.ctrl(|w| w.verifying()));
// Wait for command to complete
Ecc384::wait(ecc, || ecc.status().read().valid())?;
// Copy the random value
let verify_r = Array4x12::read_from_reg(ecc.verify_r());
self.zeroize_internal();
Ok(verify_r)
}
/// Compute a shared secret using ECDH (Elliptic Curve Diffie-Hellman)
///
/// # Arguments
///
/// * `priv_key` - Private key
/// * `pub_key` - Public key of the other party
/// * `trng` - TRNG driver instance
/// * `shared_key_out` - Output destination for the shared key
///
/// # Returns
///
/// * `()` - Success or error
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn ecdh(
&mut self,
priv_key: Ecc384PrivKeyIn,
pub_key: &Ecc384PubKey,
trng: &mut Trng,
shared_key_out: Ecc384PrivKeyOut,
) -> CaliptraResult<()> {
#[cfg(feature = "fips-test-hooks")]
unsafe {
crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::ECC384_ECDH_FAILURE)?
}
let ecc = self.ecc.regs_mut();
let mut shared_key_out = shared_key_out;
// Wait for hardware ready
Ecc384::wait(ecc, || ecc.status().read().ready())?;
// Configure hardware to route keys to user specified hardware blocks
match &mut shared_key_out {
Ecc384PrivKeyOut::Array4x12(_arr) => {
KvAccess::begin_copy_to_arr(ecc.kv_wr_pkey_status(), ecc.kv_wr_pkey_ctrl())?;
}
Ecc384PrivKeyOut::Key(key) => {
KvAccess::begin_copy_to_kv(ecc.kv_wr_pkey_status(), ecc.kv_wr_pkey_ctrl(), *key)?;
}
}
// Copy private key
match priv_key {
Ecc384PrivKeyIn::Array4x12(arr) => KvAccess::copy_from_arr(arr, ecc.privkey_in())?,
Ecc384PrivKeyIn::Key(key) => {
KvAccess::copy_from_kv(key, ecc.kv_rd_pkey_status(), ecc.kv_rd_pkey_ctrl())
.map_err(|err| err.into_read_priv_key_err())?
}
}
// Copy public key to registers
pub_key.x.write_to_reg(ecc.pubkey_x());
pub_key.y.write_to_reg(ecc.pubkey_y());
// Generate an IV.
let iv = trng.generate()?;
KvAccess::copy_from_arr(&iv, ecc.iv())?;
// Program the command register for ECDH
ecc.ctrl()
.write(|w| w.dh_sharedkey(true).ctrl(|w| w.none()));
// Wait for command to complete
Ecc384::wait(ecc, || ecc.status().read().valid())?;
// Copy the shared key
match &mut shared_key_out {
Ecc384PrivKeyOut::Array4x12(arr) => {
KvAccess::end_copy_to_arr(ecc.dh_shared_key(), arr)?
}
Ecc384PrivKeyOut::Key(key) => {
KvAccess::end_copy_to_kv(ecc.kv_wr_pkey_status(), *key)
.map_err(|err| err.into_write_priv_key_err())?;
}
}
self.zeroize_internal();
Ok(())
}
/// Zeroize the hardware registers.
fn zeroize_internal(&mut self) {
self.ecc.regs_mut().ctrl().write(|w| w.zeroize(true));
}
/// Zeroize the hardware registers.
///
/// This is useful to call from a fatal-error-handling routine.
///
/// # Safety
///
/// The caller must be certain that the results of any pending cryptographic
/// operations will not be used after this function is called.
///
/// This function is safe to call from a trap handler.
pub unsafe fn zeroize() {
let mut ecc = EccReg::new();
ecc.regs_mut().ctrl().write(|w| w.zeroize(true));
}
}
/// ECC-384 key access error trait
trait Ecc384KeyAccessErr {
/// Convert to read seed operation error
fn into_read_seed_err(self) -> CaliptraError;
/// Convert to read private key operation error
fn into_read_priv_key_err(self) -> CaliptraError;
/// Convert to write private key operation error
fn into_write_priv_key_err(self) -> CaliptraError;
}
impl Ecc384KeyAccessErr for KvAccessErr {
/// Convert to read seed operation error
fn into_read_seed_err(self) -> CaliptraError {
match self {
KvAccessErr::KeyRead => CaliptraError::DRIVER_ECC384_READ_SEED_KV_READ,
KvAccessErr::KeyWrite => CaliptraError::DRIVER_ECC384_READ_SEED_KV_WRITE,
KvAccessErr::Generic => CaliptraError::DRIVER_ECC384_READ_SEED_KV_UNKNOWN,
}
}
/// Convert to read private key operation error
fn into_read_priv_key_err(self) -> CaliptraError {
match self {
KvAccessErr::KeyRead => CaliptraError::DRIVER_ECC384_READ_PRIV_KEY_KV_READ,
KvAccessErr::KeyWrite => CaliptraError::DRIVER_ECC384_READ_PRIV_KEY_KV_WRITE,
KvAccessErr::Generic => CaliptraError::DRIVER_ECC384_READ_PRIV_KEY_KV_UNKNOWN,
}
}
/// Convert to write private key operation error
fn into_write_priv_key_err(self) -> CaliptraError {
match self {
KvAccessErr::KeyRead => CaliptraError::DRIVER_ECC384_WRITE_PRIV_KEY_KV_READ,
KvAccessErr::KeyWrite => CaliptraError::DRIVER_ECC384_WRITE_PRIV_KEY_KV_WRITE,
KvAccessErr::Generic => CaliptraError::DRIVER_ECC384_WRITE_PRIV_KEY_KV_UNKNOWN,
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/fuse_bank.rs | drivers/src/fuse_bank.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
fuse_bank.rs
Abstract:
File contains API for Fuse Bank.
--*/
use crate::{Array4x12, Array4x16, Array4x8};
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::Launder;
use caliptra_registers::soc_ifc::SocIfcReg;
use zerocopy::IntoBytes;
pub struct FuseBank<'a> {
pub(crate) soc_ifc: &'a SocIfcReg,
}
fn first_set_msbit(num_le: &[u32; 4]) -> u32 {
let fuse: u128 = u128::from_le_bytes(num_le.as_bytes().try_into().unwrap());
128 - fuse.leading_zeros()
}
pub enum X509KeyIdAlgo {
Sha1 = 0,
Sha256 = 1,
Sha384 = 2,
Sha512 = 3,
Fuse = 4,
}
bitflags::bitflags! {
#[derive(Default, Copy, Clone, Debug)]
#[cfg_attr(not(feature = "no-cfi"), derive(Launder))]
pub struct VendorEccPubKeyRevocation : u32 {
const KEY0 = 0b0001;
const KEY1 = 0b0010;
const KEY2 = 0b0100;
const KEY3 = 0b1000;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdevidCertAttr {
Flags = 0,
EccSubjectKeyId1 = 1,
EccSubjectKeyId2 = 2,
EccSubjectKeyId3 = 3,
EccSubjectKeyId4 = 4,
EccSubjectKeyId5 = 5,
MldsaSubjectKeyId1 = 6,
MldsaSubjectKeyId2 = 7,
MldsaSubjectKeyId3 = 8,
MldsaSubjectKeyId4 = 9,
MldsaSubjectKeyId5 = 10,
UeidType = 11,
ManufacturerSerialNumber1 = 12,
ManufacturerSerialNumber2 = 13,
ManufacturerSerialNumber3 = 14,
ManufacturerSerialNumber4 = 15,
}
impl From<IdevidCertAttr> for usize {
fn from(value: IdevidCertAttr) -> Self {
value as usize
}
}
impl FuseBank<'_> {
/// Get the key id crypto algorithm.
///
/// # Arguments
/// * `ecc_key_id_algo` - Whether to get ECC or MLDSA key id algorithm
///
/// # Returns
/// key id crypto algorithm
///
pub fn idev_id_x509_key_id_algo(&self, ecc_key_id_algo: bool) -> X509KeyIdAlgo {
let soc_ifc_regs = self.soc_ifc.regs();
let mut flags = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(IdevidCertAttr::Flags.into())
.read();
if !ecc_key_id_algo {
// ECC Key Id Algo is in Bits 0-2.
// MLDSA Key Id Algo is in Bits 3-5.
flags >>= 3;
}
match flags & 0x7 {
0 => X509KeyIdAlgo::Sha1,
1 => X509KeyIdAlgo::Sha256,
2 => X509KeyIdAlgo::Sha384,
4 => X509KeyIdAlgo::Sha512,
_ => X509KeyIdAlgo::Fuse,
}
}
/// Get the manufacturer serial number.
///
/// # Returns
/// manufacturer serial number
///
pub fn ueid(&self) -> [u8; 17] {
let soc_ifc_regs = self.soc_ifc.regs();
let ueid1 = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(IdevidCertAttr::ManufacturerSerialNumber1.into())
.read();
let ueid2 = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(IdevidCertAttr::ManufacturerSerialNumber2.into())
.read();
let ueid3 = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(IdevidCertAttr::ManufacturerSerialNumber3.into())
.read();
let ueid4 = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(IdevidCertAttr::ManufacturerSerialNumber4.into())
.read();
let ueid_type = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(IdevidCertAttr::UeidType.into())
.read() as u8;
let mut ueid = [0u8; 17];
ueid[0] = ueid_type;
ueid[1..5].copy_from_slice(&ueid1.to_le_bytes());
ueid[5..9].copy_from_slice(&ueid2.to_le_bytes());
ueid[9..13].copy_from_slice(&ueid3.to_le_bytes());
ueid[13..].copy_from_slice(&ueid4.to_le_bytes());
ueid
}
/// Get the subject key identifier.
///
/// # Arguments
/// * `ecc_subject_key_id` - Whether to get ECC or MLDSA subject key identifier
///
/// # Returns
/// subject key identifier
///
pub fn subject_key_id(&self, ecc_subject_key_id: bool) -> [u8; 20] {
let key_id = if ecc_subject_key_id {
[
IdevidCertAttr::EccSubjectKeyId1,
IdevidCertAttr::EccSubjectKeyId2,
IdevidCertAttr::EccSubjectKeyId3,
IdevidCertAttr::EccSubjectKeyId4,
IdevidCertAttr::EccSubjectKeyId5,
]
} else {
[
IdevidCertAttr::MldsaSubjectKeyId1,
IdevidCertAttr::MldsaSubjectKeyId2,
IdevidCertAttr::MldsaSubjectKeyId3,
IdevidCertAttr::MldsaSubjectKeyId4,
IdevidCertAttr::MldsaSubjectKeyId5,
]
};
let soc_ifc_regs = self.soc_ifc.regs();
let subkeyid1 = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(key_id[0].into())
.read();
let subkeyid2 = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(key_id[1].into())
.read();
let subkeyid3 = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(key_id[2].into())
.read();
let subkeyid4 = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(key_id[3].into())
.read();
let subkeyid5 = soc_ifc_regs
.fuse_idevid_cert_attr()
.at(key_id[4].into())
.read();
let mut subject_key_id = [0u8; 20];
subject_key_id[..4].copy_from_slice(&subkeyid1.to_le_bytes());
subject_key_id[4..8].copy_from_slice(&subkeyid2.to_le_bytes());
subject_key_id[8..12].copy_from_slice(&subkeyid3.to_le_bytes());
subject_key_id[12..16].copy_from_slice(&subkeyid4.to_le_bytes());
subject_key_id[16..20].copy_from_slice(&subkeyid5.to_le_bytes());
subject_key_id
}
/// Get the vendor public key info hash.
///
/// # Returns
/// vendor public key info hash
///
pub fn vendor_pub_key_info_hash(&self) -> Array4x12 {
let soc_ifc_regs = self.soc_ifc.regs();
Array4x12::read_from_reg(soc_ifc_regs.fuse_vendor_pk_hash())
}
/// Get the ecc vendor public key revocation mask.
///
/// # Returns
/// ecc vendor public key revocation mask
///
pub fn vendor_ecc_pub_key_revocation(&self) -> VendorEccPubKeyRevocation {
let soc_ifc_regs = self.soc_ifc.regs();
VendorEccPubKeyRevocation::from_bits_truncate(
soc_ifc_regs.fuse_ecc_revocation().read().into(),
)
}
/// Get the lms vendor public key revocation mask.
///
/// # Returns
/// lms vendor public key revocation mask
///
pub fn vendor_lms_pub_key_revocation(&self) -> u32 {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs.fuse_lms_revocation().read()
}
/// Get the mldsa vendor public key revocation mask.
///
/// # Returns
/// mldsa vendor public key revocation mask
///
pub fn vendor_mldsa_pub_key_revocation(&self) -> u32 {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs.fuse_mldsa_revocation().read().into()
}
/// Get the owner public key hash.
///
/// # Returns
/// owner public key hash
///
pub fn owner_pub_key_hash(&self) -> Array4x12 {
let soc_ifc_regs = self.soc_ifc.regs();
Array4x12::read_from_reg(soc_ifc_regs.cptra_owner_pk_hash())
}
/// Get the rollback disability setting.
///
/// # Returns
/// rollback disability setting
///
pub fn anti_rollback_disable(&self) -> bool {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs.fuse_anti_rollback_disable().read().dis()
}
/// Get the firmware fuse security version number.
///
/// # Returns
/// firmware security version number
///
pub fn fw_fuse_svn(&self) -> u32 {
let soc_ifc_regs = self.soc_ifc.regs();
// The legacy name of this register is `fuse_runtime_svn`
first_set_msbit(&soc_ifc_regs.fuse_runtime_svn().read())
}
/// Get the SoC manifest fuse security version number.
///
/// # Returns
/// SoC manifest security version number
///
pub fn soc_manifest_fuse_svn(&self) -> u32 {
let soc_ifc_regs = self.soc_ifc.regs();
first_set_msbit(&soc_ifc_regs.fuse_soc_manifest_svn().read())
}
/// Get the maximum SoC manifest fuse security version number.
///
/// # Returns
/// Maximum SoC manifest security version number
///
pub fn max_soc_manifest_fuse_svn(&self) -> u32 {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs.fuse_soc_manifest_max_svn().read().svn()
}
/// Get the lms revocation bits.
///
/// # Returns
/// lms revocation bits
///
pub fn lms_revocation(&self) -> u32 {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs.fuse_lms_revocation().read()
}
/// Get the PQC (MLDSA or LMS) key type.
///
/// # Returns
/// PQC key type set in the fuses.
///
pub fn pqc_key_type(&self) -> u32 {
self.soc_ifc.regs().fuse_pqc_key_type().read().into()
}
/// Get the manufacturing debug unlock token
///
/// # Arguments
/// * None
///
/// # Returns
/// manufacturing debug unlock token
///
pub fn manuf_dbg_unlock_token(&self) -> Array4x16 {
let soc_ifc_regs = self.soc_ifc.regs();
Array4x16::read_from_reg(soc_ifc_regs.fuse_manuf_dbg_unlock_token())
}
/// Get the OCP HEK Seed
///
/// # Arguments
/// * None
///
/// # Returns
/// OCP HEK Seed
pub fn ocp_hek_seed(&self) -> Array4x8 {
let soc_ifc_regs = self.soc_ifc.regs();
Array4x8::read_from_reg(soc_ifc_regs.fuse_hek_seed())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_first_set_msbit() {
let mut svn: u128 = 0;
let mut svn_arr: [u32; 4] = [0u32, 0u32, 0u32, 0u32];
for i in 0..128 {
for (idx, word) in svn_arr.iter_mut().enumerate() {
*word = u32::from_le_bytes(svn.as_bytes()[idx * 4..][..4].try_into().unwrap())
}
let result = first_set_msbit(&svn_arr);
assert_eq!(result, i);
svn = (svn << 1) | 1;
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/trng_ext.rs | drivers/src/trng_ext.rs | // Licensed under the Apache-2.0 license
use caliptra_error::{CaliptraError, CaliptraResult};
use caliptra_registers::soc_ifc_trng::SocIfcTrngReg;
use crate::Array4x12;
pub struct TrngExt {
soc_ifc_trng: SocIfcTrngReg,
}
impl TrngExt {
pub fn new(soc_ifc_trng: SocIfcTrngReg) -> Self {
Self { soc_ifc_trng }
}
pub fn generate(&mut self) -> CaliptraResult<Array4x12> {
const MAX_CYCLES_TO_WAIT: u32 = 250000;
let regs = self.soc_ifc_trng.regs_mut();
regs.cptra_trng_status().write(|w| w.data_req(true));
let mut cycles = 0;
while !regs.cptra_trng_status().read().data_wr_done() {
cycles += 1;
if cycles >= MAX_CYCLES_TO_WAIT {
return Err(CaliptraError::DRIVER_TRNG_EXT_TIMEOUT);
}
}
let result = Array4x12::read_from_reg(regs.cptra_trng_data());
regs.cptra_trng_status().write(|w| w.data_req(false));
Ok(result)
}
pub fn generate4(&mut self) -> CaliptraResult<(u32, u32, u32, u32)> {
const MAX_CYCLES_TO_WAIT: u32 = 250000;
let regs = self.soc_ifc_trng.regs_mut();
regs.cptra_trng_status().write(|w| w.data_req(true));
let mut cycles = 0;
while !regs.cptra_trng_status().read().data_wr_done() {
cycles += 1;
if cycles >= MAX_CYCLES_TO_WAIT {
return Err(CaliptraError::DRIVER_TRNG_EXT_TIMEOUT);
}
}
let a = regs.cptra_trng_data().at(0).read();
let b = regs.cptra_trng_data().at(1).read();
let c = regs.cptra_trng_data().at(2).read();
let d = regs.cptra_trng_data().at(3).read();
regs.cptra_trng_status().write(|w| w.data_req(false));
Ok((a, b, c, d))
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/mailbox.rs | drivers/src/mailbox.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
mailbox.rs
Abstract:
File contains API for Mailbox operations
--*/
use crate::{memory_layout, SocIfc};
use crate::{CaliptraError, CaliptraResult};
use caliptra_registers::mbox::enums::MboxFsmE;
use caliptra_registers::mbox::enums::MboxStatusE;
use caliptra_registers::mbox::MboxCsr;
use caliptra_registers::soc_ifc::SocIfcReg;
use core::cmp::min;
use core::mem::size_of;
use core::slice;
use zerocopy::{FromBytes, IntoBytes, Unalign};
/// Mailbox size when in subsystem mode.
pub const MBOX_SIZE_SUBSYSTEM: u32 = 16 * 1024;
// /// Mailbox size when in passive mode.
pub const MBOX_SIZE_PASSIVE: u32 = 256 * 1024;
#[derive(Copy, Clone, Default, Eq, PartialEq)]
/// Malbox operational states
pub enum MailboxOpState {
#[default]
RdyForCmd,
RdyForDlen,
RdyForData,
Execute,
Idle,
}
/// Caliptra mailbox abstraction
pub struct Mailbox {
mbox: MboxCsr,
mbox_len: u32,
}
impl Mailbox {
pub fn new(mbox: MboxCsr) -> Self {
let mbox_len = Self::get_mbox_size();
Self { mbox, mbox_len }
}
/// Get the mailbox size based on hardware revision
pub fn get_mbox_size() -> u32 {
let soc_ifc = unsafe { SocIfc::new(SocIfcReg::new()) };
if soc_ifc.subsystem_mode() {
MBOX_SIZE_SUBSYSTEM
} else {
MBOX_SIZE_PASSIVE
}
}
/// Attempt to acquire the lock to start sending data.
/// # Returns
/// * `MailboxSendTxn` - Object representing a send operation
pub fn try_start_send_txn(&mut self) -> Option<MailboxSendTxn> {
let mbox = self.mbox.regs();
if mbox.lock().read().lock() {
None
} else {
Some(MailboxSendTxn {
state: MailboxOpState::default(),
mbox: &mut self.mbox,
mbox_len: self.mbox_len,
})
}
}
/// Waits until the uC can acquire the lock to start sending data.
/// # Returns
/// * `MailboxSendTxn` - Object representing a send operation
pub fn wait_until_start_send_txn(&mut self) -> MailboxSendTxn {
let mbox = self.mbox.regs();
while mbox.lock().read().lock() {}
MailboxSendTxn {
state: MailboxOpState::default(),
mbox: &mut self.mbox,
mbox_len: self.mbox_len,
}
}
/// Attempts to start receiving data by checking the status.
/// # Returns
/// * 'MailboxRecvTxn' - Object representing a receive operation
pub fn try_start_recv_txn(&mut self) -> Option<MailboxRecvTxn> {
let mbox = self.mbox.regs();
match mbox.status().read().mbox_fsm_ps() {
MboxFsmE::MboxExecuteUc => Some(MailboxRecvTxn {
state: MailboxOpState::Execute,
mbox: &mut self.mbox,
mbox_len: self.mbox_len,
recovery_transaction: false,
}),
_ => None,
}
}
// Fake mailbox transaction used when downloading firmware image from Recovery Interface.
pub fn recovery_recv_txn(&mut self) -> MailboxRecvTxn {
// Acquire the lock as the DMA engine will be writing to the mailbox sram.
let mbox = self.mbox.regs();
while mbox.lock().read().lock() {}
MailboxRecvTxn {
state: MailboxOpState::Execute,
mbox: &mut self.mbox,
mbox_len: self.mbox_len,
recovery_transaction: true,
}
}
/// Lets the caller peek into the mailbox without touching the transaction.
pub fn peek_recv(&mut self) -> Option<MailboxRecvPeek> {
let mbox = self.mbox.regs();
match mbox.status().read().mbox_fsm_ps() {
MboxFsmE::MboxExecuteUc => Some(MailboxRecvPeek {
mbox: &mut self.mbox,
mbox_len: self.mbox_len,
}),
_ => None,
}
}
/// Aborts with failure any pending SoC->Uc transactions.
///
/// This is useful to call from a fatal-error-handling routine.
///
/// # Safety
///
/// Callers must guarantee that no other code is interacting with the
/// mailbox at the time this function is called. (For example, any
/// MailboxRecvTxn and MailboxSendTxn instances have been destroyed or
/// forgotten).
///
/// This function is safe to call from a trap handler.
pub unsafe fn abort_pending_soc_to_uc_transactions() {
let mut mbox = MboxCsr::new();
if mbox.regs().status().read().mbox_fsm_ps().mbox_execute_uc() {
// SoC firmware might be stuck waiting for Caliptra to finish
// executing this pending mailbox transaction. Notify them that
// we've failed.
mbox.regs_mut()
.status()
.write(|w| w.status(|w| w.cmd_failure()));
}
}
}
/// Mailbox send protocol abstraction
pub struct MailboxSendTxn<'a> {
/// Current state.
state: MailboxOpState,
mbox: &'a mut MboxCsr,
mbox_len: u32,
}
impl MailboxSendTxn<'_> {
///
/// Transitions from RdyCmd --> RdyForDlen
///
pub fn write_cmd(&mut self, cmd: u32) -> CaliptraResult<()> {
if self.state != MailboxOpState::RdyForCmd {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_STATE);
}
let mbox = self.mbox.regs_mut();
// Write Command :
mbox.cmd().write(|_| cmd);
self.state = MailboxOpState::RdyForDlen;
Ok(())
}
///
/// Writes number of bytes to data length register.
/// Transitions from RdyForDlen --> RdyForData
///
pub fn write_dlen(&mut self, dlen: u32) -> CaliptraResult<()> {
if self.state != MailboxOpState::RdyForDlen {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_STATE);
}
let mbox = self.mbox.regs_mut();
if dlen > self.mbox_len {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_DATA_LEN);
}
// Write Len in Bytes
mbox.dlen().write(|_| dlen);
self.state = MailboxOpState::RdyForData;
Ok(())
}
/// Transitions mailbox to RdyForData state and copies data to mailbox.
/// * 'cmd' - Command to Be Sent
/// * 'data' - Data Bufer
pub fn copy_request(&mut self, cmd: u32, data: &[u8]) -> CaliptraResult<()> {
if self.state != MailboxOpState::RdyForCmd {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_STATE);
}
self.write_cmd(cmd)?;
self.write_dlen(data.len() as u32)?;
// Copy data to mailbox
fifo::enqueue(self.mbox, data)?;
self.state = MailboxOpState::RdyForData;
Ok(())
}
///
/// Transitions from RdyForData --> Execute
///
pub fn execute_request(&mut self) -> CaliptraResult<()> {
if self.state != MailboxOpState::RdyForData {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_STATE);
}
let mbox = self.mbox.regs_mut();
// Set Execute Bit
mbox.execute().write(|w| w.execute(true));
self.state = MailboxOpState::Execute;
Ok(())
}
/// Send Data to SOC
/// * 'cmd' - Command to Be Sent
/// * 'data' - Data Bufer
pub fn send_request(&mut self, cmd: u32, data: &[u8]) -> CaliptraResult<()> {
self.copy_request(cmd, data)?;
self.execute_request()?;
Ok(())
}
/// Checks if receiver processed the request.
pub fn is_response_ready(&self) -> bool {
// TODO: Handle MboxStatusE::DataReady
let mbox = self.mbox.regs();
matches!(
mbox.status().read().status(),
MboxStatusE::CmdComplete | MboxStatusE::CmdFailure
)
}
pub fn status(&self) -> MboxStatusE {
let mbox = self.mbox.regs();
mbox.status().read().status()
}
///
/// Transitions from Execute --> Idle (releases the lock)
///
pub fn complete(&mut self) -> CaliptraResult<()> {
if self.state != MailboxOpState::Execute {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_STATE);
}
let mbox = self.mbox.regs_mut();
mbox.execute().write(|w| w.execute(false));
self.state = MailboxOpState::Idle;
Ok(())
}
}
impl Drop for MailboxSendTxn<'_> {
fn drop(&mut self) {
let mbox = self.mbox.regs_mut();
//
// Release the lock by transitioning the mailbox state machine back
// to Idle.
//
if mbox.status().read().mbox_fsm_ps() != MboxFsmE::MboxIdle {
mbox.unlock().write(|w| w.unlock(true));
}
}
}
pub struct MailboxRecvPeek<'a> {
mbox: &'a mut MboxCsr,
mbox_len: u32,
}
impl<'a> MailboxRecvPeek<'a> {
/// Returns the value stored in the command register
pub fn cmd(&self) -> u32 {
let mbox = self.mbox.regs();
mbox.cmd().read()
}
/// Returns the value stored in the user register
pub fn id(&self) -> u32 {
let mbox = self.mbox.regs();
mbox.user().read()
}
/// Returns the value stored in the data length register. This is the total
/// size of the mailbox data in bytes.
pub fn dlen(&self) -> u32 {
let mbox = self.mbox.regs();
mbox.dlen().read()
}
pub fn start_txn(self) -> MailboxRecvTxn<'a> {
MailboxRecvTxn {
state: MailboxOpState::Execute,
mbox: self.mbox,
mbox_len: self.mbox_len,
recovery_transaction: false,
}
}
}
/// Mailbox Fifo abstraction
mod fifo {
use super::*;
fn dequeue_words(mbox: &mut MboxCsr, buf: &mut [Unalign<u32>]) {
let mbox = mbox.regs_mut();
for word in buf.iter_mut() {
*word = Unalign::new(mbox.dataout().read());
}
}
pub fn dequeue(mbox: &mut MboxCsr, mut buf: &mut [u8]) {
let dlen_bytes = mbox.regs().dlen().read() as usize;
if dlen_bytes < buf.len() {
buf = &mut buf[..dlen_bytes];
}
let len_words = buf.len() / size_of::<u32>();
let (buf_words, suffix) =
<[Unalign<u32>]>::mut_from_prefix_with_elems(buf, len_words).unwrap();
dequeue_words(mbox, buf_words);
if !suffix.is_empty() && suffix.len() <= size_of::<u32>() {
let last_word = mbox.regs().dataout().read();
let suffix_len = suffix.len();
suffix
.as_mut_bytes()
.copy_from_slice(&last_word.as_bytes()[..suffix_len]);
}
}
fn enqueue_words(mbox: &mut MboxCsr, buf: &[Unalign<u32>]) {
let mbox = mbox.regs_mut();
for word in buf {
mbox.datain().write(|_| word.get());
}
}
/// Writes buf.len() bytes to the mailbox datain reg as dwords
#[inline(never)]
pub fn enqueue(mbox: &mut MboxCsr, buf: &[u8]) -> CaliptraResult<()> {
if mbox.regs().dlen().read() as usize != buf.len() {
return Err(CaliptraError::DRIVER_MAILBOX_ENQUEUE_ERR);
}
let count = buf.len() / size_of::<u32>();
let (buf_words, suffix) = <[Unalign<u32>]>::ref_from_prefix_with_elems(buf, count).unwrap();
enqueue_words(mbox, buf_words);
if !suffix.is_empty() && suffix.len() <= size_of::<u32>() {
let mut last_word = 0_u32;
last_word.as_mut_bytes()[..suffix.len()].copy_from_slice(suffix);
enqueue_words(mbox, &[Unalign::new(last_word)]);
}
Ok(())
}
}
/// Mailbox recveive protocol abstraction
pub struct MailboxRecvTxn<'a> {
/// Current state of transaction
state: MailboxOpState,
mbox: &'a mut MboxCsr,
mbox_len: u32,
recovery_transaction: bool,
}
impl MailboxRecvTxn<'_> {
/// Returns the value stored in the command register
pub fn cmd(&self) -> u32 {
let mbox = self.mbox.regs();
mbox.cmd().read()
}
/// Returns the value stored in the data length register. This is the total
/// size of the mailbox data in bytes.
pub fn dlen(&self) -> u32 {
let mbox = self.mbox.regs();
mbox.dlen().read()
}
/// Provides direct access to entire mailbox SRAM.
pub fn raw_mailbox_contents(&self) -> &[u8] {
unsafe {
slice::from_raw_parts(memory_layout::MBOX_ORG as *const u8, self.mbox_len as usize)
}
}
/// Pulls at most `count` words from the mailbox and throws them away
pub fn drop_words(&mut self, count: usize) -> CaliptraResult<()> {
let mbox = self.mbox.regs_mut();
let dlen_bytes = mbox.dlen().read() as usize;
let dlen_words = (dlen_bytes + 3) / 4;
let words_to_read = min(count, dlen_words);
for _ in 0..words_to_read {
_ = mbox.dataout().read();
}
Ok(())
}
/// Writes number of bytes to data length register.
fn write_dlen(&mut self, dlen: u32) -> CaliptraResult<()> {
if self.state != MailboxOpState::RdyForDlen {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_STATE);
}
let mbox = self.mbox.regs_mut();
if dlen > self.mbox_len {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_DATA_LEN);
}
// Write Len in Bytes
mbox.dlen().write(|_| dlen);
Ok(())
}
/// Pulls at most `(data.len() + 3) / 4` words from the mailbox FIFO without
/// performing state transition.
///
/// # Arguments
///
/// * `data` - data buffer.
///
/// # Returns
///
/// Status of Operation
///
pub fn copy_request(&mut self, data: &mut [u8]) -> CaliptraResult<()> {
if self.state != MailboxOpState::Execute {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_STATE);
}
fifo::dequeue(self.mbox, data);
if mailbox_uncorrectable_ecc() {
return Err(CaliptraError::DRIVER_MAILBOX_UNCORRECTABLE_ECC);
}
Ok(())
}
/// Pulls at most `(data.len() + 3) / 4` words from the mailbox FIFO.
/// Transitions from Execute --> Idle (releases the lock)
///
/// # Arguments
///
/// * `data` - data buffer.
///
/// # Returns
///
/// Status of Operation
///
pub fn recv_request(&mut self, data: &mut [u8]) -> CaliptraResult<()> {
self.copy_request(data)?;
self.complete(true)
}
/// Sends `data.len()` bytes to the mailbox FIFO
/// Transitions from Execute --> RdyForData
///
/// # Arguments
///
/// * `data` - data buffer.
///
/// # Returns
///
/// Status of Operation
///
fn copy_response(&mut self, data: &[u8]) -> CaliptraResult<()> {
if self.state != MailboxOpState::Execute {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_STATE);
}
self.state = MailboxOpState::RdyForDlen;
// Set dlen
self.write_dlen(data.len() as u32)?;
self.state = MailboxOpState::RdyForData;
// Copy the data
fifo::enqueue(self.mbox, data)
}
/// Sends `data.len()` bytes to the mailbox FIFO.
/// Transitions from Execute --> Idle (releases the lock)
///
/// # Arguments
///
/// * `data` - data buffer.
///
/// # Returns
///
/// Status of Operation
///
pub fn send_response(&mut self, data: &[u8]) -> CaliptraResult<()> {
self.copy_response(data)?;
self.complete(true)
}
///
/// Transitions from Execute or RdyForData-> Idle
///
/// Does not take ownership of self, unlike complete()
pub fn complete(&mut self, success: bool) -> CaliptraResult<()> {
// If this is a recovery transaction, we need to release the lock that was acquired for the
// DMA engine to write data to the mailbox sram. No state transition is needed if this is
// a recovery transaction.
if self.recovery_transaction {
let mbox = self.mbox.regs_mut();
mbox.unlock().write(|w| w.unlock(true));
return Ok(());
}
if self.state != MailboxOpState::Execute && self.state != MailboxOpState::RdyForData {
return Err(CaliptraError::DRIVER_MAILBOX_INVALID_STATE);
}
let status = if success {
if self.state == MailboxOpState::RdyForData {
MboxStatusE::DataReady
} else {
MboxStatusE::CmdComplete
}
} else {
MboxStatusE::CmdFailure
};
let mbox = self.mbox.regs_mut();
mbox.status().write(|w| w.status(|_| status));
self.state = MailboxOpState::Idle;
Ok(())
}
///
/// Set UC TAP unlock
///
pub fn set_uc_tap_unlock(&mut self, enable: bool) {
let mbox = self.mbox.regs_mut();
mbox.tap_mode().modify(|w| w.enabled(enable))
}
}
impl Drop for MailboxRecvTxn<'_> {
fn drop(&mut self) {
if self.state != MailboxOpState::Idle {
// Execute -> Idle (releases lock)
let _ = self.complete(false);
}
}
}
fn mailbox_uncorrectable_ecc() -> bool {
unsafe {
SocIfcReg::new()
.regs()
.intr_block_rf()
.error_internal_intr_r()
.read()
.error_mbox_ecc_unc_sts()
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/lib.rs | drivers/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains exports for for Caliptra Library.
--*/
#![cfg_attr(not(feature = "std"), no_std)]
mod array;
mod array_concat;
mod wait;
mod aes;
mod bounded_address;
pub mod cmac_kdf;
mod csrng;
mod data_vault;
pub mod dma;
mod doe;
mod ecc384;
mod error_reporter;
mod exit_ctrl;
#[cfg(feature = "fips-test-hooks")]
pub mod fips_test_hooks;
mod fuse_bank;
pub mod fuse_log;
pub mod hand_off;
mod hkdf;
mod hmac;
mod hmac_kdf;
mod key_vault;
mod kv_access;
mod lms;
mod mailbox;
pub mod memory_layout;
mod ml_kem;
mod mldsa87;
pub mod ocp_lock;
mod okref;
mod pcr_bank;
pub mod pcr_log;
pub mod pcr_reset;
mod persistent;
pub mod pic;
pub mod preconditioned_key;
pub mod printer;
mod sha1;
mod sha256;
pub mod sha2_512_384;
mod sha2_512_384acc;
mod sha3;
mod soc_ifc;
mod trng;
mod trng_ext;
pub use aes::{
Aes, AesContext, AesGcmContext, AesGcmIv, AesKey, AesOperation, AES_BLOCK_SIZE_BYTES,
AES_BLOCK_SIZE_WORDS, AES_CONTEXT_SIZE_BYTES, AES_GCM_CONTEXT_SIZE_BYTES,
};
pub use array::{
Array4x12, Array4x16, Array4x4, Array4x5, Array4x8, Array4xN, LEArray4x1157, LEArray4x16,
LEArray4x3, LEArray4x392, LEArray4x4, LEArray4x648, LEArray4x792, LEArray4x8,
};
pub use array_concat::array_concat3;
pub use bounded_address::{BoundedAddr, MemBounds, RomAddr};
pub use caliptra_error::{CaliptraError, CaliptraResult};
pub use cmac_kdf::cmac_kdf;
pub use csrng::{
Csrng, HealthFailCounts as CsrngHealthFailCounts, Seed as CsrngSeed, MAX_SEED_WORDS,
};
pub use data_vault::{ColdResetEntries, DataVault, WarmResetEntries};
pub use dma::{
AesDmaMode, AxiAddr, Dma, DmaMmio, DmaOtpCtrl, DmaReadTarget, DmaReadTransaction, DmaRecovery,
DmaWriteOrigin, DmaWriteTransaction,
};
pub use doe::DeobfuscationEngine;
pub use ecc384::{
Ecc384, Ecc384PrivKeyIn, Ecc384PrivKeyOut, Ecc384PubKey, Ecc384Result, Ecc384Scalar,
Ecc384Seed, Ecc384Signature,
};
pub use error_reporter::{
clear_fw_error_non_fatal, get_fw_error_non_fatal, report_fw_error_fatal,
report_fw_error_non_fatal,
};
pub use exit_ctrl::ExitCtrl;
#[cfg(feature = "fips-test-hooks")]
pub use fips_test_hooks::FipsTestHook;
pub use fuse_bank::{FuseBank, IdevidCertAttr, VendorEccPubKeyRevocation, X509KeyIdAlgo};
pub use hand_off::FirmwareHandoffTable;
pub use hkdf::{hkdf_expand, hkdf_extract};
pub use hmac::{Hmac, HmacData, HmacKey, HmacMode, HmacOp, HmacTag};
pub use hmac_kdf::hmac_kdf;
pub use key_vault::{KeyId, KeyUsage, KeyVault};
pub use kv_access::{KeyReadArgs, KeyWriteArgs};
pub use lms::{
get_lmots_parameters, get_lms_parameters, HashValue, Lms, LmsResult, Sha192Digest,
Sha256Digest, D_INTR, D_LEAF, D_MESG, D_PBLC,
};
pub use mailbox::{
Mailbox, MailboxRecvTxn, MailboxSendTxn, MBOX_SIZE_PASSIVE, MBOX_SIZE_SUBSYSTEM,
};
pub use ml_kem::{
MlKem1024, MlKem1024Ciphertext, MlKem1024DecapsKey, MlKem1024EncapsKey, MlKem1024Message,
MlKem1024MessageSource, MlKem1024Seed, MlKem1024Seeds, MlKem1024SharedKey,
MlKem1024SharedKeyOut, MlKemResult,
};
pub use mldsa87::{
Mldsa87, Mldsa87Msg, Mldsa87PrivKey, Mldsa87PubKey, Mldsa87Result, Mldsa87Seed, Mldsa87SignRnd,
Mldsa87Signature,
};
pub use ocp_lock::HekSeedState;
pub use okref::okmutref;
pub use okref::okref;
pub use pcr_bank::{PcrBank, PcrId};
pub use pcr_reset::PcrResetCounter;
pub use persistent::fmc_alias_csr::FmcAliasCsrs;
#[cfg(any(feature = "fmc", feature = "runtime"))]
pub use persistent::FwPersistentData;
#[cfg(feature = "runtime")]
pub use persistent::{AuthManifestImageMetadataList, ExportedCdiEntry, ExportedCdiHandles};
pub use persistent::{
Ecc384IdevIdCsr, FuseLogArray, InitDevIdCsrEnvelope, Mldsa87IdevIdCsr, PcrLogArray,
PersistentData, PersistentDataAccessor, RomPersistentData, StashMeasurementArray,
ECC384_MAX_FMC_ALIAS_CSR_SIZE, ECC384_MAX_IDEVID_CSR_SIZE, FUSE_LOG_MAX_COUNT,
MEASUREMENT_MAX_COUNT, MLDSA87_MAX_CSR_SIZE, PCR_LOG_MAX_COUNT,
};
pub use pic::{IntSource, Pic};
pub use sha1::{Sha1, Sha1Digest, Sha1DigestOp};
pub use sha256::{Sha256, Sha256Alg, Sha256DigestOp};
pub use sha2_512_384::{Sha2DigestOp, Sha2_512_384, Sha384Digest};
pub use sha2_512_384acc::{Sha2_512_384Acc, Sha2_512_384AccOp, ShaAccLockState, StreamEndianness};
pub use sha3::{Sha3, Sha3DigestOp};
pub use soc_ifc::{report_boot_status, CptraGeneration, Lifecycle, MfgFlags, ResetReason, SocIfc};
pub use trng::Trng;
#[allow(unused_imports)]
#[cfg(all(not(feature = "runtime"), not(feature = "no-cfi")))]
use caliptra_cfi_derive;
#[allow(unused_imports)]
#[cfg(all(feature = "runtime", not(feature = "no-cfi")))]
use caliptra_cfi_derive_git as caliptra_cfi_derive;
#[allow(unused_imports)]
#[cfg(all(not(feature = "runtime"), not(feature = "no-cfi")))]
use caliptra_cfi_lib;
#[allow(unused_imports)]
#[cfg(all(feature = "runtime", not(feature = "no-cfi")))]
use caliptra_cfi_lib_git as caliptra_cfi_lib;
cfg_if::cfg_if! {
if #[cfg(feature = "emu")] {
mod uart;
pub use uart::Uart;
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/ocp_lock.rs | drivers/src/ocp_lock.rs | // Licensed under the Apache-2.0 license
use caliptra_error::CaliptraError;
use crate::{Array4x8, Lifecycle};
#[derive(Debug)]
pub enum HekSeedState {
Empty,
Zeroized,
Corrupted,
Programmed,
Unerasable,
}
impl TryFrom<u16> for HekSeedState {
type Error = CaliptraError;
fn try_from(value: u16) -> Result<Self, Self::Error> {
// Values defined in OCP LOCK spec v1.0
// Table 15
match value {
0x0 => Ok(HekSeedState::Empty),
0x1 => Ok(HekSeedState::Zeroized),
0x2 => Ok(HekSeedState::Corrupted),
0x3 => Ok(HekSeedState::Programmed),
0x4 => Ok(HekSeedState::Unerasable),
_ => Err(CaliptraError::DRIVER_OCP_LOCK_COLD_RESET_INVALID_HEK_SEED),
}
}
}
impl From<HekSeedState> for u16 {
fn from(value: HekSeedState) -> Self {
match value {
HekSeedState::Empty => 0x0,
HekSeedState::Zeroized => 0x1,
HekSeedState::Corrupted => 0x2,
HekSeedState::Programmed => 0x3,
HekSeedState::Unerasable => 0x4,
}
}
}
impl From<&HekSeedState> for u16 {
fn from(value: &HekSeedState) -> Self {
match value {
HekSeedState::Empty => 0x0,
HekSeedState::Zeroized => 0x1,
HekSeedState::Corrupted => 0x2,
HekSeedState::Programmed => 0x3,
HekSeedState::Unerasable => 0x4,
}
}
}
impl HekSeedState {
/// Checks if HEK is available based on the HEK seed state and the Caliptra lifecycle state.
///
/// Section 4.6.4.1 of the OCP LOCK v1.0 spec.
pub fn hek_is_available(&self, lifecycle_state: Lifecycle, hek_seed_value: &Array4x8) -> bool {
let seed_is_empty = *hek_seed_value == Array4x8::default()
|| *hek_seed_value == Array4x8::from([u32::MAX; 8]);
match (self, lifecycle_state, seed_is_empty) {
// HEK is always available in these life cycle states.
(_, Lifecycle::Unprovisioned | Lifecycle::Manufacturing, _) => true,
// Actual seed must not be zeroized when drive declares seed state is programmed.
(Self::Programmed, Lifecycle::Production, false) => true,
// HEK is Unerasable so it's okay if the actual seed is zeroized.
(Self::Unerasable, Lifecycle::Production, _) => true,
_ => false,
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/soc_ifc.rs | drivers/src/soc_ifc.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
state.rs
Abstract:
File contains Device state related API
--*/
use crate::Array4x12;
use bitfield::size_of;
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::Launder;
use caliptra_error::{CaliptraError, CaliptraResult};
use caliptra_registers::soc_ifc::enums::DeviceLifecycleE;
use caliptra_registers::soc_ifc::{self, SocIfcReg};
use crate::{memory_layout, FuseBank};
pub type Lifecycle = DeviceLifecycleE;
pub fn report_boot_status(val: u32) {
let mut soc_ifc = unsafe { soc_ifc::SocIfcReg::new() };
// Save the boot status in DCCM.
unsafe {
let ptr = memory_layout::BOOT_STATUS_ORG as *mut u32;
*ptr = val;
};
// For testability, save the boot status in the boot status register only if debugging is enabled.
if !soc_ifc.regs().cptra_security_state().read().debug_locked() {
soc_ifc.regs_mut().cptra_boot_status().write(|_| val);
}
}
pub fn reset_reason() -> ResetReason {
let soc_ifc = unsafe { SocIfcReg::new() };
let soc_ifc_regs = soc_ifc.regs();
let bit0 = soc_ifc_regs.cptra_reset_reason().read().fw_upd_reset();
let bit1 = soc_ifc_regs.cptra_reset_reason().read().warm_reset();
match (bit0, bit1) {
(true, true) => ResetReason::Unknown,
(false, true) => ResetReason::WarmReset,
(true, false) => ResetReason::UpdateReset,
(false, false) => ResetReason::ColdReset,
}
}
/// Device State
pub struct SocIfc {
soc_ifc: SocIfcReg,
}
impl SocIfc {
pub fn new(soc_ifc: SocIfcReg) -> Self {
Self { soc_ifc }
}
/// Retrieve the device lifecycle state
pub fn lifecycle(&self) -> Lifecycle {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs
.cptra_security_state()
.read()
.device_lifecycle()
}
/// Check if device is locked for debug
pub fn debug_locked(&self) -> bool {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs.cptra_security_state().read().debug_locked()
}
/// Subsystem debug intent
pub fn ss_debug_intent(&self) -> bool {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs.ss_debug_intent().read().debug_intent()
}
/// Subsystem debug unlock requested
pub fn ss_debug_unlock_req(&self) -> CaliptraResult<bool> {
if !self.ss_debug_intent() {
return Ok(false);
}
let soc_ifc_regs = self.soc_ifc.regs();
let lifecycle = self.lifecycle();
let dbg_req = soc_ifc_regs.ss_dbg_service_reg_req().read();
let (manuf, prod) = (
dbg_req.manuf_dbg_unlock_req(),
dbg_req.prod_dbg_unlock_req(),
);
match (manuf, prod, lifecycle) {
(true, false, Lifecycle::Manufacturing) | (false, true, Lifecycle::Production) => {
Ok(true)
}
(true, true, _) | (true, false, _) | (false, true, _) => {
Err(CaliptraError::SS_DBG_UNLOCK_INVALID_REQ_REG_VALUE)
}
(false, false, _) => Ok(false),
}
}
/// Set debug unlock in progress
pub fn set_ss_dbg_unlock_in_progress(&mut self, in_progress: bool) {
let lifecycle = self.lifecycle();
let soc_ifc_regs = self.soc_ifc.regs_mut();
match lifecycle {
Lifecycle::Manufacturing => soc_ifc_regs.ss_dbg_service_reg_rsp().modify(|w| {
w.tap_mailbox_available(in_progress)
.manuf_dbg_unlock_in_progress(in_progress)
}),
DeviceLifecycleE::Production => soc_ifc_regs.ss_dbg_service_reg_rsp().modify(|w| {
w.tap_mailbox_available(in_progress)
.prod_dbg_unlock_in_progress(in_progress)
}),
_ => (),
}
}
/// Set debug unlock with either failure or success
pub fn set_ss_dbg_unlock_result(&mut self, success: bool) {
let lifecycle = self.lifecycle();
let soc_ifc_regs = self.soc_ifc.regs_mut();
match lifecycle {
Lifecycle::Manufacturing => soc_ifc_regs.ss_dbg_service_reg_rsp().modify(|w| {
if success {
w.manuf_dbg_unlock_success(true)
} else {
w.manuf_dbg_unlock_fail(true)
}
}),
DeviceLifecycleE::Production => soc_ifc_regs.ss_dbg_service_reg_rsp().modify(|w| {
if success {
w.prod_dbg_unlock_success(true)
} else {
w.prod_dbg_unlock_fail(true)
}
}),
_ => (),
}
}
pub fn set_ss_dbg_unlock_level(&mut self, debug_level: u8) {
let value = 1 << (debug_level - 1);
let soc_ifc_regs = self.soc_ifc.regs_mut();
soc_ifc_regs
.ss_soc_dbg_unlock_level()
.at(0)
.write(|_| value);
}
/// Debug unlock memory offset
pub fn debug_unlock_pk_hash_offset(&self, level: u32) -> CaliptraResult<usize> {
let soc_ifc_regs = self.soc_ifc.regs();
let fusebank_offset = soc_ifc_regs
.ss_prod_debug_unlock_auth_pk_hash_reg_bank_offset()
.read() as usize;
let num_of_debug_pk_hashes = soc_ifc_regs
.ss_num_of_prod_debug_unlock_auth_pk_hashes()
.read();
if level == 0 || level > num_of_debug_pk_hashes {
Err(CaliptraError::SS_DBG_UNLOCK_PROD_INVALID_LEVEL)?
}
// DEBUG_AUTH_PK_HASH_REG_BANK_OFFSET register value + ( (Debug Unlock Level - 1) * SHA2-384 hash size (48 bytes) )
Ok(fusebank_offset + size_of::<Array4x12>() * (level as usize - 1))
}
pub fn debug_unlock_pk_hash_count(&self) -> u32 {
self.soc_ifc
.regs()
.ss_num_of_prod_debug_unlock_auth_pk_hashes()
.read()
}
pub fn mbox_valid_pauser(&self) -> [u32; 5] {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs.cptra_mbox_valid_axi_user().read()
}
pub fn mbox_pauser_lock(&self) -> [bool; 5] {
let soc_ifc_regs = self.soc_ifc.regs();
let pauser_lock = soc_ifc_regs.cptra_mbox_axi_user_lock();
[
pauser_lock.at(0).read().lock(),
pauser_lock.at(1).read().lock(),
pauser_lock.at(2).read().lock(),
pauser_lock.at(3).read().lock(),
pauser_lock.at(4).read().lock(),
]
}
pub fn set_ss_generic_fw_exec_ctrl(&mut self, go_bitmap: &[u32; 4]) {
let soc_ifc_regs = self.soc_ifc.regs_mut();
for (i, &bitmap) in go_bitmap.iter().enumerate() {
soc_ifc_regs
.ss_generic_fw_exec_ctrl()
.at(i)
.write(|_| bitmap);
}
}
pub fn get_ss_generic_fw_exec_ctrl(&self, go_bitmap: &mut [u32; 4]) {
let soc_ifc_regs = self.soc_ifc.regs();
for (i, bitmap) in go_bitmap.iter_mut().enumerate() {
*bitmap = soc_ifc_regs.ss_generic_fw_exec_ctrl().at(i).read();
}
}
/// Locks or unlocks the ICCM.
///
/// # Arguments
/// * `lock` - Desired lock state of the ICCM
///
pub fn set_iccm_lock(&mut self, lock: bool) {
let soc_ifc_regs = self.soc_ifc.regs_mut();
soc_ifc_regs.internal_iccm_lock().modify(|w| w.lock(lock));
}
/// Retrieve reset reason
pub fn reset_reason(&mut self) -> ResetReason {
reset_reason()
}
/// Set IDEVID CSR ready
///
/// # Arguments
///
/// * None
pub fn flow_status_set_idevid_csr_ready(&mut self) {
let soc_ifc = self.soc_ifc.regs_mut();
soc_ifc
.cptra_flow_status()
.write(|w| w.idevid_csr_ready(true));
}
/// Set ready for Mailbox operations
///
/// # Arguments
///
/// * None
pub fn flow_status_set_ready_for_mb_processing(&mut self) {
let soc_ifc = self.soc_ifc.regs_mut();
soc_ifc
.cptra_flow_status()
.write(|w| w.ready_for_mb_processing(true));
}
/// Get 'ready for firmware' status
///
/// # Arguments
///
/// * None
pub fn flow_status_ready_for_mb_processing(&mut self) -> bool {
let soc_ifc = self.soc_ifc.regs_mut();
soc_ifc.cptra_flow_status().read().ready_for_mb_processing()
}
/// Set mailbox flow done
///
/// # Arguments
///
/// * `state` - desired state of `mailbox_flow_done`.
///
/// * None
pub fn flow_status_set_mailbox_flow_done(&mut self, state: bool) {
self.soc_ifc
.regs_mut()
.cptra_flow_status()
.modify(|w| w.mailbox_flow_done(state));
}
/// Get 'mailbox flow done' status
///
/// # Arguments
///
/// * None
pub fn flow_status_mailbox_flow_done(&mut self) -> bool {
let soc_ifc = self.soc_ifc.regs_mut();
soc_ifc.cptra_flow_status().read().mailbox_flow_done()
}
pub fn fuse_bank(&self) -> FuseBank {
FuseBank {
soc_ifc: &self.soc_ifc,
}
}
/// Returns the flag indicating whether to generate Initial Device ID Certificate
/// Signing Request (CSR)
pub fn mfg_flag_gen_idev_id_csr(&mut self) -> bool {
let soc_ifc_regs = self.soc_ifc.regs();
// Lower 16 bits are for mfg flags
let flags: MfgFlags = (soc_ifc_regs.cptra_dbg_manuf_service_reg().read() & 0xffff).into();
flags.contains(MfgFlags::GENERATE_IDEVID_CSR)
}
/// Returns the flag indicating whether random number generation is unavailable.
pub fn mfg_flag_rng_unavailable(&self) -> bool {
let soc_ifc_regs = self.soc_ifc.regs();
// Lower 16 bits are for mfg flags
let flags: MfgFlags = (soc_ifc_regs.cptra_dbg_manuf_service_reg().read() & 0xffff).into();
flags.contains(MfgFlags::RNG_SUPPORT_UNAVAILABLE)
}
/// Check if verification is turned on for fake-rom
pub fn verify_in_fake_mode(&self) -> bool {
// Bit 31 indicates to perform verification flow in fake ROM
const FAKE_ROM_VERIFY_EN_BIT: u32 = 31;
let soc_ifc_regs = self.soc_ifc.regs();
let val = soc_ifc_regs.cptra_dbg_manuf_service_reg().read();
((val >> FAKE_ROM_VERIFY_EN_BIT) & 1) != 0
}
/// Check if production mode is enabled for fake-rom
pub fn prod_en_in_fake_mode(&self) -> bool {
// Bit 30 indicates production mode is allowed in fake ROM
const FAKE_ROM_PROD_EN_BIT: u32 = 30;
let soc_ifc_regs = self.soc_ifc.regs();
let val = soc_ifc_regs.cptra_dbg_manuf_service_reg().read();
((val >> FAKE_ROM_PROD_EN_BIT) & 1) != 0
}
#[inline(always)]
pub fn hw_config_internal_trng(&mut self) -> bool {
self.soc_ifc.regs().cptra_hw_config().read().i_trng_en()
}
#[inline(always)]
pub fn cptra_dbg_manuf_service_flags(&mut self) -> MfgFlags {
(self.soc_ifc.regs().cptra_dbg_manuf_service_reg().read() & 0xffff).into()
}
/// Enable or disable WDT1
///
/// # Arguments
/// * `enable` - Enable or disable WDT1
///
pub fn configure_wdt1(&mut self, enable: bool) {
let soc_ifc_regs = self.soc_ifc.regs_mut();
soc_ifc_regs
.cptra_wdt_timer1_en()
.write(|w| w.timer1_en(enable));
}
/// Stop WDT1.
///
/// This is useful to call from a fatal-error-handling routine.
///
/// # Safety
///
/// The caller must be certain that it is safe to stop the WDT1.
///
/// This function is safe to call from a trap handler.
pub unsafe fn stop_wdt1() {
let mut soc_ifc = SocIfcReg::new();
soc_ifc
.regs_mut()
.cptra_wdt_timer1_en()
.write(|w| w.timer1_en(false));
}
pub fn get_cycle_count(&self, seconds: u32) -> CaliptraResult<u64> {
const GIGA_UNIT: u32 = 1_000_000_000;
let clock_period_picosecs = self.soc_ifc.regs().cptra_timer_config().read();
if clock_period_picosecs == 0 {
Err(CaliptraError::DRIVER_SOC_IFC_INVALID_TIMER_CONFIG)
} else {
// Dividing GIGA_UNIT by clock_period_picosecs gives frequency in KHz.
// This is being done to avoid 64-bit division (at the loss of precision)
Ok((seconds as u64) * ((GIGA_UNIT / clock_period_picosecs) as u64) * 1000)
}
}
/// Sets WDT1 timeout
///
/// # Arguments
/// * `cycle_count` - Timeout period in cycles
///
pub fn set_wdt1_timeout(&mut self, cycle_count: u64) {
let soc_ifc_regs = self.soc_ifc.regs_mut();
soc_ifc_regs
.cptra_wdt_timer1_timeout_period()
.at(0)
.write(|_| cycle_count as u32);
soc_ifc_regs
.cptra_wdt_timer1_timeout_period()
.at(1)
.write(|_| (cycle_count >> 32) as u32);
}
/// Sets WDT2 timeout
///
/// # Arguments
/// * `cycle_count` - Timeout period in cycles
///
pub fn set_wdt2_timeout(&mut self, cycle_count: u64) {
let soc_ifc_regs = self.soc_ifc.regs_mut();
soc_ifc_regs
.cptra_wdt_timer2_timeout_period()
.at(0)
.write(|_| cycle_count as u32);
soc_ifc_regs
.cptra_wdt_timer2_timeout_period()
.at(1)
.write(|_| (cycle_count >> 32) as u32);
}
pub fn reset_wdt1(&mut self) {
let soc_ifc_regs = self.soc_ifc.regs_mut();
soc_ifc_regs
.cptra_wdt_timer1_ctrl()
.write(|w| w.timer1_restart(true));
}
pub fn wdt1_timeout_cycle_count(&self) -> u64 {
let soc_ifc_regs = self.soc_ifc.regs();
soc_ifc_regs.cptra_wdt_cfg().at(0).read() as u64
| ((soc_ifc_regs.cptra_wdt_cfg().at(1).read() as u64) << 32)
}
pub fn internal_fw_update_reset_wait_cycles(&self) -> u32 {
self.soc_ifc
.regs()
.internal_fw_update_reset_wait_cycles()
.read()
.into()
}
pub fn assert_fw_update_reset(&mut self) {
self.soc_ifc
.regs_mut()
.internal_fw_update_reset()
.write(|w| w.core_rst(true));
}
pub fn assert_ready_for_runtime(&mut self) {
self.soc_ifc
.regs_mut()
.cptra_flow_status()
.modify(|w| w.ready_for_runtime(true));
}
pub fn set_rom_fw_rev_id(&mut self, rom_version: u16) {
// ROM version is [15:0] of CPTRA_FW_REV_ID[0]
const ROM_VERSION_MASK: u32 = 0xFFFF;
let soc_ifc_regs = self.soc_ifc.regs_mut();
let version = (soc_ifc_regs.cptra_fw_rev_id().at(0).read() & !(ROM_VERSION_MASK))
| (rom_version as u32);
soc_ifc_regs.cptra_fw_rev_id().at(0).write(|_| version);
}
pub fn set_fmc_fw_rev_id(&mut self, fmc_version: u16) {
// FMC version is [31:16] of CPTRA_FW_REV_ID[0]
const FMC_VERSION_MASK: u32 = 0xFFFF0000;
const FMC_VERSION_OFFSET: u32 = 16;
let soc_ifc_regs = self.soc_ifc.regs_mut();
let version = (soc_ifc_regs.cptra_fw_rev_id().at(0).read() & !(FMC_VERSION_MASK))
| ((fmc_version as u32) << FMC_VERSION_OFFSET);
soc_ifc_regs.cptra_fw_rev_id().at(0).write(|_| version);
}
pub fn set_rt_fw_rev_id(&mut self, rt_version: u32) {
let soc_ifc_regs = self.soc_ifc.regs_mut();
soc_ifc_regs.cptra_fw_rev_id().at(1).write(|_| rt_version);
}
pub fn get_version(&self) -> [u32; 3] {
[
u32::from(self.soc_ifc.regs().cptra_hw_rev_id().read()),
self.soc_ifc.regs().cptra_fw_rev_id().at(0).read(),
self.soc_ifc.regs().cptra_fw_rev_id().at(1).read(),
]
}
pub fn set_fw_extended_error(&mut self, err: u32) {
let soc_ifc_regs = self.soc_ifc.regs_mut();
let ext_info = soc_ifc_regs.cptra_fw_extended_error_info();
ext_info.at(0).write(|_| err);
}
pub fn enable_mbox_notif_interrupts(&mut self) {
let soc_ifc_regs = self.soc_ifc.regs_mut();
let intr_block = soc_ifc_regs.intr_block_rf();
intr_block
.notif_intr_en_r()
.write(|w| w.notif_cmd_avail_en(true));
intr_block.global_intr_en_r().write(|w| w.notif_en(true));
}
pub fn has_mbox_notif_status(&self) -> bool {
let soc_ifc = self.soc_ifc.regs();
soc_ifc
.intr_block_rf()
.notif_internal_intr_r()
.read()
.notif_cmd_avail_sts()
}
pub fn clear_mbox_notif_status(&mut self) {
let soc_ifc = self.soc_ifc.regs_mut();
soc_ifc
.intr_block_rf()
.notif_internal_intr_r()
.write(|w| w.notif_cmd_avail_sts(true));
}
pub fn uds_program_req(&self) -> bool {
self.soc_ifc
.regs()
.ss_dbg_service_reg_req()
.read()
.uds_program_req()
}
pub fn set_uds_programming_flow_state(&mut self, in_progress: bool) {
self.soc_ifc
.regs_mut()
.ss_dbg_service_reg_rsp()
.modify(|w| w.uds_program_in_progress(in_progress));
}
pub fn set_uds_programming_flow_status(&mut self, flow_succeeded: bool) {
self.soc_ifc
.regs_mut()
.ss_dbg_service_reg_rsp()
.modify(|w| {
if flow_succeeded {
w.uds_program_success(true).uds_program_fail(false)
} else {
w.uds_program_success(false).uds_program_fail(true)
}
});
}
pub fn uds_seed_dest_base_addr_low(&self) -> u32 {
self.soc_ifc.regs().ss_uds_seed_base_addr_l().read()
}
pub fn subsystem_mode(&self) -> bool {
self.soc_ifc
.regs()
.cptra_hw_config()
.read()
.subsystem_mode_en()
}
pub fn ocp_lock_enabled(&self) -> bool {
self.soc_ifc
.regs()
.cptra_hw_config()
.read()
.ocp_lock_mode_en()
}
pub fn ocp_lock_set_lock_in_progress(&mut self) {
self.soc_ifc
.regs_mut()
.ss_ocp_lock_ctrl()
.write(|w| w.lock_in_progress(true));
}
pub fn ocp_lock_get_lock_in_progress(&self) -> bool {
self.soc_ifc
.regs()
.ss_ocp_lock_ctrl()
.read()
.lock_in_progress()
}
pub fn ocp_lock_get_key_size(&self) -> u32 {
self.soc_ifc.regs().ss_key_release_size().read().into()
}
pub fn ocp_lock_get_key_release_addr(&self) -> u64 {
let low = self.soc_ifc.regs().ss_key_release_base_addr_l().read();
let high = self.soc_ifc.regs().ss_key_release_base_addr_h().read();
((high as u64) << 32) | low as u64
}
pub fn uds_fuse_row_granularity_64(&self) -> bool {
let config_val = self.soc_ifc.regs().cptra_generic_input_wires().read()[0];
// Bit 31 = 0 ==> 64-bit granularity; 1 ==> 32-bit granularity
((config_val >> 31) & 1) == 0
}
pub fn fuse_controller_base_addr(&self) -> u64 {
let low = self.soc_ifc.regs().ss_otp_fc_base_addr_l().read();
let high = self.soc_ifc.regs().ss_otp_fc_base_addr_h().read();
((high as u64) << 32) | low as u64
}
pub fn recovery_interface_base_addr(&self) -> u64 {
let low = self.soc_ifc.regs().ss_recovery_ifc_base_addr_l().read();
let high = self.soc_ifc.regs().ss_recovery_ifc_base_addr_h().read();
((high as u64) << 32) | low as u64
}
pub fn caliptra_base_axi_addr(&self) -> u64 {
let low = self.soc_ifc.regs().ss_caliptra_base_addr_l().read();
let high = self.soc_ifc.regs().ss_caliptra_base_addr_h().read();
((high as u64) << 32) | low as u64
}
pub fn mci_base_addr(&self) -> u64 {
let low = self.soc_ifc.regs().ss_mci_base_addr_l().read();
let high = self.soc_ifc.regs().ss_mci_base_addr_h().read();
((high as u64) << 32) | low as u64
}
pub fn set_mcu_firmware_ready(&mut self) {
const MCU_FW_READY_WORD: usize = 0;
const MCU_FW_READY_BIT: u32 = 1 << 2;
self.soc_ifc
.regs_mut()
.ss_generic_fw_exec_ctrl()
.at(MCU_FW_READY_WORD)
.modify(|w| w | MCU_FW_READY_BIT);
}
pub fn fw_ctrl(&mut self, idx: usize) -> u32 {
self.soc_ifc
.regs_mut()
.ss_generic_fw_exec_ctrl()
.at(idx)
.read()
}
pub fn caliptra_generation(&self) -> CptraGeneration {
CptraGeneration(
self.soc_ifc
.regs()
.cptra_hw_rev_id()
.read()
.cptra_generation(),
)
}
pub fn otp_dai_idle_bit_num(&self) -> u32 {
(self.soc_ifc.regs().ss_strap_generic().at(0).read() >> 16) & 0xFFFF
}
pub fn otp_direct_access_cmd_reg_offset(&self) -> u32 {
self.soc_ifc.regs().ss_strap_generic().at(1).read() & 0xFFFF
}
}
bitfield::bitfield! {
// [15:8] Patch version
// [ 7:4] Minor version
// [ 3:0] Major version
pub struct CptraGeneration(u32);
pub patch_version, _: 15, 8;
pub minor_version, _: 7, 4;
pub major_version, _: 3, 0;
}
bitflags::bitflags! {
/// Manufacturing State
pub struct MfgFlags : u32 {
/// Generate Initial Device Id Certificate Signing Request
const GENERATE_IDEVID_CSR = 0x01;
/// RNG functionality unavailable
const RNG_SUPPORT_UNAVAILABLE = 0x2;
}
}
impl From<u32> for MfgFlags {
/// Converts to this type from the input type.
fn from(value: u32) -> Self {
MfgFlags::from_bits_truncate(value)
}
}
/// Reset Reason
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[cfg_attr(not(feature = "no-cfi"), derive(Launder))]
pub enum ResetReason {
/// Cold Reset
ColdReset,
/// Warm Reset
WarmReset,
/// Update Reset
UpdateReset,
/// Unknown Reset
Unknown,
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/array_concat.rs | drivers/src/array_concat.rs | // Licensed under the Apache-2.0 license
use core::mem::MaybeUninit;
#[inline(always)]
pub fn array_concat3<
T: Copy,
const LEN0: usize,
const LEN1: usize,
const LEN2: usize,
const TOTAL_LEN: usize,
>(
a0: [T; LEN0],
a1: [T; LEN1],
a2: [T; LEN2],
) -> [T; TOTAL_LEN] {
let expected_total_len = LEN0 + LEN1 + LEN2;
// Unfortunately, runtime assert is the only way to detect this today.
// Fortunately, it will be optimized out when correct (and the ROM tests
// check to make sure panic is impossible).
assert!(
expected_total_len == TOTAL_LEN,
"TOTAL_LEN should be {expected_total_len}, was {TOTAL_LEN}"
);
let mut result = MaybeUninit::<[T; TOTAL_LEN]>::uninit();
let mut ptr = result.as_mut_ptr() as *mut T;
unsafe {
ptr.copy_from_nonoverlapping(a0.as_ptr(), LEN0);
ptr = ptr.add(LEN0);
ptr.copy_from_nonoverlapping(a1.as_ptr(), LEN1);
ptr = ptr.add(LEN1);
ptr.copy_from_nonoverlapping(a2.as_ptr(), LEN2);
result.assume_init()
}
}
#[cfg(test)]
mod tests {
use crate::array_concat3;
// To run inside the MIRI interpreter to detect undefined behavior in the
// unsafe code, run with:
// cargo +nightly miri test -p caliptra-drivers --lib
#[test]
fn test_array_concat3_u8() {
assert_eq!(
array_concat3([0x01u8], [0x22, 0x23], [0x34, 0x35, 0x36]),
[0x01, 0x22, 0x23, 0x34, 0x35, 0x36]
);
assert_eq!(
array_concat3([0x01u8], [], [0x34, 0x35, 0x36]),
[0x01, 0x34, 0x35, 0x36]
);
assert_eq!(
array_concat3([], [], [0x34u8, 0x35, 0x36]),
[0x34, 0x35, 0x36]
);
assert_eq!(array_concat3::<u8, 0, 0, 0, 0>([], [], []), []);
}
#[test]
fn test_array_concat3_u16() {
assert_eq!(
array_concat3([0x101u16], [0x222, 0x223], [0x334, 0x335, 0x336]),
[0x101, 0x222, 0x223, 0x334, 0x335, 0x336]
);
}
#[test]
#[should_panic(expected = "TOTAL_LEN should be 6, was 5")]
fn test_array_concat3_result_too_small() {
let _: [u8; 5] = array_concat3([0x01u8], [0x22, 0x23], [0x34, 0x35, 0x36]);
}
#[test]
#[should_panic(expected = "TOTAL_LEN should be 6, was 7")]
fn test_array_concat3_result_too_large() {
let _: [u8; 7] = array_concat3([0x01u8], [0x22, 0x23], [0x34, 0x35, 0x36]);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/sha2_512_384.rs | drivers/src/sha2_512_384.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha2_512_384.rs
Abstract:
File contains API for SHA2-512/384 Cryptography operations
--*/
use crate::kv_access::{KvAccess, KvAccessErr};
use crate::{array::Array4x32, wait, Array4x12, Array4x16, Array4x8, PcrId};
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::cfi_impl_fn;
use caliptra_error::{CaliptraError, CaliptraResult};
use caliptra_registers::sha512::Sha512Reg;
// Block size, block length offset and max data size are same for both SHA2-384 and SHA2-512.
pub const SHA512_BLOCK_BYTE_SIZE: usize = 128;
const SHA512_BLOCK_LEN_OFFSET: usize = 112;
const SHA512_MAX_DATA_SIZE: usize = 1024 * 1024;
pub const SHA384_HASH_SIZE: usize = 48;
pub const SHA512_HASH_SIZE: usize = 64;
#[derive(Copy, Clone)]
pub enum ShaMode {
Sha384,
Sha512,
}
impl ShaMode {
fn reg_value(&self) -> u32 {
match self {
Self::Sha384 => 0b10,
Self::Sha512 => 0b11,
}
}
}
/// SHA-384 Digest
pub type Sha384Digest<'a> = &'a mut Array4x12;
pub struct Sha2_512_384 {
sha512: Sha512Reg,
}
impl Sha2_512_384 {
pub fn new(sha512: Sha512Reg) -> Self {
Self { sha512 }
}
/// Initialize multi step digest operation
///
/// # Returns
///
/// * `Sha2DigestOp` - Object representing the digest operation
pub fn sha384_digest_init(&mut self) -> CaliptraResult<Sha2DigestOp<'_, Sha384>> {
let op = Sha2DigestOp {
sha: self,
state: Sha2DigestState::Init,
buf: [0u8; SHA512_BLOCK_BYTE_SIZE],
buf_idx: 0,
data_size: 0,
_phantom: core::marker::PhantomData,
};
Ok(op)
}
/// Initialize multi step digest operation
///
/// # Returns
///
/// * `Sha2DigestOp` - Object representing the digest operation
pub fn sha512_digest_init(&mut self) -> CaliptraResult<Sha2DigestOp<'_, Sha512>> {
let op = Sha2DigestOp {
sha: self,
state: Sha2DigestState::Init,
buf: [0u8; SHA512_BLOCK_BYTE_SIZE],
buf_idx: 0,
data_size: 0,
_phantom: core::marker::PhantomData,
};
Ok(op)
}
fn sha_digest_helper(&mut self, buf: &[u8], mode: ShaMode) -> CaliptraResult<()> {
#[cfg(feature = "fips-test-hooks")]
unsafe {
crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::SHA384_DIGEST_FAILURE)?
}
// Check if the buffer is not large
if buf.len() > SHA512_MAX_DATA_SIZE {
return Err(CaliptraError::DRIVER_SHA2_512_384_MAX_DATA_ERR);
}
let mut first = true;
let mut bytes_remaining = buf.len();
loop {
let offset = buf.len() - bytes_remaining;
match bytes_remaining {
0..=127 => {
// PANIC-FREE: Use buf.get() instead if buf[] as the compiler
// cannot reason about `offset` parameter to optimize out
// the panic.
if let Some(slice) = buf.get(offset..) {
self.digest_partial_block(mode, slice, first, buf.len(), false)?;
break;
} else {
return Err(CaliptraError::DRIVER_SHA2_512_384_INVALID_SLICE);
}
}
_ => {
// PANIC-FREE: Use buf.get() instead if buf[] as the compiler
// cannot reason about `offset` parameter to optimize out
// the panic call.
if let Some(slice) = buf.get(offset..offset + SHA512_BLOCK_BYTE_SIZE) {
let block = <&[u8; SHA512_BLOCK_BYTE_SIZE]>::try_from(slice).unwrap();
self.digest_block(mode, block, first, false, false)?;
bytes_remaining -= SHA512_BLOCK_BYTE_SIZE;
first = false;
} else {
return Err(CaliptraError::DRIVER_SHA2_512_384_INVALID_SLICE);
}
}
}
}
Ok(())
}
/// Calculate the SHA2-384 digest for specified data
///
/// # Arguments
///
/// * `data` - Data to used to update the digest
///
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn sha384_digest(&mut self, buf: &[u8]) -> CaliptraResult<Array4x12> {
self.sha_digest_helper(buf, ShaMode::Sha384)?;
let digest = self.sha384_read_digest();
#[cfg(feature = "fips-test-hooks")]
let digest = unsafe {
crate::FipsTestHook::corrupt_data_if_hook_set(
crate::FipsTestHook::SHA384_CORRUPT_DIGEST,
&digest,
)
};
self.zeroize_internal();
Ok(digest)
}
/// Calculate the SHA2-512 digest for specified data
///
/// # Arguments
///
/// * `data` - Data to used to update the digest
///
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn sha512_digest(&mut self, buf: &[u8]) -> CaliptraResult<Array4x16> {
self.sha_digest_helper(buf, ShaMode::Sha512)?;
wait::until(|| self.sha512.regs().status().read().valid());
let digest = Array4x16::read_from_reg(self.sha512.regs().digest());
#[cfg(feature = "fips-test-hooks")]
let digest = unsafe {
crate::FipsTestHook::corrupt_data_if_hook_set(
crate::FipsTestHook::SHA384_CORRUPT_DIGEST,
&digest,
)
};
self.zeroize_internal();
Ok(digest)
}
/// Zeroize the hardware registers.
fn zeroize_internal(&mut self) {
self.sha512.regs_mut().ctrl().write(|w| w.zeroize(true));
}
/// Zeroize the hardware registers.
///
/// This is useful to call from a fatal-error-handling routine.
///
/// # Safety
///
/// The caller must be certain that the results of any pending cryptographic
/// operations will not be used after this function is called.
///
/// This function is safe to call from a trap handler.
pub unsafe fn zeroize() {
let mut sha384 = Sha512Reg::new();
sha384.regs_mut().ctrl().write(|w| w.zeroize(true));
}
/// Copy digest to buffer
///
/// # Arguments
///
/// * `buf` - Digest buffer
pub fn sha384_read_digest(&mut self) -> Array4x12 {
let sha = self.sha512.regs();
// digest_block() only waits until the peripheral is ready for the next
// command; the result register may not be valid yet
wait::until(|| sha.status().read().valid());
Array4x12::read_from_reg(sha.digest().truncate::<12>())
}
/// Copy digest to buffer
///
/// # Arguments
///
/// * `buf` - Digest buffer
pub fn sha512_read_digest(&mut self) -> Array4x16 {
let sha = self.sha512.regs();
// digest_block() only waits until the peripheral is ready for the next
// command; the result register may not be valid yet
wait::until(|| sha.status().read().valid());
Array4x16::read_from_reg(sha.digest())
}
/// Generate digest over PCRs + nonce
///
/// # Arguments
///
/// * `nonce`- Nonce buffer
///
/// # Returns
///
/// * `buf` - Digest buffer
pub fn gen_pcr_hash(&mut self, nonce: Array4x8) -> CaliptraResult<Array4x16> {
let reg = self.sha512.regs_mut();
let status_reg = reg.gen_pcr_hash_status();
// Wait for the registers to be ready
wait::until(|| status_reg.read().ready());
// Write the nonce into the register
reg.gen_pcr_hash_nonce().write(&nonce.into());
// Use the start command to start the digesting process
reg.gen_pcr_hash_ctrl().write(|ctrl| ctrl.start(true));
// Wait for the registers to be ready
wait::until(|| status_reg.read().ready());
// Initialize SHA hardware to clear write lock
reg.ctrl().write(|w| w.init(true));
wait::until(|| status_reg.read().ready());
if status_reg.read().valid() {
Ok(reg.gen_pcr_hash_digest().read().into())
} else {
Err(CaliptraError::DRIVER_SHA2_512_384_INVALID_STATE_ERR)
}
}
pub fn pcr_extend(&mut self, id: PcrId, data: &[u8]) -> CaliptraResult<()> {
let total_bytes = data.len() + SHA384_HASH_SIZE;
if total_bytes > (SHA512_BLOCK_BYTE_SIZE - 1) {
return Err(CaliptraError::DRIVER_SHA2_512_384_MAX_DATA_ERR);
}
// Wait on the PCR to be retrieved from the PCR vault.
self.retrieve_pcr(id)?;
// Prepare the data block; first SHA384_HASH_SIZE bytes are not filled
// to account for the PCR retrieved. The retrieved PCR is unaffected as
// writing to the first SHA384_HASH_SIZE bytes is skipped by the hardware.
let mut block = [0u8; SHA512_BLOCK_BYTE_SIZE];
// PANIC-FREE: Following check optimizes the out of bounds
// panic in copy_from_slice
if SHA384_HASH_SIZE > total_bytes || total_bytes > block.len() {
return Err(CaliptraError::DRIVER_SHA2_512_384_MAX_DATA_ERR);
}
block[SHA384_HASH_SIZE..total_bytes].copy_from_slice(data);
if let Some(slice) = block.get(..total_bytes) {
self.digest_partial_block(ShaMode::Sha384, slice, true, total_bytes, false)?;
} else {
return Err(CaliptraError::DRIVER_SHA2_512_384_MAX_DATA_ERR);
}
Ok(())
}
/// Waits for the PCR to be retrieved from the PCR vault
/// and copied to the block registers.
///
/// # Arguments
///
/// * `pcr_id` - PCR to hash extend
fn retrieve_pcr(&mut self, pcr_id: PcrId) -> CaliptraResult<()> {
let sha = self.sha512.regs_mut();
KvAccess::extend_from_pv(pcr_id, sha.vault_rd_status(), sha.vault_rd_ctrl())
.map_err(|err| err.into_read_data_err())?;
Ok(())
}
/// Calculate the digest of the last block
///
/// # Arguments
///
/// * `slice` - Slice of buffer to digest
/// * `first` - Flag indicating if this is the first buffer
/// * `buf_size` - Total buffer size
fn digest_partial_block(
&mut self,
mode: ShaMode,
slice: &[u8],
first: bool,
buf_size: usize,
restore: bool,
) -> CaliptraResult<()> {
/// Set block length
fn set_block_len(buf_size: usize, block: &mut [u8; SHA512_BLOCK_BYTE_SIZE]) {
let bit_len = (buf_size as u128) << 3;
block[SHA512_BLOCK_LEN_OFFSET..].copy_from_slice(&bit_len.to_be_bytes());
}
// Construct the block
let mut block = [0u8; SHA512_BLOCK_BYTE_SIZE];
let mut last = false;
// PANIC-FREE: Following check optimizes the out of bounds
// panic in copy_from_slice
if slice.len() > block.len() - 1 {
return Err(CaliptraError::DRIVER_SHA2_512_384_INDEX_OUT_OF_BOUNDS);
}
block[..slice.len()].copy_from_slice(slice);
block[slice.len()] = 0b1000_0000;
if slice.len() < SHA512_BLOCK_LEN_OFFSET {
set_block_len(buf_size, &mut block);
last = true;
}
// Calculate the digest of the op
self.digest_block(mode, &block, first, last, restore)?;
// Add a padding block if one is needed
if slice.len() >= SHA512_BLOCK_LEN_OFFSET {
block.fill(0);
set_block_len(buf_size, &mut block);
self.digest_block(mode, &block, false, true, false)?;
}
Ok(())
}
/// Calculate digest of the full block
///
/// # Arguments
///
/// * `block`: Block to calculate the digest
/// * `first` - Flag indicating if this is the first block
/// * `last` - Flag indicating if this is the last block
fn digest_block(
&mut self,
mode: ShaMode,
block: &[u8; SHA512_BLOCK_BYTE_SIZE],
first: bool,
last: bool,
restore: bool,
) -> CaliptraResult<()> {
let sha512 = self.sha512.regs_mut();
Array4x32::from(block).write_to_reg(sha512.block());
self.digest_op(mode, first, last, restore)
}
// Perform the digest operation in the hardware
//
// # Arguments
//
/// * `first` - Flag indicating if this is the first block
/// * `last` - Flag indicating if this is the last block
/// * `restore` - Flag indicating if this is resuming a previous operation
fn digest_op(
&mut self,
mode: ShaMode,
first: bool,
last: bool,
restore: bool,
) -> CaliptraResult<()> {
let sha = self.sha512.regs_mut();
// Wait for the hardware to be ready
wait::until(|| sha.status().read().ready());
// Submit the first/next block for hashing.
sha.ctrl().write(|w| {
w.mode(mode.reg_value())
.init(first)
.next(!first)
.last(last)
.restore(restore)
});
// Wait for the digest operation to finish
wait::until(|| sha.status().read().ready());
Ok(())
}
}
/// SHA-384 Digest state
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Sha2DigestState {
/// Initial state
Init,
/// Restore previous hash state
Restore,
/// Pending state
Pending,
/// Final state
Final,
}
/// Multi step SHA-384 digest operation
pub struct Sha2DigestOp<'a, V> {
/// SHA-384 Engine
sha: &'a mut Sha2_512_384,
/// State
state: Sha2DigestState,
/// Staging buffer
buf: [u8; SHA512_BLOCK_BYTE_SIZE],
/// Current staging buffer index
buf_idx: usize,
/// Data size
data_size: usize,
/// Phantom data to use the type parameter
_phantom: core::marker::PhantomData<V>,
}
impl<V> Sha2DigestOp<'_, V> {
/// Check if this the first digest operation
fn is_first(&self) -> bool {
self.state == Sha2DigestState::Init
}
fn is_restore(&self) -> bool {
self.state == Sha2DigestState::Restore
}
/// Reset internal buffer state
fn reset_buf_state(&mut self) {
self.buf.fill(0);
self.buf_idx = 0;
self.state = Sha2DigestState::Pending;
}
}
impl<'a> Sha2DigestOpTrait<'a, Sha384> for Sha2DigestOp<'a, Sha384> {
type DigestType = Array4x12;
fn sha_mode() -> ShaMode {
ShaMode::Sha384
}
fn read_digest(sha: &mut Sha2_512_384) -> Self::DigestType {
sha.sha384_read_digest()
}
fn as_digest_op(&mut self) -> &mut Sha2DigestOp<'a, Sha384> {
self
}
}
impl<'a> Sha2DigestOpTrait<'a, Sha512> for Sha2DigestOp<'a, Sha512> {
type DigestType = Array4x16;
fn sha_mode() -> ShaMode {
ShaMode::Sha512
}
fn read_digest(sha: &mut Sha2_512_384) -> Self::DigestType {
sha.sha512_read_digest()
}
fn as_digest_op(&mut self) -> &mut Sha2DigestOp<'a, Sha512> {
self
}
}
/// Trait for SHA-2 digest operations
pub trait Sha2DigestOpTrait<'a, V>: Sized {
/// The digest type for this SHA-2 variant
type DigestType;
/// Get as Digest Op
fn as_digest_op(&mut self) -> &mut Sha2DigestOp<'a, V>;
/// Get the SHA mode for this variant
fn sha_mode() -> ShaMode;
/// Read the digest from hardware
fn read_digest(sha: &mut Sha2_512_384) -> Self::DigestType;
/// Resumes a digest operation.
fn resume(
&mut self,
previous_size: usize,
digest: &Array4x16,
buffer: &[u8],
) -> CaliptraResult<()> {
let this = self.as_digest_op();
this.data_size = previous_size;
// restore the digest if we have processed more than a block of data
if this.data_size >= SHA512_BLOCK_BYTE_SIZE {
this.state = Sha2DigestState::Restore;
let sha = this.sha.sha512.regs_mut();
wait::until(|| sha.status().read().ready());
sha.digest().write(&digest.0);
}
self.update(buffer)
}
/// Writes the current buffer to the argument and returns the total size so far (including the buffer).
fn save_buffer(&mut self, buffer: &mut [u8; SHA512_BLOCK_BYTE_SIZE]) -> CaliptraResult<usize> {
let this = self.as_digest_op();
let len = this.buf_idx;
// PANIC-FREE: Following check optimizes the out of bounds
// panic in indexing the `buffer`
if this.buf_idx >= buffer.len() {
Err(CaliptraError::DRIVER_SHA2_512_384_INDEX_OUT_OF_BOUNDS)?;
}
buffer[..len].copy_from_slice(&this.buf[..len]);
Ok(this.data_size)
}
/// Update the digest with data
fn update(&mut self, data: &[u8]) -> CaliptraResult<()> {
let this = self.as_digest_op();
if this.state == Sha2DigestState::Final {
return Err(CaliptraError::DRIVER_SHA2_512_384_INVALID_STATE_ERR);
}
if data.len() > SHA512_MAX_DATA_SIZE {
return Err(CaliptraError::DRIVER_SHA2_512_384_MAX_DATA_ERR);
}
for byte in data {
this.data_size += 1;
// PANIC-FREE: Following check optimizes the out of bounds
// panic in indexing the `buf`
if this.buf_idx >= this.buf.len() {
return Err(CaliptraError::DRIVER_SHA2_512_384_INDEX_OUT_OF_BOUNDS);
}
// Copy the data to the buffer
this.buf[this.buf_idx] = *byte;
this.buf_idx += 1;
// If the buffer is full calculate the digest of accumulated data
if this.buf_idx == this.buf.len() {
this.sha.digest_block(
Self::sha_mode(),
&this.buf,
this.is_first(),
false,
this.is_restore(),
)?;
this.reset_buf_state();
}
}
Ok(())
}
/// Finalize the digest operation
fn finalize(mut self, digest: &mut Self::DigestType) -> CaliptraResult<()> {
let this = self.as_digest_op();
if this.state == Sha2DigestState::Final {
return Err(CaliptraError::DRIVER_SHA2_512_384_INVALID_STATE_ERR);
}
if this.buf_idx > this.buf.len() {
return Err(CaliptraError::DRIVER_SHA2_512_384_INVALID_SLICE);
}
// Calculate the digest of the final block
let buf = &this.buf[..this.buf_idx];
this.sha.digest_partial_block(
Self::sha_mode(),
buf,
this.is_first(),
this.data_size,
this.is_restore(),
)?;
this.state = Sha2DigestState::Final;
*digest = Self::read_digest(this.sha);
Ok(())
}
}
/// SHA-384 variant implementation
pub struct Sha384;
/// SHA-512 variant implementation
pub struct Sha512;
/// SHA-384 key access error trait
trait Sha384KeyAccessErr {
/// Convert to read data operation error
fn into_read_data_err(self) -> CaliptraError;
}
impl Sha384KeyAccessErr for KvAccessErr {
/// Convert to read data operation error
fn into_read_data_err(self) -> CaliptraError {
match self {
KvAccessErr::KeyRead => CaliptraError::DRIVER_SHA2_512_384_READ_DATA_KV_READ,
KvAccessErr::KeyWrite => CaliptraError::DRIVER_SHA2_512_384_READ_DATA_KV_WRITE,
KvAccessErr::Generic => CaliptraError::DRIVER_SHA2_512_384_READ_DATA_KV_UNKNOWN,
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/sha3.rs | drivers/src/sha3.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha3.rs
Abstract:
File contains API for SHAKE and SHA3 Cryptography operations
--*/
use crate::{wait, Array4xN, CaliptraError, CaliptraResult};
use caliptra_cfi_derive::cfi_impl_fn;
use caliptra_registers::kmac::{regs::CfgShadowedWriteVal, Kmac as KmacReg};
#[allow(unused)]
#[derive(Copy, Clone)]
pub enum Sha3Mode {
Sha3,
Shake,
}
impl Sha3Mode {
fn reg_value(&self) -> u32 {
match self {
Self::Sha3 => 0b00,
Self::Shake => 0b10, // TODO: This does not match the RDL
}
}
fn get_rate(&self, strength: Sha3KStrength) -> u32 {
match self {
Self::Sha3 => {
match strength {
Sha3KStrength::L224 => 1152,
Sha3KStrength::L256 => 1088,
Sha3KStrength::L384 => 832,
Sha3KStrength::L512 => 576,
_ => 0, // Invalid config
}
}
Self::Shake => {
match strength {
Sha3KStrength::L128 => 1344,
Sha3KStrength::L256 => 1088,
_ => 0, // Invalid config
}
}
}
}
}
#[allow(unused)]
#[derive(Copy, Clone)]
pub enum Sha3KStrength {
L128,
L224,
L256,
L384,
L512,
}
impl Sha3KStrength {
fn reg_value(&self) -> u32 {
match self {
Self::L128 => 0x0,
Self::L224 => 0x1,
Self::L256 => 0x2,
Self::L384 => 0x3,
Self::L512 => 0x4,
}
}
}
#[allow(unused)]
#[derive(Copy, Clone)]
pub enum Sha3Cmd {
Start,
Process,
Run,
Done,
}
impl Sha3Cmd {
fn reg_value(&self) -> u32 {
match self {
Self::Start => 0x1D,
Self::Process => 0x2E,
Self::Run => 0x31,
Self::Done => 0x16,
}
}
}
pub struct Sha3 {
sha3: KmacReg,
}
impl Sha3 {
pub fn new(sha3: KmacReg) -> Self {
Self { sha3 }
}
// Additional modes may be added by simply creating analogous functions for the two below
// - (shake/sha)(128/224/256/384/512)_digest_init()
// - (shake/sha)(128/224/256/384/512)_digest()
/// Initialize multi-step SHAKE-256 digest operation
///
/// # Returns
///
/// * `Sha3DigestOp` - Object representing the digest operation
pub fn shake256_digest_init(&mut self) -> CaliptraResult<Sha3DigestOp<'_>> {
let mut op = Sha3DigestOp {
sha3: self,
mode: Sha3Mode::Shake,
strength: Sha3KStrength::L256,
state: Sha3DigestState::Init,
};
op.init()?;
Ok(op)
}
/// Calculate the SHAKE-256 digest for specified data
///
/// # Arguments
///
/// * `data` - Data to used to update the digest
///
/// # Returns
///
/// * `Array4xN` - Array containing the digest. Size depends on expected return type (Array4x8, Array4x16, etc.)
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn shake256_digest<const W: usize, const B: usize>(
&mut self,
data: &[u8],
) -> CaliptraResult<Array4xN<W, B>> {
self.digest_generic(Sha3Mode::Shake, Sha3KStrength::L256, data)
}
// Helper function to be called by a mode-specific public function
// Performs a digest using a single, provided slice of data
fn digest_generic<const W: usize, const B: usize>(
&mut self,
mode: Sha3Mode,
strength: Sha3KStrength,
data: &[u8],
) -> CaliptraResult<Array4xN<W, B>> {
// START
self.digest_start(mode, strength)?;
// UPDATE
// Stream data
self.stream_msg(data)?;
// FINALIZE
self.finalize()?;
// READ DIGEST
let digest = self.read_digest(mode, strength)?;
// Complete and zeroize
self.zeroize_internal();
Ok(digest)
}
// Initialize the digest operation and wait for the absorb state to be set
fn digest_start(&mut self, mode: Sha3Mode, strength: Sha3KStrength) -> CaliptraResult<()> {
let reg = self.sha3.regs_mut();
// INIT
// Ensure HW is in the right state
wait::until(|| reg.status().read().sha3_idle());
// Configure mode and strength/length
let write_val = CfgShadowedWriteVal::from(0)
.mode(mode.reg_value())
.kstrength(strength.reg_value())
.state_endianness(true);
// Need to write same value twice to this shadowed reg per spec
reg.cfg_shadowed().write(|_| write_val);
reg.cfg_shadowed().write(|_| write_val);
// Issue start cmd
reg.cmd().write(|w| w.cmd(Sha3Cmd::Start.reg_value()));
// Wait for absorb state
wait::until(|| reg.status().read().sha3_absorb());
Ok(())
}
// Stream data to the input FIFO
fn stream_msg(&mut self, src: &[u8]) -> CaliptraResult<()> {
let reg = self.sha3.regs_mut();
// Ensure FIFO empty is set to indicate FIFO is writable
// Spec makes it clear HW can empty this faster than FW can write, so not monitoring FIFO used space between writes
wait::until(|| reg.status().read().fifo_empty());
// TODO: There may be an existing function that can handle this.
// It needs to handle volatile writes by dword and leftover bytes individually (not padded to a dword)
// Ideally, it would also not increment the destination address (or just make sure we don't exceed mem range)
// Break off bytes if not a dword multiple
let (src_dwords, src_bytes) = src.split_at(src.len() & !3);
// Write 4-byte chunks as u32 dwords
for chunk in src_dwords.chunks_exact(4) {
let src_dword = u32::from_ne_bytes(chunk.try_into().unwrap());
reg.msg_fifo().at(0).write(|_| src_dword);
}
// Write any remaining bytes individually
let dst_u8 = reg.msg_fifo().at(0).ptr as *mut u8;
for &src_byte in src_bytes {
unsafe {
dst_u8.write_volatile(src_byte);
}
}
Ok(())
}
// Start HW process of generating digest
fn finalize(&mut self) -> CaliptraResult<()> {
let reg = self.sha3.regs_mut();
// Issue process cmd
reg.cmd().write(|w| w.cmd(Sha3Cmd::Process.reg_value()));
Ok(())
}
// Wait for digest to be complete and read out the data
// Digest size returned depends on expected return type
fn read_digest<const W: usize, const B: usize>(
&mut self,
mode: Sha3Mode,
strength: Sha3KStrength,
) -> CaliptraResult<Array4xN<W, B>> {
let reg = self.sha3.regs_mut();
// Wait for completion
wait::until(|| reg.status().read().sha3_squeeze());
// Error checking so we don't exceed the rate for the type
// NOTE: This HW does support larger digests, but another RUN command needs to be issued to do so
// There was no need for this at the time this was written
if (W * core::mem::size_of::<u32>()) as u32 > mode.get_rate(strength) {
return Err(CaliptraError::DRIVER_SHA3_DIGEST_EXCEEDS_RATE);
}
// Read out digest
let digest = Array4xN::<W, B>::read_from_reg(reg.state().truncate::<W>());
Ok(digest)
}
/// Zeroize the hardware registers.
fn zeroize_internal(&mut self) {
self.sha3
.regs_mut()
.cmd()
.write(|w| w.cmd(Sha3Cmd::Done.reg_value()));
}
/// Zeroize the hardware registers.
///
/// This is useful to call from a fatal-error-handling routine.
///
/// # Safety
///
/// The caller must be certain that the results of any pending cryptographic
/// operations will not be used after this function is called.
///
/// This function is safe to call from a trap handler.
pub unsafe fn zeroize() {
let mut sha3 = KmacReg::new();
sha3.regs_mut()
.cmd()
.write(|w| w.cmd(Sha3Cmd::Done.reg_value()));
}
}
/// SHA3 Digest state
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Sha3DigestState {
/// Initial state
Init,
/// Pending state
Pending,
/// Final state
Final,
}
/// Multi step SHA3 digest operation
pub struct Sha3DigestOp<'a> {
/// SHA3/SHAKE Engine
sha3: &'a mut Sha3,
mode: Sha3Mode,
strength: Sha3KStrength,
/// State
state: Sha3DigestState,
}
impl Sha3DigestOp<'_> {
// Start the hash operation
fn init(&mut self) -> CaliptraResult<()> {
if self.state != Sha3DigestState::Init {
return Err(CaliptraError::DRIVER_SHA3_INVALID_STATE_ERR);
}
// Call init
self.sha3.digest_start(self.mode, self.strength)?;
self.state = Sha3DigestState::Pending;
Ok(())
}
/// Update the digest with data
pub fn update(&mut self, data: &[u8]) -> CaliptraResult<()> {
if self.state != Sha3DigestState::Pending {
return Err(CaliptraError::DRIVER_SHA3_INVALID_STATE_ERR);
}
self.sha3.stream_msg(data)?;
Ok(())
}
/// Finalize the digest operation
pub fn finalize<const W: usize, const B: usize>(&mut self) -> CaliptraResult<Array4xN<W, B>> {
if self.state != Sha3DigestState::Pending {
return Err(CaliptraError::DRIVER_SHA3_INVALID_STATE_ERR);
}
// Update State
self.state = Sha3DigestState::Final;
self.sha3.finalize()?;
let digest = self.sha3.read_digest(self.mode, self.strength)?;
self.sha3.zeroize_internal();
Ok(digest)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/sha1.rs | drivers/src/sha1.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha1.rs
Abstract:
File contains API for SHA1 Cryptography operations
--*/
use crate::{Array4x5, CaliptraError, CaliptraResult};
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::cfi_impl_fn;
use zeroize::Zeroize;
const SHA1_BLOCK_BYTE_SIZE: usize = 64;
const SHA1_BLOCK_LEN_OFFSET: usize = 56;
const SHA1_MAX_DATA_SIZE: usize = 1024 * 1024;
pub type Sha1Digest<'a> = &'a mut Array4x5;
#[derive(Default)]
pub struct Sha1 {
compressor: Sha1Compressor,
}
impl Sha1 {
/// Initialize multi step digest operation
///
/// # Returns
///
/// * `Sha1Digest` - Object representing the digest operation
pub fn digest_init(&mut self) -> CaliptraResult<Sha1DigestOp<'_>> {
let op = Sha1DigestOp {
sha: self,
state: Sha1DigestState::Init,
buf: [0u8; SHA1_BLOCK_BYTE_SIZE],
buf_idx: 0,
data_size: 0,
};
Ok(op)
}
/// Calculate the digest of the buffer
///
/// # Arguments
///
/// * `buf` - Buffer to calculate the digest over
#[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)]
pub fn digest(&mut self, buf: &[u8]) -> CaliptraResult<Array4x5> {
#[cfg(feature = "fips-test-hooks")]
unsafe {
crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::SHA1_DIGEST_FAILURE)?
}
// Check if the buffer is not large
if buf.len() > SHA1_MAX_DATA_SIZE {
return Err(CaliptraError::DRIVER_SHA1_MAX_DATA);
}
let mut first = true;
let mut bytes_remaining = buf.len();
loop {
let offset = buf.len() - bytes_remaining;
match bytes_remaining {
0..=63 => {
// PANIC-FREE: Use buf.get() instead if buf[] as the compiler
// cannot reason about `offset` parameter to optimize out
// the panic.
if let Some(slice) = buf.get(offset..) {
self.digest_partial_block(slice, first, buf.len())?;
break;
} else {
return Err(CaliptraError::DRIVER_SHA1_INVALID_SLICE);
}
}
_ => {
// PANIC-FREE: Use buf.get() instead if buf[] as the compiler
// cannot reason about `offset` parameter to optimize out
// the panic call.
if let Some(slice) = buf.get(offset..offset + SHA1_BLOCK_BYTE_SIZE) {
let block = <&[u8; SHA1_BLOCK_BYTE_SIZE]>::try_from(slice).unwrap();
self.digest_block(block, first)?;
bytes_remaining -= SHA1_BLOCK_BYTE_SIZE;
first = false;
} else {
return Err(CaliptraError::DRIVER_SHA1_INVALID_SLICE);
}
}
}
}
#[cfg(feature = "fips-test-hooks")]
{
self.compressor.hash = unsafe {
crate::FipsTestHook::corrupt_data_if_hook_set(
crate::FipsTestHook::SHA1_CORRUPT_DIGEST,
&self.compressor.hash,
)
};
}
Ok(self.compressor.hash().into())
}
/// Copy digest to buffer
///
/// # Arguments
///
/// * `buf` - Digest buffer
fn copy_digest_to_buf(&self, buf: &mut Array4x5) -> CaliptraResult<()> {
*buf = (*self.compressor.hash()).into();
Ok(())
}
/// Calculate the digest of the last block
///
/// # Arguments
///
/// * `slice` - Slice of buffer to digest
/// * `first` - Flag indicating if this is the first buffer
/// * `buf_size` - Total buffer size
fn digest_partial_block(
&mut self,
slice: &[u8],
first: bool,
buf_size: usize,
) -> CaliptraResult<()> {
/// Set block length
fn set_block_len(buf_size: usize, block: &mut [u8; SHA1_BLOCK_BYTE_SIZE]) {
let bit_len = (buf_size as u64) << 3;
block[SHA1_BLOCK_LEN_OFFSET..].copy_from_slice(&bit_len.to_be_bytes());
}
// Construct the block
let mut block = [0u8; SHA1_BLOCK_BYTE_SIZE];
// PANIC-FREE: Following check optimizes the out of bounds
// panic in copy_from_slice
if slice.len() > block.len() - 1 {
return Err(CaliptraError::DRIVER_SHA1_INDEX_OUT_OF_BOUNDS);
}
block[..slice.len()].copy_from_slice(slice);
block[slice.len()] = 0b1000_0000;
if slice.len() < SHA1_BLOCK_LEN_OFFSET {
set_block_len(buf_size, &mut block);
}
// Calculate the digest of the op
self.digest_block(&block, first)?;
// Add a padding block if one is needed
if slice.len() >= SHA1_BLOCK_LEN_OFFSET {
block.fill(0);
set_block_len(buf_size, &mut block);
self.digest_block(&block, false)?;
}
Ok(())
}
/// Calculate digest of the full block
///
/// # Arguments
///
/// * `block`: Block to calculate the digest
/// * `first` - Flag indicating if this is the first block
fn digest_block(
&mut self,
block: &[u8; SHA1_BLOCK_BYTE_SIZE],
first: bool,
) -> CaliptraResult<()> {
if first {
self.compressor.reset()
}
self.compressor.compress(block);
Ok(())
}
}
/// SHA-256 Digest state
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Sha1DigestState {
/// Initial state
Init,
/// Pending state
Pending,
/// Final state
Final,
}
/// Multi step SHA-256 digest operation
#[derive(Zeroize)]
pub struct Sha1DigestOp<'a> {
/// SHA-256 Engine
#[zeroize(skip)]
sha: &'a mut Sha1,
/// State
#[zeroize(skip)]
state: Sha1DigestState,
/// Staging buffer
buf: [u8; SHA1_BLOCK_BYTE_SIZE],
/// Current staging buffer index
buf_idx: usize,
/// Data size
data_size: usize,
}
impl Sha1DigestOp<'_> {
/// Update the digest with data
///
/// # Arguments
///
/// * `data` - Data to used to update the digest
pub fn update(&mut self, data: &[u8]) -> CaliptraResult<()> {
if self.state == Sha1DigestState::Final {
return Err(CaliptraError::DRIVER_SHA1_INVALID_STATE);
}
if self.data_size + data.len() > SHA1_MAX_DATA_SIZE {
return Err(CaliptraError::DRIVER_SHA1_MAX_DATA);
}
for byte in data {
self.data_size += 1;
// PANIC-FREE: Following check optimizes the out of bounds
// panic in indexing the `buf`
if self.buf_idx >= self.buf.len() {
return Err(CaliptraError::DRIVER_SHA1_INDEX_OUT_OF_BOUNDS);
}
// Copy the data to the buffer
self.buf[self.buf_idx] = *byte;
self.buf_idx += 1;
// If the buffer is full calculate the digest of accumulated data
if self.buf_idx == self.buf.len() {
self.sha.digest_block(&self.buf, self.is_first())?;
self.reset_buf_state();
}
}
Ok(())
}
/// Finalize the digest operations
pub fn finalize(mut self, digest: &mut Array4x5) -> CaliptraResult<()> {
if self.state == Sha1DigestState::Final {
return Err(CaliptraError::DRIVER_SHA1_INVALID_STATE);
}
if self.buf_idx > self.buf.len() {
return Err(CaliptraError::DRIVER_SHA1_INVALID_SLICE);
}
// Calculate the digest of the final block
let buf = &self.buf[..self.buf_idx];
self.sha
.digest_partial_block(buf, self.is_first(), self.data_size)?;
// Set the state of the operation to final
self.state = Sha1DigestState::Final;
// Copy digest
self.sha.copy_digest_to_buf(digest)?;
Ok(())
}
/// Check if this the first digest operation
fn is_first(&self) -> bool {
self.state == Sha1DigestState::Init
}
/// Reset internal buffer state
fn reset_buf_state(&mut self) {
self.buf.fill(0);
self.buf_idx = 0;
self.state = Sha1DigestState::Pending;
}
}
/// SHA1 Compressor
///
/// Implementation based on reference code in https://www.rfc-editor.org/rfc/rfc3174
struct Sha1Compressor {
/// Hash
hash: [u32; 5],
}
impl Default for Sha1Compressor {
/// Returns the "default value" for a type.
fn default() -> Self {
Self {
hash: [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0],
}
}
}
impl Sha1Compressor {
/// Reset the compressor for new operation
pub fn reset(&mut self) {
*self = Sha1Compressor::default()
}
/// Compress the block
///
/// Implementation is based on reference code in https://www.rfc-editor.org/rfc/rfc3174
///
/// # Arguments
///
/// * `block` - Block to compress
pub fn compress(&mut self, block: &[u8; 64]) {
const K: [u32; 4] = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6];
let mut w = [0u32; 80];
// Initialize the first 16 words in
for idx in 0..16 {
w[idx] = (block[idx * 4] as u32) << 24;
w[idx] |= (block[idx * 4 + 1] as u32) << 16;
w[idx] |= (block[idx * 4 + 2] as u32) << 8;
w[idx] |= block[idx * 4 + 3] as u32;
}
for idx in 16..80 {
let val = w[idx - 3] ^ w[idx - 8] ^ w[idx - 14] ^ w[idx - 16];
w[idx] = val.rotate_left(1);
}
let mut a = self.hash[0];
let mut b = self.hash[1];
let mut c = self.hash[2];
let mut d = self.hash[3];
let mut e = self.hash[4];
for word in w.iter().take(20) {
let temp = a
.rotate_left(5)
.wrapping_add((b & c) | ((!b) & d))
.wrapping_add(e)
.wrapping_add(*word)
.wrapping_add(K[0]);
e = d;
d = c;
c = b.rotate_left(30);
b = a;
a = temp;
}
for word in w.iter().take(40).skip(20) {
let temp = a
.rotate_left(5)
.wrapping_add(b ^ c ^ d)
.wrapping_add(e)
.wrapping_add(*word)
.wrapping_add(K[1]);
e = d;
d = c;
c = b.rotate_left(30);
b = a;
a = temp;
}
for word in w.iter().take(60).skip(40) {
let temp = a
.rotate_left(5)
.wrapping_add((b & c) | (b & d) | (c & d))
.wrapping_add(e)
.wrapping_add(*word)
.wrapping_add(K[2]);
e = d;
d = c;
c = b.rotate_left(30);
b = a;
a = temp;
}
for word in w.iter().skip(60) {
let temp = a
.rotate_left(5)
.wrapping_add(b ^ c ^ d)
.wrapping_add(e)
.wrapping_add(*word)
.wrapping_add(K[3]);
e = d;
d = c;
c = b.rotate_left(30);
b = a;
a = temp;
}
self.hash[0] = self.hash[0].wrapping_add(a);
self.hash[1] = self.hash[1].wrapping_add(b);
self.hash[2] = self.hash[2].wrapping_add(c);
self.hash[3] = self.hash[3].wrapping_add(d);
self.hash[4] = self.hash[4].wrapping_add(e);
}
pub fn hash(&self) -> &[u32; 5] {
&self.hash
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/fuse_log.rs | drivers/src/fuse_log.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
fuse.rs
Abstract:
Fuse-related Types.
--*/
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
use zeroize::Zeroize;
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FuseLogEntryId {
Invalid = 0,
VendorEccPubKeyIndex = 1, // 4 bytes (From Manifest)
VendorEccPubKeyRevocation = 2, // 4 bytes (From Fuse)
ColdBootFwSvn = 3, // 4 bytes
ManifestReserved0 = 4, // 4 bytes
#[deprecated]
_DeprecatedFuseFmcSvn = 5, // 4 bytes
ManifestFwSvn = 6, // 4 bytes
ManifestReserved1 = 7, // 4 bytes
FuseFwSvn = 8, // 4 bytes
VendorPqcPubKeyIndex = 9, // 4 bytes (From Manifest)
VendorPqcPubKeyRevocation = 10, // 4 bytes (From Fuse)
}
impl From<u32> for FuseLogEntryId {
#[allow(deprecated)]
fn from(id: u32) -> FuseLogEntryId {
match id {
1 => FuseLogEntryId::VendorEccPubKeyIndex,
2 => FuseLogEntryId::VendorEccPubKeyRevocation,
3 => FuseLogEntryId::ColdBootFwSvn,
4 => FuseLogEntryId::ManifestReserved0,
5 => FuseLogEntryId::_DeprecatedFuseFmcSvn,
6 => FuseLogEntryId::ManifestFwSvn,
7 => FuseLogEntryId::ManifestReserved1,
8 => FuseLogEntryId::FuseFwSvn,
9 => FuseLogEntryId::VendorPqcPubKeyIndex,
10 => FuseLogEntryId::VendorPqcPubKeyRevocation,
_ => FuseLogEntryId::Invalid,
}
}
}
/// Fuse log entry
#[repr(C)]
#[derive(IntoBytes, Clone, Copy, Debug, Default, FromBytes, KnownLayout, Immutable, Zeroize)]
pub struct FuseLogEntry {
/// Entry identifier
pub entry_id: u32,
pub log_data: [u32; 1],
pub reserved: [u32; 2],
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/bounded_address.rs | drivers/src/bounded_address.rs | // Licensed under the Apache-2.0 license
use core::fmt::Debug;
use core::marker::PhantomData;
use caliptra_error::CaliptraError;
use zerocopy::{FromBytes, Immutable, IntoBytes, TryFromBytes, Unalign};
use zeroize::Zeroize;
use crate::memory_layout;
pub trait MemBounds {
const ORG: usize;
const SIZE: usize;
const ERROR: CaliptraError;
}
pub struct RomBounds {}
impl MemBounds for RomBounds {
const ORG: usize = memory_layout::ROM_ORG as usize;
const SIZE: usize = memory_layout::ROM_SIZE as usize;
const ERROR: CaliptraError = CaliptraError::ADDRESS_NOT_IN_ROM;
}
pub type RomAddr<T> = BoundedAddr<T, RomBounds>;
#[repr(C)]
#[derive(TryFromBytes, IntoBytes, Immutable)]
pub struct BoundedAddr<T: IntoBytes + FromBytes, B: MemBounds> {
addr: Unalign<u32>,
_phantom: PhantomData<(T, B)>,
}
impl<T, B> Zeroize for BoundedAddr<T, B>
where
T: IntoBytes + FromBytes,
B: MemBounds,
{
fn zeroize(&mut self) {
// This should never fail, and always be aligned.
if let Ok(addr) = self.addr.try_deref_mut() {
addr.zeroize();
}
// NOP since PhantomData has no data, but might as well be thorough.
self._phantom.zeroize();
}
}
impl<T: IntoBytes + FromBytes, B: MemBounds> BoundedAddr<T, B> {
pub fn new(addr: u32) -> Self {
Self {
addr: Unalign::new(addr),
_phantom: Default::default(),
}
}
pub fn get(&self) -> Result<&T, CaliptraError> {
assert!(core::mem::size_of::<Self>() == core::mem::size_of::<u32>());
Self::validate_addr(self.addr.get())?;
Ok(unsafe { &*(self.addr.get() as *const T) })
}
pub fn is_valid(&self) -> bool {
Self::validate_addr(self.addr.get()).is_ok()
}
pub fn validate_addr(addr: u32) -> Result<(), CaliptraError> {
let addr = addr as usize;
if addr % core::mem::align_of::<T>() != 0 {
return Err(CaliptraError::ADDRESS_MISALIGNED);
}
let size = core::mem::size_of::<T>();
if addr < B::ORG || size > B::SIZE || addr > B::ORG + (B::SIZE - size) {
return Err(B::ERROR);
}
Ok(())
}
}
impl<T: IntoBytes + FromBytes, B: MemBounds> Clone for BoundedAddr<T, B> {
fn clone(&self) -> Self {
Self::new(self.addr.get())
}
}
impl<T: IntoBytes + FromBytes, B: MemBounds> Debug for BoundedAddr<T, B> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("RomAddr")
.field("addr", &self.addr.get())
.finish()
}
}
impl<T: IntoBytes + FromBytes, B: MemBounds> From<&'static T> for BoundedAddr<T, B> {
fn from(value: &'static T) -> Self {
Self::new(value as *const T as u32)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memory_layout::{ROM_ORG, ROM_SIZE};
#[derive(IntoBytes, FromBytes)]
#[repr(C)]
struct MyStruct {
a: u32,
b: u32,
}
#[test]
fn test_rom_address_validate() {
RomAddr::<MyStruct>::validate_addr(ROM_ORG).unwrap();
RomAddr::<MyStruct>::validate_addr(ROM_ORG + 4).unwrap();
RomAddr::<MyStruct>::validate_addr(ROM_ORG + ROM_SIZE - 8).unwrap();
RomAddr::<u8>::validate_addr(ROM_ORG + ROM_SIZE - 1).unwrap();
assert_eq!(
RomAddr::<MyStruct>::validate_addr(ROM_ORG + 1),
Err(CaliptraError::ADDRESS_MISALIGNED)
);
assert_eq!(
RomAddr::<MyStruct>::validate_addr(ROM_ORG + 2),
Err(CaliptraError::ADDRESS_MISALIGNED)
);
assert_eq!(
RomAddr::<MyStruct>::validate_addr(ROM_ORG + ROM_SIZE - 4),
Err(CaliptraError::ADDRESS_NOT_IN_ROM)
);
assert_eq!(
RomAddr::<u8>::validate_addr(ROM_ORG + ROM_SIZE),
Err(CaliptraError::ADDRESS_NOT_IN_ROM)
);
assert_eq!(
RomAddr::<u8>::validate_addr(ROM_ORG + ROM_SIZE + 24381),
Err(CaliptraError::ADDRESS_NOT_IN_ROM)
);
assert_eq!(
RomAddr::<[u8; 128 * 1024]>::validate_addr(ROM_ORG),
Err(CaliptraError::ADDRESS_NOT_IN_ROM)
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/dma.rs | drivers/src/dma.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
dma.rs
Abstract:
File contains API for DMA Widget operations
--*/
use crate::{cprintln, Array4x12, Array4x16, Sha2_512_384Acc, ShaAccLockState, SocIfc};
use caliptra_error::{CaliptraError, CaliptraResult};
use caliptra_registers::axi_dma::{
enums::{RdRouteE, WrRouteE},
AxiDmaReg, RegisterBlock,
};
use caliptra_registers::i3ccsr::RegisterBlock as I3CRegisterBlock;
use caliptra_registers::otp_ctrl::RegisterBlock as FuseCtrlRegisterBlock;
use caliptra_registers::sha512_acc::enums::ShaCmdE;
use caliptra_registers::sha512_acc::RegisterBlock as ShaAccRegisterBlock;
use core::{cell::Cell, mem::size_of, ops::Add};
use ureg::{Mmio, MmioMut, RealMmioMut};
const I3C_BLOCK_SIZE: u32 = 64;
pub const MCU_SRAM_OFFSET: u64 = 0xc0_0000;
// SHA384 of empty stream
const SHA384_EMPTY: Array4x12 = Array4x12::new([
0x38b060a7, 0x51ac9638, 0x4cd9327e, 0xb1b1e36a, 0x21fdb711, 0x14be0743, 0x4c0cc7bf, 0x63f6e1da,
0x274edebf, 0xe76f65fb, 0xd51ad2f1, 0x4898b95b,
]);
pub enum DmaReadTarget {
Mbox(u32),
AhbFifo,
AxiWr(AxiAddr, bool),
}
pub enum AesDmaMode {
None,
Aes,
AesGcm,
}
impl AesDmaMode {
pub fn aes(&self) -> bool {
matches!(self, AesDmaMode::Aes | AesDmaMode::AesGcm)
}
pub fn gcm(&self) -> bool {
matches!(self, AesDmaMode::AesGcm)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AxiAddr {
pub lo: u32,
pub hi: u32,
}
impl Add<u32> for AxiAddr {
type Output = Self;
fn add(self, rhs: u32) -> Self {
AxiAddr::from(u64::from(self) + rhs as u64)
}
}
impl Add<u64> for AxiAddr {
type Output = Self;
fn add(self, rhs: u64) -> Self {
AxiAddr::from(u64::from(self) + rhs)
}
}
impl Add<usize> for AxiAddr {
type Output = Self;
fn add(self, rhs: usize) -> Self {
AxiAddr::from(u64::from(self) + rhs as u64)
}
}
impl From<u32> for AxiAddr {
fn from(addr: u32) -> Self {
Self { lo: addr, hi: 0 }
}
}
impl From<u64> for AxiAddr {
fn from(addr: u64) -> Self {
Self {
lo: addr as u32,
hi: (addr >> 32) as u32,
}
}
}
impl From<AxiAddr> for u64 {
fn from(addr: AxiAddr) -> Self {
((addr.hi as u64) << 32) | (addr.lo as u64)
}
}
impl Add for AxiAddr {
type Output = Self;
fn add(self, rhs: Self) -> Self {
let self_u64: u64 = self.into();
let rhs_u64: u64 = rhs.into();
let sum = self_u64 + rhs_u64;
sum.into()
}
}
/// Used to read from an AXI address and DMA the contents to a variety of targets.
pub struct DmaReadTransaction {
pub read_addr: AxiAddr,
pub fixed_addr: bool,
pub length: u32,
pub target: DmaReadTarget,
pub aes_mode: bool,
pub aes_gcm: bool,
pub block_mode: BlockMode,
}
/// Specified the kind of block size to be used for the DMA, either I3C (recovery)
/// or anything else. I3C requires a specific block size to be programmed for
/// DMA to work.
#[derive(Clone, Copy)]
pub enum BlockMode {
/// Reading from the I3C recovery register indirect fifo data
RecoveryIndirectFifoData,
/// Reading from anywhere else
Other,
}
impl DmaReadTransaction {
fn block_size(&self) -> u32 {
match self.block_mode {
BlockMode::RecoveryIndirectFifoData => I3C_BLOCK_SIZE,
BlockMode::Other => 0,
}
}
}
pub enum DmaWriteOrigin {
Mbox(u32),
AhbFifo,
AxiRd(AxiAddr),
KeyVault,
}
/// Used to write to an AXI address from a variety of origins.
pub struct DmaWriteTransaction {
pub write_addr: AxiAddr,
pub fixed_addr: bool,
pub length: u32,
pub origin: DmaWriteOrigin,
pub aes_mode: bool,
pub aes_gcm: bool,
}
/// Dma Widget
/// Safety: only one instance of the DMA widget should be created.
#[derive(Default)]
pub struct Dma {}
impl Dma {
/// Safety: This should never be called in a nested manner to avoid
/// programming conflicts with the underlying DMA registers.
pub fn with_dma<T>(&self, f: impl FnOnce(RegisterBlock<RealMmioMut>) -> T) -> T {
// Safety: Caliptra is single-threaded and only one caller to with_dma
// is allowed at a time, so it is safe to create and consume the
// zero-sized AxiDmaReg here and create a new one each time.
// Since the Mmio interface is immutable, we can't generate a
// around mutable reference to a shared AxiDmaReg without using
// Cell, which bloats the code.
let mut dma = unsafe { AxiDmaReg::new() };
f(dma.regs_mut())
}
// This function is used to flush the DMA FIFO and state machine.
// It does not clear the DMA registers.
pub fn flush(&self) {
self.with_dma(|dma| {
dma.ctrl().write(|c| c.flush(true));
while {
let status0 = dma.status0().read();
status0.busy()
} {}
})
}
pub fn setup_dma_read(&self, read_transaction: DmaReadTransaction) {
self.with_dma(|dma| {
let read_addr = read_transaction.read_addr;
dma.src_addr_l().write(|_| read_addr.lo);
dma.src_addr_h().write(|_| read_addr.hi);
let mut target_addr_lo: u32 = 0;
let mut target_addr_hi: u32 = 0;
match read_transaction.target {
DmaReadTarget::AxiWr(target_addr, _) => {
target_addr_lo = target_addr.lo;
target_addr_hi = target_addr.hi;
}
DmaReadTarget::Mbox(offset) => {
target_addr_lo = offset;
target_addr_hi = 0;
}
_ => {}
}
dma.dst_addr_l().write(|_| target_addr_lo);
dma.dst_addr_h().write(|_| target_addr_hi);
// Set the number of bytes to read.
dma.byte_count().write(|_| read_transaction.length);
// Set the block size.
let block_size = read_transaction.block_size();
dma.block_size().write(|f| f.size(block_size));
dma.ctrl().write(|c| {
c.aes_mode_en(read_transaction.aes_mode)
.aes_gcm_mode(read_transaction.aes_gcm)
// AXI read channel is sent where?
.rd_route(|_| match read_transaction.target {
DmaReadTarget::Mbox(_) => RdRouteE::Mbox,
DmaReadTarget::AhbFifo => RdRouteE::AhbFifo,
DmaReadTarget::AxiWr(_, _) => RdRouteE::AxiWr,
})
.rd_fixed(read_transaction.fixed_addr)
// AXI write channel comes from where?
.wr_route(|_| match read_transaction.target {
DmaReadTarget::AxiWr(_, _) => WrRouteE::AxiRd,
_ => WrRouteE::Disable,
})
.wr_fixed(match read_transaction.target {
DmaReadTarget::AxiWr(_, fixed) => fixed,
_ => false,
})
.go(true)
});
});
}
pub fn setup_dma_write(&self, write_transaction: DmaWriteTransaction) {
self.with_dma(|dma| {
let write_addr = write_transaction.write_addr;
dma.dst_addr_l().write(|_| write_addr.lo);
dma.dst_addr_h().write(|_| write_addr.hi);
let mut source_addr_lo: u32 = 0;
let mut source_addr_hi: u32 = 0;
match write_transaction.origin {
DmaWriteOrigin::AxiRd(origin_addr) => {
source_addr_lo = origin_addr.lo;
source_addr_hi = origin_addr.hi;
}
DmaWriteOrigin::Mbox(offset) => {
source_addr_lo = offset;
source_addr_hi = 0;
}
_ => {}
}
dma.src_addr_l().write(|_| source_addr_lo);
dma.src_addr_h().write(|_| source_addr_hi);
// Set the number of bytes to write.
dma.byte_count().write(|_| write_transaction.length);
// Set the block size (always 0 for DMA writes).
dma.block_size().write(|f| f.size(0));
dma.ctrl().write(|c| {
c.wr_route(|_| match write_transaction.origin {
DmaWriteOrigin::Mbox(_) => WrRouteE::Mbox,
DmaWriteOrigin::AhbFifo => WrRouteE::AhbFifo,
DmaWriteOrigin::AxiRd(_) => WrRouteE::AxiRd,
DmaWriteOrigin::KeyVault => WrRouteE::Keyvault,
})
.wr_fixed(write_transaction.fixed_addr)
.rd_route(|_| match write_transaction.origin {
DmaWriteOrigin::AxiRd(_) => RdRouteE::AxiWr,
_ => RdRouteE::Disable,
})
.rd_fixed(false)
.go(true)
});
})
}
/// Wait for the DMA transaction to complete
///
/// This function will block until the DMA transaction is completed successfully.
/// On a DMA error, this will loop forever.
pub fn wait_for_dma_complete(&self) {
self.with_dma(|dma| {
if dma.status0().read().error() {
let error_type = dma.intr_block_rf().error_internal_intr_r().read();
cprintln!("DMA error! ({:?})", u32::from(error_type));
}
while dma.status0().read().busy() {}
});
}
/// Read data from the DMA FIFO
///
/// # Arguments
///
/// * `read_data` - Buffer to store the read data
///
pub fn dma_read_fifo(&self, read_data: &mut [u32]) {
self.with_dma(|dma| {
for word in read_data.iter_mut() {
// Wait until the FIFO has data. fifo_depth is in DWORDs.
while dma.status0().read().fifo_depth() == 0 {}
let read = dma.read_data().read();
*word = read;
}
});
}
pub fn dma_write_fifo(&self, write_data: u32) {
self.with_dma(|dma| {
let max_fifo_depth = dma.cap().read().fifo_max_depth();
while max_fifo_depth == dma.status0().read().fifo_depth() {}
dma.write_data().write(|_| write_data);
});
}
/// Read a 32-bit word from the specified address
///
/// # Arguments
///
/// * `read_addr` - Address to read from
///
/// # Returns
///
/// * `u32` - Read value
pub fn read_dword(&self, read_addr: AxiAddr) -> u32 {
let mut read_val = [0u32; 1];
self.read_buffer(read_addr, &mut read_val);
read_val[0]
}
/// Read an arbitrary length buffer to fifo and read back the fifo into the provided buffer
///
/// # Arguments
///
/// * `read_addr` - Address to read from
/// * `buffer` - Target location to read to
///
pub fn read_buffer(&self, read_addr: AxiAddr, buffer: &mut [u32]) {
let read_transaction = DmaReadTransaction {
read_addr,
fixed_addr: false,
// Length is in bytes.
length: buffer.len() as u32 * 4,
target: DmaReadTarget::AhbFifo,
aes_mode: false,
aes_gcm: false,
block_mode: BlockMode::Other,
};
self.flush();
self.setup_dma_read(read_transaction);
self.dma_read_fifo(buffer);
self.wait_for_dma_complete();
}
/// Write a 32-bit word to the specified address
///
/// # Arguments
///
/// * `write_addr` - Address to write to
/// * `write_val` - Value to write
///
pub fn write_dword(&self, write_addr: AxiAddr, write_val: u32) {
let write_transaction = DmaWriteTransaction {
write_addr,
fixed_addr: false,
length: core::mem::size_of::<u32>() as u32,
origin: DmaWriteOrigin::AhbFifo,
aes_mode: false,
aes_gcm: false,
};
self.flush();
self.setup_dma_write(write_transaction);
self.dma_write_fifo(write_val);
self.wait_for_dma_complete();
}
/// Indicates if payload is available.
///
/// # Returns
/// true if payload is available, false otherwise
///
pub fn payload_available(&self) -> bool {
self.with_dma(|dma| dma.status0().read().payload_available())
}
/// Used by OCP LOCK to release an MEK to the Encryption Engine key vault
pub fn ocp_lock_key_vault_release(&self, soc: &SocIfc) {
let write_addr = AxiAddr::from(soc.ocp_lock_get_key_release_addr());
let kv_release_size = soc.ocp_lock_get_key_size();
let write_transaction = DmaWriteTransaction {
write_addr,
fixed_addr: false,
length: kv_release_size,
origin: DmaWriteOrigin::KeyVault,
aes_mode: false,
aes_gcm: false,
};
self.setup_dma_write(write_transaction);
self.wait_for_dma_complete();
}
}
// Implementation of the Mmio and MmioMut traits that uses
// the DMA peripheral to implement the actual reads and writes.
pub struct DmaMmio<'a> {
base: AxiAddr,
dma: &'a Dma,
last_error: Cell<Option<CaliptraError>>,
}
impl<'a> DmaMmio<'a> {
pub fn new(base: AxiAddr, dma: &'a Dma) -> Self {
Self {
base,
dma,
last_error: Cell::new(None),
}
}
pub fn check_error<T>(&self, x: T) -> CaliptraResult<T> {
match self.last_error.take() {
Some(err) => Err(err),
None => Ok(x),
}
}
}
impl Mmio for &DmaMmio<'_> {
#[inline(always)]
unsafe fn read_volatile<T: ureg::Uint>(&self, src: *const T) -> T {
// we only support 32-bit reads
if T::TYPE != ureg::UintType::U32 {
unreachable!();
}
let offset = src as usize;
let a = self.dma.read_dword(self.base + offset);
// try_into() will always succeed since we only support u32
a.try_into().unwrap_or_default()
}
}
impl MmioMut for &DmaMmio<'_> {
#[inline(always)]
unsafe fn write_volatile<T: ureg::Uint>(&self, dst: *mut T, src: T) {
// we only support 32-bit writes
if T::TYPE != ureg::UintType::U32 {
unreachable!();
}
// this will always work because we only support u32
if let Ok(src) = src.try_into() {
let offset = dst as usize;
self.dma.write_dword(self.base + offset, src);
}
}
}
// Wrapper around the DMA peripheral that provides access to the I3C recovery interface.
pub struct DmaRecovery<'a> {
recovery_base: AxiAddr,
caliptra_base: AxiAddr,
mci_base: AxiAddr,
dma: &'a Dma,
}
impl<'a> DmaRecovery<'a> {
const RECOVERY_REGISTER_OFFSET: usize = 0x100;
const INDIRECT_FIFO_DATA_OFFSET: u32 = 0x68;
const PROT_CAP2_DEVICE_ID_SUPPORT: u32 = 0x1; // Bit 0 in agent_caps
const PROT_CAP2_DEVICE_STATUS_SUPPORT: u32 = 0x10; // Bit 4 in agent_caps
const PROT_CAP2_PUSH_C_IMAGE_SUPPORT: u32 = 0x80; // Bit 7 in agent_caps
const PROT_CAP2_FLASHLESS_BOOT_VALUE: u32 = 0x800; // Bit 11 in agent_caps
const PROT_CAP2_FIFO_CMS_SUPPORT: u32 = 0x1000; // Bit 12 in agent_caps
const FLASHLESS_STREAMING_BOOT_VALUE: u32 = 0x12;
pub const RECOVERY_STATUS_AWAITING_RECOVERY_IMAGE: u32 = 0x1;
const RECOVERY_STATUS_BOOTING_RECOVERY_IMAGE: u32 = 0x2;
pub const RECOVERY_STATUS_IMAGE_AUTHENTICATION_ERROR: u32 = 0xD;
pub const RECOVERY_STATUS_SUCCESSFUL: u32 = 0x3;
pub const DEVICE_STATUS_READY_TO_ACCEPT_RECOVERY_IMAGE_VALUE: u32 = 0x3;
const DEVICE_STATUS_PENDING: u32 = 0x4;
pub const DEVICE_STATUS_RUNNING_RECOVERY_IMAGE: u32 = 0x5;
pub const DEVICE_STATUS_FATAL_ERROR: u32 = 0xF;
const ACTIVATE_RECOVERY_IMAGE_CMD: u32 = 0xF;
const RESET_VAL: u32 = 0x1;
// offset from the Caliptra base address of the SHA accelerator regs.
const SHA_ACC_OFFSET: usize = 0x2_1000;
#[inline(always)]
pub fn new(
recovery_base: AxiAddr,
caliptra_base: AxiAddr,
mci_base: AxiAddr,
dma: &'a Dma,
) -> Self {
Self {
recovery_base,
caliptra_base,
mci_base,
dma,
}
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn with_regs<T, F>(&self, f: F) -> CaliptraResult<T>
where
F: FnOnce(I3CRegisterBlock<&DmaMmio>) -> T,
{
let mmio = DmaMmio::new(self.recovery_base, self.dma);
// SAFETY: we aren't referencing memory directly
let regs = unsafe {
I3CRegisterBlock::new_with_mmio(
// substract the recovery offset since all recovery registers are relative to 0 but need to be relative to 0x100
core::ptr::null_mut::<u32>()
.sub(Self::RECOVERY_REGISTER_OFFSET / core::mem::size_of::<u32>()),
&mmio,
)
};
let t = f(regs);
mmio.check_error(t)
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn with_regs_mut<T, F>(&self, f: F) -> CaliptraResult<T>
where
F: FnOnce(I3CRegisterBlock<&DmaMmio>) -> T,
{
let mmio = DmaMmio::new(self.recovery_base, self.dma);
// SAFETY: we aren't referencing memory directly
let regs = unsafe {
I3CRegisterBlock::new_with_mmio(
// substract the recovery offset since all recovery registers are relative to 0 but need to be relative to 0x100
core::ptr::null_mut::<u32>()
.sub(Self::RECOVERY_REGISTER_OFFSET / core::mem::size_of::<u32>()),
&mmio,
)
};
let t = f(regs);
mmio.check_error(t)
}
fn with_sha_acc<T, F>(&self, f: F) -> CaliptraResult<T>
where
F: FnOnce(ShaAccRegisterBlock<&DmaMmio>) -> T,
{
let mmio = DmaMmio::new(self.caliptra_base, self.dma);
// SAFETY: we aren't referencing memory directly
let regs = unsafe {
ShaAccRegisterBlock::new_with_mmio(
// add the accelerator offset since all registers are relative to 0x2100 but need to be relative to 0x0
core::ptr::null_mut::<u32>()
.add(Self::SHA_ACC_OFFSET / core::mem::size_of::<u32>()),
&mmio,
)
};
let t = f(regs);
mmio.check_error(t)
}
/// Returns the appropriate block mode for the given AXI address.
fn block_mode_for_addr(&self, addr: AxiAddr) -> BlockMode {
if addr == self.recovery_base + Self::INDIRECT_FIFO_DATA_OFFSET {
BlockMode::RecoveryIndirectFifoData
} else {
BlockMode::Other
}
}
fn transfer_payload_to_mbox(
&self,
read_addr: AxiAddr,
payload_len_bytes: u32,
fixed_addr: bool,
offset: u32,
) -> CaliptraResult<()> {
let read_transaction = DmaReadTransaction {
read_addr,
fixed_addr,
length: payload_len_bytes,
target: DmaReadTarget::Mbox(offset),
aes_mode: false,
aes_gcm: false,
block_mode: self.block_mode_for_addr(read_addr),
};
self.exec_dma_read(read_transaction)?;
Ok(())
}
// Downloads an image from the recovery interface to the mailbox SRAM.
pub fn download_image_to_mbox(&self, fw_image_index: u32) -> CaliptraResult<u32> {
let image_size_bytes = self.request_image(fw_image_index)?;
// Transfer the image from the recovery interface to the mailbox SRAM.
let addr = self.recovery_base + Self::INDIRECT_FIFO_DATA_OFFSET;
self.transfer_payload_to_mbox(addr, image_size_bytes, true, 0)?;
cprintln!("[dma-recovery] Waiting for activation");
self.wait_for_activation()?;
// Set the RECOVERY_STATUS register 'Device Recovery Status' field to 0x2 ('Booting recovery image').
self.set_recovery_status(Self::RECOVERY_STATUS_BOOTING_RECOVERY_IMAGE, fw_image_index)?;
Ok(image_size_bytes)
}
pub fn wait_for_activation(&self) -> CaliptraResult<()> {
self.with_regs_mut(|regs_mut| {
let recovery = regs_mut.sec_fw_recovery_if();
// Set device status to 'Recovery Pending (waiting for activation)'.
recovery
.device_status_0()
.modify(|val| val.dev_status(Self::DEVICE_STATUS_PENDING));
// Read RECOVERY_CTRL register 'Activate Recovery Image' field for 'Activate Recovery Image' (0xF) command.
while recovery.recovery_ctrl().read().activate_rec_img()
!= Self::ACTIVATE_RECOVERY_IMAGE_CMD
{}
})
}
// Downloads an image from the recovery interface to the MCU SRAM.
pub fn download_image_to_mcu(
&self,
fw_image_index: u32,
aes_mode: AesDmaMode,
) -> CaliptraResult<u32> {
let image_size_bytes = self.request_image(fw_image_index)?;
let addr = self.recovery_base + Self::INDIRECT_FIFO_DATA_OFFSET;
self.transfer_payload_to_axi(
addr,
image_size_bytes,
self.mci_base + MCU_SRAM_OFFSET,
true,
false,
aes_mode,
)?;
self.wait_for_activation()?;
// Set the RECOVERY_STATUS:Byte0 Bit[3:0] to 0x2 ('Booting recovery image').
self.set_recovery_status(Self::RECOVERY_STATUS_BOOTING_RECOVERY_IMAGE, fw_image_index)?;
Ok(image_size_bytes)
}
// Downloads an image from the recovery interface to caliptra using FIFO.
pub fn download_image_to_caliptra(
&self,
fw_image_index: u32,
buffer: &mut [u32],
) -> CaliptraResult<u32> {
let image_size_bytes = self.request_image(fw_image_index)?;
// Transfer the image from the recovery interface via AHB FIFO.
let addr = self.recovery_base + Self::INDIRECT_FIFO_DATA_OFFSET;
#[cfg(any(feature = "fpga_realtime", feature = "fpga_subsystem"))]
{
// FPGA implementation: wait for FIFO to be not empty and read dword by dword
let len = (image_size_bytes as usize / 4).min(buffer.len());
for i in 0..len {
// Wait for FIFO to not be empty before each read_dword.
self.with_regs(|r| {
while r
.sec_fw_recovery_if()
.indirect_fifo_status_0()
.read()
.empty()
{}
})?;
buffer[i] = self.dma.read_dword(addr);
}
}
#[cfg(not(any(feature = "fpga_realtime", feature = "fpga_subsystem")))]
{
let read_transaction = DmaReadTransaction {
read_addr: addr,
fixed_addr: true,
length: image_size_bytes,
target: DmaReadTarget::AhbFifo,
aes_mode: false,
aes_gcm: false,
block_mode: BlockMode::RecoveryIndirectFifoData,
};
self.dma.flush();
self.dma.setup_dma_read(read_transaction);
self.dma.dma_read_fifo(buffer);
self.dma.wait_for_dma_complete();
}
cprintln!("[dma-recovery] Waiting for activation");
self.wait_for_activation()?;
// Set the RECOVERY_STATUS register 'Device Recovery Status' field to 0x2 ('Booting recovery image').
self.set_recovery_status(Self::RECOVERY_STATUS_BOOTING_RECOVERY_IMAGE, 0)?;
Ok(image_size_bytes)
}
/// Load data from MCU SRAM to a provided buffer
///
/// # Arguments
///
/// * `offset` - Offset within MCU SRAM to read from
/// * `buffer` - Buffer to store the read data
///
pub fn load_from_mcu_to_buffer(&self, offset: u64, buffer: &mut [u32]) -> CaliptraResult<()> {
let source_addr = self.mci_base + MCU_SRAM_OFFSET + offset;
self.dma.read_buffer(source_addr, buffer);
Ok(())
}
// Request the recovery interface load an image.
pub fn request_image(&self, fw_image_index: u32) -> CaliptraResult<u32> {
cprintln!(
"[dma-recovery] Requesting recovery image {}",
fw_image_index
);
self.with_regs_mut(|regs_mut| {
let recovery = regs_mut.sec_fw_recovery_if();
// Set PROT_CAP2.AGENT_CAPS
// - Bit0 to 1 ('Device ID support')
// - Bit4 to 1 ('Device Status support')
// - Bit7 to 1 ('Push C-image support')
// - Bit11 to 1 ('Flashless boot')
// - Bit12 to 1 ('FIFO CMS support')
// Set PROT_CAP2.REC_PROT_VERSION to 0x101 (1.1).
recovery.prot_cap_2().modify(|val| {
val.agent_caps(
Self::PROT_CAP2_DEVICE_ID_SUPPORT // mandatory
| Self::PROT_CAP2_DEVICE_STATUS_SUPPORT // mandatory
| Self::PROT_CAP2_FIFO_CMS_SUPPORT
| Self::PROT_CAP2_FLASHLESS_BOOT_VALUE
| Self::PROT_CAP2_PUSH_C_IMAGE_SUPPORT,
)
.rec_prot_version(0x101) // 1.1
});
// Set DEVICE_STATUS:Byte0 to 0x3 ('Recovery mode - ready to accept recovery image').
// Set DEVICE_STATUS:Byte[2:3] to 0x12 ('Recovery Reason Codes' 0x12 - Flashless/Streaming Boot (FSB)).
cprintln!(
"[dma-recovery] Set device status {}",
Self::DEVICE_STATUS_READY_TO_ACCEPT_RECOVERY_IMAGE_VALUE
);
recovery.device_status_0().modify(|val| {
val.rec_reason_code(Self::FLASHLESS_STREAMING_BOOT_VALUE)
.dev_status(Self::DEVICE_STATUS_READY_TO_ACCEPT_RECOVERY_IMAGE_VALUE)
});
// Set RECOVERY_STATUS register 'Device Recovery Status' field to 0x1 ('Awaiting recovery image')
// and 'Recovery Image Index' to recovery image index.
recovery.recovery_status().modify(|recovery_status_val| {
recovery_status_val
.rec_img_index(fw_image_index)
.dev_rec_status(Self::RECOVERY_STATUS_AWAITING_RECOVERY_IMAGE)
});
})?;
// Loop on the 'payload_available' signal for the recovery image details to be available.
while !self.dma.payload_available() {}
let image_size_bytes = self.with_regs_mut(|regs_mut| {
let recovery = regs_mut.sec_fw_recovery_if();
// Read the image size from INDIRECT_FIFO_CTRL1 register. Image size is in DWORDs.
let image_size_dwords = recovery.indirect_fifo_ctrl_1().read();
let image_size_bytes = image_size_dwords * size_of::<u32>() as u32;
cprintln!(
"[dma-recovery] Payload available, {} bytes",
image_size_bytes
);
Ok::<u32, CaliptraError>(image_size_bytes)
})??;
Ok(image_size_bytes)
}
pub fn set_recovery_status(&self, status: u32, image_idx: u32) -> CaliptraResult<()> {
self.with_regs_mut(|regs_mut| {
let recovery = regs_mut.sec_fw_recovery_if();
recovery.recovery_status().modify(|recovery_status_val| {
recovery_status_val
.rec_img_index(image_idx)
.dev_rec_status(status)
});
})
}
pub fn set_device_status(&self, status: u32) -> CaliptraResult<()> {
self.with_regs_mut(|regs_mut| {
let recovery = regs_mut.sec_fw_recovery_if();
recovery
.device_status_0()
.modify(|device_status_val| device_status_val.dev_status(status));
})
}
pub fn reset_recovery_ctrl_activate_rec_img(&self) -> CaliptraResult<()> {
self.with_regs_mut(|regs_mut| {
let recovery = regs_mut.sec_fw_recovery_if();
recovery
.recovery_ctrl()
.modify(|recovery_ctrl_val| recovery_ctrl_val.activate_rec_img(Self::RESET_VAL));
})
}
pub fn transfer_payload_to_axi(
&self,
read_addr: AxiAddr,
payload_len_bytes: u32,
write_addr: AxiAddr,
read_fixed_addr: bool,
write_fixed_addr: bool,
aes_mode: AesDmaMode,
) -> CaliptraResult<()> {
let read_transaction = DmaReadTransaction {
read_addr,
fixed_addr: read_fixed_addr,
length: payload_len_bytes,
target: DmaReadTarget::AxiWr(write_addr, write_fixed_addr),
aes_mode: aes_mode.aes(),
aes_gcm: aes_mode.gcm(),
block_mode: self.block_mode_for_addr(read_addr),
};
self.exec_dma_read(read_transaction)?;
Ok(())
}
// TODO: remove this when the FPGA can do fixed burst transfers
#[cfg(any(feature = "fpga_realtime", feature = "fpga_subsystem"))]
fn exec_dma_read(&self, read_transaction: DmaReadTransaction) -> CaliptraResult<()> {
// Flush DMA before doing anything
self.dma.flush();
for i in (0..read_transaction.length).step_by(4) {
// if this is an I3C transfer, wait for the FIFO to be not empty
if matches!(
read_transaction.block_mode,
BlockMode::RecoveryIndirectFifoData
) {
self.with_regs(|r| {
while r
.sec_fw_recovery_if()
.indirect_fifo_status_0()
.read()
.empty()
{}
})?;
}
// translate to single dword transfer
match read_transaction.target {
DmaReadTarget::AxiWr(addr, fixed) => {
let word = self.dma.read_dword(
read_transaction.read_addr
+ if read_transaction.fixed_addr { 0 } else { i },
);
self.dma.write_dword(addr + if fixed { 0 } else { i }, word);
}
DmaReadTarget::Mbox(offset) => {
let rd_tx = DmaReadTransaction {
read_addr: read_transaction.read_addr
+ if read_transaction.fixed_addr { 0 } else { i },
fixed_addr: false,
length: 4,
target: DmaReadTarget::Mbox(offset + i as u32),
aes_mode: false,
aes_gcm: false,
block_mode: read_transaction.block_mode,
};
self.dma.flush();
self.dma.setup_dma_read(rd_tx);
self.dma.wait_for_dma_complete();
}
_ => Err(CaliptraError::DRIVER_DMA_SHA_ACCELERATOR_NOT_LOCKED)?, // should be unreachable
};
}
Ok(())
}
#[cfg(not(any(feature = "fpga_realtime", feature = "fpga_subsystem")))]
fn exec_dma_read(&self, read_transaction: DmaReadTransaction) -> CaliptraResult<()> {
self.dma.flush();
self.dma.setup_dma_read(read_transaction);
self.dma.wait_for_dma_complete();
Ok(())
}
pub fn sha384_mcu_sram(
&self,
sha_acc: &'a mut Sha2_512_384Acc,
base: u32,
length: u32,
aes_mode: AesDmaMode,
) -> CaliptraResult<Array4x12> {
let source = self.mci_base + MCU_SRAM_OFFSET + AxiAddr::from(base);
self.sha384_image(sha_acc, source, length, aes_mode)
}
pub fn sha512_mcu_sram(
&self,
sha_acc: &'a mut Sha2_512_384Acc,
base: u32,
length: u32,
aes_mode: AesDmaMode,
) -> CaliptraResult<Array4x16> {
let source = self.mci_base + MCU_SRAM_OFFSET + AxiAddr::from(base);
self.sha512_image(sha_acc, source, length, aes_mode)
}
pub fn sha384_image(
&self,
sha_acc: &'a mut Sha2_512_384Acc,
source: AxiAddr,
length: u32,
aes_mode: AesDmaMode,
) -> CaliptraResult<Array4x12> {
// the hardware does not support hashing an empty stream
if length == 0 {
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/pcr_bank.rs | drivers/src/pcr_bank.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
pcr_bank.rs
Abstract:
File contains API for managing Platform Configuration Register (PCR) Bank.
--*/
use crate::{Array4x12, CaliptraError, CaliptraResult, Sha2_512_384};
use caliptra_registers::pv::PvReg;
/// PCR Identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PcrId {
PcrId0 = 0,
PcrId1 = 1,
PcrId2 = 2,
PcrId3 = 3,
PcrId4 = 4,
PcrId5 = 5,
PcrId6 = 6,
PcrId7 = 7,
PcrId8 = 8,
PcrId9 = 9,
PcrId10 = 10,
PcrId11 = 11,
PcrId12 = 12,
PcrId13 = 13,
PcrId14 = 14,
PcrId15 = 15,
PcrId16 = 16,
PcrId17 = 17,
PcrId18 = 18,
PcrId19 = 19,
PcrId20 = 20,
PcrId21 = 21,
PcrId22 = 22,
PcrId23 = 23,
PcrId24 = 24,
PcrId25 = 25,
PcrId26 = 26,
PcrId27 = 27,
PcrId28 = 28,
PcrId29 = 29,
PcrId30 = 30,
PcrId31 = 31,
}
impl From<PcrId> for u32 {
/// Converts to this type from the input type.
fn from(id: PcrId) -> Self {
id as Self
}
}
impl From<PcrId> for usize {
/// Converts to this type from the input type.
fn from(id: PcrId) -> Self {
id as Self
}
}
impl TryFrom<u8> for PcrId {
type Error = ();
fn try_from(original: u8) -> Result<Self, Self::Error> {
match original {
0 => Ok(Self::PcrId0),
1 => Ok(Self::PcrId1),
2 => Ok(Self::PcrId2),
3 => Ok(Self::PcrId3),
4 => Ok(Self::PcrId4),
5 => Ok(Self::PcrId5),
6 => Ok(Self::PcrId6),
7 => Ok(Self::PcrId7),
8 => Ok(Self::PcrId8),
9 => Ok(Self::PcrId9),
10 => Ok(Self::PcrId10),
11 => Ok(Self::PcrId11),
12 => Ok(Self::PcrId12),
13 => Ok(Self::PcrId13),
14 => Ok(Self::PcrId14),
15 => Ok(Self::PcrId15),
16 => Ok(Self::PcrId16),
17 => Ok(Self::PcrId17),
18 => Ok(Self::PcrId18),
19 => Ok(Self::PcrId19),
20 => Ok(Self::PcrId20),
21 => Ok(Self::PcrId21),
22 => Ok(Self::PcrId22),
23 => Ok(Self::PcrId23),
24 => Ok(Self::PcrId24),
25 => Ok(Self::PcrId25),
26 => Ok(Self::PcrId26),
27 => Ok(Self::PcrId27),
28 => Ok(Self::PcrId28),
29 => Ok(Self::PcrId29),
30 => Ok(Self::PcrId30),
31 => Ok(Self::PcrId31),
_ => Err(()),
}
}
}
/// Platform Configuration Register (PCR) Bank
pub struct PcrBank {
pv: PvReg,
}
impl PcrBank {
pub const ALL_PCR_IDS: [PcrId; 32] = [
PcrId::PcrId0,
PcrId::PcrId1,
PcrId::PcrId2,
PcrId::PcrId3,
PcrId::PcrId4,
PcrId::PcrId5,
PcrId::PcrId6,
PcrId::PcrId7,
PcrId::PcrId8,
PcrId::PcrId9,
PcrId::PcrId10,
PcrId::PcrId11,
PcrId::PcrId12,
PcrId::PcrId13,
PcrId::PcrId14,
PcrId::PcrId15,
PcrId::PcrId16,
PcrId::PcrId17,
PcrId::PcrId18,
PcrId::PcrId19,
PcrId::PcrId20,
PcrId::PcrId21,
PcrId::PcrId22,
PcrId::PcrId23,
PcrId::PcrId24,
PcrId::PcrId25,
PcrId::PcrId26,
PcrId::PcrId27,
PcrId::PcrId28,
PcrId::PcrId29,
PcrId::PcrId30,
PcrId::PcrId31,
];
pub fn new(pv: PvReg) -> Self {
Self { pv }
}
/// Erase all the pcrs in the pcr vault
///
/// Note: The pcrs that have "use" lock set will not be erased
pub fn erase_all_pcrs(&mut self) {
for id in PcrBank::ALL_PCR_IDS {
if !self.pcr_lock(id) {
let pv = self.pv.regs_mut();
pv.pcr_ctrl().at(id.into()).write(|w| w.clear(true));
}
}
}
/// Erase specified pcr
///
/// # Arguments
///
/// * `id` - PCR ID to erase
pub fn erase_pcr(&mut self, id: PcrId) -> CaliptraResult<()> {
if self.pcr_lock(id) {
return Err(CaliptraError::DRIVER_PCR_BANK_ERASE_WRITE_LOCK_SET_FAILURE);
}
let pv = self.pv.regs_mut();
pv.pcr_ctrl().at(id.into()).write(|w| w.clear(true));
Ok(())
}
/// Retrieve the 'lock for clear' status for a PCR
///
/// # Arguments
///
/// * `id` - PCR ID
///
/// # Returns
///
/// * `true` - If the PCR is locked for clear
/// * `false` - If the PCR is not locked for clear
pub fn pcr_lock(&self, id: PcrId) -> bool {
let pv = self.pv.regs();
pv.pcr_ctrl().at(id.into()).read().lock()
}
/// Set the 'lock for clear' setting for a PCR
///
/// # Arguments
///
/// * `id` - PCR ID
pub fn set_pcr_lock(&mut self, id: PcrId) {
let pv = self.pv.regs_mut();
pv.pcr_ctrl().at(id.into()).write(|w| w.lock(true))
}
/// Clear the 'lock for clear' setting for a PCR
///
/// # Arguments
///
/// * `id` - PCR ID
pub fn clear_pcr_lock(&mut self, id: PcrId) {
let pv = self.pv.regs_mut();
pv.pcr_ctrl().at(id.into()).write(|w| w.lock(false))
}
/// Read the value of a PCR
///
/// # Arguments
///
/// * `id` - PCR ID
///
/// # Returns
///
/// * `Array4x12` - PCR value
#[inline(never)]
pub fn read_pcr(&self, id: PcrId) -> Array4x12 {
let pv = self.pv.regs();
let mut result = Array4x12::default();
for i in 0..result.0.len() {
result.0[i] = pv.pcr_entry().at(id.into()).at(i).read();
}
result
}
/// Read the value of all PCRs
///
/// # Returns
///
/// * `[Array4x12; 32]` - All PCR values
#[cfg(feature = "runtime")]
pub fn read_all_pcrs(&self) -> [Array4x12; 32] {
Self::ALL_PCR_IDS
.into_iter()
.map(|pcr_id| self.read_pcr(pcr_id))
.enumerate()
.fold(
[Array4x12::default(); PcrBank::ALL_PCR_IDS.len()],
|mut acc, (index, next)| {
acc[index] = next;
acc
},
)
}
/// Extend the PCR with specified data
///
/// # Arguments
///
/// * `id` - PCR ID
/// * `sha` - SHA2-384 Engine
/// * `data` - Data to extend
///
pub fn extend_pcr(
&self,
id: PcrId,
sha2: &mut Sha2_512_384,
data: &[u8],
) -> CaliptraResult<()> {
sha2.pcr_extend(id, data)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/sha256.rs | drivers/src/sha256.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha256.rs
Abstract:
File contains API for SHA-256 Cryptography operations
--*/
use crate::{array::Array4x16, wait, Array4x8, CaliptraError, CaliptraResult};
use caliptra_registers::sha256::Sha256Reg;
use zeroize::Zeroize;
const SHA256_BLOCK_BYTE_SIZE: usize = 64;
const SHA256_BLOCK_LEN_OFFSET: usize = 56;
const SHA256_MAX_DATA_SIZE: usize = 1024 * 1024;
pub trait Sha256DigestOp<'a> {
fn update(&mut self, data: &[u8]) -> CaliptraResult<()>;
fn update_wntz(&mut self, data: &[u8], w_value: u8, n_mode: bool) -> CaliptraResult<()>;
/// # Arguments
///
/// * `digest` - result of the sha256 digest operation
fn finalize(self, digest: &mut Array4x8) -> CaliptraResult<()>;
/// # Arguments
///
/// * `digest` - result of the sha256 digest operation
/// * `w_value` - Winternitz W value.
/// * `n_mode` - Winternitz n value(SHA192/SHA256 --> n = 24/32)
fn finalize_wntz(self, digest: &mut Array4x8, w_value: u8, n_mode: bool) -> CaliptraResult<()>;
}
pub trait Sha256Alg {
type DigestOp<'a>: Sha256DigestOp<'a>
where
Self: 'a;
fn digest_init(&mut self) -> CaliptraResult<Self::DigestOp<'_>>;
fn digest(&mut self, buf: &[u8]) -> CaliptraResult<Array4x8>;
}
pub struct Sha256 {
sha256: Sha256Reg,
}
impl Sha256 {
pub fn new(sha256: Sha256Reg) -> Self {
Self { sha256 }
}
}
impl Sha256Alg for Sha256 {
type DigestOp<'a> = Sha256DigestOpHw<'a>;
/// Initialize multi step digest operation
///
/// # Returns
///
/// * `Sha256Digest` - Object representing the digest operation
fn digest_init(&mut self) -> CaliptraResult<Sha256DigestOpHw<'_>> {
let op = Sha256DigestOpHw {
sha: self,
state: Sha256DigestState::Init,
buf: [0u8; SHA256_BLOCK_BYTE_SIZE],
buf_idx: 0,
data_size: 0,
};
Ok(op)
}
/// Calculate the digest of the buffer
///
/// # Arguments
///
/// * `buf` - Buffer to calculate the digest over
fn digest(&mut self, buf: &[u8]) -> CaliptraResult<Array4x8> {
#[cfg(feature = "fips-test-hooks")]
unsafe {
crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::SHA256_DIGEST_FAILURE)?
}
// Check if the buffer is not large
if buf.len() > SHA256_MAX_DATA_SIZE {
return Err(CaliptraError::DRIVER_SHA256_MAX_DATA);
}
let mut first = true;
let mut bytes_remaining = buf.len();
loop {
let offset = buf.len() - bytes_remaining;
match bytes_remaining {
0..=63 => {
// PANIC-FREE: Use buf.get() instead if buf[] as the compiler
// cannot reason about `offset` parameter to optimize out
// the panic.
if let Some(slice) = buf.get(offset..) {
self.digest_partial_block(slice, first, buf.len())?;
break;
} else {
return Err(CaliptraError::DRIVER_SHA256_INVALID_SLICE);
}
}
_ => {
// PANIC-FREE: Use buf.get() instead if buf[] as the compiler
// cannot reason about `offset` parameter to optimize out
// the panic call.
if let Some(slice) = buf.get(offset..offset + SHA256_BLOCK_BYTE_SIZE) {
let block = <&[u8; SHA256_BLOCK_BYTE_SIZE]>::try_from(slice).unwrap();
self.digest_block(block, first)?;
bytes_remaining -= SHA256_BLOCK_BYTE_SIZE;
first = false;
} else {
return Err(CaliptraError::DRIVER_SHA256_INVALID_SLICE);
}
}
}
}
let digest = Array4x8::read_from_reg(self.sha256.regs().digest());
#[cfg(feature = "fips-test-hooks")]
let digest = unsafe {
crate::FipsTestHook::corrupt_data_if_hook_set(
crate::FipsTestHook::SHA256_CORRUPT_DIGEST,
&digest,
)
};
self.zeroize_internal();
Ok(digest)
}
}
impl Sha256 {
/// Take a raw sha256 digest of 0 or more 64-byte blocks of memory. Unlike
/// digest(), the each word is passed to the sha256 peripheral without
/// byte-swapping to reverse the peripheral's big-endian words. This means the
/// hash will be measured with the byte-swapped value of each word.
///
/// # Safety
///
/// The caller is responsible for ensuring that the safety requirements of
/// [`core::ptr::read`] are valid for every value between `ptr.add(0)` and
/// `ptr.add(n_blocks - 1)`.
#[inline(always)]
pub unsafe fn digest_blocks_raw(
&mut self,
mut ptr: *const [u32; 16],
n_blocks: usize,
) -> CaliptraResult<Array4x8> {
for i in 0..n_blocks {
self.sha256.regs_mut().block().write_ptr(ptr);
self.digest_op(i == 0)?;
ptr = ptr.wrapping_add(1);
}
self.digest_partial_block(&[], n_blocks == 0, n_blocks * 64)?;
Ok(Array4x8::read_from_reg(self.sha256.regs_mut().digest()))
}
/// Zeroize the hardware registers.
fn zeroize_internal(&mut self) {
self.sha256.regs_mut().ctrl().write(|w| w.zeroize(true));
}
/// Zeroize the hardware registers.
///
/// This is useful to call from a fatal-error-handling routine.
///
/// # Safety
///
/// The caller must be certain that the results of any pending cryptographic
/// operations will not be used after this function is called.
///
/// This function is safe to call from a trap handler.
pub unsafe fn zeroize() {
let mut sha256 = Sha256Reg::new();
sha256.regs_mut().ctrl().write(|w| w.zeroize(true));
}
/// Copy digest to buffer
///
/// # Arguments
///
/// * `buf` - Digest buffer
fn copy_digest_to_buf(&mut self, buf: &mut Array4x8) -> CaliptraResult<()> {
let sha256 = self.sha256.regs();
*buf = Array4x8::read_from_reg(sha256.digest());
Ok(())
}
/// Calculate the digest of the last block
///
/// # Arguments
///
/// * `slice` - Slice of buffer to digest
/// * `first` - Flag indicating if this is the first buffer
/// * `buf_size` - Total buffer size
fn digest_partial_block(
&mut self,
slice: &[u8],
first: bool,
buf_size: usize,
) -> CaliptraResult<()> {
/// Set block length
fn set_block_len(buf_size: usize, block: &mut [u8; SHA256_BLOCK_BYTE_SIZE]) {
let bit_len = (buf_size as u64) << 3;
block[SHA256_BLOCK_LEN_OFFSET..].copy_from_slice(&bit_len.to_be_bytes());
}
// Construct the block
let mut block = [0u8; SHA256_BLOCK_BYTE_SIZE];
// PANIC-FREE: Following check optimizes the out of bounds
// panic in copy_from_slice
if slice.len() > block.len() - 1 {
return Err(CaliptraError::DRIVER_SHA256_INDEX_OUT_OF_BOUNDS);
}
block[..slice.len()].copy_from_slice(slice);
block[slice.len()] = 0b1000_0000;
if slice.len() < SHA256_BLOCK_LEN_OFFSET {
set_block_len(buf_size, &mut block);
}
// Calculate the digest of the op
self.digest_block(&block, first)?;
// Add a padding block if one is needed
if slice.len() >= SHA256_BLOCK_LEN_OFFSET {
block.fill(0);
set_block_len(buf_size, &mut block);
self.digest_block(&block, false)?;
}
Ok(())
}
/// Calculate the digest of the last block
///
/// # Arguments
///
/// * `slice` - Slice of buffer to digest
/// * `first` - Flag indicating if this is the first buffer
/// * `buf_size` - Total buffer size
/// * `w_value` - Winternitz W value.
/// * `n_mode` - Winternitz n value(SHA192/SHA256 --> n = 24/32)
fn digest_wntz_partial_block(
&mut self,
slice: &[u8],
first: bool,
buf_size: usize,
w_value: u8,
n_mode: bool,
) -> CaliptraResult<()> {
/// Set block length
fn set_block_len(buf_size: usize, block: &mut [u8; SHA256_BLOCK_BYTE_SIZE]) {
let bit_len = (buf_size as u64) << 3;
block[SHA256_BLOCK_LEN_OFFSET..].copy_from_slice(&bit_len.to_be_bytes());
}
// Construct the block
let mut block = [0u8; SHA256_BLOCK_BYTE_SIZE];
// PANIC-FREE: Following check optimizes the out of bounds
// panic in copy_from_slice
if slice.len() > block.len() - 1 {
return Err(CaliptraError::DRIVER_SHA256_INDEX_OUT_OF_BOUNDS);
}
block[..slice.len()].copy_from_slice(slice);
block[slice.len()] = 0b1000_0000;
if slice.len() < SHA256_BLOCK_LEN_OFFSET {
set_block_len(buf_size, &mut block);
}
// Calculate the digest of the op
self.digest_wntz_block(&block, first, w_value, n_mode)?;
// Add a padding block if one is needed
if slice.len() >= SHA256_BLOCK_LEN_OFFSET {
block.fill(0);
set_block_len(buf_size, &mut block);
self.digest_wntz_block(&block, false, w_value, n_mode)?;
}
Ok(())
}
/// Calculate digest of the full block
///
/// # Arguments
///
/// * `block`: Block to calculate the digest
/// * `first` - Flag indicating if this is the first block
fn digest_block(
&mut self,
block: &[u8; SHA256_BLOCK_BYTE_SIZE],
first: bool,
) -> CaliptraResult<()> {
let sha256 = self.sha256.regs_mut();
Array4x16::from(block).write_to_reg(sha256.block());
self.digest_op(first)
}
/// Calculate digest of the full block
///
/// # Arguments
///
/// * `block`: Block to calculate the digest
/// * `first` - Flag indicating if this is the first block
/// * `w_value` - Winternitz W value.
/// * `n_mode` - Winternitz n value(SHA192/SHA256 --> n = 24/32)
fn digest_wntz_block(
&mut self,
block: &[u8; SHA256_BLOCK_BYTE_SIZE],
first: bool,
w_value: u8,
n_mode: bool,
) -> CaliptraResult<()> {
let sha256 = self.sha256.regs_mut();
Array4x16::from(block).write_to_reg(sha256.block());
self.digest_wntz_op(first, w_value, n_mode)
}
// Perform the digest operation in the hardware
//
// # Arguments
//
/// * `first` - Flag indicating if this is the first block
fn digest_op(&mut self, first: bool) -> CaliptraResult<()> {
let sha256 = self.sha256.regs_mut();
// Wait for the hardware to be ready
wait::until(|| sha256.status().read().ready());
sha256
.ctrl()
.write(|w| w.wntz_mode(false).mode(true).init(first).next(!first));
// Wait for the digest operation to finish
wait::until(|| sha256.status().read().valid());
Ok(())
}
// Perform the digest operation in the hardware
//
// # Arguments
//
/// * `first` - Flag indicating if this is the first block
/// * `w_value` - Winternitz W value.
/// * `n_mode` - Winternitz n value(SHA192/SHA256 --> n = 24/32)
fn digest_wntz_op(&mut self, first: bool, w_value: u8, n_mode: bool) -> CaliptraResult<()> {
let sha256 = self.sha256.regs_mut();
// Wait for the hardware to be ready
wait::until(|| sha256.status().read().ready());
// Submit the first block
sha256.ctrl().write(|w| {
w.wntz_n_mode(n_mode)
.wntz_w(w_value.into())
.wntz_mode(true)
.mode(true)
.init(first)
.next(!first)
});
// Wait for the digest operation to finish
wait::until(|| sha256.status().read().valid());
Ok(())
}
}
/// SHA-256 Digest state
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Sha256DigestState {
/// Initial state
Init,
/// Pending state
Pending,
/// Final state
Final,
}
/// Multi step SHA-256 digest operation
#[derive(Zeroize)]
pub struct Sha256DigestOpHw<'a> {
/// SHA-256 Engine
#[zeroize(skip)]
sha: &'a mut Sha256,
/// State
#[zeroize(skip)]
state: Sha256DigestState,
/// Staging buffer
buf: [u8; SHA256_BLOCK_BYTE_SIZE],
/// Current staging buffer index
buf_idx: usize,
/// Data size
data_size: usize,
}
impl<'a> Sha256DigestOp<'a> for Sha256DigestOpHw<'a> {
/// Update the digest with data
///
/// # Arguments
///
/// * `data` - Data to used to update the digest
fn update(&mut self, data: &[u8]) -> CaliptraResult<()> {
if self.state == Sha256DigestState::Final {
return Err(CaliptraError::DRIVER_SHA256_INVALID_STATE);
}
if self.data_size + data.len() > SHA256_MAX_DATA_SIZE {
return Err(CaliptraError::DRIVER_SHA256_MAX_DATA);
}
for byte in data {
self.data_size += 1;
// PANIC-FREE: Following check optimizes the out of bounds
// panic in indexing the `buf`
if self.buf_idx >= self.buf.len() {
return Err(CaliptraError::DRIVER_SHA256_INDEX_OUT_OF_BOUNDS);
}
// Copy the data to the buffer
self.buf[self.buf_idx] = *byte;
self.buf_idx += 1;
// If the buffer is full calculate the digest of accumulated data
if self.buf_idx == self.buf.len() {
self.sha.digest_block(&self.buf, self.is_first())?;
self.reset_buf_state();
}
}
Ok(())
}
/// Update the digest with data
///
/// # Arguments
///
/// * `data` - Data to used to update the digest
/// * `w_value` - Winternitz W value.
/// * `n_mode` - Winternitz n value(SHA192/SHA256 --> n = 24/32)
fn update_wntz(&mut self, data: &[u8], w_value: u8, n_mode: bool) -> CaliptraResult<()> {
if self.state == Sha256DigestState::Final {
return Err(CaliptraError::DRIVER_SHA256_INVALID_STATE);
}
if self.data_size + data.len() > SHA256_MAX_DATA_SIZE {
return Err(CaliptraError::DRIVER_SHA256_MAX_DATA);
}
for byte in data {
self.data_size += 1;
// PANIC-FREE: Following check optimizes the out of bounds
// panic in indexing the `buf`
if self.buf_idx >= self.buf.len() {
return Err(CaliptraError::DRIVER_SHA256_INDEX_OUT_OF_BOUNDS);
}
// Copy the data to the buffer
self.buf[self.buf_idx] = *byte;
self.buf_idx += 1;
// If the buffer is full calculate the digest of accumulated data
if self.buf_idx == self.buf.len() {
self.sha
.digest_wntz_block(&self.buf, self.is_first(), w_value, n_mode)?;
self.reset_buf_state();
}
}
Ok(())
}
/// Finalize the digest operations
fn finalize(mut self, digest: &mut Array4x8) -> CaliptraResult<()> {
if self.state == Sha256DigestState::Final {
return Err(CaliptraError::DRIVER_SHA256_INVALID_STATE);
}
if self.buf_idx > self.buf.len() {
return Err(CaliptraError::DRIVER_SHA256_INVALID_SLICE);
}
// Calculate the digest of the final block
let buf = &self.buf[..self.buf_idx];
self.sha
.digest_partial_block(buf, self.is_first(), self.data_size)?;
// Set the state of the operation to final
self.state = Sha256DigestState::Final;
// Copy digest
self.sha.copy_digest_to_buf(digest)?;
Ok(())
}
/// Finalize the digest operations
fn finalize_wntz(
mut self,
digest: &mut Array4x8,
w_value: u8,
n_mode: bool,
) -> CaliptraResult<()> {
if self.state == Sha256DigestState::Final {
return Err(CaliptraError::DRIVER_SHA256_INVALID_STATE);
}
if self.buf_idx > self.buf.len() {
return Err(CaliptraError::DRIVER_SHA256_INVALID_SLICE);
}
// Calculate the digest of the final block
let buf = &self.buf[..self.buf_idx];
self.sha.digest_wntz_partial_block(
buf,
self.is_first(),
self.data_size,
w_value,
n_mode,
)?;
// Set the state of the operation to final
self.state = Sha256DigestState::Final;
// Copy digest
self.sha.copy_digest_to_buf(digest)?;
Ok(())
}
}
impl Sha256DigestOpHw<'_> {
/// Check if this the first digest operation
fn is_first(&self) -> bool {
self.state == Sha256DigestState::Init
}
/// Reset internal buffer state
fn reset_buf_state(&mut self) {
self.buf.fill(0);
self.buf_idx = 0;
self.state = Sha256DigestState::Pending;
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/printer.rs | drivers/src/printer.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
pring.rs
Abstract:
File contains support routines and macros to print to UART
--*/
use core::convert::Infallible;
use ufmt::{uDisplay, uWrite};
#[derive(Default)]
pub struct Printer;
impl uWrite for Printer {
type Error = Infallible;
/// Writes a string slice into this writer, returning whether the write succeeded.
#[cfg(not(feature = "std"))]
#[inline(never)]
fn write_str(&mut self, _str: &str) -> Result<(), Self::Error> {
#[cfg(feature = "emu")]
crate::Uart::default().write(_str);
Ok(())
}
/// Writes a string slice into this writer, returning whether the write succeeded.
#[cfg(feature = "std")]
fn write_str(&mut self, str: &str) -> Result<(), Self::Error> {
print!("{str}");
Ok(())
}
}
#[macro_export]
macro_rules! cprint {
($($tt:tt)*) => {{
let _ = ufmt::uwrite!(&mut $crate::printer::Printer::default(), $($tt)*);
}}
}
#[macro_export]
macro_rules! cprintln {
($($tt:tt)*) => {{
let _ = ufmt::uwriteln!(&mut $crate::printer::Printer::default(), $($tt)*);
}}
}
#[macro_export]
macro_rules! cprint_slice {
($name:expr, $arr:expr) => {
$crate::cprint!("{} = ", $name);
for byte in $arr {
$crate::cprint!("{:02X}" byte);
}
$crate::cprintln!("");
}
}
pub struct HexBytes<'a>(pub &'a [u8]);
impl uDisplay for HexBytes<'_> {
fn fmt<W>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
where
W: uWrite + ?Sized,
{
// Rust can't prove the indexes are correct in a ufmt uwrite! macro.
for &x in self.0.iter() {
let c = x >> 4;
if c < 10 {
f.write_char((c + b'0') as char)?;
} else {
f.write_char((c - 10 + b'A') as char)?;
}
let c = x & 0xf;
if c < 10 {
f.write_char((c + b'0') as char)?;
} else {
f.write_char((c - 10 + b'A') as char)?;
}
}
Ok(())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/error_reporter.rs | drivers/src/error_reporter.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha256.rs
Abstract:
File contains API for Error Reporting via Soc Iface.
--*/
use crate::memory_layout::BOOT_STATUS_ORG;
use crate::PersistentData;
use caliptra_registers::soc_ifc::SocIfcReg;
/// Report non fatal F/W error
///
/// # Arguments
///
/// * `val` - F/W error code.
pub fn report_fw_error_non_fatal(val: u32) {
let mut soc_ifc = unsafe { SocIfcReg::new() };
soc_ifc.regs_mut().cptra_fw_error_non_fatal().write(|_| val);
update_boot_status(&mut soc_ifc);
}
/// Get non fatal F/W error
///
/// # Arguments
///
/// * `val` - F/W error code.
pub fn get_fw_error_non_fatal() -> u32 {
let mut soc_ifc = unsafe { SocIfcReg::new() };
soc_ifc.regs_mut().cptra_fw_error_non_fatal().read()
}
/// Clear non fatal F/W error
///
/// /// # Arguments
///
/// * `persistent_data` - Persistent data struct so we can track cleared errors.
pub fn clear_fw_error_non_fatal(persistent_data: &mut PersistentData) {
match get_fw_error_non_fatal() {
0 => {}
val => {
// If there is a non-zero error, save it in persistent data before clearing
persistent_data.rom.cleared_non_fatal_fw_error = val;
report_fw_error_non_fatal(0);
}
}
}
/// Report fatal F/W error
///
/// # Arguments
///
/// * `val` - F/W error code.
pub fn report_fw_error_fatal(val: u32) {
let mut soc_ifc = unsafe { SocIfcReg::new() };
soc_ifc.regs_mut().cptra_fw_error_fatal().write(|_| val);
update_boot_status(&mut soc_ifc);
}
fn update_boot_status(soc_ifc: &mut SocIfcReg) {
// Retrieve the boot status from DCCM and save it in the boot status register.
unsafe {
let ptr = BOOT_STATUS_ORG as *mut u32;
soc_ifc.regs_mut().cptra_boot_status().write(|_| *ptr);
};
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/uart.rs | drivers/src/uart.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
uart.rs
Abstract:
File contains API for accessing the UART
References:
https://os.phil-opp.com/vga-text-mode for output functionality.
--*/
use core::fmt;
use caliptra_registers::soc_ifc::SocIfcReg;
/// Caliptra UART
#[derive(Default, Debug)]
pub struct Uart {}
impl Uart {
/// Create an instance of Caliptra UART
pub fn new() -> Self {
Self {}
}
/// Write the string to UART
///
/// # Arguments
///
/// `str` - String to write to UART
pub fn write(&mut self, str: &str) {
let mut reg = unsafe { SocIfcReg::new() };
let reg = reg.regs_mut();
let output_reg = reg.cptra_generic_output_wires().at(0);
let mut val = output_reg.read();
for ch in str.bytes() {
val = u32::from(match ch {
0x20..=0x7e | b'\n' | b'\t' => ch,
_ => 0xfe,
}) | (val & 0xffff_ff00);
// Toggle bit 8 every time a character is written, so the outside
// world can tell when we've written a new character without having
// to introspect internal signals.
val ^= 0x100;
output_reg.write(|_| val);
}
}
}
impl fmt::Write for Uart {
/// Writes a [`char`] into this writer, returning whether the write succeeded.
fn write_str(&mut self, s: &str) -> fmt::Result {
self.write(s);
Ok(())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.