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/auth-manifest/gen/src/lib.rs
auth-manifest/gen/src/lib.rs
/*++ Licensed under the Apache-2.0 license. File Name: generator.rs Abstract: Caliptra Image generator --*/ mod generator; pub mod default_test_manifest; use caliptra_image_types::FwVerificationPqcKeyType; pub use generator::AuthManifestGenerator; use caliptra_auth_man_types::*; /// Image Generator Vendor Configuration #[derive(Default, Clone)] pub struct AuthManifestGeneratorKeyConfig { pub pub_keys: AuthManifestPubKeysConfig, pub priv_keys: Option<AuthManifestPrivKeysConfig>, } /// Authorization Manifest Generator Configuration #[derive(Default, Clone)] pub struct AuthManifestGeneratorConfig { pub version: u32, pub svn: u32, pub flags: AuthManifestFlags, pub pqc_key_type: FwVerificationPqcKeyType, pub vendor_fw_key_info: Option<AuthManifestGeneratorKeyConfig>, pub vendor_man_key_info: Option<AuthManifestGeneratorKeyConfig>, pub owner_fw_key_info: Option<AuthManifestGeneratorKeyConfig>, pub owner_man_key_info: Option<AuthManifestGeneratorKeyConfig>, pub image_metadata_list: Vec<AuthManifestImageMetadata>, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/auth-manifest/gen/src/generator.rs
auth-manifest/gen/src/generator.rs
/*++ Licensed under the Apache-2.0 license. File Name: generator.rs Abstract: Caliptra Authorization Manifest generator --*/ use caliptra_image_gen::ImageGeneratorCrypto; use zerocopy::IntoBytes; use crate::*; use core::mem::size_of; /// Authorization Manifest generator pub struct AuthManifestGenerator<Crypto: ImageGeneratorCrypto> { crypto: Crypto, } impl<Crypto: ImageGeneratorCrypto> AuthManifestGenerator<Crypto> { /// Create an instance `AuthManifestGenerator` pub fn new(crypto: Crypto) -> Self { Self { crypto } } pub fn generate( &self, config: &AuthManifestGeneratorConfig, ) -> anyhow::Result<AuthorizationManifest> { let mut auth_manifest = AuthorizationManifest::default(); if config.image_metadata_list.len() > AUTH_MANIFEST_IMAGE_METADATA_MAX_COUNT { eprintln!( "Unsupported image metadata count, only {} entries supported.", AUTH_MANIFEST_IMAGE_METADATA_MAX_COUNT ); return Err(anyhow::anyhow!("Error converting image metadata list")); } // Generate the Image Metadata List. let slice = config.image_metadata_list.as_slice(); auth_manifest.image_metadata_col.image_metadata_list[..slice.len()].copy_from_slice(slice); auth_manifest.image_metadata_col.entry_count = config.image_metadata_list.len() as u32; // Generate the preamble. auth_manifest.preamble.marker = AUTH_MANIFEST_MARKER; auth_manifest.preamble.size = size_of::<AuthManifestPreamble>() as u32; auth_manifest.preamble.version = config.version; auth_manifest.preamble.svn = config.svn; auth_manifest.preamble.flags = config.flags.bits(); // Sign the vendor manifest public keys. if let Some(vendor_man_config) = &config.vendor_man_key_info { auth_manifest.preamble.vendor_pub_keys.ecc_pub_key = vendor_man_config.pub_keys.ecc_pub_key; let pqc_pub_key = match config.pqc_key_type { FwVerificationPqcKeyType::LMS => vendor_man_config.pub_keys.lms_pub_key.as_bytes(), FwVerificationPqcKeyType::MLDSA => { vendor_man_config.pub_keys.mldsa_pub_key.0.as_bytes() } }; auth_manifest.preamble.vendor_pub_keys.pqc_pub_key.0[..pqc_pub_key.len()] .copy_from_slice(pqc_pub_key); } if let Some(vendor_fw_config) = &config.vendor_fw_key_info { let range = AuthManifestPreamble::vendor_signed_data_range(); if let Some(priv_keys) = vendor_fw_config.priv_keys { let data = auth_manifest .preamble .as_bytes() .get(range.start as usize..) .ok_or_else(|| anyhow::anyhow!("Failed to get vendor signed data range start"))? .get(..range.len()) .ok_or(anyhow::anyhow!( "Failed to get vendor signed data range length" ))?; let digest_sha384 = self.crypto.sha384_digest(data)?; let sig = self.crypto.ecdsa384_sign( &digest_sha384, &priv_keys.ecc_priv_key, &vendor_fw_config.pub_keys.ecc_pub_key, )?; auth_manifest.preamble.vendor_pub_keys_signatures.ecc_sig = sig; if config.pqc_key_type == FwVerificationPqcKeyType::LMS { let lms_sig = self .crypto .lms_sign(&digest_sha384, &priv_keys.lms_priv_key)?; let sig = lms_sig.as_bytes(); auth_manifest.preamble.vendor_pub_keys_signatures.pqc_sig.0[..sig.len()] .copy_from_slice(sig); } else { let data = auth_manifest .preamble .as_bytes() .get(range.start as usize..) .ok_or_else(|| { anyhow::anyhow!("Failed to get vendor signed data range start") })? .get(..range.len()) .ok_or(anyhow::anyhow!( "Failed to get vendor signed data range length" ))?; let mldsa_sig = self.crypto.mldsa_sign( data, &priv_keys.mldsa_priv_key, &vendor_fw_config.pub_keys.mldsa_pub_key, )?; let sig = mldsa_sig.as_bytes(); auth_manifest.preamble.vendor_pub_keys_signatures.pqc_sig.0[..sig.len()] .copy_from_slice(sig); } } } // Sign the owner manifest public keys. if let (Some(owner_fw_config), Some(owner_man_config)) = (&config.owner_fw_key_info, &config.owner_man_key_info) { auth_manifest.preamble.owner_pub_keys.ecc_pub_key = owner_man_config.pub_keys.ecc_pub_key; let pqc_pub_key = match config.pqc_key_type { FwVerificationPqcKeyType::LMS => owner_man_config.pub_keys.lms_pub_key.as_bytes(), FwVerificationPqcKeyType::MLDSA => { owner_man_config.pub_keys.mldsa_pub_key.0.as_bytes() } }; auth_manifest.preamble.owner_pub_keys.pqc_pub_key.0[..pqc_pub_key.len()] .copy_from_slice(pqc_pub_key); let digest = self .crypto .sha384_digest(auth_manifest.preamble.owner_pub_keys.as_bytes())?; if let Some(owner_fw_priv_keys) = owner_fw_config.priv_keys { let sig = self.crypto.ecdsa384_sign( &digest, &owner_fw_priv_keys.ecc_priv_key, &owner_fw_config.pub_keys.ecc_pub_key, )?; auth_manifest.preamble.owner_pub_keys_signatures.ecc_sig = sig; if config.pqc_key_type == FwVerificationPqcKeyType::LMS { let lms_sig = self .crypto .lms_sign(&digest, &owner_fw_priv_keys.lms_priv_key)?; let sig = lms_sig.as_bytes(); auth_manifest.preamble.owner_pub_keys_signatures.pqc_sig.0[..sig.len()] .copy_from_slice(sig); } else { let mldsa_sig = self.crypto.mldsa_sign( auth_manifest.preamble.owner_pub_keys.as_bytes(), &owner_fw_priv_keys.mldsa_priv_key, &owner_fw_config.pub_keys.mldsa_pub_key, )?; let sig = mldsa_sig.as_bytes(); auth_manifest.preamble.owner_pub_keys_signatures.pqc_sig.0[..sig.len()] .copy_from_slice(sig); } } } // Hash the IMC. let digest = self .crypto .sha384_digest(auth_manifest.image_metadata_col.as_bytes())?; // Sign the IMC with the vendor manifest public keys if indicated in the flags. if config .flags .contains(AuthManifestFlags::VENDOR_SIGNATURE_REQUIRED) { if let Some(vendor_man_config) = &config.vendor_man_key_info { if let Some(vendor_man_priv_keys) = vendor_man_config.priv_keys { let sig = self.crypto.ecdsa384_sign( &digest, &vendor_man_priv_keys.ecc_priv_key, &vendor_man_config.pub_keys.ecc_pub_key, )?; auth_manifest .preamble .vendor_image_metdata_signatures .ecc_sig = sig; if config.pqc_key_type == FwVerificationPqcKeyType::LMS { let lms_sig = self .crypto .lms_sign(&digest, &vendor_man_priv_keys.lms_priv_key)?; let sig = lms_sig.as_bytes(); auth_manifest .preamble .vendor_image_metdata_signatures .pqc_sig .0[..sig.len()] .copy_from_slice(sig); } else { let mldsa_sig = self.crypto.mldsa_sign( auth_manifest.image_metadata_col.as_bytes(), &vendor_man_priv_keys.mldsa_priv_key, &vendor_man_config.pub_keys.mldsa_pub_key, )?; let sig = mldsa_sig.as_bytes(); auth_manifest .preamble .vendor_image_metdata_signatures .pqc_sig .0[..sig.len()] .copy_from_slice(sig); } } } } // Sign the IMC with the owner manifest public keys. if let Some(owner_man_config) = &config.owner_man_key_info { if let Some(owner_man_priv_keys) = &owner_man_config.priv_keys { let sig = self.crypto.ecdsa384_sign( &digest, &owner_man_priv_keys.ecc_priv_key, &owner_man_config.pub_keys.ecc_pub_key, )?; auth_manifest .preamble .owner_image_metdata_signatures .ecc_sig = sig; if config.pqc_key_type == FwVerificationPqcKeyType::LMS { let lms_sig = self .crypto .lms_sign(&digest, &owner_man_priv_keys.lms_priv_key)?; let sig = lms_sig.as_bytes(); auth_manifest .preamble .owner_image_metdata_signatures .pqc_sig .0[..sig.len()] .copy_from_slice(sig); } else { let mldsa_sig = self.crypto.mldsa_sign( auth_manifest.image_metadata_col.as_bytes(), &owner_man_priv_keys.mldsa_priv_key, &owner_man_config.pub_keys.mldsa_pub_key, )?; let sig = mldsa_sig.as_bytes(); auth_manifest .preamble .owner_image_metdata_signatures .pqc_sig .0[..sig.len()] .copy_from_slice(sig); } } } Ok(auth_manifest) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/auth-manifest/gen/src/default_test_manifest.rs
auth-manifest/gen/src/default_test_manifest.rs
// Licensed under the Apache-2.0 license use crate::{AuthManifestGenerator, AuthManifestGeneratorConfig, AuthManifestGeneratorKeyConfig}; use caliptra_auth_man_types::{ AuthManifestFlags, AuthManifestImageMetadata, AuthManifestPrivKeysConfig, AuthManifestPubKeysConfig, AuthorizationManifest, ImageMetadataFlags, }; use caliptra_image_fake_keys::*; use caliptra_image_gen::{from_hw_format, ImageGeneratorCrypto}; use caliptra_image_types::FwVerificationPqcKeyType; // Default test MCU firmware used for subsystem mode uploads pub static DEFAULT_MCU_FW: [u8; 256] = [ 0, 0, 0, 0x6f, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; /// Get default test vendor firmware key configuration pub fn default_test_vendor_fw_key_info() -> AuthManifestGeneratorKeyConfig { AuthManifestGeneratorKeyConfig { pub_keys: AuthManifestPubKeysConfig { ecc_pub_key: VENDOR_ECC_KEY_0_PUBLIC, lms_pub_key: VENDOR_LMS_KEY_0_PUBLIC, mldsa_pub_key: VENDOR_MLDSA_KEY_0_PUBLIC, }, priv_keys: Some(AuthManifestPrivKeysConfig { ecc_priv_key: VENDOR_ECC_KEY_0_PRIVATE, lms_priv_key: VENDOR_LMS_KEY_0_PRIVATE, mldsa_priv_key: VENDOR_MLDSA_KEY_0_PRIVATE, }), } } /// Get default test vendor manifest key configuration pub fn default_test_vendor_man_key_info() -> AuthManifestGeneratorKeyConfig { AuthManifestGeneratorKeyConfig { pub_keys: AuthManifestPubKeysConfig { ecc_pub_key: VENDOR_ECC_KEY_1_PUBLIC, lms_pub_key: VENDOR_LMS_KEY_1_PUBLIC, mldsa_pub_key: VENDOR_MLDSA_KEY_1_PUBLIC, }, priv_keys: Some(AuthManifestPrivKeysConfig { ecc_priv_key: VENDOR_ECC_KEY_1_PRIVATE, lms_priv_key: VENDOR_LMS_KEY_1_PRIVATE, mldsa_priv_key: VENDOR_MLDSA_KEY_1_PRIVATE, }), } } /// Get default test owner firmware key configuration pub fn default_test_owner_fw_key_info() -> AuthManifestGeneratorKeyConfig { AuthManifestGeneratorKeyConfig { pub_keys: AuthManifestPubKeysConfig { ecc_pub_key: OWNER_ECC_KEY_PUBLIC, lms_pub_key: OWNER_LMS_KEY_PUBLIC, mldsa_pub_key: OWNER_MLDSA_KEY_PUBLIC, }, priv_keys: Some(AuthManifestPrivKeysConfig { ecc_priv_key: OWNER_ECC_KEY_PRIVATE, lms_priv_key: OWNER_LMS_KEY_PRIVATE, mldsa_priv_key: OWNER_MLDSA_KEY_PRIVATE, }), } } /// Get default test owner manifest key configuration pub fn default_test_owner_man_key_info() -> AuthManifestGeneratorKeyConfig { AuthManifestGeneratorKeyConfig { pub_keys: AuthManifestPubKeysConfig { ecc_pub_key: OWNER_ECC_KEY_PUBLIC, lms_pub_key: OWNER_LMS_KEY_PUBLIC, mldsa_pub_key: OWNER_MLDSA_KEY_PUBLIC, }, priv_keys: Some(AuthManifestPrivKeysConfig { ecc_priv_key: OWNER_ECC_KEY_PRIVATE, lms_priv_key: OWNER_LMS_KEY_PRIVATE, mldsa_priv_key: OWNER_MLDSA_KEY_PRIVATE, }), } } /// Generate a default SoC authorization manifest for testing purposes. /// This is used in subsystem mode when no specific manifest is provided. /// /// # Arguments /// /// * `mcu_fw` - The MCU firmware bytes to hash /// * `pqc_key_type` - The PQC key type to use (LMS or MLDSA) /// * `svn` - Security version number for the manifest /// * `crypto` - Crypto implementation to use for hashing /// /// # Returns /// /// An `AuthorizationManifest` signed with test keys pub fn default_test_soc_manifest<C: ImageGeneratorCrypto>( mcu_fw: &[u8], pqc_key_type: FwVerificationPqcKeyType, svn: u32, crypto: C, ) -> AuthorizationManifest { // generate a default SoC manifest if one is not provided in subsystem mode const IMAGE_SOURCE_IN_REQUEST: u32 = 1; let mut flags = ImageMetadataFlags(0); flags.set_image_source(IMAGE_SOURCE_IN_REQUEST); let digest = from_hw_format(&crypto.sha384_digest(mcu_fw).unwrap()); let metadata = vec![AuthManifestImageMetadata { fw_id: 2, flags: flags.0, digest, ..Default::default() }]; create_test_auth_manifest_with_config( metadata, AuthManifestFlags::VENDOR_SIGNATURE_REQUIRED, pqc_key_type, svn, crypto, ) } /// Create a test authorization manifest with custom metadata and configuration. /// Uses default test keys for signing. /// /// # Arguments /// /// * `image_metadata_list` - List of image metadata entries /// * `flags` - Authorization manifest flags /// * `pqc_key_type` - The PQC key type to use (LMS or MLDSA) /// * `svn` - Security version number for the manifest /// * `crypto` - Crypto implementation to use for hashing /// /// # Returns /// /// An `AuthorizationManifest` signed with test keys pub fn create_test_auth_manifest_with_config<C: ImageGeneratorCrypto>( image_metadata_list: Vec<AuthManifestImageMetadata>, flags: AuthManifestFlags, pqc_key_type: FwVerificationPqcKeyType, svn: u32, crypto: C, ) -> AuthorizationManifest { let gen_config: AuthManifestGeneratorConfig = AuthManifestGeneratorConfig { vendor_fw_key_info: Some(default_test_vendor_fw_key_info()), vendor_man_key_info: Some(default_test_vendor_man_key_info()), owner_fw_key_info: Some(default_test_owner_fw_key_info()), owner_man_key_info: Some(default_test_owner_man_key_info()), image_metadata_list, version: 1, flags, pqc_key_type, svn, }; let gen = AuthManifestGenerator::new(crypto); gen.generate(&gen_config).unwrap() } /// Create a test authorization manifest with custom metadata. /// Uses default test keys and VENDOR_SIGNATURE_REQUIRED flag. /// /// # Arguments /// /// * `image_metadata_list` - List of image metadata entries /// * `pqc_key_type` - The PQC key type to use (LMS or MLDSA) /// * `svn` - Security version number for the manifest /// * `crypto` - Crypto implementation to use for hashing /// /// # Returns /// /// An `AuthorizationManifest` signed with test keys pub fn create_test_auth_manifest_with_metadata<C: ImageGeneratorCrypto>( image_metadata_list: Vec<AuthManifestImageMetadata>, pqc_key_type: FwVerificationPqcKeyType, svn: u32, crypto: C, ) -> AuthorizationManifest { create_test_auth_manifest_with_config( image_metadata_list, AuthManifestFlags::VENDOR_SIGNATURE_REQUIRED, pqc_key_type, svn, crypto, ) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/auth-manifest/types/src/lib.rs
auth-manifest/types/src/lib.rs
/*++ Licensed under the Apache-2.0 license. File Name: lib.rs Abstract: File contains data structures for the image authorization manifest bundle. --*/ #![no_std] use bitfield::bitfield; use caliptra_image_types::*; use core::default::Default; use core::ops::Range; use memoffset::span_of; use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use zeroize::Zeroize; pub const AUTH_MANIFEST_MARKER: u32 = 0x324D_5441; pub const AUTH_MANIFEST_IMAGE_METADATA_MAX_COUNT: usize = 127; pub const AUTH_MANIFEST_PREAMBLE_SIZE: usize = 24292; bitflags::bitflags! { #[derive(Default, Copy, Clone, Debug)] pub struct AuthManifestFlags : u32 { const VENDOR_SIGNATURE_REQUIRED = 0b1; } } impl From<u32> for AuthManifestFlags { /// Converts to this type from the input type. fn from(value: u32) -> Self { AuthManifestFlags::from_bits_truncate(value) } } #[repr(C)] #[derive(IntoBytes, FromBytes, Default, Debug, Clone, Copy, Zeroize)] pub struct AuthManifestPubKeysConfig { pub ecc_pub_key: ImageEccPubKey, #[zeroize(skip)] pub lms_pub_key: ImageLmsPublicKey, pub mldsa_pub_key: ImageMldsaPubKey, } #[repr(C)] #[derive(IntoBytes, FromBytes, KnownLayout, Immutable, Default, Debug, Clone, Copy, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthManifestPubKeys { pub ecc_pub_key: ImageEccPubKey, pub pqc_pub_key: ImagePqcPubKey, } #[repr(C)] #[derive(IntoBytes, FromBytes, KnownLayout, Immutable, Default, Debug, Clone, Copy, Zeroize)] pub struct AuthManifestPrivKeysConfig { pub ecc_priv_key: ImageEccPrivKey, #[zeroize(skip)] pub lms_priv_key: ImageLmsPrivKey, pub mldsa_priv_key: ImageMldsaPrivKey, } #[repr(C)] #[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthManifestSignatures { pub ecc_sig: ImageEccSignature, pub pqc_sig: ImagePqcSignature, } /// Caliptra Authorization Image Manifest Preamble #[repr(C)] #[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Clone, Copy, Debug, Zeroize, Default)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthManifestPreamble { pub marker: u32, pub size: u32, pub version: u32, pub svn: u32, pub flags: u32, // AuthManifestFlags(VENDOR_SIGNATURE_REQUIRED) pub vendor_pub_keys: AuthManifestPubKeys, pub vendor_pub_keys_signatures: AuthManifestSignatures, pub owner_pub_keys: AuthManifestPubKeys, pub owner_pub_keys_signatures: AuthManifestSignatures, pub vendor_image_metdata_signatures: AuthManifestSignatures, pub owner_image_metdata_signatures: AuthManifestSignatures, } impl AuthManifestPreamble { /// Returns `Range<u32>` containing the version, flags and vendor manifest pub keys. pub fn vendor_signed_data_range() -> Range<u32> { let span = span_of!(AuthManifestPreamble, version..=vendor_pub_keys); span.start as u32..span.end as u32 } /// Returns `Range<u32>` containing the vendor_pub_keys_signatures pub fn vendor_pub_keys_signatures_range() -> Range<u32> { let span = span_of!(AuthManifestPreamble, vendor_pub_keys_signatures); span.start as u32..span.end as u32 } /// Returns `Range<u32>` containing the owner_pub_keys pub fn owner_pub_keys_range() -> Range<u32> { let span = span_of!(AuthManifestPreamble, owner_pub_keys); span.start as u32..span.end as u32 } /// Returns `Range<u32>` containing the owner_pub_keys_signatures pub fn owner_pub_keys_signatures_range() -> Range<u32> { let span = span_of!(AuthManifestPreamble, owner_pub_keys_signatures); span.start as u32..span.end as u32 } /// Returns `Range<u32>` containing the vendor_image_metdata_signatures pub fn vendor_image_metdata_signatures_range() -> Range<u32> { let span = span_of!(AuthManifestPreamble, vendor_image_metdata_signatures); span.start as u32..span.end as u32 } /// Returns `Range<u32>` containing the owner_image_metdata_signatures pub fn owner_image_metdata_signatures_range() -> Range<u32> { let span = span_of!(AuthManifestPreamble, owner_image_metdata_signatures); span.start as u32..span.end as u32 } } bitfield! { #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct ImageMetadataFlags(u32); pub image_source, set_image_source: 1, 0; pub ignore_auth_check, set_ignore_auth_check: 2; pub exec_bit, set_exec_bit: 14,8; } #[repr(C)] #[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Clone, Copy, Debug, Zeroize, Default)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct Addr64 { pub lo: u32, pub hi: u32, } /// Caliptra Authorization Manifest Image Metadata #[repr(C)] #[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Clone, Copy, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthManifestImageMetadata { pub fw_id: u32, pub component_id: u32, pub classification: u32, pub flags: u32, // ImageMetadataFlags(image_source, ignore_auth_check) pub image_load_address: Addr64, pub image_staging_address: Addr64, pub digest: [u8; 48], } impl Default for AuthManifestImageMetadata { fn default() -> Self { AuthManifestImageMetadata { fw_id: u32::MAX, component_id: u32::MAX, classification: 0, flags: 0, image_load_address: Addr64 { lo: 0, hi: 0 }, image_staging_address: Addr64 { lo: 0, hi: 0 }, digest: [0; 48], } } } /// Caliptra Authorization Manifest Image Metadata Collection #[repr(C)] #[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Clone, Copy, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthManifestImageMetadataCollection { pub entry_count: u32, pub image_metadata_list: [AuthManifestImageMetadata; AUTH_MANIFEST_IMAGE_METADATA_MAX_COUNT], } impl Default for AuthManifestImageMetadataCollection { fn default() -> Self { AuthManifestImageMetadataCollection { entry_count: 0, image_metadata_list: [AuthManifestImageMetadata::default(); AUTH_MANIFEST_IMAGE_METADATA_MAX_COUNT], } } } /// Caliptra Image Authorization Manifest #[repr(C)] #[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Clone, Copy, Debug, Zeroize, Default)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthorizationManifest { pub preamble: AuthManifestPreamble, pub image_metadata_col: AuthManifestImageMetadataCollection, } #[cfg(test)] mod test { use crate::{AuthManifestPreamble, AUTH_MANIFEST_PREAMBLE_SIZE}; use zerocopy::IntoBytes; #[test] fn test_auth_preamble_size() { assert_eq!( AUTH_MANIFEST_PREAMBLE_SIZE, AuthManifestPreamble::default().as_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/coverage/src/lib.rs
coverage/src/lib.rs
// Licensed under the Apache-2.0 license use anyhow::Context; use bit_vec::BitVec; use caliptra_builder::{build_firmware_elf, FwId, SymbolType}; use elf::endian::AnyEndian; use elf::ElfBytes; use std::collections::hash_map::{DefaultHasher, Entry}; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::hash::Hasher; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::{Path, PathBuf}; mod disasm; pub use disasm::invoke_objdump; pub const CPTRA_COVERAGE_PATH: &str = "CPTRA_COVERAGE_PATH"; pub struct CoverageMap { pub map: HashMap<u64, BitVec>, } impl CoverageMap { pub fn new(paths: Vec<PathBuf>) -> Self { let mut map = HashMap::<u64, BitVec>::default(); for path in paths { if let Some(new_entry) = get_entry_from_path(&path) { match map.entry(new_entry.0) { Entry::Vacant(e) => { e.insert(new_entry.1); } Entry::Occupied(mut e) => { e.get_mut().or(&new_entry.1); } } } } Self { map } } } pub struct CoverageMapEntry(u64, BitVec); pub fn get_entry_from_path(path: &PathBuf) -> Option<CoverageMapEntry> { let filename = path.file_name().and_then(|val| val.to_str()); if let Some(filename) = filename { let prefix = filename .split('-') .nth(1) .and_then(|val| val.strip_suffix(".bitvec")); if let Some(prefix) = prefix { if let Ok(tag) = prefix.parse() { if let Ok(bitmap) = read_bitvec_from_file(path) { return Some(CoverageMapEntry(tag, bitmap)); } } } } None } pub fn dump_emu_coverage_to_file( coverage_path: &str, tag: u64, bitmap: &BitVec, ) -> std::io::Result<()> { let mut filename = format!("CovData{}", hex::encode(rand::random::<[u8; 16]>())); filename.push('-'); filename.push_str(&tag.to_string()); filename.push_str(".bitvec"); let path = std::path::Path::new(coverage_path).join(filename); let file = File::create(path)?; let mut writer = BufWriter::new(file); serde_json::to_writer(&mut writer, &bitmap)?; writer.flush()?; Ok(()) } pub fn uncovered_functions<'a>( base_addr: usize, elf_bytes: &'a [u8], bitmap: &'a BitVec, ) -> std::io::Result<()> { let symbols = caliptra_builder::elf_symbols(elf_bytes)?; let filter = symbols .iter() .filter(|sym| sym.ty == SymbolType::Func) .filter(|function| { let mut pc_range = function.value..function.value + function.size; !pc_range.any(|pc| bitmap.get((pc as usize) - base_addr).unwrap_or(false)) }); for f in filter { println!( "not covered : (NAME:{}) (start:{}) (size:{})", f.name, f.value, f.size ); } Ok(()) } pub fn get_bitvec_paths(dir: &str) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> { let paths = std::fs::read_dir(dir)? // Filter out all those directory entries which couldn't be read .filter_map(|res| res.ok()) // Map the directory entries to paths .map(|dir_entry| dir_entry.path()) // Filter out all paths with extensions other than `bitvec` .filter_map(|path| { if path.extension().is_some_and(|ext| ext == "bitvec") { Some(path) } else { None } }) .collect::<Vec<_>>(); Ok(paths) } pub fn read_bitvec_from_file<P: AsRef<Path>>( path: P, ) -> Result<bit_vec::BitVec, Box<dyn std::error::Error>> { // Open the file in read-only mode with buffer. let file = File::open(path)?; let reader = BufReader::new(file); // Read the JSON contents of the file as an instance of `User`. let coverage = serde_json::from_reader(reader)?; // Return the bitmap Ok(coverage) } pub fn get_tag_from_image(image: &[u8]) -> u64 { let mut hasher = DefaultHasher::new(); std::hash::Hash::hash_slice(image, &mut hasher); hasher.finish() } pub fn get_tag_from_fw_id(id: &FwId<'static>) -> Option<u64> { if let Ok(rom) = caliptra_builder::build_firmware_rom(id) { return Some(get_tag_from_image(&rom)); } None } pub fn collect_instr_pcs(id: &FwId<'static>) -> anyhow::Result<Vec<u32>> { let elf_bytes = build_firmware_elf(id)?; let elf_file = ElfBytes::<AnyEndian>::minimal_parse(&elf_bytes) .with_context(|| "Failed to parse elf file")?; let (load_addr, text_section) = read_section(&elf_file, ".text", true)?; let mut index = 0_usize; let mut instr_pcs = Vec::<u32>::new(); while index < text_section.len() { let instruction = &text_section[index..index + 2]; let instruction = u16::from_le_bytes([instruction[0], instruction[1]]); match instruction & 0b11 { 0..=2 => { index += 2; } _ => { index += 4; } } instr_pcs.push(load_addr + index as u32); } Ok(instr_pcs) } /// Read a section from ELF file fn read_section<'a>( elf_file: &'a ElfBytes<AnyEndian>, name: &str, required: bool, ) -> anyhow::Result<(u32, &'a [u8])> { let load_addr: u32; let section = elf_file .section_header_by_name(name) .with_context(|| format!("Failed to find {name} section"))?; if let Some(section) = section { let data = elf_file .section_data(&section) .with_context(|| format!("Failed to read {name} section"))? .0; load_addr = section.sh_addr as u32; Ok((load_addr, data)) } else { if required { anyhow::bail!("{} section not found", name) } Ok((0, &[])) } } pub fn parse_trace_file(trace_file_path: &str) -> HashSet<u32> { let mut unique_pcs = HashSet::new(); // Open the trace file if let Ok(file) = File::open(trace_file_path) { let reader = BufReader::new(file); // Iterate through each line in the trace file for line in reader.lines() { match line { Ok(line) => { // Check if the line starts with "pc=" if line.starts_with("pc=") { // Extract the PC by splitting the line at '=' and parsing the hexadecimal value if let Some(pc_str) = line.strip_prefix("pc=") { if let Ok(pc) = u32::from_str_radix(pc_str.trim_start_matches("0x"), 16) { unique_pcs.insert(pc); } } } } Err(_) => println!("Trace is malformed"), } } } unique_pcs } pub mod calculator { use bit_vec::BitVec; use super::*; pub fn coverage_from_bitmap(base_addr: usize, coverage: &BitVec, instr_pcs: &[u32]) -> i32 { let mut hit = 0; for pc in instr_pcs { if coverage[*pc as usize - base_addr] { hit += 1; } } hit } pub fn coverage_from_instr_trace(trace_path: &str, instr_pcs: &[u32]) -> i32 { // Count the nunmer of instructions executed let unique_executed_pcs = parse_trace_file(trace_path); let mut hit = 0; for pc in unique_executed_pcs.iter() { if instr_pcs.contains(pc) { hit += 1; } } hit } } #[test] fn test_parse_trace_file() { // Create a temporary trace file for testing let temp_trace_file = "temp_trace.txt"; let trace_data = [ "SoC write4 *0x300300bc <- 0x0", "SoC write4 *0x30030110 <- 0x2625a00", "SoC write4 *0x30030114 <- 0x0", "SoC write4 *0x300300b8 <- 0x1", "pc=0x0", "pc=0x4", "pc=0x4", "pc=0x4", "pc=0x0", ]; // Write the test data to the temporary trace file std::fs::write(temp_trace_file, trace_data.join("\n")) .expect("Failed to write test trace file"); // Call the function to parse the test trace file let unique_pcs = parse_trace_file(temp_trace_file); // Define the expected unique PCs based on the test data let expected_pcs: HashSet<u32> = vec![0x0, 0x4].into_iter().collect(); // Assert that the result matches the expected unique PCs assert_eq!(unique_pcs, expected_pcs); // Clean up: remove the temporary trace file std::fs::remove_file(temp_trace_file).expect("Failed to remove test trace file"); } #[test] fn test_coverage_map_creation_no_data_files_found() { let tag = 123_u64; let paths = Vec::new(); let cv = CoverageMap::new(paths); assert_eq!(None, cv.map.get(&tag)); } #[test] fn test_coverage_map_creation_data_files() { let tag = 123_u64; let bitmap = BitVec::from_elem(1024, false); assert!(dump_emu_coverage_to_file("/tmp", tag, &bitmap).is_ok()); let paths = get_bitvec_paths("/tmp").unwrap(); let cv = CoverageMap::new(paths); assert!(cv.map.contains_key(&tag)); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/coverage/src/disasm.rs
coverage/src/disasm.rs
// Licensed under the Apache-2.0 license use std::process::Command; use caliptra_builder::run_cmd_stdout; const OBJDUMP: &str = "riscv64-unknown-elf-objdump"; pub fn invoke_objdump(binary_path: &str) -> std::io::Result<String> { let mut cmd = Command::new(OBJDUMP); cmd.arg("-C").arg("-d").arg(binary_path); run_cmd_stdout(&mut cmd, None) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/coverage/src/main.rs
coverage/src/main.rs
// Licensed under the Apache-2.0 license use bit_vec::BitVec; use caliptra_builder::build_firmware_elf; use caliptra_builder::firmware::APP_WITH_UART; use caliptra_builder::firmware::FMC_WITH_UART; use caliptra_coverage::calculator; use caliptra_coverage::collect_instr_pcs; use caliptra_coverage::get_bitvec_paths; use caliptra_coverage::CoverageMap; use caliptra_coverage::CPTRA_COVERAGE_PATH; use caliptra_builder::firmware::ROM_WITH_UART; use caliptra_coverage::get_tag_from_fw_id; use caliptra_coverage::invoke_objdump; use caliptra_coverage::uncovered_functions; use caliptra_drivers::memory_layout::ICCM_ORG; use caliptra_drivers::memory_layout::ROM_ORG; use caliptra_image_types::IMAGE_MANIFEST_BYTE_SIZE; pub fn highlight_covered_instructions_in_objdump_output( base_address: usize, bitmap: &BitVec, output: String, ) { let mut is_disassembly = false; let re = regex::Regex::new(r"^\s*(?P<address>[0-9a-f]+):\s*(?P<instruction>[0-9a-f]+\s+.+)") .unwrap(); for line in output.lines() { if line.contains("Disassembly of section") { is_disassembly = true; continue; } if is_disassembly && re.is_match(line) { if let Some(captures) = re.captures(line) { let pc = usize::from_str_radix(&captures["address"], 16).unwrap(); if bitmap.get(pc - base_address).unwrap_or(false) { let s = format!("[*]{}", line); println!("{s}"); } else { println!(" {}", line); } } } else { println!(" {}", line); } } } fn main() -> std::io::Result<()> { let cov_path = std::env::var(CPTRA_COVERAGE_PATH).unwrap_or_else(|_| "".into()); if cov_path.is_empty() { return Ok(()); } let paths = get_bitvec_paths(cov_path.as_str()).unwrap(); if paths.is_empty() { println!("{} coverage files found", paths.len()); return Ok(()); } let tag = get_tag_from_fw_id(&ROM_WITH_UART).unwrap(); println!("{} coverage files found", paths.len()); let instr_pcs = collect_instr_pcs(&ROM_WITH_UART).unwrap(); println!("ROM instruction count = {}", instr_pcs.len()); let cv = CoverageMap::new(paths); let bv = cv .map .get(&tag) .expect("Coverage data not found for image"); let elf_bytes = build_firmware_elf(&ROM_WITH_UART)?; uncovered_functions(ROM_ORG as usize, &elf_bytes, bv)?; println!( "Coverage for ROM_WITH_UART is {}%", (100 * calculator::coverage_from_bitmap(ROM_ORG as usize, bv, &instr_pcs)) as f32 / instr_pcs.len() as f32 ); if let Some(fw_dir) = std::env::var_os("CALIPTRA_PREBUILT_FW_DIR") { let path = std::path::PathBuf::from(fw_dir).join(ROM_WITH_UART.elf_filename()); let objdump_output = invoke_objdump(&path.to_string_lossy()); highlight_covered_instructions_in_objdump_output( caliptra_drivers::memory_layout::ROM_ORG as usize, bv, objdump_output.unwrap(), ); } else { println!("Prebuilt firmware not found"); } let iccm_image_tag = { let image = caliptra_builder::build_and_sign_image( &FMC_WITH_UART, &APP_WITH_UART, caliptra_builder::ImageOptions { fmc_version: caliptra_builder::version::get_fmc_version(), app_version: caliptra_builder::version::get_runtime_version(), ..Default::default() }, ) .unwrap(); let image = image.to_bytes().unwrap(); let iccm_image = &image.as_slice()[IMAGE_MANIFEST_BYTE_SIZE..]; caliptra_coverage::get_tag_from_image(iccm_image) }; let iccm_bitmap = cv .map .get(&iccm_image_tag) .expect("Coverage data not found for ICCM image"); let iccm_images = vec![&FMC_WITH_UART, &APP_WITH_UART]; for e in iccm_images { println!("////////////////////////////////////"); println!("Coverage report for {}", e.bin_name); println!("////////////////////////////////////"); let instr_pcs = collect_instr_pcs(e).unwrap(); println!("{} instruction count = {}", e.bin_name, instr_pcs.len()); println!( "Coverage % is {}%", (100 * calculator::coverage_from_bitmap(ICCM_ORG as usize, iccm_bitmap, &instr_pcs)) as f32 / instr_pcs.len() as f32 ); let elf_bytes = build_firmware_elf(e)?; uncovered_functions(ICCM_ORG as usize, &elf_bytes, iccm_bitmap)?; if let Some(fw_dir) = std::env::var_os("CALIPTRA_PREBUILT_FW_DIR") { let path = std::path::PathBuf::from(fw_dir).join(e.elf_filename()); let objdump_output = invoke_objdump(&path.to_string_lossy()); highlight_covered_instructions_in_objdump_output( ICCM_ORG as usize, iccm_bitmap, objdump_output.unwrap(), ); } else { println!("Prebuilt firmware not found"); } } Ok(()) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cfi/lib/src/lib.rs
cfi/lib/src/lib.rs
/*++ Licensed under the Apache-2.0 license. File Name: lib.rs --*/ #![no_std] extern crate core; mod cfi; mod cfi_counter; mod xoshiro; pub use cfi::*; pub use cfi_counter::{CfiCounter, CfiInt}; pub use xoshiro::Xoshiro128; #[repr(C)] pub struct CfiState { val: u32, mask: u32, prng: Xoshiro128, } #[cfg(feature = "cfi-test")] static mut CFI_STATE: CfiState = CfiState { val: 0, mask: 0, prng: Xoshiro128::new_unseeded(), }; #[cfg(not(feature = "cfi-test"))] extern "C" { #[link_name = "CFI_STATE_ORG"] static mut CFI_STATE: CfiState; }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cfi/lib/src/cfi.rs
cfi/lib/src/cfi.rs
/*++ Licensed under the Apache-2.0 license. File Name: cfi.rs Abstract: File contains CFI launder implementation. References: https://github.com/lowRISC/opentitan/blob/7a61300cf7c409fa68fd892942c1d7b58a7cd4c0/sw/device/lib/base/hardened.h#L260 --*/ use caliptra_error::CaliptraError; use crate::CfiCounter; use core::cfg; use core::cmp::{Eq, Ord, PartialEq, PartialOrd}; use core::marker::{Copy, PhantomData}; /// CFI Panic Information #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum CfiPanicInfo { /// CFI Counter decode error CounterCorrupt, /// CFI Counter overflow CounterOverflow, /// CFI Counter underflow CounterUnderflow, /// CFI Counter mismatch CounterMismatch, /// CFI Assert Equal failed AssertEqFail, /// CFI Assert Not Equal failed AssertNeFail, /// CFI Greater Than failed AssertGtFail, /// CFI Less Than failed AssertLtFail, /// CFI Greater Than Equal failed AssertGeFail, /// CFI Less Than Equal failed AssertLeFail, /// Random number generator error TrngError, /// An enum match statement finds an unexpected value. UnexpectedMatchBranch, /// Unknown error UnknownError, } impl From<CfiPanicInfo> for CaliptraError { /// Converts to this type from the input type. fn from(info: CfiPanicInfo) -> CaliptraError { match info { CfiPanicInfo::CounterCorrupt => CaliptraError::ROM_CFI_PANIC_COUNTER_CORRUPT, CfiPanicInfo::CounterOverflow => CaliptraError::ROM_CFI_PANIC_COUNTER_OVERFLOW, CfiPanicInfo::CounterUnderflow => CaliptraError::ROM_CFI_PANIC_COUNTER_UNDERFLOW, CfiPanicInfo::CounterMismatch => CaliptraError::ROM_CFI_PANIC_COUNTER_MISMATCH, CfiPanicInfo::AssertEqFail => CaliptraError::ROM_CFI_PANIC_ASSERT_EQ_FAILURE, CfiPanicInfo::AssertNeFail => CaliptraError::ROM_CFI_PANIC_ASSERT_NE_FAILURE, CfiPanicInfo::AssertGtFail => CaliptraError::ROM_CFI_PANIC_ASSERT_GT_FAILURE, CfiPanicInfo::AssertLtFail => CaliptraError::ROM_CFI_PANIC_ASSERT_LT_FAILURE, CfiPanicInfo::AssertGeFail => CaliptraError::ROM_CFI_PANIC_ASSERT_GE_FAILURE, CfiPanicInfo::AssertLeFail => CaliptraError::ROM_CFI_PANIC_ASSERT_LE_FAILURE, CfiPanicInfo::TrngError => CaliptraError::ROM_CFI_PANIC_TRNG_FAILURE, _ => CaliptraError::ROM_CFI_PANIC_UNKNOWN, } } } /// Launder the value to prevent compiler optimization /// /// # Arguments /// /// * `val` - Value to launder /// /// # Returns /// /// `T` - Same value pub fn cfi_launder<T>(val: T) -> T where Launder<T>: LaunderTrait<T>, { if cfg!(feature = "cfi") { Launder { _val: PhantomData }.launder(val) } else { val } } pub trait LaunderTrait<T> { fn launder(&self, val: T) -> T { core::hint::black_box(val) } } pub struct Launder<T> { _val: PhantomData<T>, } // Inline-assembly laundering trick is adapted from OpenTitan: // https://github.com/lowRISC/opentitan/blob/master/sw/device/lib/base/hardened.h#L193 // // NOTE: This implementation is LLVM-specific, and should be considered to be // a no-op in every other compiler. For example, GCC has in the past peered // into the insides of assembly blocks. // // At the time of writing, it seems preferable to have something we know is // correct rather than being overly clever; this is recorded here in case // the current implementation is unsuitable and we need something more // carefully tuned. // // Unlike in C, we don't have volatile assembly blocks, so this doesn't // necessarily prevent reordering by LLVM. // // When we're building for static analysis, reduce false positives by // short-circuiting the inline assembly block. impl LaunderTrait<u32> for Launder<u32> { #[allow(asm_sub_register)] fn launder(&self, val: u32) -> u32 { let mut val = val; // Safety: this is a no-op, since we don't modify the input. unsafe { // We use inout so that LLVM thinks the value might // be mutated by the assembly and can't eliminate it. core::arch::asm!( "/* {t} */", t = inout(reg) val, ); } val } } impl LaunderTrait<bool> for Launder<bool> { #[allow(asm_sub_register)] fn launder(&self, val: bool) -> bool { let mut val = val as u32; // Safety: this is a no-op, since we don't modify the input. unsafe { core::arch::asm!( "/* {t} */", t = inout(reg) val, ); } val != 0 } } impl LaunderTrait<usize> for Launder<usize> { #[allow(asm_sub_register)] fn launder(&self, mut val: usize) -> usize { // Safety: this is a no-op, since we don't modify the input. unsafe { core::arch::asm!( "/* {t} */", t = inout(reg) val, ); } val } } impl<const N: usize, T> LaunderTrait<[T; N]> for Launder<[T; N]> {} impl<'a, const N: usize, T> LaunderTrait<&'a [T; N]> for Launder<&'a [T; N]> { fn launder(&self, val: &'a [T; N]) -> &'a [T; N] { let mut valp = val.as_ptr() as *const [T; N]; // Safety: this is a no-op, since we don't modify the input. unsafe { core::arch::asm!( "/* {t} */", t = inout(reg) valp, ); &*valp } } } impl LaunderTrait<Option<u32>> for Launder<Option<u32>> {} impl LaunderTrait<CfiPanicInfo> for Launder<CfiPanicInfo> {} /// Control flow integrity panic /// /// This panic is raised when the control flow integrity error is detected /// /// # Arguments /// /// * `info` - Panic information /// /// # Returns /// /// `!` - Never returns #[inline(never)] pub fn cfi_panic(info: CfiPanicInfo) -> ! { // Prevent the compiler from optimizing the reason let _ = cfi_launder(info); #[cfg(feature = "cfi")] { #[cfg(feature = "cfi-test")] { panic!("CFI Panic = {:04x?}", info); } #[cfg(not(feature = "cfi-test"))] { extern "C" { fn cfi_panic_handler(code: u32) -> !; } unsafe { cfi_panic_handler(CaliptraError::from(info).into()); } } } #[cfg(not(feature = "cfi"))] { unimplemented!() } } macro_rules! cfi_assert_macro { ($name: ident, $op: tt, $trait1: path, $trait2: path, $panic_info: ident) => { /// CFI Binary Condition Assertion /// /// # Arguments /// /// `a` - Left hand side /// `b` - Right hand side #[inline(always)] #[allow(unused)] pub fn $name<T>(lhs: T, rhs: T) where T: $trait1 + $trait2, Launder<T>: LaunderTrait<T>, { if cfg!(feature = "cfi") { CfiCounter::delay(); if !(lhs $op rhs) { cfi_panic(CfiPanicInfo::$panic_info); } // Second check for glitch protection CfiCounter::delay(); if !(cfi_launder(lhs) $op cfi_launder(rhs)) { cfi_panic(CfiPanicInfo::$panic_info); } } else { lhs $op rhs; } } }; } cfi_assert_macro!(cfi_assert_eq, ==, Eq, PartialEq, AssertEqFail); cfi_assert_macro!(cfi_assert_ne, !=, Eq, PartialEq, AssertNeFail); cfi_assert_macro!(cfi_assert_gt, >, Ord, PartialOrd, AssertGtFail); cfi_assert_macro!(cfi_assert_lt, <, Ord, PartialOrd, AssertLtFail); cfi_assert_macro!(cfi_assert_ge, >=, Ord, PartialOrd, AssertGeFail); cfi_assert_macro!(cfi_assert_le, <=, Ord, PartialOrd, AssertLeFail); // special case for bool assert #[inline(always)] #[allow(unused)] pub fn cfi_assert_bool(cond: bool) { if cfg!(feature = "cfi") { CfiCounter::delay(); if !cond { cfi_panic(CfiPanicInfo::AssertEqFail); } // Second check for glitch protection CfiCounter::delay(); if !cfi_launder(cond) { cfi_panic(CfiPanicInfo::AssertEqFail); } } } #[macro_export] macro_rules! cfi_assert { ($cond: expr) => { cfi_assert_bool($cond) }; } #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))] pub fn cfi_assert_eq_16_words(a: &[u32; 16], b: &[u32; 16]) { if a != b { cfi_panic(CfiPanicInfo::AssertEqFail) } } /// Unrolled comparison of 16 words /// /// Written in assembly so the trampoline is above the comparisons rather than /// below #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] #[inline(always)] pub fn cfi_assert_eq_16_words(a: &[u32; 16], b: &[u32; 16]) { unsafe { core::arch::asm!( "j 3f", "2:", "li a0, 0x01040055", "j cfi_panic_handler", "3:", "lw {tmp0}, 0(a4)", "lw {tmp1}, 0(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 4(a4)", "lw {tmp1}, 4(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 8(a4)", "lw {tmp1}, 8(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 12(a4)", "lw {tmp1}, 12(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 16(a4)", "lw {tmp1}, 16(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 20(a4)", "lw {tmp1}, 20(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 24(a4)", "lw {tmp1}, 24(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 28(a4)", "lw {tmp1}, 28(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 32(a4)", "lw {tmp1}, 32(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 36(a4)", "lw {tmp1}, 36(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 40(a4)", "lw {tmp1}, 40(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 44(a4)", "lw {tmp1}, 44(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 48(a4)", "lw {tmp1}, 48(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 52(a4)", "lw {tmp1}, 52(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 56(a4)", "lw {tmp1}, 56(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 60(a4)", "lw {tmp1}, 60(a5)", "bne {tmp0}, {tmp1}, 2b", in("a4") a.as_ptr(), in("a5") b.as_ptr(), tmp0 = out(reg) _, tmp1 = out(reg) _); } } #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))] pub fn cfi_assert_ne_16_words(a: &[u32; 16], b: &[u32; 16]) { if a == b { cfi_panic(CfiPanicInfo::AssertNeFail) } } /// Unrolled comparison of 16 words /// /// Written in assembly so the trampoline is above the comparisons rather than /// below #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] #[inline(always)] pub fn cfi_assert_ne_16_words(a: &[u32; 16], b: &[u32; 16]) { unsafe { core::arch::asm!( "j 3f", "2:", "li a0, 0x01040056", "j cfi_panic_handler", "3:", "lw {tmp0}, 0(a4)", "lw {tmp1}, 0(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 4(a4)", "lw {tmp1}, 4(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 8(a4)", "lw {tmp1}, 8(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 12(a4)", "lw {tmp1}, 12(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 16(a4)", "lw {tmp1}, 16(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 20(a4)", "lw {tmp1}, 20(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 24(a4)", "lw {tmp1}, 24(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 28(a4)", "lw {tmp1}, 28(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 32(a4)", "lw {tmp1}, 32(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 36(a4)", "lw {tmp1}, 36(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 40(a4)", "lw {tmp1}, 40(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 44(a4)", "lw {tmp1}, 44(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 48(a4)", "lw {tmp1}, 48(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 52(a4)", "lw {tmp1}, 52(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 56(a4)", "lw {tmp1}, 56(a5)", "bne {tmp0}, {tmp1}, 4f", "lw {tmp0}, 60(a4)", "lw {tmp1}, 60(a5)", "bne {tmp0}, {tmp1}, 4f", "j 2b", "4:", in("a4") a.as_ptr(), in("a5") b.as_ptr(), tmp0 = out(reg) _, tmp1 = out(reg) _,); } } #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))] pub fn cfi_assert_eq_12_words(a: &[u32; 12], b: &[u32; 12]) { if a != b { cfi_panic(CfiPanicInfo::AssertEqFail) } } /// Unrolled comparison of 12 words /// /// Written in assembly so the trampoline is above the comparisons rather than /// below #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] #[inline(always)] pub fn cfi_assert_eq_12_words(a: &[u32; 12], b: &[u32; 12]) { unsafe { core::arch::asm!( "j 3f", "2:", "li a0, 0x01040055", "j cfi_panic_handler", "3:", "lw {tmp0}, 0(a4)", "lw {tmp1}, 0(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 4(a4)", "lw {tmp1}, 4(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 8(a4)", "lw {tmp1}, 8(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 12(a4)", "lw {tmp1}, 12(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 16(a4)", "lw {tmp1}, 16(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 20(a4)", "lw {tmp1}, 20(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 24(a4)", "lw {tmp1}, 24(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 28(a4)", "lw {tmp1}, 28(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 32(a4)", "lw {tmp1}, 32(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 36(a4)", "lw {tmp1}, 36(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 40(a4)", "lw {tmp1}, 40(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 44(a4)", "lw {tmp1}, 44(a5)", "bne {tmp0}, {tmp1}, 2b", in("a4") a.as_ptr(), in("a5") b.as_ptr(), tmp0 = out(reg) _, tmp1 = out(reg) _); } } #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))] pub fn cfi_assert_eq_8_words(a: &[u32; 8], b: &[u32; 8]) { if a != b { cfi_panic(CfiPanicInfo::AssertEqFail) } } /// Unrolled comparison of 8 words /// /// Written in assembly so the trampoline is above the comparisons rather than /// below #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] #[inline(always)] pub fn cfi_assert_eq_8_words(a: &[u32; 8], b: &[u32; 8]) { unsafe { core::arch::asm!( "j 3f", "2:", "li a0, 0x01040055", "j cfi_panic_handler", "3:", "lw {tmp0}, 0(a4)", "lw {tmp1}, 0(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 4(a4)", "lw {tmp1}, 4(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 8(a4)", "lw {tmp1}, 8(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 12(a4)", "lw {tmp1}, 12(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 16(a4)", "lw {tmp1}, 16(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 20(a4)", "lw {tmp1}, 20(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 24(a4)", "lw {tmp1}, 24(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 28(a4)", "lw {tmp1}, 28(a5)", "bne {tmp0}, {tmp1}, 2b", in("a4") a.as_ptr(), in("a5") b.as_ptr(), tmp0 = out(reg) _, tmp1 = out(reg) _); } } #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))] pub fn cfi_assert_eq_6_words(a: &[u32; 6], b: &[u32; 6]) { if a != b { cfi_panic(CfiPanicInfo::AssertEqFail) } } /// Unrolled comparison of 6 words /// /// Written in assembly so the trampoline is above the comparisons rather than /// below #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] #[inline(always)] pub fn cfi_assert_eq_6_words(a: &[u32; 6], b: &[u32; 6]) { unsafe { core::arch::asm!( "j 3f", "2:", "li a0, 0x01040055", "j cfi_panic_handler", "3:", "lw {tmp0}, 0(a4)", "lw {tmp1}, 0(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 4(a4)", "lw {tmp1}, 4(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 8(a4)", "lw {tmp1}, 8(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 12(a4)", "lw {tmp1}, 12(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 16(a4)", "lw {tmp1}, 16(a5)", "bne {tmp0}, {tmp1}, 2b", "lw {tmp0}, 20(a4)", "lw {tmp1}, 20(a5)", "bne {tmp0}, {tmp1}, 2b", in("a4") a.as_ptr(), in("a5") b.as_ptr(), tmp0 = out(reg) _, tmp1 = out(reg) _); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cfi/lib/src/cfi_counter.rs
cfi/lib/src/cfi_counter.rs
/*++ Licensed under the Apache-2.0 license. File Name: cfi_ctr.rs Abstract: File contains CFI Integer and Counter implementations. The counter is based on ideas from Trusted Firmware-M firmware. References: https://tf-m-user-guide.trustedfirmware.org/design_docs/tfm_physical_attack_mitigation.html --*/ use caliptra_error::CaliptraResult; use crate::cfi::{cfi_panic, CfiPanicInfo}; use crate::xoshiro::Xoshiro128; use crate::CFI_STATE; use core::default::Default; /// CFI Integer #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub struct CfiInt { /// Actual Value val: u32, /// Masked Value masked_val: u32, } impl CfiInt { /// Integer mask with high hamming distance const MASK: u32 = 0xA5A5A5A5; /// Create integer from raw values fn from_raw(val: u32, masked_val: u32) -> Self { Self { val, masked_val } } /// Encode the integer fn encode(val: u32) -> Self { Self { val, masked_val: val ^ Self::MASK, } } /// Check if the integer is valid fn is_valid(&self) -> bool { self.val == self.masked_val ^ Self::MASK } } impl Default for CfiInt { /// Returns the "default value" for a type. fn default() -> Self { Self::encode(0) } } fn prng() -> &'static Xoshiro128 { let cfi_state = &raw const CFI_STATE; unsafe { &(*cfi_state).prng } } /// CFI counter pub enum CfiCounter {} impl CfiCounter { /// Reset counter #[inline(always)] pub fn reset(entropy_gen: &mut impl FnMut() -> CaliptraResult<(u32, u32, u32, u32)>) { prng().mix_entropy(entropy_gen); Self::reset_internal(); } #[cfg(feature = "cfi-test")] pub fn reset_for_test() { Self::reset_internal() } fn reset_internal() { Self::write(CfiInt::default()); } // Zero the counter pub fn corrupt() { Self::write(CfiInt { val: 0, masked_val: 0, }); } /// Increment counter #[inline(never)] pub fn increment() -> CfiInt { if cfg!(all(feature = "cfi", feature = "cfi-counter")) { let int = Self::read(); if !int.is_valid() { cfi_panic(CfiPanicInfo::CounterCorrupt); } let (new, overflow) = int.val.overflowing_add(1); if overflow { cfi_panic(CfiPanicInfo::CounterOverflow); } let new_int = CfiInt::encode(new); Self::write(new_int); int } else { CfiInt::default() } } /// Decrement Counter #[inline(never)] pub fn decrement() -> CfiInt { if cfg!(all(feature = "cfi", feature = "cfi-counter")) { let val = Self::read(); if !val.is_valid() { cfi_panic(CfiPanicInfo::CounterCorrupt); } let (new, underflow) = val.val.overflowing_sub(1); if underflow { cfi_panic(CfiPanicInfo::CounterUnderflow); } let new_val = CfiInt::encode(new); Self::write(new_val); Self::read() } else { CfiInt::default() } } /// Assert the counters are equal #[inline(never)] pub fn assert_eq(val1: CfiInt, val2: CfiInt) { if cfg!(all(feature = "cfi", feature = "cfi-counter")) { if !val1.is_valid() { cfi_panic(CfiPanicInfo::CounterCorrupt); } if !val2.is_valid() { cfi_panic(CfiPanicInfo::CounterCorrupt); } if val1 != val2 { cfi_panic(CfiPanicInfo::CounterMismatch); } } } #[inline(never)] pub fn delay() { let cycles = prng().next() % 256; let _real_cyc = 1 + cycles / 2; #[cfg(all(target_arch = "riscv32", feature = "cfi", feature = "cfi-counter"))] unsafe { core::arch::asm!( "1:", "addi {0}, {0}, -1", "bne {0}, zero, 1b", inout(reg) _real_cyc => _, options(nomem, nostack), ); } } /// Read counter value pub fn read() -> CfiInt { unsafe { CfiInt::from_raw( core::ptr::read_volatile(&raw const CFI_STATE.val), core::ptr::read_volatile(&raw const CFI_STATE.mask), ) } } /// Write counter value fn write(val: CfiInt) { unsafe { core::ptr::write_volatile(&raw mut CFI_STATE.val, val.val); core::ptr::write_volatile(&raw mut CFI_STATE.mask, val.masked_val); } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cfi/lib/src/xoshiro.rs
cfi/lib/src/xoshiro.rs
/*++ Licensed under the Apache-2.0 license. File Name: xoshiro.rs Abstract: File contains implementation of RNG based on System.Random Xoshiro128** algorithm. References: https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Random.Xoshiro128StarStarImpl.cs --*/ use core::cell::Cell; use caliptra_error::CaliptraResult; use crate::{cfi_panic, CfiPanicInfo}; /// Provides an implementation of the xoshiro128** algorithm. This implementation is used /// on 32-bit when no seed is specified and an instance of the base Random class is constructed. /// As such, we are free to implement however we see fit, without back compat concerns around /// the sequence of numbers generated or what methods call what other methods. #[repr(C)] pub struct Xoshiro128 { // It is critical for safety that every bit-pattern of this struct // is valid (no padding, no enums, no references), similar to the requirements for // zerocopy::FromBytes. s0: Cell<u32>, s1: Cell<u32>, s2: Cell<u32>, s3: Cell<u32>, } impl Xoshiro128 { /// Create a new instance of the xoshiro128** algorithm seeded with zeroes. #[allow(unused)] pub(crate) const fn new_unseeded() -> Self { Self::new_with_seed(0, 0, 0, 0) } /// Create a new instance of the xoshiro128** algorithm with a seed. pub const fn new_with_seed(s0: u32, s1: u32, s2: u32, s3: u32) -> Self { Self { s0: Cell::new(s0), s1: Cell::new(s1), s2: Cell::new(s2), s3: Cell::new(s3), } } #[inline(never)] pub fn mix_entropy( &self, entropy_gen: &mut impl FnMut() -> CaliptraResult<(u32, u32, u32, u32)>, ) { loop { if let Ok(entropy) = entropy_gen() { self.s0.set(self.s0.get() ^ entropy.0); self.s1.set(self.s1.get() ^ entropy.1); self.s2.set(self.s2.get() ^ entropy.2); self.s3.set(self.s3.get() ^ entropy.3); } else { cfi_panic(CfiPanicInfo::TrngError) } // Atlease one value must be non-zero if self.s0.get() | self.s1.get() | self.s2.get() | self.s3.get() != 0 { break; } } } /// Get the next random number pub fn next(&self) -> u32 { // next is based on the algorithm from http://prng.di.unimi.it/xoshiro128starstar.c: // // Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org) // // To the extent possible under law, the author has dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // See <http://creativecommons.org/publicdomain/zero/1.0/>. let mut s0 = self.s0.get(); let mut s1 = self.s1.get(); let mut s2 = self.s2.get(); let mut s3 = self.s3.get(); let result = u32::wrapping_mul(u32::wrapping_mul(s1, 5).rotate_left(7), 9); let t = s1 << 9; s2 ^= s0; s3 ^= s1; s1 ^= s2; s0 ^= s3; s2 ^= t; s3 = s3.rotate_left(11); self.s0.set(s0); self.s1.set(s1); self.s2.set(s2); self.s3.set(s3); result } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cfi/lib/tests/test_asm.rs
cfi/lib/tests/test_asm.rs
// Licensed under the Apache-2.0 license #![cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] // This test only runs on risc-v. // To test, run "cargo install cross", then "cross test --target // riscv64gc-unknown-linux-gnu" use std::cell::RefCell; use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; use std::sync::Arc; use std::time::Duration; use caliptra_error::CaliptraError; thread_local! { static CFI_PANIC_CALLED: RefCell<Arc<AtomicU32>> = RefCell::new(Arc::new(0.into())); } #[no_mangle] extern "C" fn cfi_panic_handler(code: u32) -> ! { // This function cannot return or panic, so the only way we have to detect // this call is to set a thread-local variable that can be checked from // another thread before hanging this thread forever. CFI_PANIC_CALLED.with(|c| c.borrow_mut().store(code, Relaxed)); #[allow(clippy::empty_loop)] loop { std::thread::sleep(Duration::from_secs(1)); } } #[test] pub fn test_assert_eq_12words_success() { CFI_PANIC_CALLED.with(|c| c.borrow_mut().store(0, Relaxed)); use caliptra_cfi_lib::cfi_assert_eq_12_words; let a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; let b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; // Make sure these are separate memory addresses assert_ne!(a.as_ptr(), b.as_ptr()); cfi_assert_eq_12_words(&a, &b); assert_eq!(CFI_PANIC_CALLED.with(|c| c.borrow_mut().load(Relaxed)), 0); } #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] #[test] pub fn test_assert_eq_12words_failure() { use caliptra_cfi_lib::cfi_assert_eq_12_words; let cfi_panic_called = Arc::new(AtomicU32::new(0)); let cfi_panic_called2 = cfi_panic_called.clone(); std::thread::spawn(|| { CFI_PANIC_CALLED.with(|c| c.replace(cfi_panic_called2)); cfi_assert_eq_12_words( &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12], ); }); let val = loop { let val = cfi_panic_called.load(Relaxed); if val != 0 { break val; } }; assert_eq!(val, CaliptraError::ROM_CFI_PANIC_ASSERT_EQ_FAILURE.into()); // Leak thread in infinite loop... } #[test] pub fn test_assert_eq_8words_success() { CFI_PANIC_CALLED.with(|c| c.borrow_mut().store(0, Relaxed)); use caliptra_cfi_lib::cfi_assert_eq_8_words; let a = [0, 1, 2, 3, 4, 5, 6, 7]; let b = [0, 1, 2, 3, 4, 5, 6, 7]; // Make sure these are separate memory addresses assert_ne!(a.as_ptr(), b.as_ptr()); cfi_assert_eq_8_words(&a, &b); assert_eq!(CFI_PANIC_CALLED.with(|c| c.borrow_mut().load(Relaxed)), 0); } #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] #[test] pub fn test_assert_eq_8words_failure() { use caliptra_cfi_lib::cfi_assert_eq_8_words; let cfi_panic_called = Arc::new(AtomicU32::new(0)); let cfi_panic_called2 = cfi_panic_called.clone(); std::thread::spawn(|| { CFI_PANIC_CALLED.with(|c| c.replace(cfi_panic_called2)); cfi_assert_eq_8_words(&[0, 1, 2, 3, 4, 5, 6, 7], &[0, 1, 2, 3, 4, 5, 6, 8]); }); let val = loop { let val = cfi_panic_called.load(Relaxed); if val != 0 { break val; } }; assert_eq!(val, CaliptraError::ROM_CFI_PANIC_ASSERT_EQ_FAILURE.into()); // Leak thread in infinite loop... } #[test] pub fn test_assert_eq_6words_success() { CFI_PANIC_CALLED.with(|c| c.borrow_mut().store(0, Relaxed)); use caliptra_cfi_lib::cfi_assert_eq_6_words; let a = [0, 1, 2, 3, 4, 5]; let b = [0, 1, 2, 3, 4, 5]; // Make sure these are separate memory addresses assert_ne!(a.as_ptr(), b.as_ptr()); cfi_assert_eq_6_words(&a, &b); assert_eq!(CFI_PANIC_CALLED.with(|c| c.borrow_mut().load(Relaxed)), 0); } #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] #[test] pub fn test_assert_eq_6words_failure() { use caliptra_cfi_lib::cfi_assert_eq_6_words; let cfi_panic_called = Arc::new(AtomicU32::new(0)); let cfi_panic_called2 = cfi_panic_called.clone(); std::thread::spawn(|| { CFI_PANIC_CALLED.with(|c| c.replace(cfi_panic_called2)); cfi_assert_eq_6_words(&[0, 1, 2, 3, 4, 0x8000_0005], &[0, 1, 2, 3, 4, 5]); }); let val = loop { let val = cfi_panic_called.load(Relaxed); if val != 0 { break val; } }; assert_eq!(val, CaliptraError::ROM_CFI_PANIC_ASSERT_EQ_FAILURE.into()); // Leak thread in infinite loop... }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cfi/lib/tests/test_derive.rs
cfi/lib/tests/test_derive.rs
/*++ Licensed under the Apache-2.0 license. File Name: test_derive.rs --*/ use caliptra_cfi_derive::{cfi_impl_fn, cfi_mod_fn}; use caliptra_cfi_lib::{CfiCounter, Xoshiro128}; use serial_test::serial; #[cfi_mod_fn] fn test1<T>(val: T) -> T { test2(val) } #[cfi_mod_fn] fn test2<T>(val: T) -> T { val } struct Test; impl Test { #[cfi_mod_fn] fn test1<T>(val: T) -> T { test2(val) } #[cfi_mod_fn] #[allow(dead_code)] fn test2<T>(val: T) -> T { val } #[cfi_impl_fn] fn test_self1<T>(&self, val: T) -> T { test2(val) } #[cfi_impl_fn] #[allow(dead_code)] fn test_self2<T>(&self, val: T) -> T { test2(val) } } #[test] #[serial] #[cfg(feature = "cfi-counter")] #[should_panic(expected = "CFI Panic = CounterCorrupt")] fn test_with_not_initialized_counter() { CfiCounter::corrupt(); assert_eq!(test1(10), 10); } #[test] #[serial] fn test_with_initialized_counter() { CfiCounter::reset_for_test(); assert_eq!(test1(10), 10); assert_eq!(Test::test1(10), 10); let test = Test; assert_eq!(test.test_self1(10), 10); } #[test] fn test_rand() { // Expected random numbers generated from a modified implementation of: // https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Random.Xoshiro128StarStarImpl.cs let expected_rand_num: [u32; 20] = [ 11520, 0, 5927040, 70819200, 2031721883, 1637235492, 1287239034, 3734860849, 3729100597, 4258142804, 337829053, 2142557243, 3576906021, 2006103318, 3870238204, 1001584594, 3804789018, 2299676403, 3571406116, 2962224741, ]; let prng = Xoshiro128::new_with_seed(1, 2, 3, 4); for expected_rand_num in expected_rand_num.iter() { assert_eq!(prng.next(), *expected_rand_num); } } #[test] fn test_rand_stress() { let prng = Xoshiro128::new_with_seed(1, 2, 3, 4); for _idx in 0..1000 { prng.next(); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cfi/derive/src/lib.rs
cfi/derive/src/lib.rs
/*++ Licensed under the Apache-2.0 license. File Name: lib.rs Abstract: File contains CFI procedural macro. References: https://tf-m-user-guide.trustedfirmware.org/design_docs/tfm_physical_attack_mitigation.html https://github.com/rust-embedded/riscv/blob/master/src/asm.rs --*/ mod cfi_asm_test; use proc_macro::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::__private::TokenStream2; use syn::parse_macro_input; use syn::parse_quote; use syn::DeriveInput; use syn::FnArg; use syn::ItemFn; #[proc_macro_attribute] pub fn cfi_mod_fn(_args: TokenStream, input: TokenStream) -> TokenStream { cfi_fn(true, input) } #[proc_macro_attribute] pub fn cfi_impl_fn(_args: TokenStream, input: TokenStream) -> TokenStream { cfi_fn(false, input) } fn cfi_fn(mod_fn: bool, input: TokenStream) -> TokenStream { let mut wrapper_fn: ItemFn = parse_macro_input!(input as ItemFn); let mut orig_fn = wrapper_fn.clone(); orig_fn.sig.ident = format_ident!("__cfi_{}", wrapper_fn.sig.ident); orig_fn.attrs.retain(|a| a.path.is_ident("inline")); orig_fn.vis = syn::Visibility::Inherited; wrapper_fn.attrs.retain(|a| !a.path.is_ident("inline")); let fn_name = format_ident!("{}", orig_fn.sig.ident); let param_names: Vec<TokenStream2> = orig_fn .sig .inputs .iter() .map(|input| match input { FnArg::Receiver(r) => r.self_token.to_token_stream(), FnArg::Typed(p) => p.pat.to_token_stream(), }) .collect(); let fn_call = if mod_fn { quote!(#fn_name( #(#param_names,)* )) } else { quote!(Self::#fn_name( #(#param_names,)* )) }; wrapper_fn.block.stmts.clear(); wrapper_fn.block.stmts = parse_quote!( let saved_ctr = caliptra_cfi_lib::CfiCounter::read(); caliptra_cfi_lib::CfiCounter::delay(); let ret = #fn_call; caliptra_cfi_lib::CfiCounter::delay(); let new_ctr = caliptra_cfi_lib::CfiCounter::decrement(); caliptra_cfi_lib::CfiCounter::assert_eq(saved_ctr, new_ctr); ret ); // Add inline attribute to the wrapper function. let inline_attr = parse_quote! { #[inline(always)] }; wrapper_fn.attrs.insert(wrapper_fn.attrs.len(), inline_attr); // Add CFI counter increment statement to the beginning of the original function. orig_fn.block.stmts.insert( 0, parse_quote!( caliptra_cfi_lib::CfiCounter::increment(); ), ); let code = quote! { #wrapper_fn #orig_fn }; code.into() } #[proc_macro_derive(Launder)] pub fn derive_launder_trait(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident; let (impl_generics, ty_generics, _) = input.generics.split_for_impl(); let expanded = quote! { impl #impl_generics caliptra_cfi_lib::LaunderTrait<#name #ty_generics> for caliptra_cfi_lib::Launder<#name #ty_generics> {} impl #impl_generics caliptra_cfi_lib::LaunderTrait<&#name #ty_generics> for caliptra_cfi_lib::Launder<&#name #ty_generics> {} }; TokenStream::from(expanded) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cfi/derive/src/cfi_asm_test.rs
cfi/derive/src/cfi_asm_test.rs
// Licensed under the Apache-2.0 license // These tests are here so that they are excluded in FPGA tests. // These tests don't directly import the CFI code. If they fail, // this likely indicates that the CFI laundering code may not // be doing what we want, and we need to investigate. #[cfg(test)] mod test { const START: &str = " #![no_std] pub fn add(mut a: u32, mut b: u32) -> u32 { launder(a) + launder(a) + launder(b) + launder(b) } "; const LAUNDER: &str = " #[inline(always)] fn launder(mut val: u32) -> u32 { // Safety: this is a no-op, since we don't modify the input. unsafe { core::arch::asm!( \"/* {t} */\", t = inout(reg) val, ); } val }"; const NO_LAUNDER: &str = " #[inline(always)] fn launder(mut val: u32) -> u32 { val } "; fn compile_to_riscv32_asm(src: String) -> String { let dir = std::env::temp_dir(); let src_path = dir.join("asm.rs"); let dst_path = dir.join("asm.s"); std::fs::write(src_path.clone(), src).expect("could not write asm file"); let p = std::process::Command::new("rustc") .args([ "--crate-type=lib", "--target", "riscv32imc-unknown-none-elf", "-C", "opt-level=s", "--emit", "asm", src_path.to_str().expect("could not convert path"), "-o", dst_path.to_str().expect("could not convert path"), ]) .output() .expect("failed to compile"); assert!(p.status.success()); std::fs::read_to_string(dst_path).expect("could not read asm file") } #[test] fn test_launder() { // With no laundering, LLVM can simplify the double add to a shift left. let src = format!("{}{}", START, NO_LAUNDER); let asm = compile_to_riscv32_asm(src); assert!(asm.contains("sll")); // With laundering, LLVM cannot simplify the double add and has to use the register twice. let src = format!("{}{}", START, LAUNDER); let asm = compile_to_riscv32_asm(src); assert!(!asm.contains("sll")); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test-harness/src/lib.rs
test-harness/src/lib.rs
/*++ Licensed under the Apache-2.0 license. File Name: mod.rs Abstract: File contains Macros and API for Caliptra Library Test Harness References: https://os.phil-opp.com/vga-text-mode for print functionality. --*/ #![no_std] use core::fmt; use core::format_args; use core::ops::Fn; // If not using the runtime entrypoint, include a test start.S #[cfg(all(feature = "riscv", not(feature = "runtime")))] core::arch::global_asm!(include_str!("start.S")); #[macro_export] macro_rules! print { ($($arg:tt)*) => ($crate::_print(format_args!($($arg)*))); } #[macro_export] macro_rules! println { () => ($crate::print!("\n")); ($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*))); } #[doc(hidden)] pub fn _print(args: fmt::Arguments) { cfg_if::cfg_if! { if #[cfg(feature = "emu")] { use caliptra_drivers::Uart; use core::fmt::Write; Uart::new().write_fmt(args).unwrap(); } else { let _ = args; } } } #[macro_export] macro_rules! runtime_handlers { () => { use caliptra_cpu::{log_trap_record, TrapRecord}; #[no_mangle] #[inline(never)] extern "C" fn exception_handler(trap_record: &TrapRecord) { println!( "TEST EXCEPTION mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X} ra=0x{:08X}", trap_record.mcause, trap_record.mscause, trap_record.mepc, trap_record.ra, ); log_trap_record(trap_record, None); // Signal non-fatal error to SOC caliptra_drivers::report_fw_error_fatal(caliptra_drivers::CaliptraError::RUNTIME_GLOBAL_EXCEPTION.into()); assert!(false); } #[no_mangle] #[inline(never)] 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)); println!( "TEST NMI mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X} ra=0x{:08X} error_internal_intr_r={:08X}", trap_record.mcause, trap_record.mscause, trap_record.mepc, trap_record.ra, err_interrupt_status, ); let wdt_status = soc_ifc.regs().cptra_wdt_status().read(); let error = if wdt_status.t1_timeout() || wdt_status.t2_timeout() { println!("WDT Expired"); caliptra_drivers::CaliptraError::RUNTIME_GLOBAL_WDT_EXPIRED } else { caliptra_drivers::CaliptraError::RUNTIME_GLOBAL_NMI }; // Signal non-fatal error to SOC caliptra_drivers::report_fw_error_fatal(error.into()); assert!(false); } }; } #[macro_export] macro_rules! test_suite { ($($test_case: ident,)*) => { use core::arch::global_asm; use core::panic::PanicInfo; use caliptra_test_harness::{println, Testable}; #[panic_handler] pub fn panic(info: &PanicInfo) -> ! { println!("[failed]"); println!("Error: {}\n", info); cfg_if::cfg_if! { if #[cfg(feature = "emu")] { use caliptra_drivers::ExitCtrl; ExitCtrl::exit(u32::MAX); } else { loop { use caliptra_drivers::Mailbox; unsafe { Mailbox::abort_pending_soc_to_uc_transactions() }; } } } } #[no_mangle] extern "C" fn cfi_panic_handler(code: u32) -> ! { println!("[test] CFI Panic code=0x{:08X}", code); caliptra_drivers::report_fw_error_fatal(0xdead2); caliptra_drivers::ExitCtrl::exit(u32::MAX) } #[no_mangle] pub extern "C" fn main() { $( $test_case.run(); )* } #[no_mangle] pub extern "C" fn entry_point() { main(); caliptra_drivers::ExitCtrl::exit(0); } #[cfg(feature = "runtime")] runtime_handlers! {} }; } pub trait Testable { fn run(&self); } impl<T> Testable for T where T: Fn(), { fn run(&self) { print!("{}...\t", core::any::type_name::<T>()); self(); println!("[ok]"); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test-harness/types/src/lib.rs
test-harness/types/src/lib.rs
// Licensed under the Apache-2.0 license /// Errors codes placed into CPTRA_FW_ERROR_NON_FATAL /// by the test harness. pub const ERROR_EXCEPTION: u32 = 0x0300_0002; pub const ERROR_NMI: u32 = 0x0300_0003; // From RISC-V_VeeR_EL2_PRM.pdf // Exception causes pub const EXCEPTION_CAUSE_INSTRUCTION_ACCESS_FAULT: u32 = 0x0000_0001; pub const EXCEPTION_CAUSE_ILLEGAL_INSTRUCTION_ERROR: u32 = 0x0000_0002; pub const EXCEPTION_CAUSE_LOAD_ACCESS_FAULT: u32 = 0x0000_0005; // NMI causes pub const NMI_CAUSE_PIN_ASSERTION: u32 = 0x0000_0000; pub const NMI_CAUSE_DBUS_STORE_ERROR: u32 = 0xf000_0000; pub const NMI_CAUSE_DBUS_NON_BLOCKING_LOAD_ERROR: u32 = 0xf000_0001; pub const NMI_CAUSE_FAST_INTERRUPT_DOUBLE_BIT_ECC_ERROR: u32 = 0xf000_1000; pub const NMI_CAUSE_FAST_INTERRUPT_DCCM_REGION_ACCESS_ERROR: u32 = 0xf000_1001; pub const NMI_CAUSE_FAST_INTERRUPT_NON_DCCM_REGION: u32 = 0xf000_1002; pub const MCAUSE_LOAD_ACCESS_FAULT_MSCAUSE_DCCM_DOUBLE_BIT_ECC: u32 = 1; /// Error info collected by the test-harness's trap/NMI handlers and placed into /// CPTRA_FW_EXTENDED_ERROR_INFO. See `test-harness/start.S` for more /// information. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ExtErrorInfo { pub sp: u32, pub mepc: u32, pub mcause: u32, pub mscause: u32, pub mstatus: u32, pub mtval: u32, } impl From<[u32; 8]> for ExtErrorInfo { fn from(value: [u32; 8]) -> Self { ExtErrorInfo { sp: value[0], mepc: value[1], mcause: value[2], mscause: value[3], mstatus: value[4], mtval: value[5], } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/src/lib.rs
test/src/lib.rs
// Licensed under the Apache-2.0 license use caliptra_api::soc_mgr::SocManager; use caliptra_auth_man_gen::default_test_manifest::default_test_soc_manifest; pub use caliptra_auth_man_gen::default_test_manifest::DEFAULT_MCU_FW; use caliptra_builder::{ firmware::{APP_WITH_UART, APP_WITH_UART_FPGA, FMC_WITH_UART}, FwId, ImageOptions, }; use caliptra_hw_model::{BootParams, DefaultHwModel, HwModel, InitParams}; use caliptra_image_crypto::OsslCrypto as Crypto; use caliptra_image_types::FwVerificationPqcKeyType; use zerocopy::IntoBytes; pub mod crypto; pub mod derive; mod redact; mod unwrap_single; pub mod x509; use caliptra_image_types::ImageManifest; use openssl::sha::sha384; pub use redact::{redact_cert, redact_csr, RedactOpts}; pub use unwrap_single::UnwrapSingle; pub const DEFAULT_FMC_VERSION: u16 = 0xaaaa; pub const DEFAULT_APP_VERSION: u32 = 0xbbbbbbbb; pub fn swap_word_bytes(words: &[u32]) -> Vec<u32> { words.iter().map(|word| word.swap_bytes()).collect() } pub fn swap_word_bytes_inplace(words: &mut [u32]) { for word in words.iter_mut() { *word = word.swap_bytes() } } pub fn bytes_to_be_words_48(buf: &[u8; 48]) -> [u32; 12] { let mut result: [u32; 12] = zerocopy::transmute!(*buf); swap_word_bytes_inplace(&mut result); result } // Returns the vendor public key descriptor and owner public key hashes from the image. pub fn image_pk_desc_hash(manifest: &ImageManifest) -> ([u32; 12], [u32; 12]) { let vendor_pk_desc_hash = bytes_to_be_words_48(&sha384(manifest.preamble.vendor_pub_key_info.as_bytes())); let owner_pk_hash = bytes_to_be_words_48(&sha384(manifest.preamble.owner_pub_keys.as_bytes())); (vendor_pk_desc_hash, owner_pk_hash) } /// Generate default SOC manifest bytes for testing pub fn default_soc_manifest_bytes(pqc_key_type: FwVerificationPqcKeyType, svn: u32) -> Vec<u8> { let manifest = default_test_soc_manifest(&DEFAULT_MCU_FW, pqc_key_type, svn, Crypto::default()); manifest.as_bytes().to_vec() } /// Helper function to upload firmware, handling both regular and subsystem modes pub fn test_upload_firmware<T: HwModel>( model: &mut T, fw_image: &[u8], pqc_key_type: FwVerificationPqcKeyType, ) { if model.subsystem_mode() { model .upload_firmware_rri( fw_image, Some(&default_soc_manifest_bytes(pqc_key_type, 1)), Some(&DEFAULT_MCU_FW), ) .unwrap(); } else { model.upload_firmware(fw_image).unwrap(); } } // Run a test which boots ROM -> FMC -> test_bin. If test_bin_name is None, // run the production runtime image. pub fn run_test( test_fwid: Option<&'static FwId>, test_image_options: Option<ImageOptions>, init_params: Option<InitParams>, boot_params: Option<BootParams>, ) -> DefaultHwModel { let default_fwid = &if cfg!(feature = "fpga_subsystem") { APP_WITH_UART_FPGA } else { APP_WITH_UART }; let runtime_fwid = test_fwid.unwrap_or(default_fwid); let image_options = test_image_options.unwrap_or_else(|| { let mut opts = ImageOptions::default(); opts.vendor_config.pl0_pauser = Some(0x1); opts.fmc_version = DEFAULT_FMC_VERSION; opts.app_version = DEFAULT_APP_VERSION; opts }); let rom = caliptra_builder::rom_for_fw_integration_tests().unwrap(); let init_params = match init_params { Some(init_params) => init_params, None => InitParams { rom: &rom, ..Default::default() }, }; let image = caliptra_builder::build_and_sign_image(&FMC_WITH_UART, runtime_fwid, image_options) .unwrap(); let image_bytes = image.to_bytes().unwrap(); let boot_params = boot_params.unwrap_or_default(); // Use image in boot_params if provided // Otherwise, add our newly built image let boot_params = match boot_params.fw_image { Some(_) => boot_params, None => BootParams { fw_image: Some(&image_bytes), ..boot_params }, }; let mut model = caliptra_hw_model::new(init_params, boot_params).unwrap(); model.step_until(|m| { m.soc_ifc() .cptra_flow_status() .read() .ready_for_mb_processing() }); model }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/src/unwrap_single.rs
test/src/unwrap_single.rs
// Licensed under the Apache-2.0 license pub trait UnwrapSingle { type RetVal; fn unwrap_single(self) -> Self::RetVal; } impl<T: Iterator> UnwrapSingle for T { type RetVal = T::Item; #[track_caller] fn unwrap_single(mut self) -> Self::RetVal { let Some(result) = self.next() else { panic!("No item found"); }; if self.next().is_some() { panic!("More than one item found"); } result } } #[test] pub fn test_single() { assert_eq!([42_u32].into_iter().unwrap_single(), 42); } #[test] #[should_panic(expected = "No item found")] pub fn test_none() { [0_u32; 0].into_iter().unwrap_single(); } #[test] #[should_panic(expected = "More than one item found")] pub fn test_two() { [42_u32, 43].into_iter().unwrap_single(); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/src/redact.rs
test/src/redact.rs
// Licensed under the Apache-2.0 license use openssl::nid::Nid; use crate::{crypto::pubkey_ecdsa_der, UnwrapSingle}; fn replace(bytes: &mut [u8], search: &[u8], replace: &[u8]) { assert_eq!(search.len(), replace.len()); let mut offsets = vec![]; for window in bytes.windows(search.len()) { if window == search { offsets.push(window.as_ptr() as usize - bytes.as_ptr() as usize); } } for offset in offsets { bytes[offset..][..search.len()].copy_from_slice(replace); } } fn redact(bytes: &mut [u8], value_to_redact: &[u8]) { replace(bytes, value_to_redact, &vec![0x44; value_to_redact.len()]); } pub struct RedactOpts { pub keep_authority: bool, } // Redact with a real public key so openssl can parse the cert const REDACTED_PUBLIC_KEY: &[u8] = &[ 0x04, 0xd1, 0x7f, 0xd2, 0x78, 0xd2, 0x2e, 0x75, 0xeb, 0xf0, 0xed, 0x36, 0x2d, 0xf0, 0x46, 0x18, 0x24, 0xc4, 0x54, 0x5d, 0xdb, 0x07, 0x08, 0x53, 0xe8, 0xa2, 0xd3, 0xa9, 0xd0, 0xa3, 0xca, 0x59, 0x8d, 0x86, 0x06, 0x08, 0x4e, 0x78, 0xab, 0xc8, 0xcf, 0x13, 0x5d, 0x5d, 0x1b, 0xbb, 0xd7, 0x6c, 0xf2, 0x64, 0x49, 0x0e, 0xf4, 0xa2, 0x95, 0xfa, 0x8e, 0x0f, 0x0f, 0x1f, 0xee, 0x22, 0xfc, 0x88, 0x57, 0x1a, 0x55, 0x9f, 0x7c, 0xe9, 0x68, 0xdc, 0x67, 0xc5, 0x13, 0xd7, 0xfc, 0xbb, 0x79, 0xb6, 0x09, 0xda, 0x23, 0x1d, 0xef, 0xb1, 0xbf, 0x96, 0x72, 0x3d, 0xfd, 0xb2, 0x8d, 0x86, 0xf1, 0x6f, 0x5d, ]; const REDACTED_SIGNATURE: &[u8] = &[ 0x30, 0x64, 0x02, 0x30, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x02, 0x30, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, ]; /// Replace all the non-static fields with 0x44 bytes. This is useful for /// creating golden-data for fmc-alias or rt-alias certs. pub fn redact_cert(der: &[u8], opts: RedactOpts) -> Vec<u8> { let cert = openssl::x509::X509::from_der(der).unwrap(); let mut result = crate::x509::replace_sig(der, REDACTED_SIGNATURE).unwrap(); let pubkey_der = pubkey_ecdsa_der(&cert.public_key().unwrap()); replace(&mut result, &pubkey_der, REDACTED_PUBLIC_KEY); redact( &mut result, &cert .serial_number() .to_bn() .unwrap() .to_vec_padded(20) .unwrap(), ); redact(&mut result, cert.subject_key_id().unwrap().as_slice()); redact( &mut result, cert.subject_name() .entries_by_nid(Nid::SERIALNUMBER) .unwrap_single() .data() .as_slice(), ); if !opts.keep_authority { redact(&mut result, cert.authority_key_id().unwrap().as_slice()); redact( &mut result, cert.issuer_name() .entries_by_nid(Nid::SERIALNUMBER) .unwrap_single() .data() .as_slice(), ); } if let Some(tcb_info) = crate::x509::get_cert_extension(der, &crate::x509::DICE_MULTI_TCB_INFO_OID).unwrap() { redact(&mut result, tcb_info); } if let Some(tcb_info) = crate::x509::get_cert_extension(der, &crate::x509::DICE_TCB_INFO_OID).unwrap() { redact(&mut result, tcb_info); } result } /// Replace all the non-static fields with 0x44 bytes. This is useful for /// creating golden-data for fmc-alias CSR pub fn redact_csr(der: &[u8]) -> Vec<u8> { let csr = openssl::x509::X509Req::from_der(der).unwrap(); let mut result = crate::x509::replace_sig(der, REDACTED_SIGNATURE).unwrap(); let pubkey_der = pubkey_ecdsa_der(&csr.public_key().unwrap()); replace(&mut result, &pubkey_der, REDACTED_PUBLIC_KEY); redact( &mut result, csr.subject_name() .entries_by_nid(Nid::SERIALNUMBER) .unwrap_single() .data() .as_slice(), ); if let Some(tcb_info) = crate::x509::get_csr_extension(der, &crate::x509::DICE_MULTI_TCB_INFO_OID).unwrap() { redact(&mut result, tcb_info); } if let Some(tcb_info) = crate::x509::get_csr_extension(der, &crate::x509::DICE_TCB_INFO_OID).unwrap() { redact(&mut result, tcb_info); } result } #[test] fn test_redact() { let mut value = vec![1_u8, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; redact(&mut value, &[3, 4, 5]); assert_eq!( value, vec![1_u8, 2, 0x44, 0x44, 0x44, 6, 7, 1, 2, 0x44, 0x44, 0x44, 6, 7] ) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/src/derive.rs
test/src/derive.rs
// Licensed under the Apache-2.0 license /// Caliptra key derivation logic implemented independently from the hardware / /// firmware, for use in end-to-end test-cases. /// /// DO NOT REFACTOR THIS FILE TO RE-USE CODE FROM OTHER PARTS OF CALIPTRA use caliptra_api_types::SecurityState; use caliptra_image_types::ImageManifest; use openssl::{ pkey::{PKey, Public}, sha::{sha256, sha384}, }; use zerocopy::{transmute, IntoBytes}; #[cfg(test)] use caliptra_api_types::DeviceLifecycle; #[cfg(test)] use caliptra_image_types::FwVerificationPqcKeyType; use crate::{ crypto::{ self, aes256_ecb_decrypt, aes256_ecb_encrypt, cmac_kdf, derive_ecdsa_key, derive_mldsa_key, hmac384_drbg_keygen, hmac512, hmac512_kdf, }, swap_word_bytes, swap_word_bytes_inplace, }; // The IV fed to the DOE when the ROM deobfuscates the UDS seed / field entropy (as passed to doe registers) pub const DOE_IV: [u32; 4] = [0xfb10365b, 0xa1179741, 0xfba193a1, 0x0f406d7e]; pub const ECDSA_KEYGEN_NONCE: [u32; 12] = [0u32; 12]; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct DoeInput { // The DOE obfuscation key, as wired to caliptra_top pub doe_obf_key: [u32; 8], // The DOE initialization vector, as given to the DOE_IV register by the // firmware when decrypting the UDS and field entropy. pub doe_iv: [u32; 4], // The UDS seed, as stored in the fuses pub uds_seed: [u32; 16], // The field entropy, as stored in the fuses pub field_entropy_seed: [u32; 8], // The initial value of key-vault entry words at startup pub keyvault_initial_word_value: u32, } impl Default for DoeInput { fn default() -> Self { Self { doe_obf_key: caliptra_hw_model_types::DEFAULT_CPTRA_OBF_KEY, doe_iv: DOE_IV, uds_seed: caliptra_hw_model_types::DEFAULT_UDS_SEED, field_entropy_seed: caliptra_hw_model_types::DEFAULT_FIELD_ENTROPY, // in debug-locked mode, this defaults to 0 keyvault_initial_word_value: 0x0000_0000, } } } impl DoeInput { pub fn debug_unlocked() -> Self { Self { doe_obf_key: [0xffff_ffff_u32; 8], doe_iv: DOE_IV, uds_seed: [0xffff_ffff_u32; 16], field_entropy_seed: [0xffff_ffff_u32; 8], // In debug mode, this defaults to 0xaaaa_aaaa keyvault_initial_word_value: 0xaaaa_aaaa, } } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct DoeOutput { // The decrypted UDS as stored in the key vault pub uds: [u32; 16], // The decrypted field entropy as stored in the key vault (with padding) pub field_entropy: [u32; 12], } impl DoeOutput { /// A standalone implementation of the cryptographic operations necessary to /// generate the expected DOE output from fuse values and silicon secrets. pub fn generate(input: &DoeInput) -> Self { use openssl::{cipher::Cipher, cipher_ctx::CipherCtx}; fn aes256_decrypt_blocks(key: &[u8], iv: &[u8], input: &[u8]) -> Vec<u8> { let cipher = Cipher::aes_256_cbc(); let mut ctx = CipherCtx::new().unwrap(); ctx.decrypt_init(Some(cipher), Some(key), Some(iv)).unwrap(); ctx.set_padding(false); let mut result = vec![]; ctx.cipher_update_vec(input, &mut result).unwrap(); ctx.cipher_final_vec(&mut result).unwrap(); result } let mut result = Self { uds: [0_u32; 16], // After reset, the key-vault registers are filled with a particular // word, depending on the debug-locked mode. The field entropy only // takes up 8 of the 12 words, so the 4 remaining words keep their // original value (their contents are used when the key-vault entry is // used as a HMAC key, but not when used as HMAC // data). field_entropy: [input.keyvault_initial_word_value; 12], }; result .uds .as_mut_bytes() .copy_from_slice(&aes256_decrypt_blocks( swap_word_bytes(&input.doe_obf_key).as_bytes(), swap_word_bytes(&input.doe_iv).as_bytes(), swap_word_bytes(&input.uds_seed).as_bytes(), )); swap_word_bytes_inplace(&mut result.uds); result.field_entropy[0..8] .as_mut_bytes() .copy_from_slice(&aes256_decrypt_blocks( swap_word_bytes(&input.doe_obf_key).as_bytes(), swap_word_bytes(&input.doe_iv).as_bytes(), swap_word_bytes(&input.field_entropy_seed).as_bytes(), )); swap_word_bytes_inplace(&mut result.field_entropy); result } } #[test] fn test_doe_output() { let output = DoeOutput::generate(&crate::derive::DoeInput { doe_obf_key: [ 0x4f0b1c83, 0xb231c258, 0x7759c92b, 0xf22ac83f, 0x97c4e162, 0x3580ca0f, 0xb79529c2, 0x8a340dfd, ], doe_iv: [0x455ba825, 0x45e16ca6, 0xf97d1f86, 0xb3718021], uds_seed: [ 0x86c65f40, 0x04d45413, 0x5041da9a, 0x8580ec9a, 0xc7007ee6, 0xceb4a4b8, 0xce485f47, 0xbf6976b8, 0xc906de7b, 0xb0cd2dce, 0x8d2b8eed, 0xa537255f, 0x2fd70f7c, 0xda37caeb, 0xa748021, 0x34d2fd94, ], field_entropy_seed: [ 0x8531a3db, 0xc1725f07, 0x05f5a301, 0x047c1e27, 0xd0f18efa, 0x6a33e9d2, 0x3827ead4, 0x690aaee2, ], keyvault_initial_word_value: 0x5555_5555, }); assert_eq!( output, DoeOutput { uds: [ 2450659586, 3204072599, 1027011035, 1213873878, 763047603, 1402117172, 2275304687, 1797647086, 2750999, 2465724634, 992659675, 557913425, 1982584393, 56096072, 3122931436, 3177452069 ], field_entropy: [ 437386532, 405572964, 972652519, 2702758929, 92052297, 1822317414, 295423989, 3895283936, 1431655765, 1431655765, 1431655765, 1431655765 ] } ); } /// Macro for deriving keys (ECC or MLDSA) consistently macro_rules! derive_key { // ECC key derivation (ecc, $cdi:expr, $label:expr) => {{ let mut key_seed: [u32; 16] = transmute!(hmac512_kdf(swap_word_bytes($cdi).as_bytes(), $label, None)); swap_word_bytes_inplace(&mut key_seed); let mut priv_key: [u32; 12] = transmute!(hmac384_drbg_keygen( &swap_word_bytes(&key_seed).as_bytes()[..48], swap_word_bytes(&ECDSA_KEYGEN_NONCE).as_bytes() )); swap_word_bytes_inplace(&mut priv_key); priv_key }}; // MLDSA seed derivation (mldsa, $cdi:expr, $label:expr) => {{ let mut kdf_result = hmac512_kdf(swap_word_bytes($cdi).as_bytes(), $label, None); let to_reverse_bytes = kdf_result.get_mut(..32).unwrap(); let seed = to_reverse_bytes .chunks_exact_mut(4) .enumerate() .fold([0; 32], |mut acc, (i, c)| { let index = 32 - (i + 1) * 4; c.reverse(); acc[index..index + 4].copy_from_slice(c); acc }); seed }}; } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct IDevId { pub cdi: [u32; 16], pub ecc_priv_key: [u32; 12], pub mldsa_seed: [u8; 32], } impl IDevId { pub fn derive(doe_output: &DoeOutput) -> Self { let mut cdi: [u32; 16] = transmute!(hmac512_kdf( swap_word_bytes(&doe_output.uds).as_bytes(), b"idevid_cdi", None )); swap_word_bytes_inplace(&mut cdi); let ecc_priv_key = derive_key!(ecc, &cdi, b"idevid_ecc_key"); let mldsa_seed = derive_key!(mldsa, &cdi, b"idevid_mldsa_key"); Self { cdi, ecc_priv_key, mldsa_seed, } } pub fn derive_ecc_public_key(&self) -> PKey<Public> { derive_ecdsa_key( swap_word_bytes(&self.ecc_priv_key) .as_bytes() .try_into() .unwrap(), ) } pub fn derive_mldsa_public_key(&self) -> PKey<Public> { derive_mldsa_key(&self.mldsa_seed) } } pub struct Mek { pub mek: [u8; 64], pub checksum: [u8; 16], } pub struct OcpLockKeyLadderBuilder { cdi: [u32; 16], hek: Option<[u32; 16]>, mdk: Option<[u32; 16]>, intermediate_mek_secret: Option<[u32; 16]>, } impl From<IDevId> for OcpLockKeyLadderBuilder { fn from(value: IDevId) -> Self { Self { cdi: value.cdi, hek: None, mdk: None, intermediate_mek_secret: None, } } } impl OcpLockKeyLadderBuilder { pub fn new(output: DoeOutput) -> Self { let idevid = IDevId::derive(&output); Self { cdi: idevid.cdi, hek: None, mdk: None, intermediate_mek_secret: None, } } pub fn add_hek(self, hek_seed: [u32; 8]) -> Self { let mut hek: [u32; 16] = transmute!(hmac512_kdf( swap_word_bytes(&self.cdi).as_bytes(), b"ocp_lock_hek", Some(hek_seed.as_bytes()), )); swap_word_bytes_inplace(&mut hek); Self { hek: Some(hek), ..self } } pub fn add_mdk(self) -> Self { let mut mdk: [u32; 16] = transmute!(hmac512_kdf( swap_word_bytes(&self.cdi).as_bytes(), b"ocp_lock_mdk", None )); swap_word_bytes_inplace(&mut mdk); Self { mdk: Some(mdk), ..self } } pub fn add_intermediate_mek_secret(self, sek: [u8; 32], dpk: [u8; 32]) -> Self { let mut epk: [u32; 16] = transmute!(hmac512_kdf( swap_word_bytes(&self.hek.unwrap()).as_bytes(), b"ocp_lock_epk", Some(sek.as_bytes()) )); swap_word_bytes_inplace(&mut epk); let mut intermediate_mek_secret: [u32; 16] = transmute!(hmac512_kdf( swap_word_bytes(&epk).as_bytes(), b"ocp_lock_intermediate_mek_secret", Some(dpk.as_bytes()), )); swap_word_bytes_inplace(&mut intermediate_mek_secret); Self { intermediate_mek_secret: Some(intermediate_mek_secret), ..self } } pub fn derive_mek(self) -> Mek { let ims = self.intermediate_mek_secret.unwrap(); let mut mek_secret: [u32; 16] = transmute!(hmac512_kdf( swap_word_bytes(&ims).as_bytes(), b"ocp_lock_derived_mek", None, )); swap_word_bytes_inplace(&mut mek_secret); let mek_seed = cmac_kdf( &swap_word_bytes(&mek_secret).as_bytes()[..32], b"ocp_lock_mek_seed", None, 4, ); let key = mek_seed[..32].as_bytes(); let checksum = aes256_ecb_encrypt(key, &[0; 16]); let mdk = swap_word_bytes(&self.mdk.unwrap()); let key = &mdk.as_bytes()[..32]; let decrypted_mek = aes256_ecb_decrypt(key, mek_seed.as_bytes()); let mut mek_checksum = [0; 16]; mek_checksum.clone_from_slice(&checksum); let mut mek = [0; 64]; mek.clone_from_slice(&decrypted_mek); Mek { mek, checksum: mek_checksum, } } } #[test] fn test_golden_ocp_lock_keyladder() { let doe_out = DoeOutput::generate(&DoeInput::default()); let generated_idevid = IDevId::derive(&doe_out); assert_eq!( generated_idevid.cdi, [ 1595302429, 2693222204, 2700750034, 2341068947, 1086336218, 1015077934, 3439704633, 2756110496, 670106478, 1965056064, 3175014961, 1018544412, 1086626027, 1869434586, 2638089882, 3209973098 ] ); let mek = OcpLockKeyLadderBuilder::from(generated_idevid) .add_mdk() .add_hek([0xABDEu32; 8]) .add_intermediate_mek_secret([0xAB; 32], [0xCD; 32]) .derive_mek(); assert_eq!( mek.checksum, [208, 2, 161, 131, 8, 80, 187, 246, 107, 90, 21, 150, 58, 194, 61, 52] ); assert_eq!( mek.mek, [ 94, 152, 39, 23, 80, 241, 238, 103, 219, 79, 3, 73, 159, 38, 155, 127, 106, 161, 12, 18, 56, 249, 187, 171, 151, 33, 80, 177, 43, 88, 170, 232, 206, 234, 175, 214, 95, 181, 46, 96, 36, 178, 8, 146, 11, 219, 238, 52, 72, 59, 214, 205, 102, 183, 43, 144, 0, 226, 80, 160, 212, 180, 219, 171 ] ); } #[test] fn test_idevid() { let idevid = IDevId::derive(&DoeOutput { uds: [ 0x92121902, 0xbefa4497, 0x3d36f1db, 0x485a3ed6, 0x2d7b2eb3, 0x53929c34, 0x879e64ef, 0x6b25eaee, 0x0029fa17, 0x92f7f8da, 0x3b2ac8db, 0x21411551, 0xed0e3d62, 0x5e51aed, 0x14199450, 0x45b540a1, ], field_entropy: [ 0xdbca1cfa, 0x149c0355, 0x7ee48ddb, 0xb022238b, 0x057c9b49, 0x6c9e5b66, 0x119bcff5, 0xe82d50e0, 0x55555555, 0x55555555, 0x55555555, 0x55555555, ], }); assert_eq!( idevid, IDevId { cdi: [ 0xe047693d, 0x5038cf58, 0xbafff529, 0x4308aced, 0xd356fd37, 0x620386b3, 0xb2cfdd97, 0x602e5b26, 0x29ff1601, 0xe3196949, 0xe04109ab, 0x9b6bcab1, 0xef5dc70d, 0xbd2d0875, 0xf17a7559, 0x2328baa2, ], ecc_priv_key: [ 0x34d9279, 0x2e58660b, 0xcfa3e026, 0x90ac31dc, 0xb97a6b6c, 0xf259f7d4, 0xaa3b7a0d, 0x565232ff, 0x38560790, 0x73ff1c04, 0x34501150, 0x48641108, ], mldsa_seed: [ 192, 145, 213, 14, 122, 253, 72, 90, 56, 247, 119, 131, 20, 126, 203, 11, 216, 201, 246, 85, 219, 174, 204, 136, 180, 203, 152, 163, 112, 65, 29, 62 ], // Add dummy value for test } ); } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct LDevId { pub cdi: [u32; 16], pub ecc_priv_key: [u32; 12], pub mldsa_seed: [u8; 32], } impl LDevId { pub fn derive(doe_output: &DoeOutput) -> Self { let idevid = IDevId::derive(doe_output); let mut cdi_seed: [u32; 16] = transmute!(hmac512( swap_word_bytes(&idevid.cdi).as_bytes(), b"ldevid_cdi", )); swap_word_bytes_inplace(&mut cdi_seed); let mut cdi: [u32; 16] = transmute!(hmac512( swap_word_bytes(&cdi_seed).as_bytes(), swap_word_bytes(&doe_output.field_entropy[0..8]).as_bytes(), )); swap_word_bytes_inplace(&mut cdi); let ecc_priv_key = derive_key!(ecc, &cdi, b"ldevid_ecc_key"); let mldsa_seed = derive_key!(mldsa, &cdi, b"ldevid_mldsa_key"); Self { cdi, ecc_priv_key, mldsa_seed, } } pub fn derive_ecc_public_key(&self) -> PKey<Public> { derive_ecdsa_key( swap_word_bytes(&self.ecc_priv_key) .as_bytes() .try_into() .unwrap(), ) } pub fn derive_mldsa_public_key(&self) -> PKey<Public> { derive_mldsa_key(&self.mldsa_seed) } } #[test] fn test_ldevid() { let ldevid = LDevId::derive(&DoeOutput { uds: [ 0x92121902, 0xbefa4497, 0x3d36f1db, 0x485a3ed6, 0x2d7b2eb3, 0x53929c34, 0x879e64ef, 0x6b25eaee, 0x0029fa17, 0x92f7f8da, 0x3b2ac8db, 0x21411551, 0x57d115c, 0xfade7a, 0xb8cca563, 0xe1f504a2, ], field_entropy: [ 0xdbca1cfa, 0x149c0355, 0x7ee48ddb, 0xb022238b, 0x057c9b49, 0x6c9e5b66, 0x119bcff5, 0xe82d50e0, 0x55555555, 0x55555555, 0x55555555, 0x55555555, ], }); assert_eq!( ldevid, LDevId { cdi: [ 0x5c705f09, 0x63f7edfb, 0x9cf0cb89, 0x7306da3f, 0xff1acde2, 0xf1f0b333, 0xafb85fa3, 0x8783a424, 0x6c6aa9db, 0x43ce3297, 0x2568332, 0x53670f99, 0x9e4fff07, 0xdc1911f7, 0xd7af58ed, 0xab20aff0, ], ecc_priv_key: [ 0x15e65daa, 0x3e7dedbb, 0x60eb7ea6, 0xd7e9e441, 0xf2adaa7a, 0x35ca904c, 0x9076d1a1, 0x69972589, 0x274a2869, 0x48eb0fb4, 0xee749db1, 0x15cbe26e, ], mldsa_seed: [ 215, 71, 232, 245, 17, 199, 101, 142, 50, 162, 109, 154, 217, 87, 34, 196, 205, 74, 87, 124, 231, 161, 155, 171, 224, 35, 214, 114, 21, 175, 170, 67 ], } ); } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Pcr0Input { pub security_state: SecurityState, pub fuse_anti_rollback_disable: bool, pub vendor_pub_key_hash: [u32; 12], pub owner_pub_key_hash: [u32; 12], pub owner_pub_key_hash_from_fuses: bool, pub ecc_vendor_pub_key_index: u32, pub fmc_digest: [u32; 12], pub cold_boot_fw_svn: u32, pub fw_fuse_svn: u32, pub pqc_vendor_pub_key_index: u32, pub pqc_key_type: u32, } impl Pcr0Input {} #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Pcr0(pub [u32; 12]); impl Pcr0 { pub fn derive(input: &Pcr0Input) -> Self { let mut value = [0u8; 48]; let extend = |value: &mut [u8; 48], buf: &[u8]| { *value = sha384(&[value.as_slice(), buf].concat()); }; extend( &mut value, &[ input.security_state.device_lifecycle() as u8, input.security_state.debug_locked() as u8, input.fuse_anti_rollback_disable as u8, input.ecc_vendor_pub_key_index as u8, input.cold_boot_fw_svn as u8, input.fw_fuse_svn as u8, input.pqc_vendor_pub_key_index as u8, input.pqc_key_type as u8, input.owner_pub_key_hash_from_fuses as u8, ], ); extend( &mut value, swap_word_bytes(&input.vendor_pub_key_hash).as_bytes(), ); extend( &mut value, swap_word_bytes(&input.owner_pub_key_hash).as_bytes(), ); extend(&mut value, swap_word_bytes(&input.fmc_digest).as_bytes()); let mut result: [u32; 12] = zerocopy::transmute!(value); swap_word_bytes_inplace(&mut result); Self(result) } } #[test] fn test_derive_pcr0() { let pcr0 = Pcr0::derive(&Pcr0Input { security_state: *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production), fuse_anti_rollback_disable: false, vendor_pub_key_hash: [ 0xed6dd78c, 0x131d69e2, 0x313b5d89, 0x0acd8e4e, 0xe2a1db67, 0x790721de, 0x01346b64, 0x1c5cf3c9, 0xcf284e7d, 0x0e114d50, 0xe894b381, 0xd874ba94, ], owner_pub_key_hash: [ 0xdc1a27ef, 0x0c08201a, 0x8b066094, 0x118c29fe, 0x0bc2270e, 0xbd965c43, 0xf7b9a68d, 0x8eaf37fa, 0x968ca8d8, 0x13b2920b, 0x3b88b026, 0xf2f0ebb0, ], owner_pub_key_hash_from_fuses: true, ecc_vendor_pub_key_index: 0, fmc_digest: [ 0xe44ea855, 0x9fcf4063, 0xd3110a9a, 0xd60579db, 0xe03e6dd7, 0x4556cd98, 0xb2b941f5, 0x1bb5034b, 0x587eea1f, 0xfcdd0e0f, 0x8e88d406, 0x3327a3fe, ], cold_boot_fw_svn: 5, fw_fuse_svn: 2, pqc_vendor_pub_key_index: u32::MAX, pqc_key_type: FwVerificationPqcKeyType::LMS as u32, }); assert_eq!( pcr0, Pcr0([ 1597321057, 3306746665, 3870835391, 3103173150, 3318383838, 3407565263, 3776158384, 4231654246, 1759479765, 3561253448, 1491479508, 1619944441 ]) ) } pub struct PcrRtCurrentInput { pub runtime_digest: [u32; 12], pub manifest: ImageManifest, } pub struct PcrRtCurrent(pub [u32; 12]); impl PcrRtCurrent { pub fn derive(input: &PcrRtCurrentInput) -> Self { let mut value = [0u8; 48]; let extend = |value: &mut [u8; 48], buf: &[u8]| { *value = sha384(&[value.as_slice(), buf].concat()); }; extend( &mut value, swap_word_bytes(&input.runtime_digest).as_bytes(), ); let manifest_digest = sha384(input.manifest.as_bytes()); extend(&mut value, &manifest_digest); println!("Pcr is {:02x?}", value); let mut result: [u32; 12] = zerocopy::transmute!(value); swap_word_bytes_inplace(&mut result); Self(result) } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct FmcAliasKey { // The FMC alias private key as stored in the key-vault pub ecc_priv_key: [u32; 12], pub cdi: [u32; 16], pub mldsa_seed: [u8; 32], } impl FmcAliasKey { pub fn derive(pcr0: &Pcr0, ldevid: &LDevId) -> Self { let mut cdi: [u32; 16] = transmute!(hmac512_kdf( swap_word_bytes(&ldevid.cdi).as_bytes(), b"alias_fmc_cdi", Some(swap_word_bytes(&pcr0.0).as_bytes()), )); swap_word_bytes_inplace(&mut cdi); let ecc_priv_key = derive_key!(ecc, &cdi, b"alias_fmc_ecc_key"); let mldsa_seed = derive_key!(mldsa, &cdi, b"alias_fmc_mldsa_key"); Self { ecc_priv_key, cdi, mldsa_seed, } } pub fn derive_public_key(&self) -> PKey<Public> { derive_ecdsa_key( swap_word_bytes(&self.ecc_priv_key) .as_bytes() .try_into() .unwrap(), ) } pub fn derive_mldsa_public_key(&self) -> PKey<Public> { derive_mldsa_key(&self.mldsa_seed) } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct RtAliasKey { pub cdi: [u32; 16], // The FMC alias ECC private key as stored in the key-vault pub ecc_priv_key: [u32; 12], pub mldsa_seed: [u8; 32], } impl RtAliasKey { pub fn derive(tci_input: &PcrRtCurrentInput, fmc_key: &FmcAliasKey) -> Self { // NOTE: This works differently than FmcAliasKey. FmcAliasKey takes the // 48-byte value from Pcr0 as context, this version uses a 96-byte // concatenation of the runtime digest and manifest digest. let mut tci: [u8; 96] = [0; 96]; tci[0..48].copy_from_slice(swap_word_bytes(&tci_input.runtime_digest).as_bytes()); tci[48..96] .as_mut_bytes() .copy_from_slice(&sha384(tci_input.manifest.as_bytes())); let mut cdi: [u32; 16] = transmute!(hmac512_kdf( swap_word_bytes(&fmc_key.cdi).as_bytes(), b"alias_rt_cdi", Some(&tci), )); swap_word_bytes_inplace(&mut cdi); let ecc_priv_key = derive_key!(ecc, &cdi, b"alias_rt_ecc_key"); let mldsa_seed = derive_key!(mldsa, &cdi, b"alias_rt_mldsa_key"); Self { ecc_priv_key, cdi, mldsa_seed, } } pub fn derive_public_key(&self) -> PKey<Public> { derive_ecdsa_key( swap_word_bytes(&self.ecc_priv_key) .as_bytes() .try_into() .unwrap(), ) } pub fn derive_mldsa_public_key(&self) -> PKey<Public> { derive_mldsa_key(&self.mldsa_seed) } } #[test] fn test_derive_fmc_alias_key() { let fmc_alias_key = FmcAliasKey::derive( &Pcr0([ 0xd8f3fd4, 0x4698aaae, 0x7bacaf67, 0x714a8035, 0x9a8d3a51, 0x3fcde890, 0x8039f4c1, 0x77f9d5a9, 0x77b8ecd5, 0xf29b3fa9, 0x30e25097, 0xe1d82b14, ]), &LDevId { cdi: [ 0x0e7b8a15, 0x0cc1476b, 0x28d395d9, 0x233f9f05, 0x670bd435, 0x96758224, 0xd3dd5081, 0x3da916e5, 0x94f2b09e, 0x257f151d, 0x261ade90, 0x73a9b3fb, 0xf35c0619, 0x0856f1e3, 0x7d560cf2, 0xaa227256, ], ecc_priv_key: [ 0xd3ef1bff, 0x0b52919d, 0xe084ee81, 0x47544a50, 0xf7ff4c2d, 0x18038a26, 0x0695a0b1, 0x8103e7f4, 0x30651311, 0xc5658261, 0xe30ae241, 0xa8d9ad51, ], mldsa_seed: [ 192, 145, 213, 14, 122, 253, 72, 90, 56, 247, 119, 131, 20, 126, 203, 11, 216, 201, 246, 85, 219, 174, 204, 136, 180, 203, 152, 163, 112, 65, 29, 62, ], // Add dummy value for test }, ); assert_eq!( fmc_alias_key, FmcAliasKey { ecc_priv_key: [ 0xfcd8c50e, 0x45ddf47b, 0xe272c12c, 0x2a49576f, 0xb57f994d, 0x723de453, 0x14229ac9, 0x714b2a8a, 0x6f1ce75f, 0x788cf75c, 0xdbe9da02, 0x51a22e82, ], cdi: [ 0x41529a09, 0xe976d227, 0x456a211c, 0x86187b33, 0x15c88587, 0x60c51cb8, 0xfbcbb695, 0xf67988dc, 0x14f6ae96, 0xc3dbdaa2, 0xad287006, 0x33a7f284, 0x81d964ce, 0x45af6c6b, 0xdd8b95fd, 0x5cbcbc4b, ], mldsa_seed: [ 163, 117, 67, 78, 222, 82, 68, 243, 158, 242, 24, 40, 127, 39, 156, 161, 226, 203, 189, 13, 13, 191, 228, 58, 7, 166, 34, 186, 152, 21, 78, 195 ], } ); } pub fn ecc_key_id(pub_key: &PKey<Public>) -> [u8; 20] { key_id_from_der(&crypto::pubkey_ecdsa_der(pub_key)) } pub fn ecc_cert_serial_number(pub_key: &PKey<Public>) -> [u8; 20] { cert_serial_number_from_der(&crypto::pubkey_ecdsa_der(pub_key)) } pub fn ecc_serial_number_str(pub_key: &PKey<Public>) -> String { serial_number_str_from_der(&crypto::pubkey_ecdsa_der(pub_key)) } pub fn mldsa_key_id(pub_key: &PKey<Public>) -> [u8; 20] { key_id_from_der(&crypto::pubkey_mldsa_der(pub_key)) } pub fn mldsa_cert_serial_number(pub_key: &PKey<Public>) -> [u8; 20] { cert_serial_number_from_der(&crypto::pubkey_mldsa_der(pub_key)) } pub fn mldsa_serial_number_str(pub_key: &PKey<Public>) -> String { serial_number_str_from_der(&crypto::pubkey_mldsa_der(pub_key)) } fn key_id_from_der(pub_key_der: &[u8]) -> [u8; 20] { sha256(pub_key_der)[..20].try_into().unwrap() } fn serial_number_str_from_der(pub_key_der: &[u8]) -> String { use std::fmt::Write; let digest = sha256(pub_key_der); let mut result = String::new(); for byte in digest { write!(&mut result, "{byte:02X}").unwrap(); } result } fn cert_serial_number_from_der(pub_key_der: &[u8]) -> [u8; 20] { let mut result = key_id_from_der(pub_key_der); // ensure integer is positive and first octet is non-zero result[0] &= !0x80; result[0] |= 0x04; result } #[test] fn test_key_id() { assert_eq!( key_id_from_der(&[ 0x04, 0x84, 0x2c, 0x00, 0xaf, 0x05, 0xac, 0xcc, 0xeb, 0x14, 0x51, 0x4e, 0x2d, 0x37, 0xb0, 0xc3, 0xaa, 0xa2, 0x18, 0xf1, 0x50, 0x57, 0xf1, 0xdc, 0xb8, 0x24, 0xa2, 0x14, 0x98, 0x0b, 0x74, 0x46, 0x88, 0xa0, 0x88, 0x8a, 0x02, 0x97, 0xfa, 0x7d, 0xc5, 0xe1, 0xea, 0xd8, 0xca, 0x12, 0x91, 0xdb, 0x22, 0x9c, 0x28, 0xeb, 0x86, 0x78, 0xbc, 0xe8, 0x00, 0x82, 0x2c, 0x07, 0x22, 0x8f, 0x41, 0x6a, 0xe4, 0x9d, 0x21, 0x8e, 0x5d, 0xa2, 0xf2, 0xd1, 0xa8, 0xa2, 0x7d, 0xc1, 0x9a, 0xdf, 0x66, 0x8a, 0x74, 0x62, 0x89, 0x99, 0xd2, 0x22, 0xb4, 0x01, 0x59, 0xd8, 0x07, 0x6f, 0xaf, 0xbb, 0x8c, 0x5e, 0xdb ]), [ 0x21, 0xee, 0xef, 0x9a, 0x4c, 0x61, 0xd4, 0xb9, 0xe3, 0xd9, 0x4b, 0xea, 0x46, 0xf9, 0xa1, 0x2a, 0xc6, 0x88, 0x7c, 0xe2 ] ); assert_eq!( key_id_from_der(&[ 0x04, 0x1a, 0xe7, 0x83, 0xc2, 0xd0, 0x47, 0xcb, 0xc4, 0xc9, 0x54, 0x26, 0x8b, 0x70, 0xff, 0x5e, 0x75, 0x18, 0xb9, 0xb7, 0xda, 0x0e, 0x26, 0x4b, 0xde, 0x4d, 0x52, 0x8b, 0xe4, 0x6c, 0x79, 0x5e, 0xd2, 0x1a, 0x3c, 0x8d, 0xa6, 0xa9, 0x5c, 0xcd, 0x08, 0x11, 0xf6, 0x7e, 0x26, 0x6d, 0x27, 0xf2, 0x1c, 0xb0, 0x73, 0x36, 0x22, 0xff, 0x64, 0xcb, 0x6a, 0x29, 0xf7, 0xeb, 0x57, 0x25, 0x8b, 0xe9, 0xa2, 0xac, 0x5c, 0xe1, 0x9d, 0x78, 0xd3, 0x36, 0x50, 0xa5, 0x45, 0x3f, 0x19, 0x2c, 0x2c, 0x48, 0x2c, 0x77, 0x55, 0x8c, 0x19, 0x6e, 0x30, 0xba, 0x1a, 0x05, 0xe2, 0x6e, 0xd2, 0xe0, 0x9d, 0xfe, 0x4a ]), [ 0xe7, 0x35, 0xc1, 0x7c, 0x08, 0x2c, 0xfc, 0xbc, 0x3e, 0x1b, 0x8f, 0xbf, 0xbe, 0xa4, 0x90, 0x79, 0xbc, 0xb7, 0x22, 0x10 ] ); } #[test] fn test_cert_serial_number() { assert_eq!( cert_serial_number_from_der(&[ 0x04, 0x84, 0x2c, 0x00, 0xaf, 0x05, 0xac, 0xcc, 0xeb, 0x14, 0x51, 0x4e, 0x2d, 0x37, 0xb0, 0xc3, 0xaa, 0xa2, 0x18, 0xf1, 0x50, 0x57, 0xf1, 0xdc, 0xb8, 0x24, 0xa2, 0x14, 0x98, 0x0b, 0x74, 0x46, 0x88, 0xa0, 0x88, 0x8a, 0x02, 0x97, 0xfa, 0x7d, 0xc5, 0xe1, 0xea, 0xd8, 0xca, 0x12, 0x91, 0xdb, 0x22, 0x9c, 0x28, 0xeb, 0x86, 0x78, 0xbc, 0xe8, 0x00, 0x82, 0x2c, 0x07, 0x22, 0x8f, 0x41, 0x6a, 0xe4, 0x9d, 0x21, 0x8e, 0x5d, 0xa2, 0xf2, 0xd1, 0xa8, 0xa2, 0x7d, 0xc1, 0x9a, 0xdf, 0x66, 0x8a, 0x74, 0x62, 0x89, 0x99, 0xd2, 0x22, 0xb4, 0x01, 0x59, 0xd8, 0x07, 0x6f, 0xaf, 0xbb, 0x8c, 0x5e, 0xdb ]), [ 0x25, 0xee, 0xef, 0x9a, 0x4c, 0x61, 0xd4, 0xb9, 0xe3, 0xd9, 0x4b, 0xea, 0x46, 0xf9, 0xa1, 0x2a, 0xc6, 0x88, 0x7c, 0xe2 ] ); assert_eq!( cert_serial_number_from_der(&[ 0x04, 0x1a, 0xe7, 0x83, 0xc2, 0xd0, 0x47, 0xcb, 0xc4, 0xc9, 0x54, 0x26, 0x8b, 0x70, 0xff, 0x5e, 0x75, 0x18, 0xb9, 0xb7, 0xda, 0x0e, 0x26, 0x4b, 0xde, 0x4d, 0x52, 0x8b, 0xe4, 0x6c, 0x79, 0x5e, 0xd2, 0x1a, 0x3c, 0x8d, 0xa6, 0xa9, 0x5c, 0xcd, 0x08, 0x11, 0xf6, 0x7e, 0x26, 0x6d, 0x27, 0xf2, 0x1c, 0xb0, 0x73, 0x36, 0x22, 0xff, 0x64, 0xcb, 0x6a, 0x29, 0xf7, 0xeb, 0x57, 0x25, 0x8b, 0xe9, 0xa2, 0xac, 0x5c, 0xe1, 0x9d, 0x78, 0xd3, 0x36, 0x50, 0xa5, 0x45, 0x3f, 0x19, 0x2c, 0x2c, 0x48, 0x2c, 0x77, 0x55, 0x8c, 0x19, 0x6e, 0x30, 0xba, 0x1a, 0x05, 0xe2, 0x6e, 0xd2, 0xe0, 0x9d, 0xfe, 0x4a ]), [ 0x67, 0x35, 0xc1, 0x7c, 0x08, 0x2c, 0xfc, 0xbc, 0x3e, 0x1b, 0x8f, 0xbf, 0xbe, 0xa4, 0x90, 0x79, 0xbc, 0xb7, 0x22, 0x10 ] ); } #[test] fn test_issuer_serial_number() { assert_eq!( serial_number_str_from_der(&[ 0x04, 0x84, 0x2c, 0x00, 0xaf, 0x05, 0xac, 0xcc, 0xeb, 0x14, 0x51, 0x4e, 0x2d, 0x37, 0xb0, 0xc3, 0xaa, 0xa2, 0x18, 0xf1, 0x50, 0x57, 0xf1, 0xdc, 0xb8, 0x24, 0xa2, 0x14, 0x98, 0x0b, 0x74, 0x46, 0x88, 0xa0, 0x88, 0x8a, 0x02, 0x97, 0xfa, 0x7d, 0xc5, 0xe1, 0xea, 0xd8, 0xca, 0x12, 0x91, 0xdb, 0x22, 0x9c, 0x28, 0xeb, 0x86, 0x78, 0xbc, 0xe8, 0x00, 0x82, 0x2c, 0x07, 0x22, 0x8f, 0x41, 0x6a, 0xe4, 0x9d, 0x21, 0x8e, 0x5d, 0xa2, 0xf2, 0xd1, 0xa8, 0xa2, 0x7d, 0xc1, 0x9a, 0xdf, 0x66, 0x8a, 0x74, 0x62, 0x89, 0x99, 0xd2, 0x22, 0xb4, 0x01, 0x59, 0xd8, 0x07, 0x6f, 0xaf, 0xbb, 0x8c, 0x5e, 0xdb ]), "21EEEF9A4C61D4B9E3D94BEA46F9A12AC6887CE2188559F40FF95777E8014889" ); assert_eq!( serial_number_str_from_der(&[ 0x04, 0x1a, 0xe7, 0x83, 0xc2, 0xd0, 0x47, 0xcb, 0xc4, 0xc9, 0x54, 0x26, 0x8b, 0x70, 0xff, 0x5e, 0x75, 0x18, 0xb9, 0xb7, 0xda, 0x0e, 0x26, 0x4b, 0xde, 0x4d, 0x52, 0x8b, 0xe4, 0x6c, 0x79, 0x5e, 0xd2, 0x1a, 0x3c, 0x8d, 0xa6, 0xa9, 0x5c, 0xcd, 0x08, 0x11, 0xf6, 0x7e, 0x26, 0x6d, 0x27, 0xf2, 0x1c, 0xb0, 0x73, 0x36, 0x22, 0xff, 0x64, 0xcb, 0x6a, 0x29, 0xf7, 0xeb, 0x57, 0x25, 0x8b, 0xe9, 0xa2, 0xac, 0x5c, 0xe1, 0x9d, 0x78, 0xd3, 0x36, 0x50, 0xa5, 0x45, 0x3f, 0x19, 0x2c, 0x2c, 0x48, 0x2c, 0x77, 0x55, 0x8c, 0x19, 0x6e, 0x30, 0xba, 0x1a, 0x05, 0xe2, 0x6e, 0xd2, 0xe0, 0x9d, 0xfe, 0x4a ]), "E735C17C082CFCBC3E1B8FBFBEA49079BCB7221096001C4730C4EE2A64009B62" ); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/src/crypto.rs
test/src/crypto.rs
// Licensed under the Apache-2.0 license #![allow(unused)] /// Cryptographic operations implemented for readability rather than /// performance, implemented independently from the rest of Caliptra for use in /// end-to-end test cases. /// /// DO NOT REFACTOR THIS FILE TO RE-USE CODE FROM OTHER PARTS OF CALIPTRA use openssl::{ bn::{BigNum, BigNumContext}, ec::{EcGroup, EcKey, EcPoint, PointConversionForm}, nid::Nid, pkey::{PKey, Private, Public}, pkey_ml_dsa::{PKeyMlDsaBuilder, PKeyMlDsaParams, Variant}, }; use ml_kem::{ kem::{DecapsulationKey, Kem}, Encoded, EncodedSizeUser, KemCore, MlKem1024, MlKem1024Params, }; use serde::{Deserialize, Serialize}; use serde_json; pub mod hpke; use hpke::Hpke; const ML_KEM_ID: u16 = 66; // Derives a key using a DRBG. Returns (priv, pub_x, pub_y) pub fn derive_ecdsa_keypair(seed: &[u8]) -> ([u8; 48], [u8; 48], [u8; 48]) { let priv_key = hmac384_drbg_keygen(seed, &[0; 48]); let pub_key = derive_ecdsa_key(&priv_key); let ec_key = EcKey::try_from(pub_key).unwrap(); let group = EcGroup::from_curve_name(Nid::SECP384R1).unwrap(); let mut bn_ctx = BigNumContext::new().unwrap(); let mut pub_x = BigNum::new().unwrap(); let mut pub_y = BigNum::new().unwrap(); ec_key .public_key() .affine_coordinates(&group, &mut pub_x, &mut pub_y, &mut bn_ctx) .unwrap(); ( priv_key, pub_x.to_vec_padded(48).unwrap().try_into().unwrap(), pub_y.to_vec_padded(48).unwrap().try_into().unwrap(), ) } #[test] fn test_derive_ecdsa_keypair() { let (priv_key, pub_x, pub_y) = derive_ecdsa_keypair(&[ 0x75, 0xb7, 0x66, 0x26, 0x10, 0x09, 0x7e, 0xb6, 0x58, 0xc4, 0x2c, 0x44, 0xa5, 0xe3, 0xf1, 0x4f, 0x64, 0xd2, 0xc7, 0xde, 0x15, 0x4d, 0xbd, 0xda, 0x03, 0x1c, 0x18, 0xbc, 0x1a, 0x8a, 0xfa, 0xd4, 0xcb, 0x61, 0x3d, 0x5b, 0x85, 0x69, 0x96, 0x53, 0x9b, 0x14, 0x55, 0xab, 0x89, 0xa1, 0xd0, 0x3f, ]); assert_eq!( priv_key, [ 0x9f, 0xb1, 0xc3, 0xff, 0xf6, 0xd6, 0xfa, 0x09, 0x28, 0x3a, 0x5d, 0x6b, 0x78, 0xe5, 0xcb, 0x31, 0x7e, 0x9c, 0xa1, 0xd1, 0x8a, 0x12, 0xbf, 0x90, 0x45, 0x76, 0x41, 0x9d, 0x77, 0x2f, 0xed, 0x33, 0x51, 0x6c, 0x8a, 0x85, 0x6b, 0xdd, 0x84, 0xd6, 0x7a, 0x1f, 0xf1, 0x19, 0xe2, 0x95, 0x15, 0x0f ] ); assert_eq!( pub_x, [ 0x6a, 0x95, 0x60, 0x46, 0xea, 0x28, 0x3a, 0x03, 0x19, 0x10, 0x5d, 0xed, 0x52, 0x11, 0x81, 0xea, 0x95, 0x7f, 0xdb, 0x40, 0xb1, 0x1f, 0x52, 0x17, 0xdf, 0x3f, 0x33, 0x92, 0x17, 0xa6, 0x19, 0x01, 0xab, 0xe7, 0x4c, 0xf9, 0xbc, 0xad, 0xd5, 0xc1, 0x1f, 0x29, 0xe4, 0xc2, 0xd7, 0x0f, 0xb5, 0x43, ], ); assert_eq!( pub_y, [ 0x01, 0x5c, 0x00, 0x00, 0x34, 0x76, 0xc6, 0xb9, 0xc2, 0xa5, 0x7d, 0x79, 0x90, 0x14, 0xe1, 0x56, 0xa1, 0x1c, 0x6b, 0x32, 0x88, 0x97, 0x3f, 0x90, 0xc2, 0xb5, 0x68, 0x5a, 0xd4, 0x5a, 0x65, 0xc9, 0xe9, 0x17, 0x5b, 0xfd, 0x83, 0x6e, 0x93, 0xcf, 0xdb, 0xc0, 0x54, 0x1a, 0x3b, 0xf6, 0x3d, 0xae, ], ); } pub(crate) fn derive_ecdsa_key(priv_bytes: &[u8; 48]) -> PKey<Public> { let group = EcGroup::from_curve_name(Nid::SECP384R1).unwrap(); let mut pub_point = EcPoint::new(&group).unwrap(); let bn_ctx = BigNumContext::new().unwrap(); let priv_key_bn = &BigNum::from_slice(priv_bytes).unwrap(); pub_point .mul_generator(&group, priv_key_bn, &bn_ctx) .unwrap(); let key = EcKey::from_private_components(&group, priv_key_bn, &pub_point).unwrap(); let public_key = EcKey::from_public_key(&group, key.public_key()).unwrap(); PKey::from_ec_key(public_key).unwrap() } pub(crate) fn derive_mldsa_key(seed: &[u8; 32]) -> PKey<Public> { let builder = PKeyMlDsaBuilder::<Private>::from_seed(Variant::MlDsa87, seed).unwrap(); let private_key = builder.build().unwrap(); let public_params = PKeyMlDsaParams::<Public>::from_pkey(&private_key).unwrap(); PKeyMlDsaBuilder::<Public>::new(Variant::MlDsa87, public_params.public_key().unwrap(), None) .unwrap() .build() .unwrap() } #[test] fn test_derive_ecdsa_key() { // test vector from https://csrc.nist.gov/Projects/cryptographic-algorithm-validation-program/digital-signatures let expected_public_key = PKey::from_ec_key( EcKey::from_public_key_affine_coordinates( &EcGroup::from_curve_name(Nid::SECP384R1).unwrap(), &BigNum::from_slice(&[ 0xfd, 0x3c, 0x84, 0xe5, 0x68, 0x9b, 0xed, 0x27, 0x0e, 0x60, 0x1b, 0x3d, 0x80, 0xf9, 0x0d, 0x67, 0xa9, 0xae, 0x45, 0x1c, 0xce, 0x89, 0x0f, 0x53, 0xe5, 0x83, 0x22, 0x9a, 0xd0, 0xe2, 0xee, 0x64, 0x56, 0x11, 0xfa, 0x99, 0x36, 0xdf, 0xa4, 0x53, 0x06, 0xec, 0x18, 0x06, 0x67, 0x74, 0xaa, 0x24, ]) .unwrap(), &BigNum::from_slice(&[ 0xb8, 0x3c, 0xa4, 0x12, 0x6c, 0xfc, 0x4c, 0x4d, 0x1d, 0x18, 0xa4, 0xb6, 0xc2, 0x1c, 0x7f, 0x69, 0x9d, 0x51, 0x23, 0xdd, 0x9c, 0x24, 0xf6, 0x6f, 0x83, 0x38, 0x46, 0xee, 0xb5, 0x82, 0x96, 0x19, 0x6b, 0x42, 0xec, 0x06, 0x42, 0x5d, 0xb5, 0xb7, 0x0a, 0x4b, 0x81, 0xb7, 0xfc, 0xf7, 0x05, 0xa0, ]) .unwrap(), ) .unwrap(), ) .unwrap(); let derived_public_key = derive_ecdsa_key(&[ 0x53, 0x94, 0xf7, 0x97, 0x3e, 0xa8, 0x68, 0xc5, 0x2b, 0xf3, 0xff, 0x8d, 0x8c, 0xee, 0xb4, 0xdb, 0x90, 0xa6, 0x83, 0x65, 0x3b, 0x12, 0x48, 0x5d, 0x5f, 0x62, 0x7c, 0x3c, 0xe5, 0xab, 0xd8, 0x97, 0x8f, 0xc9, 0x67, 0x3d, 0x14, 0xa7, 0x1d, 0x92, 0x57, 0x47, 0x93, 0x16, 0x62, 0x49, 0x3c, 0x37, ]); assert!(expected_public_key.public_eq(&derived_public_key)); } pub(crate) fn hmac384(key: &[u8], data: &[u8]) -> [u8; 48] { use openssl::hash::MessageDigest; use openssl::sign::Signer; let pkey = PKey::hmac(key).unwrap(); let mut signer = Signer::new(MessageDigest::sha384(), &pkey).unwrap(); signer.update(data).unwrap(); let mut result = [0u8; 48]; signer.sign(&mut result).unwrap(); result } pub(crate) fn hmac512(key: &[u8], data: &[u8]) -> [u8; 64] { use openssl::hash::MessageDigest; use openssl::sign::Signer; let pkey = PKey::hmac(key).unwrap(); let mut signer = Signer::new(MessageDigest::sha512(), &pkey).unwrap(); signer.update(data).unwrap(); let mut result = [0u8; 64]; signer.sign(&mut result).unwrap(); result } #[test] fn test_hmac384() { // test vector from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/message-authentication assert_eq!( hmac384( &[ 0x5e, 0xab, 0x0d, 0xfa, 0x27, 0x31, 0x12, 0x60, 0xd7, 0xbd, 0xdc, 0xf7, 0x71, 0x12, 0xb2, 0x3d, 0x8b, 0x42, 0xeb, 0x7a, 0x5d, 0x72, 0xa5, 0xa3, 0x18, 0xe1, 0xba, 0x7e, 0x79, 0x27, 0xf0, 0x07, 0x9d, 0xbb, 0x70, 0x13, 0x17, 0xb8, 0x7a, 0x33, 0x40, 0xe1, 0x56, 0xdb, 0xce, 0xe2, 0x8e, 0xc3, 0xa8, 0xd9, ], &[ 0xf4, 0x13, 0x80, 0x12, 0x3c, 0xcb, 0xec, 0x4c, 0x52, 0x7b, 0x42, 0x56, 0x52, 0x64, 0x11, 0x91, 0xe9, 0x0a, 0x17, 0xd4, 0x5e, 0x2f, 0x62, 0x06, 0xcf, 0x01, 0xb5, 0xed, 0xbe, 0x93, 0x2d, 0x41, 0xcc, 0x8a, 0x24, 0x05, 0xc3, 0x19, 0x56, 0x17, 0xda, 0x2f, 0x42, 0x05, 0x35, 0xee, 0xd4, 0x22, 0xac, 0x60, 0x40, 0xd9, 0xcd, 0x65, 0x31, 0x42, 0x24, 0xf0, 0x23, 0xf3, 0xba, 0x73, 0x0d, 0x19, 0xdb, 0x98, 0x44, 0xc7, 0x1c, 0x32, 0x9c, 0x8d, 0x9d, 0x73, 0xd0, 0x4d, 0x8c, 0x5f, 0x24, 0x4a, 0xea, 0x80, 0x48, 0x82, 0x92, 0xdc, 0x80, 0x3e, 0x77, 0x24, 0x02, 0xe7, 0x2d, 0x2e, 0x9f, 0x1b, 0xab, 0xa5, 0xa6, 0x00, 0x4f, 0x00, 0x06, 0xd8, 0x22, 0xb0, 0xb2, 0xd6, 0x5e, 0x9e, 0x4a, 0x30, 0x2d, 0xd4, 0xf7, 0x76, 0xb4, 0x7a, 0x97, 0x22, 0x50, 0x05, 0x1a, 0x70, 0x1f, 0xab, 0x2b, 0x70, ] ), [ 0x7c, 0xf5, 0xa0, 0x61, 0x56, 0xad, 0x3d, 0xe5, 0x40, 0x5a, 0x5d, 0x26, 0x1d, 0xe9, 0x02, 0x75, 0xf9, 0xbb, 0x36, 0xde, 0x45, 0x66, 0x7f, 0x84, 0xd0, 0x8f, 0xbc, 0xb3, 0x08, 0xca, 0x8f, 0x53, 0xa4, 0x19, 0xb0, 0x7d, 0xea, 0xb3, 0xb5, 0xf8, 0xea, 0x23, 0x1c, 0x5b, 0x03, 0x6f, 0x88, 0x75, ], ); } pub(crate) fn hmac384_kdf(key: &[u8], label: &[u8], context: Option<&[u8]>) -> [u8; 48] { let ctr_be = 1_u32.to_be_bytes(); let mut msg = Vec::<u8>::default(); msg.extend_from_slice(&ctr_be); msg.extend_from_slice(label); if let Some(context) = context { msg.push(0x00); msg.extend_from_slice(context); } hmac384(key, &msg) } pub(crate) fn hmac512_kdf(key: &[u8], label: &[u8], context: Option<&[u8]>) -> [u8; 64] { let ctr_be = 1_u32.to_be_bytes(); let mut msg = Vec::<u8>::default(); msg.extend_from_slice(&ctr_be); msg.extend_from_slice(label); if let Some(context) = context { msg.push(0x00); msg.extend_from_slice(context); } hmac512(key, &msg) } #[test] fn test_hmac384_kdf() { // test vector from https://csrc.nist.gov/Projects/cryptographic-algorithm-validation-program/key-derivation assert_eq!( hmac384_kdf( &[ 0xb5, 0x7d, 0xc5, 0x23, 0x54, 0xaf, 0xee, 0x11, 0xed, 0xb4, 0xc9, 0x05, 0x2a, 0x52, 0x83, 0x44, 0x34, 0x8b, 0x2c, 0x6b, 0x6c, 0x39, 0xf3, 0x21, 0x33, 0xed, 0x3b, 0xb7, 0x20, 0x35, 0xa4, 0xab, 0x55, 0xd6, 0x64, 0x8c, 0x15, 0x29, 0xef, 0x7a, 0x91, 0x70, 0xfe, 0xc9, 0xef, 0x26, 0xa8, 0x1e, ], &[ 0x17, 0xe6, 0x41, 0x90, 0x9d, 0xed, 0xfe, 0xe4, 0x96, 0x8b, 0xb9, 0x5d, 0x7f, 0x77, 0x0e, 0x45, 0x57, 0xca, 0x34, 0x7a, 0x46, 0x61, 0x4c, 0xb3, 0x71, 0x42, 0x3f, 0x0d, 0x91, 0xdf, 0x3b, 0x58, 0xb5, 0x36, 0xed, 0x54, 0x53, 0x1f, 0xd2, 0xa2, 0xeb, 0x0b, 0x8b, 0x2a, 0x16, 0x34, 0xc2, 0x3c, 0x88, 0xfa, 0xd9, 0x70, 0x6c, 0x45, 0xdb, 0x44, 0x11, 0xa2, 0x3b, 0x89, ], None )[..40], [ 0x59, 0x49, 0xac, 0xf9, 0x63, 0x5a, 0x77, 0x29, 0x79, 0x28, 0xc1, 0xe1, 0x55, 0xd4, 0x3a, 0x4e, 0x4b, 0xca, 0x61, 0xb1, 0x36, 0x9a, 0x5e, 0xf5, 0x05, 0x30, 0x88, 0x85, 0x50, 0xba, 0x27, 0x0e, 0x26, 0xbe, 0x4a, 0x42, 0x1c, 0xdf, 0x80, 0xb7, ], ); } fn is_valid_privkey(buf: &[u8; 48]) -> bool { let group = EcGroup::from_curve_name(Nid::SECP384R1).unwrap(); let mut ctx = BigNumContext::new().unwrap(); let mut order = BigNum::new().unwrap(); group.order(&mut order, &mut ctx).unwrap(); let zero = BigNum::from_u32(0).unwrap(); let bn = &BigNum::from_slice(buf).unwrap(); bn > &zero && bn < &order } #[test] fn test_is_valid_privkey() { assert!(!is_valid_privkey(&[0; 48])); assert!(is_valid_privkey(&[1; 48])); assert!(is_valid_privkey(&[ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf, 0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a, 0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x72 ])); assert!(!is_valid_privkey(&[ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf, 0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a, 0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x73 ])); } struct Hmac384Drbg { k: [u8; 48], v: [u8; 48], } impl Hmac384Drbg { pub fn new(entropy: &[u8], nonce: &[u8]) -> Self { let mut result = Self { k: [0x00; 48], v: [0x01; 48], }; result.update(&[entropy, nonce].concat()); result } pub fn generate(&mut self, len: usize) -> Vec<u8> { let mut result = vec![]; while result.len() < len { self.v = hmac384(&self.k, &self.v); result.extend(self.v); } self.update(&[]); result.resize(len, 0x00); result } fn update(&mut self, data: &[u8]) { self.k = hmac384(&self.k, &[self.v.as_slice(), &[0x00], data].concat()); self.v = hmac384(&self.k, &self.v); if !data.is_empty() { self.k = hmac384(&self.k, &[self.v.as_slice(), &[0x01], data].concat()); self.v = hmac384(&self.k, &self.v); } } } #[test] fn test_hmac384_drbg() { // Test vector from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/random-number-generators#DRBG let mut drbg = Hmac384Drbg::new( &[ 0xa1, 0xdc, 0x2d, 0xfe, 0xda, 0x4f, 0x3a, 0x11, 0x24, 0xe0, 0xe7, 0x5e, 0xbf, 0xbe, 0x5f, 0x98, 0xca, 0xc1, 0x10, 0x18, 0x22, 0x1d, 0xda, 0x3f, 0xdc, 0xf8, 0xf9, 0x12, 0x5d, 0x68, 0x44, 0x7a, ], &[ 0xba, 0xe5, 0xea, 0x27, 0x16, 0x65, 0x40, 0x51, 0x52, 0x68, 0xa4, 0x93, 0xa9, 0x6b, 0x51, 0x87, ], ); // The NIST test ignores the first call to generate drbg.generate(192); assert_eq!( drbg.generate(192), vec![ 0x22, 0x82, 0x93, 0xe5, 0x9b, 0x1e, 0x45, 0x45, 0xa4, 0xff, 0x9f, 0x23, 0x26, 0x16, 0xfc, 0x51, 0x08, 0xa1, 0x12, 0x8d, 0xeb, 0xd0, 0xf7, 0xc2, 0x0a, 0xce, 0x83, 0x7c, 0xa1, 0x05, 0xcb, 0xf2, 0x4c, 0x0d, 0xac, 0x1f, 0x98, 0x47, 0xda, 0xfd, 0x0d, 0x05, 0x00, 0x72, 0x1f, 0xfa, 0xd3, 0xc6, 0x84, 0xa9, 0x92, 0xd1, 0x10, 0xa5, 0x49, 0xa2, 0x64, 0xd1, 0x4a, 0x89, 0x11, 0xc5, 0x0b, 0xe8, 0xcd, 0x6a, 0x7e, 0x8f, 0xac, 0x78, 0x3a, 0xd9, 0x5b, 0x24, 0xf6, 0x4f, 0xd8, 0xcc, 0x4c, 0x8b, 0x64, 0x9e, 0xac, 0x2b, 0x15, 0xb3, 0x63, 0xe3, 0x0d, 0xf7, 0x95, 0x41, 0xa6, 0xb8, 0xa1, 0xca, 0xac, 0x23, 0x89, 0x49, 0xb4, 0x66, 0x43, 0x69, 0x4c, 0x85, 0xe1, 0xd5, 0xfc, 0xbc, 0xd9, 0xaa, 0xae, 0x62, 0x60, 0xac, 0xee, 0x66, 0x0b, 0x8a, 0x79, 0xbe, 0xa4, 0x8e, 0x07, 0x9c, 0xeb, 0x6a, 0x5e, 0xaf, 0x49, 0x93, 0xa8, 0x2c, 0x3f, 0x1b, 0x75, 0x8d, 0x7c, 0x53, 0xe3, 0x09, 0x4e, 0xea, 0xc6, 0x3d, 0xc2, 0x55, 0xbe, 0x6d, 0xcd, 0xcc, 0x2b, 0x51, 0xe5, 0xca, 0x45, 0xd2, 0xb2, 0x06, 0x84, 0xa5, 0xa8, 0xfa, 0x58, 0x06, 0xb9, 0x6f, 0x84, 0x61, 0xeb, 0xf5, 0x1b, 0xc5, 0x15, 0xa7, 0xdd, 0x8c, 0x54, 0x75, 0xc0, 0xe7, 0x0f, 0x2f, 0xd0, 0xfa, 0xf7, 0x86, 0x9a, 0x99, 0xab, 0x6c ], ); } /// Generates a SECP384R1 key from the provided entropy and nonce, using the /// same mechanism as the Caliptra hardware (HMAC_DRBG). pub(crate) fn hmac384_drbg_keygen(entropy: &[u8], nonce: &[u8]) -> [u8; 48] { let mut drbg = Hmac384Drbg::new(entropy, nonce); loop { let key = drbg.generate(48).try_into().unwrap(); if is_valid_privkey(&key) { return key; } } } #[test] fn test_hmac384_drbg_keygen() { assert_eq!( hmac384_drbg_keygen( &[ 0xae, 0x5e, 0x52, 0xd1, 0x4b, 0x0d, 0xef, 0x76, 0xda, 0xe5, 0x7c, 0x2b, 0x07, 0x6c, 0x2b, 0xf3, 0x05, 0x20, 0xad, 0x5b, 0x85, 0xef, 0x9b, 0xce, 0xb3, 0x30, 0x98, 0x46, 0x5f, 0xe7, 0xee, 0xb1, 0xa6, 0xf4, 0x5f, 0xcb, 0x19, 0x30, 0x89, 0xcf, 0xd7, 0x96, 0x8d, 0xad, 0x91, 0xc8, 0x30, 0xbc, ], &[ 0x13, 0xf7, 0xee, 0x43, 0x52, 0xfd, 0xf9, 0xf9, 0x22, 0xdc, 0x9e, 0xa7, 0x89, 0x46, 0x36, 0x28, 0x11, 0x20, 0xc9, 0x12, 0x51, 0x75, 0x1b, 0xe8, 0x99, 0xa8, 0xef, 0x7c, 0x90, 0xbb, 0xca, 0xdf, 0x19, 0x14, 0x57, 0x85, 0x56, 0xf6, 0xe1, 0x1c, 0xaf, 0xce, 0xd3, 0x38, 0xb9, 0x04, 0x84, 0x4f, ] ), [ 0xc7, 0xfa, 0x34, 0xe9, 0xa7, 0x2f, 0xb5, 0x7f, 0x61, 0x16, 0x94, 0xc3, 0xc8, 0x7f, 0xe3, 0xf4, 0x2c, 0xe4, 0x1c, 0xac, 0x44, 0x6b, 0x63, 0x63, 0x28, 0xa7, 0xf9, 0x55, 0x05, 0xd8, 0xf7, 0x42, 0x70, 0x33, 0xcf, 0x37, 0xa1, 0x69, 0x4c, 0x7c, 0x45, 0xfd, 0x72, 0x48, 0xe0, 0x7c, 0x35, 0xad, ] ); } pub(crate) fn pubkey_ecdsa_der(pub_key: &PKey<Public>) -> Vec<u8> { let ec_group = EcGroup::from_curve_name(Nid::SECP384R1).unwrap(); let ec_key = pub_key.ec_key().unwrap(); let mut bn_ctx = BigNumContext::new().unwrap(); ec_key .public_key() .to_bytes(&ec_group, PointConversionForm::UNCOMPRESSED, &mut bn_ctx) .unwrap() } pub(crate) fn pubkey_mldsa_der(pub_key: &PKey<Public>) -> Vec<u8> { let pkey_param = PKeyMlDsaParams::<Public>::from_pkey(pub_key).unwrap(); pkey_param.public_key().unwrap().to_vec() } #[test] fn test_pubkey_ecdsa_der() { const KEY_PEM: &str = "\ -----BEGIN PUBLIC KEY----- MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE/1JNLIcrWUHx2fSoUEiKohwyP3GTL3TN k0MGr7vVgOM9kdPLeNtwgZUQ1up40UA+dgfFOoE/sqBWdwQLmO0LQIoHBpqfnQE+ DmQQPrr5e0u3qIopwfq1hXtOLI0nTm2F -----END PUBLIC KEY-----"; let key = PKey::public_key_from_pem(KEY_PEM.as_bytes()).unwrap(); assert_eq!( pubkey_ecdsa_der(&key), &[ 0x04, 0xff, 0x52, 0x4d, 0x2c, 0x87, 0x2b, 0x59, 0x41, 0xf1, 0xd9, 0xf4, 0xa8, 0x50, 0x48, 0x8a, 0xa2, 0x1c, 0x32, 0x3f, 0x71, 0x93, 0x2f, 0x74, 0xcd, 0x93, 0x43, 0x06, 0xaf, 0xbb, 0xd5, 0x80, 0xe3, 0x3d, 0x91, 0xd3, 0xcb, 0x78, 0xdb, 0x70, 0x81, 0x95, 0x10, 0xd6, 0xea, 0x78, 0xd1, 0x40, 0x3e, 0x76, 0x07, 0xc5, 0x3a, 0x81, 0x3f, 0xb2, 0xa0, 0x56, 0x77, 0x04, 0x0b, 0x98, 0xed, 0x0b, 0x40, 0x8a, 0x07, 0x06, 0x9a, 0x9f, 0x9d, 0x01, 0x3e, 0x0e, 0x64, 0x10, 0x3e, 0xba, 0xf9, 0x7b, 0x4b, 0xb7, 0xa8, 0x8a, 0x29, 0xc1, 0xfa, 0xb5, 0x85, 0x7b, 0x4e, 0x2c, 0x8d, 0x27, 0x4e, 0x6d, 0x85 ] ) } pub fn aes_cmac(key: &[u8], data: &[u8]) -> [u8; 16] { use openssl::hash::MessageDigest; use openssl::sign::Signer; use openssl::symm::Cipher; let cipher = Cipher::aes_256_cbc(); let pkey = PKey::cmac(&cipher, key).unwrap(); let mut signer = Signer::new(MessageDigest::null(), &pkey).unwrap(); signer.update(data).unwrap(); let mut result = [0u8; 16]; signer.sign(&mut result).unwrap(); result } #[test] fn test_aes_cmac() { // Test vector from NIST SP 800-38B // D.3 Example 9 let key = [ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4, ]; let data = []; let expected = [ 0x02, 0x89, 0x62, 0xf6, 0x1b, 0x7b, 0xf8, 0x9e, 0xfc, 0x6b, 0x55, 0x1f, 0x46, 0x67, 0xd9, 0x83, ]; assert_eq!(aes_cmac(&key, &data), expected); } pub fn cmac_kdf(key: &[u8], label: &[u8], context: Option<&[u8]>, rounds: usize) -> Vec<u8> { let mut output = Vec::new(); for i in 1..=rounds { let mut input = Vec::new(); input.extend_from_slice(&(i as u32).to_be_bytes()); input.extend_from_slice(label); if let Some(ctx) = context { input.push(0x00); input.extend_from_slice(ctx); } output.extend_from_slice(&aes_cmac(key, &input)); } output } #[test] fn test_cmac_kdf() { // Test vector from kat/src/cmackdf_kat.rs // Key: BFB99C6AAB859A9873ACC9880BD875BB83A8B24A9307576A054216908756BE5B let key = [ 0xbf, 0xb9, 0x9c, 0x6a, 0xab, 0x85, 0x9a, 0x98, 0x73, 0xac, 0xc9, 0x88, 0x0b, 0xd8, 0x75, 0xbb, 0x83, 0xa8, 0xb2, 0x4a, 0x93, 0x07, 0x57, 0x6a, 0x05, 0x42, 0x16, 0x90, 0x87, 0x56, 0xbe, 0x5b, ]; // Fixed Data: CD9B9791F5EEE211918BA1E2B01B4E29 let label = [ 0xcd, 0x9b, 0x97, 0x91, 0xf5, 0xee, 0xe2, 0x11, 0x91, 0x8b, 0xa1, 0xe2, 0xb0, 0x1b, 0x4e, 0x29, ]; let output = cmac_kdf(&key, &label, None, 4); // Key Out: C303887FB0ACA8E78DEBB8A008E75C88C26E927F0FA8A1DF1614C97E1B6F78B... let expected = [ 0xc3, 0x03, 0x88, 0x7f, 0xb0, 0xac, 0xa8, 0xe7, 0x8d, 0xeb, 0xb8, 0xa0, 0x08, 0xe7, 0x5c, 0x88, 0xc2, 0x6e, 0x92, 0x7f, 0x0f, 0xa8, 0xa1, 0xdf, 0x16, 0x14, 0xc9, 0x7e, 0x1b, 0x6f, 0x78, 0xb3, 0x5c, 0x8f, 0x8a, 0x1c, 0xb9, 0xcd, 0x9f, 0x18, 0xdc, 0x30, 0xd0, 0x6c, 0x73, 0xb7, 0x5f, 0xde, 0xa5, 0xa6, 0x36, 0xac, 0xb9, 0x2f, 0x69, 0x0f, 0xc6, 0xcb, 0x06, 0x0f, 0x0a, 0x3d, 0xb6, 0x6e, ]; assert_eq!(output, expected); } pub fn aes256_ecb_encrypt(key: &[u8], data: &[u8]) -> Vec<u8> { use openssl::symm::{Cipher, Crypter, Mode}; let mut crypter = Crypter::new(Cipher::aes_256_ecb(), Mode::Encrypt, key, None).unwrap(); crypter.pad(false); let mut ciphertext = vec![0; data.len() + Cipher::aes_256_ecb().block_size()]; let count = crypter.update(data, &mut ciphertext).unwrap(); let rest = crypter.finalize(&mut ciphertext[count..]).unwrap(); ciphertext.truncate(count + rest); ciphertext } pub fn aes256_ecb_decrypt(key: &[u8], data: &[u8]) -> Vec<u8> { use openssl::symm::{Cipher, Crypter, Mode}; let mut crypter = Crypter::new(Cipher::aes_256_ecb(), Mode::Decrypt, key, None).unwrap(); crypter.pad(false); let mut plaintext = vec![0; data.len() + Cipher::aes_256_ecb().block_size()]; let count = crypter.update(data, &mut plaintext).unwrap(); let rest = crypter.finalize(&mut plaintext[count..]).unwrap(); plaintext.truncate(count + rest); plaintext } #[test] fn test_aes256_ecb() { // NIST SP 800-38A F.1.5 let key = [ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4, ]; let plaintext = [ 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, ]; let expected_ciphertext = [ 0xf3, 0xee, 0xd1, 0xbd, 0xb5, 0xd2, 0xa0, 0x3c, 0x06, 0x4b, 0x5a, 0x7e, 0x3d, 0xb1, 0x81, 0xf8, ]; let ciphertext = aes256_ecb_encrypt(&key, &plaintext); assert_eq!(ciphertext, expected_ciphertext); let decrypted = aes256_ecb_decrypt(&key, &ciphertext); assert_eq!(decrypted, plaintext); } #[test] fn hpke_mlkem_1024() { let test_vector = hpke::test_vector::HpkeTestArgs::new(ML_KEM_ID); let ctx = hpke::HpkeMlKem1024::derive_key_pair(test_vector.ikm_r); assert_eq!(ctx.ek.as_bytes().as_slice().to_vec(), test_vector.pk_rm); assert_eq!(ctx.dk, test_vector.sk_rm); assert_eq!( ctx.decap(&test_vector.enc, &ctx.dk), test_vector.shared_secret.clone() ); let mut reader_ctx = ctx.setup_base_r(&test_vector.enc, &test_vector.sk_rm, &test_vector.info); assert_eq!(reader_ctx.base_nonce, test_vector.base_nonce); assert_eq!(reader_ctx.key, test_vector.key); assert_eq!(reader_ctx.exporter_secret, test_vector.exporter_secret); for (idx, encryption) in test_vector.encryptions.iter().enumerate() { assert_eq!(encryption.nonce, reader_ctx.computed_nonce()); assert_eq!( encryption.pt, reader_ctx.open(&encryption.aad, &encryption.ct) ); } // Self talk test let (enc, mut sender_ctx) = ctx.setup_base_s(&test_vector.pk_rm, &test_vector.info); let mut reader_ctx = ctx.setup_base_r(&enc, &ctx.dk, &test_vector.info); for (idx, encryption) in test_vector.encryptions.iter().enumerate() { let ct = sender_ctx.seal(&encryption.aad, &encryption.pt); assert_eq!(encryption.pt, reader_ctx.open(&encryption.aad, &ct)); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/src/x509.rs
test/src/x509.rs
// Licensed under the Apache-2.0 license use std::error::Error; use asn1::{Explicit, Implicit, ObjectIdentifier, ParseError, Utf8String}; pub const DICE_TCB_INFO_OID: ObjectIdentifier = asn1::oid!(2, 23, 133, 5, 4, 1); pub const DICE_MULTI_TCB_INFO_OID: ObjectIdentifier = asn1::oid!(2, 23, 133, 5, 4, 5); #[derive(Eq, PartialEq)] pub struct DiceFwid { pub hash_alg: asn1::ObjectIdentifier, pub digest: Vec<u8>, } impl std::fmt::Debug for DiceFwid { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("DiceFwid") .field("hash_alg", &format!("{}", &self.hash_alg)) .field("digest", &format!("{:02x?}", self.digest)) .finish() } } #[derive(Debug, Default, Eq, PartialEq)] pub struct DiceTcbInfo { pub vendor: Option<String>, pub model: Option<String>, pub version: Option<String>, pub svn: Option<u32>, pub layer: Option<u32>, pub index: Option<u32>, pub fwids: Vec<DiceFwid>, pub flags: Option<u32>, pub vendor_info: Option<Vec<u8>>, pub ty: Option<Vec<u8>>, } impl DiceTcbInfo { #[allow(clippy::result_large_err)] fn parse(d: &mut asn1::Parser) -> Result<Self, asn1::ParseError> { let result = DiceTcbInfo { vendor: d .read_element::<Option<Implicit<Utf8String, 0>>>()? .map(|s| s.as_inner().as_str().into()), model: d .read_element::<Option<Implicit<Utf8String, 1>>>()? .map(|s| s.as_inner().as_str().into()), version: d .read_element::<Option<Implicit<Utf8String, 2>>>()? .map(|s| s.as_inner().as_str().into()), svn: d .read_element::<Option<Implicit<u32, 3>>>()? .map(|s| s.into_inner()), layer: d .read_element::<Option<Implicit<u32, 4>>>()? .map(|s| s.into_inner()), index: d .read_element::<Option<Implicit<u32, 5>>>()? .map(|s| s.into_inner()), fwids: d .read_element::<Option<Implicit<asn1::Sequence, 6>>>()? .map(|s| { s.as_inner().clone().parse(|d| { let mut result = vec![]; while !d.is_empty() { result.push(d.read_element::<asn1::Sequence>()?.parse(|d| { Ok(DiceFwid { hash_alg: d.read_element()?, digest: d.read_element::<&[u8]>()?.to_vec(), }) })?); } Ok(result) }) }) .transpose()? .unwrap_or_default(), flags: d .read_element::<Option<Implicit<asn1::BitString, 7>>>()? .and_then(|b| b.as_inner().as_bytes().try_into().ok()) .map(u32::from_be_bytes), vendor_info: d .read_element::<Option<Implicit<&[u8], 8>>>()? .map(|s| s.as_inner().to_vec()), ty: d .read_element::<Option<Implicit<&[u8], 9>>>()? .map(|s| s.as_inner().to_vec()), }; d.read_element::<Option<Implicit<u32, 10>>>().unwrap(); Ok(result) } #[allow(clippy::result_large_err)] fn parse_single(d: &mut asn1::Parser) -> Result<Self, asn1::ParseError> { d.read_element::<asn1::Sequence>()?.parse(Self::parse) } #[allow(clippy::result_large_err)] fn parse_multiple(d: &mut asn1::Parser) -> Result<Vec<Self>, asn1::ParseError> { d.read_element::<asn1::Sequence>()?.parse(|d| { let mut result = vec![]; while !d.is_empty() { result.push(d.read_element::<asn1::Sequence>()?.parse(Self::parse)?); } Ok(result) }) } #[allow(clippy::result_large_err)] pub fn find_multiple_in_cert(cert_der: &[u8]) -> Result<Vec<Self>, asn1::ParseError> { let Some(ext_der) = get_cert_extension(cert_der, &DICE_MULTI_TCB_INFO_OID)? else { return Ok(vec![]); }; asn1::parse(ext_der, Self::parse_multiple) } #[allow(clippy::result_large_err)] pub fn find_single_in_cert(cert_der: &[u8]) -> Result<Option<Self>, asn1::ParseError> { let Some(ext_der) = get_cert_extension(cert_der, &DICE_TCB_INFO_OID)? else { return Ok(None); }; asn1::parse(ext_der, Self::parse_single).map(Some) } #[allow(clippy::result_large_err)] pub fn find_multiple_in_csr(csr_der: &[u8]) -> Result<Vec<Self>, asn1::ParseError> { let Some(ext_der) = get_csr_extension(csr_der, &DICE_MULTI_TCB_INFO_OID)? else { return Ok(vec![]); }; asn1::parse(ext_der, Self::parse_multiple) } #[allow(clippy::result_large_err)] pub fn find_single_in_csr(csr_der: &[u8]) -> Result<Option<Self>, asn1::ParseError> { let Some(ext_der) = get_csr_extension(csr_der, &DICE_TCB_INFO_OID)? else { return Ok(None); }; asn1::parse(ext_der, Self::parse_single).map(Some) } } #[test] fn test_tcb_info_parse() { let tcb_info = asn1::parse( &[ 0x30, 0x81, 0xbc, 0x30, 0x24, 0x80, 0x08, 0x43, 0x61, 0x6c, 0x69, 0x70, 0x74, 0x72, 0x61, 0x81, 0x06, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x83, 0x02, 0x01, 0x07, 0x87, 0x05, 0x00, 0x80, 0x00, 0x00, 0x00, 0x8a, 0x05, 0x00, 0x80, 0x00, 0x00, 0x0b, 0x30, 0x81, 0x93, 0x80, 0x08, 0x43, 0x61, 0x6c, 0x69, 0x70, 0x74, 0x72, 0x61, 0x81, 0x03, 0x46, 0x4d, 0x43, 0x83, 0x02, 0x01, 0x09, 0xa6, 0x7e, 0x30, 0x3d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x04, 0x30, 0xc6, 0x72, 0x45, 0x3a, 0xc6, 0x55, 0x83, 0xbf, 0x9e, 0xb3, 0xe7, 0x16, 0xd8, 0x98, 0x58, 0x05, 0x2b, 0x16, 0xb5, 0x9a, 0xeb, 0xba, 0x9d, 0x6b, 0x82, 0xaa, 0x49, 0x11, 0x29, 0xf7, 0x38, 0xab, 0x69, 0xab, 0x4f, 0x5a, 0xac, 0xfd, 0x92, 0x68, 0xe6, 0xcc, 0x92, 0x7b, 0x8f, 0x0a, 0x73, 0x24, 0x30, 0x3d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x04, 0x30, 0xb8, 0x3a, 0xe1, 0x33, 0x17, 0x05, 0x24, 0x34, 0xe5, 0x40, 0x16, 0x45, 0x52, 0xeb, 0xc6, 0x18, 0x11, 0x73, 0x5b, 0x4f, 0x3c, 0x9a, 0x03, 0xe8, 0xd2, 0xfd, 0x92, 0x4a, 0x47, 0xb0, 0xe3, 0x5d, 0xf5, 0x79, 0x23, 0xba, 0x44, 0x2c, 0x45, 0xab, 0x15, 0x62, 0x54, 0xf1, 0x70, 0x84, 0x2b, 0x65, ], DiceTcbInfo::parse_multiple, ) .unwrap(); assert_eq!( tcb_info, vec![ DiceTcbInfo { vendor: Some("Caliptra".into()), model: Some("Device".into()), svn: Some(0x107), flags: Some(0x80000000), ..Default::default() }, DiceTcbInfo { vendor: Some("Caliptra".into()), model: Some("FMC".into()), svn: Some(0x109), fwids: vec![ DiceFwid { hash_alg: asn1::oid!(2, 16, 840, 1, 101, 3, 4, 2, 2), digest: vec![ 0xc6, 0x72, 0x45, 0x3a, 0xc6, 0x55, 0x83, 0xbf, 0x9e, 0xb3, 0xe7, 0x16, 0xd8, 0x98, 0x58, 0x05, 0x2b, 0x16, 0xb5, 0x9a, 0xeb, 0xba, 0x9d, 0x6b, 0x82, 0xaa, 0x49, 0x11, 0x29, 0xf7, 0x38, 0xab, 0x69, 0xab, 0x4f, 0x5a, 0xac, 0xfd, 0x92, 0x68, 0xe6, 0xcc, 0x92, 0x7b, 0x8f, 0x0a, 0x73, 0x24 ], }, DiceFwid { hash_alg: asn1::oid!(2, 16, 840, 1, 101, 3, 4, 2, 2), digest: vec![ 0xb8, 0x3a, 0xe1, 0x33, 0x17, 0x05, 0x24, 0x34, 0xe5, 0x40, 0x16, 0x45, 0x52, 0xeb, 0xc6, 0x18, 0x11, 0x73, 0x5b, 0x4f, 0x3c, 0x9a, 0x03, 0xe8, 0xd2, 0xfd, 0x92, 0x4a, 0x47, 0xb0, 0xe3, 0x5d, 0xf5, 0x79, 0x23, 0xba, 0x44, 0x2c, 0x45, 0xab, 0x15, 0x62, 0x54, 0xf1, 0x70, 0x84, 0x2b, 0x65 ], }, ], ..Default::default() }, ] ) } #[test] fn test_tcb_info_find_multiple_in_cert_when_no_tcb_info() { let cert_der = include_bytes!("../tests/caliptra_integration_tests/smoke_testdata/ldevid_cert_ecc.der"); assert_eq!(Ok(vec![]), DiceTcbInfo::find_multiple_in_cert(cert_der)); } /// Extracts the DER bytes of an extension from x509 certificate bytes /// (`cert_der`) with the provided `oid`. #[allow(clippy::result_large_err)] pub(crate) fn get_cert_extension<'a>( cert_der: &'a [u8], oid: &asn1::ObjectIdentifier, ) -> Result<Option<&'a [u8]>, asn1::ParseError> { asn1::parse(cert_der, |d| { d.read_element::<asn1::Sequence>()?.parse(|d| { let result = d.read_element::<asn1::Sequence>()?.parse(|d| { d.read_element::<Explicit<u32, 0>>()?; // version d.read_element::<asn1::BigInt>()?; // serial-number d.read_element::<asn1::Sequence>()?; // signature d.read_element::<asn1::Sequence>()?; // name d.read_element::<asn1::Sequence>()?; // validity d.read_element::<asn1::Sequence>()?; // subject d.read_element::<asn1::Sequence>()?; // subjectPublicKeyInfo d.read_element::<Option<Implicit<asn1::BitString, 1>>>()?; // issuerUniqueID d.read_element::<Option<Implicit<asn1::BitString, 2>>>()?; // subjectUniqueId let result = d .read_element::<Explicit<asn1::Sequence, 3>>()? .as_inner() .clone() .parse(|d| { let mut result = None; while !d.is_empty() { let found_result = d.read_element::<asn1::Sequence>()?.parse(|d| { let item_oid = d.read_element::<asn1::ObjectIdentifier>()?; d.read_element::<Option<bool>>()?; // critical let value = d.read_element::<&[u8]>()?; if &item_oid == oid { Ok(Some(value)) } else { Ok(None) } })?; if let Some(found_result) = found_result { if result.is_some() { // The extension was found more than once return Err(asn1::ParseError::new( asn1::ParseErrorKind::ExtraData, )); } result = Some(found_result); } } Ok(result) })?; Ok(result) })?; d.read_element::<asn1::Sequence>()?; // signatureAlgorithm d.read_element::<asn1::BitString>()?; // signatureValue Ok(result) }) }) } /// Extracts the DER bytes of an extension from x509 CSR bytes /// (`csr_der`) with the provided `oid`. #[allow(clippy::result_large_err)] pub(crate) fn get_csr_extension<'a>( csr_der: &'a [u8], oid: &asn1::ObjectIdentifier, ) -> Result<Option<&'a [u8]>, asn1::ParseError> { asn1::parse(csr_der, |d| { d.read_element::<asn1::Sequence>()?.parse(|d| { let result = d.read_element::<asn1::Sequence>()?.parse(|d| { d.read_element::<asn1::BigInt>()?; // version d.read_element::<asn1::Sequence>()?; // subject d.read_element::<asn1::Sequence>()?; // subject PK info let ext_reqs = d.read_explicit_element::<asn1::Sequence>(0)?.parse(|d| { let attr_oid = d.read_element::<asn1::ObjectIdentifier>()?; // Confirm this the OID for extensionRequest assert_eq!(attr_oid, asn1::oid!(1, 2, 840, 113549, 1, 9, 14)); d.read_element::<asn1::SetOf<asn1::Sequence>>() })?; let mut result = None; for ext_req in ext_reqs { result = ext_req.parse(|d| { let mut result = None; while !d.is_empty() { let found_result = d.read_element::<asn1::Sequence>()?.parse(|d| { let item_oid = d.read_element::<asn1::ObjectIdentifier>()?; d.read_element::<Option<bool>>()?; // critical let value = d.read_element::<&[u8]>()?; if &item_oid == oid { Ok(Some(value)) } else { Ok(None) } })?; if let Some(found_result) = found_result { if result.is_some() { // The extension was found more than once return Err(asn1::ParseError::new( asn1::ParseErrorKind::ExtraData, )); } result = Some(found_result); } } Ok(result) })? } Ok(result) })?; d.read_element::<asn1::Sequence>()?; // signatureAlgorithm d.read_element::<asn1::BitString>()?; // signatureValue Ok(result) }) }) } #[test] fn test_get_cert_extension() { let cert = include_bytes!("../tests/caliptra_integration_tests/smoke_testdata/ldevid_cert_ecc.der"); assert_eq!(get_cert_extension(cert, &asn1::oid!(5, 3)), Ok(None)); assert_eq!( get_cert_extension(cert, &asn1::oid!(2, 5, 29, 15)), Ok(Some([0x03, 0x02, 0x02, 0x04].as_slice())) ); } pub(crate) fn replace_sig<'a>( cert_der: &'a [u8], new_sig: &[u8], ) -> Result<Vec<u8>, Box<dyn Error + 'static>> { let (tbs, sig_algorithm) = asn1::parse(cert_der, |d| { d.read_element::<asn1::Sequence>()? .parse(|d| -> Result<_, ParseError> { let tbs = d.read_element::<asn1::Sequence>()?; let sig_algorithm = d.read_element::<asn1::Sequence>()?; let _sig_value = d.read_element::<asn1::BitString>()?; Ok((tbs, sig_algorithm)) }) })?; Ok(asn1::write(|w| { w.write_element(&asn1::SequenceWriter::new(&|w| { w.write_element(&tbs)?; w.write_element(&sig_algorithm)?; w.write_element(&asn1::BitString::new(new_sig, 0)) })) }) .map_err(|e| format!("{:?}", e))?) } #[test] fn test_replace_sig() { const REPLACED_KEY: &[u8] = &[0x01, 0x2, 0x3, 0x4]; let cert_der = include_bytes!("../tests/caliptra_integration_tests/smoke_testdata/ldevid_cert_ecc.der"); let cert_der_replaced = replace_sig(cert_der, REPLACED_KEY).unwrap(); let cert = openssl::x509::X509::from_der(&cert_der_replaced).unwrap(); assert_eq!(cert.signature().as_slice(), REPLACED_KEY); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/src/crypto/hpke/test_vector.rs
test/src/crypto/hpke/test_vector.rs
// Licensed under the Apache-2.0 license use serde::{Deserialize, Serialize}; /// This file contains the test vectors as defined in Appendix A of /// https://datatracker.ietf.org/doc/draft-ietf-hpke-pq/03/. const HPKE_TEST_VECTOR_PQ: &str = include_str!("../../crypto/test_vectors/hpke-pq.json"); #[derive(Deserialize, Serialize)] pub struct Encryption { #[serde(with = "hex::serde")] pub aad: Vec<u8>, #[serde(with = "hex::serde")] pub ct: Vec<u8>, #[serde(with = "hex::serde")] pub nonce: Vec<u8>, #[serde(with = "hex::serde")] pub pt: Vec<u8>, } #[derive(Deserialize, Serialize)] pub struct HpkeTestArgs { pub mode: u8, pub kem_id: u16, pub kdf_id: u16, pub aead_id: u16, #[serde(with = "hex::serde")] pub info: Vec<u8>, #[serde(with = "hex::serde", rename = "ikmE")] pub ikm_e: Vec<u8>, #[serde(with = "hex::serde", rename = "ikmR")] pub ikm_r: Vec<u8>, #[serde(with = "hex::serde", rename = "skRm")] pub sk_rm: Vec<u8>, #[serde(with = "hex::serde", rename = "pkRm")] pub pk_rm: Vec<u8>, #[serde(with = "hex::serde")] pub enc: Vec<u8>, #[serde(with = "hex::serde")] pub shared_secret: Vec<u8>, #[serde(with = "hex::serde")] pub suite_id: Vec<u8>, #[serde(with = "hex::serde")] pub key: Vec<u8>, #[serde(with = "hex::serde")] pub base_nonce: Vec<u8>, #[serde(with = "hex::serde")] pub exporter_secret: Vec<u8>, pub encryptions: Vec<Encryption>, } impl HpkeTestArgs { /// Returns the HPKE Test vector for the chosen KEM. pub fn new(kem_id: u16) -> Self { let kdf_id = 2; let aead_id = 2; let test_vectors: Vec<HpkeTestArgs> = serde_json::from_str(HPKE_TEST_VECTOR_PQ).unwrap(); test_vectors .into_iter() .find(|args| args.kem_id == kem_id && args.kdf_id == kdf_id && aead_id == args.aead_id) .unwrap() } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/src/crypto/hpke/mod.rs
test/src/crypto/hpke/mod.rs
// Licensed under the Apache-2.0 license use std::marker::PhantomData; /// HPKE Implementation intended to be used in OCP LOCK tests /// /// Implements: /// * ML-KEM-1024-HKDF-SHA-384-AES-256-GCM use aes_gcm::{ aead::{Aead, Payload}, Aes256Gcm, KeyInit, }; use ml_kem::{ kem::{Decapsulate, DecapsulationKey, Encapsulate, EncapsulationKey}, EncapsulateDeterministic, KemCore, MlKem1024, MlKem1024Params, B32, }; use openssl::{ hash::MessageDigest, pkey::PKey, pkey_ml_kem::{PKeyMlKemBuilder, PKeyMlKemParams, Variant}, sign::Signer, }; use rand::Rng; use zerocopy::IntoBytes; pub mod kdf; pub mod test_vector; const BASE_MODE: u8 = 0x0; pub trait Role {} pub struct Sender; pub struct Receiver; impl Role for Sender {} impl Role for Receiver {} /// Implements an HPKE Encryption Context with AES-256-GCM. pub struct EncryptionContext<Role> { pub key: Vec<u8>, pub base_nonce: Vec<u8>, pub exporter_secret: Vec<u8>, pub nonce: usize, _role: PhantomData<Role>, } impl<Role> EncryptionContext<Role> { const NN: usize = 12; pub fn new(key: Vec<u8>, base_nonce: Vec<u8>, exporter_secret: Vec<u8>) -> Self { Self { key, base_nonce, nonce: 0, exporter_secret, _role: PhantomData::<Role>, } } pub fn computed_nonce(&self) -> Vec<u8> { let nonce_bytes = self.nonce.to_be_bytes(); let mut current_nonce = vec![0; Self::NN]; let padding = Self::NN - nonce_bytes.len(); current_nonce[padding..].clone_from_slice(&nonce_bytes); for (nonce, base) in current_nonce.iter_mut().zip(self.base_nonce.iter()) { *nonce ^= base; } current_nonce } } impl<Sender> EncryptionContext<Sender> { pub fn seal(&mut self, aad: &[u8], pt: &[u8]) -> Vec<u8> { let nonce = self.computed_nonce(); let payload = Payload { aad, msg: pt }; let cipher = Aes256Gcm::new(self.key.as_slice().into()); let ct = cipher.encrypt(nonce.as_slice().into(), payload).unwrap(); self.nonce = self .nonce .checked_add(1) .expect("NONCE overflowed. This should never happen!"); ct } } impl<Receiver> EncryptionContext<Receiver> { pub fn open(&mut self, aad: &[u8], ct: &[u8]) -> Vec<u8> { let nonce = self.computed_nonce(); let payload = Payload { aad, msg: ct }; let cipher = Aes256Gcm::new(self.key.as_slice().into()); let pt = cipher.decrypt(nonce.as_slice().into(), payload).unwrap(); self.nonce = self .nonce .checked_add(1) .expect("NONCE overflowed. This should never happen!"); pt } } /// HPKE trait /// /// NOTE: Does not implement [secret /// export](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-02#name-secret-export-2) as /// this is not used in OCP LOCK. pub trait Hpke { const LABEL_DERIVE_SUITE_ID: &'static [u8]; const ALG_ID: &'static [u8]; const NK: usize; const NT: usize; const NH: usize; fn labeled_extract(salt: &[u8], label: &[u8], ikm: &[u8]) -> Vec<u8> { let suite_id: Vec<u8> = [&b"HPKE"[..], Self::ALG_ID].concat(); let labeled_ikm = { let mut ikm_builder = Vec::new(); ikm_builder.extend_from_slice(b"HPKE-v1"); ikm_builder.extend_from_slice(&suite_id); ikm_builder.extend_from_slice(label); ikm_builder.extend_from_slice(ikm); ikm_builder }; kdf::Hmac384Kdf::extract(salt, &labeled_ikm) } fn labeled_expand(prk: &[u8], label: &[u8], info: &[u8], l: usize) -> Vec<u8> { let suite_id: Vec<u8> = [&b"HPKE"[..], Self::ALG_ID].concat(); let labeled_info = { let mut ikm_builder = Vec::new(); ikm_builder.extend_from_slice(&u16::try_from(l).unwrap().to_be_bytes()); ikm_builder.extend_from_slice(b"HPKE-v1"); ikm_builder.extend_from_slice(&suite_id); ikm_builder.extend_from_slice(label); ikm_builder.extend_from_slice(info); ikm_builder }; kdf::Hmac384Kdf::expand(prk, &labeled_info, l) } /// NOTE: This impementation does not support `psk` and `psk_id`. fn key_schedule<R: Role>( mode: u8, shared_secret: &[u8], info: Option<&[u8]>, ) -> EncryptionContext<R> { let psk_id_hash = Self::labeled_extract(&[], b"psk_id_hash", &[]); let info_hash = Self::labeled_extract(&[], b"info_hash", info.unwrap_or_default()); let key_schedule_context: Vec<u8> = { let mut key_schedule_context = Vec::new(); key_schedule_context.extend_from_slice(mode.as_bytes()); key_schedule_context.extend_from_slice(psk_id_hash.as_bytes()); key_schedule_context.extend_from_slice(info_hash.as_bytes()); key_schedule_context }; let secret = Self::labeled_extract(shared_secret, b"secret", &[]); let key = Self::labeled_expand(&secret, b"key", &key_schedule_context, Self::NK); let base_nonce = Self::labeled_expand( &secret, b"base_nonce", &key_schedule_context, EncryptionContext::<R>::NN, ); let exporter_secret = Self::labeled_expand(&secret, b"exp", &key_schedule_context, Self::NH); EncryptionContext::new(key, base_nonce, exporter_secret) } fn setup_base_r(&self, enc: &[u8], sk_r: &[u8], info: &[u8]) -> EncryptionContext<Receiver> { let shared_secret = self.decap(enc, sk_r); Self::key_schedule(BASE_MODE, &shared_secret, Some(info)) } fn setup_base_s(&self, pkr: &[u8], info: &[u8]) -> (Vec<u8>, EncryptionContext<Sender>) { let (shared_secret, enc) = self.encap(pkr); ( enc, Self::key_schedule(BASE_MODE, &shared_secret, Some(info)), ) } fn decap(&self, enc: &[u8], sk_r: &[u8]) -> Vec<u8>; fn encap(&self, pk_r: &[u8]) -> (Vec<u8>, Vec<u8>); fn derive_key_pair(ikm: Vec<u8>) -> Self; fn generate_key_pair() -> Self; } pub struct HpkeMlKem1024 { pub dk: Vec<u8>, pub ek: EncapsulationKey<MlKem1024Params>, } impl Hpke for HpkeMlKem1024 { // ML-KEM-1024: KEM\x00\x42 (hex: 4b454d0042) + KEM ID (0x00 0x42) const LABEL_DERIVE_SUITE_ID: &'static [u8] = &[0x4b, 0x45, 0x4d, 0x00, 0x42]; // KDF + KDF + AAD const ALG_ID: &'static [u8] = &[0x0, 0x42, 0x0, 0x02, 0x0, 0x02]; const NK: usize = 32; const NT: usize = 16; const NH: usize = 48; fn decap(&self, enc: &[u8], sk_r: &[u8]) -> Vec<u8> { let d = B32::try_from(&sk_r[..32]).unwrap(); let z = B32::try_from(&sk_r[32..]).unwrap(); let (dk, _) = MlKem1024::generate_deterministic(&d, &z); let pt = dk.decapsulate(enc.try_into().unwrap()).unwrap(); pt.to_vec() } fn encap(&self, pk_r: &[u8]) -> (Vec<u8>, Vec<u8>) { let mut rng = rand::thread_rng(); let (enc, shared_secret) = self.ek.encapsulate(&mut rng).unwrap(); (shared_secret.to_vec(), enc.to_vec()) } fn derive_key_pair(ikm: Vec<u8>) -> Self { let expanded_ikm = kdf::Shake256Kdf::labeled_derive( Self::LABEL_DERIVE_SUITE_ID, &ikm, b"DeriveKeyPair", b"", 64, ); let d = B32::try_from(&expanded_ikm[..32]).unwrap(); let z = B32::try_from(&expanded_ikm[32..]).unwrap(); let (_, ek) = MlKem1024::generate_deterministic(&d, &z); Self { dk: expanded_ikm, ek, } } fn generate_key_pair() -> Self { let mut rng = rand::thread_rng(); let mut dz = vec![0; 64]; rng.fill(&mut dz[..]); Self::derive_key_pair(dz) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/src/crypto/hpke/kdf.rs
test/src/crypto/hpke/kdf.rs
// Licensed under the Apache-2.0 license use hkdf::Hkdf; use sha3::{ digest::{ExtendableOutput, Update, XofReader}, Shake256, }; pub struct Hmac384Kdf; impl Hmac384Kdf { pub fn extract(salt: &[u8], ikm: &[u8]) -> Vec<u8> { let (prk, _) = Hkdf::<sha2::Sha384>::extract(Some(salt), ikm); prk.to_vec() } pub fn expand(prk: &[u8], info: &[u8], l: usize) -> Vec<u8> { let mut okm = vec![0; l]; let hkdf = Hkdf::<sha2::Sha384>::from_prk(prk).unwrap(); hkdf.expand(info, &mut okm).unwrap(); okm } } pub struct Shake256Kdf; impl Shake256Kdf { pub fn labeled_derive( suite_id: &[u8], ikm: &[u8], label: &[u8], context: &[u8], l: usize, ) -> Vec<u8> { let label_len = u16::try_from(label.len()).unwrap().to_be_bytes(); let label_with_len = [&label_len, label].concat(); let labeled_ikm = { let mut data = Vec::new(); data.extend_from_slice(ikm); data.extend_from_slice(b"HPKE-v1"); data.extend_from_slice(suite_id); data.extend_from_slice(&label_with_len); data.extend_from_slice(&u16::try_from(l).unwrap().to_be_bytes()); data.extend_from_slice(context); data }; Self::derive(&labeled_ikm, l) } pub fn derive(ikm: &[u8], len: usize) -> Vec<u8> { let mut shake = sha3::Shake256::default(); shake.update(ikm); let mut res = vec![0; len]; let mut reader = shake.finalize_xof(); reader.read(&mut res); res } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/caliptra_integration_tests/fake_collateral_boot_test.rs
test/tests/caliptra_integration_tests/fake_collateral_boot_test.rs
// Licensed under the Apache-2.0 license #![allow(dead_code)] use caliptra_api::mailbox::{ AlgorithmType, GetFmcAliasEcc384CertReq, GetFmcAliasMlDsa87CertReq, GetLdevEcc384CertReq, GetLdevMldsa87CertReq, }; use caliptra_api_types::Fuses; use caliptra_builder::{ firmware::{ APP_WITH_UART, APP_WITH_UART_FPGA, FMC_FAKE_WITH_UART, ROM_FAKE_WITH_UART, ROM_FAKE_WITH_UART_FPGA, }, ImageOptions, }; use caliptra_hw_model::{BootParams, DeviceLifecycle, HwModel, InitParams, SecurityState}; use caliptra_image_types::FwVerificationPqcKeyType; use caliptra_test::{ derive::{DoeInput, DoeOutput, LDevId}, image_pk_desc_hash, x509::{DiceFwid, DiceTcbInfo}, }; use std::io::Write; const RT_READY_FOR_COMMANDS: u32 = 0x600; pub const PQC_KEY_TYPE: [FwVerificationPqcKeyType; 2] = [ FwVerificationPqcKeyType::LMS, FwVerificationPqcKeyType::MLDSA, ]; const ALGORITHM_TYPES: [AlgorithmType; 2] = [AlgorithmType::Ecc384, AlgorithmType::Mldsa87]; // Need hardcoded HASH for the canned FMC alias cert const FMC_CANNED_DEVICE_INFO_DIGEST: [u8; 48] = [ 0x89, 0x17, 0x4d, 0x32, 0x32, 0x70, 0xf9, 0xd4, 0x56, 0xb0, 0x86, 0x23, 0x35, 0x94, 0x94, 0x37, 0x95, 0x9b, 0xe8, 0xa1, 0x34, 0x45, 0x8d, 0xf8, 0x98, 0x21, 0xcb, 0x50, 0xe2, 0xac, 0x11, 0x84, 0x3d, 0xaa, 0x5b, 0x5a, 0x5a, 0x6b, 0xac, 0xf7, 0x4e, 0xf8, 0xbd, 0xff, 0xd4, 0x22, 0xe2, 0xb, ]; const FMC_CANNED_FMC_INFO_DIGEST: [u8; 48] = [ 0x83, 0xff, 0xe1, 0x84, 0x76, 0x3, 0x28, 0xcf, 0x12, 0x63, 0x2, 0x6a, 0xac, 0xbc, 0x9d, 0x81, 0xe5, 0xd1, 0x43, 0xd4, 0xfd, 0xc6, 0x25, 0x3a, 0xfc, 0xee, 0x32, 0x10, 0xf7, 0xc2, 0x5b, 0xfc, 0xad, 0x4c, 0xae, 0x40, 0x5b, 0x8b, 0x28, 0x11, 0x40, 0x3b, 0xb3, 0xf1, 0xe3, 0xe8, 0x5c, 0x19, ]; #[track_caller] fn assert_output_contains(haystack: &str, needle: &str) { assert!( haystack.contains(needle), "Expected substring in output not found: {needle}" ); } fn get_idevid_pubkey_ecc() -> openssl::pkey::PKey<openssl::pkey::Public> { let csr = openssl::x509::X509Req::from_der(include_bytes!("smoke_testdata/idevid_csr_ecc.der")) .unwrap(); csr.public_key().unwrap() } fn get_idevid_pubkey_mldsa() -> openssl::pkey::PKey<openssl::pkey::Public> { let csr = openssl::x509::X509Req::from_der(include_bytes!("smoke_testdata/idevid_csr_mldsa.der")) .unwrap(); csr.public_key().unwrap() } #[test] fn fake_boot_test() { for pqc_key_type in PQC_KEY_TYPE.iter() { for algorithm_type in ALGORITHM_TYPES.iter() { let idevid_pubkey = match algorithm_type { AlgorithmType::Ecc384 => get_idevid_pubkey_ecc(), AlgorithmType::Mldsa87 => get_idevid_pubkey_mldsa(), }; let rom = caliptra_builder::build_firmware_rom(&if cfg!(feature = "fpga_subsystem") { ROM_FAKE_WITH_UART_FPGA } else { ROM_FAKE_WITH_UART }) .unwrap(); let image = caliptra_builder::build_and_sign_image( &FMC_FAKE_WITH_UART, &if cfg!(feature = "fpga_subsystem") { APP_WITH_UART_FPGA } else { APP_WITH_UART }, ImageOptions { fw_svn: 9, pqc_key_type: *pqc_key_type, ..Default::default() }, ) .unwrap(); let (vendor_pk_desc_hash, owner_pk_hash) = image_pk_desc_hash(&image.manifest); let canned_cert_security_state = *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production); 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 fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }, rom: &rom, security_state: canned_cert_security_state, ..Default::default() }, BootParams { fw_image: Some(&image.to_bytes().unwrap()), initial_dbg_manuf_service_reg: (1 << 30), ..Default::default() }, ) .unwrap(); let mut output = vec![]; hw.step_until_output_contains("[rt] RT listening for mailbox commands...\n") .unwrap(); output .write_all(hw.output().take(usize::MAX).as_bytes()) .unwrap(); let output = String::from_utf8_lossy(&output); assert_output_contains(&output, "Running Caliptra ROM"); assert_output_contains(&output, "[fake-rom-cold-reset]"); assert_output_contains(&output, "Running Caliptra FMC"); assert_output_contains(&output, "Caliptra RT"); let ldev_cert_resp = match algorithm_type { AlgorithmType::Ecc384 => hw .mailbox_execute_req(GetLdevEcc384CertReq::default()) .unwrap(), AlgorithmType::Mldsa87 => hw .mailbox_execute_req(GetLdevMldsa87CertReq::default()) .unwrap(), }; // Extract the certificate from the response let ldev_cert_der = &ldev_cert_resp.data().unwrap(); let ldev_cert = openssl::x509::X509::from_der(ldev_cert_der).unwrap(); let ldev_cert_txt = String::from_utf8(ldev_cert.to_text().unwrap()).unwrap(); match algorithm_type { AlgorithmType::Ecc384 => { // To update the ldev cert testdata: // std::fs::write("tests/caliptra_integration_tests/smoke_testdata/ldevid_cert_ecc.txt", &ldev_cert_txt).unwrap(); // std::fs::write("tests/caliptra_integration_tests/smoke_testdata/ldevid_cert_ecc.der", ldev_cert_der).unwrap(); assert_eq!( ldev_cert_txt.as_str(), include_str!("smoke_testdata/ldevid_cert_ecc.txt") ); assert_eq!( ldev_cert_der, include_bytes!("smoke_testdata/ldevid_cert_ecc.der") ); } AlgorithmType::Mldsa87 => { // To update the ldev cert testdata: // std::fs::write("tests/caliptra_integration_tests/smoke_testdata/ldevid_cert_mldsa.txt", &ldev_cert_txt).unwrap(); // std::fs::write("tests/caliptra_integration_tests/smoke_testdata/ldevid_cert_mldsa.der", ldev_cert_der).unwrap(); assert_eq!( ldev_cert_txt.as_str(), include_str!("smoke_testdata/ldevid_cert_mldsa.txt") ); assert_eq!( ldev_cert_der, include_bytes!("smoke_testdata/ldevid_cert_mldsa.der") ); } } assert!( ldev_cert.verify(&idevid_pubkey).unwrap(), "ldev cert failed to validate with idev pubkey" ); let ldev_pubkey = ldev_cert.public_key().unwrap(); let expected_ldevid_key = LDevId::derive(&DoeOutput::generate(&DoeInput::default())); // Check that the LDevID key has all the field entropy input mixed into it // If a firmware change causes this assertion to fail, it is likely that the // logic in the ROM that derives LDevID has changed. Ensure this is // intentional, and then make the same change to // caliptra_test::LDevId::derive(). match algorithm_type { AlgorithmType::Ecc384 => { assert!(expected_ldevid_key .derive_ecc_public_key() .public_eq(&ldev_pubkey)); } AlgorithmType::Mldsa87 => { assert!(expected_ldevid_key .derive_mldsa_public_key() .public_eq(&ldev_pubkey)); } } println!("ldev-cert: {}", ldev_cert_txt); let fmc_alias_cert_resp = match algorithm_type { AlgorithmType::Ecc384 => hw .mailbox_execute_req(GetFmcAliasEcc384CertReq::default()) .unwrap(), AlgorithmType::Mldsa87 => hw .mailbox_execute_req(GetFmcAliasMlDsa87CertReq::default()) .unwrap(), }; // Extract the certificate from the response let fmc_alias_cert_der = fmc_alias_cert_resp.data().unwrap(); let mut fmc_alias_cert = openssl::x509::X509::from_der(fmc_alias_cert_der).unwrap(); if *algorithm_type == AlgorithmType::Mldsa87 { fmc_alias_cert = openssl::x509::X509::from_der(include_bytes!( "smoke_testdata/fmc_alias_cert_mldsa.der" )) .unwrap(); assert_eq!( fmc_alias_cert_der, include_bytes!("smoke_testdata/fmc_alias_cert_mldsa.der") ) } println!( "fmc-alias cert: {}", String::from_utf8_lossy(&fmc_alias_cert.to_text().unwrap()) ); let dice_tcb_info = DiceTcbInfo::find_multiple_in_cert(fmc_alias_cert_der).unwrap(); assert_eq!( dice_tcb_info, [ DiceTcbInfo { vendor: None, model: None, // This is from the SVN in the fuses (7 bits set) svn: Some(0x107), fwids: vec![DiceFwid { hash_alg: asn1::oid!(2, 16, 840, 1, 101, 3, 4, 2, 2), digest: FMC_CANNED_DEVICE_INFO_DIGEST.to_vec(), },], flags: Some(0x00000001), ty: Some(b"DEVICE_INFO".to_vec()), ..Default::default() }, DiceTcbInfo { vendor: None, model: None, // This is from the SVN in the image (9) svn: Some(0x109), fwids: vec![DiceFwid { // FMC hash_alg: asn1::oid!(2, 16, 840, 1, 101, 3, 4, 2, 2), digest: FMC_CANNED_FMC_INFO_DIGEST.to_vec(), },], ty: Some(b"FMC_INFO".to_vec()), ..Default::default() }, ] ); // TODO: re-enable when it's easier to update the canned responses // Need to use production for the canned certs to match the LDEV cert in testdata /* let canned_cert_security_state = *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production); let expected_fmc_alias_key = FmcAliasKey::derive( &Pcr0::derive(&Pcr0Input { security_state: canned_cert_security_state, fuse_anti_rollback_disable: false, vendor_pub_key_hash: vendor_pk_desc_hash, owner_pub_key_hash: owner_pk_hash, owner_pub_key_hash_from_fuses: true, ecc_vendor_pub_key_index: image.manifest.preamble.vendor_ecc_pub_key_idx, fmc_digest: image.manifest.fmc.digest, cold_boot_fw_svn: image.manifest.header.svn, // This is from the SVN in the fuses (7 bits set) fw_fuse_svn: 7, pqc_vendor_pub_key_index: image.manifest.header.vendor_pqc_pub_key_idx, pqc_key_type: 1 as u32, // MLDSA }), &expected_ldevid_key, ); // Check that the fmc-alias key has all the pcr0 input above mixed into it // If a firmware change causes this assertion to fail, it is likely that the // logic in the ROM that update PCR0 has changed. Ensure this is // intentional, and then make the same change to // caliptra_test::Pcr0Input::derive_pcr0(). assert!(expected_fmc_alias_key .derive_public_key() .public_eq(&fmc_alias_cert.public_key().unwrap())); */ assert!( fmc_alias_cert.verify(&ldev_pubkey).unwrap(), "fmc_alias cert failed to validate with ldev pubkey" ); // TODO: Validate the rest of the fmc_alias certificate fields } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/caliptra_integration_tests/test_code_coverage.rs
test/tests/caliptra_integration_tests/test_code_coverage.rs
// Licensed under the Apache-2.0 license #[cfg(all( not(feature = "verilator"), not(feature = "fpga_realtime"), not(feature = "fpga_subsystem") ))] #[test] fn test_emu_coverage() { use std::path::PathBuf; use caliptra_api::SocManager; use caliptra_builder::firmware; use caliptra_coverage::{calculator, collect_instr_pcs}; use caliptra_emu_cpu::CoverageBitmaps; use caliptra_hw_model::HwModel; use caliptra_hw_model::{BootParams, InitParams}; const TRACE_PATH: &str = "/tmp/caliptra_coverage_trace.txt"; let instr_pcs = collect_instr_pcs(firmware::rom_from_env()).unwrap(); let coverage_from_bitmap = { let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env()).unwrap(); let mut hw = caliptra_hw_model::new( InitParams { rom: &rom, trace_path: Some(PathBuf::from(TRACE_PATH)), ..Default::default() }, BootParams { ..Default::default() }, ) .unwrap(); // Upload FW hw.step_until(|m| { m.soc_ifc() .cptra_flow_status() .read() .ready_for_mb_processing() }); let CoverageBitmaps { rom, iccm: _iccm } = hw.code_coverage_bitmap(); calculator::coverage_from_bitmap(0, rom, &instr_pcs) }; println!( "Test coverage using different methods {} , {}", coverage_from_bitmap, calculator::coverage_from_instr_trace(TRACE_PATH, &instr_pcs) ); assert_eq!( coverage_from_bitmap, calculator::coverage_from_instr_trace(TRACE_PATH, &instr_pcs) ); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/caliptra_integration_tests/warm_reset.rs
test/tests/caliptra_integration_tests/warm_reset.rs
// Licensed under the Apache-2.0 license use caliptra_api::soc_mgr::SocManager; use caliptra_api_types::{DeviceLifecycle, Fuses}; use caliptra_auth_man_gen::default_test_manifest::DEFAULT_MCU_FW; use caliptra_builder::{ firmware::{APP_WITH_UART, APP_WITH_UART_FPGA, FMC_WITH_UART}, ImageOptions, }; use caliptra_common::mailbox_api::CommandId; use caliptra_hw_model::{mbox_write_fifo, BootParams, HwModel, InitParams, SecurityState}; use caliptra_image_types::FwVerificationPqcKeyType; use caliptra_test::{default_soc_manifest_bytes, image_pk_desc_hash, test_upload_firmware}; #[test] fn warm_reset_basic() { let pqc_key_type = FwVerificationPqcKeyType::LMS; // Default for test let security_state = *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production); 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") { APP_WITH_UART_FPGA } else { APP_WITH_UART }, ImageOptions { fw_svn: 9, pqc_key_type, ..Default::default() }, ) .unwrap(); let (vendor_pk_desc_hash, owner_pk_hash) = image_pk_desc_hash(&image.manifest); 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 fuse_pqc_key_type: pqc_key_type as u32, ..Default::default() }, rom: &rom, security_state, ..Default::default() }, BootParams { ..Default::default() }, ) .unwrap(); // Upload firmware using the helper function that handles subsystem mode test_upload_firmware(&mut hw, &image.to_bytes().unwrap(), pqc_key_type); // 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 warm_reset_during_fw_load() { let pqc_key_type = FwVerificationPqcKeyType::LMS; // Default for test let security_state = *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production); 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") { APP_WITH_UART_FPGA } else { APP_WITH_UART }, ImageOptions { fw_svn: 9, pqc_key_type, ..Default::default() }, ) .unwrap(); let (vendor_pk_desc_hash, owner_pk_hash) = image_pk_desc_hash(&image.manifest); let boot_params = BootParams { ..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 fuse_pqc_key_type: pqc_key_type as u32, ..Default::default() }, rom: &rom, security_state, ..Default::default() }, boot_params.clone(), ) .unwrap(); // Start the FW load // Wait for rom to be ready for firmware while !hw.ready_for_fw() { hw.step(); } let buf = image.to_bytes().unwrap(); if hw.subsystem_mode() { // In subsystem mode, use put_firmware_in_rri to stage the firmware hw.upload_firmware_rri( &buf, Some(&default_soc_manifest_bytes(pqc_key_type, 1)), Some(&DEFAULT_MCU_FW), ) .unwrap(); hw.step_until_output_contains("Running Caliptra FMC ...") .unwrap(); } else { // For non-subsystem mode, manually start the firmware load assert!(!hw.soc_mbox().lock().read().lock()); hw.soc_mbox() .cmd() .write(|_| CommandId::FIRMWARE_LOAD.into()); assert!(mbox_write_fifo(&hw.soc_mbox(), &buf).is_ok()); hw.soc_mbox().execute().write(|w| w.execute(true)); } // Perform warm reset while ROM is executing the firmware load hw.warm_reset_flow().unwrap(); // Wait for error while hw.soc_ifc().cptra_fw_error_fatal().read() == 0 { hw.step(); } assert_ne!(hw.soc_ifc().cptra_fw_error_fatal().read(), 0); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/caliptra_integration_tests/smoke_test.rs
test/tests/caliptra_integration_tests/smoke_test.rs
use caliptra_api::mailbox::AlgorithmType; // Licensed under the Apache-2.0 license use caliptra_api::soc_mgr::SocManager; use caliptra_api_types::{DeviceLifecycle, Fuses}; use caliptra_auth_man_gen::default_test_manifest::DEFAULT_MCU_FW; use caliptra_builder::firmware::{APP_WITH_UART, APP_WITH_UART_FPGA, FMC_WITH_UART}; use caliptra_builder::{firmware, ImageOptions}; use caliptra_common::mailbox_api::{ GetFmcAliasEcc384CertReq, GetFmcAliasEccCsrReq, GetFmcAliasMlDsa87CertReq, GetFmcAliasMldsaCsrReq, GetLdevEcc384CertReq, GetLdevMldsa87CertReq, GetRtAliasEcc384CertReq, GetRtAliasMlDsa87CertReq, }; use caliptra_common::RomBootStatus; use caliptra_drivers::{CaliptraError, InitDevIdCsrEnvelope}; use caliptra_hw_model::{BootParams, HwModel, InitParams, SecurityState}; use caliptra_hw_model_types::{RandomEtrngResponses, RandomNibbles}; use caliptra_image_types::FwVerificationPqcKeyType; use caliptra_test::derive::{PcrRtCurrentInput, RtAliasKey}; use caliptra_test::{ bytes_to_be_words_48, default_soc_manifest_bytes, derive::{DoeInput, DoeOutput, FmcAliasKey, IDevId, LDevId, Pcr0, Pcr0Input}, swap_word_bytes, test_upload_firmware, x509::{DiceFwid, DiceTcbInfo}, }; use caliptra_test::{derive, redact_cert, redact_csr, run_test, RedactOpts, UnwrapSingle}; use openssl::nid::Nid; use openssl::sha::{sha384, Sha384}; use rand::rngs::StdRng; use rand::SeedableRng; use regex::Regex; use std::mem; use zerocopy::{IntoBytes, TryFromBytes}; pub const PQC_KEY_TYPE: [FwVerificationPqcKeyType; 2] = [ FwVerificationPqcKeyType::LMS, FwVerificationPqcKeyType::MLDSA, ]; // Support testing against older versions of ROM in CI // More constants may need to be added here as the ROMs further diverge struct RomTestParams<'a> { #[allow(dead_code)] testdata_path: &'a str, fmc_alias_cert_redacted_txt: &'a str, fmc_alias_cert_redacted_der: &'a [u8], tcb_info_vendor: Option<&'a str>, tcb_device_info_model: Option<&'a str>, tcb_fmc_info_model: Option<&'a str>, tcb_info_flags: Option<u32>, } const ROM_LATEST_TEST_PARAMS: RomTestParams = RomTestParams { testdata_path: "tests/caliptra_integration_tests/smoke_testdata/rom-latest", fmc_alias_cert_redacted_txt: include_str!( "smoke_testdata/rom-latest/fmc_alias_cert_redacted.txt" ), fmc_alias_cert_redacted_der: include_bytes!( "smoke_testdata/rom-latest/fmc_alias_cert_redacted.der" ), tcb_info_vendor: None, tcb_device_info_model: None, tcb_fmc_info_model: None, tcb_info_flags: Some(0x00000001), }; fn get_rom_test_params() -> RomTestParams<'static> { ROM_LATEST_TEST_PARAMS } #[track_caller] fn assert_output_contains(haystack: &str, needle: &str) { assert!( haystack.contains(needle), "Expected substring in output not found: {needle}" ); } #[track_caller] fn assert_output_contains_regex(haystack: &str, needle: &str) { let re = Regex::new(needle).unwrap(); assert! { re.is_match(haystack), "Expected substring in output not found: {needle}" } } #[test] fn retrieve_csr_test() { const GENERATE_IDEVID_CSR: u32 = 1; let rom = caliptra_builder::rom_for_fw_integration_tests_fpga(cfg!(feature = "fpga_subsystem")) .unwrap(); let mut hw = caliptra_hw_model::new( InitParams { rom: &rom, security_state: *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Manufacturing), ..Default::default() }, BootParams { initial_dbg_manuf_service_reg: GENERATE_IDEVID_CSR, ..Default::default() }, ) .unwrap(); let mut txn = hw.wait_for_mailbox_receive().unwrap(); let (csr_envelop, _) = InitDevIdCsrEnvelope::try_read_from_prefix(&mem::take(&mut txn.req.data)).unwrap(); txn.respond_success(); let ecc_csr_der = &csr_envelop.ecc_csr.csr[..csr_envelop.ecc_csr.csr_len as usize]; let ecc_csr = openssl::x509::X509Req::from_der(ecc_csr_der).unwrap(); let ecc_csr_txt = String::from_utf8(ecc_csr.to_text().unwrap()).unwrap(); let mldsa_csr_der = &csr_envelop.mldsa_csr.csr[..csr_envelop.mldsa_csr.csr_len as usize]; let mldsa_csr = openssl::x509::X509Req::from_der(mldsa_csr_der).unwrap(); let mldsa_csr_txt = String::from_utf8(mldsa_csr.to_text().unwrap()).unwrap(); // To update the CSR testdata: // std::fs::write( // "tests/caliptra_integration_tests/smoke_testdata/idevid_csr_ecc.txt", // &ecc_csr_txt, // ) // .unwrap(); // std::fs::write( // "tests/caliptra_integration_tests/smoke_testdata/idevid_csr_ecc.der", // &ecc_csr_der, // ) // .unwrap(); // std::fs::write( // "tests/caliptra_integration_tests/smoke_testdata/idevid_csr_mldsa.txt", // &mldsa_csr_txt, // ) // .unwrap(); // std::fs::write( // "tests/caliptra_integration_tests/smoke_testdata/idevid_csr_mldsa.der", // &mldsa_csr_der, // ) // .unwrap(); println!("ecc csr: {}", ecc_csr_txt); println!("mldsa csr: {}", mldsa_csr_txt); assert_eq!( ecc_csr_txt.as_str(), include_str!("smoke_testdata/idevid_csr_ecc.txt") ); assert_eq!( mldsa_csr_txt.as_str(), include_str!("smoke_testdata/idevid_csr_mldsa.txt") ); assert_eq!( ecc_csr_der, include_bytes!("smoke_testdata/idevid_csr_ecc.der") ); assert_eq!( mldsa_csr_der, include_bytes!("smoke_testdata/idevid_csr_mldsa.der") ); assert!( ecc_csr.verify(&ecc_csr.public_key().unwrap()).unwrap(), "ECC CSR's self signature failed to validate" ); assert!( mldsa_csr.verify(&mldsa_csr.public_key().unwrap()).unwrap(), "ECC CSR's self signature failed to validate" ); } fn get_idevid_pubkey_ecc() -> openssl::pkey::PKey<openssl::pkey::Public> { let csr = openssl::x509::X509Req::from_der(include_bytes!("smoke_testdata/idevid_csr_ecc.der")) .unwrap(); csr.public_key().unwrap() } fn get_ldevid_pubkey_ecc() -> openssl::pkey::PKey<openssl::pkey::Public> { let cert = openssl::x509::X509::from_der(include_bytes!("smoke_testdata/ldevid_cert_ecc.der")) .unwrap(); cert.public_key().unwrap() } fn get_idevid_pubkey_mldsa() -> openssl::pkey::PKey<openssl::pkey::Public> { let csr = openssl::x509::X509Req::from_der(include_bytes!("smoke_testdata/idevid_csr_mldsa.der")) .unwrap(); csr.public_key().unwrap() } fn get_ldevid_pubkey_mldsa() -> openssl::pkey::PKey<openssl::pkey::Public> { let cert = openssl::x509::X509::from_der(include_bytes!("smoke_testdata/ldevid_cert_mldsa.der")) .unwrap(); cert.public_key().unwrap() } #[test] fn test_golden_idevid_pubkey_matches_generated() { let idevid_pubkey_ecc = get_idevid_pubkey_ecc(); let idevid_pubkey_mldsa = get_idevid_pubkey_mldsa(); let doe_out = DoeOutput::generate(&DoeInput::default()); let generated_idevid = IDevId::derive(&doe_out); assert_eq!( generated_idevid.cdi, [ 1595302429, 2693222204, 2700750034, 2341068947, 1086336218, 1015077934, 3439704633, 2756110496, 670106478, 1965056064, 3175014961, 1018544412, 1086626027, 1869434586, 2638089882, 3209973098 ] ); assert!(generated_idevid .derive_ecc_public_key() .public_eq(&idevid_pubkey_ecc)); assert!(generated_idevid .derive_mldsa_public_key() .public_eq(&idevid_pubkey_mldsa)); } #[test] fn test_golden_ldevid_pubkey_matches_generated() { let ldevid_pubkey_ecc = get_ldevid_pubkey_ecc(); let ldevid_pubkey_mldsa = get_ldevid_pubkey_mldsa(); let doe_out = DoeOutput::generate(&DoeInput::default()); let generated_ldevid = LDevId::derive(&doe_out); assert_eq!( generated_ldevid.cdi, [ 2646856615, 2999180291, 4071428836, 3246385254, 3302857457, 919578714, 2458268004, 291060689, 3979116117, 4017638804, 3557014009, 2639554114, 2914235687, 3521247795, 1993163061, 3092908117 ] ); assert!(generated_ldevid .derive_ecc_public_key() .public_eq(&ldevid_pubkey_ecc)); assert!(generated_ldevid .derive_mldsa_public_key() .public_eq(&ldevid_pubkey_mldsa)); } #[test] fn smoke_test() { const ALGORITHM_TYPES: [AlgorithmType; 2] = [AlgorithmType::Ecc384, AlgorithmType::Mldsa87]; for pqc_key_type in PQC_KEY_TYPE.iter() { for algorithm_type in ALGORITHM_TYPES.iter() { let security_state = *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production); let idevid_pubkey = match algorithm_type { AlgorithmType::Ecc384 => get_idevid_pubkey_ecc(), AlgorithmType::Mldsa87 => get_idevid_pubkey_mldsa(), }; let rom = caliptra_builder::rom_for_fw_integration_tests_fpga(cfg!( feature = "fpga_subsystem" )) .unwrap(); let fw_svn = 9; let image = 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 }, ImageOptions { fw_svn, pqc_key_type: *pqc_key_type, ..Default::default() }, ) .unwrap(); let vendor_pk_desc_hash = sha384(image.manifest.preamble.vendor_pub_key_info.as_bytes()); let owner_pk_hash = sha384(image.manifest.preamble.owner_pub_keys.as_bytes()); let vendor_pk_desc_hash_words = bytes_to_be_words_48(&vendor_pk_desc_hash); let owner_pk_hash_words = bytes_to_be_words_48(&owner_pk_hash); let fuses = Fuses { vendor_pk_hash: vendor_pk_desc_hash_words, owner_pk_hash: owner_pk_hash_words, fw_svn: [0x7F, 0, 0, 0], // Equals 7 fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; let mut hw = caliptra_hw_model::new( InitParams { fuses: fuses.clone(), rom: &rom, security_state, ..Default::default() }, BootParams { fw_image: Some(&image.to_bytes().unwrap()), soc_manifest: Some(&default_soc_manifest_bytes(*pqc_key_type, fw_svn)), mcu_fw_image: Some(&DEFAULT_MCU_FW), ..Default::default() }, ) .unwrap(); if firmware::rom_from_env() == &firmware::ROM_WITH_UART { hw.step_until_output_contains("[rt] RT listening for mailbox commands...\n") .unwrap(); let output = hw.output().take(usize::MAX); assert_output_contains(&output, "Running Caliptra ROM"); assert_output_contains(&output, "[cold-reset]"); // Confirm KAT is running. assert_output_contains(&output, "[kat] ++"); assert_output_contains(&output, "[kat] sha1"); assert_output_contains(&output, "[kat] SHA2-256"); assert_output_contains(&output, "[kat] SHA2-384"); assert_output_contains(&output, "[kat] SHA2-512"); assert_output_contains_regex(&output, r"\[kat\] SHA2-(384|512)-ACC"); assert_output_contains(&output, "[kat] HMAC-384Kdf"); assert_output_contains(&output, "[kat] HMAC-512Kdf"); assert_output_contains(&output, "[kat] LMS"); assert_output_contains(&output, "[kat] MLDSA87"); assert_output_contains(&output, "[kat] --"); assert_output_contains(&output, "Running Caliptra FMC"); assert_output_contains(&output, "Caliptra RT"); } let ldev_cert_resp = match algorithm_type { AlgorithmType::Ecc384 => hw .mailbox_execute_req(GetLdevEcc384CertReq::default()) .unwrap(), AlgorithmType::Mldsa87 => hw .mailbox_execute_req(GetLdevMldsa87CertReq::default()) .unwrap(), }; // Extract the certificate from the response let ldev_cert_der = ldev_cert_resp.data().unwrap(); let ldev_cert = openssl::x509::X509::from_der(ldev_cert_der).unwrap(); let ldev_cert_txt = String::from_utf8(ldev_cert.to_text().unwrap()).unwrap(); // To update the ldev cert testdata: // std::fs::write( // format!( // "tests/caliptra_integration_tests/smoke_testdata/ldevid_cert{}.txt", // if *algorithm_type == AlgorithmType::Mldsa87 { // "_mldsa" // } else { // "_ecc" // } // ), // &ldev_cert_txt, // ) // .unwrap(); // std::fs::write( // format!( // "tests/caliptra_integration_tests/smoke_testdata/ldevid_cert{}.der", // if *algorithm_type == AlgorithmType::Mldsa87 { // "_mldsa" // } else { // "_ecc" // } // ), // ldev_cert_der, // ) // .unwrap(); match algorithm_type { AlgorithmType::Ecc384 => { assert_eq!( ldev_cert_txt.as_str(), include_str!("smoke_testdata/ldevid_cert_ecc.txt") ); assert_eq!( ldev_cert_der, include_bytes!("smoke_testdata/ldevid_cert_ecc.der") ); } AlgorithmType::Mldsa87 => { assert_eq!( ldev_cert_txt.as_str(), include_str!("smoke_testdata/ldevid_cert_mldsa.txt") ); assert_eq!( ldev_cert_der, include_bytes!("smoke_testdata/ldevid_cert_mldsa.der") ); } } assert!( ldev_cert.verify(&idevid_pubkey).unwrap(), "ldev cert failed to validate with idev pubkey" ); let ldev_pubkey = ldev_cert.public_key().unwrap(); let expected_ldevid_key = LDevId::derive(&DoeOutput::generate(&DoeInput::default())); // Check that the LDevID key has all the field entropy input mixed into it // If a firmware change causes this assertion to fail, it is likely that the // logic in the ROM that derives LDevID has changed. Ensure this is // intentional, and then make the same change to // caliptra_test::LDevId::derive(). match algorithm_type { AlgorithmType::Ecc384 => { assert!(expected_ldevid_key .derive_ecc_public_key() .public_eq(&ldev_pubkey)); } AlgorithmType::Mldsa87 => { assert!(expected_ldevid_key .derive_mldsa_public_key() .public_eq(&ldev_pubkey)); } } println!("ldev-cert: {}", ldev_cert_txt); // Execute command let fmc_alias_cert_resp = match algorithm_type { AlgorithmType::Ecc384 => hw .mailbox_execute_req(GetFmcAliasEcc384CertReq::default()) .unwrap(), AlgorithmType::Mldsa87 => hw .mailbox_execute_req(GetFmcAliasMlDsa87CertReq::default()) .unwrap(), }; // Extract the certificate from the response let fmc_alias_cert_der = fmc_alias_cert_resp.data().unwrap(); // For fake rom // std::fs::write( // format!( // "tests/caliptra_integration_tests/smoke_testdata/fmc_alias_cert{}.der", // if *algorithm_type == AlgorithmType::Mldsa87 { // "_mldsa" // } else { // "" // } // ), // fmc_alias_cert_der, // ) // .unwrap(); let fmc_alias_cert = openssl::x509::X509::from_der(fmc_alias_cert_der).unwrap(); println!( "fmc-alias cert: {}", String::from_utf8_lossy(&fmc_alias_cert.to_text().unwrap()) ); let mut hasher = Sha384::new(); hasher.update(&[security_state.device_lifecycle() as u8]); hasher.update(&[security_state.debug_locked() as u8]); hasher.update(&[fuses.anti_rollback_disable as u8]); hasher.update(/*vendor_ecc_pk_index=*/ &[0u8]); // No keys are revoked hasher.update(&[image.manifest.header.vendor_pqc_pub_key_idx as u8]); hasher.update(&[image.manifest.pqc_key_type]); hasher.update(&[true as u8]); hasher.update(vendor_pk_desc_hash.as_bytes()); hasher.update(&owner_pk_hash); let device_info_hash = hasher.finish(); let fmc_expected_tcb_info = [ DiceTcbInfo { vendor: get_rom_test_params().tcb_info_vendor.map(String::from), model: get_rom_test_params() .tcb_device_info_model .map(String::from), // This is from the SVN in the fuses (7 bits set) svn: Some(0x107), fwids: vec![DiceFwid { hash_alg: asn1::oid!(2, 16, 840, 1, 101, 3, 4, 2, 2), digest: device_info_hash.to_vec(), }], flags: get_rom_test_params().tcb_info_flags, ty: Some(b"DEVICE_INFO".to_vec()), ..Default::default() }, DiceTcbInfo { vendor: get_rom_test_params().tcb_info_vendor.map(String::from), model: get_rom_test_params().tcb_fmc_info_model.map(String::from), // This is from the SVN in the image (9) svn: Some(0x109), fwids: vec![DiceFwid { // FMC hash_alg: asn1::oid!(2, 16, 840, 1, 101, 3, 4, 2, 2), digest: swap_word_bytes(&image.manifest.fmc.digest) .as_bytes() .to_vec(), }], ty: Some(b"FMC_INFO".to_vec()), ..Default::default() }, ]; let dice_tcb_info = DiceTcbInfo::find_multiple_in_cert(fmc_alias_cert_der).unwrap(); assert_eq!(dice_tcb_info, fmc_expected_tcb_info); let expected_fmc_alias_key = FmcAliasKey::derive( &Pcr0::derive(&Pcr0Input { security_state, fuse_anti_rollback_disable: false, vendor_pub_key_hash: vendor_pk_desc_hash_words, owner_pub_key_hash: owner_pk_hash_words, owner_pub_key_hash_from_fuses: true, ecc_vendor_pub_key_index: image.manifest.preamble.vendor_ecc_pub_key_idx, fmc_digest: image.manifest.fmc.digest, cold_boot_fw_svn: image.manifest.header.svn, // This is from the SVN in the fuses (7 bits set) fw_fuse_svn: 7, pqc_vendor_pub_key_index: image.manifest.header.vendor_pqc_pub_key_idx, pqc_key_type: *pqc_key_type as u32, }), &expected_ldevid_key, ); // Check that the fmc-alias key has all the pcr0 input above mixed into it // If a firmware change causes this assertion to fail, it is likely that the // logic in the ROM that update PCR0 has changed. Ensure this is // intentional, and then make the same change to // caliptra_test::Pcr0Input::derive_pcr0(). match algorithm_type { AlgorithmType::Ecc384 => { assert!(expected_fmc_alias_key .derive_public_key() .public_eq(&fmc_alias_cert.public_key().unwrap())); } AlgorithmType::Mldsa87 => { assert!(expected_fmc_alias_key .derive_mldsa_public_key() .public_eq(&fmc_alias_cert.public_key().unwrap())); } } assert!( fmc_alias_cert.verify(&ldev_pubkey).unwrap(), "fmc_alias cert failed to validate with ldev pubkey" ); let fmc_alias_pubkey = fmc_alias_cert.public_key().unwrap(); // Validate the fmc-alias fields (this are redacted in the testdata because they can change): match algorithm_type { AlgorithmType::Ecc384 => { assert_eq!( fmc_alias_cert .serial_number() .to_bn() .unwrap() .to_vec_padded(20) .unwrap(), derive::ecc_cert_serial_number(&fmc_alias_pubkey) ); assert_eq!( fmc_alias_cert.subject_key_id().unwrap().as_slice(), derive::ecc_key_id(&fmc_alias_pubkey), ); } AlgorithmType::Mldsa87 => { assert_eq!( fmc_alias_cert .serial_number() .to_bn() .unwrap() .to_vec_padded(20) .unwrap(), derive::mldsa_cert_serial_number(&fmc_alias_pubkey) ); assert_eq!( fmc_alias_cert.subject_key_id().unwrap().as_slice(), derive::mldsa_key_id(&fmc_alias_pubkey), ); } } assert_eq!( fmc_alias_cert.authority_key_id().unwrap().as_slice(), ldev_cert.subject_key_id().unwrap().as_slice(), ); match algorithm_type { AlgorithmType::Ecc384 => { assert_eq!( &fmc_alias_cert .subject_name() .entries_by_nid(Nid::SERIALNUMBER) .unwrap_single() .data() .as_utf8() .unwrap()[..], derive::ecc_serial_number_str(&fmc_alias_pubkey) ); } AlgorithmType::Mldsa87 => { assert_eq!( &fmc_alias_cert .subject_name() .entries_by_nid(Nid::SERIALNUMBER) .unwrap_single() .data() .as_utf8() .unwrap()[..], derive::mldsa_serial_number_str(&fmc_alias_pubkey) ); } } assert_eq!( &fmc_alias_cert .issuer_name() .entries_by_nid(Nid::SERIALNUMBER) .unwrap_single() .data() .as_utf8() .unwrap()[..], &ldev_cert .subject_name() .entries_by_nid(Nid::SERIALNUMBER) .unwrap_single() .data() .as_utf8() .unwrap()[..], ); if *algorithm_type == AlgorithmType::Ecc384 { // When comparing fmc-alias golden-data, redact fields that are affected // by firmware measurements (this is ok because these values are checked // above) let fmc_alias_cert_redacted_der = redact_cert( fmc_alias_cert_der, RedactOpts { keep_authority: true, }, ); let fmc_alias_cert_redacted = openssl::x509::X509::from_der(&fmc_alias_cert_redacted_der).unwrap(); let fmc_alias_cert_redacted_txt = String::from_utf8(fmc_alias_cert_redacted.to_text().unwrap()).unwrap(); // To update the alias-cert golden-data: // std::fs::write( // format!( // "{}/fmc_alias_cert_redacted.txt", // get_rom_test_params().testdata_path // ), // &fmc_alias_cert_redacted_txt, // ) // .unwrap(); // std::fs::write( // format!( // "{}/fmc_alias_cert_redacted.der", // get_rom_test_params().testdata_path // ), // &fmc_alias_cert_redacted_der, // ) // .unwrap(); assert_eq!( fmc_alias_cert_redacted_txt.as_str(), get_rom_test_params().fmc_alias_cert_redacted_txt ); assert_eq!( fmc_alias_cert_redacted_der, get_rom_test_params().fmc_alias_cert_redacted_der ); } // Get FMC Alias CSR so we can verify it let fmc_alias_csr_resp = match algorithm_type { AlgorithmType::Ecc384 => hw .mailbox_execute_req(GetFmcAliasEccCsrReq::default()) .unwrap(), AlgorithmType::Mldsa87 => hw .mailbox_execute_req(GetFmcAliasMldsaCsrReq::default()) .unwrap(), }; // Extract the CSR from the response let fmc_alias_csr_der = fmc_alias_csr_resp.data().unwrap(); let fmc_alias_csr = openssl::x509::X509Req::from_der(fmc_alias_csr_der).unwrap(); println!( "fmc-alias csr: {}", String::from_utf8_lossy(&fmc_alias_csr.to_text().unwrap()) ); // Validate TCB info let dice_tcb_info = DiceTcbInfo::find_multiple_in_csr(fmc_alias_csr_der).unwrap(); // Use the same expected TCB info from FMC Alias cert assert_eq!(dice_tcb_info, fmc_expected_tcb_info); // Use the same expected public key from FMC Alias cert match algorithm_type { AlgorithmType::Ecc384 => { assert!(expected_fmc_alias_key .derive_public_key() .public_eq(&fmc_alias_csr.public_key().unwrap())); } AlgorithmType::Mldsa87 => { assert!(expected_fmc_alias_key .derive_mldsa_public_key() .public_eq(&fmc_alias_csr.public_key().unwrap())); } } assert!( fmc_alias_csr.verify(&fmc_alias_pubkey).unwrap(), "fmc_alias csr failed to validate with ldev pubkey" ); // Validate the fmc-alias CSR fields that are redacted in the testdata because they can change: match algorithm_type { AlgorithmType::Ecc384 => { assert_eq!( &fmc_alias_csr .subject_name() .entries_by_nid(Nid::SERIALNUMBER) .unwrap_single() .data() .as_utf8() .unwrap()[..], derive::ecc_serial_number_str(&fmc_alias_pubkey) ); } AlgorithmType::Mldsa87 => { assert_eq!( &fmc_alias_csr .subject_name() .entries_by_nid(Nid::SERIALNUMBER) .unwrap_single() .data() .as_utf8() .unwrap()[..], derive::mldsa_serial_number_str(&fmc_alias_pubkey) ); } } if *algorithm_type == AlgorithmType::Ecc384 { // When comparing fmc-alias CSR golden-data, redact fields that will change let fmc_alias_csr_redacted_der = redact_csr(fmc_alias_csr_der); let fmc_alias_csr_redacted = openssl::x509::X509Req::from_der(&fmc_alias_csr_redacted_der).unwrap(); let fmc_alias_csr_redacted_txt = String::from_utf8(fmc_alias_csr_redacted.to_text().unwrap()).unwrap(); // To update the CSR testdata: // std::fs::write( // "tests/caliptra_integration_tests/smoke_testdata/fmc_alias_csr_redacted.txt", // &fmc_alias_csr_redacted_txt, // ) // .unwrap(); // std::fs::write( // "tests/caliptra_integration_tests/smoke_testdata/fmc_alias_csr_redacted.der", // &fmc_alias_csr_redacted_der, // ) // .unwrap(); assert_eq!( fmc_alias_csr_redacted_txt.as_str(), include_str!("smoke_testdata/fmc_alias_csr_redacted.txt") ); assert_eq!( fmc_alias_csr_redacted_der, include_bytes!("smoke_testdata/fmc_alias_csr_redacted.der") ); } // Get the RT Alias Cert so we can verify it let rt_alias_cert_resp = match algorithm_type { AlgorithmType::Ecc384 => hw .mailbox_execute_req(GetRtAliasEcc384CertReq::default()) .unwrap(), AlgorithmType::Mldsa87 => hw .mailbox_execute_req(GetRtAliasMlDsa87CertReq::default()) .unwrap(), }; // Extract the certificate from the response let rt_alias_cert_der = rt_alias_cert_resp.data().unwrap(); let rt_alias_cert = openssl::x509::X509::from_der(rt_alias_cert_der).unwrap(); let rt_alias_cert_txt = String::from_utf8(rt_alias_cert.to_text().unwrap()).unwrap(); println!( "Manifest Runtime digest is {:02x?}", image.manifest.runtime.digest.as_bytes() ); let expected_rt_alias_key = RtAliasKey::derive( &PcrRtCurrentInput { runtime_digest: image.manifest.runtime.digest, manifest: image.manifest, }, &expected_fmc_alias_key, ); // Check that the rt-alias key has the rt measurements input above mixed into it // If a firmware change causes this assertion to fail, it is likely that the // logic in the FMC that derives the CDI. Ensure this is intentional, and // then make the same change to caliptra_test::RtAliasKey::derive(). match algorithm_type { AlgorithmType::Ecc384 => { assert!(expected_rt_alias_key
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/caliptra_integration_tests/main.rs
test/tests/caliptra_integration_tests/main.rs
// Licensed under the Apache-2.0 license mod fake_collateral_boot_test; mod jtag_test; mod smoke_test; mod test_code_coverage; mod warm_reset;
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/caliptra_integration_tests/jtag_test.rs
test/tests/caliptra_integration_tests/jtag_test.rs
// Licensed under the Apache-2.0 license use caliptra_builder::{firmware, get_elf_path, ImageOptions}; use caliptra_api_types::DeviceLifecycle; use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams, SecurityState}; use caliptra_test::image_pk_desc_hash; use std::io::{BufRead, BufReader, Write}; use std::process::{ChildStdin, Command, Stdio}; #[derive(PartialEq, Debug)] enum RegAccess { Invalid, RO, RW, } fn gdb_mem_test<R>( stdin: &mut ChildStdin, stdout: &mut BufReader<R>, addr: u32, size: u8, access_type: RegAccess, ) where R: std::io::Read, { stdin .write_all(format!("mem_access_test 0x{:x} {}\n", addr, size).as_bytes()) .expect("Failed to write to stdin"); let mut output = String::new(); loop { stdout.read_line(&mut output).unwrap(); if output.contains("Done") || output.contains("Cannot access memory at address") { break; } } let actual_access_type = if output.contains("Write Accepted") { RegAccess::RW } else if output.contains("Read Accepted") { RegAccess::RO } else { RegAccess::Invalid }; assert_eq!( actual_access_type, access_type, "Addr: 0x{:08x} Size: {:} Log:\n{}", addr, size, output ); // Openocd's GDB server ACKs 8 byte writes immediatelly for a speedup on large transfers. This has a side // effect of causing the next successful write to erroneously report a failure. Perform writes to a known // writable address until it stops reporting failures. if size == 8 && actual_access_type != RegAccess::RW { let mut output = String::new(); loop { stdin .write_all("recover\n".as_bytes()) .expect("Failed to write to stdin"); stdout.read_line(&mut output).unwrap(); if output.contains("Recovered") { break; } } } } //TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070 #[test] #[cfg(not(feature = "fpga_realtime"))] fn gdb_test() { #![cfg_attr(not(feature = "fpga_realtime"), ignore)] let security_state = *SecurityState::default() .set_debug_locked(false) .set_device_lifecycle(DeviceLifecycle::Production); 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, &if cfg!(feature = "fpga_subsystem") { firmware::APP_WITH_UART_FPGA } else { firmware::APP_WITH_UART }, ImageOptions { fw_svn: 9, ..Default::default() }, ) .unwrap(); let (vendor_pk_desc_hash, owner_pk_hash) = image_pk_desc_hash(&image.manifest); let fuses = Fuses { vendor_pk_hash: vendor_pk_desc_hash, owner_pk_hash, fw_svn: [0x7F, 0, 0, 0], ..Default::default() }; let mut hw = caliptra_hw_model::new( InitParams { fuses, rom: &rom, security_state, ..Default::default() }, BootParams { fw_image: Some(&image.to_bytes().unwrap()), ..Default::default() }, ) .unwrap(); hw.step(); hw.step_until_output_contains("[rt] RT listening for mailbox commands...\n") .unwrap(); #[cfg(feature = "fpga_realtime")] hw.launch_openocd().unwrap(); let elf_path = get_elf_path(&if cfg!(feature = "fpga_subsystem") { firmware::APP_WITH_UART_FPGA } else { firmware::APP_WITH_UART }) .unwrap(); let mut gdb = Command::new("gdb-multiarch") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .arg(elf_path) .spawn() .unwrap(); gdb.wait().unwrap(); let mut stdin = gdb.stdin.take().expect("Failed to open stdin"); let mut stderr = BufReader::new(gdb.stderr.as_mut().unwrap()); stdin .write_all(include_str!("smoke_testdata/gdb_script.txt").as_bytes()) .expect("Failed to write to stdin"); loop { let mut output = String::new(); stderr.read_line(&mut output).unwrap(); if output.contains("GDB Launched") { break; } } // Start of ROM gdb_mem_test(&mut stdin, &mut stderr, 0x00000000, 1, RegAccess::RO); gdb_mem_test(&mut stdin, &mut stderr, 0x00000000, 2, RegAccess::RO); gdb_mem_test(&mut stdin, &mut stderr, 0x00000000, 4, RegAccess::RO); gdb_mem_test(&mut stdin, &mut stderr, 0x00000000, 8, RegAccess::RO); // End of ROM gdb_mem_test(&mut stdin, &mut stderr, 0x0000BFFF, 1, RegAccess::RO); gdb_mem_test(&mut stdin, &mut stderr, 0x0000BFFE, 2, RegAccess::RO); gdb_mem_test(&mut stdin, &mut stderr, 0x0000BFFC, 4, RegAccess::RO); gdb_mem_test(&mut stdin, &mut stderr, 0x0000BFF8, 8, RegAccess::RO); // Start of ICCM gdb_mem_test(&mut stdin, &mut stderr, 0x40000000, 1, RegAccess::Invalid); gdb_mem_test(&mut stdin, &mut stderr, 0x40000000, 2, RegAccess::Invalid); gdb_mem_test(&mut stdin, &mut stderr, 0x40000000, 4, RegAccess::RW); gdb_mem_test(&mut stdin, &mut stderr, 0x40000000, 8, RegAccess::RO); // End of ICCM gdb_mem_test(&mut stdin, &mut stderr, 0x4001FFFF, 1, RegAccess::Invalid); gdb_mem_test(&mut stdin, &mut stderr, 0x4001FFFE, 2, RegAccess::Invalid); gdb_mem_test(&mut stdin, &mut stderr, 0x4001FFFC, 4, RegAccess::RW); gdb_mem_test(&mut stdin, &mut stderr, 0x4001FFF8, 8, RegAccess::RO); // Start of DCCM gdb_mem_test(&mut stdin, &mut stderr, 0x50000000, 1, RegAccess::RW); gdb_mem_test(&mut stdin, &mut stderr, 0x50000000, 2, RegAccess::RW); gdb_mem_test(&mut stdin, &mut stderr, 0x50000000, 4, RegAccess::RW); gdb_mem_test(&mut stdin, &mut stderr, 0x50000000, 8, RegAccess::RW); // End of DCCM gdb_mem_test(&mut stdin, &mut stderr, 0x5001FFFF, 1, RegAccess::RW); gdb_mem_test(&mut stdin, &mut stderr, 0x5001FFFE, 2, RegAccess::RW); gdb_mem_test(&mut stdin, &mut stderr, 0x5001FFFC, 4, RegAccess::RW); gdb_mem_test(&mut stdin, &mut stderr, 0x5001FFF8, 8, RegAccess::RW); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/fips_test_suite/services.rs
test/tests/fips_test_suite/services.rs
// Licensed under the Apache-2.0 license use crate::common; use caliptra_api::SocManager; use caliptra_auth_man_gen::default_test_manifest::{default_test_soc_manifest, DEFAULT_MCU_FW}; use caliptra_builder::firmware::{ APP_WITH_UART_FIPS_TEST_HOOKS, APP_WITH_UART_FIPS_TEST_HOOKS_FPGA, FMC_WITH_UART, }; use caliptra_builder::ImageOptions; use caliptra_common::fips::FipsVersionCmd; use caliptra_common::mailbox_api::*; use caliptra_drivers::CaliptraError; use caliptra_drivers::FipsTestHook; use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams, ModelError}; use caliptra_image_crypto::OsslCrypto as Crypto; use caliptra_image_types::FwVerificationPqcKeyType; use caliptra_image_types::ImageManifest; use common::*; use dpe::{commands::*, context::ContextHandle, response::Response, DPE_PROFILE}; use openssl::sha::sha384; use zerocopy::{FromBytes, IntoBytes}; pub fn exec_cmd_version<T: HwModel>(hw: &mut T, fmc_version: u16, app_version: u32) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::VERSION), &[]), }; let version_resp = mbx_send_and_check_resp_hdr::<_, FipsVersionResp>( hw, u32::from(CommandId::VERSION), payload.as_bytes(), ) .unwrap(); // Verify command-specific response data assert_eq!(version_resp.mode, FipsVersionCmd::MODE); let fw_version_0_expected = ((fmc_version as u32) << 16) | (RomExpVals::get().rom_version as u32); assert_eq!( version_resp.fips_rev, [ HwExpVals::get().hw_revision, fw_version_0_expected, app_version ] ); let name = &version_resp.name[..]; assert_eq!(name, FipsVersionCmd::NAME.as_bytes()); } pub fn exec_cmd_self_test_start<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::SELF_TEST_START), &[], ), }; mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( hw, u32::from(CommandId::SELF_TEST_START), payload.as_bytes(), ) .unwrap(); } pub fn exec_cmd_self_test_get_results<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::SELF_TEST_GET_RESULTS), &[], ), }; // Attempt get_results in a loop until we get a response loop { // Get self test results match mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( hw, u32::from(CommandId::SELF_TEST_GET_RESULTS), payload.as_bytes(), ) { // Nothing extra to do once we see success Ok(_resp) => break, Err(ModelError::MailboxCmdFailed(code)) => { if code != u32::from(CaliptraError::RUNTIME_SELF_TEST_NOT_STARTED) { panic!("Unexpected caliptra error code {:#x}", code); } } Err(ModelError::UnableToLockMailbox) => (), Err(e) => panic!("Unexpected error {}", e), } // Give FW time to run let mut cycle_count = 10000; hw.step_until(|_| -> bool { cycle_count -= 1; cycle_count == 0 }); } } pub fn exec_cmd_get_idev_cert<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::GET_IDEV_ECC384_CERT), &[], ), }; let cert_resp = mbx_send_and_check_resp_hdr::<_, GetIdevCertResp>( hw, u32::from(CommandId::GET_IDEV_ECC384_CERT), payload.as_bytes(), ) .unwrap(); // Make sure we got some cert data (not verifying contents) assert!(cert_resp.data_size > 0); // Verify we have something in the data field assert!(contains_some_data( &cert_resp.data[..cert_resp.data_size as usize] )); } pub fn exec_cmd_get_idev_info<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::GET_IDEV_ECC384_INFO), &[], ), }; let resp = mbx_send_and_check_resp_hdr::<_, GetIdevEcc384InfoResp>( hw, u32::from(CommandId::GET_IDEV_ECC384_INFO), payload.as_bytes(), ) .unwrap(); // Verify we have something in the data fields assert!(contains_some_data(&resp.idev_pub_x)); assert!(contains_some_data(&resp.idev_pub_y)); } pub fn exec_cmd_populate_idev_cert<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::POPULATE_IDEV_ECC384_CERT), &[], ), }; mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( hw, u32::from(CommandId::POPULATE_IDEV_ECC384_CERT), payload.as_bytes(), ) .unwrap(); } pub fn exec_cmd_get_ldev_cert<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::GET_LDEV_ECC384_CERT), &[], ), }; let ldev_cert_resp = mbx_send_and_check_resp_hdr::<_, GetLdevCertResp>( hw, u32::from(CommandId::GET_LDEV_ECC384_CERT), payload.as_bytes(), ) .unwrap(); // Make sure we got some cert data (not verifying contents) assert!(ldev_cert_resp.data_size > 0); // Verify we have something in the data field assert!(contains_some_data( &ldev_cert_resp.data[..ldev_cert_resp.data_size as usize] )); } pub fn exec_cmd_get_fmc_cert<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::GET_FMC_ALIAS_ECC384_CERT), &[], ), }; let cert_resp = mbx_send_and_check_resp_hdr::<_, GetFmcAliasEcc384CertResp>( hw, u32::from(CommandId::GET_FMC_ALIAS_ECC384_CERT), payload.as_bytes(), ) .unwrap(); // Make sure we got some cert data (not verifying contents) assert!(cert_resp.data_size > 0); // Verify we have something in the data field assert!(contains_some_data( &cert_resp.data[..cert_resp.data_size as usize] )); } pub fn exec_cmd_get_rt_cert<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::GET_RT_ALIAS_ECC384_CERT), &[], ), }; let cert_resp = mbx_send_and_check_resp_hdr::<_, GetRtAliasCertResp>( hw, u32::from(CommandId::GET_RT_ALIAS_ECC384_CERT), payload.as_bytes(), ) .unwrap(); // Make sure we got some cert data (not verifying contents) assert!(cert_resp.data_size > 0); // Verify we have something in the data field assert!(contains_some_data( &cert_resp.data[..cert_resp.data_size as usize] )); } pub fn exec_cmd_capabilities<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::CAPABILITIES), &[]), }; let capabilities_resp = mbx_send_and_check_resp_hdr::<_, CapabilitiesResp>( hw, u32::from(CommandId::CAPABILITIES), payload.as_bytes(), ) .unwrap(); // Verify command-specific response data assert_eq!( capabilities_resp.capabilities, RomExpVals::get().capabilities ); } pub fn exec_cmd_ecdsa_verify<T: HwModel>(hw: &mut T) { // 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); let mut payload = MailboxReq::EcdsaVerify(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, }); payload.populate_chksum().unwrap(); mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( hw, u32::from(CommandId::ECDSA384_SIGNATURE_VERIFY), payload.as_bytes().unwrap(), ) .unwrap(); } pub fn exec_cmd_stash_measurement<T: HwModel>(hw: &mut T) { let payload = StashMeasurementReq { hdr: MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::STASH_MEASUREMENT), &[], ), }, ..Default::default() }; let stash_measurement_resp = mbx_send_and_check_resp_hdr::<_, StashMeasurementResp>( hw, u32::from(CommandId::STASH_MEASUREMENT), payload.as_bytes(), ) .unwrap(); // Verify command-specific response data assert_eq!(stash_measurement_resp.dpe_result, 0); } pub fn exec_fw_info<T: HwModel>(hw: &mut T, fw_image: &[u8]) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::FW_INFO), &[]), }; let fw_info_resp = mbx_send_and_check_resp_hdr::<_, FwInfoResp>( hw, u32::from(CommandId::FW_INFO), payload.as_bytes(), ) .unwrap(); let (manifest, _) = ImageManifest::read_from_prefix(fw_image).unwrap(); // Verify command-specific response data assert_eq!(fw_info_resp.fmc_revision, manifest.fmc.revision); assert_eq!(fw_info_resp.runtime_revision, manifest.runtime.revision); assert!(contains_some_data(&fw_info_resp.rom_revision)); assert!(contains_some_data(&fw_info_resp.rom_sha256_digest)); assert!(contains_some_data(&fw_info_resp.fmc_sha384_digest)); assert!(contains_some_data(&fw_info_resp.runtime_sha384_digest)); } pub fn exec_dpe_tag_tci<T: HwModel>(hw: &mut T) { let mut payload = MailboxReq::TagTci(TagTciReq { hdr: MailboxReqHeader { chksum: 0 }, handle: [0u8; 16], tag: 1, }); payload.populate_chksum().unwrap(); mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( hw, u32::from(CommandId::DPE_TAG_TCI), payload.as_bytes().unwrap(), ) .unwrap(); } pub fn exec_get_taged_tci<T: HwModel>(hw: &mut T) { let mut payload = MailboxReq::GetTaggedTci(GetTaggedTciReq { hdr: MailboxReqHeader { chksum: 0 }, tag: 1, }); payload.populate_chksum().unwrap(); let resp = mbx_send_and_check_resp_hdr::<_, GetTaggedTciResp>( hw, u32::from(CommandId::DPE_GET_TAGGED_TCI), payload.as_bytes().unwrap(), ) .unwrap(); // Verify command-specific response data assert!(contains_some_data(&resp.tci_cumulative)); assert_eq!(resp.tci_current, [0u8; 48]); } pub fn exec_incr_pcr_rst_counter<T: HwModel>(hw: &mut T) { let mut payload = MailboxReq::IncrementPcrResetCounter(IncrementPcrResetCounterReq { hdr: MailboxReqHeader { chksum: 0 }, index: 1, }); payload.populate_chksum().unwrap(); mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( hw, u32::from(CommandId::INCREMENT_PCR_RESET_COUNTER), payload.as_bytes().unwrap(), ) .unwrap(); } pub fn exec_cmd_quote_pcrs_ecc384<T: HwModel>(hw: &mut T) { let mut payload = MailboxReq::QuotePcrsEcc384(QuotePcrsEcc384Req { hdr: MailboxReqHeader { chksum: 0 }, nonce: [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, ], }); payload.populate_chksum().unwrap(); let resp = mbx_send_and_check_resp_hdr::<_, QuotePcrsEcc384Resp>( hw, u32::from(CommandId::QUOTE_PCRS_ECC384), payload.as_bytes().unwrap(), ) .unwrap(); // Verify command-specific response data assert!(contains_some_data(&resp.pcrs)); assert!(contains_some_data(&resp.nonce)); assert!(contains_some_data(&resp.digest)); assert!(contains_some_data(&resp.reset_ctrs)); assert!(contains_some_data(&resp.signature_r)); assert!(contains_some_data(&resp.signature_s)); } pub fn exec_cmd_quote_pcrs_mldsa87<T: HwModel>(hw: &mut T) { let mut payload = MailboxReq::QuotePcrsMldsa87(QuotePcrsMldsa87Req { hdr: MailboxReqHeader { chksum: 0 }, nonce: [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, ], }); payload.populate_chksum().unwrap(); let resp = mbx_send_and_check_resp_hdr::<_, QuotePcrsMldsa87Resp>( hw, u32::from(CommandId::QUOTE_PCRS_MLDSA87), payload.as_bytes().unwrap(), ) .unwrap(); // Verify command-specific response data assert!(contains_some_data(&resp.pcrs)); assert!(contains_some_data(&resp.nonce)); assert!(contains_some_data(&resp.digest)); assert!(contains_some_data(&resp.reset_ctrs)); assert!(contains_some_data(&resp.signature)); } pub fn exec_cmd_extend_pcr<T: HwModel>(hw: &mut T) { let mut payload = MailboxReq::ExtendPcr(ExtendPcrReq { hdr: MailboxReqHeader { chksum: 0 }, pcr_idx: 4, data: [0u8; 48], }); payload.populate_chksum().unwrap(); mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( hw, u32::from(CommandId::EXTEND_PCR), payload.as_bytes().unwrap(), ) .unwrap(); } pub fn exec_dpe_get_profile<T: HwModel>(hw: &mut T) { let resp = execute_dpe_cmd(hw, &mut Command::GetProfile); let Response::GetProfile(get_profile_resp) = resp else { panic!("Wrong response type!"); }; assert_eq!(get_profile_resp.resp_hdr.profile, DPE_PROFILE); } pub fn exec_dpe_init_ctx<T: HwModel>(hw: &mut T) { let resp = execute_dpe_cmd(hw, &mut Command::InitCtx(&InitCtxCmd::new_simulation())); let Response::InitCtx(init_ctx_resp) = resp else { panic!("Wrong response type!"); }; assert!(contains_some_data(&init_ctx_resp.handle.0)); } pub fn exec_dpe_derive_ctx<T: HwModel>(hw: &mut T) { let derive_context_cmd = DeriveContextCmd { handle: ContextHandle::default(), data: [0u8; 48], flags: DeriveContextFlags::RETAIN_PARENT_CONTEXT | DeriveContextFlags::CHANGE_LOCALITY, tci_type: 0, target_locality: 0, svn: 0, }; let resp = execute_dpe_cmd(hw, &mut Command::DeriveContext(&derive_context_cmd)); let Response::DeriveContext(derive_ctx_resp) = resp else { panic!("Wrong response type!"); }; assert!(contains_some_data(&derive_ctx_resp.handle.0)); } pub fn exec_dpe_certify_key<T: HwModel>(hw: &mut T) { pub const TEST_LABEL: [u8; 48] = [ 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, ]; let certify_key_cmd = CertifyKeyCmd { handle: ContextHandle::default(), label: TEST_LABEL, flags: CertifyKeyFlags::empty(), format: CertifyKeyCmd::FORMAT_CSR, }; let resp = execute_dpe_cmd(hw, &mut Command::CertifyKey(&certify_key_cmd)); let Response::CertifyKey(certify_key_resp) = resp else { panic!("Wrong response type!"); }; assert_eq!( certify_key_resp.new_context_handle.0, [0u8; ContextHandle::SIZE] ); assert!(contains_some_data(&certify_key_resp.derived_pubkey_x)); assert!(contains_some_data(&certify_key_resp.derived_pubkey_y)); assert_ne!(0, certify_key_resp.cert_size); assert!(contains_some_data(&certify_key_resp.cert)); } pub fn exec_dpe_sign<T: HwModel>(hw: &mut T) { pub const TEST_LABEL: [u8; 48] = [ 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, ]; pub const TEST_DIGEST: [u8; 48] = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, ]; let sign_cmd = SignCmd { handle: ContextHandle::default(), label: TEST_LABEL, flags: SignFlags::empty(), digest: TEST_DIGEST, }; let resp = execute_dpe_cmd(hw, &mut Command::Sign(&sign_cmd)); let Response::Sign(sign_resp) = resp else { panic!("Wrong response type!"); }; assert!(contains_some_data(&sign_resp.sig_r)); assert!(contains_some_data(&sign_resp.sig_s)); } pub fn exec_rotate_ctx<T: HwModel>(hw: &mut T) { let rotate_ctx_cmd = RotateCtxCmd { handle: ContextHandle::default(), flags: RotateCtxFlags::empty(), }; let resp = execute_dpe_cmd(hw, &mut Command::RotateCtx(&rotate_ctx_cmd)); let Response::RotateCtx(rotate_ctx_resp) = resp else { panic!("Wrong response type!"); }; assert!(contains_some_data(&rotate_ctx_resp.handle.0)); } pub fn exec_get_cert_chain<T: HwModel>(hw: &mut T) { let get_cert_chain_cmd = GetCertificateChainCmd { offset: 0, size: 2048, }; let resp = execute_dpe_cmd(hw, &mut Command::GetCertificateChain(&get_cert_chain_cmd)); let Response::GetCertificateChain(get_cert_chain_resp) = resp else { panic!("Wrong response type!"); }; assert_ne!(0, get_cert_chain_resp.certificate_size); assert!(contains_some_data(&get_cert_chain_resp.certificate_chain)); } pub fn exec_destroy_ctx<T: HwModel>(hw: &mut T) { let destroy_ctx_cmd = DestroyCtxCmd { handle: ContextHandle::default(), }; execute_dpe_cmd(hw, &mut Command::DestroyCtx(&destroy_ctx_cmd)); } pub fn exec_cmd_disable_attestation<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::DISABLE_ATTESTATION), &[], ), }; mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( hw, u32::from(CommandId::DISABLE_ATTESTATION), payload.as_bytes(), ) .unwrap(); } pub fn exec_cmd_shutdown<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::SHUTDOWN), &[]), }; mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( hw, u32::from(CommandId::SHUTDOWN), payload.as_bytes(), ) .unwrap(); } #[test] pub fn check_version_rom() { let mut hw = fips_test_init_to_rom(None, None); // FMC and FW version should both be 0 before loading exec_cmd_version(&mut hw, 0x0, 0x0); } #[test] pub fn check_version_rt() { let mut hw = fips_test_init_to_rt(None, None); exec_cmd_version( &mut hw, RtExpVals::get().fmc_version, RtExpVals::get().fw_version, ); } #[test] pub fn version_info_update() { let mut hw = fips_test_init_to_rom(None, None); let pre_load_fmc_version = 0x0; let pre_load_fw_version = 0x0; let fmc_version = RtExpVals::get().fmc_version; let fw_version = RtExpVals::get().fw_version; // Prove the expected versions are different assert!(fmc_version != 0x0); assert!(fw_version != 0x0); // Check pre-load versions exec_cmd_version(&mut hw, pre_load_fmc_version, pre_load_fw_version); // Load the FW let fw_image = fips_fw_image(); if hw.subsystem_mode() { hw.upload_firmware_rri( &fw_image, Some( default_test_soc_manifest( &DEFAULT_MCU_FW, FwVerificationPqcKeyType::MLDSA, 1, Crypto::default(), ) .as_bytes(), ), Some(&DEFAULT_MCU_FW), ) .unwrap(); hw.step_until(|m| m.soc_ifc().cptra_flow_status().read().ready_for_runtime()); } else { hw.upload_firmware(&fw_image).unwrap() } // FMC and FW version should be populated after loading FW exec_cmd_version(&mut hw, fmc_version, fw_version); } #[test] pub fn execute_all_services_rom() { let mut hw = fips_test_init_to_rom(None, None); // VERSION // FMC and FW version should both be 0 before loading exec_cmd_version(&mut hw, 0x0, 0x0); // SELF TEST START exec_cmd_self_test_start(&mut hw); // SELF TEST GET RESULTS exec_cmd_self_test_get_results(&mut hw); // CAPABILITIES exec_cmd_capabilities(&mut hw); // STASH MEASUREMENT exec_cmd_stash_measurement(&mut hw); // SHUTDOWN // (Do this last) exec_cmd_shutdown(&mut hw); } #[test] pub fn execute_all_services_rt() { let fw_image = fips_fw_image(); let soc_manifest = default_test_soc_manifest( &DEFAULT_MCU_FW, FwVerificationPqcKeyType::MLDSA, 1, Crypto::default(), ); let mut hw = fips_test_init_to_rt( None, Some(BootParams { fw_image: Some(&fw_image), soc_manifest: Some(soc_manifest.as_bytes()), mcu_fw_image: Some(&DEFAULT_MCU_FW), ..Default::default() }), ); // VERSION // FMC and FW version should both be 0 before loading exec_cmd_version( &mut hw, RtExpVals::get().fmc_version, RtExpVals::get().fw_version, ); // SELF TEST START exec_cmd_self_test_start(&mut hw); // SELF TEST GET RESULTS exec_cmd_self_test_get_results(&mut hw); // GET_IDEV_CERT exec_cmd_get_idev_cert(&mut hw); // GET_IDEV_INFO exec_cmd_get_idev_info(&mut hw); // POPULATE_IDEV_CERT exec_cmd_populate_idev_cert(&mut hw); // GET_LDEV_CERT exec_cmd_get_ldev_cert(&mut hw); // GET_FMC_ALIAS_CERT exec_cmd_get_fmc_cert(&mut hw); // GET_RT_ALIAS_CERT exec_cmd_get_rt_cert(&mut hw); // ECDSA384_VERIFY // TODO: add LMS verify // TODO: add MLDSA verify exec_cmd_ecdsa_verify(&mut hw); // STASH_MEASUREMENT exec_cmd_stash_measurement(&mut hw); // FW_INFO exec_fw_info(&mut hw, &fw_image); // DPE_TAG_TCI exec_dpe_tag_tci(&mut hw); // DPE_GET_TAGGED_TCI exec_get_taged_tci(&mut hw); // INCREMENT_PCR_RESET_COUNTER exec_incr_pcr_rst_counter(&mut hw); // QUOTE_PCRS_ECC384 exec_cmd_quote_pcrs_ecc384(&mut hw); // QUOTE_PCRS_MLDSA87 exec_cmd_quote_pcrs_mldsa87(&mut hw); // EXTEND_PCR exec_cmd_extend_pcr(&mut hw); // INVOKE_DPE exec_dpe_get_profile(&mut hw); exec_dpe_init_ctx(&mut hw); exec_dpe_derive_ctx(&mut hw); exec_dpe_certify_key(&mut hw); exec_dpe_sign(&mut hw); exec_rotate_ctx(&mut hw); exec_get_cert_chain(&mut hw); exec_destroy_ctx(&mut hw); // (Do these last) // DISABLE_ATTESTATION exec_cmd_disable_attestation(&mut hw); // SHUTDOWN exec_cmd_shutdown(&mut hw); } #[test] pub fn zeroize_halt_check_no_output() { for pqc_key_type in PQC_KEY_TYPE.iter() { let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; // Build FW with test hooks and init to runtime let fw_image = caliptra_builder::build_and_sign_image( &FMC_WITH_UART, &if cfg!(feature = "fpga_subsystem") { APP_WITH_UART_FIPS_TEST_HOOKS_FPGA } else { APP_WITH_UART_FIPS_TEST_HOOKS }, image_options, ) .unwrap() .to_bytes() .unwrap(); let fuses = Fuses { fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; let soc_manifest = default_test_soc_manifest(&DEFAULT_MCU_FW, *pqc_key_type, 1, Crypto::default()); let mut hw = fips_test_init_to_rt( Some(InitParams { fuses, ..Default::default() }), Some(BootParams { fw_image: Some(&fw_image), initial_dbg_manuf_service_reg: (FipsTestHook::HALT_SHUTDOWN_RT as u32) << HOOK_CODE_OFFSET, soc_manifest: Some(soc_manifest.as_bytes()), mcu_fw_image: Some(&DEFAULT_MCU_FW), ..Default::default() }), ); // Send the shutdown command (do not wait for response) let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::SHUTDOWN), &[]), }; hw.start_mailbox_execute(u32::from(CommandId::SHUTDOWN), payload.as_bytes()) .unwrap(); // Wait for ACK that ROM reached halt point hook_wait_for_complete(&mut hw); // Check output is inhibited verify_output_inhibited(&mut hw); } } #[test] pub fn fips_self_test_rom() { let mut hw = fips_test_init_to_rom(None, None); // SELF TEST START exec_cmd_self_test_start(&mut hw); // SELF TEST GET RESULTS exec_cmd_self_test_get_results(&mut hw); } #[test] pub fn fips_self_test_rt() { let mut hw = fips_test_init_to_rt(None, None); // SELF TEST START exec_cmd_self_test_start(&mut hw); // SELF TEST GET RESULTS exec_cmd_self_test_get_results(&mut hw); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/fips_test_suite/jtag_locked.rs
test/tests/fips_test_suite/jtag_locked.rs
// Licensed under the Apache-2.0 license use crate::common::fips_test_init_to_rom; use caliptra_hw_model::OpenOcdError; use caliptra_hw_model::{InitParams, SecurityState}; use caliptra_hw_model_types::DeviceLifecycle; fn check_jtag_accessible( rom: &[u8], debug_locked: bool, device_lifecycle: DeviceLifecycle, expect_result: Result<(), OpenOcdError>, ) { let security_state = *SecurityState::default() .set_debug_locked(debug_locked) .set_device_lifecycle(device_lifecycle); let mut hw = fips_test_init_to_rom( Some(InitParams { rom, security_state, ..Default::default() }), None, ); #[cfg(feature = "fpga_realtime")] assert_eq!( expect_result, hw.launch_openocd(), " for {device_lifecycle:?}:{debug_locked}" ); } //TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070 #[test] #[cfg(not(feature = "fpga_realtime"))] fn jtag_locked() { #![cfg_attr(not(feature = "fpga_realtime"), ignore)] let rom = caliptra_builder::rom_for_fw_integration_tests_fpga(cfg!(feature = "fpga_subsystem")) .unwrap(); // When debug is locked JTAG is only accesisble in Manufacturing mode. check_jtag_accessible( &rom, true, DeviceLifecycle::Unprovisioned, Err(OpenOcdError::CaliptraNotAccessible), ); check_jtag_accessible( &rom, true, DeviceLifecycle::Manufacturing, Err(OpenOcdError::VeerNotAccessible), ); check_jtag_accessible( &rom, true, DeviceLifecycle::Reserved2, Err(OpenOcdError::CaliptraNotAccessible), ); check_jtag_accessible( &rom, true, DeviceLifecycle::Production, Err(OpenOcdError::CaliptraNotAccessible), ); // When debug not locked JTAG is accessible in any mode. check_jtag_accessible(&rom, false, DeviceLifecycle::Unprovisioned, Ok(())); check_jtag_accessible(&rom, false, DeviceLifecycle::Manufacturing, Ok(())); check_jtag_accessible(&rom, false, DeviceLifecycle::Reserved2, Ok(())); check_jtag_accessible(&rom, false, DeviceLifecycle::Production, Ok(())); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/fips_test_suite/fw_load.rs
test/tests/fips_test_suite/fw_load.rs
// Licensed under the Apache-2.0 license use crate::common; use caliptra_api::SocManager; use caliptra_auth_man_gen::default_test_manifest::{default_test_soc_manifest, DEFAULT_MCU_FW}; use caliptra_builder::firmware::{ APP_WITH_UART, APP_WITH_UART_FPGA, FMC_FAKE_WITH_UART, FMC_WITH_UART, ROM_WITH_FIPS_TEST_HOOKS, ROM_WITH_FIPS_TEST_HOOKS_FPGA, }; use caliptra_builder::ImageOptions; use caliptra_common::memory_layout::{ICCM_ORG, ICCM_SIZE}; use caliptra_drivers::CaliptraError; use caliptra_drivers::FipsTestHook; use caliptra_hw_model::{ BootParams, DefaultHwModel, DeviceLifecycle, Fuses, HwModel, InitParams, ModelError, SecurityState, U4, }; use caliptra_image_crypto::OsslCrypto as Crypto; use caliptra_image_fake_keys::{VENDOR_CONFIG_KEY_0, VENDOR_CONFIG_KEY_1}; use caliptra_image_gen::{ImageGenerator, ImageGeneratorConfig, ImageGeneratorVendorConfig}; use caliptra_image_types::{ FwVerificationPqcKeyType, ImageBundle, ImageLmsPublicKey, ImageMldsaPubKey, ImageSignData, MLDSA87_PUB_KEY_WORD_SIZE, SHA384_DIGEST_WORD_SIZE, VENDOR_ECC_MAX_KEY_COUNT, VENDOR_LMS_MAX_KEY_COUNT, VENDOR_MLDSA_MAX_KEY_COUNT, }; use caliptra_test::image_pk_desc_hash; use common::*; use zerocopy::{FromBytes, IntoBytes}; #[allow(dead_code)] #[derive(PartialEq, Eq)] enum HdrDigest { Update, Skip, } #[derive(PartialEq, Eq)] enum TocDigest { Update, Skip, } const PQC_KEY_TYPE: [FwVerificationPqcKeyType; 2] = [ FwVerificationPqcKeyType::MLDSA, FwVerificationPqcKeyType::LMS, ]; pub fn build_fw_image(image_options: ImageOptions) -> ImageBundle { caliptra_builder::build_and_sign_image( &FMC_WITH_UART, &if cfg!(feature = "fpga_subsystem") { APP_WITH_UART_FPGA } else { APP_WITH_UART }, image_options, ) .unwrap() } fn update_manifest(image_bundle: &mut ImageBundle, hdr_digest: HdrDigest, toc_digest: TocDigest) { let pqc_key_type = FwVerificationPqcKeyType::from_u8(image_bundle.manifest.pqc_key_type).unwrap(); let opts = ImageOptions { pqc_key_type, ..Default::default() }; let config = ImageGeneratorConfig { fmc: caliptra_image_elf::ElfExecutable::default(), runtime: caliptra_image_elf::ElfExecutable::default(), vendor_config: opts.vendor_config, owner_config: opts.owner_config, pqc_key_type, fw_svn: 0, }; let gen = ImageGenerator::new(Crypto::default()); // Update TOC digest if toc_digest == TocDigest::Update { image_bundle.manifest.header.toc_digest = gen .toc_digest(&image_bundle.manifest.fmc, &image_bundle.manifest.runtime) .unwrap(); } if hdr_digest == HdrDigest::Update { let vendor_header_digest_384 = gen .vendor_header_digest_384(&image_bundle.manifest.header) .unwrap(); let vendor_header_bytes = gen.vendor_header_bytes(&image_bundle.manifest.header); let vendor_header_digest_holder = ImageSignData { digest_384: &vendor_header_digest_384, mldsa_msg: Some(vendor_header_bytes), }; let owner_header_digest_384 = gen .owner_header_digest_384(&image_bundle.manifest.header) .unwrap(); let owner_header_bytes = image_bundle.manifest.header.as_bytes(); let owner_header_digest_holder = ImageSignData { digest_384: &owner_header_digest_384, mldsa_msg: Some(owner_header_bytes), }; // Update preamble image_bundle.manifest.preamble = gen .gen_preamble( &config, image_bundle.manifest.preamble.vendor_ecc_pub_key_idx, image_bundle.manifest.preamble.vendor_pqc_pub_key_idx, &vendor_header_digest_holder, &owner_header_digest_holder, ) .unwrap(); } } // Get a byte array from an image_bundle without any error checking // Normally, to_bytes will perform some error checking // We need to bypass this for the sake of these tests fn image_to_bytes_no_error_check(image_bundle: &ImageBundle) -> Vec<u8> { let mut image = vec![]; image.extend_from_slice(image_bundle.manifest.as_bytes()); image.extend_from_slice(&image_bundle.fmc); image.extend_from_slice(&image_bundle.runtime); image } // Returns a fuse struct with safe values for boot // (Mainly needed for manufacturing or production security states) fn safe_fuses(fw_image: &ImageBundle) -> Fuses { let gen = ImageGenerator::new(Crypto::default()); let vendor_pubkey_info_digest = gen .vendor_pubkey_info_digest(&fw_image.manifest.preamble) .unwrap(); let owner_pubkey_digest = gen .owner_pubkey_digest(&fw_image.manifest.preamble) .unwrap(); Fuses { vendor_pk_hash: vendor_pubkey_info_digest, owner_pk_hash: owner_pubkey_digest, fuse_pqc_key_type: fw_image.manifest.pqc_key_type as u32, ..Default::default() } } // NOTE: These tests are about the image verification which is contained in ROM. // The version of the FW used in the image bundles within these tests is irrelevant. // Because of this, we are just building the FW so it's easier to modify components // of the image bundle instead of using any pre-existing FW binary fn fw_load_error_flow( fw_image: Option<ImageBundle>, fuses: Option<Fuses>, exp_error_code: u32, pqc_key_type: FwVerificationPqcKeyType, ) { fw_load_error_flow_base( fw_image, None, fuses, None, exp_error_code, None, pqc_key_type, ); } fn fw_load_error_flow_with_test_hooks( fw_image: Option<ImageBundle>, fuses: Option<Fuses>, exp_error_code: u32, test_hook_cmd: u8, pqc_key_type: FwVerificationPqcKeyType, ) { let rom = caliptra_builder::build_firmware_rom(&if cfg!(feature = "fpga_subsystem") { ROM_WITH_FIPS_TEST_HOOKS_FPGA } else { ROM_WITH_FIPS_TEST_HOOKS }) .unwrap(); fw_load_error_flow_base( fw_image, Some(&rom), fuses, None, exp_error_code, Some((test_hook_cmd as u32) << HOOK_CODE_OFFSET), pqc_key_type, ); } fn update_fw_error_flow( fw_image: Option<ImageBundle>, fuses: Option<Fuses>, update_fw_image: Option<ImageBundle>, exp_error_code: u32, pqc_key_type: FwVerificationPqcKeyType, ) { let update_fw_image = update_fw_image.unwrap_or(build_fw_image(ImageOptions::default())); fw_load_error_flow_base( fw_image, None, fuses, Some(update_fw_image), exp_error_code, None, pqc_key_type, ); } fn fw_load_error_flow_base( fw_image: Option<ImageBundle>, rom: Option<&[u8]>, fuses: Option<Fuses>, update_fw_image: Option<ImageBundle>, exp_error_code: u32, initial_dbg_manuf_service_reg: Option<u32>, pqc_key_type: FwVerificationPqcKeyType, ) { // Use defaults if not provided let fuses_default = Fuses { fuse_pqc_key_type: pqc_key_type as u32, ..Default::default() }; let fuses = fuses.unwrap_or(fuses_default); let image_options = ImageOptions { pqc_key_type, ..Default::default() }; let fw_image = fw_image.unwrap_or(build_fw_image(image_options.clone())); let life_cycle = fuses.life_cycle; // Attempt to load the FW let mut hw = fips_test_init_to_rom( Some(InitParams { fuses, security_state: SecurityState::from(life_cycle as u32), rom: rom.unwrap_or_default(), ..Default::default() }), Some(BootParams { initial_dbg_manuf_service_reg: initial_dbg_manuf_service_reg.unwrap_or_default(), ..Default::default() }), ); // Upload initial FW let fw_upload = |hw: &mut DefaultHwModel, image: Vec<u8>| { if hw.subsystem_mode() { hw.upload_firmware_rri( &image, Some( default_test_soc_manifest( &DEFAULT_MCU_FW, pqc_key_type, image_options.fw_svn, Crypto::default(), ) .as_bytes(), ), Some(&DEFAULT_MCU_FW), ) } else { hw.upload_firmware(&image) } }; let mut fw_load_result = fw_upload(&mut hw, image_to_bytes_no_error_check(&fw_image)); // Update the FW if specified match update_fw_image { None => { if hw.subsystem_mode() { hw.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() != 0); assert_eq!(hw.soc_ifc().cptra_fw_error_fatal().read(), exp_error_code); } else { // Verify the correct error was returned from FW load assert_eq!( ModelError::MailboxCmdFailed(exp_error_code), fw_load_result.unwrap_err() ); // Verify we cannot utilize RT FW by sending a message verify_mbox_cmds_fail(&mut hw, exp_error_code); // Verify an undocumented attempt to clear the error fails hw.soc_ifc().cptra_fw_error_fatal().write(|_| 0); hw.soc_ifc().cptra_fw_error_non_fatal().write(|_| 0); verify_mbox_cmds_fail(&mut hw, 0); } let clean_fw_image = build_fw_image(image_options.clone()); let safe_fuses = safe_fuses(&clean_fw_image); // Clear the error with an approved method - restart Caliptra // TODO: Reset to the default fuse state - provided fuses may be intended to cause errors if cfg!(any( feature = "verilator", feature = "fpga_realtime", feature = "fpga_subsystem" )) { hw.set_fuses(safe_fuses); hw.cold_reset(); } else { hw = fips_test_init_model(Some(InitParams { fuses: safe_fuses, ..Default::default() })) } hw.boot(BootParams { ..Default::default() }) .unwrap(); hw.step_until(|m| { m.soc_ifc() .cptra_flow_status() .read() .ready_for_mb_processing() }); // Verify we can load FW (use clean FW) fw_upload(&mut hw, clean_fw_image.to_bytes().unwrap()).unwrap(); } Some(update_image) => { if hw.subsystem_mode() { hw.step_until_output_contains("RT listening for mailbox commands...") .unwrap(); } else { // Verify initial FW load was successful fw_load_result.unwrap(); } // Update FW fw_load_result = hw.upload_firmware(&image_to_bytes_no_error_check(&update_image)); // Verify the correct error was returned from FW load assert_eq!( fw_load_result.unwrap_err(), ModelError::MailboxCmdFailed(exp_error_code) ); // In the update FW case, the error will be non-fatal and fall back to the previous, good FW // Verify we can load FW (use first FW) hw.upload_firmware(&image_to_bytes_no_error_check(&fw_image)) .unwrap(); } } } #[test] fn fw_load_error_manifest_marker_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Corrupt manifest marker fw_image.manifest.marker = 0xDEADBEEF; fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_MARKER_MISMATCH.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_manifest_size_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Change manifest size fw_image.manifest.size -= 1; fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_SIZE_MISMATCH.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_vendor_pub_key_digest_invalid() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Set fuses let fuses = caliptra_hw_model::Fuses { life_cycle: DeviceLifecycle::Manufacturing, vendor_pk_hash: [0u32; 12], fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; fw_load_error_flow( None, Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_INVALID.into(), *pqc_key_type, ); } } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] fn fw_load_error_vendor_pub_key_digest_failure() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Set fuses let fuses = caliptra_hw_model::Fuses { life_cycle: DeviceLifecycle::Manufacturing, vendor_pk_hash: [0xDEADBEEF; 12], fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; fw_load_error_flow_with_test_hooks( None, Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_FAILURE.into(), FipsTestHook::FW_LOAD_VENDOR_PUB_KEY_DIGEST_FAILURE, *pqc_key_type, ); } } #[test] fn fw_load_error_vendor_pub_key_digest_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Set fuses let fuses = caliptra_hw_model::Fuses { life_cycle: DeviceLifecycle::Manufacturing, vendor_pk_hash: [0xDEADBEEF; 12], fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; fw_load_error_flow( None, Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_MISMATCH.into(), *pqc_key_type, ); } } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] fn fw_load_error_owner_pub_key_digest_failure() { for pqc_key_type in PQC_KEY_TYPE.iter() { fw_load_error_flow_with_test_hooks( None, None, CaliptraError::IMAGE_VERIFIER_ERR_OWNER_PUB_KEY_DIGEST_FAILURE.into(), FipsTestHook::FW_LOAD_OWNER_PUB_KEY_DIGEST_FAILURE, *pqc_key_type, ); } } #[test] fn fw_load_error_owner_pub_key_digest_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Set fuses let fuses = caliptra_hw_model::Fuses { owner_pk_hash: [0xDEADBEEF; 12], fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; fw_load_error_flow( None, Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_OWNER_PUB_KEY_DIGEST_MISMATCH.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_vendor_ecc_pub_key_index_out_of_bounds() { for pqc_key_type in PQC_KEY_TYPE.iter() { let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; // Generate image let mut fw_image = build_fw_image(image_options); // Change ECC pub key index to max+1 fw_image.manifest.preamble.vendor_ecc_pub_key_idx = VENDOR_ECC_MAX_KEY_COUNT; fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INDEX_OUT_OF_BOUNDS.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_vendor_ecc_pub_key_revoked() { for pqc_key_type in PQC_KEY_TYPE.iter() { let vendor_config = VENDOR_CONFIG_KEY_1; let image_options = ImageOptions { vendor_config, pqc_key_type: *pqc_key_type, ..Default::default() }; // Set fuses 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, ..Default::default() }; // Generate image let fw_image = build_fw_image(image_options); fw_load_error_flow( Some(fw_image), Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_REVOKED.into(), *pqc_key_type, ); } } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] fn fw_load_error_header_digest_failure() { for pqc_key_type in PQC_KEY_TYPE.iter() { fw_load_error_flow_with_test_hooks( None, None, CaliptraError::IMAGE_VERIFIER_ERR_HEADER_DIGEST_FAILURE.into(), FipsTestHook::FW_LOAD_HEADER_DIGEST_FAILURE, *pqc_key_type, ); } } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] fn fw_load_error_vendor_ecc_verify_failure() { for pqc_key_type in PQC_KEY_TYPE.iter() { fw_load_error_flow_with_test_hooks( None, None, CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_VERIFY_FAILURE.into(), FipsTestHook::FW_LOAD_VENDOR_ECC_VERIFY_FAILURE, *pqc_key_type, ); } } #[test] fn fw_load_error_vendor_ecc_signature_invalid() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Corrupt vendor ECC sig fw_image.manifest.preamble.vendor_sigs.ecc_sig.r.fill(1); fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_SIGNATURE_INVALID.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_vendor_ecc_pub_key_index_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Change vendor pubkey index. fw_image.manifest.header.vendor_ecc_pub_key_idx = fw_image.manifest.preamble.vendor_ecc_pub_key_idx + 1; update_manifest(&mut fw_image, HdrDigest::Update, TocDigest::Update); fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INDEX_MISMATCH.into(), *pqc_key_type, ); } } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] fn fw_load_error_owner_ecc_verify_failure() { for pqc_key_type in PQC_KEY_TYPE.iter() { fw_load_error_flow_with_test_hooks( None, None, CaliptraError::IMAGE_VERIFIER_ERR_OWNER_ECC_VERIFY_FAILURE.into(), FipsTestHook::FW_LOAD_OWNER_ECC_VERIFY_FAILURE, *pqc_key_type, ); } } #[test] fn fw_load_error_owner_ecc_signature_invalid() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Corrupt owner ECC sig fw_image.manifest.preamble.owner_sigs.ecc_sig.r.fill(1); fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_OWNER_ECC_SIGNATURE_INVALID.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_toc_entry_count_invalid() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Change the TOC length to over the maximum fw_image.manifest.header.toc_len = caliptra_image_types::MAX_TOC_ENTRY_COUNT + 1; update_manifest(&mut fw_image, HdrDigest::Update, TocDigest::Update); fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_TOC_ENTRY_COUNT_INVALID.into(), *pqc_key_type, ); } } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] fn fw_load_error_toc_digest_failure() { for pqc_key_type in PQC_KEY_TYPE.iter() { fw_load_error_flow_with_test_hooks( None, None, CaliptraError::IMAGE_VERIFIER_ERR_TOC_DIGEST_FAILURE.into(), FipsTestHook::FW_LOAD_OWNER_TOC_DIGEST_FAILURE, *pqc_key_type, ); } } #[test] fn fw_load_error_toc_digest_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Change the TOC digest. fw_image.manifest.header.toc_digest[0] = 0xDEADBEEF; update_manifest(&mut fw_image, HdrDigest::Update, TocDigest::Skip); fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_TOC_DIGEST_MISMATCH.into(), *pqc_key_type, ); } } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] fn fw_load_error_fmc_digest_failure() { for pqc_key_type in PQC_KEY_TYPE.iter() { fw_load_error_flow_with_test_hooks( None, None, CaliptraError::IMAGE_VERIFIER_ERR_FMC_DIGEST_FAILURE.into(), FipsTestHook::FW_LOAD_FMC_DIGEST_FAILURE, *pqc_key_type, ); } } #[test] fn fw_load_error_fmc_digest_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Change the FMC image. fw_image.fmc[0..4].copy_from_slice(0xDEADBEEFu32.as_bytes()); fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_FMC_DIGEST_MISMATCH.into(), *pqc_key_type, ); } } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] fn fw_load_error_runtime_digest_failure() { for pqc_key_type in PQC_KEY_TYPE.iter() { fw_load_error_flow_with_test_hooks( None, None, CaliptraError::IMAGE_VERIFIER_ERR_RUNTIME_DIGEST_FAILURE.into(), FipsTestHook::FW_LOAD_RUNTIME_DIGEST_FAILURE, *pqc_key_type, ); } } #[test] fn fw_load_error_runtime_digest_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Change the runtime image. fw_image.runtime[0..4].copy_from_slice(0xDEADBEEFu32.as_bytes()); fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_RUNTIME_DIGEST_MISMATCH.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_fmc_runtime_overlap() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Corrupt FMC offset fw_image.manifest.fmc.offset = fw_image.manifest.runtime.offset; update_manifest(&mut fw_image, HdrDigest::Update, TocDigest::Update); fw_load_error_flow( Some(fw_image), None, CaliptraError::IMAGE_VERIFIER_ERR_FMC_RUNTIME_OVERLAP.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_fmc_runtime_incorrect_order() { for pqc_key_type in PQC_KEY_TYPE.iter() { let fuses = caliptra_hw_model::Fuses { fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Flip FMC and RT positions let old_fmc_offset = fw_image.manifest.fmc.offset; let old_fmc_size = fw_image.manifest.fmc.size; fw_image.manifest.fmc.offset = fw_image.manifest.runtime.offset; fw_image.manifest.fmc.size = fw_image.manifest.runtime.size; fw_image.manifest.runtime.offset = old_fmc_offset; fw_image.manifest.runtime.size = old_fmc_size; update_manifest(&mut fw_image, HdrDigest::Update, TocDigest::Update); fw_load_error_flow( Some(fw_image), Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_FMC_RUNTIME_INCORRECT_ORDER.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_owner_ecc_pub_key_invalid_arg() { for pqc_key_type in PQC_KEY_TYPE.iter() { let fuses = caliptra_hw_model::Fuses { fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Set ecc_pub_key.y to zero. fw_image .manifest .preamble .owner_pub_keys .ecc_pub_key .y .fill(0); fw_load_error_flow( Some(fw_image), Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_OWNER_ECC_PUB_KEY_INVALID_ARG.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_owner_ecc_signature_invalid_arg() { for pqc_key_type in PQC_KEY_TYPE.iter() { let fuses = caliptra_hw_model::Fuses { fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Set owner_sig.s to zero. fw_image.manifest.preamble.owner_sigs.ecc_sig.s.fill(0); fw_load_error_flow( Some(fw_image), Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_OWNER_ECC_SIGNATURE_INVALID_ARG.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_vendor_pub_key_invalid_arg() { for pqc_key_type in PQC_KEY_TYPE.iter() { let fuses = caliptra_hw_model::Fuses { fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Set ecc_pub_key.x to zero. fw_image .manifest .preamble .vendor_ecc_active_pub_key .x .fill(0); fw_load_error_flow( Some(fw_image), Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INVALID_ARG.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_vendor_ecc_signature_invalid_arg() { for pqc_key_type in PQC_KEY_TYPE.iter() { let fuses = caliptra_hw_model::Fuses { fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Set vendor_sig.r to zero. fw_image.manifest.preamble.vendor_sigs.ecc_sig.r.fill(0); fw_load_error_flow( Some(fw_image), Some(fuses), CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_SIGNATURE_INVALID_ARG.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_update_reset_owner_digest_failure() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut update_image = build_fw_image(image_options); // Set ecc_pub_key.y to some corrupted, non-zero value update_image .manifest .preamble .owner_pub_keys .ecc_pub_key .y .fill(0x1234abcd); update_fw_error_flow( None, None, Some(update_image), CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_OWNER_DIGEST_FAILURE.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_update_reset_vendor_ecc_pub_key_idx_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { let vendor_config_cold_boot = ImageGeneratorVendorConfig { ecc_key_idx: 3, ..VENDOR_CONFIG_KEY_0 }; let image_options_cold_boot = ImageOptions { vendor_config: vendor_config_cold_boot, pqc_key_type: *pqc_key_type, ..Default::default() }; let vendor_config_update_reset = ImageGeneratorVendorConfig { ecc_key_idx: 2, ..VENDOR_CONFIG_KEY_0 }; let image_options_update_reset = ImageOptions { vendor_config: vendor_config_update_reset, pqc_key_type: *pqc_key_type, ..Default::default() }; // Generate images let first_image = build_fw_image(image_options_cold_boot); let update_image = build_fw_image(image_options_update_reset); update_fw_error_flow( Some(first_image), None, Some(update_image), CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_VENDOR_ECC_PUB_KEY_IDX_MISMATCH.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_update_reset_fmc_digest_mismatch() { for pqc_key_type in PQC_KEY_TYPE.iter() { // Generate images let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let first_image = build_fw_image(image_options.clone()); // Use a different FMC for the update image let update_image = caliptra_builder::build_and_sign_image( &FMC_FAKE_WITH_UART, &APP_WITH_UART, image_options, ) .unwrap(); update_fw_error_flow( Some(first_image), None, Some(update_image), CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_FMC_DIGEST_MISMATCH.into(), *pqc_key_type, ); } } #[test] fn fw_load_error_fmc_load_addr_invalid() { for pqc_key_type in PQC_KEY_TYPE.iter() { let fuses = caliptra_hw_model::Fuses { fuse_pqc_key_type: *pqc_key_type as u32, ..Default::default() }; // Generate image let image_options = ImageOptions { pqc_key_type: *pqc_key_type, ..Default::default() }; let mut fw_image = build_fw_image(image_options); // Change FMC load addr
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/fips_test_suite/self_tests.rs
test/tests/fips_test_suite/self_tests.rs
// Licensed under the Apache-2.0 license use crate::common; use caliptra_api::SocManager; use caliptra_builder::firmware::{ APP_WITH_UART_FIPS_TEST_HOOKS, FMC_WITH_UART, ROM_WITH_FIPS_TEST_HOOKS, ROM_WITH_UART, }; use caliptra_builder::ImageOptions; use caliptra_common::mailbox_api::*; use caliptra_drivers::CaliptraError; use caliptra_drivers::FipsTestHook; use caliptra_hw_model::{BootParams, HwModel, InitParams, ModelError}; use common::*; use zerocopy::IntoBytes; #[test] //TODO: https://github.com/chipsalliance/caliptra-sw/issues/2070 #[cfg(all( not(feature = "test_env_immutable_rom"), not(feature = "fpga_realtime") ))] pub fn kat_halt_check_no_output() { let rom = caliptra_builder::build_firmware_rom(&ROM_WITH_FIPS_TEST_HOOKS).unwrap(); let mut hw = fips_test_init_to_boot_start( Some(InitParams { rom: &rom, ..Default::default() }), Some(BootParams { initial_dbg_manuf_service_reg: (FipsTestHook::HALT_SELF_TESTS as u32) << HOOK_CODE_OFFSET, ..Default::default() }), ); // Wait for ACK that ROM reached halt point hook_wait_for_complete(&mut hw); // Check output is inhibited verify_output_inhibited(&mut hw); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn fw_load_halt_check_no_output() { let rom = caliptra_builder::build_firmware_rom(&ROM_WITH_FIPS_TEST_HOOKS).unwrap(); let mut hw = fips_test_init_to_rom( Some(InitParams { rom: &rom, ..Default::default() }), Some(BootParams { initial_dbg_manuf_service_reg: (FipsTestHook::HALT_FW_LOAD as u32) << HOOK_CODE_OFFSET, ..Default::default() }), ); // Start the FW load (don't wait for a result) let fw_image = fips_fw_image(); hw.start_mailbox_execute(u32::from(CommandId::FIRMWARE_LOAD), &fw_image) .unwrap(); // Wait for ACK that ROM reached halt point hook_wait_for_complete(&mut hw); // Check output is inhibited verify_mbox_output_inhibited(&mut hw); // NOTE: SHA engine is not locked during FW load } fn self_test_failure_flow_rom(hook_code: u8, exp_error_code: u32) { let rom = caliptra_builder::build_firmware_rom(&ROM_WITH_FIPS_TEST_HOOKS).unwrap(); let mut hw = fips_test_init_to_boot_start( Some(InitParams { rom: &rom, ..Default::default() }), Some(BootParams { initial_dbg_manuf_service_reg: (hook_code as u32) << HOOK_CODE_OFFSET, ..Default::default() }), ); // Wait for fatal error hw.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() != 0); // Wait for the remaining operations and cleanup from a fatal error to complete // (This is mainly for the SW emulator which only runs when we step) for _ in 0..1000 { hw.step(); } // Verify fatal code is correct assert_eq!(hw.soc_ifc().cptra_fw_error_fatal().read(), exp_error_code); // Verify we cannot use the algorithm // We can't directly call this algorithm, so check that Caliptra will not process messages // Using the Load FW message since that is what uses most of the crypto anyway // Check that the SHA engine is not usable let fw_image = fips_fw_image(); match hw.upload_firmware(&fw_image) { Ok(_) => panic!("FW Load should fail at this point"), Err(act_error) => { if act_error != ModelError::MailboxCmdFailed(exp_error_code) { panic!("FW Load received unexpected error {}", act_error) } } } // Attempt to clear the error in an undocumented way // Clear the error reg and attempt output again // Now that we have cleared the error, we expect an error code of 0 because // The fatal error loop that marks all mbox messages as failed does not update the error code hw.soc_ifc().cptra_fw_error_fatal().write(|_| 0); hw.soc_ifc().cptra_fw_error_non_fatal().write(|_| 0); match hw.upload_firmware(&fw_image) { Ok(_) => panic!("FW Load should fail at this point"), Err(ModelError::MailboxCmdFailed(0x0)) => (), Err(e) => panic!("FW Load received unexpected error {}", e), } // Restart Caliptra if cfg!(any(feature = "verilator", feature = "fpga_realtime")) { hw.cold_reset(); } else { hw = fips_test_init_model(Some(InitParams { rom: &rom, ..Default::default() })) } hw.boot(BootParams::default()).unwrap(); hw.step_until(|m| { m.soc_ifc() .cptra_flow_status() .read() .ready_for_mb_processing() }); // Verify we can load FW hw.upload_firmware(&fw_image).unwrap(); } fn self_test_failure_flow_rt(hook_code: u8, exp_error_code: u32) { // Build FW with test hooks and init to runtime let fw_image = caliptra_builder::build_and_sign_image( &FMC_WITH_UART, &APP_WITH_UART_FIPS_TEST_HOOKS, ImageOptions::default(), ) .unwrap() .to_bytes() .unwrap(); let mut hw = fips_test_init_to_rt( None, Some(BootParams { fw_image: Some(&fw_image), ..Default::default() }), ); // Wait for RT to be ready for commands before setting hook hw.step_until(|m| m.soc_ifc().cptra_flow_status().read().ready_for_runtime()); // Set the test hook hw.soc_ifc() .cptra_dbg_manuf_service_reg() .write(|_| (hook_code as u32) << HOOK_CODE_OFFSET); // Start the self tests let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum( u32::from(CommandId::SELF_TEST_START), &[], ), }; mbx_send_and_check_resp_hdr::<_, MailboxRespHeader>( &mut hw, u32::from(CommandId::SELF_TEST_START), payload.as_bytes(), ) .unwrap(); // Wait for error hw.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() != 0); // Wait for the remaining operations and cleanup from a fatal error to complete // (This is mainly for the SW emulator which only runs when we step) for _ in 0..1000 { hw.step(); } // Verify error code is correct assert_eq!(hw.soc_ifc().cptra_fw_error_fatal().read(), exp_error_code); // Verify we cannot use the algorithm match hw.upload_firmware(&fw_image) { Ok(_) => panic!("FW Load should fail at this point"), Err(act_error) => { if act_error != ModelError::MailboxCmdFailed(exp_error_code) { panic!("FW Load received unexpected error {}", act_error) } } } // Attempt to clear the error in an undocumented way // Clear the error reg and attempt output again // Now that we have cleared the error, we expect an error code of 0 because // The fatal error loop that marks all mbox messages as failed does not update the error code hw.soc_ifc().cptra_fw_error_fatal().write(|_| 0); hw.soc_ifc().cptra_fw_error_non_fatal().write(|_| 0); match hw.upload_firmware(&fw_image) { Ok(_) => panic!("FW Load should fail at this point"), Err(ModelError::MailboxCmdFailed(0x0)) => (), Err(e) => panic!("FW Load received unexpected error {}", e), } // Restart Caliptra if cfg!(any(feature = "verilator", feature = "fpga_realtime")) { hw.cold_reset(); } else { hw = fips_test_init_model(None) } hw.boot(BootParams::default()).unwrap(); hw.step_until(|m| { m.soc_ifc() .cptra_flow_status() .read() .ready_for_mb_processing() }); // Verify we can load FW hw.upload_firmware(&fw_image).unwrap(); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_sha1_digest_failure_rom() { self_test_failure_flow_rom( FipsTestHook::SHA1_DIGEST_FAILURE, u32::from(CaliptraError::KAT_SHA1_DIGEST_FAILURE), ); } #[test] pub fn kat_sha1_digest_failure_rt() { self_test_failure_flow_rt( FipsTestHook::SHA1_DIGEST_FAILURE, u32::from(CaliptraError::KAT_SHA1_DIGEST_FAILURE), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_sha1_digest_mismatch_rom() { self_test_failure_flow_rom( FipsTestHook::SHA1_CORRUPT_DIGEST, u32::from(CaliptraError::KAT_SHA1_DIGEST_MISMATCH), ); } #[test] pub fn kat_sha1_digest_mismatch_rt() { self_test_failure_flow_rt( FipsTestHook::SHA1_CORRUPT_DIGEST, u32::from(CaliptraError::KAT_SHA1_DIGEST_MISMATCH), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_sha256_digest_failure_rom() { self_test_failure_flow_rom( FipsTestHook::SHA256_DIGEST_FAILURE, u32::from(CaliptraError::KAT_SHA256_DIGEST_FAILURE), ); } #[test] pub fn kat_sha256_digest_failure_rt() { self_test_failure_flow_rt( FipsTestHook::SHA256_DIGEST_FAILURE, u32::from(CaliptraError::KAT_SHA256_DIGEST_FAILURE), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_sha256_digest_mismatch_rom() { self_test_failure_flow_rom( FipsTestHook::SHA256_CORRUPT_DIGEST, u32::from(CaliptraError::KAT_SHA256_DIGEST_MISMATCH), ); } #[test] pub fn kat_sha256_digest_mismatch_rt() { self_test_failure_flow_rt( FipsTestHook::SHA256_CORRUPT_DIGEST, u32::from(CaliptraError::KAT_SHA256_DIGEST_MISMATCH), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_sha384_digest_failure_rom() { self_test_failure_flow_rom( FipsTestHook::SHA384_DIGEST_FAILURE, u32::from(CaliptraError::KAT_SHA384_DIGEST_FAILURE), ); } #[test] pub fn kat_sha384_digest_failure_rt() { self_test_failure_flow_rt( FipsTestHook::SHA384_DIGEST_FAILURE, u32::from(CaliptraError::KAT_SHA384_DIGEST_FAILURE), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_sha384_digest_mismatch_rom() { self_test_failure_flow_rom( FipsTestHook::SHA384_CORRUPT_DIGEST, u32::from(CaliptraError::KAT_SHA384_DIGEST_MISMATCH), ); } #[test] pub fn kat_sha384_digest_mismatch_rt() { self_test_failure_flow_rt( FipsTestHook::SHA384_CORRUPT_DIGEST, u32::from(CaliptraError::KAT_SHA384_DIGEST_MISMATCH), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_sha2_512_384acc_digest_start_op_failure_rom() { self_test_failure_flow_rom( FipsTestHook::SHA2_512_384_ACC_START_OP_FAILURE, u32::from(CaliptraError::KAT_SHA2_512_384_ACC_DIGEST_START_OP_FAILURE), ); } #[test] pub fn kat_sha2_512_384acc_digest_start_op_failure_rt() { self_test_failure_flow_rt( FipsTestHook::SHA2_512_384_ACC_START_OP_FAILURE, u32::from(CaliptraError::KAT_SHA2_512_384_ACC_DIGEST_START_OP_FAILURE), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_sha2_512_384acc_digest_failure_rom() { self_test_failure_flow_rom( FipsTestHook::SHA2_512_384_ACC_DIGEST_512_FAILURE, u32::from(CaliptraError::KAT_SHA2_512_384_ACC_DIGEST_FAILURE), ); } #[test] pub fn kat_sha2_512_384acc_digest_failure_rt() { self_test_failure_flow_rt( FipsTestHook::SHA2_512_384_ACC_DIGEST_512_FAILURE, u32::from(CaliptraError::KAT_SHA2_512_384_ACC_DIGEST_FAILURE), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_sha2_512_384acc_digest_mismatch_rom() { self_test_failure_flow_rom( FipsTestHook::SHA2_512_384_ACC_CORRUPT_DIGEST_512, u32::from(CaliptraError::KAT_SHA2_512_384_ACC_DIGEST_MISMATCH), ); } #[test] pub fn kat_sha2_512_384acc_digest_mismatch_rt() { self_test_failure_flow_rt( FipsTestHook::SHA2_512_384_ACC_CORRUPT_DIGEST_512, u32::from(CaliptraError::KAT_SHA2_512_384_ACC_DIGEST_MISMATCH), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_ecc384_signature_generate_failure_rom() { self_test_failure_flow_rom( FipsTestHook::ECC384_SIGNATURE_GENERATE_FAILURE, u32::from(CaliptraError::KAT_ECC384_KEY_PAIR_GENERATE_FAILURE), ); } #[test] pub fn kat_ecc384_signature_generate_failure_rt() { self_test_failure_flow_rt( FipsTestHook::ECC384_SIGNATURE_GENERATE_FAILURE, u32::from(CaliptraError::KAT_ECC384_KEY_PAIR_GENERATE_FAILURE), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_ecc384_signature_verify_failure_rom() { self_test_failure_flow_rom( FipsTestHook::ECC384_CORRUPT_SIGNATURE, u32::from(CaliptraError::KAT_ECC384_SIGNATURE_MISMATCH), ); } #[test] pub fn kat_ecc384_signature_verify_failure_rt() { self_test_failure_flow_rt( FipsTestHook::ECC384_CORRUPT_SIGNATURE, u32::from(CaliptraError::KAT_ECC384_SIGNATURE_MISMATCH), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_ecc384_deterministic_key_gen_generate_failure_rom() { self_test_failure_flow_rom( FipsTestHook::ECC384_KEY_PAIR_GENERATE_FAILURE, u32::from(CaliptraError::KAT_ECC384_KEY_PAIR_GENERATE_FAILURE), ); } #[test] pub fn kat_ecc384_deterministic_key_gen_generate_failure_rt() { self_test_failure_flow_rt( FipsTestHook::ECC384_KEY_PAIR_GENERATE_FAILURE, u32::from(CaliptraError::KAT_ECC384_KEY_PAIR_GENERATE_FAILURE), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_ecc384_deterministic_key_gen_verify_failure_rom() { self_test_failure_flow_rom( FipsTestHook::ECC384_CORRUPT_KEY_PAIR, u32::from(CaliptraError::KAT_ECC384_KEY_PAIR_VERIFY_FAILURE), ); } #[test] pub fn kat_ecc384_deterministic_key_gen_verify_failure_rt() { self_test_failure_flow_rt( FipsTestHook::ECC384_CORRUPT_KEY_PAIR, u32::from(CaliptraError::KAT_ECC384_KEY_PAIR_VERIFY_FAILURE), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_hmac384_failure_rom() { self_test_failure_flow_rom( FipsTestHook::HMAC384_FAILURE, u32::from(CaliptraError::KAT_HMAC384_FAILURE), ); } #[test] pub fn kat_hmac384_failure_rt() { self_test_failure_flow_rt( FipsTestHook::HMAC384_FAILURE, u32::from(CaliptraError::KAT_HMAC384_FAILURE), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_hmac384_tag_mismatch_rom() { self_test_failure_flow_rom( FipsTestHook::HMAC384_CORRUPT_TAG, u32::from(CaliptraError::KAT_HMAC384_TAG_MISMATCH), ); } #[test] pub fn kat_hmac384_tag_mismatch_rt() { self_test_failure_flow_rt( FipsTestHook::HMAC384_CORRUPT_TAG, u32::from(CaliptraError::KAT_HMAC384_TAG_MISMATCH), ); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn kat_lms_digest_mismatch_rom() { self_test_failure_flow_rom( FipsTestHook::LMS_CORRUPT_INPUT, u32::from(CaliptraError::KAT_LMS_DIGEST_MISMATCH), ); } #[test] pub fn kat_lms_digest_mismatch_rt() { self_test_failure_flow_rt( FipsTestHook::LMS_CORRUPT_INPUT, u32::from(CaliptraError::KAT_LMS_DIGEST_MISMATCH), ); } 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] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn integrity_check_failure_rom() { // NOTE: Corruption steps from test_rom_integrity.rs let exp_error_code = u32::from(CaliptraError::ROM_INTEGRITY_FAILURE); let mut rom = caliptra_builder::build_firmware_rom(&ROM_WITH_UART).unwrap(); let rom_info_offset = find_rom_info_offset(&rom); // 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 = fips_test_init_to_boot_start( Some(InitParams { rom: &rom, ..Default::default() }), None, ); // Wait for fatal error hw.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() != 0); // Wait for the remaining operations and cleanup from a fatal error to complete // (This is mainly for the SW emulator which only runs when we step) for _ in 0..1000 { hw.step(); } // Verify fatal code is correct assert_eq!(hw.soc_ifc().cptra_fw_error_fatal().read(), exp_error_code); // Verify we cannot send messages or use the SHA engine let fw_image = fips_fw_image(); match hw.upload_firmware(&fw_image) { Ok(_) => panic!("FW Load should fail at this point"), Err(act_error) => { if act_error != ModelError::MailboxCmdFailed(exp_error_code) { panic!("FW Load received unexpected error {}", act_error) } } } // Attempt to clear the error in an undocumented way // Clear the error reg and attempt output again // Now that we have cleared the error, we expect an error code of 0 because // The fatal error loop that marks all mbox messages as failed does not update the error code hw.soc_ifc().cptra_fw_error_fatal().write(|_| 0); hw.soc_ifc().cptra_fw_error_non_fatal().write(|_| 0); match hw.upload_firmware(&fw_image) { Ok(_) => panic!("FW Load should fail at this point"), Err(ModelError::MailboxCmdFailed(0x0)) => (), Err(e) => panic!("FW Load received unexpected error {}", e), } // This error cannot be cleared. } // TODO: Enable once https://github.com/chipsalliance/caliptra-sw/issues/1598 is addressed // Operations with invalid key pairs not supported by SW emulator // #[test] // #[cfg(not(feature = "test_env_immutable_rom"))] // #[cfg(any(feature = "verilator", feature = "fpga_realtime"))] // pub fn ecc384_pairwise_consistency_error() { // self_test_failure_flow_rom( // FipsTestHook::ECC384_PAIRWISE_CONSISTENCY_ERROR, // u32::from(CaliptraError::DRIVER_ECC384_KEYGEN_PAIRWISE_CONSISTENCY_FAILURE), // ); // }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/fips_test_suite/main.rs
test/tests/fips_test_suite/main.rs
// Licensed under the Apache-2.0 license mod common; mod fw_load; #[cfg(feature = "fpga_realtime")] mod jtag_locked; mod security_parameters; mod self_tests; mod services;
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/fips_test_suite/common.rs
test/tests/fips_test_suite/common.rs
// Licensed under the Apache-2.0 license use caliptra_api::SocManager; use caliptra_auth_man_gen::default_test_manifest::{default_test_soc_manifest, DEFAULT_MCU_FW}; use caliptra_builder::firmware::{APP_WITH_UART, APP_WITH_UART_FPGA, FMC_WITH_UART}; use caliptra_builder::{version, ImageOptions}; use caliptra_common::mailbox_api::*; use caliptra_drivers::FipsTestHook; use caliptra_hw_model::{BootParams, DefaultHwModel, HwModel, InitParams, ModelError}; use caliptra_image_crypto::OsslCrypto as Crypto; use caliptra_image_types::FwVerificationPqcKeyType; use dpe::{ commands::*, response::{ CertifyKeyResp, DeriveContextResp, GetCertificateChainResp, GetProfileResp, NewHandleResp, Response, ResponseHdr, SignResp, }, DPE_PROFILE, }; use zerocopy::{FromBytes, IntoBytes, TryFromBytes}; pub const PQC_KEY_TYPE: [FwVerificationPqcKeyType; 2] = [ FwVerificationPqcKeyType::LMS, FwVerificationPqcKeyType::MLDSA, ]; pub const HOOK_CODE_MASK: u32 = 0x00FF0000; pub const HOOK_CODE_OFFSET: u32 = 16; // ================================= // EXPECTED CONSTANTS // ================================= // Constants are grouped into RTL, ROM, and Runtime // Values can be specified for specific release versions (i.e. 1.0.1) // The user can specify which release (or default to current) to use when executing tests // Subsequent versions should "inherit" the previous version and override any changed values // The "current" struct must always match the behavior of components built from the same commit ID // === RTL === pub struct HwExpVals { pub hw_revision: u32, } const HW_EXP_2_0_0: HwExpVals = HwExpVals { hw_revision: 0x2 }; const HW_EXP_CURRENT: HwExpVals = HwExpVals { hw_revision: 0x112 }; // === ROM === pub struct RomExpVals { pub rom_version: u16, pub capabilities: [u8; 16], } #[cfg(not(feature = "ocp-lock"))] const ROM_EXP_2_0_0: RomExpVals = RomExpVals { rom_version: 0x1000, // 2.0.0 capabilities: [ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, ], }; #[cfg(feature = "ocp-lock")] const ROM_EXP_2_0_0: RomExpVals = RomExpVals { rom_version: 0x1000, // 2.0.0 capabilities: [ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3, ], }; const ROM_EXP_CURRENT: RomExpVals = RomExpVals { ..ROM_EXP_2_0_0 }; // === RUNTIME === pub struct RtExpVals { pub fmc_version: u16, pub fw_version: u32, } const RT_EXP_2_0_0: RtExpVals = RtExpVals { fmc_version: 0x1000, // 2.0.0 fw_version: 0x0200_0000, // 2.0.0 }; const RT_EXP_CURRENT: RtExpVals = RtExpVals { ..RT_EXP_2_0_0 }; // === Getter implementations === // TODO: These could be improved // Can we generate a var name from a str in rust and check if it exists? // Or we can just do a macro to generate a list of the valid versions and const names to use here impl HwExpVals { pub fn get() -> HwExpVals { if let Ok(version) = std::env::var("FIPS_TEST_HW_EXP_VERSION") { match version.as_str() { // Add more versions here "2_0_0" => HW_EXP_2_0_0, _ => panic!( "FIPS Test: Unknown version for expected HW values ({})", version ), } } else { HW_EXP_CURRENT } } } impl RomExpVals { pub fn get() -> RomExpVals { if let Ok(version) = std::env::var("FIPS_TEST_ROM_EXP_VERSION") { match version.as_str() { // Add more versions here "2_0_0" => ROM_EXP_2_0_0, _ => panic!( "FIPS Test: Unknown version for expected ROM values ({})", version ), } } else { ROM_EXP_CURRENT } } } impl RtExpVals { pub fn get() -> RtExpVals { if let Ok(version) = std::env::var("FIPS_TEST_RT_EXP_VERSION") { match version.as_str() { // Add more versions here "2_0_0" => RT_EXP_2_0_0, _ => panic!( "FIPS Test: Unknown version for expected Runtime values ({})", version ), } } else { RT_EXP_CURRENT } } } // ================================= // HELPER FUNCTIONS // ================================= pub fn fips_test_init_model(init_params: Option<InitParams>) -> DefaultHwModel { // Create params if not provided let mut init_params = init_params.unwrap_or_default(); // Check that ROM was not provided if the immutable_rom feature is set #[cfg(feature = "test_env_immutable_rom")] if init_params.rom != <&[u8]>::default() { panic!("FIPS_TEST_SUITE ERROR: ROM cannot be provided/changed when immutable_ROM feature is set") } // If rom was not provided, build it or get it from the specified path let rom = match std::env::var("FIPS_TEST_ROM_BIN") { // Build default rom if not provided and no path is specified Err(_) => { caliptra_builder::rom_for_fw_integration_tests_fpga(cfg!(feature = "fpga_subsystem")) .unwrap() } Ok(rom_path) => { // Read in the ROM file if a path was provided match std::fs::read(&rom_path) { Err(why) => panic!("couldn't open {}: {}", rom_path, why), Ok(rom) => rom.into(), } } }; if init_params.rom == <&[u8]>::default() { init_params.rom = &rom; } // Create the model caliptra_hw_model::new_unbooted(init_params).unwrap() } fn fips_test_boot<T: HwModel>(hw: &mut T, boot_params: Option<BootParams>) { // Create params if not provided let boot_params = boot_params.unwrap_or_default(); // Boot hw.boot(boot_params).unwrap(); } // Generic helper to boot to ROM or runtime // Builds ROM, if not provided // HW Model will boot to runtime if image is provided fn fips_test_init_base( init_params: Option<InitParams>, boot_params: Option<BootParams>, ) -> DefaultHwModel { let mut hw = fips_test_init_model(init_params); fips_test_boot(&mut hw, boot_params); hw } // Initializes Caliptra // Builds and uses default ROM if not provided pub fn fips_test_init_to_boot_start( init_params: Option<InitParams>, boot_params: Option<BootParams>, ) -> DefaultHwModel { // Check that no fw_image is in boot params if let Some(ref params) = boot_params { if params.fw_image.is_some() { panic!("No FW image should be provided when calling fips_test_init_to_boot_start") } } fips_test_init_base(init_params, boot_params) } // Initializes caliptra to "ready_for_fw" // Builds and uses default ROM if not provided pub fn fips_test_init_to_rom( init_params: Option<InitParams>, boot_params: Option<BootParams>, ) -> DefaultHwModel { let mut model = fips_test_init_base(init_params, boot_params); // Step to ready for FW in ROM model.step_until(|m| { m.soc_ifc() .cptra_flow_status() .read() .ready_for_mb_processing() }); model } // Initializes Caliptra to runtime // Builds and uses default ROM and FW if not provided pub fn fips_test_init_to_rt( init_params: Option<InitParams>, boot_params: Option<BootParams>, ) -> DefaultHwModel { // Create params if not provided let mut boot_params = boot_params.unwrap_or_default(); let mut hw = if boot_params.fw_image.is_some() { fips_test_init_base(init_params, Some(boot_params)) } else { let fw_image = fips_fw_image(); boot_params.fw_image = Some(&fw_image); let soc_manifest = default_test_soc_manifest( &DEFAULT_MCU_FW, FwVerificationPqcKeyType::MLDSA, 1, Crypto::default(), ); boot_params.soc_manifest = Some(soc_manifest.as_bytes()); boot_params.mcu_fw_image = Some(&DEFAULT_MCU_FW); fips_test_init_base(init_params, Some(boot_params)) }; // We need this on fpga_subsystem hw.step_until(|m| m.soc_ifc().cptra_flow_status().read().ready_for_runtime()); hw // HW model will complete FW upload cmd, nothing to wait for } pub fn mbx_send_and_check_resp_hdr<T: HwModel, U: FromBytes + IntoBytes>( hw: &mut T, cmd: u32, req_payload: &[u8], ) -> std::result::Result<U, ModelError> { let resp_bytes = hw.mailbox_execute(cmd, req_payload)?.unwrap(); // Check values against expected. let resp_hdr = MailboxRespHeader::read_from_bytes( &resp_bytes[..core::mem::size_of::<MailboxRespHeader>()], ) .unwrap(); assert!(caliptra_common::checksum::verify_checksum( resp_hdr.chksum, 0x0, &resp_bytes[core::mem::size_of_val(&resp_hdr.chksum)..], )); assert_eq!( resp_hdr.fips_status, MailboxRespHeader::FIPS_STATUS_APPROVED ); // Handle variable-sized responses assert!(resp_bytes.len() <= std::mem::size_of::<U>()); let mut typed_resp = U::new_zeroed(); typed_resp.as_mut_bytes()[..resp_bytes.len()].copy_from_slice(&resp_bytes); Ok(typed_resp) // TODO: Add option for fixed-length enforcement //Ok(U::read_from_bytes(resp_bytes.as_bytes()).unwrap()) } fn get_cmd_id(dpe_cmd: &mut Command) -> u32 { match dpe_cmd { Command::GetProfile => Command::GET_PROFILE, Command::InitCtx(_) => Command::INITIALIZE_CONTEXT, Command::DeriveContext(_) => Command::DERIVE_CONTEXT, Command::CertifyKey(_) => Command::CERTIFY_KEY, Command::Sign(_) => Command::SIGN, Command::RotateCtx(_) => Command::ROTATE_CONTEXT_HANDLE, Command::DestroyCtx(_) => Command::DESTROY_CONTEXT, Command::GetCertificateChain(_) => Command::GET_CERTIFICATE_CHAIN, } } pub fn as_bytes<'a>(dpe_cmd: &'a mut Command) -> &'a [u8] { match dpe_cmd { Command::CertifyKey(cmd) => cmd.as_bytes(), Command::DeriveContext(cmd) => cmd.as_bytes(), Command::GetCertificateChain(cmd) => cmd.as_bytes(), Command::DestroyCtx(cmd) => cmd.as_bytes(), Command::GetProfile => &[], Command::InitCtx(cmd) => cmd.as_bytes(), Command::RotateCtx(cmd) => cmd.as_bytes(), Command::Sign(cmd) => cmd.as_bytes(), } } pub fn parse_dpe_response(dpe_cmd: &mut Command, resp_bytes: &[u8]) -> Response { match dpe_cmd { Command::CertifyKey(_) => { Response::CertifyKey(CertifyKeyResp::try_read_from_bytes(resp_bytes).unwrap()) } Command::DeriveContext(_) => { Response::DeriveContext(DeriveContextResp::try_read_from_bytes(resp_bytes).unwrap()) } Command::GetCertificateChain(_) => Response::GetCertificateChain( GetCertificateChainResp::try_read_from_bytes(resp_bytes).unwrap(), ), Command::DestroyCtx(_) => { Response::DestroyCtx(ResponseHdr::try_read_from_bytes(resp_bytes).unwrap()) } Command::GetProfile => { Response::GetProfile(GetProfileResp::try_read_from_bytes(resp_bytes).unwrap()) } Command::InitCtx(_) => { Response::InitCtx(NewHandleResp::try_read_from_bytes(resp_bytes).unwrap()) } Command::RotateCtx(_) => { Response::RotateCtx(NewHandleResp::try_read_from_bytes(resp_bytes).unwrap()) } Command::Sign(_) => Response::Sign(SignResp::try_read_from_bytes(resp_bytes).unwrap()), } } pub fn execute_dpe_cmd<T: HwModel>(hw: &mut T, dpe_cmd: &mut Command) -> Response { let mut cmd_data: [u8; 512] = [0u8; InvokeDpeReq::DATA_MAX_SIZE]; let dpe_cmd_id = get_cmd_id(dpe_cmd); let cmd_hdr = CommandHdr::new(DPE_PROFILE, dpe_cmd_id); let cmd_hdr_buf = cmd_hdr.as_bytes(); cmd_data[..cmd_hdr_buf.len()].copy_from_slice(cmd_hdr_buf); let dpe_cmd_buf = as_bytes(dpe_cmd); cmd_data[cmd_hdr_buf.len()..cmd_hdr_buf.len() + dpe_cmd_buf.len()].copy_from_slice(dpe_cmd_buf); let mut payload = MailboxReq::InvokeDpeCommand(InvokeDpeReq { hdr: MailboxReqHeader { chksum: 0 }, data: cmd_data, data_size: (cmd_hdr_buf.len() + dpe_cmd_buf.len()) as u32, }); payload.populate_chksum().unwrap(); let resp = mbx_send_and_check_resp_hdr::<_, InvokeDpeResp>( hw, u32::from(CommandId::INVOKE_DPE), payload.as_bytes().unwrap(), ) .unwrap(); let resp_bytes = &resp.data[..resp.data_size as usize]; parse_dpe_response(dpe_cmd, resp_bytes) } pub fn fips_fw_image() -> Vec<u8> { match std::env::var("FIPS_TEST_FW_BIN") { // Build default FW if not provided and no path is specified Err(_) => caliptra_builder::build_and_sign_image( &FMC_WITH_UART, &if cfg!(feature = "fpga_subsystem") { APP_WITH_UART_FPGA } else { APP_WITH_UART }, ImageOptions { fmc_version: version::get_fmc_version(), app_version: version::get_runtime_version(), ..Default::default() }, ) .unwrap() .to_bytes() .unwrap(), // Read in the ROM file if a path was provided Ok(fw_path) => match std::fs::read(&fw_path) { Err(why) => panic!("couldn't open {}: {}", fw_path, why), Ok(fw_image) => fw_image, }, } } // Returns true if not all elements in array are the same // (Mainly want to make sure data is not all 0s or all Fs) pub fn contains_some_data<T: std::cmp::PartialEq>(data: &[T]) -> bool { for element in data { if *element != data[0] { return true; } } false } pub fn verify_mbox_cmds_fail<T: HwModel>(hw: &mut T, exp_error_code: u32) { // Send an arbitrary, valid message let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::FW_INFO), &[]), }; // Make sure we get the right failure match mbx_send_and_check_resp_hdr::<_, FwInfoResp>( hw, u32::from(CommandId::FW_INFO), payload.as_bytes(), ) { Ok(_) => panic!("MBX command should fail at this point"), Err(act_error) => { if act_error != ModelError::MailboxCmdFailed(exp_error_code) { panic!("MBX command received unexpected error {}", act_error) } } } } // Check mailbox output is inhibited pub fn verify_mbox_output_inhibited<T: HwModel>(hw: &mut T) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::VERSION), &[]), }; match hw.mailbox_execute(u32::from(CommandId::VERSION), payload.as_bytes()) { Ok(_) => panic!("Mailbox output is not inhibited"), Err(ModelError::MailboxTimeout) => (), Err(ModelError::UnableToLockMailbox) => (), Err(e) => panic!("Unexpected error from mailbox_execute {:?}", e), } } // Verify all output is inhibited pub fn verify_output_inhibited<T: HwModel>(hw: &mut T) { verify_mbox_output_inhibited(hw); } pub fn hook_code_read<T: HwModel>(hw: &mut T) -> u8 { ((hw.soc_ifc().cptra_dbg_manuf_service_reg().read() & HOOK_CODE_MASK) >> HOOK_CODE_OFFSET) as u8 } pub fn hook_code_write<T: HwModel>(hw: &mut T, code: u8) { let val = (hw.soc_ifc().cptra_dbg_manuf_service_reg().read() & !(HOOK_CODE_MASK)) | ((code as u32) << HOOK_CODE_OFFSET); hw.soc_ifc().cptra_dbg_manuf_service_reg().write(|_| val); } pub fn hook_wait_for_complete<T: HwModel>(hw: &mut T) { while hook_code_read(hw) != FipsTestHook::COMPLETE { // Give FW time to run let mut cycle_count = 1000; hw.step_until(|_| -> bool { cycle_count -= 1; cycle_count == 0 }); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/test/tests/fips_test_suite/security_parameters.rs
test/tests/fips_test_suite/security_parameters.rs
// Licensed under the Apache-2.0 license #![allow(dead_code)] use crate::common; use caliptra_builder::firmware::ROM_WITH_FIPS_TEST_HOOKS; use caliptra_common::mailbox_api::*; use caliptra_drivers::{CaliptraError, FipsTestHook}; use caliptra_hw_model::{BootParams, DeviceLifecycle, HwModel, InitParams, SecurityState}; use caliptra_image_crypto::OsslCrypto as Crypto; use caliptra_image_gen::ImageGenerator; use caliptra_image_types::ImageManifest; use ureg::{Mmio, MmioMut}; use common::*; use zerocopy::FromBytes; // TODO: This may differ per environment (0s vs Fs) const INACCESSIBLE_READ_VALUE: u32 = 0x0; fn prove_jtag_inaccessible<T: HwModel>(_hw: &mut T) { // TODO: Add generic JTAG functions to FW model so something like what's below can work // #[cfg(feature = "fpga_realtime")] // assert_eq!(_hw.launch_openocd().unwrap_err(), caliptra_hw_model::OpenOcdError::NotAccessible); } fn attempt_csp_fuse_read<T: HwModel>(hw: &mut T) { let uds_ptr = hw.soc_ifc().fuse_uds_seed().at(0).ptr; let uds_read_val = unsafe { caliptra_hw_model::BusMmio::new(hw.apb_bus()).read_volatile(uds_ptr) }; let field_entropy_ptr = hw.soc_ifc().fuse_field_entropy().at(0).ptr; let field_entropy_read_val = unsafe { caliptra_hw_model::BusMmio::new(hw.apb_bus()).read_volatile(field_entropy_ptr) }; // TODO: Add exception for SW emulator (does not model locked registers at the MMIO level) assert_eq!(uds_read_val, INACCESSIBLE_READ_VALUE); assert_eq!(field_entropy_read_val, INACCESSIBLE_READ_VALUE); } fn attempt_psp_fuse_modify<T: HwModel>(hw: &mut T) { let owner_pk_hash_read_orig_val = hw.soc_ifc().cptra_owner_pk_hash().at(0).read(); // TODO: Add exception for SW emulator (write failure panics) // Try to write a new value let owner_pk_hash_ptr = hw.soc_ifc().cptra_owner_pk_hash().at(0).ptr; unsafe { caliptra_hw_model::BusMmio::new(hw.apb_bus()).write_volatile(owner_pk_hash_ptr, 0xaaaaaaaa) }; let owner_pk_hash_read_val = hw.soc_ifc().cptra_owner_pk_hash().at(0).read(); // Make sure the value was unchanged assert_eq!(owner_pk_hash_read_orig_val, owner_pk_hash_read_val); } fn attempt_keyvault_access<T: HwModel>(hw: &mut T) { const KV_KEY_CTRL_ADDR: u32 = 0x1001_8000; let kv_key_ctrl_ptr = KV_KEY_CTRL_ADDR as *mut u32; // Attempt to read keyvault module from the SoC side // This is not visible to the SoC, but shared modules (mailbox, SHA engine, etc.) use a 1:1 // address mapping between the SoC and Caliptra let kv_key_ctrl_val = unsafe { caliptra_hw_model::BusMmio::new(hw.apb_bus()).read_volatile(kv_key_ctrl_ptr) }; assert_eq!(kv_key_ctrl_val, INACCESSIBLE_READ_VALUE); // Attempt to write unsafe { caliptra_hw_model::BusMmio::new(hw.apb_bus()).write_volatile(kv_key_ctrl_ptr, 0xffffffff) }; // Read again let kv_key_ctrl_val = unsafe { caliptra_hw_model::BusMmio::new(hw.apb_bus()).read_volatile(kv_key_ctrl_ptr) }; assert_eq!(kv_key_ctrl_val, INACCESSIBLE_READ_VALUE); } fn attempt_caliptra_dccm_access<T: HwModel>(hw: &mut T) { const DCCM_BASE: u32 = 0x5000_0000; let dccm_ptr = DCCM_BASE as *mut u32; // Attempt to read DCCM module from the SoC side // This is not visible to the SoC, but shared modules (mailbox, SHA engine, etc.) use a 1:1 // address mapping between the SoC and Caliptra let dccm_val = unsafe { caliptra_hw_model::BusMmio::new(hw.apb_bus()).read_volatile(dccm_ptr) }; assert_eq!(dccm_val, INACCESSIBLE_READ_VALUE); // Attempt to write unsafe { caliptra_hw_model::BusMmio::new(hw.apb_bus()).write_volatile(dccm_ptr, 0xffffffff) }; // Read again let dccm_val = unsafe { caliptra_hw_model::BusMmio::new(hw.apb_bus()).read_volatile(dccm_ptr) }; assert_eq!(dccm_val, INACCESSIBLE_READ_VALUE); } fn attempt_mbox_access<T: HwModel>(hw: &mut T) { // Makes sure we can't read anything from dataout let dataout_val = hw.soc_mbox().dataout().read(); assert_eq!(dataout_val, 0x0); } fn attempt_ssp_access<T: HwModel>(hw: &mut T) { prove_jtag_inaccessible(hw); // TODO: Enable on other environments (not possible on SW emulator) #[cfg(feature = "verilator")] attempt_csp_fuse_read(hw); // TODO: Enable on other environments (not possible on SW emulator) #[cfg(feature = "verilator")] attempt_psp_fuse_modify(hw); // TODO: Enable on other environments (not possible on SW emulator) #[cfg(feature = "verilator")] attempt_keyvault_access(hw); // TODO: Enable on other environments (not possible on SW emulator) #[cfg(feature = "verilator")] attempt_caliptra_dccm_access(hw); // TODO: Enable on other environments (not possible on SW emulator) #[cfg(feature = "verilator")] attempt_mbox_access(hw); } #[test] pub fn attempt_ssp_access_rom() { let fuses = caliptra_hw_model::Fuses { //field_entropy vendor_pk_hash: [0x55555555u32; 12], ..Default::default() }; let security_state = *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production); let mut hw = fips_test_init_to_rom( Some(InitParams { fuses, security_state, ..Default::default() }), Some(BootParams { ..Default::default() }), ); // Perform all the SSP access attempts attempt_ssp_access(&mut hw); } #[test] #[cfg(not(feature = "test_env_immutable_rom"))] pub fn attempt_ssp_access_fw_load() { let rom = caliptra_builder::build_firmware_rom(&ROM_WITH_FIPS_TEST_HOOKS).unwrap(); let fw_image = fips_fw_image(); let (manifest, _) = ImageManifest::read_from_prefix(&fw_image).unwrap(); let gen = ImageGenerator::new(Crypto::default()); let vendor_pubkey_info_digest = gen.vendor_pubkey_info_digest(&manifest.preamble).unwrap(); let fuses = caliptra_hw_model::Fuses { //field_entropy vendor_pk_hash: vendor_pubkey_info_digest, life_cycle: DeviceLifecycle::Production, ..Default::default() }; let security_state = *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production); let mut hw = fips_test_init_to_rom( Some(InitParams { fuses, rom: &rom, security_state, ..Default::default() }), Some(BootParams { initial_dbg_manuf_service_reg: (FipsTestHook::HALT_FW_LOAD as u32) << HOOK_CODE_OFFSET, ..Default::default() }), ); // Start the FW load (don't wait for a result) hw.start_mailbox_execute(u32::from(CommandId::FIRMWARE_LOAD), &fw_image) .unwrap(); // Wait for ACK that ROM reached halt point hook_wait_for_complete(&mut hw); // Perform all the SSP access attempts attempt_ssp_access(&mut hw); // Tell ROM to continue hook_code_write(&mut hw, FipsTestHook::CONTINUE); // Wait for ACK that ROM continued hook_wait_for_complete(&mut hw); // Wait for the FW load to report success hw.finish_mailbox_execute().unwrap(); } #[test] pub fn attempt_ssp_access_rt() { let fw_image = fips_fw_image(); let (manifest, _) = ImageManifest::read_from_prefix(&fw_image).unwrap(); let gen = ImageGenerator::new(Crypto::default()); let vendor_pubkey_info_digest = gen.vendor_pubkey_info_digest(&manifest.preamble).unwrap(); let fuses = caliptra_hw_model::Fuses { //field_entropy vendor_pk_hash: vendor_pubkey_info_digest, life_cycle: DeviceLifecycle::Production, ..Default::default() }; let security_state = *SecurityState::default() .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production); let mut hw = fips_test_init_to_rt( Some(InitParams { fuses, security_state, ..Default::default() }), Some(BootParams { fw_image: Some(&fw_image), ..Default::default() }), ); // Perform all the SSP access attempts attempt_ssp_access(&mut hw); } #[test] pub fn zeroize_check_inaccessible() { let mut hw = fips_test_init_to_rt(None, None); // SHUTDOWN/Zeroize crate::services::exec_cmd_shutdown(&mut hw); // Verify we cannot access the module verify_mbox_cmds_fail(&mut hw, CaliptraError::RUNTIME_SHUTDOWN.into()); // Perform all the SSP access attempts attempt_ssp_access(&mut hw); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/sha256_kat.rs
kat/src/sha256_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha256_kat.rs Abstract: File contains the Known Answer Tests (KAT) for SHA-256 cryptography operations. --*/ use caliptra_drivers::{Array4x8, CaliptraError, CaliptraResult, Sha256, Sha256Alg}; const EXPECTED_DIGEST: Array4x8 = Array4x8::new([ 0xe3b0c442, 0x98fc1c14, 0x9afbf4c8, 0x996fb924, 0x27ae41e4, 0x649b934c, 0xa495991b, 0x7852b855, ]); #[derive(Default, Debug)] pub struct Sha256Kat {} impl Sha256Kat { /// This function executes the Known Answer Tests (aka KAT) for SHA256. /// /// Test vector source: /// https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/shs/shabytetestvectors.zip /// /// # Arguments /// /// * `sha` - SHA2-256 Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, sha: &mut Sha256) -> CaliptraResult<()> { self.kat_no_data(sha) } fn kat_no_data(&self, sha: &mut Sha256) -> CaliptraResult<()> { let data = []; let digest = sha .digest(&data) .map_err(|_| CaliptraError::KAT_SHA256_DIGEST_FAILURE)?; if digest != EXPECTED_DIGEST { return Err(CaliptraError::KAT_SHA256_DIGEST_MISMATCH); } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/aes256cmac_kat.rs
kat/src/aes256cmac_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: aes256gcm_kat.rs Abstract: File contains the Known Answer Tests (KAT) for AES-256-CMAC cryptography operations. --*/ use caliptra_drivers::{Aes, AesKey, CaliptraError, CaliptraResult, LEArray4x4, LEArray4x8}; // FROM ACVP test vector: // { // "tgId": 21, // "testType": "AFT", // "direction": "gen", // "keyLen": 256, // "msgLen": 0, // "macLen": 128, // "tests": [ // { // "tcId": 161, // "key": "699A4FCEF53E9FA9236EBCAA0A142270722F0D1045F6C3812D82A9E2564CFAD8", // "message": "" // }, // ... // { // "tgId": 21, // "tests": [ // { // "tcId": 161, // "mac": "43108180C8C4FD4D94C511FE0B084629" // }, const KEY: LEArray4x8 = LEArray4x8::new([ 0xce4f9a69, 0xa99f3ef5, 0xaabc6e23, 0x7022140a, 0x100d2f72, 0x81c3f645, 0xe2a9822d, 0xd8fa4c56, ]); const EXPECTED_MAC: LEArray4x4 = LEArray4x4::new([0x80811043u32, 0x4dfdc4c8u32, 0xfe11c594u32, 0x2946080bu32]); #[derive(Default, Debug)] pub struct Aes256CmacKat {} impl Aes256CmacKat { /// This function executes the Known Answer Tests (aka KAT) for AES-256-CMAC. /// /// Test vector source: /// NIST test vectors /// /// # Arguments /// /// * `aes` - AES driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, aes: &mut Aes) -> CaliptraResult<()> { let mac = aes.cmac(AesKey::Array(&KEY), &[])?; if mac != EXPECTED_MAC { Err(CaliptraError::KAT_AES_CIPHERTEXT_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/hkdf_kat.rs
kat/src/hkdf_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: hmac_kdf_kat.rs Abstract: File contains the Known Answer Tests (KAT) for HKDF Extract and Expand using HMAC-384 and HMAC-512. --*/ use caliptra_drivers::{ hkdf_expand, hkdf_extract, Array4x12, Array4x16, CaliptraError, CaliptraResult, Hmac, HmacMode, Trng, }; const KI_384: [u8; 48] = [ 0x2f, 0x0f, 0x2e, 0x94, 0x19, 0x44, 0x7b, 0x12, 0x2c, 0x2d, 0x62, 0xe9, 0xcc, 0x51, 0x16, 0x86, 0xed, 0x6d, 0x04, 0x4f, 0x67, 0xaa, 0x49, 0x95, 0x6a, 0x79, 0x54, 0xe5, 0xbb, 0x7e, 0xe7, 0xa6, 0x8d, 0x19, 0x93, 0xcc, 0xa0, 0xcc, 0xb3, 0xaf, 0x29, 0x78, 0xc3, 0xb9, 0x5d, 0x04, 0xc9, 0x09, ]; const KI_512: [u8; 64] = [ 0xd5, 0x58, 0x05, 0x7f, 0x2b, 0xdd, 0x1d, 0x69, 0xbb, 0xbc, 0x10, 0x9f, 0xfd, 0x0d, 0xdf, 0x8f, 0xa5, 0xdf, 0x35, 0xc0, 0xd5, 0xe7, 0xad, 0xb5, 0x70, 0x5d, 0xda, 0xa5, 0x07, 0x40, 0x30, 0x8c, 0x98, 0xbf, 0x99, 0x3c, 0x6d, 0xa6, 0x2e, 0x0c, 0x56, 0xd8, 0x2c, 0x30, 0x74, 0x04, 0xfd, 0x14, 0xbd, 0xc6, 0x36, 0x2f, 0x97, 0x16, 0xe6, 0x15, 0x00, 0x1f, 0x9f, 0xcf, 0x85, 0x23, 0x05, 0x0a, ]; #[derive(Default, Debug)] pub struct Hkdf384Kat {} impl Hkdf384Kat { /// This function executes the Known Answer Tests (aka KAT) for HKDF with HMAC-SHA384. /// /// # Arguments /// /// * `hmac` - HMAC Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { self.hkdf_extract_kat_nist_vector(hmac, trng)?; self.hkdf_expand_kat_nist_vector(hmac, trng)?; Ok(()) } /// This function executes the Known Answer Tests (aka KAT) for HKDF-Extract with HMAC-SHA384. /// /// Test vector source: /// Python script: (No NIST test vectors available.) /// >>> import hashlib /// >>> import hmac /// >>> key = bytes.fromhex("2f0f2e9419447b122c2d62e9cc511686ed6d044f67aa49956a7954e5bb7ee7a68d1993cca0ccb3af2978c3b95d04c909") /// >>> print(hmac.new(b"", key, hashlib.sha384).hexdigest()) /// /// 5a93140871c1301c2f55cb4e720e02d29f12bc8f7738a0d86a1cfb96fe014efd126f226adeb887f5982be71d998973fd /// /// # Arguments /// /// * `hmac` - HMAC-384 Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. fn hkdf_extract_kat_nist_vector(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { const EXPECTED: [u8; 48] = [ 0x24, 0x14, 0xda, 0x94, 0x53, 0xbf, 0x5e, 0x6e, 0xea, 0xe9, 0xf8, 0xb5, 0xb6, 0x3c, 0xa0, 0xff, 0x15, 0x0c, 0x47, 0xd2, 0x5f, 0x04, 0x28, 0x5b, 0x5c, 0xd4, 0xac, 0x75, 0x11, 0x06, 0x9a, 0xd8, 0x86, 0x03, 0xd1, 0xbe, 0x6e, 0xd7, 0xe0, 0x37, 0x41, 0x55, 0x44, 0x7f, 0xab, 0x69, 0xc5, 0x59, ]; let mut out = Array4x12::default(); hkdf_extract( hmac, &KI_384, &[], trng, (&mut out).into(), HmacMode::Hmac384, ) .map_err(|_| CaliptraError::KAT_HMAC384_FAILURE)?; if EXPECTED != <[u8; 48]>::from(out)[..EXPECTED.len()] { Err(CaliptraError::KAT_HMAC384_TAG_MISMATCH)?; } Ok(()) } /// This function executes the Known Answer Tests (aka KAT) for HKDF-Expand with HMAC-SHA384. /// /// Test vector source: /// https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Key-Derivation /// /// # Arguments /// /// * `hmac` - HMAC-384 Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. fn hkdf_expand_kat_nist_vector(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { // COUNT=39 // L = 320 // KI = 2f0f2e9419447b122c2d62e9cc511686ed6d044f67aa49956a7954e5bb7ee7a68d1993cca0ccb3af2978c3b95d04c909 // FixedInputDataByteLen = 60 // FixedInputData = 9a31c5deeb0304aabdb2d8cd0ebb82583b2b30db519c9413e2f7281a9ca4f8d919e8cdf1a518ed16788ec7a74d02724e0241e4f6b369297b1525f97a // Binary rep of i = 01 // instring = 9a31c5deeb0304aabdb2d8cd0ebb82583b2b30db519c9413e2f7281a9ca4f8d919e8cdf1a518ed16788ec7a74d02724e0241e4f6b369297b1525f97a01 // KO = d201f90262f79f11109047763ffaea2f5f3baf7fc5345c587fd2cde0d93a90ea43f5f321d52650c1 const KI_384: [u8; 48] = [ 0x2f, 0x0f, 0x2e, 0x94, 0x19, 0x44, 0x7b, 0x12, 0x2c, 0x2d, 0x62, 0xe9, 0xcc, 0x51, 0x16, 0x86, 0xed, 0x6d, 0x04, 0x4f, 0x67, 0xaa, 0x49, 0x95, 0x6a, 0x79, 0x54, 0xe5, 0xbb, 0x7e, 0xe7, 0xa6, 0x8d, 0x19, 0x93, 0xcc, 0xa0, 0xcc, 0xb3, 0xaf, 0x29, 0x78, 0xc3, 0xb9, 0x5d, 0x04, 0xc9, 0x09, ]; const FIXED_INFO: [u8; 60] = [ 0x9a, 0x31, 0xc5, 0xde, 0xeb, 0x03, 0x04, 0xaa, 0xbd, 0xb2, 0xd8, 0xcd, 0x0e, 0xbb, 0x82, 0x58, 0x3b, 0x2b, 0x30, 0xdb, 0x51, 0x9c, 0x94, 0x13, 0xe2, 0xf7, 0x28, 0x1a, 0x9c, 0xa4, 0xf8, 0xd9, 0x19, 0xe8, 0xcd, 0xf1, 0xa5, 0x18, 0xed, 0x16, 0x78, 0x8e, 0xc7, 0xa7, 0x4d, 0x02, 0x72, 0x4e, 0x02, 0x41, 0xe4, 0xf6, 0xb3, 0x69, 0x29, 0x7b, 0x15, 0x25, 0xf9, 0x7a, ]; const KO: [u8; 40] = [ 0xd2, 0x01, 0xf9, 0x02, 0x62, 0xf7, 0x9f, 0x11, 0x10, 0x90, 0x47, 0x76, 0x3f, 0xfa, 0xea, 0x2f, 0x5f, 0x3b, 0xaf, 0x7f, 0xc5, 0x34, 0x5c, 0x58, 0x7f, 0xd2, 0xcd, 0xe0, 0xd9, 0x3a, 0x90, 0xea, 0x43, 0xf5, 0xf3, 0x21, 0xd5, 0x26, 0x50, 0xc1, ]; let mut out = Array4x12::default(); let ki: Array4x12 = Array4x12::from(&KI_384); hkdf_expand( hmac, (&ki).into(), &FIXED_INFO, trng, (&mut out).into(), HmacMode::Hmac384, ) .map_err(|_| CaliptraError::KAT_HMAC384_FAILURE)?; if KO != <[u8; 48]>::from(out)[..KO.len()] { Err(CaliptraError::KAT_HMAC384_TAG_MISMATCH)?; } Ok(()) } } #[derive(Default, Debug)] pub struct Hkdf512Kat {} impl Hkdf512Kat { /// This function executes the Known Answer Tests (aka KAT) for HKDF with HMAC-SHA512. /// /// Test vector source: /// https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Key-Derivation /// /// # Arguments /// /// * `hmac` - HMAC Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { self.hkdf_extract_kat_nist_vector(hmac, trng)?; self.hkdf_expand_kat_nist_vector(hmac, trng)?; Ok(()) } /// This function executes the Known Answer Tests (aka KAT) for HKDF-Extract with HMAC-SHA512. /// /// Test vector source: /// Python script: (No NIST test vectors available.) /// >>> import hashlib /// >>> import hmac /// >>> key = bytes.fromhex("d558057f2bdd1d69bbbc109ffd0ddf8fa5df35c0d5e7adb5705ddaa50740308c98bf993c6da62e0c56d82c307404fd14bdc6362f9716e615001f9fcf8523050a") /// >>> print(hmac.new(b"", key, hashlib.sha512).hexdigest()) /// /// 8ed0c3c9a36e122ed29fab9ec3963fabd084d86b689a159c3f0927f71f26070696718a738cc97fb954ea12e64cd5bc4b40ab4b55b8c0dde35db63c8612e377cf /// /// # Arguments /// /// * `hmac` - HMAC Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. fn hkdf_extract_kat_nist_vector(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { const EXPECTED: [u8; 64] = [ 0x8e, 0xd0, 0xc3, 0xc9, 0xa3, 0x6e, 0x12, 0x2e, 0xd2, 0x9f, 0xab, 0x9e, 0xc3, 0x96, 0x3f, 0xab, 0xd0, 0x84, 0xd8, 0x6b, 0x68, 0x9a, 0x15, 0x9c, 0x3f, 0x09, 0x27, 0xf7, 0x1f, 0x26, 0x07, 0x06, 0x96, 0x71, 0x8a, 0x73, 0x8c, 0xc9, 0x7f, 0xb9, 0x54, 0xea, 0x12, 0xe6, 0x4c, 0xd5, 0xbc, 0x4b, 0x40, 0xab, 0x4b, 0x55, 0xb8, 0xc0, 0xdd, 0xe3, 0x5d, 0xb6, 0x3c, 0x86, 0x12, 0xe3, 0x77, 0xcf, ]; let mut out = Array4x16::default(); hkdf_extract( hmac, &KI_512, &[], trng, (&mut out).into(), HmacMode::Hmac512, ) .map_err(|_| CaliptraError::KAT_HMAC384_FAILURE)?; if EXPECTED != <[u8; 64]>::from(out)[..EXPECTED.len()] { Err(CaliptraError::KAT_HMAC384_TAG_MISMATCH)?; } Ok(()) } /// Performs KDF generation with a single fixed input data buffer. /// /// Test vector source: /// https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Key-Derivation /// /// # Arguments /// /// * `hmac` - HMAC Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. fn hkdf_expand_kat_nist_vector(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { // COUNT=39 // L = 320 // KI = d558057f2bdd1d69bbbc109ffd0ddf8fa5df35c0d5e7adb5705ddaa50740308c98bf993c6da62e0c56d82c307404fd14bdc6362f9716e615001f9fcf8523050a // FixedInputDataByteLen = 60 // FixedInputData = 7a4cad59057380a1f8979c960e8e2d07ce5260e6f94b0a77eb1fc59b4d87a6c6a94155f3c3c9d5565d0c7214a24b78dfcad23c69d7c064f46378c5fb // Binary rep of i = 01 // instring = 7a4cad59057380a1f8979c960e8e2d07ce5260e6f94b0a77eb1fc59b4d87a6c6a94155f3c3c9d5565d0c7214a24b78dfcad23c69d7c064f46378c5fb01 // KO = e0d67286cc618d06db2a67b4e8c4455cf802efc4d93edbe63aeffa777601821c42405ae6eec3a874 const FIXED_INPUT: [u8; 60] = [ 0x7a, 0x4c, 0xad, 0x59, 0x05, 0x73, 0x80, 0xa1, 0xf8, 0x97, 0x9c, 0x96, 0x0e, 0x8e, 0x2d, 0x07, 0xce, 0x52, 0x60, 0xe6, 0xf9, 0x4b, 0x0a, 0x77, 0xeb, 0x1f, 0xc5, 0x9b, 0x4d, 0x87, 0xa6, 0xc6, 0xa9, 0x41, 0x55, 0xf3, 0xc3, 0xc9, 0xd5, 0x56, 0x5d, 0x0c, 0x72, 0x14, 0xa2, 0x4b, 0x78, 0xdf, 0xca, 0xd2, 0x3c, 0x69, 0xd7, 0xc0, 0x64, 0xf4, 0x63, 0x78, 0xc5, 0xfb, ]; const KO: [u8; 40] = [ 0xe0, 0xd6, 0x72, 0x86, 0xcc, 0x61, 0x8d, 0x06, 0xdb, 0x2a, 0x67, 0xb4, 0xe8, 0xc4, 0x45, 0x5c, 0xf8, 0x02, 0xef, 0xc4, 0xd9, 0x3e, 0xdb, 0xe6, 0x3a, 0xef, 0xfa, 0x77, 0x76, 0x01, 0x82, 0x1c, 0x42, 0x40, 0x5a, 0xe6, 0xee, 0xc3, 0xa8, 0x74, ]; let mut out = Array4x16::default(); let ki: Array4x16 = Array4x16::from(&KI_512); hkdf_expand( hmac, (&ki).into(), &FIXED_INPUT, trng, (&mut out).into(), HmacMode::Hmac512, ) .map_err(|_| CaliptraError::KAT_HMAC384_FAILURE)?; if KO != <[u8; 64]>::from(out)[..KO.len()] { Err(CaliptraError::KAT_HMAC384_TAG_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/aes256gcm_kat.rs
kat/src/aes256gcm_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: aes256gcm_kat.rs Abstract: File contains the Known Answer Tests (KAT) for AES-256-GCM cryptography operations. --*/ use caliptra_drivers::{ Aes, AesKey, CaliptraError, CaliptraResult, LEArray4x3, LEArray4x4, LEArray4x8, Trng, }; // Taken from NIST test vectors: https://csrc.nist.gov/Projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes#GCMVS // KEY = f0eaf7b41b42f4500635bc05d9cede11a5363d59a6288870f527bcffeb4d6e04 // IV = 18f316781077a595c72d4c07 // CT = 7a1b61009dce6b7cd4d1ea0203b179f1219dd5ce7407e12ea0a4c56c71bb791b // AAD = 42cade3a19204b7d4843628c425c2375 // Tag = 4419180b0b963b7289a4fa3f45c535a3 // PT = 400fb5ef32083b3abea957c4f068abad50c8d86bbf9351fa72e7da5171df38f9 const KEY: LEArray4x8 = LEArray4x8::new([ 0xb4f7eaf0, 0x50f4421b, 0x05bc3506, 0x11deced9, 0x593d36a5, 0x708828a6, 0xffbc27f5, 0x046e4deb, ]); const IV: LEArray4x3 = LEArray4x3::new([0x7816f318, 0x95a57710, 0x074c2dc7]); const CT: [u8; 32] = [ 0x7a, 0x1b, 0x61, 0x0, 0x9d, 0xce, 0x6b, 0x7c, 0xd4, 0xd1, 0xea, 0x2, 0x3, 0xb1, 0x79, 0xf1, 0x21, 0x9d, 0xd5, 0xce, 0x74, 0x7, 0xe1, 0x2e, 0xa0, 0xa4, 0xc5, 0x6c, 0x71, 0xbb, 0x79, 0x1b, ]; const AAD: [u8; 16] = [ 0x42, 0xca, 0xde, 0x3a, 0x19, 0x20, 0x4b, 0x7d, 0x48, 0x43, 0x62, 0x8c, 0x42, 0x5c, 0x23, 0x75, ]; const TAG: LEArray4x4 = LEArray4x4::new([0x0b181944, 0x723b960b, 0x3ffaa489, 0xa335c545]); const PT: [u8; 32] = [ 0x40, 0xf, 0xb5, 0xef, 0x32, 0x8, 0x3b, 0x3a, 0xbe, 0xa9, 0x57, 0xc4, 0xf0, 0x68, 0xab, 0xad, 0x50, 0xc8, 0xd8, 0x6b, 0xbf, 0x93, 0x51, 0xfa, 0x72, 0xe7, 0xda, 0x51, 0x71, 0xdf, 0x38, 0xf9, ]; #[derive(Default, Debug)] pub struct Aes256GcmKat {} impl Aes256GcmKat { /// This function executes the Known Answer Tests (aka KAT) for AES-256-GCM. /// /// Test vector source: /// NIST test vectors /// /// # Arguments /// /// * `aes` - AES driver /// * `trng` - TRNG driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, aes: &mut Aes, trng: &mut Trng) -> CaliptraResult<()> { self.encrypt_decrypt(aes, trng) } fn encrypt_decrypt(&self, aes: &mut Aes, trng: &mut Trng) -> CaliptraResult<()> { let iv = (&IV).into(); let key = AesKey::Array(&KEY); let mut ciphertext = [0u8; 32]; let (_, tag) = aes.aes_256_gcm_encrypt(trng, iv, key, &AAD[..], &PT[..], &mut ciphertext, 16)?; if ciphertext != CT { Err(CaliptraError::KAT_AES_CIPHERTEXT_MISMATCH)?; } if tag != TAG { Err(CaliptraError::KAT_AES_TAG_MISMATCH)?; } let mut plaintext = [0u8; 32]; aes.aes_256_gcm_decrypt(trng, &IV, key, &AAD[..], &CT[..], &mut plaintext, &TAG)?; if plaintext != PT { Err(CaliptraError::KAT_AES_PLAINTEXT_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/kats_env.rs
kat/src/kats_env.rs
// Licensed under the Apache-2.0 license use caliptra_drivers::{ Aes, Ecc384, Hmac, Lms, Mldsa87, Sha1, Sha256, Sha2_512_384, Sha2_512_384Acc, Sha3, ShaAccLockState, Trng, }; pub struct KatsEnv<'a> { // SHA1 Engine pub sha1: &'a mut Sha1, // SHA2-256 Engine pub sha256: &'a mut Sha256, // SHA2-512/384 Engine pub sha2_512_384: &'a mut Sha2_512_384, // SHA2-512/384 Accelerator pub sha2_512_384_acc: &'a mut Sha2_512_384Acc, // SHA3/SHAKE Engine pub sha3: &'a mut Sha3, /// Hmac-512/384 Engine pub hmac: &'a mut Hmac, /// Cryptographically Secure Random Number Generator pub trng: &'a mut Trng, /// LMS Engine pub lms: &'a mut Lms, /// Ecc384 Engine pub ecc384: &'a mut Ecc384, /// SHA Acc Lock State pub sha_acc_lock_state: ShaAccLockState, /// MLDSA Engine pub mldsa87: &'a mut Mldsa87, /// AES Engine //#[cfg(feature = "runtime")] pub aes: &'a mut Aes, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/lms_kat.rs
kat/src/lms_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: lms_kat.rs Abstract: File contains the Known Answer Tests (KAT) for LMS cryptography operations. --*/ use caliptra_drivers::{CaliptraError, CaliptraResult, Lms, LmsResult, Sha256}; use caliptra_lms_types::{ bytes_to_words_6, LmotsAlgorithmType, LmotsSignature, LmsAlgorithmType, LmsIdentifier, LmsPublicKey, LmsSignature, }; use zerocopy::{BigEndian, LittleEndian, U32}; #[derive(Default, Debug)] pub struct LmsKat {} impl LmsKat { /// This function executes the Known Answer Tests (aka KAT) for LMS. pub fn execute(&self, sha256_driver: &mut Sha256, lms: &mut Lms) -> CaliptraResult<()> { let result = self.kat_lms_24(sha256_driver, lms); lms.mark_kat_complete(); result } /// This calls execute only if it has not completed before pub fn execute_once(&self, sha256_driver: &mut Sha256, lms: &mut Lms) -> CaliptraResult<()> { if !lms.kat_is_complete() { self.execute(sha256_driver, lms) } else { Ok(()) } } fn kat_lms_24(&self, sha256_driver: &mut Sha256, lms: &Lms) -> CaliptraResult<()> { const MESSAGE: [u8; 8] = [0, 0, 30, 76, 217, 179, 51, 230]; const LMS_TYPE: LmsAlgorithmType = LmsAlgorithmType::LmsSha256N24H15; const LMOTS_TYPE: LmotsAlgorithmType = LmotsAlgorithmType::LmotsSha256N24W4; const Q: U32<BigEndian> = U32::ZERO; const LMS_IDENTIFIER: LmsIdentifier = [ 97, 165, 213, 125, 55, 245, 228, 107, 251, 117, 32, 128, 107, 7, 161, 184, ]; const LMS_PUBLIC_HASH: [U32<LittleEndian>; 6] = bytes_to_words_6([ 0xf6, 0xb6, 0xac, 0x88, 0xd6, 0xbf, 0x10, 0x62, 0x13, 0x03, 0x85, 0x8a, 0x85, 0x4e, 0x19, 0xcb, 0xbc, 0x7f, 0xb6, 0x3c, 0xeb, 0x80, 0x44, 0xfb, ]); const NONCE: [U32<LittleEndian>; 6] = [U32::ZERO; 6]; const Y: [[U32<LittleEndian>; 6]; 51] = [ bytes_to_words_6([ 0x0a, 0x03, 0xc9, 0x4b, 0xb4, 0xb3, 0x1f, 0x2f, 0xaa, 0x24, 0xd1, 0xbd, 0xcc, 0x4f, 0xef, 0xda, 0x59, 0x83, 0x22, 0x10, 0xc5, 0xa4, 0x0e, 0x8f, ]), bytes_to_words_6([ 0xdc, 0xb4, 0x87, 0xc4, 0x5d, 0x23, 0xb6, 0x4d, 0x38, 0xf4, 0xc8, 0x09, 0xfd, 0x09, 0xd2, 0xbd, 0xa8, 0xaa, 0x0f, 0xf6, 0x0f, 0xc4, 0x71, 0x81, ]), bytes_to_words_6([ 0xf9, 0x8f, 0xaf, 0x2c, 0x69, 0x31, 0x89, 0xd7, 0x1e, 0xdb, 0x87, 0xf6, 0xa5, 0x8c, 0x01, 0x02, 0x77, 0xa7, 0x76, 0x67, 0xe3, 0x81, 0xf1, 0x38, ]), bytes_to_words_6([ 0xe8, 0x97, 0xe1, 0x09, 0xc2, 0x9a, 0xa3, 0x26, 0x54, 0xe4, 0x32, 0xda, 0x3b, 0x3e, 0x25, 0x45, 0x4f, 0x6b, 0xce, 0xd7, 0x88, 0x07, 0xe9, 0x52, ]), bytes_to_words_6([ 0xf2, 0xf4, 0x48, 0x3d, 0xe4, 0x7b, 0xee, 0x24, 0xc8, 0x24, 0xb7, 0x66, 0xdb, 0x5d, 0x50, 0x10, 0x2e, 0xbe, 0xa7, 0x56, 0x73, 0x8a, 0x10, 0x52, ]), bytes_to_words_6([ 0xfe, 0x65, 0x0e, 0xe9, 0xc5, 0x8e, 0x5c, 0xdd, 0xd0, 0x01, 0x70, 0xca, 0x0c, 0x31, 0x35, 0x41, 0x01, 0x0c, 0x2c, 0xf2, 0xd0, 0x2c, 0x50, 0x44, ]), bytes_to_words_6([ 0x9c, 0x47, 0x81, 0x51, 0x5d, 0xaf, 0x9c, 0xb1, 0x2e, 0xe7, 0xec, 0xa4, 0x6f, 0x15, 0x40, 0x6d, 0x2b, 0x7a, 0x3a, 0x68, 0xd1, 0xc1, 0xbc, 0x43, ]), bytes_to_words_6([ 0x94, 0x6c, 0xa9, 0x9f, 0x4d, 0xea, 0x75, 0x13, 0xf6, 0x0c, 0x29, 0x7d, 0x4f, 0xae, 0x9b, 0x6c, 0x33, 0x45, 0x7d, 0x1e, 0xda, 0xdc, 0xf0, 0xcf, ]), bytes_to_words_6([ 0x70, 0xf8, 0x74, 0x81, 0xf4, 0x6a, 0xbc, 0x67, 0x64, 0x7d, 0x22, 0xf4, 0x5d, 0x50, 0x10, 0x34, 0x5f, 0xa0, 0xf3, 0x5a, 0xe4, 0x4a, 0x31, 0x3a, ]), bytes_to_words_6([ 0x67, 0x64, 0x06, 0xf2, 0x97, 0xff, 0x53, 0x3e, 0x72, 0x12, 0x9e, 0x29, 0xbb, 0x4e, 0xc9, 0xcb, 0xa6, 0xfa, 0x9b, 0x8c, 0xd1, 0xdb, 0x8d, 0x0d, ]), bytes_to_words_6([ 0xa8, 0xa7, 0x9c, 0x6f, 0xf1, 0xcd, 0x58, 0xa4, 0x83, 0xfc, 0xbd, 0x35, 0xb6, 0x33, 0x2e, 0x9a, 0x89, 0x13, 0x94, 0xa5, 0xb6, 0x1f, 0xf3, 0x1a, ]), bytes_to_words_6([ 0x88, 0x65, 0xeb, 0x3e, 0x83, 0xf4, 0xed, 0xee, 0xd6, 0x15, 0x04, 0xc4, 0xbb, 0x5e, 0x30, 0xab, 0x81, 0x00, 0xfa, 0x9f, 0x99, 0x55, 0x7e, 0xf9, ]), bytes_to_words_6([ 0xb3, 0x0b, 0x61, 0xa4, 0x0e, 0xa0, 0x75, 0xb4, 0x1e, 0x95, 0x80, 0x49, 0xa7, 0x4f, 0xa4, 0xa5, 0xc4, 0x86, 0x54, 0xb8, 0xe0, 0x03, 0x61, 0x90, ]), bytes_to_words_6([ 0x07, 0x7c, 0x55, 0x0a, 0x59, 0xd5, 0xe4, 0xb4, 0xaa, 0x8a, 0x6b, 0xa6, 0x1b, 0x27, 0x02, 0x03, 0x1b, 0xfb, 0x19, 0xf2, 0x90, 0x42, 0x84, 0xb0, ]), bytes_to_words_6([ 0xb5, 0xbc, 0x90, 0xa7, 0xcf, 0x1a, 0x4a, 0x5b, 0xc2, 0xf2, 0x7e, 0xdd, 0x03, 0x57, 0x44, 0x67, 0x58, 0x9b, 0x2f, 0x72, 0xdd, 0x8c, 0x79, 0x5e, ]), bytes_to_words_6([ 0x2f, 0xcb, 0x15, 0xd7, 0x4c, 0x34, 0x73, 0x9b, 0x50, 0x3f, 0xd9, 0x0d, 0x5f, 0xdf, 0x49, 0xe3, 0x5c, 0x53, 0x9c, 0x9e, 0xd1, 0x83, 0x85, 0xaa, ]), bytes_to_words_6([ 0xb6, 0x19, 0x6f, 0xb0, 0xc7, 0x8f, 0x06, 0xcc, 0xba, 0x32, 0x65, 0x46, 0xeb, 0x2c, 0xaf, 0xb8, 0x92, 0x07, 0x8a, 0xd0, 0xa0, 0xe1, 0x07, 0x8a, ]), bytes_to_words_6([ 0x86, 0x37, 0xed, 0xdc, 0x0b, 0xce, 0xdb, 0x77, 0x11, 0x37, 0x0a, 0x16, 0x5f, 0xfe, 0x0c, 0x67, 0x79, 0xd1, 0x54, 0x78, 0x40, 0x98, 0x60, 0x10, ]), bytes_to_words_6([ 0x12, 0x9c, 0x66, 0x89, 0x47, 0xbf, 0x4d, 0xea, 0x6c, 0x8b, 0xfd, 0xa7, 0x05, 0xfb, 0x33, 0x8d, 0xf9, 0xc2, 0xe0, 0x2d, 0xfd, 0xb3, 0xe6, 0x1b, ]), bytes_to_words_6([ 0x2c, 0xae, 0x80, 0x41, 0x1e, 0x33, 0x49, 0x64, 0x5b, 0x55, 0x6b, 0xff, 0xea, 0xa8, 0x89, 0x33, 0x9b, 0xc6, 0xa5, 0xa3, 0x14, 0x95, 0x96, 0x98, ]), bytes_to_words_6([ 0x31, 0x54, 0xa1, 0x95, 0x7a, 0x87, 0x93, 0x7f, 0x17, 0x4e, 0x2c, 0xb5, 0xfd, 0xff, 0x62, 0xd9, 0xe0, 0xc8, 0xce, 0x45, 0x90, 0xcf, 0xb6, 0x8e, ]), bytes_to_words_6([ 0x2e, 0x87, 0x10, 0x6b, 0x25, 0xb7, 0x89, 0x33, 0x77, 0xaa, 0x71, 0xd6, 0x43, 0xe9, 0xdb, 0x06, 0xab, 0xd9, 0xbd, 0x59, 0x47, 0x54, 0xcc, 0x54, ]), bytes_to_words_6([ 0xff, 0xd9, 0x58, 0xb3, 0x20, 0x35, 0xd8, 0x1f, 0xf5, 0xb2, 0xfd, 0x2b, 0xab, 0x3e, 0xc8, 0x36, 0x74, 0x67, 0xe2, 0x43, 0xe5, 0xff, 0xb3, 0x62, ]), bytes_to_words_6([ 0x79, 0xf1, 0x4f, 0x99, 0x1a, 0xb3, 0x29, 0x3a, 0x36, 0x4d, 0xc5, 0xe7, 0xf0, 0xb1, 0x04, 0x1c, 0x8e, 0x45, 0x58, 0xe9, 0x21, 0x45, 0xbb, 0x51, ]), bytes_to_words_6([ 0x0c, 0xf5, 0x05, 0x0a, 0xb0, 0x57, 0x8c, 0x1f, 0x9c, 0xd3, 0x96, 0x4d, 0x46, 0x41, 0x9d, 0x88, 0x8b, 0xd8, 0x8d, 0x01, 0x73, 0x2c, 0x51, 0xeb, ]), bytes_to_words_6([ 0x4b, 0x03, 0xe5, 0xf2, 0x6c, 0x89, 0x40, 0x4e, 0xb1, 0x03, 0xe6, 0x1a, 0x85, 0x57, 0x50, 0x0d, 0x7c, 0xaa, 0x2e, 0x70, 0xac, 0xde, 0x1f, 0xb4, ]), bytes_to_words_6([ 0xae, 0xe2, 0xa8, 0xfd, 0x0f, 0x78, 0x97, 0x6f, 0xcc, 0x27, 0x1c, 0x90, 0x98, 0x91, 0x0b, 0xd2, 0x48, 0x5c, 0xff, 0xb1, 0x6d, 0xa0, 0x72, 0xcf, ]), bytes_to_words_6([ 0x51, 0x73, 0x8e, 0x2c, 0xf4, 0xf8, 0x6a, 0x6c, 0xc3, 0xe1, 0x30, 0x77, 0x37, 0xdc, 0x75, 0x91, 0xa2, 0x59, 0x2d, 0x38, 0xe7, 0x43, 0x5c, 0xc7, ]), bytes_to_words_6([ 0x60, 0x06, 0x86, 0x5b, 0x90, 0x20, 0x82, 0xe1, 0x5c, 0x46, 0xbb, 0x70, 0x52, 0x97, 0x90, 0x8f, 0x78, 0xc8, 0xfb, 0xe8, 0xe8, 0x93, 0x5d, 0x30, ]), bytes_to_words_6([ 0x20, 0xcc, 0xda, 0xf0, 0x33, 0x59, 0x85, 0xa0, 0xb6, 0xe6, 0x08, 0x0d, 0x2a, 0xf4, 0x10, 0x38, 0x6b, 0x6e, 0xfc, 0x40, 0xef, 0xe9, 0xe7, 0x69, ]), bytes_to_words_6([ 0x1d, 0x16, 0xcf, 0xe2, 0x12, 0x80, 0xa5, 0x66, 0x1c, 0x11, 0x10, 0xc8, 0xfc, 0x62, 0x67, 0xda, 0x33, 0x83, 0x2d, 0xe9, 0xdc, 0x04, 0xce, 0xc9, ]), bytes_to_words_6([ 0xe3, 0x6b, 0xa5, 0xc6, 0x4c, 0x67, 0xf8, 0xb0, 0xdc, 0xef, 0xe7, 0xd2, 0xcf, 0xb8, 0xfa, 0xf1, 0xe8, 0x56, 0x73, 0x2a, 0xf5, 0x0a, 0x82, 0x3e, ]), bytes_to_words_6([ 0x25, 0x10, 0x89, 0x48, 0x2b, 0x75, 0x9c, 0xa8, 0xce, 0x35, 0x68, 0xb7, 0x13, 0xc6, 0xa4, 0x0e, 0x1c, 0xad, 0xbd, 0x35, 0x4a, 0xe1, 0x1c, 0x33, ]), bytes_to_words_6([ 0x8c, 0x0d, 0x27, 0xb6, 0xb6, 0x02, 0x29, 0xee, 0x81, 0x63, 0x6a, 0xeb, 0xc0, 0x99, 0x86, 0x22, 0x57, 0xfa, 0xf9, 0xbc, 0x1f, 0x58, 0x20, 0xf7, ]), bytes_to_words_6([ 0xd4, 0x27, 0x1d, 0x9f, 0x9b, 0x3d, 0x92, 0xa8, 0x8c, 0x0c, 0x76, 0x3e, 0xa9, 0xc3, 0x7e, 0xd7, 0xc6, 0x79, 0x64, 0x0f, 0x83, 0x90, 0xdd, 0x97, ]), bytes_to_words_6([ 0x65, 0x2f, 0xa1, 0x29, 0x3e, 0xb8, 0xc1, 0xad, 0xf9, 0x01, 0xe9, 0x61, 0xaa, 0x1e, 0x88, 0xdc, 0x0e, 0x58, 0x46, 0xba, 0x3f, 0xb1, 0x45, 0xc6, ]), bytes_to_words_6([ 0xb4, 0x69, 0x66, 0xd3, 0xdc, 0xd2, 0x4e, 0xc8, 0xbf, 0xf7, 0xa1, 0x40, 0x97, 0x37, 0x9b, 0xe0, 0x70, 0x85, 0x12, 0x6b, 0x4d, 0x66, 0x33, 0x26, ]), bytes_to_words_6([ 0xa6, 0xe6, 0x4e, 0x71, 0x6e, 0x63, 0x35, 0x16, 0x9c, 0xfe, 0x20, 0x14, 0x9b, 0xee, 0xcb, 0xc3, 0xdd, 0xfb, 0xf7, 0x99, 0xe3, 0xa0, 0x18, 0x7d, ]), bytes_to_words_6([ 0x6d, 0x36, 0x5e, 0xa6, 0xcc, 0xd8, 0x18, 0xad, 0x8a, 0xd8, 0x43, 0x62, 0xe5, 0x09, 0x1e, 0xaf, 0xb4, 0xe5, 0x19, 0xdc, 0x18, 0x08, 0x5a, 0xe9, ]), bytes_to_words_6([ 0x57, 0x65, 0x1f, 0xff, 0x94, 0x8b, 0x38, 0x80, 0xb9, 0xcf, 0x08, 0x1d, 0x8d, 0x1b, 0x36, 0xda, 0xb0, 0x59, 0x14, 0x58, 0x28, 0x1c, 0x30, 0x16, ]), bytes_to_words_6([ 0x2b, 0xa9, 0x94, 0x9a, 0x2a, 0x8a, 0xa0, 0x43, 0x2e, 0xf1, 0xf9, 0x98, 0x35, 0x6d, 0x85, 0x5b, 0xa6, 0xbc, 0x62, 0x4f, 0x56, 0x6e, 0x42, 0xb3, ]), bytes_to_words_6([ 0x78, 0x6f, 0x52, 0xf5, 0x45, 0x39, 0xfa, 0x0d, 0x1d, 0x29, 0xf8, 0xe5, 0xd8, 0x8a, 0xb4, 0x1d, 0x54, 0xe7, 0x91, 0x84, 0xd4, 0xfb, 0xcc, 0x83, ]), bytes_to_words_6([ 0xa2, 0x21, 0xbf, 0x3a, 0x08, 0x45, 0xf7, 0xbb, 0x1a, 0x05, 0x1d, 0x59, 0x59, 0xd5, 0xea, 0x7b, 0xdf, 0x95, 0x3b, 0x37, 0x3b, 0x9a, 0x9d, 0xb2, ]), bytes_to_words_6([ 0x83, 0xd3, 0x4a, 0xea, 0x0e, 0x84, 0x24, 0xfe, 0x8a, 0x8c, 0x9f, 0xb2, 0x3b, 0xb7, 0xd3, 0x4a, 0x6d, 0x07, 0xef, 0x9e, 0x76, 0xc7, 0xd9, 0xe0, ]), bytes_to_words_6([ 0xe6, 0x68, 0x81, 0xf9, 0x51, 0x8c, 0x7f, 0xae, 0xbf, 0x89, 0xa0, 0xc3, 0xcd, 0x55, 0xe6, 0x9a, 0x3f, 0x93, 0xdc, 0x01, 0xc6, 0x1c, 0x4f, 0xc0, ]), bytes_to_words_6([ 0x88, 0xd0, 0xc9, 0x89, 0xec, 0xc6, 0x25, 0x19, 0xd3, 0x02, 0x83, 0x70, 0x50, 0xa7, 0x31, 0x96, 0x62, 0xb2, 0xcb, 0x5d, 0x72, 0x5d, 0xcc, 0x96, ]), bytes_to_words_6([ 0x33, 0x2a, 0xe6, 0x80, 0x06, 0x87, 0x71, 0x13, 0xf9, 0x78, 0x1e, 0x4f, 0x61, 0xba, 0x17, 0x9f, 0x04, 0x11, 0x67, 0xd1, 0xc2, 0xee, 0x29, 0x5e, ]), bytes_to_words_6([ 0xe5, 0x3d, 0xba, 0x38, 0x3f, 0xe4, 0xe5, 0x1f, 0x53, 0x6b, 0xb3, 0x23, 0x9c, 0x03, 0x34, 0xae, 0x8f, 0x39, 0x72, 0xbd, 0x24, 0x25, 0x37, 0x9f, ]), bytes_to_words_6([ 0xd0, 0xb0, 0xd9, 0x2a, 0x78, 0xf9, 0xeb, 0xa9, 0x64, 0x8b, 0x3a, 0x9f, 0x3b, 0xca, 0x44, 0xa3, 0xba, 0xf8, 0x36, 0x32, 0x6d, 0x42, 0x20, 0x6d, ]), bytes_to_words_6([ 0x5a, 0x8c, 0x8e, 0xb1, 0x8f, 0xbf, 0x5b, 0xf2, 0x8d, 0xa4, 0x9b, 0x7d, 0x2e, 0x89, 0xc1, 0x57, 0x62, 0x45, 0x87, 0xd7, 0x28, 0x0b, 0x93, 0x82, ]), bytes_to_words_6([ 0x2f, 0xac, 0xcc, 0x4e, 0x1e, 0xfd, 0xb4, 0xbf, 0xe7, 0xe7, 0x73, 0xd8, 0x9f, 0x35, 0xde, 0x74, 0x0c, 0x66, 0xa4, 0xc1, 0x43, 0x2d, 0xf7, 0x86, ]), ]; const PATH: [[U32<LittleEndian>; 6]; 15] = [ bytes_to_words_6([ 0x22, 0xa6, 0x0d, 0x20, 0x0a, 0x86, 0x38, 0xac, 0x4f, 0xe0, 0x98, 0x13, 0x34, 0x5b, 0x3b, 0x89, 0xe5, 0x4c, 0xf3, 0x92, 0x1d, 0x07, 0x6b, 0x1f, ]), bytes_to_words_6([ 0xcb, 0xbf, 0xbd, 0x1a, 0x2a, 0xb3, 0x72, 0x15, 0x6a, 0x52, 0xb8, 0x81, 0xa3, 0x40, 0xca, 0x6c, 0xd4, 0x58, 0xd5, 0xa0, 0xd9, 0x11, 0x0a, 0x1d, ]), bytes_to_words_6([ 0x46, 0xae, 0xa3, 0x45, 0x86, 0xe7, 0x18, 0xaf, 0x12, 0x6a, 0x9c, 0xa2, 0x2c, 0x3d, 0x3c, 0xdf, 0x10, 0xa5, 0x6b, 0x90, 0xe2, 0xf2, 0x71, 0x6e, ]), bytes_to_words_6([ 0x4b, 0x34, 0xa2, 0x69, 0x79, 0x05, 0x1b, 0x29, 0x16, 0xea, 0xda, 0x7d, 0x6e, 0x53, 0x48, 0x59, 0xbf, 0x02, 0x9c, 0x42, 0xdd, 0x79, 0xea, 0xcd, ]), bytes_to_words_6([ 0x68, 0xff, 0xa6, 0x67, 0x53, 0x0c, 0x99, 0x03, 0x65, 0x60, 0x38, 0xdc, 0x3a, 0x7f, 0x80, 0x22, 0xb7, 0x52, 0x06, 0x8b, 0x73, 0x1c, 0x83, 0x50, ]), bytes_to_words_6([ 0xb5, 0x94, 0xc4, 0x6e, 0x11, 0x1f, 0x69, 0x11, 0x3b, 0x4d, 0x4f, 0xee, 0xca, 0x5b, 0x91, 0x3b, 0x5a, 0x14, 0xe2, 0xda, 0x2a, 0xe0, 0x7a, 0x02, ]), bytes_to_words_6([ 0x56, 0x7c, 0x23, 0x36, 0x9a, 0x3c, 0x8b, 0x71, 0x79, 0xe7, 0x7e, 0xef, 0x0b, 0xd8, 0x38, 0x3a, 0x87, 0x74, 0x49, 0xf2, 0x8f, 0xd4, 0x54, 0xf8, ]), bytes_to_words_6([ 0x9e, 0x54, 0x4b, 0xc0, 0xa6, 0x6d, 0xd3, 0x70, 0x7c, 0xad, 0x3c, 0xbc, 0xa1, 0xae, 0x7c, 0xff, 0xa4, 0xcb, 0xa6, 0xd7, 0x3e, 0x90, 0x90, 0xed, ]), bytes_to_words_6([ 0xb1, 0x5f, 0x19, 0xe2, 0x03, 0x3b, 0xe4, 0x24, 0x61, 0x25, 0x12, 0x62, 0xc3, 0x0e, 0xac, 0x30, 0x92, 0x79, 0xc6, 0x5b, 0x03, 0x61, 0x79, 0xb8, ]), bytes_to_words_6([ 0x85, 0x4d, 0xc9, 0xa5, 0x8d, 0x70, 0x8f, 0x83, 0x61, 0xa4, 0x83, 0x7b, 0x4a, 0x3e, 0xfa, 0xdb, 0x8c, 0xa2, 0x3a, 0xaa, 0xb4, 0xcb, 0x69, 0xbe, ]), bytes_to_words_6([ 0x5a, 0x2d, 0xb9, 0xa9, 0x92, 0xd9, 0x7d, 0xf5, 0x3e, 0xd5, 0xcf, 0xba, 0x60, 0x6e, 0xa5, 0x60, 0xf8, 0x1a, 0x66, 0x4f, 0x51, 0xce, 0x47, 0xf8, ]), bytes_to_words_6([ 0x86, 0xf6, 0x80, 0x56, 0x37, 0xc8, 0x9e, 0xea, 0x6f, 0x64, 0x2f, 0x19, 0x3b, 0x67, 0xda, 0xfb, 0xd6, 0xfc, 0x4e, 0x87, 0x19, 0x15, 0x18, 0xc8, ]), bytes_to_words_6([ 0x85, 0x26, 0x32, 0xe9, 0x4e, 0xce, 0x78, 0xe3, 0xb9, 0xa4, 0x44, 0xf3, 0x19, 0x2e, 0x1a, 0x51, 0xf7, 0x9d, 0x69, 0x7d, 0x82, 0xf9, 0x7c, 0xd1, ]), bytes_to_words_6([ 0x44, 0xe2, 0xa3, 0xe1, 0x26, 0x82, 0xc9, 0x70, 0x91, 0x51, 0x69, 0x33, 0x6b, 0x3b, 0xb0, 0xda, 0x43, 0x30, 0xf5, 0x01, 0x0a, 0x3e, 0xc1, 0xbd, ]), bytes_to_words_6([ 0x33, 0x29, 0x53, 0x1c, 0xe7, 0x75, 0xdf, 0xdc, 0xf6, 0x64, 0x46, 0x28, 0x58, 0xfa, 0x61, 0xa7, 0x97, 0xb8, 0x2a, 0xb1, 0x88, 0xde, 0xca, 0xf1, ]), ]; const LMS_SIG: LmsSignature<6, 51, 15> = LmsSignature { q: Q, ots: LmotsSignature { ots_type: LMOTS_TYPE, nonce: NONCE, y: Y, }, tree_type: LMS_TYPE, tree_path: PATH, }; const LMS_PUBLIC_KEY: LmsPublicKey<6> = LmsPublicKey { id: LMS_IDENTIFIER, digest: LMS_PUBLIC_HASH, tree_type: LMS_TYPE, otstype: LMOTS_TYPE, }; let success = lms.verify_lms_signature(sha256_driver, &MESSAGE, &LMS_PUBLIC_KEY, &LMS_SIG)?; if success != LmsResult::Success { Err(CaliptraError::KAT_LMS_DIGEST_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/lib.rs
kat/src/lib.rs
/*++ Licensed under the Apache-2.0 license. File Name: lib.rs Abstract: File contains exports for the Caliptra Known Answer Tests. --*/ #![no_std] mod aes256cbc_kat; mod aes256cmac_kat; mod aes256ctr_kat; mod aes256ecb_kat; mod aes256gcm_kat; mod cmackdf_kat; mod ecc384_kat; mod ecdh_kat; mod hkdf_kat; mod hmac_kdf_kat; mod kats_env; mod lms_kat; mod mldsa87_kat; mod sha1_kat; mod sha256_kat; mod sha2_512_384acc_kat; mod sha384_kat; mod sha3_kat; mod sha512_kat; pub use aes256cbc_kat::Aes256CbcKat; pub use aes256cmac_kat::Aes256CmacKat; pub use aes256ctr_kat::Aes256CtrKat; pub use aes256ecb_kat::Aes256EcbKat; pub use aes256gcm_kat::Aes256GcmKat; pub use caliptra_drivers::{CaliptraError, CaliptraResult}; pub use cmackdf_kat::CmacKdfKat; pub use ecc384_kat::Ecc384Kat; pub use ecdh_kat::EcdhKat; pub use hkdf_kat::{Hkdf384Kat, Hkdf512Kat}; pub use hmac_kdf_kat::{Hmac384KdfKat, Hmac512KdfKat}; pub use kats_env::KatsEnv; pub use lms_kat::LmsKat; pub use mldsa87_kat::Mldsa87Kat; pub use sha1_kat::Sha1Kat; pub use sha256_kat::Sha256Kat; pub use sha2_512_384acc_kat::Sha2_512_384AccKat; pub use sha384_kat::Sha384Kat; pub use sha3_kat::Shake256Kat; pub use sha512_kat::Sha512Kat; use caliptra_drivers::cprintln; /// Execute Known Answer Tests /// /// # Arguments /// /// * `env` - ROM Environment pub fn execute_kat(env: &mut KatsEnv) -> CaliptraResult<()> { cprintln!("[kat] ++"); cprintln!("[kat] sha1"); Sha1Kat::default().execute(env.sha1)?; cprintln!("[kat] SHA2-256"); Sha256Kat::default().execute(env.sha256)?; cprintln!("[kat] SHA2-384"); Sha384Kat::default().execute(env.sha2_512_384)?; cprintln!("[kat] SHA2-512"); Sha512Kat::default().execute(env.sha2_512_384)?; cprintln!("[kat] SHA2-512-ACC"); Sha2_512_384AccKat::default().execute(env.sha2_512_384_acc, env.sha_acc_lock_state)?; cprintln!("[kat] SHAKE-256"); Shake256Kat::default().execute(env.sha3)?; cprintln!("[kat] ECC-384"); Ecc384Kat::default().execute(env.ecc384, env.trng)?; cprintln!("[kat] ECDH"); EcdhKat::default().execute(env.ecc384, env.trng)?; cprintln!("[kat] HMAC-384Kdf"); Hmac384KdfKat::default().execute(env.hmac, env.trng)?; cprintln!("[kat] HMAC-512Kdf"); Hmac512KdfKat::default().execute(env.hmac, env.trng)?; cprintln!("[kat] HKDF-384"); Hkdf384Kat::default().execute(env.hmac, env.trng)?; cprintln!("[kat] HKDF-512"); Hkdf512Kat::default().execute(env.hmac, env.trng)?; cprintln!("[kat] KDF-CMAC"); CmacKdfKat::default().execute(env.aes)?; cprintln!("[kat] LMS"); LmsKat::default().execute(env.sha256, env.lms)?; cprintln!("[kat] MLDSA87"); Mldsa87Kat::default().execute(env.mldsa87, env.trng)?; cprintln!("[kat] AES-256-ECB"); Aes256EcbKat::default().execute(env.aes)?; cprintln!("[kat] AES-256-CBC"); Aes256CbcKat::default().execute(env.aes)?; cprintln!("[kat] AES-256-CMAC"); Aes256CmacKat::default().execute(env.aes)?; cprintln!("[kat] AES-256-CTR"); Aes256CtrKat::default().execute(env.aes)?; cprintln!("[kat] AES-256-GCM"); Aes256GcmKat::default().execute(env.aes, env.trng)?; cprintln!("[kat] --"); Ok(()) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/aes256ecb_kat.rs
kat/src/aes256ecb_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: aes256ecb_kat.rs Abstract: File contains the Known Answer Tests (KAT) for AES-256-ECB cryptography operations. --*/ use caliptra_drivers::{Aes, AesKey, AesOperation, CaliptraError, CaliptraResult, LEArray4x8}; // Generated from Python code: // >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes // >>> key = b'\x00' * 32 // >>> pt = b'\x00' * 48 // >>> cipher = Cipher(algorithms.AES(key), modes.ECB) // >>> encryptor = cipher.encryptor() // >>> ct = encryptor.update(pt) + encryptor.finalize() // >>> print(ct.hex()) // dc95c078a2408989ad48a21492842087dc95c078a2408989ad48a21492842087dc95c078a2408989ad48a21492842087dc95c078a2408989ad48a21492842087 const KEY: AesKey<'_> = AesKey::Array(&LEArray4x8::new([0u32; 8])); const PT: [u8; 48] = [0u8; 48]; const CT: [u8; 48] = [ 0xdc, 0x95, 0xc0, 0x78, 0xa2, 0x40, 0x89, 0x89, 0xad, 0x48, 0xa2, 0x14, 0x92, 0x84, 0x20, 0x87, 0xdc, 0x95, 0xc0, 0x78, 0xa2, 0x40, 0x89, 0x89, 0xad, 0x48, 0xa2, 0x14, 0x92, 0x84, 0x20, 0x87, 0xdc, 0x95, 0xc0, 0x78, 0xa2, 0x40, 0x89, 0x89, 0xad, 0x48, 0xa2, 0x14, 0x92, 0x84, 0x20, 0x87, ]; #[derive(Default, Debug)] pub struct Aes256EcbKat {} impl Aes256EcbKat { /// This function executes the Known Answer Tests (aka KAT) for AES-256-ECB. /// /// # Arguments /// /// * `aes` - AES driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, aes: &mut Aes) -> CaliptraResult<()> { self.encrypt_decrypt(aes) } fn encrypt_decrypt(&self, aes: &mut Aes) -> CaliptraResult<()> { let mut ciphertext: [u8; 48] = [0u8; 48]; aes.aes_256_ecb(KEY, AesOperation::Encrypt, &PT[..], &mut ciphertext)?; if ciphertext != CT { Err(CaliptraError::KAT_AES_CIPHERTEXT_MISMATCH)?; } let mut plaintext: [u8; 48] = [0u8; 48]; aes.aes_256_ecb(KEY, AesOperation::Decrypt, &CT[..], &mut plaintext)?; if plaintext != PT { Err(CaliptraError::KAT_AES_PLAINTEXT_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/aes256ctr_kat.rs
kat/src/aes256ctr_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: aes256gcm_kat.rs Abstract: File contains the Known Answer Tests (KAT) for AES-256-CTR cryptography operations. --*/ use caliptra_drivers::{Aes, CaliptraError, CaliptraResult, LEArray4x4, LEArray4x8}; // From NIST SP800-38A, F.5.5 // CTR-AES256.Encrypt // Key // 603deb1015ca71be2b73aef0857d7781 // 1f352c073b6108d72d9810a30914dff4 // Init. Counter f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff // Block #1 // Input Block // f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff // Output Block // 0bdf7df1591716335e9a8b15c860c502 // Plaintext // 6bc1bee22e409f96e93d7e117393172a // Ciphertext // 601ec313775789a5b7a7f504bbf3d228 // Block #2 // Input Block // f0f1f2f3f4f5f6f7f8f9fafbfcfdff00 // Output Block // 5a6e699d536119065433863c8f657b94 // Plaintext // ae2d8a571e03ac9c9eb76fac45af8e51 // Ciphertext // f443e3ca4d62b59aca84e990cacaf5c5 // Block #3 // Input Block // f0f1f2f3f4f5f6f7f8f9fafbfcfdff01 // Output Block // 1bc12c9c01610d5d0d8bd6a3378eca62 // Plaintext // 30c81c46a35ce411e5fbc1191a0a52ef // Ciphertext // 2b0930daa23de94ce87017ba2d84988d // Block #4 // Input Block // f0f1f2f3f4f5f6f7f8f9fafbfcfdff02 // Output Block // 2956e1c8693536b1bee99c73a31576b6 // Plaintext // f69f2445df4f9b17ad2b417be66c3710 // Ciphertext // dfc9c58db67aada613c2dd08457941a6 const KEY: LEArray4x8 = LEArray4x8::new([ 0x10eb3d60, 0xbe71ca15, 0xf0ae732b, 0x81777d85, 0x072c351f, 0xd708613b, 0xa310982d, 0xf4df1409, ]); const IV: LEArray4x4 = LEArray4x4::new([0xf3f2f1f0, 0xf7f6f5f4, 0xfbfaf9f8, 0xfffefdfc]); const PT: [u8; 64] = [ 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10, ]; const CT: [u8; 64] = [ 0x60, 0x1e, 0xc3, 0x13, 0x77, 0x57, 0x89, 0xa5, 0xb7, 0xa7, 0xf5, 0x04, 0xbb, 0xf3, 0xd2, 0x28, 0xf4, 0x43, 0xe3, 0xca, 0x4d, 0x62, 0xb5, 0x9a, 0xca, 0x84, 0xe9, 0x90, 0xca, 0xca, 0xf5, 0xc5, 0x2b, 0x09, 0x30, 0xda, 0xa2, 0x3d, 0xe9, 0x4c, 0xe8, 0x70, 0x17, 0xba, 0x2d, 0x84, 0x98, 0x8d, 0xdf, 0xc9, 0xc5, 0x8d, 0xb6, 0x7a, 0xad, 0xa6, 0x13, 0xc2, 0xdd, 0x08, 0x45, 0x79, 0x41, 0xa6, ]; #[derive(Default, Debug)] pub struct Aes256CtrKat {} impl Aes256CtrKat { /// This function executes the Known Answer Tests (aka KAT) for AES-256-CBC. /// /// Test vector source: /// NIST test vectors /// /// # Arguments /// /// * `aes` - AES driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, aes: &mut Aes) -> CaliptraResult<()> { self.encrypt_decrypt(aes) } fn encrypt_decrypt(&self, aes: &mut Aes) -> CaliptraResult<()> { let mut ciphertext: [u8; 64] = [0u8; 64]; aes.aes_256_ctr(&KEY, &IV, 0, &PT[..], &mut ciphertext)?; if ciphertext != CT { Err(CaliptraError::KAT_AES_CIPHERTEXT_MISMATCH)?; } let mut plaintext: [u8; 64] = [0u8; 64]; aes.aes_256_ctr(&KEY, &IV, 0, &CT[..], &mut plaintext)?; if plaintext != PT { Err(CaliptraError::KAT_AES_PLAINTEXT_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/cmackdf_kat.rs
kat/src/cmackdf_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: hmac_kdf_kat.rs Abstract: File contains the Known Answer Tests (KAT) for Counter Mode KDF using CMAC. --*/ // From ACVP test vector: // "tgId": 263, // "keyOutLength": 1024, // "kdfMode": "counter", // "macMode": "CMAC-AES256", // "counterLength": 32, // "counterLocation": "before fixed data", // "testType": "AFT", // "tests": [ // { // "tcId": 525, // "keyIn": "BFB99C6AAB859A9873ACC9880BD875BB83A8B24A9307576A054216908756BE5B" // }, // "fixedData": "CD9B9791F5EEE211918BA1E2B01B4E29", // "keyOut": "C303887FB0ACA8E78DEBB8A008E75C88C26E927F0FA8A1DF1614C97E1B6F78B35C8F8A1CB9CD9F18DC30D06C73B75FDEA5A636ACB92F690FC6CB060F0A3DB66E759E30097C297E56C59DB8E17FF2656A8520D7309307B8E161B091FDDAF375B34E2EB8084D2832621C37BB67F09AAB29F3E467F422270B237D9B5AEBAD2D1F05" use caliptra_drivers::{cmac_kdf, Aes, CaliptraError, CaliptraResult, LEArray4x16, LEArray4x8}; const KEY_IN: LEArray4x8 = LEArray4x8::new([ 0x6a9cb9bf, 0x989a85ab, 0x88c9ac73, 0xbb75d80b, 0x4ab2a883, 0x6a570793, 0x90164205, 0x5bbe5687, ]); const FIXED_DATA: [u8; 16] = [ 0xcd, 0x9b, 0x97, 0x91, 0xf5, 0xee, 0xe2, 0x11, 0x91, 0x8b, 0xa1, 0xe2, 0xb0, 0x1b, 0x4e, 0x29, ]; const KEY_OUT: LEArray4x16 = LEArray4x16::new([ 0x7f8803c3, 0xe7a8acb0, 0xa0b8eb8d, 0x885ce708, 0x7f926ec2, 0xdfa1a80f, 0x7ec91416, 0xb3786f1b, 0x1c8a8f5c, 0x189fcdb9, 0x6cd030dc, 0xde5fb773, 0xac36a6a5, 0x0f692fb9, 0x0f06cbc6, 0x6eb63d0a, ]); #[derive(Default, Debug)] pub struct CmacKdfKat {} impl CmacKdfKat { /// This function executes the Known Answer Tests (aka KAT) for CMAC KDF. pub fn execute(&self, aes: &mut Aes) -> CaliptraResult<()> { let output = cmac_kdf( aes, caliptra_drivers::AesKey::Array(&KEY_IN), &FIXED_DATA, None, 4, )?; if KEY_OUT != output { Err(CaliptraError::KAT_CMAC_KDF_OUTPUT_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/aes256cbc_kat.rs
kat/src/aes256cbc_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: aes256gcm_kat.rs Abstract: File contains the Known Answer Tests (KAT) for AES-256-CBC cryptography operations. --*/ use caliptra_drivers::{Aes, AesOperation, CaliptraError, CaliptraResult, LEArray4x4, LEArray4x8}; // Generated from Python code: // >>> import os // >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes // >>> key = b'\x00' * 32 // >>> iv = b'\x00' * 16 // >>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv)) // >>> encryptor = cipher.encryptor() // >>> ct = encryptor.update(iv * 3) + encryptor.finalize() // >>> print(ct.hex()) // dc95c078a2408989ad48a2149284208708c374848c228233c2b34f332bd2e9d38b70c515a6663d38cdb8e6532b266491 const KEY: LEArray4x8 = LEArray4x8::new([0u32; 8]); const IV: LEArray4x4 = LEArray4x4::new([0u32; 4]); const PT: [u8; 48] = [0u8; 48]; const CT: [u8; 48] = [ 0xdc, 0x95, 0xc0, 0x78, 0xa2, 0x40, 0x89, 0x89, 0xad, 0x48, 0xa2, 0x14, 0x92, 0x84, 0x20, 0x87, 0x08, 0xc3, 0x74, 0x84, 0x8c, 0x22, 0x82, 0x33, 0xc2, 0xb3, 0x4f, 0x33, 0x2b, 0xd2, 0xe9, 0xd3, 0x8b, 0x70, 0xc5, 0x15, 0xa6, 0x66, 0x3d, 0x38, 0xcd, 0xb8, 0xe6, 0x53, 0x2b, 0x26, 0x64, 0x91, ]; #[derive(Default, Debug)] pub struct Aes256CbcKat {} impl Aes256CbcKat { /// This function executes the Known Answer Tests (aka KAT) for AES-256-CBC. /// /// Test vector source: /// NIST test vectors /// /// # Arguments /// /// * `aes` - AES driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, aes: &mut Aes) -> CaliptraResult<()> { self.encrypt_decrypt(aes) } fn encrypt_decrypt(&self, aes: &mut Aes) -> CaliptraResult<()> { let mut ciphertext: [u8; 48] = [0u8; 48]; aes.aes_256_cbc(&KEY, &IV, AesOperation::Encrypt, &PT[..], &mut ciphertext)?; if ciphertext != CT { Err(CaliptraError::KAT_AES_CIPHERTEXT_MISMATCH)?; } let mut plaintext: [u8; 48] = [0u8; 48]; aes.aes_256_cbc(&KEY, &IV, AesOperation::Decrypt, &CT[..], &mut plaintext)?; if plaintext != PT { Err(CaliptraError::KAT_AES_PLAINTEXT_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/sha512_kat.rs
kat/src/sha512_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha512_kat.rs Abstract: File contains the Known Answer Tests (KAT) for SHA-512 cryptography operations. --*/ use caliptra_drivers::{Array4x16, CaliptraError, CaliptraResult, Sha2_512_384}; pub const EXPECTED_DIGEST: Array4x16 = Array4x16::new([ 0xcf83e135, 0x7eefb8bd, 0xf1542850, 0xd66d8007, 0xd620e405, 0xb5715dc, 0x83f4a921, 0xd36ce9ce, 0x47d0d13c, 0x5d85f2b0, 0xff8318d2, 0x877eec2f, 0x63b931bd, 0x47417a81, 0xa538327a, 0xf927da3e, ]); #[derive(Default, Debug)] pub struct Sha512Kat {} impl Sha512Kat { /// This function executes the Known Answer Tests (aka KAT) for SHA512. /// /// # Arguments /// /// * `sha` - SHA2-512 Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, sha: &mut Sha2_512_384) -> CaliptraResult<()> { self.kat_no_data(sha) } fn kat_no_data(&self, sha2: &mut Sha2_512_384) -> CaliptraResult<()> { let data = &[]; let digest = sha2 .sha512_digest(data) .map_err(|_| CaliptraError::KAT_SHA512_DIGEST_FAILURE)?; if digest != EXPECTED_DIGEST { Err(CaliptraError::KAT_SHA512_DIGEST_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/sha3_kat.rs
kat/src/sha3_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha3_kat.rs Abstract: File contains the Known Answer Tests (KAT) for SHA3 cryptography operations. --*/ use caliptra_drivers::{Array4x8, CaliptraError, CaliptraResult, Sha3}; pub const EXPECTED_SHAKE256_DIGEST: Array4x8 = Array4x8::new([ 0x46b9dd2b, 0x0ba88d13, 0x233b3feb, 0x743eeb24, 0x3fcd52ea, 0x62b81b82, 0xb50c2764, 0x6ed5762f, ]); #[derive(Default, Debug)] pub struct Shake256Kat {} impl Shake256Kat { /// This function executes the Known Answer Tests (aka KAT) for SHAKE256. /// /// # Arguments /// /// * `sha` - SHA3 Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, sha: &mut Sha3) -> CaliptraResult<()> { self.kat_no_data(sha) } fn kat_no_data(&self, sha3: &mut Sha3) -> CaliptraResult<()> { let data = &[]; let digest = sha3 .shake256_digest(data) .map_err(|_| CaliptraError::KAT_SHA3_SHAKE256_DIGEST_FAILURE)?; if digest != EXPECTED_SHAKE256_DIGEST { Err(CaliptraError::KAT_SHA3_SHAKE256_DIGEST_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/hmac_kdf_kat.rs
kat/src/hmac_kdf_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: hmac_kdf_kat.rs Abstract: File contains the Known Answer Tests (KAT) for HMAC-384 and HMAC-512 cryptography operations. --*/ use caliptra_drivers::{ hmac_kdf, Array4x12, Array4x16, CaliptraError, CaliptraResult, Hmac, HmacMode, Trng, }; const KEY: Array4x12 = Array4x12::new([ 0xb57dc523, 0x54afee11, 0xedb4c905, 0x2a528344, 0x348b2c6b, 0x6c39f321, 0x33ed3bb7, 0x2035a4ab, 0x55d6648c, 0x1529ef7a, 0x9170fec9, 0xef26a81e, ]); const LABEL: [u8; 60] = [ 0x17, 0xe6, 0x41, 0x90, 0x9d, 0xed, 0xfe, 0xe4, 0x96, 0x8b, 0xb9, 0x5d, 0x7f, 0x77, 0x0e, 0x45, 0x57, 0xca, 0x34, 0x7a, 0x46, 0x61, 0x4c, 0xb3, 0x71, 0x42, 0x3f, 0x0d, 0x91, 0xdf, 0x3b, 0x58, 0xb5, 0x36, 0xed, 0x54, 0x53, 0x1f, 0xd2, 0xa2, 0xeb, 0x0b, 0x8b, 0x2a, 0x16, 0x34, 0xc2, 0x3c, 0x88, 0xfa, 0xd9, 0x70, 0x6c, 0x45, 0xdb, 0x44, 0x11, 0xa2, 0x3b, 0x89, ]; const EXPECTED_OUT: [u8; 40] = [ 0x59, 0x49, 0xac, 0xf9, 0x63, 0x5a, 0x77, 0x29, 0x79, 0x28, 0xc1, 0xe1, 0x55, 0xd4, 0x3a, 0x4e, 0x4b, 0xca, 0x61, 0xb1, 0x36, 0x9a, 0x5e, 0xf5, 0x05, 0x30, 0x88, 0x85, 0x50, 0xba, 0x27, 0x0e, 0x26, 0xbe, 0x4a, 0x42, 0x1c, 0xdf, 0x80, 0xb7, ]; #[derive(Default, Debug)] pub struct Hmac384KdfKat {} impl Hmac384KdfKat { /// This function executes the Known Answer Tests (aka KAT) for HMAC384Kdf. /// /// Test vector source: /// https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Key-Derivation /// /// # Arguments /// /// * `hmac` - HMAC-384 Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { self.kat_nist_vector(hmac, trng)?; Ok(()) } /// Performs KDF generation with a single fixed input data buffer. /// /// # Arguments /// /// * `hmac` - HMAC-384 Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. fn kat_nist_vector(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { let mut out = Array4x12::default(); hmac_kdf( hmac, (&KEY).into(), &LABEL, None, trng, (&mut out).into(), HmacMode::Hmac384, ) .map_err(|_| CaliptraError::KAT_HMAC384_FAILURE)?; if EXPECTED_OUT != <[u8; 48]>::from(out)[..EXPECTED_OUT.len()] { Err(CaliptraError::KAT_HMAC384_TAG_MISMATCH)?; } Ok(()) } } #[derive(Default, Debug)] pub struct Hmac512KdfKat {} impl Hmac512KdfKat { /// This function executes the Known Answer Tests (aka KAT) for HMAC512Kdf. /// /// Test vector source: /// https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Key-Derivation /// NOTE: Test vectors do not include separate label and context. Instead, split the input of /// one vector that included a 0x00 byte into those fields. /// /// # Arguments /// /// * `hmac` - HMAC-512 Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { self.kat_nist_vector(hmac, trng)?; Ok(()) } /// Performs KDF generation with a single fixed input data buffer. /// /// # Arguments /// /// * `hmac` - HMAC-512 Driver /// * `trng` - TRNG Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. fn kat_nist_vector(&self, hmac: &mut Hmac, trng: &mut Trng) -> CaliptraResult<()> { let key: [u8; 64] = [ 0x24, 0x43, 0x56, 0xbe, 0x9b, 0x32, 0x79, 0x64, 0x73, 0x2e, 0xb4, 0xa7, 0xc0, 0x9b, 0x04, 0xb4, 0x20, 0x71, 0x23, 0x96, 0xeb, 0x57, 0xf7, 0x2b, 0xc9, 0x49, 0x24, 0x06, 0x6c, 0x68, 0x7e, 0x87, 0x8e, 0x79, 0x8e, 0x0a, 0x03, 0x3a, 0x1e, 0xe1, 0xa4, 0xd8, 0xcd, 0xc2, 0xda, 0x04, 0x43, 0xec, 0xd7, 0x74, 0x01, 0xd0, 0x46, 0x0c, 0xd9, 0x06, 0xea, 0xab, 0x02, 0x65, 0x6c, 0x1e, 0xdc, 0x98, ]; let label: [u8; 44] = [ 0xd8, 0x06, 0xe2, 0xdf, 0x8c, 0x85, 0xd3, 0xba, 0xf5, 0xd6, 0x7e, 0x9c, 0x97, 0xb7, 0x46, 0xee, 0x6b, 0xbb, 0x1b, 0xc1, 0x0d, 0xcd, 0xf6, 0xc7, 0xa6, 0x07, 0x5c, 0x31, 0x1c, 0xf3, 0x47, 0x52, 0xac, 0xbe, 0x60, 0xe6, 0x8f, 0x23, 0xc7, 0xf8, 0x90, 0xb5, 0xea, 0x73, ]; let context: [u8; 15] = [ 0xa1, 0xad, 0x32, 0x17, 0x82, 0x54, 0x88, 0x52, 0x46, 0xf0, 0x49, 0x39, 0x87, 0xa6, 0xe8, ]; let expected_out: [u8; 40] = [ 0xf0, 0xb5, 0xbc, 0x74, 0x9e, 0xb3, 0x00, 0xca, 0x21, 0x7c, 0xa8, 0x2f, 0xdf, 0xfe, 0xd8, 0x9b, 0x1b, 0xf2, 0xc8, 0xaf, 0xc2, 0xb3, 0x6e, 0xe2, 0xb4, 0x86, 0x95, 0xe5, 0x08, 0x5b, 0x89, 0x3a, 0x6d, 0xaa, 0xd5, 0x47, 0x4f, 0x74, 0xef, 0x0f, ]; let mut out = Array4x12::default(); hmac_kdf( hmac, (&Array4x16::from(key)).into(), &label, Some(&context), trng, (&mut out).into(), HmacMode::Hmac512, ) .map_err(|_| CaliptraError::KAT_HMAC384_FAILURE)?; if expected_out != <[u8; 48]>::from(out)[..expected_out.len()] { Err(CaliptraError::KAT_HMAC384_TAG_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/sha1_kat.rs
kat/src/sha1_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha1_kat.rs Abstract: File contains the Known Answer Tests (KAT) for SHA-1 cryptography operations. --*/ use caliptra_drivers::{Array4x5, CaliptraError, CaliptraResult, Sha1}; const EXPECTED_DIGEST: Array4x5 = Array4x5::new([0xda39a3ee, 0x5e6b4b0d, 0x3255bfef, 0x95601890, 0xafd80709]); #[derive(Default, Debug)] pub struct Sha1Kat {} impl Sha1Kat { /// This function executes the Known Answer Tests (aka KAT) for SHA1. /// /// Test vector source: /// https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/shs/shabytetestvectors.zip /// /// # Arguments /// /// * `sha` - SHA1 Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, sha: &mut Sha1) -> CaliptraResult<()> { self.kat_no_data(sha) } fn kat_no_data(&self, sha: &mut Sha1) -> CaliptraResult<()> { let data = []; let digest = sha .digest(&data) .map_err(|_| CaliptraError::KAT_SHA1_DIGEST_FAILURE)?; if digest != EXPECTED_DIGEST { Err(CaliptraError::KAT_SHA1_DIGEST_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/ecc384_kat.rs
kat/src/ecc384_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: ecc384_kat.rs Abstract: File contains the Known Answer Tests (KAT) for ECC-384 cryptography operations. --*/ use caliptra_drivers::{ Array4x12, Array4xN, CaliptraError, CaliptraResult, Ecc384, Ecc384PrivKeyOut, Ecc384PubKey, Ecc384Signature, Trng, }; const KEY_GEN_PRIV_KEY: Array4x12 = Array4x12::new([ 0xfeeef554, 0x4a765649, 0x90128ad1, 0x89e873f2, 0x1f0dfd5a, 0xd7e2fa86, 0x1127ee6e, 0x394ca784, 0x871c1aec, 0x032c7a8b, 0x10b93e0e, 0xab8946d6, ]); const KEY_GEN_PUB_KEY: Ecc384PubKey = Ecc384PubKey { x: Array4xN([ 0xd7dd94e0, 0xbffc4cad, 0xe9902b7f, 0xdb154260, 0xd5ec5dfd, 0x57950e83, 0x59015a30, 0x2c8bf7bb, 0xa7e5f6df, 0xfc168516, 0x2bdd35f9, 0xf5c1b0ff, ]), y: Array4xN([ 0xbb9c3a2f, 0x061e8d70, 0x14278dd5, 0x1e66a918, 0xa6b6f9f1, 0xc1937312, 0xd4e7a921, 0xb18ef0f4, 0x1fdd401d, 0x9e771850, 0x9f8731e9, 0xeec9c31d, ]), }; const SIGNATURE: Ecc384Signature = Ecc384Signature { r: Array4xN([ 0x93799D55, 0x12263628, 0x34F60F7B, 0x945290B7, 0xCCE6E996, 0x01FB7EBD, 0x026C2E3C, 0x445D3CD9, 0xB65068DA, 0xC0A848BE, 0x9F0560AA, 0x758FDA27, ]), s: Array4xN([ 0xE548E535, 0xA1CC600E, 0x133B5591, 0xAEBAAD78, 0x054006D7, 0x52D0E1DF, 0x94FBFA95, 0xD78F0B3F, 0x8E81B911, 0x9C2BE008, 0xBF6D6F4E, 0x4185F87D, ]), }; #[derive(Default, Debug)] pub struct Ecc384Kat {} impl Ecc384Kat { /// This function executes the Known Answer Tests (aka KAT) for ECC384. /// /// Test vector source: /// Zeroed inputs, outputs verified against python cryptography lib built on OpenSSL /// /// # Arguments /// /// * `ecc` - ECC-384 Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, ecc: &mut Ecc384, trng: &mut Trng) -> CaliptraResult<()> { self.kat_key_pair_gen_sign_and_verify(ecc, trng) } fn kat_key_pair_gen_sign_and_verify( &self, ecc: &mut Ecc384, trng: &mut Trng, ) -> CaliptraResult<()> { let mut priv_key = Array4x12::new([0u32; 12]); let mut pct_sig = Ecc384Signature { r: Array4x12::new([0u32; 12]), s: Array4x12::new([0u32; 12]), }; let pub_key = ecc .key_pair_for_fips_kat(trng, Ecc384PrivKeyOut::from(&mut priv_key), &mut pct_sig) .map_err(|_| CaliptraError::KAT_ECC384_KEY_PAIR_GENERATE_FAILURE)?; // NOTE: Signature verify step is performed in ECC driver sign function if priv_key != KEY_GEN_PRIV_KEY { Err(CaliptraError::KAT_ECC384_KEY_PAIR_VERIFY_FAILURE)?; } if pub_key != KEY_GEN_PUB_KEY { Err(CaliptraError::KAT_ECC384_KEY_PAIR_VERIFY_FAILURE)?; } if pct_sig != SIGNATURE { Err(CaliptraError::KAT_ECC384_SIGNATURE_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/mldsa87_kat.rs
kat/src/mldsa87_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: mldsa_kat.rs Abstract: File contains the Known Answer Tests (KAT) for MLDSA cryptography operations. --*/ use caliptra_drivers::{ Array4x16, CaliptraError, CaliptraResult, LEArray4x8, Mldsa87, Mldsa87PrivKey, Mldsa87Seed, Mldsa87SignRnd, Sha2_512_384, Trng, }; use caliptra_registers::sha512::Sha512Reg; use zerocopy::IntoBytes; const SEED: LEArray4x8 = LEArray4x8::new([ 0x0a004093, 0x27d15f67, 0x121d0737, 0xd5e4ce3f, 0x28fe43a2, 0xd4f06807, 0x858a7646, 0x9cf85c2d, ]); const KAT_MESSAGE: [u32; 16] = [ 0x78fb03e7, 0x22ed1fc4, 0xf2a5e244, 0x9600e616, 0x0d298750, 0x179a0dd9, 0xb503d306, 0xbc2ac6d4, 0x735f11ee, 0x23f6c548, 0x358498db, 0x04f50a80, 0xfb169e3c, 0x1c6cd56e, 0xd41baaf3, 0xd418f5c8, ]; const KAT_PUB_KEY_DIGEST: Array4x16 = Array4x16::new([ 0x156d7184, 0xed6113a4, 0x1944255a, 0x3ffd5aa1, 0x3273e7a7, 0x3d8b5feb, 0xf695df65, 0x351a7476, 0xb74d6d96, 0xe8927960, 0x0d188fda, 0xb7adaa9a, 0x431308ed, 0xf9544ec3, 0x5fe96fa4, 0xd012c3a8, ]); const KAT_PRIV_KEY_DIGEST: Array4x16 = Array4x16::new([ 0x535af06c, 0x07e85226, 0x21991715, 0xb1db1b31, 0x3bffe2d3, 0x6ac688bf, 0x960fe7df, 0xda987e1a, 0x779b9471, 0x80983ac8, 0x45a293ec, 0x70269c4a, 0xeb947158, 0xbe85be08, 0x40730835, 0x3b4700ef, ]); const KAT_SIGNATURE_DIGEST: Array4x16 = Array4x16::new([ 0x2cc91683, 0xf3f36770, 0x20082e60, 0x06351dbe, 0x459019bb, 0xf99c95f4, 0xf34a6562, 0xf712686d, 0xe85df11e, 0x324c7954, 0x6e4ff08c, 0x5a028589, 0x1c5ee701, 0x8d490941, 0xb805a337, 0x51746789, ]); #[derive(Default, Debug)] pub struct Mldsa87Kat {} impl Mldsa87Kat { /// This function executes the Known Answer Tests (aka KAT) for MLDSA87. /// /// # Arguments /// /// * `mldsa87` - MLDSA87 Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, mldsa87: &mut Mldsa87, trng: &mut Trng) -> CaliptraResult<()> { self.kat_key_pair_gen_sign_and_verify(mldsa87, trng) } fn kat_key_pair_gen_sign_and_verify( &self, mldsa87: &mut Mldsa87, trng: &mut Trng, ) -> CaliptraResult<()> { // Compare SHA-512 hashes of the keys and signature to save on ROM space. let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let mut priv_key = Mldsa87PrivKey::default(); let pub_key = mldsa87 .key_pair(Mldsa87Seed::Array4x8(&SEED), trng, Some(&mut priv_key)) .map_err(|_| CaliptraError::KAT_MLDSA87_KEY_PAIR_GENERATE_FAILURE)?; let pub_key_digest = sha2 .sha512_digest(pub_key.as_bytes()) .map_err(|_| CaliptraError::KAT_SHA384_DIGEST_FAILURE)?; let priv_key_digest = sha2 .sha512_digest(priv_key.as_bytes()) .map_err(|_| CaliptraError::KAT_SHA384_DIGEST_FAILURE)?; if pub_key_digest != KAT_PUB_KEY_DIGEST || priv_key_digest != KAT_PRIV_KEY_DIGEST { Err(CaliptraError::KAT_MLDSA87_KEY_PAIR_VERIFY_FAILURE)?; } let signature = mldsa87 .sign( Mldsa87Seed::PrivKey(&priv_key), &pub_key, &KAT_MESSAGE.into(), &Mldsa87SignRnd::default(), trng, ) .map_err(|_| CaliptraError::KAT_MLDSA87_SIGNATURE_FAILURE)?; let signature_digest = sha2 .sha512_digest(signature.as_bytes()) .map_err(|_| CaliptraError::KAT_SHA384_DIGEST_FAILURE)?; if signature_digest != KAT_SIGNATURE_DIGEST { Err(CaliptraError::KAT_MLDSA87_SIGNATURE_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/sha2_512_384acc_kat.rs
kat/src/sha2_512_384acc_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha2_512_384acc_kat.rs Abstract: File contains the Known Answer Tests (KAT) for SHA512 accelerator cryptography operations. --*/ use caliptra_drivers::{ Array4x16, CaliptraError, CaliptraResult, Sha2_512_384Acc, ShaAccLockState, StreamEndianness, }; const SHA512_EXPECTED_DIGEST: Array4x16 = Array4x16::new([ 0xcf83e135, 0x7eefb8bd, 0xf1542850, 0xd66d8007, 0xd620e405, 0x0b5715dc, 0x83f4a921, 0xd36ce9ce, 0x47d0d13c, 0x5d85f2b0, 0xff8318d2, 0x877eec2f, 0x63b931bd, 0x47417a81, 0xa538327a, 0xf927da3e, ]); #[derive(Default)] pub struct Sha2_512_384AccKat {} impl Sha2_512_384AccKat { /// This function executes the Known Answer Tests (aka KAT) for SHA512ACC. /// Performing this test for SHA512 mode also covers SHA384 /// /// Test vector source: /// https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/shs/shabytetestvectors.zip /// /// # Arguments /// /// * `sha_acc` - SHA2-384 Accelerator Driver /// * `lock_state` - SHA Acc Lock State /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute( &self, sha_acc: &mut Sha2_512_384Acc, lock_state: ShaAccLockState, ) -> CaliptraResult<()> { self.kat_no_data(sha_acc, lock_state)?; Ok(()) } fn kat_no_data( &self, sha_acc: &mut Sha2_512_384Acc, lock_state: ShaAccLockState, ) -> CaliptraResult<()> { let mut digest = Array4x16::default(); if let Some(mut sha_acc_op) = sha_acc.try_start_operation(lock_state)? { let result = || -> CaliptraResult<()> { // SHA 512 sha_acc_op .digest_512(0, 0, StreamEndianness::Reorder, &mut digest) .map_err(|_| CaliptraError::KAT_SHA2_512_384_ACC_DIGEST_FAILURE)?; if digest != SHA512_EXPECTED_DIGEST { Err(CaliptraError::KAT_SHA2_512_384_ACC_DIGEST_MISMATCH)?; } Ok(()) }(); // If error, don't drop the operation since that will unlock the // peripheral for SoC use, which we're not allowed to do if the // KAT doesn't pass. if result.is_err() { caliptra_drivers::cprintln!("Dropping operation"); core::mem::forget(sha_acc_op); } result?; } else { Err(CaliptraError::KAT_SHA2_512_384_ACC_DIGEST_START_OP_FAILURE)?; }; Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/ecdh_kat.rs
kat/src/ecdh_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: ecc384_kat.rs Abstract: File contains the Known Answer Tests (KAT) for ECC-384 cryptography operations. --*/ use caliptra_drivers::{ Array4x12, CaliptraError, CaliptraResult, Ecc384, Ecc384PrivKeyIn, Ecc384PrivKeyOut, Ecc384PubKey, Trng, }; // From NIST // CAVS 14.1 // ECC CDH Primitive (SP800-56A Section 5.7.1.2) Test Information for "testecccdh" // Curves tested: Curves tested: P-192 P-224 P-256 P-384 P-521 K-163 K-233 K-283 K-409 K-571 B-163 B-233 B-283 B-409 B-571 // Generated on Mon Nov 19 10:52:17 2012 // https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/components/ecccdhvs.pdf // https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/components/ecccdhtestvectors.zip // [P-384] // COUNT = 0 // QCAVSx = a7c76b970c3b5fe8b05d2838ae04ab47697b9eaf52e764592efda27fe7513272734466b400091adbf2d68c58e0c50066 // QCAVSy = ac68f19f2e1cb879aed43a9969b91a0839c4c38a49749b661efedf243451915ed0905a32b060992b468c64766fc8437a // dIUT = 3cc3122a68f0d95027ad38c067916ba0eb8c38894d22e1b15618b6818a661774ad463b205da88cf699ab4d43c9cf98a1 // QIUTx = 9803807f2f6d2fd966cdd0290bd410c0190352fbec7ff6247de1302df86f25d34fe4a97bef60cff548355c015dbb3e5f // QIUTy = ba26ca69ec2f5b5d9dad20cc9da711383a9dbe34ea3fa5a2af75b46502629ad54dd8b7d73a8abb06a3a3be47d650cc99 // ZIUT = 5f9d29dc5e31a163060356213669c8ce132e22f57c9a04f40ba7fcead493b457e5621e766c40a2e3d4d6a04b25e533f1 const A_PRIV_KEY: Array4x12 = Array4x12::new([ 0x3cc3122a, 0x68f0d950, 0x27ad38c0, 0x67916ba0, 0xeb8c3889, 0x4d22e1b1, 0x5618b681, 0x8a661774, 0xad463b20, 0x5da88cf6, 0x99ab4d43, 0xc9cf98a1, ]); const B_PUB_KEY: Ecc384PubKey = Ecc384PubKey { x: Array4x12::new([ 0xa7c76b97, 0x0c3b5fe8, 0xb05d2838, 0xae04ab47, 0x697b9eaf, 0x52e76459, 0x2efda27f, 0xe7513272, 0x734466b4, 0x00091adb, 0xf2d68c58, 0xe0c50066, ]), y: Array4x12::new([ 0xac68f19f, 0x2e1cb879, 0xaed43a99, 0x69b91a08, 0x39c4c38a, 0x49749b66, 0x1efedf24, 0x3451915e, 0xd0905a32, 0xb060992b, 0x468c6476, 0x6fc8437a, ]), }; const SHARED_SECRET: Array4x12 = Array4x12::new([ 0x5f9d29dc, 0x5e31a163, 0x06035621, 0x3669c8ce, 0x132e22f5, 0x7c9a04f4, 0x0ba7fcea, 0xd493b457, 0xe5621e76, 0x6c40a2e3, 0xd4d6a04b, 0x25e533f1, ]); #[derive(Default, Debug)] pub struct EcdhKat {} impl EcdhKat { /// This function executes the Known Answer Tests (aka KAT) for ECDH. /// /// Test vector source: /// https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/components/ecccdhtestvectors.zip /// /// # Arguments /// /// * `ecc` - ECC-384 Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, ecc: &mut Ecc384, trng: &mut Trng) -> CaliptraResult<()> { self.ecdh(ecc, trng) } fn ecdh(&self, ecc: &mut Ecc384, trng: &mut Trng) -> CaliptraResult<()> { let mut shared_secret = Array4x12::new([0u32; 12]); ecc.ecdh( Ecc384PrivKeyIn::Array4x12(&A_PRIV_KEY), &B_PUB_KEY, trng, Ecc384PrivKeyOut::Array4x12(&mut shared_secret), )?; if shared_secret != SHARED_SECRET { Err(CaliptraError::KAT_ECDH_VERIFY_FAILURE)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/kat/src/sha384_kat.rs
kat/src/sha384_kat.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha384_kat.rs Abstract: File contains the Known Answer Tests (KAT) for SHA-384 cryptography operations. --*/ use caliptra_drivers::{Array4x12, CaliptraError, CaliptraResult, Sha2_512_384}; pub const SHA384_EXPECTED_DIGEST: Array4x12 = Array4x12::new([ 0x38b060a7, 0x51ac9638, 0x4cd9327e, 0xb1b1e36a, 0x21fdb711, 0x14be0743, 0x4c0cc7bf, 0x63f6e1da, 0x274edebf, 0xe76f65fb, 0xd51ad2f1, 0x4898b95b, ]); #[derive(Default, Debug)] pub struct Sha384Kat {} impl Sha384Kat { /// This function executes the Known Answer Tests (aka KAT) for SHA384. /// /// Test vector source: /// https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/shs/shabytetestvectors.zip /// /// # Arguments /// /// * `sha` - SHA2-384 Driver /// /// # Returns /// /// * `CaliptraResult` - Result denoting the KAT outcome. pub fn execute(&self, sha: &mut Sha2_512_384) -> CaliptraResult<()> { self.kat_no_data(sha) } fn kat_no_data(&self, sha2: &mut Sha2_512_384) -> CaliptraResult<()> { let data = &[]; let digest = sha2 .sha384_digest(data) .map_err(|_| CaliptraError::KAT_SHA384_DIGEST_FAILURE)?; if digest != SHA384_EXPECTED_DIGEST { Err(CaliptraError::KAT_SHA384_DIGEST_MISMATCH)?; } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cpu/build.rs
cpu/build.rs
// Licensed under the Apache-2.0 license use std::env; use std::fs; use std::path::PathBuf; fn main() { let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); // Put the linker script somewhere the linker can find it. fs::write( out_dir.join("link.x"), r#"SECTIONS { .text : ALIGN(4) { _stext = .; KEEP(*(.init .init.*)); *(.text .text.*); KEEP(*(.vectors)) . = ALIGN(4); _etext = .; } > REGION_TEXT .rodata : ALIGN(4) { _srodata = .; *(.srodata .srodata.*); *(.rodata .rodata.*); . = ALIGN(4); _erodata = .; } > REGION_RODATA .data : AT (_erodata) ALIGN(4) { _sidata = LOADADDR(.data); _sdata = .; /* Must be called __global_pointer$ for linker relaxations to work. */ PROVIDE(__global_pointer$ = . + 0x800); *(.sdata .sdata.* .sdata2 .sdata2.*); *(.data .data.*); . = ALIGN(4); _edata = .; } > REGION_DATA .bss (NOLOAD) : ALIGN(4) { _sbss = .; *(.bss*) *(.sbss*) *(COMMON) . = ALIGN(4); _ebss = .; } > REGION_BSS .stack (NOLOAD): ALIGN(4) { _estack = .; . = . + STACK_SIZE; . = ALIGN(4); _sstack = .; } > REGION_STACK .estack (NOLOAD): ALIGN(4) { _eestack = .; . = . + ESTACK_SIZE; . = ALIGN(4); _sestack = .; } > REGION_ESTACK .nstack (NOLOAD): ALIGN(4) { _enstack = .; . = . + NSTACK_SIZE; . = ALIGN(4); _snstack = .; } > REGION_NSTACK .got (INFO) : { KEEP(*(.got .got.*)); } .eh_frame (INFO) : { KEEP(*(.eh_frame)) } .eh_frame_hdr (INFO) : { *(.eh_frame_hdr) } } _bss_len = SIZEOF(.bss); _data_len = SIZEOF(.data); ASSERT(SIZEOF(.got) == 0, ".got section detected"); ASSERT(SIZEOF(.bss) == 0, ".bss section detected"); ASSERT(SIZEOF(.stack) == STACK_SIZE, ".stack section overflow"); ASSERT(SIZEOF(.estack) == ESTACK_SIZE, ".estack section overflow"); ASSERT(SIZEOF(.nstack) == NSTACK_SIZE, ".nstack section overflow");"# .as_bytes(), ) .unwrap(); println!("cargo:rustc-link-search={}", out_dir.display()); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cpu/src/lib.rs
cpu/src/lib.rs
// Licensed under the Apache-2.0 license #![no_std] #[cfg(not(feature = "std"))] #[cfg(feature = "riscv")] core::arch::global_asm!(include_str!("start.S")); #[cfg(feature = "riscv")] core::arch::global_asm!(include_str!("nmi.S")); #[cfg(feature = "riscv")] core::arch::global_asm!(include_str!("trap.S")); pub mod csr; pub mod trap; use caliptra_registers::soc_ifc::SocIfcReg; pub use trap::{Exception, Interrupt, Trap, TrapRecord}; pub fn log_trap_record(trap_record: &TrapRecord, err_interrupt_status: Option<u32>) { let mut soc_ifc = unsafe { SocIfcReg::new() }; let soc_ifc = soc_ifc.regs_mut(); let ext_info = soc_ifc.cptra_fw_extended_error_info(); ext_info.at(0).write(|_| trap_record.mcause); ext_info.at(1).write(|_| trap_record.mscause); ext_info.at(2).write(|_| trap_record.mepc); ext_info.at(3).write(|_| trap_record.ra); // The err_interrup_status is only avaiable on NMI. if let Some(err_interrupt_status) = err_interrupt_status { ext_info.at(4).write(|_| err_interrupt_status); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cpu/src/trap.rs
cpu/src/trap.rs
/*++ Licensed under the Apache-2.0 license. File Name: exception.rs Abstract: File contains RISCV trap related types. --*/ /// Exception Record #[repr(C)] pub struct TrapRecord { pub ra: u32, pub sp: u32, pub a0: u32, pub a1: u32, pub a2: u32, pub a3: u32, pub a4: u32, pub a5: u32, pub a6: u32, pub a7: u32, pub t0: u32, pub t1: u32, pub t2: u32, pub t3: u32, pub t4: u32, pub t5: u32, pub t6: u32, pub mepc: u32, pub mcause: u32, pub mscause: u32, pub mstatus: u32, pub mtval: u32, } pub enum Trap { Synchronous(Exception), Asynchronous(Interrupt), } /// Exceptions are unusual conditions that occur at run time, associated with an instruction in the current RISC-V hart. #[derive(Debug, Clone, Copy)] pub enum Exception { /// Instruction access fault InstructionAccessFault, /// Illegal instruction IllegalInstruction, /// Breakpoint Breakpoint, /// Load address misaligned LoadMisaligned, /// Load access fault LoadAccessFault, /// Store/AMO address misaligned StoreMisaligned, /// Store access fault StoreAccessFault, /// Environment call from M-mode MachineEnvCall, // Not Implemented NotImplemented, } // Convert machine cause register value to Exception impl From<u32> for Exception { #[inline(always)] fn from(val: u32) -> Exception { match val { 0x01 => Exception::InstructionAccessFault, 0x02 => Exception::IllegalInstruction, 0x03 => Exception::Breakpoint, 0x04 => Exception::LoadMisaligned, 0x05 => Exception::LoadAccessFault, 0x07 => Exception::StoreMisaligned, 0x08 => Exception::StoreAccessFault, 0x0b => Exception::MachineEnvCall, _ => Exception::NotImplemented, } } } /// Interrupts are events that occur asynchronously outside any of the RISC-V harts. #[derive(Debug, Clone, Copy)] pub enum Interrupt { MachineSoftwareInterrupt, MachineTimerInterrupt, MachineExternalInterrupt, MachineInternalLocalTimer1, MachineInternalLocalTimer0, MachineCorrectableErrLocalInterrupt, NotImplemented, } impl From<u32> for Interrupt { #[inline(always)] fn from(val: u32) -> Self { match val { 0x03 => Self::MachineSoftwareInterrupt, 0x07 => Self::MachineTimerInterrupt, 0x0b => Self::MachineExternalInterrupt, 0x1c => Self::MachineInternalLocalTimer1, 0x1d => Self::MachineInternalLocalTimer0, 0x1e => Self::MachineCorrectableErrLocalInterrupt, _ => Self::NotImplemented, } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cpu/src/csr.rs
cpu/src/csr.rs
// Licensed under the Apache-2.0 license // Standard RISC-V MIE CSR #[cfg(feature = "riscv")] pub fn mie_enable_external_interrupts() { const MEIE: usize = 1 << 11; unsafe { core::arch::asm!("csrrs zero, mie, {r}", r = in(reg) MEIE); } } // VeeR EL2 PRM 5.5.1 Power Management Control Register // If bit 1 is set, setting bit0 globally enables interrupts, i.e. MIE in mstatus CSR #[cfg(feature = "riscv")] pub fn mpmc_halt_and_enable_interrupts() { // Tell the core to go to sleep const HALT: usize = 1 << 0; const HALTIE: usize = 1 << 1; unsafe { core::arch::asm!("csrrs zero, 0x7c6, {r}", r = in(reg) HALT | HALTIE); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/cpu/gen/src/lib.rs
cpu/gen/src/lib.rs
// Licensed under the Apache-2.0 license use caliptra_common::memory_layout::*; pub fn gen_memory_x(iccm_org: u32, iccm_size: u32) -> String { format!( r#" ICCM_ORG = 0x{iccm_org:08X}; DCCM_ORG = 0x{DCCM_ORG:08X}; DATA_ORG = 0x{EXTRA_MEMORY_ORG:08X}; STACK_ORG = 0x{STACK_ORG:08X}; ESTACK_ORG = 0x{ESTACK_ORG:08X}; NSTACK_ORG = 0x{NSTACK_ORG:08X}; CFI_STATE_ORG = 0x{CFI_STATE_ORG:08X}; ICCM_SIZE = 0x{iccm_size:08X}; DCCM_SIZE = 0x{DCCM_SIZE:08X}; DATA_SIZE = 0x{EXTRA_MEMORY_SIZE:08X}; STACK_SIZE = 0x{STACK_SIZE:08X}; ESTACK_SIZE = 0x{ESTACK_SIZE:08X}; NSTACK_SIZE = 0x{NSTACK_SIZE:08X}; MEMORY {{ ICCM (rx) : ORIGIN = ICCM_ORG, LENGTH = ICCM_SIZE DATA (rw) : ORIGIN = DATA_ORG, LENGTH = DATA_SIZE STACK (rw) : ORIGIN = STACK_ORG, LENGTH = STACK_SIZE ESTACK (rw) : ORIGIN = ESTACK_ORG, LENGTH = ESTACK_SIZE NSTACK (rw) : ORIGIN = NSTACK_ORG, LENGTH = NSTACK_SIZE }} REGION_ALIAS("REGION_TEXT", ICCM); REGION_ALIAS("REGION_RODATA", ICCM); REGION_ALIAS("REGION_DATA", DATA); REGION_ALIAS("REGION_BSS", DATA); REGION_ALIAS("REGION_STACK", STACK); REGION_ALIAS("REGION_ESTACK", ESTACK); REGION_ALIAS("REGION_NSTACK", NSTACK);"# ) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/build.rs
runtime/build.rs
/*++ Licensed under the Apache-2.0 license. File Name: build.rs Abstract: Build script for Caliptra Runtime. --*/ 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::RUNTIME_ORG, caliptra_common::RUNTIME_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/runtime/src/hmac.rs
runtime/src/hmac.rs
/*++ Licensed under the Apache-2.0 license. File Name: hmac.rs Abstract: File contains cryptography helper functions related to HMAC. --*/ use caliptra_cfi_derive_git::{cfi_impl_fn, cfi_mod_fn}; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_launder}; use caliptra_common::{cfi_check, crypto::Ecc384KeyPair, keyids::KEY_ID_TMP}; use caliptra_drivers::{ hmac_kdf, sha2_512_384::Sha2DigestOpTrait, Array4x12, HmacData, HmacKey, HmacMode, HmacTag, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, }; use caliptra_error::CaliptraResult; use zerocopy::IntoBytes; use zeroize::Zeroize; use crate::Drivers; /// Generate an ECC key pair /// /// # Arguments /// /// * `drivers` - Drivers /// * `input` - KeyId containing the input data /// * `label` - Label for KDF /// * `priv_key` - KeyId which the private key should be written to /// /// # Returns /// /// * `Ecc384KeyPair` - Generated key pair #[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)] fn ecc384_key_gen( drivers: &mut Drivers, input: KeyId, label: &[u8], priv_key: KeyId, ) -> CaliptraResult<Ecc384KeyPair> { hmac_kdf( &mut drivers.hmac, KeyReadArgs::new(input).into(), label, None, &mut drivers.trng, KeyWriteArgs::new( KEY_ID_TMP, KeyUsage::default() .set_hmac_key_en() .set_ecc_key_gen_seed_en() .set_mldsa_key_gen_seed_en(), ) .into(), HmacMode::Hmac384, )?; let pub_key = drivers.ecc384.key_pair( KeyReadArgs::new(KEY_ID_TMP).into(), &Array4x12::default(), &mut drivers.trng, KeyWriteArgs::new(priv_key, KeyUsage::default().set_ecc_private_key_en()).into(), ); if KEY_ID_TMP != priv_key { drivers.key_vault.erase_key(KEY_ID_TMP)?; } else { cfi_assert_eq(KEY_ID_TMP, priv_key); } Ok(Ecc384KeyPair { priv_key, pub_key: pub_key?, }) } pub enum Hmac {} impl Hmac { /// Calculate HMAC-384 KDF /// /// # Arguments /// /// * `drivers` - Drivers /// * `key` - HMAC384 key slot /// * `label` - Input label /// * `context` - Input context /// * `output` - Key slot to store the output #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn hmac_kdf( drivers: &mut Drivers, key: KeyId, label: &[u8], context: Option<&[u8]>, mode: HmacMode, output: KeyId, ) -> CaliptraResult<()> { hmac_kdf( &mut drivers.hmac, KeyReadArgs::new(key).into(), label, context, &mut drivers.trng, KeyWriteArgs::new( output, KeyUsage::default() .set_hmac_key_en() .set_ecc_key_gen_seed_en() .set_mldsa_key_gen_seed_en(), ) .into(), mode, ) } /// Perform an "HMAC" with a key from KV by first using it to derive an /// ECC keypair, then hashing the public key coordinates into an HMAC key. /// This roundabout mechanism is necessary because the hardware does not /// directly support exposing an HMAC computed with key material from KV. /// Note that the derived public key is considered secret. /// /// # Arguments /// /// * `drivers` - Drivers /// * `input` - KeyId containing the input data /// * `label` - Used to diversify the key material before it is used to compute an ECC keypair /// * `data` - Data provided to HMAC /// /// # Returns /// /// * `Array4x12` - Computed HMAC result #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn ecc384_hmac( drivers: &mut Drivers, input: KeyId, label: &[u8], data: &[u8], ) -> CaliptraResult<Array4x12> { let keypair_result = ecc384_key_gen(drivers, input, label, KEY_ID_TMP); cfi_check!(keypair_result); let mut keypair = keypair_result?; let mut pubkey_digest = Array4x12::default(); // Done in a closure to ensure state is always cleaned up. let hmac_result = || -> CaliptraResult<Array4x12> { let mut hasher = drivers.sha2_512_384.sha384_digest_init()?; hasher.update(keypair.pub_key.x.as_bytes())?; hasher.update(keypair.pub_key.y.as_bytes())?; hasher.finalize(&mut pubkey_digest)?; let mut hmac_output = Array4x12::default(); drivers.hmac.hmac( HmacKey::Array4x12(&pubkey_digest), HmacData::Slice(data), &mut drivers.trng, HmacTag::Array4x12(&mut hmac_output), HmacMode::Hmac384, )?; Ok(hmac_output) }(); // Clean up state. unsafe { caliptra_drivers::Sha2_512_384::zeroize() } pubkey_digest.zeroize(); keypair.pub_key.zeroize(); drivers.key_vault.erase_key(keypair.priv_key)?; hmac_result } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/tagging.rs
runtime/src/tagging.rs
/*++ Licensed under the Apache-2.0 license. File Name: tagging.rs Abstract: File contains mailbox commands dealing with tagging. --*/ use crate::{mutrefbytes, Drivers}; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::{ GetTaggedTciReq, GetTaggedTciResp, MailboxRespHeader, TagTciReq, }; use caliptra_error::{CaliptraError, CaliptraResult}; use dpe::{context::ContextHandle, U8Bool, MAX_HANDLES}; use zerocopy::FromBytes; pub struct TagTciCmd; impl TagTciCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult<usize> { let cmd = TagTciReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; let pdata_mut = drivers.persistent_data.get_mut(); let dpe = &mut pdata_mut.fw.dpe.state; let context_has_tag = &mut pdata_mut.fw.dpe.context_has_tag; let context_tags = &mut pdata_mut.fw.dpe.context_tags; // Make sure the tag isn't used by any other contexts. if (0..MAX_HANDLES).any(|i| { i < context_has_tag.len() && i < context_tags.len() && context_has_tag[i].get() && context_tags[i] == cmd.tag }) { return Err(CaliptraError::RUNTIME_DUPLICATE_TAG); } let locality = drivers.mbox.id(); let idx = dpe .get_active_context_pos(&ContextHandle(cmd.handle), locality) .map_err(|_| CaliptraError::RUNTIME_TAGGING_FAILURE)?; // Make sure the context doesn't already have a tag if context_has_tag[idx].get() { return Err(CaliptraError::RUNTIME_CONTEXT_ALREADY_TAGGED); } context_has_tag[idx] = U8Bool::new(true); context_tags[idx] = cmd.tag; Ok(0) } } pub struct GetTaggedTciCmd; impl GetTaggedTciCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute( drivers: &Drivers, cmd_args: &[u8], resp: &mut [u8], ) -> CaliptraResult<usize> { let cmd = GetTaggedTciReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; let persistent_data = drivers.persistent_data.get(); let context_has_tag = &persistent_data.fw.dpe.context_has_tag; let context_tags = &persistent_data.fw.dpe.context_tags; let idx = (0..MAX_HANDLES) .find(|i| { *i < context_has_tag.len() && *i < context_tags.len() && context_has_tag[*i].get() && context_tags[*i] == cmd.tag }) .ok_or(CaliptraError::RUNTIME_TAGGING_FAILURE)?; if idx >= persistent_data.fw.dpe.state.contexts.len() { return Err(CaliptraError::RUNTIME_TAGGING_FAILURE); } let context = persistent_data.fw.dpe.state.contexts[idx]; let resp = mutrefbytes::<GetTaggedTciResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.tci_cumulative = context.tci.tci_cumulative.0; resp.tci_current = context.tci.tci_current.0; Ok(core::mem::size_of::<GetTaggedTciResp>()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/get_fmc_alias_csr.rs
runtime/src/get_fmc_alias_csr.rs
// Licensed under the Apache-2.0 license use crate::{mutrefbytes, Drivers}; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::{GetFmcAliasCsrResp, MailboxRespHeader, ResponseVarSize}; use caliptra_error::{CaliptraError, CaliptraResult}; use caliptra_drivers::FmcAliasCsrs; pub struct GetFmcAliasCsrCmd; impl GetFmcAliasCsrCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, mbox_resp: &mut [u8]) -> CaliptraResult<usize> { let csr_persistent_mem = &drivers.persistent_data.get().fw.fmc_alias_csr; match csr_persistent_mem.get_ecc_csr_len() { FmcAliasCsrs::UNPROVISIONED_CSR => { Err(CaliptraError::RUNTIME_GET_FMC_CSR_UNPROVISIONED) } 0 => Err(CaliptraError::RUNTIME_GET_FMC_CSR_UNSUPPORTED_FMC), _ => { // the compiler has trouble understanding that csr.len() is the same // as csr_persistent_mem.get_csr_len() let csr = csr_persistent_mem .get_ecc_csr() .ok_or(CaliptraError::RUNTIME_GET_FMC_CSR_UNPROVISIONED)?; let resp = mutrefbytes::<GetFmcAliasCsrResp>(mbox_resp)?; resp.hdr = MailboxRespHeader::default(); resp.data_size = csr.len() as u32; resp.data[..csr.len()].copy_from_slice(csr); Ok(resp.partial_len()?) } } } } pub struct GetFmcAliasMldsaCsrCmd; impl GetFmcAliasMldsaCsrCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, mbox_resp: &mut [u8]) -> CaliptraResult<usize> { let csr_persistent_mem = &drivers.persistent_data.get().fw.fmc_alias_csr; match csr_persistent_mem.get_mldsa_csr_len() { FmcAliasCsrs::UNPROVISIONED_CSR => { Err(CaliptraError::RUNTIME_GET_FMC_CSR_UNPROVISIONED) } 0 => Err(CaliptraError::RUNTIME_GET_FMC_CSR_UNSUPPORTED_FMC), _ => { // the compiler has trouble understanding that csr.len() is the same // as csr_persistent_mem.get_csr_len() let csr = csr_persistent_mem .get_mldsa_csr() .ok_or(CaliptraError::RUNTIME_GET_FMC_CSR_UNPROVISIONED)?; let resp = mutrefbytes::<GetFmcAliasCsrResp>(mbox_resp)?; resp.hdr = MailboxRespHeader::default(); resp.data_size = csr.len() as u32; resp.data[..csr.len()].copy_from_slice(csr); Ok(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/runtime/src/handoff.rs
runtime/src/handoff.rs
/*++ Licensed under the Apache-2.0 license. File Name: handoff.rs Abstract: File contains helper functions that extract values from the FirmwareHandoffTable and DataVault. --*/ use caliptra_common::DataStore::KeyVaultSlot; use caliptra_drivers::{hand_off::DataStore, DataVault, FirmwareHandoffTable, KeyId}; use caliptra_error::{CaliptraError, CaliptraResult}; pub struct RtHandoff<'a> { pub data_vault: &'a DataVault, pub fht: &'a FirmwareHandoffTable, } impl RtHandoff<'_> { fn read_as_kv(&self, ds: DataStore) -> CaliptraResult<KeyId> { match ds { KeyVaultSlot(key_id) => Ok(key_id), _ => Err(CaliptraError::RUNTIME_INTERNAL), } } /// Retrieve firmware SVN. pub fn fw_svn(&self) -> u32 { self.data_vault.fw_svn() } /// Retrieve firmware minimum SVN. pub fn fw_min_svn(&self) -> u32 { self.data_vault.fw_min_svn() } /// Retrieve cold-boot firmware SVN. pub fn cold_boot_fw_svn(&self) -> u32 { self.data_vault.cold_boot_fw_svn() } /// Retrieve the FW key ladder. pub fn fw_key_ladder(&self) -> CaliptraResult<KeyId> { self.read_as_kv(self.fht.fw_key_ladder_kv_hdl.try_into()?) .map_err(|_| CaliptraError::RUNTIME_KEY_LADDER_HANDOFF_FAILED) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/mailbox.rs
runtime/src/mailbox.rs
/*++ Licensed under the Apache-2.0 license. File Name: mailbox.rs Abstract: File contains mailbox interface. --*/ use core::mem::size_of; use core::slice; use caliptra_drivers::{memory_layout, CaliptraResult, SocIfc}; use caliptra_error::CaliptraError; use caliptra_registers::mbox::{ enums::{MboxFsmE, MboxStatusE}, MboxCsr, }; use zerocopy::{FromBytes, IntoBytes, Unalign}; use crate::CommandId; // Mailbox size when in subsystem mode. const MBOX_SIZE_SUBSYSTEM: u32 = 16 * 1024; // Mailbox size when in passive mode. const MBOX_SIZE_PASSIVE: u32 = 256 * 1024; pub struct Mailbox { mbox: MboxCsr, mbox_len: u32, } impl Mailbox { /// Create a new 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(caliptra_registers::soc_ifc::SocIfcReg::new()) }; if soc_ifc.subsystem_mode() { MBOX_SIZE_SUBSYSTEM } else { MBOX_SIZE_PASSIVE } } /// Check if there is a new command to be executed pub fn is_cmd_ready(&self) -> bool { let mbox = self.mbox.regs(); mbox.status().read().mbox_fsm_ps().mbox_execute_uc() } /// Check if we are currently executing a mailbox command pub fn cmd_busy(&self) -> bool { let mbox = self.mbox.regs(); mbox.status().read().status().cmd_busy() } /// Get the current state of the mailbox FSM pub fn mailbox_state(&self) -> MboxFsmE { let mbox = self.mbox.regs(); mbox.status().read().mbox_fsm_ps() } /// Get the length of the current mailbox data in bytes pub fn dlen(&self) -> u32 { let mbox = self.mbox.regs(); mbox.dlen().read() } /// Set the length of the current mailbox data in bytes pub fn set_dlen(&mut self, len: u32) -> CaliptraResult<()> { if len > self.mbox_len { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } let mbox = self.mbox.regs_mut(); mbox.dlen().write(|_| len); Ok(()) } /// Get the length of the current mailbox data in words pub fn dlen_words(&self) -> u32 { (self.dlen() + 3) / 4 } /// Get the CommandId from the mailbox pub fn cmd(&self) -> CommandId { let mbox = self.mbox.regs(); let cmd_code = mbox.cmd().read(); CommandId(cmd_code) } /// Lock the mailbox pub fn lock(&mut self) -> bool { let mbox = self.mbox.regs(); mbox.lock().read().lock() } /// Unlock the mailbox pub fn unlock(&mut self) { let mbox = self.mbox.regs_mut(); mbox.unlock().write(|_| 1.into()); } /// Writes command `cmd` ot the mailbox if it is ready for a command pub fn write_cmd(&mut self, cmd: u32) -> CaliptraResult<()> { let mbox = self.mbox.regs_mut(); match mbox.status().read().mbox_fsm_ps() { MboxFsmE::MboxRdyForCmd => { mbox.cmd().write(|_| cmd); Ok(()) } _ => Err(CaliptraError::RUNTIME_INTERNAL), } } /// Gets the id of the mailbox pub fn id(&self) -> u32 { let mbox = self.mbox.regs(); mbox.user().read() } /// Copies data in mailbox to `buf` pub fn copy_from_mbox(&mut self, buf: &mut [u32]) { let mbox = self.mbox.regs_mut(); for word in buf { *word = mbox.dataout().read(); } } /// Clears the mailbox pub fn flush(&mut self) { let count = self.dlen_words(); let mbox = self.mbox.regs_mut(); for _ii in 0..count { let _ = mbox.dataout().read(); } } /// Copies `buf` to the mailbox pub fn copy_words_to_mbox(&mut self, buf: &[Unalign<u32>]) { let mbox = self.mbox.regs_mut(); for word in buf { mbox.datain().write(|_| word.get()); } } /// Copies word-aligned `buf` to the mailbox pub fn copy_bytes_to_mbox(&mut self, buf: &[u8]) -> CaliptraResult<()> { let count = buf.len() / size_of::<u32>(); let (buf_words, suffix) = <[Unalign<u32>]>::ref_from_prefix_with_elems(buf, count).unwrap(); self.copy_words_to_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); self.copy_words_to_mbox(&[Unalign::new(last_word)]); } Ok(()) } /// Write a word-aligned `buf` to the mailbox pub fn write_response(&mut self, buf: &[u8]) -> CaliptraResult<()> { self.set_dlen(buf.len() as u32)?; self.copy_bytes_to_mbox(buf)?; Ok(()) } /// Set mailbox status to `status` pub fn set_status(&mut self, status: MboxStatusE) { let mbox = self.mbox.regs_mut(); mbox.status().write(|w| w.status(|_| status)); } /// Retrieve a slice with the contents of the mailbox pub fn raw_mailbox_contents(&self) -> &[u8] { unsafe { slice::from_raw_parts(memory_layout::MBOX_ORG as *const u8, self.mbox_len 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/runtime/src/packet.rs
runtime/src/packet.rs
/*++ Licensed under the Apache-2.0 license. File Name: packet.rs Abstract: File contains an API that reads commands and writes responses to the mailbox. --*/ use caliptra_drivers::CaliptraResult; use caliptra_common::mailbox_api::MailboxReqHeader; use caliptra_drivers::CaliptraError; use zerocopy::FromBytes; #[derive(Debug)] pub struct Packet { pub cmd: u32, // Using raw pointer to avoid lifetime issues payload_ptr: *const u8, payload_len: usize, } impl Packet { /// Retrieves the data in the mailbox and converts it into a Packet pub fn get_from_mbox(drivers: &mut crate::Drivers) -> CaliptraResult<Self> { let mbox = &mut drivers.mbox; let cmd = mbox.cmd(); let dlen = mbox.dlen() as usize; // Get reference to raw mailbox contents let raw_data = mbox.raw_mailbox_contents(); // Create the packet with raw pointers to the mailbox data let packet = Packet { cmd: cmd.into(), payload_ptr: raw_data.as_ptr(), payload_len: dlen, }; // Verify incoming checksum // Make sure enough data was sent to even have a checksum if packet.payload().len() < core::mem::size_of::<MailboxReqHeader>() { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } // Assumes chksum is always offset 0 let req_hdr: &MailboxReqHeader = MailboxReqHeader::ref_from_bytes( &packet.payload()[..core::mem::size_of::<MailboxReqHeader>()], ) .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; if !caliptra_common::checksum::verify_checksum( req_hdr.chksum, packet.cmd, &packet.payload()[core::mem::size_of_val(&req_hdr.chksum)..], ) { return Err(CaliptraError::RUNTIME_INVALID_CHECKSUM); } Ok(packet) } /// Returns the byte representation of the packet's payload pub fn as_bytes(&self) -> CaliptraResult<&[u8]> { Ok(self.payload()) } /// Get a reference to the payload data pub fn payload(&self) -> &[u8] { unsafe { // Safety: This is safe because: // 1. None of the mailbox request handlers use the mailbox in a way that // modifies the mailbox sram content before sending back a reply. core::slice::from_raw_parts(self.payload_ptr, self.payload_len) } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/get_image_info.rs
runtime/src/get_image_info.rs
/*++ Licensed under the Apache-2.0 license. File Name: get_image_info.rs Abstract: File contains GET_IMAGE_INFO mailbox command. --*/ use crate::Drivers; use crate::{manifest::find_metadata_entry, mutrefbytes}; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::{GetImageInfoReq, GetImageInfoResp, MailboxRespHeader}; use caliptra_drivers::{CaliptraError, CaliptraResult}; use zerocopy::FromBytes; pub struct GetImageInfoCmd; impl GetImageInfoCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, cmd_args: &[u8], resp: &mut [u8], ) -> CaliptraResult<usize> { if let Ok(cmd) = GetImageInfoReq::ref_from_bytes(cmd_args) { let metadata = find_metadata_entry( &drivers .persistent_data .get() .fw .auth_manifest_image_metadata_col, u32::from_le_bytes(cmd.fw_id), ) .ok_or(CaliptraError::RUNTIME_IMAGE_METADATA_NOT_FOUND)?; let resp = mutrefbytes::<GetImageInfoResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.component_id = metadata.component_id; resp.flags = metadata.flags; resp.image_load_address_high = metadata.image_load_address.hi; resp.image_load_address_low = metadata.image_load_address.lo; resp.image_staging_address_high = metadata.image_staging_address.hi; resp.image_staging_address_low = metadata.image_staging_address.lo; Ok(core::mem::size_of::<GetImageInfoResp>()) } else { Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY) } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/fips.rs
runtime/src/fips.rs
/*++ Licensed under the Apache-2.0 license. File Name: fips.rs Abstract: File contains FIPS module and FIPS self test. --*/ use caliptra_cfi_derive_git::{cfi_impl_fn, cfi_mod_fn}; use caliptra_common::cprintln; use caliptra_drivers::CaliptraError; use caliptra_drivers::CaliptraResult; use caliptra_drivers::Ecc384; use caliptra_drivers::Hmac; use caliptra_drivers::KeyVault; use caliptra_drivers::Sha256; use caliptra_drivers::Sha2_512_384; use caliptra_drivers::Sha2_512_384Acc; use zeroize::Zeroize; use crate::Drivers; pub struct FipsModule; /// Fips command handler. impl FipsModule { /// Clear data structures in DCCM. #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] fn zeroize(env: &mut Drivers) { unsafe { // Zeroize the crypto blocks. Ecc384::zeroize(); Hmac::zeroize(); Sha256::zeroize(); Sha2_512_384::zeroize(); Sha2_512_384Acc::zeroize(); // Zeroize the key vault. KeyVault::zeroize(); // Lock the SHA Accelerator. Sha2_512_384Acc::lock(); } #[cfg(feature = "fips-test-hooks")] unsafe { caliptra_drivers::FipsTestHook::halt_if_hook_set( caliptra_drivers::FipsTestHook::HALT_SHUTDOWN_RT, ) }; env.persistent_data.get_mut().zeroize(); } } #[cfg(feature = "fips_self_test")] pub mod fips_self_test_cmd { use super::*; use crate::RtBootStatus::{RtFipSelfTestComplete, RtFipSelfTestStarted}; use caliptra_cfi_lib_git::cfi_assert_eq_8_words; use caliptra_common::{verifier::FirmwareImageVerificationEnv, FMC_SIZE, RUNTIME_SIZE}; use caliptra_drivers::{ResetReason, ShaAccLockState}; use caliptra_image_types::{ImageTocEntry, RomInfo}; use caliptra_image_verify::ImageVerifier; use zerocopy::IntoBytes; // Helper function to create a slice from a memory region unsafe fn create_slice(toc: &ImageTocEntry) -> &'static [u8] { let ptr = toc.load_addr as *mut u8; core::slice::from_raw_parts(ptr, toc.size as usize) } pub enum SelfTestStatus { Idle, InProgress(fn(&mut Drivers) -> CaliptraResult<()>), Done, } #[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)] fn copy_and_verify_image(env: &mut Drivers) -> CaliptraResult<()> { let fmc_toc = &env.persistent_data.get().rom.manifest1.fmc; let rt_toc = &env.persistent_data.get().rom.manifest1.runtime; if fmc_toc.size > FMC_SIZE { return Err(CaliptraError::RUNTIME_INVALID_FMC_SIZE); } if rt_toc.size > RUNTIME_SIZE { return Err(CaliptraError::RUNTIME_INVALID_RUNTIME_SIZE); } let manifest = env.persistent_data.get().rom.manifest1.as_bytes(); let fmc = unsafe { create_slice(fmc_toc) }; let rt = unsafe { create_slice(rt_toc) }; let image_source = caliptra_common::verifier::ImageSource::FipsTest { manifest, fmc, runtime: rt, }; let mut venv = FirmwareImageVerificationEnv { sha256: &mut env.sha256, sha2_512_384: &mut env.sha2_512_384, sha2_512_384_acc: &mut env.sha2_512_384_acc, soc_ifc: &mut env.soc_ifc, ecc384: &mut env.ecc384, mldsa87: &mut env.mldsa87, data_vault: &env.persistent_data.get().rom.data_vault, pcr_bank: &mut env.pcr_bank, image_source, persistent_data: &env.persistent_data.get(), }; let mut verifier = ImageVerifier::new(&mut venv); let _info = verifier.verify( &env.persistent_data.get().rom.manifest1, env.persistent_data.get().rom.manifest1.size + env.persistent_data.get().rom.manifest1.fmc.size + env.persistent_data.get().rom.manifest1.runtime.size, ResetReason::UpdateReset, )?; cprintln!("[rt] Verify complete"); Ok(()) } #[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)] pub(crate) fn execute(env: &mut Drivers) -> CaliptraResult<()> { caliptra_drivers::report_boot_status(RtFipSelfTestStarted.into()); cprintln!("[rt] FIPS self test"); execute_kats(env)?; rom_integrity_test(env)?; copy_and_verify_image(env)?; caliptra_drivers::report_boot_status(RtFipSelfTestComplete.into()); Ok(()) } /// Execute KAT for cryptographic algorithms implemented in H/W. fn execute_kats(env: &mut Drivers) -> CaliptraResult<()> { let mut kats_env = caliptra_kat::KatsEnv { // SHA1 Engine sha1: &mut env.sha1, // sha256 sha256: &mut env.sha256, // SHA2-512/384 Engine sha2_512_384: &mut env.sha2_512_384, // SHA2-512/384 Accelerator sha2_512_384_acc: &mut env.sha2_512_384_acc, // SHA3/SHAKE sha3: &mut env.sha3, // Hmac-512/384 Engine hmac: &mut env.hmac, // Cryptographically Secure Random Number Generator trng: &mut env.trng, // LMS Engine lms: &mut env.lms, // MLDSA87 Engine mldsa87: &mut env.mldsa87, // Ecc384 Engine ecc384: &mut env.ecc384, // AES Engine, aes: &mut env.aes, // SHA Acc Lock State sha_acc_lock_state: ShaAccLockState::NotAcquired, }; caliptra_kat::execute_kat(&mut kats_env)?; Ok(()) } #[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)] fn rom_integrity_test(env: &mut Drivers) -> CaliptraResult<()> { // Extract the expected has from the fht. let rom_info = env.persistent_data.get().rom.fht.rom_info_addr.get()?; // WARNING: It is undefined behavior to dereference a zero (null) pointer in // rust code. This is only safe because the dereference is being done by an // an assembly routine ([`ureg::opt_riscv::copy_16_words`]) rather // than dereferencing directly in Rust. #[allow(clippy::zero_ptr)] let rom_start = 0 as *const [u32; 16]; let n_blocks = env.persistent_data.get().rom.fht.rom_info_addr.get()? as *const RomInfo as usize / 64; let mut digest = unsafe { env.sha256.digest_blocks_raw(rom_start, n_blocks)? }; if digest.0 != rom_info.sha256_digest { digest.zeroize(); cprintln!("ROM integrity test failed"); return Err(CaliptraError::ROM_INTEGRITY_FAILURE); } else { cfi_assert_eq_8_words(&digest.0, &rom_info.sha256_digest); } digest.zeroize(); // Run digest function and compare with expected hash. Ok(()) } } pub struct FipsShutdownCmd; impl FipsShutdownCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(env: &mut Drivers) -> CaliptraResult<usize> { FipsModule::zeroize(env); env.is_shutdown = true; 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/runtime/src/lib.rs
runtime/src/lib.rs
/*++ Licensed under the Apache-2.0 license. File Name: lib.rs Abstract: File contains exports for the Runtime library and mailbox command handling logic. --*/ #![cfg_attr(not(feature = "fips_self_test"), allow(unused))] #![no_std] mod activate_firmware; mod authorize_and_stash; mod capabilities; mod certify_key_extended; mod cryptographic_mailbox; mod debug_unlock; pub mod dice; mod disable; mod dpe_crypto; mod dpe_platform; mod drivers; mod fe_programming; pub mod fips; mod firmware_verify; mod get_fmc_alias_csr; mod get_idev_csr; mod get_image_info; pub mod handoff; mod hmac; pub mod info; mod invoke_dpe; pub mod key_ladder; pub mod manifest; mod ocp_lock; mod pcr; mod populate_idev; mod reallocate_dpe_context_limits; mod recovery_flow; mod revoke_exported_cdi_handle; mod set_auth_manifest; mod sign_with_exported_ecdsa; mod sign_with_exported_mldsa; mod stash_measurement; mod subject_alt_name; mod update; mod verify; // Used by runtime tests pub mod mailbox; use authorize_and_stash::AuthorizeAndStashCmd; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_assert_ne, cfi_launder, CfiCounter}; use caliptra_common::cfi_check; use caliptra_common::mailbox_api::{ExternalMailboxCmdReq, MailboxReqHeader}; pub use drivers::{Drivers, PauserPrivileges}; use fe_programming::FeProgrammingCmd; use mailbox::Mailbox; use populate_idev::PopulateIDevIdMldsa87CertCmd; use zerocopy::{FromBytes, IntoBytes, KnownLayout}; use crate::capabilities::CapabilitiesCmd; pub use crate::certify_key_extended::CertifyKeyExtendedCmd; pub use crate::hmac::Hmac; use crate::revoke_exported_cdi_handle::RevokeExportedCdiHandleCmd; use crate::sign_with_exported_ecdsa::SignWithExportedEcdsaCmd; pub use crate::subject_alt_name::AddSubjectAltNameCmd; pub use activate_firmware::ActivateFirmwareCmd; pub use authorize_and_stash::{IMAGE_AUTHORIZED, IMAGE_HASH_MISMATCH, IMAGE_NOT_AUTHORIZED}; pub use caliptra_common::fips::FipsVersionCmd; use caliptra_common::mailbox_api::{populate_checksum, FipsVersionResp, MAX_RESP_SIZE}; pub use dice::{GetFmcAliasCertCmd, GetLdevCertCmd, IDevIdCertCmd}; pub use disable::DisableAttestationCmd; use dpe_crypto::DpeCrypto; pub use dpe_platform::{DpePlatform, VENDOR_ID, VENDOR_SKU}; pub use fips::FipsShutdownCmd; #[cfg(feature = "fips_self_test")] pub use fips::{fips_self_test_cmd, fips_self_test_cmd::SelfTestStatus}; pub use populate_idev::PopulateIDevIdEcc384CertCmd; pub use get_fmc_alias_csr::GetFmcAliasCsrCmd; pub use get_idev_csr::{GetIdevCsrCmd, GetIdevMldsaCsrCmd}; pub use get_image_info::GetImageInfoCmd; pub use info::{FwInfoCmd, IDevIdInfoCmd}; pub use invoke_dpe::InvokeDpeCmd; pub use key_ladder::KeyLadder; pub use pcr::{GetPcrLogCmd, IncrementPcrResetCounterCmd}; pub use reallocate_dpe_context_limits::ReallocateDpeContextLimitsCmd; pub use set_auth_manifest::SetAuthManifestCmd; pub use stash_measurement::StashMeasurementCmd; pub use verify::LmsVerifyCmd; pub mod packet; use caliptra_common::mailbox_api::{AlgorithmType, CommandId}; use packet::Packet; pub mod tagging; use tagging::{GetTaggedTciCmd, TagTciCmd}; use caliptra_common::cprintln; use caliptra_drivers::{AxiAddr, CaliptraError, CaliptraResult, ResetReason}; use caliptra_registers::mbox::enums::MboxStatusE; pub use dpe::{context::ContextState, tci::TciMeasurement, DpeInstance, U8Bool, MAX_HANDLES}; use dpe::{ dpe_instance::{DpeEnv, DpeTypes}, support::Support, }; use crate::{ dice::GetRtAliasCertCmd, pcr::{ExtendPcrCmd, GetPcrQuoteCmd}, }; const RUNTIME_BOOT_STATUS_BASE: u32 = 0x600; /// Statuses used by ROM to log dice derivation progress. #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum RtBootStatus { // RtAlias Statuses RtReadyForCommands = RUNTIME_BOOT_STATUS_BASE, RtFipSelfTestStarted = RUNTIME_BOOT_STATUS_BASE + 1, RtFipSelfTestComplete = RUNTIME_BOOT_STATUS_BASE + 2, } impl From<RtBootStatus> for u32 { /// Converts to this type from the input type. fn from(status: RtBootStatus) -> u32 { status as u32 } } pub const DPE_SUPPORT: Support = Support::all(); pub const MAX_ECC_CERT_CHAIN_SIZE: usize = 4096; pub const MAX_MLDSA_CERT_CHAIN_SIZE: usize = 31_000; pub const PL0_PAUSER_FLAG: u32 = 1; pub const PL0_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD: usize = 16; pub const PL1_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD: usize = 16; pub const PL0_DPE_ACTIVE_CONTEXT_THRESHOLD_MIN: usize = 2; pub const CALIPTRA_LOCALITY: u32 = 0xFFFFFFFF; const RESERVED_PAUSER: u32 = CALIPTRA_LOCALITY; #[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 struct CptraDpeTypes; impl DpeTypes for CptraDpeTypes { type Crypto<'a> = DpeCrypto<'a>; type Platform<'a> = DpePlatform<'a>; } /// Run pending jobs and enter low power mode. fn enter_idle(drivers: &mut Drivers) { // Run pending jobs before entering low power mode. #[cfg(feature = "fips_self_test")] if let SelfTestStatus::InProgress(execute) = drivers.self_test_status { let lock = drivers.mbox.lock(); if !lock { let result = execute(drivers); drivers.mbox.unlock(); match result { Ok(_) => drivers.self_test_status = SelfTestStatus::Done, Err(e) => caliptra_common::handle_fatal_error(e.into()), } } else { cfi_assert!(lock); // Don't enter low power mode when in progress return; } } #[cfg(feature = "riscv")] caliptra_cpu::csr::mpmc_halt_and_enable_interrupts(); } fn human_readable_command(bytes: &[u8]) -> Option<&str> { if bytes.len() == 4 && bytes.iter().all(|c| c.is_ascii_alphanumeric()) { // Safety: we just checked that all bytes are ASCII. Some(unsafe { core::str::from_utf8_unchecked(bytes) }) } else { None } } /// Handles the pending mailbox command and writes the repsonse back to the mailbox /// /// # Returns /// /// * `MboxStatusE` - the mailbox status (DataReady when we send a response) fn handle_command(drivers: &mut Drivers) -> CaliptraResult<MboxStatusE> { // Drop all commands for invalid PAUSER if drivers.mbox.id() == RESERVED_PAUSER { return Err(CaliptraError::RUNTIME_CMD_RESERVED_PAUSER); } // For firmware update, don't read data from the mailbox if drivers.mbox.cmd() == CommandId::FIRMWARE_LOAD { cfi_assert_eq(drivers.mbox.cmd(), CommandId::FIRMWARE_LOAD); update::handle_impactless_update(drivers)?; // If the handler succeeds but does not invoke reset that is // unexpected. Denote that the update failed. return Err(CaliptraError::RUNTIME_UNEXPECTED_UPDATE_RETURN); } else { cfi_assert_ne(drivers.mbox.cmd(), CommandId::FIRMWARE_LOAD); } if drivers.mbox.cmd() == CommandId::FIRMWARE_VERIFY { return firmware_verify::FirmwareVerifyCmd::execute( drivers, firmware_verify::VerifySrc::Mbox, ); } else { cfi_assert_ne(drivers.mbox.cmd(), CommandId::FIRMWARE_VERIFY); } // Get the command bytes let req_packet = Packet::get_from_mbox(drivers)?; let mut cmd_bytes = req_packet.as_bytes()?; let mut cmd_id = req_packet.cmd; if let Some(ascii) = human_readable_command(&cmd_id.to_be_bytes()) { cprintln!( "[rt] Received command=0x{:x} ({}), len={}", req_packet.cmd, ascii, req_packet.payload().len() ); } else { cprintln!( "[rt] Received command=0x{:x}, len={}", req_packet.cmd, req_packet.payload().len() ); } let mut external_cmd_buffer = [0; caliptra_common::mailbox_api::MAX_REQ_SIZE / size_of::<u32>()]; // Check for EXTERNAL_MAILBOX_CMD and handle FIRMWARE_VERIFY specially if drivers.soc_ifc.subsystem_mode() && CommandId::from(cmd_id) == CommandId::EXTERNAL_MAILBOX_CMD { let external_cmd = ExternalMailboxCmdReq::read_from_bytes(cmd_bytes) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; if external_cmd.command_id == CommandId::FIRMWARE_VERIFY.into() { let axi_addr = AxiAddr { lo: external_cmd.axi_address_start_low, hi: external_cmd.axi_address_start_high, }; return firmware_verify::FirmwareVerifyCmd::execute( drivers, firmware_verify::VerifySrc::External { axi_address: axi_addr, image_size: external_cmd.command_size, }, ); } } if let Some(ext) = handle_external_mailbox_cmd(cmd_id, cmd_bytes, drivers, &mut external_cmd_buffer)? { cmd_id = ext.cmd_id; cmd_bytes = external_cmd_buffer .as_bytes() .get(..ext.cmd_size) .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; } // stage the response once on the stack let resp = &mut [0u8; MAX_RESP_SIZE][..]; let len = match CommandId::from(cmd_id) { CommandId::ACTIVATE_FIRMWARE => { activate_firmware::ActivateFirmwareCmd::execute(drivers, cmd_bytes, resp) } CommandId::FIRMWARE_LOAD => Err(CaliptraError::RUNTIME_UNIMPLEMENTED_COMMAND), CommandId::FIRMWARE_VERIFY => Err(CaliptraError::RUNTIME_UNIMPLEMENTED_COMMAND), CommandId::GET_IDEV_ECC384_CERT => { IDevIdCertCmd::execute(cmd_bytes, AlgorithmType::Ecc384, resp) } CommandId::GET_IDEV_ECC384_INFO => { IDevIdInfoCmd::execute(drivers, AlgorithmType::Ecc384, resp) } CommandId::GET_IDEV_MLDSA87_INFO => { IDevIdInfoCmd::execute(drivers, AlgorithmType::Mldsa87, resp) } CommandId::GET_IDEV_MLDSA87_CERT => { IDevIdCertCmd::execute(cmd_bytes, AlgorithmType::Mldsa87, resp) } CommandId::GET_LDEV_ECC384_CERT => { GetLdevCertCmd::execute(drivers, AlgorithmType::Ecc384, resp) } CommandId::GET_LDEV_MLDSA87_CERT => { GetLdevCertCmd::execute(drivers, AlgorithmType::Mldsa87, resp) } CommandId::INVOKE_DPE => InvokeDpeCmd::execute(drivers, cmd_bytes, resp), CommandId::ECDSA384_SIGNATURE_VERIFY => { caliptra_common::verify::EcdsaVerifyCmd::execute(&mut drivers.ecc384, cmd_bytes) } CommandId::LMS_SIGNATURE_VERIFY => LmsVerifyCmd::execute(drivers, cmd_bytes), CommandId::MLDSA87_SIGNATURE_VERIFY => { caliptra_common::verify::MldsaVerifyCmd::execute(&mut drivers.mldsa87, cmd_bytes) } CommandId::EXTEND_PCR => ExtendPcrCmd::execute(drivers, cmd_bytes), CommandId::STASH_MEASUREMENT => StashMeasurementCmd::execute(drivers, cmd_bytes, resp), CommandId::DISABLE_ATTESTATION => DisableAttestationCmd::execute(drivers), CommandId::AUTHORIZE_AND_STASH => AuthorizeAndStashCmd::execute(drivers, cmd_bytes, resp), CommandId::CAPABILITIES => CapabilitiesCmd::execute(drivers, resp), CommandId::FW_INFO => FwInfoCmd::execute(drivers, resp), CommandId::DPE_TAG_TCI => TagTciCmd::execute(drivers, cmd_bytes), CommandId::DPE_GET_TAGGED_TCI => GetTaggedTciCmd::execute(drivers, cmd_bytes, resp), CommandId::POPULATE_IDEV_ECC384_CERT => { PopulateIDevIdEcc384CertCmd::execute(drivers, cmd_bytes) } CommandId::POPULATE_IDEV_MLDSA87_CERT => { PopulateIDevIdMldsa87CertCmd::execute(drivers, cmd_bytes) } CommandId::GET_FMC_ALIAS_ECC384_CERT => { GetFmcAliasCertCmd::execute(drivers, AlgorithmType::Ecc384, resp) } CommandId::GET_FMC_ALIAS_MLDSA87_CERT => { GetFmcAliasCertCmd::execute(drivers, AlgorithmType::Mldsa87, resp) } CommandId::GET_RT_ALIAS_ECC384_CERT => { GetRtAliasCertCmd::execute(drivers, AlgorithmType::Ecc384, resp) } CommandId::GET_RT_ALIAS_MLDSA87_CERT => { GetRtAliasCertCmd::execute(drivers, AlgorithmType::Mldsa87, resp) } CommandId::ADD_SUBJECT_ALT_NAME => AddSubjectAltNameCmd::execute(drivers, cmd_bytes), CommandId::CERTIFY_KEY_EXTENDED => CertifyKeyExtendedCmd::execute(drivers, cmd_bytes, resp), CommandId::INCREMENT_PCR_RESET_COUNTER => { IncrementPcrResetCounterCmd::execute(drivers, cmd_bytes) } CommandId::QUOTE_PCRS_ECC384 => { GetPcrQuoteCmd::execute(drivers, AlgorithmType::Ecc384, cmd_bytes, resp) } CommandId::QUOTE_PCRS_MLDSA87 => { GetPcrQuoteCmd::execute(drivers, AlgorithmType::Mldsa87, cmd_bytes, resp) } CommandId::VERSION => FipsVersionCmd::execute(&drivers.soc_ifc) .write_to_prefix(resp) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY) .map(|_| core::mem::size_of::<FipsVersionResp>()), #[cfg(feature = "fips_self_test")] CommandId::SELF_TEST_START => match drivers.self_test_status { SelfTestStatus::Idle => { drivers.self_test_status = SelfTestStatus::InProgress(fips_self_test_cmd::execute); Ok(0) } _ => Err(CaliptraError::RUNTIME_SELF_TEST_IN_PROGRESS), }, #[cfg(feature = "fips_self_test")] CommandId::SELF_TEST_GET_RESULTS => match drivers.self_test_status { SelfTestStatus::Done => { drivers.self_test_status = SelfTestStatus::Idle; Ok(0) } _ => Err(CaliptraError::RUNTIME_SELF_TEST_NOT_STARTED), }, CommandId::SHUTDOWN => FipsShutdownCmd::execute(drivers), CommandId::SET_AUTH_MANIFEST => SetAuthManifestCmd::execute(drivers, cmd_bytes, false), CommandId::VERIFY_AUTH_MANIFEST => SetAuthManifestCmd::execute(drivers, cmd_bytes, true), CommandId::GET_IDEV_ECC384_CSR => GetIdevCsrCmd::execute(drivers, resp), CommandId::GET_IDEV_MLDSA87_CSR => GetIdevMldsaCsrCmd::execute(drivers, resp), CommandId::GET_FMC_ALIAS_ECC384_CSR => GetFmcAliasCsrCmd::execute(drivers, resp), CommandId::GET_FMC_ALIAS_MLDSA87_CSR => { get_fmc_alias_csr::GetFmcAliasMldsaCsrCmd::execute(drivers, resp) } CommandId::GET_PCR_LOG => GetPcrLogCmd::execute(drivers, resp), CommandId::SIGN_WITH_EXPORTED_ECDSA => { SignWithExportedEcdsaCmd::execute(drivers, cmd_bytes, resp) } CommandId::REVOKE_EXPORTED_CDI_HANDLE => { RevokeExportedCdiHandleCmd::execute(drivers, cmd_bytes) } CommandId::GET_IMAGE_INFO => GetImageInfoCmd::execute(drivers, cmd_bytes, resp), // Cryptographic mailbox commands CommandId::CM_IMPORT => cryptographic_mailbox::Commands::import(drivers, cmd_bytes, resp), CommandId::CM_DELETE => cryptographic_mailbox::Commands::delete(drivers, cmd_bytes, resp), CommandId::CM_CLEAR => cryptographic_mailbox::Commands::clear(drivers, resp), CommandId::CM_STATUS => cryptographic_mailbox::Commands::status(drivers, resp), CommandId::CM_SHA_INIT => { cryptographic_mailbox::Commands::sha_init(drivers, cmd_bytes, resp) } CommandId::CM_SHA_UPDATE => { cryptographic_mailbox::Commands::sha_update(drivers, cmd_bytes, resp) } CommandId::CM_SHA_FINAL => { cryptographic_mailbox::Commands::sha_final(drivers, cmd_bytes, resp) } CommandId::CM_RANDOM_GENERATE => { cryptographic_mailbox::Commands::random_generate(drivers, cmd_bytes, resp) } CommandId::CM_RANDOM_STIR => { cryptographic_mailbox::Commands::random_stir(drivers, cmd_bytes) } CommandId::CM_AES_ENCRYPT_INIT => { cryptographic_mailbox::Commands::aes_256_encrypt_init(drivers, cmd_bytes, resp) } CommandId::CM_AES_ENCRYPT_UPDATE => { cryptographic_mailbox::Commands::aes_256_encrypt_update(drivers, cmd_bytes, resp) } CommandId::CM_AES_DECRYPT_INIT => { cryptographic_mailbox::Commands::aes_256_cbc_decrypt_init(drivers, cmd_bytes, resp) } CommandId::CM_AES_DECRYPT_UPDATE => { cryptographic_mailbox::Commands::aes_256_cbc_decrypt_update(drivers, cmd_bytes, resp) } CommandId::CM_AES_GCM_ENCRYPT_INIT => { cryptographic_mailbox::Commands::aes_256_gcm_encrypt_init(drivers, cmd_bytes, resp) } CommandId::CM_AES_GCM_SPDM_ENCRYPT_INIT => { cryptographic_mailbox::Commands::aes_256_gcm_spdm_encrypt_init(drivers, cmd_bytes, resp) } CommandId::CM_AES_GCM_ENCRYPT_UPDATE => { cryptographic_mailbox::Commands::aes_256_gcm_encrypt_update(drivers, cmd_bytes, resp) } CommandId::CM_AES_GCM_ENCRYPT_FINAL => { cryptographic_mailbox::Commands::aes_256_gcm_encrypt_final(drivers, cmd_bytes, resp) } CommandId::CM_AES_GCM_DECRYPT_INIT => { cryptographic_mailbox::Commands::aes_256_gcm_decrypt_init(drivers, cmd_bytes, resp) } CommandId::CM_AES_GCM_SPDM_DECRYPT_INIT => { cryptographic_mailbox::Commands::aes_256_gcm_spdm_decrypt_init(drivers, cmd_bytes, resp) } CommandId::CM_AES_GCM_DECRYPT_UPDATE => { cryptographic_mailbox::Commands::aes_256_gcm_decrypt_update(drivers, cmd_bytes, resp) } CommandId::CM_AES_GCM_DECRYPT_FINAL => { cryptographic_mailbox::Commands::aes_256_gcm_decrypt_final(drivers, cmd_bytes, resp) } CommandId::CM_ECDH_GENERATE => { cryptographic_mailbox::Commands::ecdh_generate(drivers, cmd_bytes, resp) } CommandId::CM_ECDH_FINISH => { cryptographic_mailbox::Commands::ecdh_finish(drivers, cmd_bytes, resp) } CommandId::CM_HMAC => cryptographic_mailbox::Commands::hmac(drivers, cmd_bytes, resp), CommandId::CM_HMAC_KDF_COUNTER => { cryptographic_mailbox::Commands::hmac_kdf_counter(drivers, cmd_bytes, resp) } CommandId::CM_HKDF_EXTRACT => { cryptographic_mailbox::Commands::hkdf_extract(drivers, cmd_bytes, resp) } CommandId::CM_HKDF_EXPAND => { cryptographic_mailbox::Commands::hkdf_expand(drivers, cmd_bytes, resp) } CommandId::CM_MLDSA_PUBLIC_KEY => { cryptographic_mailbox::Commands::mldsa_public_key(drivers, cmd_bytes, resp) } CommandId::CM_MLDSA_SIGN => { cryptographic_mailbox::Commands::mldsa_sign(drivers, cmd_bytes, resp) } CommandId::CM_MLDSA_VERIFY => { cryptographic_mailbox::Commands::mldsa_verify(drivers, cmd_bytes, resp) } CommandId::CM_ECDSA_PUBLIC_KEY => { cryptographic_mailbox::Commands::ecdsa_public_key(drivers, cmd_bytes, resp) } CommandId::CM_ECDSA_SIGN => { cryptographic_mailbox::Commands::ecdsa_sign(drivers, cmd_bytes, resp) } CommandId::CM_ECDSA_VERIFY => { cryptographic_mailbox::Commands::ecdsa_verify(drivers, cmd_bytes, resp) } CommandId::CM_DERIVE_STABLE_KEY => { cryptographic_mailbox::Commands::derive_stable_key(drivers, cmd_bytes, resp) } CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_REQ => drivers.debug_unlock.handle_request( &mut drivers.trng, &drivers.soc_ifc, cmd_bytes, resp, ), CommandId::PRODUCTION_AUTH_DEBUG_UNLOCK_TOKEN => drivers.debug_unlock.handle_token( &mut drivers.soc_ifc, &mut drivers.sha2_512_384, &mut drivers.sha2_512_384_acc, &mut drivers.ecc384, &mut drivers.mldsa87, &mut drivers.dma, cmd_bytes, ), CommandId::FE_PROG => FeProgrammingCmd::execute(drivers, cmd_bytes), CommandId::REALLOCATE_DPE_CONTEXT_LIMITS => { ReallocateDpeContextLimitsCmd::execute(drivers, cmd_bytes, resp) } ocp_lock_command_id @ CommandId::OCP_LOCK_GET_ALGORITHMS | ocp_lock_command_id @ CommandId::OCP_LOCK_INITIALIZE_MEK_SECRET | ocp_lock_command_id @ CommandId::OCP_LOCK_DERIVE_MEK => { ocp_lock::command_handler(ocp_lock_command_id, drivers, cmd_bytes, resp) } _ => Err(CaliptraError::RUNTIME_UNIMPLEMENTED_COMMAND), }?; let len = len.max(8); // guarantee it is big enough to hold the header if len > MAX_RESP_SIZE { // should be impossible return Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY); } let mbox = &mut drivers.mbox; let resp = &mut resp[..len]; // Generate response checksum populate_checksum(resp); // Send the payload mbox.write_response(resp)?; // zero the original resp buffer so as not to leak sensitive data resp.fill(0); Ok(MboxStatusE::DataReady) } struct ExternalCommand { cmd_id: u32, cmd_size: usize, } /// Handles an external mailbox command. If a valid external command was parsed, /// then Some is returned and the external mailbox command will be copied into /// the external_cmd_buffer argument. fn handle_external_mailbox_cmd( cmd_id: u32, cmd_bytes: &[u8], drivers: &mut Drivers, external_cmd_buffer: &mut [u32], ) -> CaliptraResult<Option<ExternalCommand>> { if !drivers.soc_ifc.subsystem_mode() || CommandId::from(cmd_id) != CommandId::EXTERNAL_MAILBOX_CMD { return Ok(None); } let external_cmd = ExternalMailboxCmdReq::read_from_bytes(cmd_bytes) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; let cmd_id = external_cmd.command_id; let axi_addr = AxiAddr { lo: external_cmd.axi_address_start_low, hi: external_cmd.axi_address_start_high, }; if cmd_id == CommandId::FIRMWARE_LOAD.into() { cfi_assert_eq(cmd_id, CommandId::FIRMWARE_LOAD.into()); update::handle_impactless_update(drivers)?; // If the handler succeeds but does not invoke reset that is // unexpected. Denote that the update failed. return Err(CaliptraError::RUNTIME_UNEXPECTED_UPDATE_RETURN); } else { cfi_assert_ne(cmd_id, CommandId::FIRMWARE_LOAD.into()); } // FIRMWARE_VERIFY is handled earlier in handle_command() before this function is called cfi_assert_ne(cmd_id, CommandId::FIRMWARE_VERIFY.into()); if let Some(ascii) = human_readable_command(&cmd_id.to_be_bytes()) { cprintln!( "[rt] Loading external command=0x{:x} ({}), len={} from AXI address: 0x{:x}", external_cmd.command_id, ascii, external_cmd.command_size, u64::from(axi_addr), ); } else { cprintln!( "[rt] Loading external command=0x{:x}, len={} from AXI address: 0x{:x}", external_cmd.command_id, external_cmd.command_size, u64::from(axi_addr), ); } // check that the command is not too large if external_cmd.command_size as usize > caliptra_common::mailbox_api::MAX_REQ_SIZE { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } let buffer = external_cmd_buffer .get_mut(..external_cmd.command_size as usize / size_of::<u32>()) .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; drivers.dma.read_buffer(axi_addr, buffer); let cmd_bytes = buffer.as_bytes(); // Verify incoming checksum // Make sure enough data was sent to even have a checksum if cmd_bytes.len() < core::mem::size_of::<MailboxReqHeader>() { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } // Assumes chksum is always offset 0 let req_hdr: &MailboxReqHeader = MailboxReqHeader::ref_from_bytes(&cmd_bytes[..core::mem::size_of::<MailboxReqHeader>()]) .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; if !caliptra_common::checksum::verify_checksum( req_hdr.chksum, cmd_id, &cmd_bytes[core::mem::size_of_val(&req_hdr.chksum)..], ) { return Err(CaliptraError::RUNTIME_INVALID_CHECKSUM); } if let Some(ascii) = human_readable_command(&cmd_id.to_be_bytes()) { cprintln!( "[rt] Received external command=0x{:x} ({}), len={}", cmd_id, ascii, cmd_bytes.len() ); } else { cprintln!( "[rt] Received external command=0x{:x}, len={}", cmd_id, cmd_bytes.len() ); } Ok(Some(ExternalCommand { cmd_id, cmd_size: cmd_bytes.len(), })) } #[cfg(feature = "riscv")] // TODO implement in emulator fn setup_mailbox_wfi(drivers: &mut Drivers) { use caliptra_drivers::IntSource; caliptra_cpu::csr::mie_enable_external_interrupts(); // Set highest priority so that Int can wake CPU drivers.pic.int_set_max_priority(IntSource::SocIfcNotif); drivers.pic.int_enable(IntSource::SocIfcNotif); drivers.soc_ifc.enable_mbox_notif_interrupts(); } /// Handles mailbox commands when the command is ready pub fn handle_mailbox_commands(drivers: &mut Drivers) -> CaliptraResult<()> { // Indicator to SOC that RT firmware is ready drivers.soc_ifc.assert_ready_for_runtime(); caliptra_drivers::report_boot_status(RtBootStatus::RtReadyForCommands.into()); // Disable attestation if in the middle of executing an mbox cmd during warm reset let command_was_running = drivers .persistent_data .get() .fw .dpe .runtime_cmd_active .get(); if command_was_running { let reset_reason = drivers.soc_ifc.reset_reason(); if reset_reason == ResetReason::WarmReset { cfi_assert_eq(drivers.soc_ifc.reset_reason(), ResetReason::WarmReset); let result = DisableAttestationCmd::execute(drivers); cfi_check!(result); match result { Ok(_) => { cprintln!("Disabled attestation due to cmd busy during warm reset"); caliptra_drivers::report_fw_error_non_fatal( CaliptraError::RUNTIME_CMD_BUSY_DURING_WARM_RESET.into(), ); } Err(e) => { cprintln!("{}", e.0); return Err(CaliptraError::RUNTIME_GLOBAL_EXCEPTION); } } } } else { cfi_assert!(!command_was_running); } #[cfg(feature = "riscv")] setup_mailbox_wfi(drivers); caliptra_common::wdt::stop_wdt(&mut drivers.soc_ifc); loop { if drivers.is_shutdown { return Err(CaliptraError::RUNTIME_SHUTDOWN); } // No command is executing, set the mailbox flow done to true before beginning idle. drivers.soc_ifc.flow_status_set_mailbox_flow_done(true); drivers.persistent_data.get_mut().fw.dpe.runtime_cmd_active = U8Bool::new(false); enter_idle(drivers); // Random delay for CFI glitch protection. CfiCounter::delay(); // The hardware will set this interrupt high when the mbox_fsm_ps // transitions to state MBOX_EXECUTE_UC (same state as mbox.is_cmd_ready()), // but once cleared will not set it high again until the state // transitions away from MBOX_EXECUTE_UC and back. let cmd_ready = drivers.soc_ifc.has_mbox_notif_status(); if cmd_ready { // We have woken from idle and have a command ready, set the mailbox flow done to false until we return to // idle. drivers.soc_ifc.flow_status_set_mailbox_flow_done(false); drivers.persistent_data.get_mut().fw.dpe.runtime_cmd_active = U8Bool::new(true); // Acknowledge the interrupt so we go back to sleep after // processing the mailbox. After this point, if the mailbox is // still in the MBOX_EXECUTE_UC state before going back to // sleep, we will hang. drivers.soc_ifc.clear_mbox_notif_status(); if !drivers.mbox.is_cmd_ready() { // This is expected after boot, as the ROM did not clear the // interrupt status when processing FIRMWARE_LOAD continue; } // TODO : Move start/stop WDT to wait_for_cmd when NMI is implemented. caliptra_common::wdt::start_wdt( &mut drivers.soc_ifc, caliptra_common::WdtTimeout::default(), ); // Clear non-fatal error before processing command caliptra_drivers::clear_fw_error_non_fatal(drivers.persistent_data.get_mut()); let command_result = handle_command(drivers); cfi_check!(command_result); match command_result { Ok(status) => { drivers.mbox.set_status(status); } Err(e) => { caliptra_drivers::report_fw_error_non_fatal(e.into()); drivers.mbox.set_status(MboxStatusE::CmdFailure); } } caliptra_common::wdt::stop_wdt(&mut drivers.soc_ifc); } else { cfi_assert!(!cmd_ready); } } // Ok(()) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/update.rs
runtime/src/update.rs
/*++ Licensed under the Apache-2.0 license. File Name: update.rs Abstract: File contains FirmwareLoad mailbox command. --*/ use crate::Drivers; use caliptra_cfi_derive_git::cfi_mod_fn; use caliptra_drivers::{CaliptraError, CaliptraResult}; #[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)] pub(crate) fn handle_impactless_update(drivers: &mut Drivers) -> CaliptraResult<()> { let cycles = drivers.soc_ifc.internal_fw_update_reset_wait_cycles(); for _ in 0..cycles { drivers.soc_ifc.assert_fw_update_reset(); } Err(CaliptraError::RUNTIME_UNEXPECTED_UPDATE_RETURN) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/dice.rs
runtime/src/dice.rs
/*++ Licensed under the Apache-2.0 license. File Name: dice.rs Abstract: File contains mailbox commands related to DICE certificates. --*/ use crate::{mutrefbytes, Drivers}; use caliptra_common::{ dice::{ copy_ldevid_ecc384_cert, copy_ldevid_mldsa87_cert, ecc384_cert_from_tbs_and_sig, mldsa87_cert_from_tbs_and_sig, }, mailbox_api::{ AlgorithmType, GetFmcAliasEcc384CertResp, GetFmcAliasMlDsa87CertResp, GetIdevCertResp, GetIdevEcc384CertReq, GetIdevMldsa87CertReq, GetLdevCertResp, GetRtAliasCertResp, MailboxRespHeader, ResponseVarSize, }, }; use caliptra_drivers::{ CaliptraError, CaliptraResult, Ecc384Signature, Mldsa87Signature, PersistentData, }; use caliptra_x509::{Ecdsa384CertBuilder, Ecdsa384Signature, MlDsa87CertBuilder}; use zerocopy::IntoBytes; pub struct IDevIdCertCmd; impl IDevIdCertCmd { #[inline(never)] pub(crate) fn execute( cmd_args: &[u8], alg_type: AlgorithmType, resp: &mut [u8], ) -> CaliptraResult<usize> { let resp = mutrefbytes::<GetIdevCertResp>(resp)?; resp.hdr = MailboxRespHeader::default(); match alg_type { AlgorithmType::Ecc384 => { if cmd_args.len() <= core::mem::size_of::<GetIdevEcc384CertReq>() { let mut cmd = GetIdevEcc384CertReq::default(); cmd.as_mut_bytes()[..cmd_args.len()].copy_from_slice(cmd_args); // Validate tbs if cmd.tbs_size as usize > cmd.tbs.len() { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } let sig = Ecdsa384Signature { r: cmd.signature_r, s: cmd.signature_s, }; let Some(builder) = Ecdsa384CertBuilder::new(&cmd.tbs[..cmd.tbs_size as usize], &sig) else { return Err(CaliptraError::RUNTIME_GET_IDEVID_CERT_FAILED); }; let Some(cert_size) = builder.build(&mut resp.data) else { return Err(CaliptraError::RUNTIME_GET_IDEVID_CERT_FAILED); }; resp.data_size = cert_size as u32; Ok(resp.partial_len()?) } else { Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY) } } AlgorithmType::Mldsa87 => { if cmd_args.len() <= core::mem::size_of::<GetIdevMldsa87CertReq>() { let mut cmd = GetIdevMldsa87CertReq::default(); cmd.as_mut_bytes()[..cmd_args.len()].copy_from_slice(cmd_args); // Validate tbs if cmd.tbs_size as usize > cmd.tbs.len() { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } let sig = caliptra_x509::MlDsa87Signature { sig: cmd.signature[..4627] .try_into() .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?, }; let Some(builder) = MlDsa87CertBuilder::new(&cmd.tbs[..cmd.tbs_size as usize], &sig) else { return Err(CaliptraError::RUNTIME_GET_IDEVID_CERT_FAILED); }; let Some(cert_size) = builder.build(&mut resp.data) else { return Err(CaliptraError::RUNTIME_GET_IDEVID_CERT_FAILED); }; resp.data_size = cert_size as u32; Ok(resp.partial_len()?) } else { Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY) } } } } } pub struct GetLdevCertCmd; impl GetLdevCertCmd { #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, 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(drivers.persistent_data.get(), &mut resp.data)? as u32; } AlgorithmType::Mldsa87 => { resp.data_size = copy_ldevid_mldsa87_cert(drivers.persistent_data.get(), &mut resp.data)? as u32; } } resp.partial_len() } } pub struct GetFmcAliasCertCmd; impl GetFmcAliasCertCmd { #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, alg_type: AlgorithmType, resp: &mut [u8], ) -> CaliptraResult<usize> { match alg_type { AlgorithmType::Ecc384 => { let resp = mutrefbytes::<GetFmcAliasEcc384CertResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.data_size = copy_fmc_alias_ecc384_cert(drivers.persistent_data.get(), &mut resp.data)? as u32; resp.partial_len() } AlgorithmType::Mldsa87 => { let resp = mutrefbytes::<GetFmcAliasMlDsa87CertResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.data_size = copy_fmc_alias_mldsa87_cert(drivers.persistent_data.get(), &mut resp.data)? as u32; resp.partial_len() } } } } pub struct GetRtAliasCertCmd; impl GetRtAliasCertCmd { #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, alg_type: AlgorithmType, resp: &mut [u8], ) -> CaliptraResult<usize> { match alg_type { AlgorithmType::Ecc384 => { let resp = mutrefbytes::<GetRtAliasCertResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.data_size = copy_rt_alias_ecc384_cert(drivers.persistent_data.get(), &mut resp.data)? as u32; resp.partial_len() } AlgorithmType::Mldsa87 => { let resp = mutrefbytes::<GetRtAliasCertResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.data_size = copy_rt_alias_mldsa87_cert(drivers.persistent_data.get(), &mut resp.data)? as u32; resp.partial_len() } } } } /// Piece together the r and s portions of the FMC alias cert signature /// /// # Arguments /// /// * `persistent_data` - PersistentData /// /// # Returns /// /// * `Ecc384Signature` - The formed signature pub fn fmc_dice_sign(persistent_data: &PersistentData) -> Ecc384Signature { persistent_data.rom.data_vault.fmc_dice_ecc_signature() } /// Retrieve the MLDSA87 signature for the FMC alias cert /// /// # Arguments /// /// * `persistent_data` - PersistentData /// /// # Returns /// /// * `Mldsa87Signature` - The formed signature pub fn fmc_dice_sign_mldsa87(persistent_data: &PersistentData) -> Mldsa87Signature { persistent_data.rom.data_vault.fmc_dice_mldsa_signature() } /// Copy FMC alias 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_fmc_alias_ecc384_cert( persistent_data: &PersistentData, cert: &mut [u8], ) -> CaliptraResult<usize> { let tbs = persistent_data .rom .ecc_fmcalias_tbs .get(..persistent_data.rom.fht.ecc_fmcalias_tbs_size.into()); let sig = fmc_dice_sign(persistent_data); ecc384_cert_from_tbs_and_sig(tbs, &sig, cert) .map_err(|_| CaliptraError::RUNTIME_GET_FMC_ALIAS_CERT_FAILED) } /// Copy FMC alias MLDSA87 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_fmc_alias_mldsa87_cert( persistent_data: &PersistentData, cert: &mut [u8], ) -> CaliptraResult<usize> { let tbs = persistent_data .rom .mldsa_fmcalias_tbs .get(..persistent_data.rom.fht.mldsa_fmcalias_tbs_size.into()); let sig = fmc_dice_sign_mldsa87(persistent_data); mldsa87_cert_from_tbs_and_sig(tbs, &sig, cert) .map_err(|_| CaliptraError::RUNTIME_GET_FMC_ALIAS_CERT_FAILED) } /// Copy RT Alias certificate produced by FMC 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_rt_alias_ecc384_cert( persistent_data: &PersistentData, cert: &mut [u8], ) -> CaliptraResult<usize> { let tbs = persistent_data .fw .ecc_rtalias_tbs .get(..persistent_data.rom.fht.rtalias_ecc_tbs_size.into()); ecc384_cert_from_tbs_and_sig(tbs, &persistent_data.rom.fht.rt_dice_ecc_sign, cert) .map_err(|_| CaliptraError::RUNTIME_GET_RT_ALIAS_CERT_FAILED) } /// Copy RT Alias MLDSA87 certificate produced by FMC to `cert` buffer /// /// # Arguments /// /// * `persistent_data` - PersistentData /// * `cert` - Buffer to copy RT Alias MLDSA87 certificate to /// /// # Returns /// /// * `usize` - The number of bytes written to `cert` #[inline(never)] pub fn copy_rt_alias_mldsa87_cert( persistent_data: &PersistentData, cert: &mut [u8], ) -> CaliptraResult<usize> { let tbs = persistent_data .fw .mldsa_rtalias_tbs .get(..persistent_data.fw.rtalias_mldsa_tbs_size.into()); mldsa87_cert_from_tbs_and_sig(tbs, &persistent_data.fw.rt_dice_mldsa_sign, cert) .map_err(|_| CaliptraError::RUNTIME_GET_RT_ALIAS_CERT_FAILED) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/sign_with_exported_mldsa.rs
runtime/src/sign_with_exported_mldsa.rs
// Licensed under the Apache-2.0 license use crate::Drivers; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_error::{CaliptraError, CaliptraResult}; #[allow(dead_code)] pub struct SignWithExportedMldsaCmd; impl SignWithExportedMldsaCmd { #[allow(dead_code)] #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute( _drivers: &mut Drivers, _cmd_args: &[u8], _resp: &mut [u8], ) -> CaliptraResult<usize> { // [TODO][CAP2] Err(CaliptraError::RUNTIME_SIGN_WITH_EXPORTED_MLDSA_NOT_SUPPORTED)? } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/manifest.rs
runtime/src/manifest.rs
/*++ Licensed under the Apache-2.0 license. File Name: manifest.rs Abstract: File contains utilities related to the auth manifest. --*/ use caliptra_auth_man_types::{AuthManifestImageMetadata, AuthManifestImageMetadataCollection}; /// Search for a metadata entry in the sorted `AuthManifestImageMetadataCollection` that matches the firmware ID. /// /// This function performs a binary search on the `image_metadata_list` of the provided `AuthManifestImageMetadataCollection`. /// It compares the firmware ID (`fw_id`) of each metadata entry with the provided `cmd_fw_id`. /// /// # Arguments /// /// * `auth_manifest_image_metadata_col` - A reference to the `AuthManifestImageMetadataCollection` containing the metadata entries. /// * `cmd_fw_id` - The firmware ID from the command to search for. /// /// # Returns /// /// * `Option<&AuthManifestImageMetadata>` - Returns `Some(&AuthManifestImageMetadata)` if a matching entry is found, /// otherwise returns `None`. /// #[inline(never)] pub fn find_metadata_entry( auth_manifest_image_metadata_col: &AuthManifestImageMetadataCollection, cmd_fw_id: u32, ) -> Option<&AuthManifestImageMetadata> { auth_manifest_image_metadata_col .image_metadata_list .binary_search_by(|metadata| metadata.fw_id.cmp(&cmd_fw_id)) .ok() .map(|index| { auth_manifest_image_metadata_col .image_metadata_list .get(index) })? }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/dpe_crypto.rs
runtime/src/dpe_crypto.rs
/*++ Licensed under the Apache-2.0 license. File Name: dpe_crypto.rs Abstract: File contains DpeCrypto implementation. --*/ #[cfg(not(feature = "no-cfi"))] use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::keyids::{ KEY_ID_DPE_CDI, KEY_ID_DPE_PRIV_KEY, KEY_ID_EXPORTED_DPE_CDI, KEY_ID_TMP, }; use caliptra_drivers::{ hmac_kdf, sha2_512_384::{Sha2DigestOpTrait, Sha384}, Array4x12, Ecc384, Ecc384PrivKeyIn, Ecc384PubKey, Ecc384Scalar, Ecc384Seed, ExportedCdiEntry, ExportedCdiHandles, Hmac, HmacMode, KeyId, KeyReadArgs, KeyUsage, KeyVault, KeyWriteArgs, Sha2DigestOp, Sha2_512_384, Trng, }; use constant_time_eq::constant_time_eq; use crypto::{AlgLen, Crypto, CryptoBuf, CryptoError, Digest, EcdsaPub, EcdsaSig, Hasher}; use dpe::{ExportedCdiHandle, U8Bool, MAX_EXPORTED_CDI_SIZE}; pub struct DpeCrypto<'a> { sha2_512_384: &'a mut Sha2_512_384, trng: &'a mut Trng, ecc384: &'a mut Ecc384, hmac: &'a mut Hmac, key_vault: &'a mut KeyVault, rt_pub_key: &'a mut Ecc384PubKey, key_id_rt_cdi: KeyId, key_id_rt_priv_key: KeyId, exported_cdi_slots: &'a mut ExportedCdiHandles, } impl<'a> DpeCrypto<'a> { #[allow(clippy::too_many_arguments)] pub fn new( sha2_512_384: &'a mut Sha2_512_384, trng: &'a mut Trng, ecc384: &'a mut Ecc384, hmac: &'a mut Hmac, key_vault: &'a mut KeyVault, rt_pub_key: &'a mut Ecc384PubKey, key_id_rt_cdi: KeyId, key_id_rt_priv_key: KeyId, exported_cdi_slots: &'a mut ExportedCdiHandles, ) -> Self { Self { sha2_512_384, trng, ecc384, hmac, key_vault, rt_pub_key, key_id_rt_cdi, key_id_rt_priv_key, exported_cdi_slots, } } fn derive_cdi_inner( &mut self, algs: AlgLen, measurement: &Digest, info: &[u8], key_id: KeyId, ) -> Result<<DpeCrypto<'a> as crypto::Crypto>::Cdi, CryptoError> { match algs { AlgLen::Bit256 => Err(CryptoError::Size), AlgLen::Bit384 => { let mut hasher = self.hash_initialize(algs)?; hasher.update(measurement.bytes())?; hasher.update(info)?; let context = hasher.finish()?; hmac_kdf( self.hmac, KeyReadArgs::new(self.key_id_rt_cdi).into(), b"derive_cdi", Some(context.bytes()), self.trng, KeyWriteArgs::new( key_id, KeyUsage::default() .set_hmac_key_en() .set_ecc_key_gen_seed_en(), ) .into(), HmacMode::Hmac384, ) .map_err(|e| CryptoError::CryptoLibError(u32::from(e)))?; Ok(key_id) } } } fn derive_key_pair_inner( &mut self, algs: AlgLen, cdi: &<DpeCrypto<'a> as crypto::Crypto>::Cdi, label: &[u8], info: &[u8], key_id: KeyId, ) -> Result<(<DpeCrypto<'a> as crypto::Crypto>::PrivKey, EcdsaPub), CryptoError> { match algs { AlgLen::Bit256 => Err(CryptoError::Size), AlgLen::Bit384 => { hmac_kdf( self.hmac, KeyReadArgs::new(*cdi).into(), label, Some(info), self.trng, KeyWriteArgs::new(KEY_ID_TMP, KeyUsage::default().set_ecc_key_gen_seed_en()) .into(), HmacMode::Hmac384, ) .map_err(|e| CryptoError::CryptoLibError(u32::from(e)))?; let pub_key = self .ecc384 .key_pair( Ecc384Seed::Key(KeyReadArgs::new(KEY_ID_TMP)), &Array4x12::default(), self.trng, KeyWriteArgs::new(key_id, KeyUsage::default().set_ecc_private_key_en()) .into(), ) .map_err(|e| CryptoError::CryptoLibError(u32::from(e)))?; let pub_key = EcdsaPub { x: CryptoBuf::new(&<[u8; AlgLen::Bit384.size()]>::from(pub_key.x)) .map_err(|_| CryptoError::Size)?, y: CryptoBuf::new(&<[u8; AlgLen::Bit384.size()]>::from(pub_key.y)) .map_err(|_| CryptoError::Size)?, }; Ok((key_id, pub_key)) } } } pub fn get_cdi_from_exported_handle( &mut self, exported_cdi_handle: &[u8; MAX_EXPORTED_CDI_SIZE], ) -> Option<<DpeCrypto<'a> as crypto::Crypto>::Cdi> { for cdi_slot in self.exported_cdi_slots.entries.iter() { match cdi_slot { ExportedCdiEntry { key, handle, active, } if active.get() && constant_time_eq(handle, exported_cdi_handle) => { return Some(*key) } _ => (), } } None } } impl Drop for DpeCrypto<'_> { fn drop(&mut self) { let _ = self.key_vault.erase_key(KEY_ID_DPE_CDI); let _ = self.key_vault.erase_key(KEY_ID_DPE_PRIV_KEY); let _ = self.key_vault.erase_key(KEY_ID_TMP); } } pub struct DpeHasher<'a> { op: Sha2DigestOp<'a, Sha384>, } impl<'a> DpeHasher<'a> { pub fn new(op: Sha2DigestOp<'a, Sha384>) -> Self { Self { op } } } impl Hasher for DpeHasher<'_> { fn update(&mut self, bytes: &[u8]) -> Result<(), CryptoError> { self.op .update(bytes) .map_err(|e| CryptoError::HashError(u32::from(e))) } fn finish(self) -> Result<Digest, CryptoError> { let mut digest = Array4x12::default(); self.op .finalize(&mut digest) .map_err(|e| CryptoError::HashError(u32::from(e)))?; Digest::new(<[u8; AlgLen::Bit384.size()]>::from(digest).as_ref()) } } impl Crypto for DpeCrypto<'_> { type Cdi = KeyId; type Hasher<'b> = DpeHasher<'b> where Self: 'b; type PrivKey = KeyId; fn rand_bytes(&mut self, dst: &mut [u8]) -> Result<(), CryptoError> { for chunk in dst.chunks_mut(48) { let trng_bytes = <[u8; 48]>::from( self.trng .generate() .map_err(|e| CryptoError::CryptoLibError(u32::from(e)))?, ); chunk.copy_from_slice(&trng_bytes[..chunk.len()]) } Ok(()) } fn hash_initialize(&mut self, algs: AlgLen) -> Result<Self::Hasher<'_>, CryptoError> { match algs { AlgLen::Bit256 => Err(CryptoError::Size), AlgLen::Bit384 => { let op = self .sha2_512_384 .sha384_digest_init() .map_err(|e| CryptoError::HashError(u32::from(e)))?; Ok(DpeHasher::new(op)) } } } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn derive_exported_cdi( &mut self, algs: AlgLen, measurement: &Digest, info: &[u8], ) -> Result<ExportedCdiHandle, CryptoError> { let mut exported_cdi_handle = [0; MAX_EXPORTED_CDI_SIZE]; self.rand_bytes(&mut exported_cdi_handle)?; // Currently we only use one slot for export CDIs. let cdi_slot = KEY_ID_EXPORTED_DPE_CDI; // Copy the CDI slots to work around the borrow checker. let mut slots_clone = self.exported_cdi_slots.clone(); for slot in slots_clone.entries.iter_mut() { match slot { // Matching existing slot ExportedCdiEntry { key, handle: _, active, } if active.get() && *key == cdi_slot => { Err(CryptoError::ExportedCdiHandleDuplicateCdi)? } ExportedCdiEntry { key: _, handle: _, active, } if !active.get() => { // Empty slot let cdi = self.derive_cdi_inner(algs, measurement, info, cdi_slot)?; *slot = ExportedCdiEntry { key: cdi, handle: exported_cdi_handle, active: U8Bool::new(true), }; // We need to update `self.exported_cdi_slots` with our mutation. *self.exported_cdi_slots = slots_clone; return Ok(exported_cdi_handle); } // Used slot for a different CDI. _ => (), } } // Never found an available slot. Err(CryptoError::ExportedCdiHandleLimitExceeded) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn derive_cdi( &mut self, algs: AlgLen, measurement: &Digest, info: &[u8], ) -> Result<Self::Cdi, CryptoError> { self.derive_cdi_inner(algs, measurement, info, KEY_ID_DPE_CDI) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn derive_key_pair( &mut self, algs: AlgLen, cdi: &Self::Cdi, label: &[u8], info: &[u8], ) -> Result<(Self::PrivKey, EcdsaPub), CryptoError> { self.derive_key_pair_inner(algs, cdi, label, info, KEY_ID_DPE_PRIV_KEY) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn derive_key_pair_exported( &mut self, algs: AlgLen, exported_handle: &ExportedCdiHandle, label: &[u8], info: &[u8], ) -> Result<(Self::PrivKey, EcdsaPub), CryptoError> { let cdi = { let mut cdi = None; for cdi_slot in self.exported_cdi_slots.entries.iter() { match cdi_slot { ExportedCdiEntry { key, handle, active, } if active.get() && constant_time_eq(handle, exported_handle) => { cdi = Some(*key); break; } _ => (), } } cdi.ok_or(CryptoError::InvalidExportedCdiHandle) }?; self.derive_key_pair_inner(algs, &cdi, label, info, KEY_ID_TMP) } fn ecdsa_sign_with_alias( &mut self, algs: AlgLen, digest: &Digest, ) -> Result<EcdsaSig, CryptoError> { let pub_key = EcdsaPub { x: CryptoBuf::new(&<[u8; AlgLen::Bit384.size()]>::from(self.rt_pub_key.x)) .map_err(|_| CryptoError::Size)?, y: CryptoBuf::new(&<[u8; AlgLen::Bit384.size()]>::from(self.rt_pub_key.y)) .map_err(|_| CryptoError::Size)?, }; self.ecdsa_sign_with_derived(algs, digest, &self.key_id_rt_priv_key.clone(), &pub_key) } fn ecdsa_sign_with_derived( &mut self, algs: AlgLen, digest: &Digest, priv_key: &Self::PrivKey, pub_key: &EcdsaPub, ) -> Result<EcdsaSig, CryptoError> { match algs { AlgLen::Bit256 => Err(CryptoError::Size), AlgLen::Bit384 => { let priv_key_args = KeyReadArgs::new(*priv_key); let ecc_priv_key = Ecc384PrivKeyIn::Key(priv_key_args); const SIZE: usize = AlgLen::Bit384.size(); let mut x = [0u8; SIZE]; let mut y = [0u8; SIZE]; x.get_mut(..SIZE) .ok_or(CryptoError::CryptoLibError(0))? .copy_from_slice( pub_key .x .bytes() .get(..SIZE) .ok_or(CryptoError::CryptoLibError(0))?, ); y.get_mut(..SIZE) .ok_or(CryptoError::CryptoLibError(0))? .copy_from_slice( pub_key .y .bytes() .get(..SIZE) .ok_or(CryptoError::CryptoLibError(0))?, ); let ecc_pub_key = Ecc384PubKey { x: Ecc384Scalar::from(x), y: Ecc384Scalar::from(y), }; let mut digest_arr = [0u8; SIZE]; digest_arr .get_mut(..SIZE) .ok_or(CryptoError::CryptoLibError(0))? .copy_from_slice( digest .bytes() .get(..SIZE) .ok_or(CryptoError::CryptoLibError(0))?, ); let sig = self .ecc384 .sign( ecc_priv_key, &ecc_pub_key, &Ecc384Scalar::from(digest_arr), self.trng, ) .map_err(|e| CryptoError::CryptoLibError(u32::from(e)))?; let r = CryptoBuf::new(&<[u8; SIZE]>::from(sig.r))?; let s = CryptoBuf::new(&<[u8; SIZE]>::from(sig.s))?; Ok(EcdsaSig { r, s }) } } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/drivers.rs
runtime/src/drivers.rs
/*++ Licensed under the Apache-2.0 license. File Name: drivers.rs Abstract: File contains driver initializations. --*/ #![cfg_attr(not(feature = "fips_self_test"), allow(unused))] use crate::cryptographic_mailbox::CmStorage; use crate::debug_unlock::ProductionDebugUnlock; #[cfg(feature = "fips_self_test")] pub use crate::fips::fips_self_test_cmd::SelfTestStatus; use crate::ocp_lock::OcpLockContext; use crate::recovery_flow::RecoveryFlow; use crate::{ dice, CptraDpeTypes, DisableAttestationCmd, DpeCrypto, DpePlatform, Mailbox, CALIPTRA_LOCALITY, DPE_SUPPORT, MAX_ECC_CERT_CHAIN_SIZE, MAX_MLDSA_CERT_CHAIN_SIZE, PL0_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD, PL0_PAUSER_FLAG, PL1_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD, }; use arrayvec::ArrayVec; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_assert_eq_12_words, cfi_launder}; use caliptra_common::cfi_check; use caliptra_common::dice::{copy_ldevid_ecc384_cert, copy_ldevid_mldsa87_cert}; use caliptra_common::mailbox_api::AddSubjectAltNameReq; use caliptra_drivers::{ cprintln, hand_off::DataStore, pcr_log::RT_FW_JOURNEY_PCR, sha2_512_384::Sha2DigestOpTrait, Aes, Array4x12, CaliptraError, CaliptraResult, Ecc384, Hmac, KeyId, KeyVault, Lms, Mldsa87, PcrBank, PersistentDataAccessor, Pic, ResetReason, Sha1, Sha256, Sha256Alg, Sha2_512_384, Sha2_512_384Acc, Sha3, SocIfc, Trng, }; use caliptra_drivers::{Dma, DmaMmio}; use caliptra_image_types::ImageManifest; use caliptra_registers::aes::AesReg; use caliptra_registers::aes_clp::AesClpReg; use caliptra_registers::{ abr::AbrReg, csrng::CsrngReg, ecc::EccReg, el2_pic_ctrl::El2PicCtrl, entropy_src::EntropySrcReg, hmac::HmacReg, kmac::Kmac as KmacReg, kv::KvReg, mbox::MboxCsr, pv::PvReg, sha256::Sha256Reg, sha512::Sha512Reg, sha512_acc::Sha512AccCsr, soc_ifc::SocIfcReg, soc_ifc_trng::SocIfcTrngReg, }; use caliptra_x509::{NotAfter, NotBefore}; use dpe::context::{Context, ContextState, ContextType}; use dpe::tci::TciMeasurement; use dpe::validation::DpeValidator; use dpe::DpeFlags; use dpe::MAX_HANDLES; use dpe::{ commands::{CommandExecution, DeriveContextCmd, DeriveContextFlags}, context::ContextHandle, dpe_instance::{DpeEnv, DpeInstance}, DPE_PROFILE, }; use ureg::MmioMut; use core::cmp::Ordering::{Equal, Greater}; use crypto::CryptoBuf; use zerocopy::IntoBytes; pub const MCI_TOP_REG_RESET_REASON_OFFSET: u32 = 0x38; #[derive(PartialEq, Clone, Copy)] pub enum PauserPrivileges { PL0, PL1, } #[derive(Debug, Copy, Clone)] pub enum McuResetReason { Cold = 0, FwHitlessUpd = 0b1 << 0, FwBoot = 0b1 << 1, Warm = 0b1 << 2, } impl From<McuResetReason> for u32 { fn from(reason: McuResetReason) -> Self { reason as u32 } } #[derive(Debug, Copy, Clone)] pub enum McuFwStatus { NotLoaded, Loaded, HitlessUpdateStarted, } impl From<McuFwStatus> for u32 { fn from(status: McuFwStatus) -> Self { status as u32 } } pub struct Drivers { pub mbox: Mailbox, pub sha_acc: Sha512AccCsr, pub key_vault: KeyVault, pub soc_ifc: SocIfc, 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, // SHA3/SHAKE Engine pub sha3: Sha3, /// Hmac-512/384 Engine pub hmac: Hmac, /// Cryptographically Secure Random Number Generator pub trng: Trng, /// Ecc384 Engine pub ecc384: Ecc384, /// Mldsa87 Engine pub mldsa87: Mldsa87, pub persistent_data: PersistentDataAccessor, pub lms: Lms, pub sha1: Sha1, pub pcr_bank: PcrBank, pub pic: Pic, // [CAP2][TODO] maybe use the Mbox Resp buffer to construct these are runtime rather than storing them here. // That should reduce the stack size by 28K pub ecc_cert_chain: ArrayVec<u8, MAX_ECC_CERT_CHAIN_SIZE>, pub mldsa_cert_chain: ArrayVec<u8, MAX_MLDSA_CERT_CHAIN_SIZE>, #[cfg(feature = "fips_self_test")] pub self_test_status: SelfTestStatus, pub is_shutdown: bool, pub dmtf_device_info: Option<ArrayVec<u8, { AddSubjectAltNameReq::MAX_DEVICE_INFO_LEN }>>, pub dma: Dma, pub cryptographic_mailbox: CmStorage, pub aes: Aes, pub debug_unlock: ProductionDebugUnlock, pub ocp_lock_context: OcpLockContext, } impl Drivers { /// # 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(), )?; let aes = Aes::new(AesReg::new(), AesClpReg::new()); let soc_ifc = SocIfc::new(SocIfcReg::new()); let persistent_data = PersistentDataAccessor::new(); let hek_available = persistent_data.get().rom.ocp_lock_metadata.hek_available; let ocp_lock_context = OcpLockContext::new(&soc_ifc, hek_available); Ok(Self { mbox: Mailbox::new(MboxCsr::new()), sha_acc: Sha512AccCsr::new(), key_vault: KeyVault::new(KvReg::new()), soc_ifc, sha256: Sha256::new(Sha256Reg::new()), sha2_512_384: Sha2_512_384::new(Sha512Reg::new()), sha2_512_384_acc: Sha2_512_384Acc::new(Sha512AccCsr::new()), sha3: Sha3::new(KmacReg::new()), hmac: Hmac::new(HmacReg::new()), ecc384: Ecc384::new(EccReg::new()), mldsa87: Mldsa87::new(AbrReg::new()), sha1: Sha1::default(), lms: Lms::default(), trng, persistent_data, pcr_bank: PcrBank::new(PvReg::new()), pic: Pic::new(El2PicCtrl::new()), #[cfg(feature = "fips_self_test")] self_test_status: SelfTestStatus::Idle, ecc_cert_chain: ArrayVec::new(), mldsa_cert_chain: ArrayVec::new(), is_shutdown: false, dmtf_device_info: None, dma: Dma::default(), cryptographic_mailbox: CmStorage::new(), debug_unlock: ProductionDebugUnlock::new(), ocp_lock_context, aes, }) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn run_reset_flow(&mut self) -> CaliptraResult<()> { Self::create_cert_chain(self)?; self.cryptographic_mailbox .init(&self.persistent_data, &mut self.trng)?; if self.persistent_data.get().fw.dpe.attestation_disabled.get() { DisableAttestationCmd::execute(self) .map_err(|_| CaliptraError::RUNTIME_GLOBAL_EXCEPTION)?; } let reset_reason = self.soc_ifc.reset_reason(); match reset_reason { ResetReason::ColdReset => { cfi_assert_eq(self.soc_ifc.reset_reason(), ResetReason::ColdReset); Self::initialize_dpe(self)?; if self.soc_ifc.subsystem_mode() { RecoveryFlow::recovery_flow(self)?; } } ResetReason::UpdateReset => { cfi_assert_eq(self.soc_ifc.reset_reason(), ResetReason::UpdateReset); Self::validate_dpe_structure(self)?; Self::validate_context_tags(self)?; Self::update_dpe_rt_journey(self)?; } ResetReason::WarmReset => { cfi_assert_eq(self.soc_ifc.reset_reason(), ResetReason::WarmReset); Self::validate_dpe_structure(self)?; Self::validate_context_tags(self)?; Self::check_dpe_rt_journey_unchanged(self)?; Self::update_fw_version(self, true, true); if self.soc_ifc.subsystem_mode() { Self::release_mcu_sram(self)?; } } ResetReason::Unknown => { cfi_assert_eq(self.soc_ifc.reset_reason(), ResetReason::Unknown); return Err(CaliptraError::RUNTIME_UNKNOWN_RESET_FLOW); } } Ok(()) } /// Retrieves the root context index. Inlined so the callsite optimizer /// knows that root_idx < dpe.contexts.len() and won't insert possible call to panic. /// /// # Arguments /// /// * `dpe` - DpeInstance /// /// # Returns /// /// * `usize` - Index containing the root DPE context #[inline(always)] pub fn get_dpe_root_context_idx(dpe: &dpe::State) -> CaliptraResult<usize> { // Find root node by finding the non-inactive context with parent equal to ROOT_INDEX let root_idx = dpe .contexts .iter() .enumerate() .find(|&(_idx, context)| { context.state != ContextState::Inactive && context.parent_idx == Context::ROOT_INDEX && context.context_type == ContextType::Normal }) .ok_or(CaliptraError::RUNTIME_UNABLE_TO_FIND_DPE_ROOT_CONTEXT)? .0; if root_idx >= dpe.contexts.len() { return Err(CaliptraError::RUNTIME_UNABLE_TO_FIND_DPE_ROOT_CONTEXT); } Ok(root_idx) } pub fn set_mcu_reset_reason(drivers: &mut Drivers, reason: McuResetReason) { let dma = &drivers.dma; let mci_base_addr = drivers.soc_ifc.mci_base_addr().into(); let mmio = &DmaMmio::new(mci_base_addr, dma); unsafe { mmio.write_volatile(MCI_TOP_REG_RESET_REASON_OFFSET as *mut u32, reason.into()) }; } pub fn request_mcu_reset(drivers: &mut Drivers, reason: McuResetReason) { Self::set_mcu_reset_reason(drivers, reason); drivers.soc_ifc.set_mcu_firmware_ready(); } /// Validate DPE and disable attestation if validation fails fn validate_dpe_structure(drivers: &mut Drivers) -> CaliptraResult<()> { let dpe = &mut drivers.persistent_data.get_mut().fw.dpe.state; let dpe_validator = DpeValidator { dpe }; let validation_result = dpe_validator.validate_dpe(); if let Err(e) = validation_result { // If SRAM Dpe Instance validation fails, disable attestation let result = DisableAttestationCmd::execute(drivers); cfi_check!(result); match result { Ok(_) => { // store specific validation error in CPTRA_FW_EXTENDED_ERROR_INFO drivers.soc_ifc.set_fw_extended_error(e.get_error_code()); caliptra_drivers::report_fw_error_non_fatal( CaliptraError::RUNTIME_DPE_VALIDATION_FAILED.into(), ); } Err(e) => { cprintln!("{}", e.0); return Err(CaliptraError::RUNTIME_GLOBAL_EXCEPTION); } } } else { let _pl0_pauser = drivers .persistent_data .get() .rom .manifest1 .header .pl0_pauser; // check that DPE used context limits are not exceeded let dpe_context_threshold_exceeded = drivers.is_dpe_context_threshold_exceeded(drivers.caller_privilege_level()); cfi_check!(dpe_context_threshold_exceeded); if let Err(e) = dpe_context_threshold_exceeded { let result = DisableAttestationCmd::execute(drivers); cfi_check!(result); match result { Ok(_) => { caliptra_drivers::report_fw_error_non_fatal(e.into()); } Err(e) => { cprintln!("{}", e.0); return Err(CaliptraError::RUNTIME_GLOBAL_EXCEPTION); } } } } Ok(()) } /// Update DPE root context's TCI measurement with RT_FW_JOURNEY_PCR #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn update_dpe_rt_journey(drivers: &mut Drivers) -> CaliptraResult<()> { let dpe = &mut drivers.persistent_data.get_mut().fw.dpe.state; let root_idx = Self::get_dpe_root_context_idx(dpe)?; let latest_pcr = <[u8; 48]>::from(drivers.pcr_bank.read_pcr(RT_FW_JOURNEY_PCR)); dpe.contexts[root_idx].tci.tci_current = TciMeasurement(latest_pcr); dpe.contexts[root_idx].tci.tci_cumulative = TciMeasurement(latest_pcr); Ok(()) } fn update_fw_version(drivers: &mut Drivers, update_fmc_ver: bool, update_rt_ver: bool) { // This is a temp workaround since cptra_fw_rev_id registers are not sticky on a warm reset. if update_fmc_ver { drivers .soc_ifc .set_fmc_fw_rev_id(drivers.persistent_data.get().rom.manifest1.fmc.version as u16); } if update_rt_ver { drivers .soc_ifc .set_rt_fw_rev_id(drivers.persistent_data.get().rom.manifest1.runtime.version); } } /// Release MCU SRAM if MCU FW was previously loaded correctly fn release_mcu_sram(drivers: &mut Drivers) -> CaliptraResult<()> { // Check if MCU previous Cold-Reset was successful. let mcu_firmware_loaded = drivers.persistent_data.get().fw.mcu_firmware_loaded; if mcu_firmware_loaded == McuFwStatus::NotLoaded.into() { cprintln!("[rt-warm-reset] Warning: Prev Cold Reset failed, not releasing MCU SRAM"); } // Check if MCU previous Update-Reset, if any, was successful. if mcu_firmware_loaded == McuFwStatus::HitlessUpdateStarted.into() { cprintln!( "[rt-warm-reset] Warning: Prev Hitless Update Reset failed, not releasing MCU SRAM" ); } cfi_assert_eq(mcu_firmware_loaded, McuFwStatus::Loaded.into()); cprintln!("[rt-warm-reset] MCU FW is loaded in SRAM"); Self::request_mcu_reset(drivers, McuResetReason::FwBoot); Ok(()) } /// Check that RT_FW_JOURNEY_PCR == DPE Root Context's TCI measurement fn check_dpe_rt_journey_unchanged(drivers: &mut Drivers) -> CaliptraResult<()> { let dpe = &drivers.persistent_data.get().fw.dpe.state; let root_idx = Self::get_dpe_root_context_idx(dpe)?; let latest_tci = Array4x12::from(&dpe.contexts[root_idx].tci.tci_current.0); let latest_pcr = drivers.pcr_bank.read_pcr(RT_FW_JOURNEY_PCR); // Ensure TCI from SRAM == RT_FW_JOURNEY_PCR if latest_pcr != latest_tci { // If latest pcr validation fails, disable attestation let result = DisableAttestationCmd::execute(drivers); cfi_check!(result); match result { Ok(_) => { caliptra_drivers::report_fw_error_non_fatal( CaliptraError::RUNTIME_RT_JOURNEY_PCR_VALIDATION_FAILED.into(), ); } Err(e) => { cprintln!("{}", e.0); return Err(CaliptraError::RUNTIME_GLOBAL_EXCEPTION); } } } else { cfi_assert_eq_12_words( &<[u32; 12]>::from(latest_tci), &<[u32; 12]>::from(latest_pcr), ) } Ok(()) } /// Check that inactive DPE contexts do not have context tags set fn validate_context_tags(drivers: &mut Drivers) -> CaliptraResult<()> { let pdata = drivers.persistent_data.get(); let context_has_tag = &pdata.fw.dpe.context_has_tag; let context_tags = &pdata.fw.dpe.context_tags; let dpe = &pdata.fw.dpe.state; for i in 0..MAX_HANDLES { if dpe.contexts[i].state == ContextState::Inactive { if context_tags[i] != 0 { return Err(CaliptraError::RUNTIME_CONTEXT_TAGS_VALIDATION_FAILED); } else if context_has_tag[i].get() { return Err(CaliptraError::RUNTIME_CONTEXT_HAS_TAG_VALIDATION_FAILED); } } } Ok(()) } /// Compute the Caliptra Name SerialNumber by Sha256 hashing the RT Alias public key #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn compute_rt_alias_sn(&mut self) -> CaliptraResult<CryptoBuf> { let key = self .persistent_data .get() .rom .fht .rt_dice_ecc_pub_key .to_der(); let rt_digest = self.sha256.digest(&key)?; let token = CryptoBuf::new(&Into::<[u8; 32]>::into(rt_digest)) .map_err(|_| CaliptraError::RUNTIME_COMPUTE_RT_ALIAS_SN_FAILED)?; Ok(token) } /// Initialize DPE with measurements and store in Drivers #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn initialize_dpe(drivers: &mut Drivers) -> CaliptraResult<()> { let pl0_pauser_locality = drivers .persistent_data .get() .rom .manifest1 .header .pl0_pauser; let hashed_rt_pub_key = drivers.compute_rt_alias_sn()?; let privilege_level = drivers.caller_privilege_level(); // Set context limits in persistent data as we init DPE drivers.persistent_data.get_mut().fw.dpe.pl0_context_limit = PL0_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD as u8; drivers.persistent_data.get_mut().fw.dpe.pl1_context_limit = PL1_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD as u8; let pl0_context_limit = drivers.persistent_data.get().fw.dpe.pl0_context_limit; let pl1_context_limit = drivers.persistent_data.get().fw.dpe.pl1_context_limit; // create a hash of all the mailbox valid pausers const PAUSER_COUNT: usize = 5; let mbox_valid_pauser: [u32; PAUSER_COUNT] = drivers.soc_ifc.mbox_valid_pauser(); let mbox_pauser_lock: [bool; PAUSER_COUNT] = drivers.soc_ifc.mbox_pauser_lock(); let mut digest_op = drivers.sha2_512_384.sha384_digest_init()?; for i in 0..PAUSER_COUNT { if mbox_pauser_lock[i] { digest_op.update(mbox_valid_pauser[i].as_bytes())?; } } let mut valid_pauser_hash = Array4x12::default(); digest_op.finalize(&mut valid_pauser_hash)?; let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; let key_id_rt_priv_key = Drivers::get_key_id_rt_priv_key(drivers)?; let pdata = drivers.persistent_data.get_mut(); let crypto = DpeCrypto::new( &mut drivers.sha2_512_384, &mut drivers.trng, &mut drivers.ecc384, &mut drivers.hmac, &mut drivers.key_vault, &mut pdata.rom.fht.rt_dice_ecc_pub_key, key_id_rt_cdi, key_id_rt_priv_key, &mut pdata.fw.dpe.exported_cdi_slots, ); let (nb, nf) = Self::get_cert_validity_info(&pdata.rom.manifest1); let mut state = dpe::State::new(DPE_SUPPORT, DpeFlags::empty()); let mut env = DpeEnv::<CptraDpeTypes> { crypto, platform: DpePlatform::new( CALIPTRA_LOCALITY, &hashed_rt_pub_key, &drivers.ecc_cert_chain, &nb, &nf, None, None, ), state: &mut state, }; // Initialize DPE with the RT journey PCR let rt_journey_measurement = <[u8; DPE_PROFILE.hash_size()]>::from(&drivers.pcr_bank.read_pcr(RT_FW_JOURNEY_PCR)); let mut dpe = DpeInstance::new_auto_init( &mut env, u32::from_be_bytes(*b"RTJM"), rt_journey_measurement, ) .map_err(|_| CaliptraError::RUNTIME_INITIALIZE_DPE_FAILED)?; // Call DeriveContext to create a measurement for the mailbox valid pausers and change locality to the pl0 pauser locality let derive_context_resp = DeriveContextCmd { handle: ContextHandle::default(), data: valid_pauser_hash .as_bytes() .try_into() .map_err(|_| CaliptraError::RUNTIME_ADD_VALID_PAUSER_MEASUREMENT_TO_DPE_FAILED)?, flags: DeriveContextFlags::MAKE_DEFAULT | DeriveContextFlags::CHANGE_LOCALITY | DeriveContextFlags::ALLOW_NEW_CONTEXT_TO_EXPORT | DeriveContextFlags::INPUT_ALLOW_X509, tci_type: u32::from_be_bytes(*b"MBVP"), target_locality: pl0_pauser_locality, svn: 0, } .execute(&mut dpe, &mut env, CALIPTRA_LOCALITY); if let Err(e) = derive_context_resp { // If there is extended error info, populate CPTRA_FW_EXTENDED_ERROR_INFO if let Some(ext_err) = e.get_error_detail() { drivers.soc_ifc.set_fw_extended_error(ext_err); } Err(CaliptraError::RUNTIME_ADD_VALID_PAUSER_MEASUREMENT_TO_DPE_FAILED)? } // Call DeriveContext to create TCIs for each measurement added in ROM let num_measurements = pdata.rom.fht.meas_log_index as usize; let measurement_log = pdata.rom.measurement_log; for measurement_log_entry in measurement_log.iter().take(num_measurements) { // Check that adding this measurement to DPE doesn't cause // the PL0 context threshold to be exceeded. // // Use the helper method here because the DPE instance holds a mutable reference to driver Self::is_dpe_context_threshold_exceeded_helper( pl0_pauser_locality, privilege_level, env.state, pl0_context_limit as usize, pl1_context_limit as usize, )?; let measurement_data = measurement_log_entry.pcr_entry.measured_data(); let tci_type = u32::from_ne_bytes(measurement_log_entry.metadata); let derive_context_resp = DeriveContextCmd { handle: ContextHandle::default(), data: measurement_data .try_into() .map_err(|_| CaliptraError::RUNTIME_ADD_ROM_MEASUREMENTS_TO_DPE_FAILED)?, flags: DeriveContextFlags::MAKE_DEFAULT | DeriveContextFlags::CHANGE_LOCALITY | DeriveContextFlags::ALLOW_NEW_CONTEXT_TO_EXPORT | DeriveContextFlags::INPUT_ALLOW_X509, tci_type, target_locality: pl0_pauser_locality, svn: 0, } .execute(&mut dpe, &mut env, pl0_pauser_locality); if let Err(e) = derive_context_resp { // If there is extended error info, populate CPTRA_FW_EXTENDED_ERROR_INFO if let Some(ext_err) = e.get_error_detail() { drivers.soc_ifc.set_fw_extended_error(ext_err); } Err(CaliptraError::RUNTIME_ADD_ROM_MEASUREMENTS_TO_DPE_FAILED)? } } // Tell the compiler env is no longer needed so the state can be copied to persistent data. // Otherwise the error, "cannot move out of `state` because it is borrowed" is given. drop(env); // Write DPE to persistent data. pdata.fw.dpe.state = state; Ok(()) } /// Create certificate chain and store in Drivers #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn create_cert_chain(drivers: &mut Drivers) -> CaliptraResult<()> { Self::create_ecc_cert_chain(drivers)?; Self::create_mldsa_cert_chain(drivers) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn create_ecc_cert_chain(drivers: &mut Drivers) -> CaliptraResult<()> { let persistent_data = &drivers.persistent_data; // Clear and resize the cert chain to have space for writing drivers.ecc_cert_chain.clear(); for _ in 0..MAX_ECC_CERT_CHAIN_SIZE { drivers .ecc_cert_chain .try_push(0) .map_err(|_| CaliptraError::RUNTIME_CERT_CHAIN_CREATION_FAILED)?; } // Write ldev_id cert to cert chain. let ldevid_cert_size = copy_ldevid_ecc384_cert(persistent_data.get(), drivers.ecc_cert_chain.as_mut_slice())?; if ldevid_cert_size > drivers.ecc_cert_chain.len() { return Err(CaliptraError::RUNTIME_LDEV_ID_CERT_TOO_BIG); } // Write fmc alias cert to cert chain. let fmcalias_cert_size = dice::copy_fmc_alias_ecc384_cert( persistent_data.get(), &mut drivers.ecc_cert_chain.as_mut_slice()[ldevid_cert_size..], )?; if ldevid_cert_size + fmcalias_cert_size > drivers.ecc_cert_chain.len() { return Err(CaliptraError::RUNTIME_FMC_ALIAS_CERT_TOO_BIG); } // Write rt alias cert to cert chain. let rtalias_cert_size = dice::copy_rt_alias_ecc384_cert( persistent_data.get(), &mut drivers.ecc_cert_chain.as_mut_slice()[ldevid_cert_size + fmcalias_cert_size..], )?; let cert_chain_size = ldevid_cert_size + fmcalias_cert_size + rtalias_cert_size; if cert_chain_size > drivers.ecc_cert_chain.len() { return Err(CaliptraError::RUNTIME_RT_ALIAS_CERT_TOO_BIG); } // Truncate to actual used size drivers.ecc_cert_chain.truncate(cert_chain_size); Ok(()) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn create_mldsa_cert_chain(drivers: &mut Drivers) -> CaliptraResult<()> { let persistent_data = &drivers.persistent_data; // Clear and resize the cert chain to have space for writing drivers.mldsa_cert_chain.clear(); for _ in 0..MAX_MLDSA_CERT_CHAIN_SIZE { drivers .mldsa_cert_chain .try_push(0) .map_err(|_| CaliptraError::RUNTIME_CERT_CHAIN_CREATION_FAILED)?; } // Write ldev_id cert to cert chain. let ldevid_cert_size = copy_ldevid_mldsa87_cert( persistent_data.get(), drivers.mldsa_cert_chain.as_mut_slice(), )?; if ldevid_cert_size > drivers.mldsa_cert_chain.len() { return Err(CaliptraError::RUNTIME_LDEV_ID_CERT_TOO_BIG); } // Write fmc alias cert to cert chain. let fmcalias_cert_size = dice::copy_fmc_alias_mldsa87_cert( persistent_data.get(), &mut drivers.mldsa_cert_chain.as_mut_slice()[ldevid_cert_size..], )?; if ldevid_cert_size + fmcalias_cert_size > drivers.mldsa_cert_chain.len() { return Err(CaliptraError::RUNTIME_FMC_ALIAS_CERT_TOO_BIG); } // Write rt alias cert to cert chain. let rtalias_cert_size = dice::copy_rt_alias_mldsa87_cert( persistent_data.get(), &mut drivers.mldsa_cert_chain.as_mut_slice()[ldevid_cert_size + fmcalias_cert_size..], )?; let cert_chain_size = ldevid_cert_size + fmcalias_cert_size + rtalias_cert_size; if cert_chain_size > drivers.mldsa_cert_chain.len() { return Err(CaliptraError::RUNTIME_RT_ALIAS_CERT_TOO_BIG); } // Truncate to actual used size drivers.mldsa_cert_chain.truncate(cert_chain_size); Ok(()) } /// Counts the number of non-inactive DPE contexts pub fn dpe_get_used_context_counts(&self) -> CaliptraResult<(usize, usize)> { Self::dpe_get_used_context_counts_helper( self.persistent_data.get().rom.manifest1.header.pl0_pauser, &self.persistent_data.get().fw.dpe.state, ) } fn dpe_get_used_context_counts_helper( pl0_pauser: u32, dpe: &dpe::State, ) -> CaliptraResult<(usize, usize)> { let used_pl0_dpe_context_count = dpe .count_contexts(|c: &Context| { c.state != ContextState::Inactive && (c.locality == pl0_pauser || c.locality == CALIPTRA_LOCALITY) }) .map_err(|_| CaliptraError::RUNTIME_INTERNAL)?; // the number of used pl1 dpe contexts is the total number of used contexts // minus the number of used pl0 contexts, since a context can only be activated // from pl0 or from pl1. Here, used means an active or retired context. let used_pl1_dpe_context_count = dpe .count_contexts(|c: &Context| c.state != ContextState::Inactive) .map_err(|_| CaliptraError::RUNTIME_INTERNAL)? - used_pl0_dpe_context_count; Ok((used_pl0_dpe_context_count, used_pl1_dpe_context_count)) } /// Counts the number of non-inactive DPE contexts and returns an error /// if this number is greater than or equal to the active context threshold /// corresponding to the privilege level provided. pub fn is_dpe_context_threshold_exceeded( &self, context_privilege_level: PauserPrivileges, ) -> CaliptraResult<()> { let dpe_data = &self.persistent_data.get().fw.dpe; Self::is_dpe_context_threshold_exceeded_helper( self.persistent_data.get().rom.manifest1.header.pl0_pauser, context_privilege_level, &dpe_data.state, dpe_data.pl0_context_limit as usize, dpe_data.pl1_context_limit as usize, ) } fn is_dpe_context_threshold_exceeded_helper( pl0_pauser: u32, caller_privilege_level: PauserPrivileges, dpe: &dpe::State, pl0_context_limit: usize, pl1_context_limit: usize, ) -> CaliptraResult<()> { let (used_pl0_dpe_context_count, used_pl1_dpe_context_count) = Self::dpe_get_used_context_counts_helper(pl0_pauser, dpe)?; match ( caller_privilege_level, used_pl1_dpe_context_count.cmp(&pl1_context_limit), used_pl0_dpe_context_count.cmp(&pl0_context_limit), ) { (PauserPrivileges::PL1, Equal, _) => { Err(CaliptraError::RUNTIME_PL1_USED_DPE_CONTEXT_THRESHOLD_REACHED) } (PauserPrivileges::PL1, Greater, _) => { Err(CaliptraError::RUNTIME_PL1_USED_DPE_CONTEXT_THRESHOLD_EXCEEDED) } (PauserPrivileges::PL0, _, Equal) => { Err(CaliptraError::RUNTIME_PL0_USED_DPE_CONTEXT_THRESHOLD_REACHED) } (PauserPrivileges::PL0, _, Greater) => { Err(CaliptraError::RUNTIME_PL0_USED_DPE_CONTEXT_THRESHOLD_EXCEEDED) } _ => Ok(()), } } /// Retrieves the caller permission level pub fn caller_privilege_level(&self) -> PauserPrivileges { let locality = self.mbox.id(); self.privilege_level_from_locality(locality) } pub fn privilege_level_from_locality(&self, locality: u32) -> PauserPrivileges { let manifest_header = self.persistent_data.get().rom.manifest1.header; let flags = manifest_header.flags; let pl0_pauser = manifest_header.pl0_pauser; // When the PL0_PAUSER_FLAG bit is not set there can be no PL0 PAUSER. if flags & PL0_PAUSER_FLAG == 0 { return PauserPrivileges::PL1; } if locality == pl0_pauser { PauserPrivileges::PL0 } else { PauserPrivileges::PL1 } } /// Get the KeyId for the RT Alias CDI /// /// # Arguments /// /// * `drivers` - Drivers /// /// # Returns /// /// * `KeyId` - RT Alias CDI pub fn get_key_id_rt_cdi(drivers: &Drivers) -> CaliptraResult<KeyId> { let ds: DataStore = drivers .persistent_data .get() .rom .fht .rt_cdi_kv_hdl .try_into() .map_err(|_| CaliptraError::RUNTIME_CDI_KV_HDL_HANDOFF_FAILED)?; match ds { DataStore::KeyVaultSlot(key_id) => Ok(key_id), _ => Err(CaliptraError::RUNTIME_CDI_KV_HDL_HANDOFF_FAILED), } } /// Get the KeyId for the RT Alias private key /// /// # Arguments /// /// * `drivers` - Drivers /// /// # Returns /// /// * `KeyId` - RT Alias private key pub fn get_key_id_rt_priv_key(drivers: &Drivers) -> CaliptraResult<KeyId> { let ds: DataStore = drivers .persistent_data .get() .rom .fht
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/revoke_exported_cdi_handle.rs
runtime/src/revoke_exported_cdi_handle.rs
// Licensed under the Apache-2.0 license use crate::{Drivers, PauserPrivileges}; #[cfg(not(feature = "no-cfi"))] use caliptra_cfi_derive_git::cfi_impl_fn; #[cfg(not(feature = "no-cfi"))] use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq}; use caliptra_common::mailbox_api::RevokeExportedCdiHandleReq; use caliptra_drivers::ExportedCdiEntry; use caliptra_error::{CaliptraError, CaliptraResult}; use constant_time_eq::constant_time_eq; use dpe::U8Bool; use zerocopy::FromBytes; use zeroize::Zeroize; pub struct RevokeExportedCdiHandleCmd; impl RevokeExportedCdiHandleCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult<usize> { let cmd = RevokeExportedCdiHandleReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; match drivers.caller_privilege_level() { // REVOKE_EXPORTED_CDI_HANDLE MUST only be called from PL0 PauserPrivileges::PL0 => (), PauserPrivileges::PL1 => { return Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL); } } for slot in drivers .persistent_data .get_mut() .fw .dpe .exported_cdi_slots .entries .iter_mut() { match slot { ExportedCdiEntry { key: _, handle, active, } if constant_time_eq(handle, &cmd.exported_cdi_handle) && active.get() => { #[cfg(not(feature = "no-cfi"))] cfi_assert!(constant_time_eq(handle, &cmd.exported_cdi_handle)); // Setting to false is redundant with zeroize but included for clarity. *active = U8Bool::new(false); slot.zeroize(); return Ok(0); } _ => (), } } Err(CaliptraError::RUNTIME_REVOKE_EXPORTED_CDI_HANDLE_NOT_FOUND) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/info.rs
runtime/src/info.rs
/*++ Licensed under the Apache-2.0 license. File Name: info.rs Abstract: File contains mailbox commands to retrieve info about state of the Runtime firmware. --*/ use crate::{handoff::RtHandoff, mutrefbytes, Drivers}; use caliptra_common::mailbox_api::{ AlgorithmType, FwInfoResp, GetIdevEcc384InfoResp, GetIdevMldsa87InfoResp, MailboxRespHeader, }; use caliptra_drivers::{get_fw_error_non_fatal, CaliptraResult}; pub struct FwInfoCmd; impl FwInfoCmd { #[inline(never)] pub(crate) fn execute(drivers: &Drivers, resp: &mut [u8]) -> CaliptraResult<usize> { let pdata = drivers.persistent_data.get(); let handoff = RtHandoff { data_vault: &pdata.rom.data_vault, fht: &pdata.rom.fht, }; let rom_info = handoff.fht.rom_info_addr.get()?; let resp = mutrefbytes::<FwInfoResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.pl0_pauser = pdata.rom.manifest1.header.pl0_pauser; resp.fw_svn = handoff.fw_svn(); resp.min_fw_svn = handoff.fw_min_svn(); resp.cold_boot_fw_svn = handoff.cold_boot_fw_svn(); resp.attestation_disabled = pdata.fw.dpe.attestation_disabled.get().into(); resp.rom_revision = rom_info.revision; resp.fmc_revision = pdata.rom.manifest1.fmc.revision; resp.runtime_revision = pdata.rom.manifest1.runtime.revision; resp.rom_sha256_digest = rom_info.sha256_digest; resp.fmc_sha384_digest = pdata.rom.manifest1.fmc.digest; resp.runtime_sha384_digest = pdata.rom.manifest1.runtime.digest; resp.owner_pub_key_hash = pdata.rom.data_vault.owner_pk_hash().into(); resp.authman_sha384_digest = pdata.fw.auth_manifest_digest; resp.most_recent_fw_error = match get_fw_error_non_fatal() { 0 => drivers.persistent_data.get().rom.cleared_non_fatal_fw_error, e => e, }; Ok(core::mem::size_of::<FwInfoResp>()) } } pub struct IDevIdInfoCmd; impl IDevIdInfoCmd { #[inline(never)] pub(crate) fn execute( drivers: &Drivers, alg_type: AlgorithmType, resp: &mut [u8], ) -> CaliptraResult<usize> { let pdata = drivers.persistent_data.get(); match alg_type { AlgorithmType::Ecc384 => { let pub_key = pdata.rom.fht.idev_dice_ecdsa_pub_key; let resp = mutrefbytes::<GetIdevEcc384InfoResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.idev_pub_x = pub_key.x.into(); resp.idev_pub_y = pub_key.y.into(); Ok(core::mem::size_of::<GetIdevEcc384InfoResp>()) } AlgorithmType::Mldsa87 => { let pub_key = pdata.rom.idevid_mldsa_pub_key; let resp = mutrefbytes::<GetIdevMldsa87InfoResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.idev_pub_key = pub_key.into(); Ok(core::mem::size_of::<GetIdevMldsa87InfoResp>()) } } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/disable.rs
runtime/src/disable.rs
/*++ Licensed under the Apache-2.0 license. File Name: disable.rs Abstract: File contains DisableAttestation mailbox command. --*/ use crate::Drivers; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::keyids::KEY_ID_EXPORTED_DPE_CDI; use caliptra_drivers::{ hmac_kdf, Array4x12, CaliptraResult, Ecc384Seed, HmacKey, HmacMode, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, }; use dpe::U8Bool; pub struct DisableAttestationCmd; impl DisableAttestationCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers) -> CaliptraResult<usize> { Self::erase_keys(drivers)?; let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; Self::zero_cdi(drivers, key_id_rt_cdi)?; Self::zero_cdi(drivers, KEY_ID_EXPORTED_DPE_CDI)?; Self::generate_dice_key(drivers)?; drivers .persistent_data .get_mut() .fw .dpe .attestation_disabled = U8Bool::new(true); Ok(0) } /// Erase the RT CDI and RT Private Key from the key vault /// /// # Arguments /// /// * `drivers` - Drivers #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn erase_keys(drivers: &mut Drivers) -> CaliptraResult<()> { let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; let key_id_rt_priv_key = Drivers::get_key_id_rt_priv_key(drivers)?; drivers.key_vault.erase_key(key_id_rt_cdi)?; drivers.key_vault.erase_key(key_id_rt_priv_key) } /// Set CDI key vault slot to a KDF of a buffer of 0s. /// /// # Arguments /// /// * `drivers` - Drivers #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] fn zero_cdi(drivers: &mut Drivers, key: KeyId) -> CaliptraResult<()> { hmac_kdf( &mut drivers.hmac, HmacKey::Array4x12(&Array4x12::default()), b"zero_cdi", None, &mut drivers.trng, KeyWriteArgs::new( key, KeyUsage::default() .set_hmac_key_en() .set_ecc_key_gen_seed_en() .set_mldsa_key_gen_seed_en(), ) .into(), HmacMode::Hmac384, )?; Ok(()) } /// Generate a new RT alias key from the zeroed-out RT CDI. Since this new /// key is derived from an empty CDI slot it will not match the key that was /// certified in the RT alias cert. /// /// # Arguments /// /// * `drivers` - Drivers #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn generate_dice_key(drivers: &mut Drivers) -> CaliptraResult<()> { let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; let key_id_rt_priv_key = Drivers::get_key_id_rt_priv_key(drivers)?; let pub_key = drivers.ecc384.key_pair( Ecc384Seed::Key(KeyReadArgs::new(key_id_rt_cdi)), &Array4x12::default(), &mut drivers.trng, KeyWriteArgs::new( key_id_rt_priv_key, KeyUsage::default().set_ecc_private_key_en(), ) .into(), )?; drivers .persistent_data .get_mut() .rom .fht .rt_dice_ecc_pub_key = pub_key; Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/verify.rs
runtime/src/verify.rs
/*++ Licensed under the Apache-2.0 license. File Name: verify.rs Abstract: File contains EcdsaVerify mailbox command and HmacVerify test-only mailbox command. --*/ use crate::Drivers; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::LmsVerifyReq; use caliptra_drivers::{CaliptraError, CaliptraResult, LmsResult}; use caliptra_lms_types::{ LmotsAlgorithmType, LmotsSignature, LmsAlgorithmType, LmsPublicKey, LmsSignature, }; use zerocopy::{BigEndian, FromBytes, LittleEndian, U32}; pub struct LmsVerifyCmd; impl LmsVerifyCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult<usize> { // Re-run LMS KAT once (since LMS is more SW-based than other crypto) if let Err(e) = caliptra_kat::LmsKat::default().execute_once(&mut drivers.sha256, &mut drivers.lms) { // KAT failures must be fatal errors caliptra_common::handle_fatal_error(e.into()); } // Constants from fixed LMS param set const LMS_N: usize = 6; const LMS_P: usize = 51; const LMS_H: usize = 15; const LMS_ALGORITHM_TYPE: LmsAlgorithmType = LmsAlgorithmType::new(12); const LMOTS_ALGORITHM_TYPE: LmotsAlgorithmType = LmotsAlgorithmType::new(7); let cmd = LmsVerifyReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; // Somehow doing a memcopy of 24 bytes results in unaligned access on the mbox SRAM MMIO // Avoid this doing manual u32 reads let digest = cmd.pub_key_digest.chunks_exact(4).enumerate().fold( [U32::<LittleEndian>::new(0); LMS_N], |mut acc, (i, chunk)| { let dword = u32::from_le_bytes(chunk.try_into().unwrap()); acc[i] = U32::<LittleEndian>::from(dword); acc }, ); let lms_pub_key: LmsPublicKey<LMS_N> = LmsPublicKey { id: cmd.pub_key_id, digest, tree_type: LmsAlgorithmType::new(cmd.pub_key_tree_type), otstype: LmotsAlgorithmType::new(cmd.pub_key_ots_type), }; // Somehow doing a memcopy of 360 bytes results in unaligned access on the mbox SRAM MMIO // Avoid this doing manual u32 reads let tree_path = cmd.signature_tree_path.chunks_exact(4).enumerate().fold( [[U32::<LittleEndian>::new(0); LMS_N]; LMS_H], |mut acc, (i, chunk)| { let h = i / LMS_N; let n = i % LMS_N; let dword = u32::from_le_bytes(chunk.try_into().unwrap()); acc[h][n] = U32::<LittleEndian>::new(dword); acc }, ); // Somehow doing a memcopy of 1252 bytes results in unaligned access on the mbox SRAM MMIO // Avoid this doing manual u32 reads let ots_buf = cmd.signature_ots.chunks_exact(4).enumerate().fold( [0u8; size_of::<LmotsSignature<LMS_N, LMS_P>>()], |mut acc, (i, chunk)| { let offset = i * 4; acc[offset..offset + 4].copy_from_slice(chunk); acc }, ); let ots = <LmotsSignature<LMS_N, LMS_P>>::read_from_bytes(&ots_buf[..]) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; let lms_sig: LmsSignature<LMS_N, LMS_P, LMS_H> = LmsSignature { q: <U32<BigEndian>>::from(cmd.signature_q), ots, tree_type: LmsAlgorithmType::new(cmd.signature_tree_type), tree_path, }; // Check that fixed params are correct if lms_pub_key.tree_type != LMS_ALGORITHM_TYPE { return Err(CaliptraError::RUNTIME_LMS_VERIFY_INVALID_LMS_ALGORITHM); } if lms_pub_key.otstype != LMOTS_ALGORITHM_TYPE { return Err(CaliptraError::RUNTIME_LMS_VERIFY_INVALID_LMOTS_ALGORITHM); } if lms_sig.tree_type != LMS_ALGORITHM_TYPE { return Err(CaliptraError::RUNTIME_LMS_VERIFY_INVALID_LMS_ALGORITHM); } let success = drivers.lms.verify_lms_signature( &mut drivers.sha256, &cmd.hash, &lms_pub_key, &lms_sig, )?; if success != LmsResult::Success { return Err(CaliptraError::RUNTIME_LMS_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/runtime/src/certify_key_extended.rs
runtime/src/certify_key_extended.rs
/*++ Licensed under the Apache-2.0 license. File Name: populate_idev.rs Abstract: File contains CertifyKeyExtended mailbox command. --*/ use crate::{ mutrefbytes, CptraDpeTypes, DpeCrypto, DpeEnv, DpePlatform, Drivers, PauserPrivileges, }; use caliptra_common::mailbox_api::{ CertifyKeyExtendedFlags, CertifyKeyExtendedReq, CertifyKeyExtendedResp, MailboxRespHeader, }; use caliptra_error::{CaliptraError, CaliptraResult}; use dpe::{ commands::{CertifyKeyCmd, CommandExecution}, response::Response, DpeInstance, }; use zerocopy::{FromBytes, IntoBytes}; pub struct CertifyKeyExtendedCmd; impl CertifyKeyExtendedCmd { #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, cmd_args: &[u8], mbox_resp: &mut [u8], ) -> CaliptraResult<usize> { let cmd = CertifyKeyExtendedReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; match drivers.caller_privilege_level() { // CERTIFY_KEY_EXTENDED MUST only be called from PL0 PauserPrivileges::PL0 => (), PauserPrivileges::PL1 => { return Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL); } } let hashed_rt_pub_key = drivers.compute_rt_alias_sn()?; let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; let key_id_rt_priv_key = Drivers::get_key_id_rt_priv_key(drivers)?; let pdata = drivers.persistent_data.get_mut(); let crypto = DpeCrypto::new( &mut drivers.sha2_512_384, &mut drivers.trng, &mut drivers.ecc384, &mut drivers.hmac, &mut drivers.key_vault, &mut pdata.rom.fht.rt_dice_ecc_pub_key, key_id_rt_cdi, key_id_rt_priv_key, &mut pdata.fw.dpe.exported_cdi_slots, ); let pl0_pauser = pdata.rom.manifest1.header.pl0_pauser; let (nb, nf) = Drivers::get_cert_validity_info(&pdata.rom.manifest1); // Populate the otherName only if requested and provided by ADD_SUBJECT_ALT_NAME let dmtf_device_info = if cmd.flags.contains(CertifyKeyExtendedFlags::DMTF_OTHER_NAME) { drivers .dmtf_device_info .as_ref() .map(|dmtf_device_info| dmtf_device_info.as_bytes()) } else { None }; let mut env = DpeEnv::<CptraDpeTypes> { crypto, platform: DpePlatform::new( pl0_pauser, &hashed_rt_pub_key, &drivers.ecc_cert_chain, &nb, &nf, dmtf_device_info, None, ), state: &mut pdata.fw.dpe.state, }; let certify_key_cmd = CertifyKeyCmd::ref_from_bytes(&cmd.certify_key_req[..]).or(Err( CaliptraError::RUNTIME_DPE_COMMAND_DESERIALIZATION_FAILED, ))?; let locality = drivers.mbox.id(); let resp = certify_key_cmd.execute(&mut DpeInstance::initialized(), &mut env, locality); let certify_key_resp = match resp { Ok(Response::CertifyKey(certify_key_resp)) => certify_key_resp, Ok(_) => return Err(CaliptraError::RUNTIME_CERTIFY_KEY_EXTENDED_FAILED), Err(e) => { // If there is extended error info, populate CPTRA_FW_EXTENDED_ERROR_INFO if let Some(ext_err) = e.get_error_detail() { drivers.soc_ifc.set_fw_extended_error(ext_err); } return Err(CaliptraError::RUNTIME_CERTIFY_KEY_EXTENDED_FAILED); } }; let certify_key_extended_resp = mutrefbytes::<CertifyKeyExtendedResp>(mbox_resp)?; certify_key_extended_resp.hdr = MailboxRespHeader::default(); certify_key_extended_resp.certify_key_resp = certify_key_resp .as_bytes() .try_into() .map_err(|_| CaliptraError::RUNTIME_DPE_RESPONSE_SERIALIZATION_FAILED)?; Ok(core::mem::size_of::<CertifyKeyExtendedResp>()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/stash_measurement.rs
runtime/src/stash_measurement.rs
/*++ Licensed under the Apache-2.0 license. File Name: stash_measurement.rs Abstract: File contains StashMeasurement mailbox command. --*/ use crate::{ dpe_crypto::DpeCrypto, mutrefbytes, CptraDpeTypes, DpePlatform, Drivers, PauserPrivileges, }; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::{MailboxRespHeader, StashMeasurementReq, StashMeasurementResp}; use caliptra_drivers::{pcr_log::PCR_ID_STASH_MEASUREMENT, CaliptraError, CaliptraResult}; use dpe::{ commands::{CommandExecution, DeriveContextCmd, DeriveContextFlags}, context::ContextHandle, dpe_instance::DpeEnv, response::DpeErrorCode, DpeInstance, }; use zerocopy::{FromBytes, IntoBytes}; pub struct StashMeasurementCmd; impl StashMeasurementCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn stash_measurement( drivers: &mut Drivers, metadata: &[u8; 4], measurement: &[u8; 48], svn: u32, ) -> CaliptraResult<DpeErrorCode> { let dpe_result = { let caller_privilege_level = drivers.caller_privilege_level(); match caller_privilege_level { // Only PL0 can call STASH_MEASUREMENT PauserPrivileges::PL0 => (), PauserPrivileges::PL1 => { return Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL); } } // Check that adding this measurement to DPE doesn't cause // the PL0 context threshold to be exceeded. drivers.is_dpe_context_threshold_exceeded(caller_privilege_level)?; let hashed_rt_pub_key = drivers.compute_rt_alias_sn()?; let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; let key_id_rt_priv_key = Drivers::get_key_id_rt_priv_key(drivers)?; let pdata = drivers.persistent_data.get_mut(); let crypto = DpeCrypto::new( &mut drivers.sha2_512_384, &mut drivers.trng, &mut drivers.ecc384, &mut drivers.hmac, &mut drivers.key_vault, &mut pdata.rom.fht.rt_dice_ecc_pub_key, key_id_rt_cdi, key_id_rt_priv_key, &mut pdata.fw.dpe.exported_cdi_slots, ); let (nb, nf) = Drivers::get_cert_validity_info(&pdata.rom.manifest1); let mut env = DpeEnv::<CptraDpeTypes> { crypto, platform: DpePlatform::new( pdata.rom.manifest1.header.pl0_pauser, &hashed_rt_pub_key, &drivers.ecc_cert_chain, &nb, &nf, None, None, ), state: &mut pdata.fw.dpe.state, }; let locality = drivers.mbox.id(); let derive_context_resp = DeriveContextCmd { handle: ContextHandle::default(), data: *measurement, flags: DeriveContextFlags::MAKE_DEFAULT | DeriveContextFlags::CHANGE_LOCALITY | DeriveContextFlags::ALLOW_NEW_CONTEXT_TO_EXPORT | DeriveContextFlags::INPUT_ALLOW_X509, tci_type: u32::from_ne_bytes(*metadata), target_locality: locality, svn, } .execute(&mut DpeInstance::initialized(), &mut env, locality); match derive_context_resp { Ok(_) => DpeErrorCode::NoError, Err(e) => { // If there is extended error info, populate CPTRA_FW_EXTENDED_ERROR_INFO if let Some(ext_err) = e.get_error_detail() { drivers.soc_ifc.set_fw_extended_error(ext_err); } e } } }; if let DpeErrorCode::NoError = dpe_result { // Extend the measurement into PCR31 drivers.pcr_bank.extend_pcr( PCR_ID_STASH_MEASUREMENT, &mut drivers.sha2_512_384, measurement.as_bytes(), )?; } Ok(dpe_result) } pub(crate) fn execute( drivers: &mut Drivers, cmd_args: &[u8], resp: &mut [u8], ) -> CaliptraResult<usize> { let cmd = StashMeasurementReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; let dpe_result = Self::stash_measurement(drivers, &cmd.metadata, &cmd.measurement, cmd.svn)?; let resp = mutrefbytes::<StashMeasurementResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.dpe_result = dpe_result.get_error_code(); Ok(core::mem::size_of::<StashMeasurementResp>()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/subject_alt_name.rs
runtime/src/subject_alt_name.rs
/*++ Licensed under the Apache-2.0 license. File Name: populate_idev.rs Abstract: File contains AddSubjectAltName mailbox command. --*/ use crate::Drivers; use arrayvec::ArrayVec; use caliptra_common::mailbox_api::AddSubjectAltNameReq; use caliptra_error::{CaliptraError, CaliptraResult}; use zerocopy::IntoBytes; pub struct AddSubjectAltNameCmd; impl AddSubjectAltNameCmd { // https://www.dmtf.org/sites/default/files/standards/documents/DSP0274_1.3.0.pdf 1.3.6.1.4.1.412.274.1 pub const DMTF_OID: &'static [u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x83, 0x1C, 0x82, 0x12, 0x01]; #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult<usize> { if cmd_args.len() <= core::mem::size_of::<AddSubjectAltNameReq>() { let mut cmd = AddSubjectAltNameReq::default(); cmd.as_mut_bytes()[..cmd_args.len()].copy_from_slice(cmd_args); let dmtf_device_info_size = cmd.dmtf_device_info_size as usize; if dmtf_device_info_size > cmd.dmtf_device_info.len() { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } Self::validate_dmtf_device_info(&cmd.dmtf_device_info[..dmtf_device_info_size])?; let mut dmtf_device_info = ArrayVec::new(); dmtf_device_info .try_extend_from_slice(&cmd.dmtf_device_info[..dmtf_device_info_size]) .map_err(|_| CaliptraError::RUNTIME_STORE_DMTF_DEVICE_INFO_FAILED)?; drivers.dmtf_device_info = Some(dmtf_device_info); Ok(0) } else { Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY) } } /// Verifies that `dmtf_device_info` only contains ascii characters and contains exactly 2 ':' /// characters. /// /// dmtf_device_info_utf8 must match ^[^:]*:[^:]*:[^:]*$ fn validate_dmtf_device_info(dmtf_device_info: &[u8]) -> CaliptraResult<()> { let mut colon_count = 0; for c in dmtf_device_info.iter() { if !c.is_ascii() { Err(CaliptraError::RUNTIME_DMTF_DEVICE_INFO_VALIDATION_FAILED)? } if *c == b':' { colon_count += 1; } } if colon_count != 2 { Err(CaliptraError::RUNTIME_DMTF_DEVICE_INFO_VALIDATION_FAILED)? } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/sign_with_exported_ecdsa.rs
runtime/src/sign_with_exported_ecdsa.rs
// Licensed under the Apache-2.0 license use crate::{dpe_crypto::DpeCrypto, mutrefbytes, Drivers, PauserPrivileges}; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_launder}; use caliptra_common::cfi_check; use caliptra_common::mailbox_api::{ MailboxRespHeader, SignWithExportedEcdsaReq, SignWithExportedEcdsaResp, }; use caliptra_error::{CaliptraError, CaliptraResult}; use crypto::{Crypto, Digest, EcdsaPub, EcdsaSig}; use dpe::{DPE_PROFILE, MAX_EXPORTED_CDI_SIZE}; use zerocopy::FromBytes; pub struct SignWithExportedEcdsaCmd; impl SignWithExportedEcdsaCmd { /// SignWithExported signs a `digest` using an ECDSA keypair derived from a exported_cdi /// handle and the CDI stored in DPE. /// /// # Arguments /// /// * `env` - DPE environment containing Crypto and Platform implementations /// * `digest` - The data to be signed /// * `exported_cdi_handle` - A handle from DPE that is exchanged for a CDI. #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn ecdsa_sign( env: &mut DpeCrypto, digest: &Digest, exported_cdi_handle: &[u8; MAX_EXPORTED_CDI_SIZE], ) -> CaliptraResult<(EcdsaSig, EcdsaPub)> { let algs = DPE_PROFILE.alg_len(); let key_pair = env.derive_key_pair_exported( algs, exported_cdi_handle, b"Exported ECC", b"Exported ECC", ); cfi_check!(key_pair); let (priv_key, pub_key) = key_pair .map_err(|_| CaliptraError::RUNTIME_SIGN_WITH_EXPORTED_ECDSA_KEY_DERIVIATION_FAILED)?; let sig = env .ecdsa_sign_with_derived(algs, digest, &priv_key, &pub_key) .map_err(|_| CaliptraError::RUNTIME_SIGN_WITH_EXPORTED_ECDSA_SIGNATURE_FAILED)?; Ok((sig, pub_key)) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, cmd_args: &[u8], resp: &mut [u8], ) -> CaliptraResult<usize> { let cmd = SignWithExportedEcdsaReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; match drivers.caller_privilege_level() { // SIGN_WITH_EXPORTED_ECDSA MUST only be called from PL0 PauserPrivileges::PL0 => (), PauserPrivileges::PL1 => { return Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL); } } let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; let key_id_rt_priv_key = Drivers::get_key_id_rt_priv_key(drivers)?; let pdata = drivers.persistent_data.get_mut(); let mut crypto = DpeCrypto::new( &mut drivers.sha2_512_384, &mut drivers.trng, &mut drivers.ecc384, &mut drivers.hmac, &mut drivers.key_vault, &mut pdata.rom.fht.rt_dice_ecc_pub_key, key_id_rt_cdi, key_id_rt_priv_key, &mut pdata.fw.dpe.exported_cdi_slots, ); let digest = Digest::new(&cmd.tbs) .map_err(|_| CaliptraError::RUNTIME_SIGN_WITH_EXPORTED_ECDSA_INVALID_DIGEST)?; let (EcdsaSig { ref r, ref s }, EcdsaPub { ref x, ref y }) = Self::ecdsa_sign(&mut crypto, &digest, &cmd.exported_cdi_handle)?; let resp = mutrefbytes::<SignWithExportedEcdsaResp>(resp)?; resp.hdr = MailboxRespHeader::default(); if r.len() <= resp.signature_r.len() { resp.signature_r[..r.len()].copy_from_slice(r.bytes()); } else { return Err(CaliptraError::RUNTIME_SIGN_WITH_EXPORTED_ECDSA_INVALID_SIGNATURE); } if s.len() <= resp.signature_s.len() { resp.signature_s[..s.len()].copy_from_slice(s.bytes()); } else { return Err(CaliptraError::RUNTIME_SIGN_WITH_EXPORTED_ECDSA_INVALID_SIGNATURE); } if x.len() <= resp.derived_pubkey_x.len() { resp.derived_pubkey_x[..x.len()].copy_from_slice(x.bytes()); } else { return Err(CaliptraError::RUNTIME_SIGN_WITH_EXPORTED_ECDSA_INVALID_SIGNATURE); } if y.len() <= resp.derived_pubkey_y.len() { resp.derived_pubkey_y[..y.len()].copy_from_slice(y.bytes()); } else { return Err(CaliptraError::RUNTIME_SIGN_WITH_EXPORTED_ECDSA_INVALID_SIGNATURE); } Ok(core::mem::size_of::<SignWithExportedEcdsaResp>()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/pcr.rs
runtime/src/pcr.rs
/*++ Licensed under the Apache-2.0 license. File Name: pcr.rs Abstract: File contains mailbox commands that deal with PCRs. --*/ use crate::{mutrefbytes, Drivers}; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::{ AlgorithmType, ExtendPcrReq, GetPcrLogResp, IncrementPcrResetCounterReq, MailboxRespHeader, QuotePcrsEcc384Req, QuotePcrsEcc384Resp, QuotePcrsMldsa87Req, QuotePcrsMldsa87Resp, }; use caliptra_drivers::{CaliptraError, CaliptraResult, PcrId}; use zerocopy::{FromBytes, IntoBytes}; pub struct IncrementPcrResetCounterCmd; impl IncrementPcrResetCounterCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult<usize> { let cmd = IncrementPcrResetCounterReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; let index = u8::try_from(cmd.index).map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; let pcr = PcrId::try_from(index).map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; if !drivers .persistent_data .get_mut() .fw .pcr_reset .increment(pcr) { return Err(CaliptraError::RUNTIME_INCREMENT_PCR_RESET_MAX_REACHED); } Ok(0) } } pub struct GetPcrQuoteCmd; impl GetPcrQuoteCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, alg_type: AlgorithmType, cmd_bytes: &[u8], resp: &mut [u8], ) -> CaliptraResult<usize> { let raw_pcrs = drivers.pcr_bank.read_all_pcrs(); match alg_type { AlgorithmType::Ecc384 => { let args = QuotePcrsEcc384Req::ref_from_bytes(cmd_bytes) .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; let pcr_hash = drivers.sha2_512_384.gen_pcr_hash(args.nonce.into())?; let signature = drivers.ecc384.pcr_sign_flow(&mut drivers.trng)?; let resp = mutrefbytes::<QuotePcrsEcc384Resp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.nonce = args.nonce; for (i, p) in raw_pcrs.iter().enumerate() { resp.pcrs[i] = p.into() } resp.reset_ctrs = drivers.persistent_data.get().fw.pcr_reset.all_counters(); // Change the word endianness for ECC verification. Take lower 48 bytes. resp.digest .copy_from_slice((&<[_; 64]>::from(pcr_hash))[..48].as_ref()); resp.signature_r = signature.r.into(); resp.signature_s = signature.s.into(); Ok(core::mem::size_of::<QuotePcrsEcc384Resp>()) } AlgorithmType::Mldsa87 => { let args = QuotePcrsMldsa87Req::ref_from_bytes(cmd_bytes) .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; let mut pcr_hash = drivers.sha2_512_384.gen_pcr_hash(args.nonce.into())?; pcr_hash.0.reverse(); // Reverse the order of the DWORDs for MLDSA. let signature = drivers.mldsa87.pcr_sign_flow(&mut drivers.trng)?; let resp = mutrefbytes::<QuotePcrsMldsa87Resp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.nonce = args.nonce; for (i, p) in raw_pcrs.iter().enumerate() { resp.pcrs[i] = p.into() } resp.reset_ctrs = drivers.persistent_data.get().fw.pcr_reset.all_counters(); resp.digest.copy_from_slice(pcr_hash.0.as_bytes()); resp.signature = signature.into(); Ok(core::mem::size_of::<QuotePcrsMldsa87Resp>()) } } } } pub struct ExtendPcrCmd; impl ExtendPcrCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult<usize> { let cmd = ExtendPcrReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; let idx = u8::try_from(cmd.pcr_idx).map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; let pcr_index: PcrId = match PcrId::try_from(idx).map_err(|_| CaliptraError::RUNTIME_PCR_INVALID_INDEX)? { PcrId::PcrId0 | PcrId::PcrId1 | PcrId::PcrId2 | PcrId::PcrId3 => { return Err(CaliptraError::RUNTIME_PCR_RESERVED) } pcr_id => pcr_id, }; drivers .pcr_bank .extend_pcr(pcr_index, &mut drivers.sha2_512_384, &cmd.data)?; Ok(0) } } pub struct GetPcrLogCmd; impl GetPcrLogCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, resp: &mut [u8]) -> CaliptraResult<usize> { let resp = mutrefbytes::<GetPcrLogResp>(resp)?; resp.hdr = MailboxRespHeader::default(); let pcr_log = drivers.persistent_data.get().rom.pcr_log.as_bytes(); let len = pcr_log.len(); resp.data_size = len as u32; resp.data[..len].copy_from_slice(&pcr_log[..len]); Ok(core::mem::size_of::<GetPcrLogResp>()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/authorize_and_stash.rs
runtime/src/authorize_and_stash.rs
/*++ Licensed under the Apache-2.0 license. File Name: authorize_and_stash.rs Abstract: File contains AUTHORIZE_AND_STASH mailbox command. --*/ use crate::manifest::find_metadata_entry; use crate::{mutrefbytes, Drivers, StashMeasurementCmd}; use caliptra_auth_man_types::ImageMetadataFlags; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_launder}; use caliptra_common::mailbox_api::{ AuthAndStashFlags, AuthorizeAndStashReq, AuthorizeAndStashResp, ImageHashSource, MailboxRespHeader, }; use caliptra_drivers::{AesDmaMode, DmaRecovery}; use caliptra_drivers::{Array4x12, AxiAddr, CaliptraError, CaliptraResult}; use dpe::response::DpeErrorCode; use zerocopy::FromBytes; pub const IMAGE_AUTHORIZED: u32 = 0xDEADC0DE; // Either FW ID and image digest matched or 'ignore_auth_check' is set for the FW ID. pub const IMAGE_NOT_AUTHORIZED: u32 = 0x21523F21; // FW ID not found in the image metadata entry collection. pub const IMAGE_HASH_MISMATCH: u32 = 0x8BFB95CB; // FW ID matched, but image digest mismatched. pub struct AuthorizeAndStashCmd; impl AuthorizeAndStashCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, cmd_args: &[u8], resp: &mut [u8], ) -> CaliptraResult<usize> { if let Ok(cmd) = AuthorizeAndStashReq::ref_from_bytes(cmd_args) { let resp = mutrefbytes::<AuthorizeAndStashResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.auth_req_result = Self::authorize_and_stash(drivers, cmd)?; Ok(core::mem::size_of::<AuthorizeAndStashResp>()) } else { Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY) } } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn authorize_and_stash( drivers: &mut Drivers, cmd: &AuthorizeAndStashReq, ) -> CaliptraResult<u32> { let source = ImageHashSource::from(cmd.source); if source == ImageHashSource::Invalid { Err(CaliptraError::RUNTIME_AUTH_AND_STASH_UNSUPPORTED_IMAGE_SOURCE)?; } // Check if firmware id is present in the image metadata entry collection. let persistent_data = drivers.persistent_data.get(); let dma_image = DmaRecovery::new( drivers.soc_ifc.recovery_interface_base_addr().into(), drivers.soc_ifc.caliptra_base_axi_addr().into(), drivers.soc_ifc.mci_base_addr().into(), &drivers.dma, ); let auth_manifest_image_metadata_col = &persistent_data.fw.auth_manifest_image_metadata_col; let cmd_fw_id = u32::from_le_bytes(cmd.fw_id); let auth_result = if let Some(metadata_entry) = find_metadata_entry(auth_manifest_image_metadata_col, cmd_fw_id) { // If 'ignore_auth_check' is set, then skip the image digest comparison and authorize the image. let flags = ImageMetadataFlags(metadata_entry.flags); if flags.ignore_auth_check() { cfi_assert!(cfi_launder(flags.ignore_auth_check())); IMAGE_AUTHORIZED } else if source == ImageHashSource::InRequest { if cfi_launder(metadata_entry.digest) == cmd.measurement { caliptra_cfi_lib_git::cfi_assert_eq_12_words( &Array4x12::from(metadata_entry.digest).0, &Array4x12::from(cmd.measurement).0, ); IMAGE_AUTHORIZED } else { IMAGE_HASH_MISMATCH } } else if source == ImageHashSource::LoadAddress || source == ImageHashSource::StagingAddress { let image_source = if source == ImageHashSource::LoadAddress { metadata_entry.image_load_address } else { metadata_entry.image_staging_address }; let measurement: [u8; 48] = dma_image .sha384_image( &mut drivers.sha2_512_384_acc, AxiAddr { hi: image_source.hi, lo: image_source.lo, }, cmd.image_size, AesDmaMode::None, ) .map_err(|_| CaliptraError::RUNTIME_INTERNAL)? .into(); if cfi_launder(metadata_entry.digest) == measurement { caliptra_cfi_lib_git::cfi_assert_eq_12_words( &Array4x12::from(metadata_entry.digest).0, &Array4x12::from(measurement).0, ); IMAGE_AUTHORIZED } else { IMAGE_HASH_MISMATCH } } else { IMAGE_NOT_AUTHORIZED } } else { IMAGE_NOT_AUTHORIZED }; // Stash the measurement if the image is authorized. if auth_result == IMAGE_AUTHORIZED { let flags: AuthAndStashFlags = cmd.flags.into(); if !flags.contains(AuthAndStashFlags::SKIP_STASH) { let dpe_result = StashMeasurementCmd::stash_measurement( drivers, &cmd.fw_id, &cmd.measurement, cmd.svn, )?; if dpe_result != DpeErrorCode::NoError { drivers .soc_ifc .set_fw_extended_error(dpe_result.get_error_code()); Err(CaliptraError::RUNTIME_AUTH_AND_STASH_MEASUREMENT_DPE_ERROR)?; } } } Ok(auth_result) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/get_idev_csr.rs
runtime/src/get_idev_csr.rs
// Licensed under the Apache-2.0 license use crate::{mutrefbytes, Drivers}; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::{GetIdevCsrResp, MailboxRespHeader, ResponseVarSize}; use caliptra_error::{CaliptraError, CaliptraResult}; use caliptra_drivers::{Ecc384IdevIdCsr, Mldsa87IdevIdCsr}; pub struct GetIdevCsrCmd; impl GetIdevCsrCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, resp: &mut [u8]) -> CaliptraResult<usize> { let csr_persistent_mem = &drivers.persistent_data.get().rom.idevid_csr_envelop.ecc_csr; match csr_persistent_mem.get_csr_len() { Ecc384IdevIdCsr::UNPROVISIONED_CSR => { Err(CaliptraError::RUNTIME_GET_IDEV_ID_UNPROVISIONED) } 0 => Err(CaliptraError::RUNTIME_GET_IDEV_ID_UNSUPPORTED_ROM), len => { let csr = csr_persistent_mem .get() .ok_or(CaliptraError::RUNTIME_GET_IDEV_ID_UNPROVISIONED)?; let resp = mutrefbytes::<GetIdevCsrResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.data_size = len; // NOTE: This code will not panic. // // csr is guranteed to be the same size as `len`, and therefore // `resp.data_size` by the `IDevIDCsr::get` API. // // A valid `IDevIDCsr` cannot be larger than `ECC384_MAX_IDEVID_CSR_SIZE`, which is less // than the the max size of the buffer in `GetIdevCsrResp` resp.data[..resp.data_size as usize].copy_from_slice(csr); Ok(resp.partial_len()?) } } } } pub struct GetIdevMldsaCsrCmd; impl GetIdevMldsaCsrCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, resp: &mut [u8]) -> CaliptraResult<usize> { let csr_persistent_mem = &drivers .persistent_data .get() .rom .idevid_csr_envelop .mldsa_csr; match csr_persistent_mem.get_csr_len() { Mldsa87IdevIdCsr::UNPROVISIONED_CSR => { Err(CaliptraError::RUNTIME_GET_IDEV_ID_UNPROVISIONED) } 0 => Err(CaliptraError::RUNTIME_GET_IDEV_ID_UNSUPPORTED_ROM), len => { let csr = csr_persistent_mem .get() .ok_or(CaliptraError::RUNTIME_GET_IDEV_ID_UNPROVISIONED)?; let resp = mutrefbytes::<GetIdevCsrResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.data_size = len; // NOTE: This code will not panic. // // csr is guranteed to be the same size as `len`, and therefore // `resp.data_size` by the `IDevIDCsr::get` API. // // A valid `IDevIDCsr` cannot be larger than `MLDSA87_MAX_CSR_SIZE`, which is less // than the the max size of the buffer in `GetIdevCsrResp` resp.data[..resp.data_size as usize].copy_from_slice(csr); Ok(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/runtime/src/main.rs
runtime/src/main.rs
/*++ Licensed under the Apache-2.0 license. File Name: main.rs Abstract: File contains main entry point for Caliptra Test Runtime --*/ #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_main)] #[cfg(target_arch = "riscv32")] core::arch::global_asm!(include_str!("ext_intr.S")); use caliptra_cfi_lib_git::CfiCounter; use caliptra_common::{cprintln, handle_fatal_error}; use caliptra_cpu::{log_trap_record, TrapRecord}; use caliptra_drivers::{FwPersistentData, RomPersistentData}; use caliptra_error::CaliptraError; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_runtime::Drivers; use core::hint::black_box; #[cfg(feature = "std")] pub fn main() {} const BANNER: &str = "Caliptra RT"; #[no_mangle] #[allow(clippy::empty_loop)] pub extern "C" fn entry_point() -> ! { cprintln!("{}", BANNER); #[cfg(target_arch = "riscv32")] unsafe { // Write meivt (External Interrupt Vector Table Register) // VeeR has been instantiated with RV_FAST_INTERRUPT_REDIRECT, // so external interrupts always bypass the standard risc-v dispatch logic // and instead load the destination address from this table in DCCM. core::arch::asm!( "la {tmp}, _ext_intr_vector", "csrw 0xbc8, {tmp}", tmp = out(reg) _, ); } let mut drivers = unsafe { Drivers::new_from_registers().unwrap_or_else(|e| { cprintln!("[rt] RT can't load drivers"); handle_fatal_error(e.into()); }) }; if !cfg!(feature = "no-cfi") { cprintln!("[state] CFI Enabled"); let mut entropy_gen = || { drivers .trng .generate() .map(|a| a.0) .map_err(|_| caliptra_cfi_lib_git::CfiPanicInfo::TrngError) }; CfiCounter::reset(&mut entropy_gen); CfiCounter::reset(&mut entropy_gen); CfiCounter::reset(&mut entropy_gen); } else { cprintln!("[state] CFI Disabled"); } // Check persistent data is valid let pdata = drivers.persistent_data.get(); if pdata.rom.marker != RomPersistentData::MAGIC { handle_fatal_error(CaliptraError::RUNTIME_INVALID_ROM_PERSISTENT_DATA_MARKER.into()) } if pdata.rom.major_version != RomPersistentData::MAJOR_VERSION || pdata.rom.minor_version != RomPersistentData::MINOR_VERSION { handle_fatal_error(CaliptraError::RUNTIME_INVALID_ROM_PERSISTENT_DATA_VERSION.into()) } if pdata.fw.marker != FwPersistentData::MAGIC { handle_fatal_error(CaliptraError::RUNTIME_INVALID_FW_PERSISTENT_DATA_MARKER.into()) } if pdata.fw.version != FwPersistentData::VERSION { handle_fatal_error(CaliptraError::RUNTIME_INVALID_FW_PERSISTENT_DATA_VERSION.into()) } if drivers.ocp_lock_context.available() { cprintln!("[rt] OCP LOCK Supported"); } else { cprintln!("[rt] OCP LOCK Unsupported"); } drivers.run_reset_flow().unwrap_or_else(|e| { cprintln!("[rt] RT failed reset flow"); handle_fatal_error(e.into()); }); if !drivers.persistent_data.get().rom.fht.is_valid() { cprintln!("[rt] RT can't load FHT"); handle_fatal_error(caliptra_drivers::CaliptraError::RUNTIME_HANDOFF_FHT_NOT_LOADED.into()); } cprintln!("[rt] RT listening for mailbox commands..."); if let Err(e) = caliptra_runtime::handle_mailbox_commands(&mut drivers) { 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!( "RT EXCEPTION mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X} ra=0x{:08X}", trap_record.mcause, trap_record.mscause, trap_record.mepc, trap_record.ra, ); log_trap_record(trap_record, None); // Signal non-fatal error to SOC handle_fatal_error(caliptra_drivers::CaliptraError::RUNTIME_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!( "RT NMI mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X} ra=0x{:08X} error_internal_intr_r={:08X}", trap_record.mcause, trap_record.mscause, trap_record.mepc, trap_record.ra, err_interrupt_status, ); let wdt_status = soc_ifc.regs().cptra_wdt_status().read(); let error = if wdt_status.t1_timeout() || wdt_status.t2_timeout() { cprintln!("[rt] WDT Expired"); CaliptraError::RUNTIME_GLOBAL_WDT_EXPIRED } else { CaliptraError::RUNTIME_GLOBAL_NMI }; handle_fatal_error(error.into()); } #[panic_handler] #[inline(never)] #[cfg(not(feature = "std"))] #[allow(clippy::empty_loop)] fn runtime_panic(_: &core::panic::PanicInfo) -> ! { cprintln!("RT Panic!!"); panic_is_possible(); // TODO: Signal non-fatal error to SOC handle_fatal_error(caliptra_drivers::CaliptraError::RUNTIME_GLOBAL_PANIC.into()); } #[no_mangle] extern "C" fn cfi_panic_handler(code: u32) -> ! { cprintln!("RT CFI Panic code=0x{:08X}", code); handle_fatal_error(code); } #[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/runtime/src/activate_firmware.rs
runtime/src/activate_firmware.rs
/*++ Licensed under the Apache-2.0 license. File Name: activate_firmware.rs Abstract: File contains ACTIVATE_FIRMWARE mailbox command. --*/ use core::mem::offset_of; use crate::authorize_and_stash::AuthorizeAndStashCmd; use crate::drivers::{McuFwStatus, McuResetReason}; use crate::Drivers; use crate::{manifest::find_metadata_entry, mutrefbytes}; use caliptra_api::mailbox::{AuthAndStashFlags, AuthorizeAndStashReq, ImageHashSource}; use caliptra_auth_man_types::ImageMetadataFlags; use caliptra_common::mailbox_api::{ActivateFirmwareReq, ActivateFirmwareResp, MailboxRespHeader}; use caliptra_drivers::dma::MCU_SRAM_OFFSET; use caliptra_drivers::{AesDmaMode, AxiAddr, CaliptraError, CaliptraResult, DmaMmio, DmaRecovery}; use ureg::{Mmio, MmioMut}; pub const MCI_TOP_REG_RESET_REASON_OFFSET: u32 = 0x38; const MCI_TOP_REG_INTR_RF_BLOCK_OFFSET: u32 = 0x1000; const NOTIF0_INTERNAL_INTR_R_OFFSET: u32 = MCI_TOP_REG_INTR_RF_BLOCK_OFFSET + 0x24; const NOTIF0_INTR_TRIG_R_OFFSET: u32 = MCI_TOP_REG_INTR_RF_BLOCK_OFFSET + 0x34; const NOTIF_CPTRA_MCU_RESET_REQ_STS_MASK: u32 = 0x2; const MAX_EXEC_GO_BIT_INDEX: u8 = 127; pub struct ActivateFirmwareCmd; impl ActivateFirmwareCmd { #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, cmd_args: &[u8], resp: &mut [u8], ) -> CaliptraResult<usize> { let fw_id_count: usize = { let err = CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS; let offset = offset_of!(ActivateFirmwareReq, fw_id_count); u32::from_le_bytes( cmd_args .get(offset..offset + 4) .ok_or(err)? .try_into() .map_err(|_| err)?, ) .try_into() .unwrap() }; if (fw_id_count == 0) || (fw_id_count > ActivateFirmwareReq::MAX_FW_ID_COUNT) { Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; } let mcu_image_size: usize = { let err = CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS; let offset = offset_of!(ActivateFirmwareReq, mcu_fw_image_size); u32::from_le_bytes( cmd_args .get(offset..offset + 4) .ok_or(err)? .try_into() .map_err(|_| err)?, ) .try_into() .unwrap() }; let mut images_to_activate_bitmap: [u32; 4] = [0; 4]; for i in 0..fw_id_count { let offset = offset_of!(ActivateFirmwareReq, fw_ids) + (i * 4); if cmd_args.len() < offset + 4 { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } let fw_id = u32::from_le_bytes( cmd_args[offset..offset + 4] .try_into() .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?, ); if fw_id == ActivateFirmwareReq::RESERVED0_IMAGE_ID || fw_id == ActivateFirmwareReq::RESERVED1_IMAGE_ID { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } if fw_id == ActivateFirmwareReq::MCU_IMAGE_ID && mcu_image_size == 0 { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } let image_metadata = find_metadata_entry( &drivers .persistent_data .get() .fw .auth_manifest_image_metadata_col, fw_id, ) .ok_or(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; let exec_bit = ImageMetadataFlags(image_metadata.flags).exec_bit() as u8; // Check if exec_bit is valid // Note that bits 0 and 1 are reserved. Refer to // https://chipsalliance.github.io/caliptra-rtl/main/external-regs/?p=caliptra_top_reg.generic_and_fuse_reg.SS_GENERIC_FW_EXEC_CTRL%5B0%5D if exec_bit == 0 || exec_bit == 1 || exec_bit > MAX_EXEC_GO_BIT_INDEX { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } Self::set_bit(&mut images_to_activate_bitmap, fw_id as usize); } Self::activate_fw(drivers, &images_to_activate_bitmap, mcu_image_size as u32) .map_err(|_| CaliptraError::IMAGE_VERIFIER_ACTIVATION_FAILED)?; let resp = mutrefbytes::<ActivateFirmwareResp>(resp)?; resp.hdr = MailboxRespHeader::default(); Ok(core::mem::size_of::<ActivateFirmwareResp>()) } #[inline(never)] pub(crate) fn activate_fw( drivers: &mut Drivers, activate_bitmap: &[u32; 4], mcu_image_size: u32, ) -> Result<(), ()> { let mci_base_addr: AxiAddr = drivers.soc_ifc.mci_base_addr().into(); let mut go_bitmap: [u32; 4] = [0; 4]; // Get the current value of FW_EXEC_CTRL drivers.soc_ifc.get_ss_generic_fw_exec_ctrl(&mut go_bitmap); let mut temp_bitmap: [u32; 4] = [0; 4]; // Caliptra clears FW_EXEC_CTRL for all affected images for i in 0..4 { temp_bitmap[i] = go_bitmap[i] & !activate_bitmap[i]; } // Leave MCU image bit as is, we will set it later after the reset_reason is set to avoid race condition // between Caliptra and MCU if Self::is_bit_set(&go_bitmap, ActivateFirmwareReq::MCU_IMAGE_ID as usize) { Self::set_bit(&mut temp_bitmap, ActivateFirmwareReq::MCU_IMAGE_ID as usize); } drivers.soc_ifc.set_ss_generic_fw_exec_ctrl(&temp_bitmap); if Self::is_bit_set(activate_bitmap, ActivateFirmwareReq::MCU_IMAGE_ID as usize) { // MCU sees request from Caliptra and shall clear the interrupt status. // MCU sets RESET_REQUEST.mcu_req in MCI to request a reset. // MCI does an MCU halt req/ack handshake to ensure the MCU is idle // MCI asserts MCU reset (min reset time for MCU is until MIN_MCU_RST_COUNTER overflows) drivers.persistent_data.get_mut().fw.mcu_firmware_loaded = McuFwStatus::HitlessUpdateStarted.into(); Drivers::set_mcu_reset_reason(drivers, McuResetReason::FwHitlessUpd); let dma = &drivers.dma; let mmio = &DmaMmio::new(mci_base_addr, dma); // Trigger MCU reset request unsafe { mmio.write_volatile( NOTIF0_INTR_TRIG_R_OFFSET as *mut u32, NOTIF_CPTRA_MCU_RESET_REQ_STS_MASK, ); } // Wait for MCU to clear interrupt let mut intr_status: u32 = 1; while intr_status != 0 { intr_status = unsafe { mmio.read_volatile(NOTIF0_INTERNAL_INTR_R_OFFSET as *const u32) } & NOTIF_CPTRA_MCU_RESET_REQ_STS_MASK; } // Clear FW_EXEC_CTRL[2] Self::clear_bit(&mut temp_bitmap, ActivateFirmwareReq::MCU_IMAGE_ID as usize); drivers.soc_ifc.set_ss_generic_fw_exec_ctrl(&temp_bitmap); // Wait for MCU to clear interrupt let mut intr_status: u32 = 1; while intr_status != 0 { intr_status = unsafe { mmio.read_volatile(NOTIF0_INTERNAL_INTR_R_OFFSET as *const u32) } & NOTIF_CPTRA_MCU_RESET_REQ_STS_MASK; } // Caliptra will then have access to MCU SRAM Updatable Execution Region and update the FW image. let image_metadata = find_metadata_entry( &drivers .persistent_data .get() .fw .auth_manifest_image_metadata_col, ActivateFirmwareReq::MCU_IMAGE_ID, ) .ok_or(())?; let dma_image = DmaRecovery::new( drivers.soc_ifc.recovery_interface_base_addr().into(), drivers.soc_ifc.caliptra_base_axi_addr().into(), drivers.soc_ifc.mci_base_addr().into(), &drivers.dma, ); let mcu_sram_addr: u64 = ((mci_base_addr.hi as u64) << 32) + (mci_base_addr.lo as u64) + MCU_SRAM_OFFSET; dma_image .transfer_payload_to_axi( AxiAddr { hi: image_metadata.image_staging_address.hi, lo: image_metadata.image_staging_address.lo, }, mcu_image_size, AxiAddr { hi: (mcu_sram_addr >> 32) as u32, lo: mcu_sram_addr as u32, }, false, false, AesDmaMode::None, ) .map_err(|_| ())?; // Verify MCU after loading let auth_and_stash_req = AuthorizeAndStashReq { fw_id: ActivateFirmwareReq::MCU_IMAGE_ID.to_le_bytes(), measurement: [0; 48], source: ImageHashSource::LoadAddress.into(), flags: AuthAndStashFlags::SKIP_STASH.bits(), ..Default::default() }; AuthorizeAndStashCmd::authorize_and_stash(drivers, &auth_and_stash_req) .map(|_| ()) .map_err(|_| ())?; drivers.persistent_data.get_mut().fw.mcu_firmware_loaded = McuFwStatus::Loaded.into(); } for i in 0..4 { temp_bitmap[i] = go_bitmap[i] | activate_bitmap[i]; } // Caliptra sets FW_EXEC_CTRL drivers.soc_ifc.set_ss_generic_fw_exec_ctrl(&temp_bitmap); Ok(()) } fn set_bit(bitmap: &mut [u32; 4], bit: usize) { if bit < core::mem::size_of_val(bitmap) * 8 { let idx = bit / 32; let offset = bit % 32; bitmap[idx] |= 1 << offset; } } fn clear_bit(bitmap: &mut [u32; 4], bit: usize) { if bit < core::mem::size_of_val(bitmap) * 8 { let idx = bit / 32; let offset = bit % 32; bitmap[idx] &= !(1 << offset); } } fn is_bit_set(bitmap: &[u32; 4], bit: usize) -> bool { if bit < core::mem::size_of_val(bitmap) * 8 { let idx = bit / 32; let offset = bit % 32; (bitmap[idx] & (1 << offset)) != 0 } else { false } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/invoke_dpe.rs
runtime/src/invoke_dpe.rs
/*++ Licensed under the Apache-2.0 license. File Name: invoke_dpe.rs Abstract: File contains InvokeDpe mailbox command. --*/ use crate::{ mutrefbytes, CptraDpeTypes, DpeCrypto, DpeEnv, DpePlatform, Drivers, PauserPrivileges, }; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::{InvokeDpeReq, InvokeDpeResp, ResponseVarSize}; use caliptra_drivers::{CaliptraError, CaliptraResult}; use dpe::{ commands::{CertifyKeyCmd, Command, CommandExecution, DeriveContextCmd, InitCtxCmd}, context::ContextState, response::{Response, ResponseHdr}, DpeInstance, DpeProfile, U8Bool, MAX_HANDLES, }; use zerocopy::IntoBytes; pub struct InvokeDpeCmd; impl InvokeDpeCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, cmd_args: &[u8], mbox_resp: &mut [u8], ) -> CaliptraResult<usize> { if cmd_args.len() <= core::mem::size_of::<InvokeDpeReq>() { let mut cmd = InvokeDpeReq::default(); cmd.as_mut_bytes()[..cmd_args.len()].copy_from_slice(cmd_args); let hashed_rt_pub_key = drivers.compute_rt_alias_sn()?; let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; let key_id_rt_priv_key = Drivers::get_key_id_rt_priv_key(drivers)?; let caller_privilege_level = drivers.caller_privilege_level(); // Validate data length if cmd.data_size as usize > cmd.data.len() { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } let command = Command::deserialize(DpeProfile::P384Sha384, &cmd.data[..cmd.data_size as usize]) .map_err(|_| CaliptraError::RUNTIME_DPE_COMMAND_DESERIALIZATION_FAILED)?; // Determine the target privilege level of a new context then check if we exceed thresholds let new_context_privilege_level = match command { Command::DeriveContext(cmd) if DeriveContextCmd::changes_locality(cmd) => { drivers.privilege_level_from_locality(cmd.target_locality) } _ => caller_privilege_level, }; let dpe_context_threshold_err = drivers.is_dpe_context_threshold_exceeded(new_context_privilege_level); let pdata = drivers.persistent_data.get_mut(); let crypto = DpeCrypto::new( &mut drivers.sha2_512_384, &mut drivers.trng, &mut drivers.ecc384, &mut drivers.hmac, &mut drivers.key_vault, &mut pdata.rom.fht.rt_dice_ecc_pub_key, key_id_rt_cdi, key_id_rt_priv_key, &mut pdata.fw.dpe.exported_cdi_slots, ); let pl0_pauser = pdata.rom.manifest1.header.pl0_pauser; let (nb, nf) = Drivers::get_cert_validity_info(&pdata.rom.manifest1); let ueid = &drivers.soc_ifc.fuse_bank().ueid(); let mut env = DpeEnv::<CptraDpeTypes> { crypto, platform: DpePlatform::new( pl0_pauser, &hashed_rt_pub_key, &drivers.ecc_cert_chain, &nb, &nf, None, Some(ueid), ), state: &mut pdata.fw.dpe.state, }; let locality = drivers.mbox.id(); let dpe = &mut DpeInstance::initialized(); let context_has_tag = &mut pdata.fw.dpe.context_has_tag; let context_tags = &mut pdata.fw.dpe.context_tags; let resp = match command { Command::GetProfile => Ok(Response::GetProfile( dpe.get_profile(&mut env.platform, env.state.support) .map_err(|_| CaliptraError::RUNTIME_COULD_NOT_GET_DPE_PROFILE)?, )), Command::InitCtx(cmd) => { // InitCtx can only create new contexts if they are simulation contexts. if InitCtxCmd::flag_is_simulation(cmd) { dpe_context_threshold_err?; } cmd.execute(dpe, &mut env, locality) } Command::DeriveContext(cmd) => { // If the recursive flag is not set, DeriveContext will generate a new context. // If recursive _is_ set, it will extend the existing one, which will not count // against the context threshold. if !DeriveContextCmd::is_recursive(cmd) { // Takes target locality into consideration if applicable. See above dpe_context_threshold_err?; } if DeriveContextCmd::changes_locality(cmd) && cmd.target_locality == pl0_pauser && caller_privilege_level != PauserPrivileges::PL0 { return Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL); } if DeriveContextCmd::exports_cdi(cmd) && caller_privilege_level != PauserPrivileges::PL0 { return Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL); } cmd.execute(dpe, &mut env, locality) } Command::CertifyKey(cmd) => { // PL1 cannot request X509 if cmd.format == CertifyKeyCmd::FORMAT_X509 && caller_privilege_level != PauserPrivileges::PL0 { return Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL); } cmd.execute(dpe, &mut env, locality) } Command::DestroyCtx(cmd) => { let destroy_ctx_resp = cmd.execute(dpe, &mut env, locality); // clear tags for destroyed contexts Self::clear_tags_for_inactive_contexts( env.state, context_has_tag, context_tags, ); destroy_ctx_resp } Command::Sign(cmd) => cmd.execute(dpe, &mut env, locality), Command::RotateCtx(cmd) => cmd.execute(dpe, &mut env, locality), Command::GetCertificateChain(cmd) => cmd.execute(dpe, &mut env, locality), }; // If DPE command failed, populate header with error code, but // don't fail the mailbox command. let invoke_resp = mutrefbytes::<InvokeDpeResp>(mbox_resp)?; match resp { Ok(ref r) => { let resp_bytes = r.as_bytes(); let data_size = resp_bytes.len(); invoke_resp.data[..data_size].copy_from_slice(resp_bytes); invoke_resp.data_size = data_size as u32; } Err(ref e) => { // If there is extended error info, populate CPTRA_FW_EXTENDED_ERROR_INFO if let Some(ext_err) = e.get_error_detail() { drivers.soc_ifc.set_fw_extended_error(ext_err); } let r = dpe.response_hdr(*e); invoke_resp.data[..core::mem::size_of::<ResponseHdr>()] .copy_from_slice(r.as_bytes()); let data_size = r.as_bytes().len(); invoke_resp.data_size = data_size as u32; } }; Ok(invoke_resp.partial_len()?) } else { Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY) } } /// Remove context tags for all inactive DPE contexts /// /// # Arguments /// /// * `dpe` - DPE state /// * `context_has_tag` - Bool slice indicating if a DPE context has a tag /// * `context_tags` - Tags for each DPE context #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn clear_tags_for_inactive_contexts( dpe: &mut dpe::State, context_has_tag: &mut [U8Bool; MAX_HANDLES], context_tags: &mut [u32; MAX_HANDLES], ) { (0..MAX_HANDLES).for_each(|i| { if i < dpe.contexts.len() && i < context_has_tag.len() && i < context_tags.len() && dpe.contexts[i].state == ContextState::Inactive { context_has_tag[i] = U8Bool::new(false); context_tags[i] = 0; } }); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/debug_unlock.rs
runtime/src/debug_unlock.rs
/*++ Licensed under the Apache-2.0 license. File Name: debug_unlock.rs Abstract: File contains code to handle production debug unlock in the runtime. --*/ use crate::mutrefbytes; use caliptra_cfi_lib_git::CfiCounter; use caliptra_common::{ cprintln, mailbox_api::{ ProductionAuthDebugUnlockChallenge, ProductionAuthDebugUnlockReq, ProductionAuthDebugUnlockToken, }, }; use caliptra_drivers::{CaliptraResult, Lifecycle}; use caliptra_error::CaliptraError; use zerocopy::FromBytes; /// Handle production debug unlock for runtime firmware pub struct ProductionDebugUnlock { // Store the last challenge for token validation last_challenge: Option<ProductionAuthDebugUnlockChallenge>, // Store the original request for token validation last_request: Option<ProductionAuthDebugUnlockReq>, } impl Default for ProductionDebugUnlock { fn default() -> Self { Self::new() } } impl ProductionDebugUnlock { /// Create a new instance of the debug unlock handler pub fn new() -> Self { Self { last_challenge: None, last_request: None, } } /// Handle the production debug unlock request pub fn handle_request( &mut self, trng: &mut caliptra_drivers::Trng, soc_ifc: &caliptra_drivers::SocIfc, cmd_bytes: &[u8], resp: &mut [u8], ) -> CaliptraResult<usize> { if !soc_ifc.ss_debug_unlock_req()? { Err(CaliptraError::SS_DBG_UNLOCK_REQ_BIT_NOT_SET)?; } // Parse the request let req = ProductionAuthDebugUnlockReq::read_from_bytes(cmd_bytes) .map_err(|_| CaliptraError::RUNTIME_MAILBOX_API_REQUEST_DATA_LEN_TOO_LARGE)?; cprintln!("[rt] Starting production debug unlock request"); // Check if the device is in Production lifecycle if soc_ifc.lifecycle() != Lifecycle::Production { cprintln!("[rt] Debug unlock request failed: Not in Production lifecycle"); return Err(CaliptraError::RUNTIME_DEBUG_UNLOCK_INVALID_LIFECYCLE); } // Use common function to create challenge let challenge = caliptra_common::debug_unlock::create_debug_unlock_challenge(trng, soc_ifc, &req)?; // Store the challenge for future token validation let stored_challenge = challenge.clone(); self.last_challenge = Some(stored_challenge); self.last_request = Some(req); cprintln!("[rt] Production debug unlock challenge generated"); let resp = mutrefbytes::<ProductionAuthDebugUnlockChallenge>(resp)?; *resp = challenge; Ok(core::mem::size_of::<ProductionAuthDebugUnlockChallenge>()) } /// Handle the production debug unlock token verification #[allow(clippy::too_many_arguments)] pub fn handle_token( &mut self, soc_ifc: &mut caliptra_drivers::SocIfc, sha2_512_384: &mut caliptra_drivers::Sha2_512_384, sha2_512_384_acc: &mut caliptra_drivers::Sha2_512_384Acc, ecc384: &mut caliptra_drivers::Ecc384, mldsa87: &mut caliptra_drivers::Mldsa87, dma: &mut caliptra_drivers::Dma, cmd_bytes: &[u8], ) -> CaliptraResult<usize> { // Parse the token let token = ProductionAuthDebugUnlockToken::read_from_bytes(cmd_bytes) .map_err(|_| CaliptraError::RUNTIME_MAILBOX_API_REQUEST_DATA_LEN_TOO_LARGE)?; cprintln!("[rt] Starting production debug unlock token validation"); // Random delay for CFI glitch protection. CfiCounter::delay(); // Check if the device is in Production lifecycle if soc_ifc.lifecycle() != Lifecycle::Production { cprintln!("[rt] Debug unlock token validation failed: Not in Production lifecycle"); return Err(CaliptraError::RUNTIME_DEBUG_UNLOCK_INVALID_LIFECYCLE); } // Get the stored challenge and request let challenge = self .last_challenge .take() .ok_or(CaliptraError::RUNTIME_DEBUG_UNLOCK_NO_CHALLENGE)?; let request = self .last_request .take() .ok_or(CaliptraError::RUNTIME_DEBUG_UNLOCK_NO_REQUEST)?; // Set debug unlock in progress soc_ifc.set_ss_dbg_unlock_in_progress(true); // Use the common validation logic let result = caliptra_common::debug_unlock::validate_debug_unlock_token( soc_ifc, sha2_512_384, sha2_512_384_acc, ecc384, mldsa87, dma, &request, &challenge, &token, ); let ret = match result { Ok(()) => { soc_ifc.set_ss_dbg_unlock_level(request.unlock_level); cprintln!("[rt] Debug unlock successful"); soc_ifc.set_ss_dbg_unlock_result(true); Ok(0) } Err(e) => { cprintln!("[rt] Debug unlock failed: {}", e.0); soc_ifc.set_ss_dbg_unlock_result(false); Err(e) } }; soc_ifc.set_ss_dbg_unlock_in_progress(false); ret } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/key_ladder.rs
runtime/src/key_ladder.rs
/*++ Licensed under the Apache-2.0 license. File Name: key_ladder.rs Abstract: File contains key ladder utilities. --*/ use crate::{handoff::RtHandoff, Drivers, Hmac}; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::keyids::KEY_ID_TMP; use caliptra_drivers::{CaliptraResult, HmacMode, KeyId}; use caliptra_error::CaliptraError; pub struct KeyLadder; impl KeyLadder { /// Calculates a secret from the key ladder. /// /// Extends the key ladder the requisite number of times, based on /// the given target SVN. Fails if the target SVN is too large. Runs /// a final KDF to derive the resulting secret in the destination KV /// slot. /// /// # Arguments /// /// * `drivers` - Drivers /// * `target_svn` - SVN to which the derived secret should be bound. May not be larger than the current key ladder's SVN. /// * `context` - Diversification value /// * `dest` - Key Vault slot to whch the derived secret should be written. #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub fn derive_secret( drivers: &mut Drivers, target_svn: u32, context: &[u8], dest: KeyId, ) -> CaliptraResult<()> { let handoff = RtHandoff { data_vault: &drivers.persistent_data.get().rom.data_vault, fht: &drivers.persistent_data.get().rom.fht, }; let key_ladder_svn = handoff.fw_min_svn(); let key_ladder_kv = handoff.fw_key_ladder()?; // Don't allow stomping over the key ladder secret. if dest == key_ladder_kv { // If this occurs it is an internal programming error within Caliptra firmware. Err(CaliptraError::RUNTIME_INTERNAL)?; } if target_svn > key_ladder_svn { Err(CaliptraError::RUNTIME_KEY_LADDER_TARGET_SVN_TOO_LARGE)?; } let num_iters = key_ladder_svn - target_svn; let secret_source = if num_iters == 0 { key_ladder_kv } else { let mut src_slot = key_ladder_kv; for _ in 0..num_iters { // First time through, KDF from key_ladder_kv into KEY_ID_TMP; // all other times through, stay in KEY_ID_TMP. Hmac::hmac_kdf( drivers, src_slot, b"si_extend", None, HmacMode::Hmac512, KEY_ID_TMP, )?; src_slot = KEY_ID_TMP; } KEY_ID_TMP }; Hmac::hmac_kdf( drivers, secret_source, b"chain_output", Some(context), HmacMode::Hmac512, dest, )?; if secret_source == KEY_ID_TMP && dest != KEY_ID_TMP { drivers.key_vault.erase_key(KEY_ID_TMP).unwrap(); } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/populate_idev.rs
runtime/src/populate_idev.rs
/*++ Licensed under the Apache-2.0 license. File Name: populate_idev.rs Abstract: File contains PopulateIdev mailbox command. --*/ use caliptra_common::mailbox_api::{PopulateIdevEcc384CertReq, PopulateIdevMldsa87CertReq}; use caliptra_error::{CaliptraError, CaliptraResult}; use zerocopy::IntoBytes; use crate::{Drivers, PL0_PAUSER_FLAG}; pub struct PopulateIDevIdEcc384CertCmd; impl PopulateIDevIdEcc384CertCmd { #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult<usize> { if cmd_args.len() > core::mem::size_of::<PopulateIdevEcc384CertReq>() { return Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY); } let mut cmd = PopulateIdevEcc384CertReq::default(); if cmd_args.len() > cmd.as_bytes().len() { return Err(CaliptraError::RUNTIME_MAILBOX_API_REQUEST_DATA_LEN_TOO_LARGE); } cmd.as_mut_bytes()[..cmd_args.len()].copy_from_slice(cmd_args); let cert_size = cmd.cert_size as usize; if cert_size > cmd.cert.len() { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } let flags = drivers.persistent_data.get().rom.manifest1.header.flags; // PL1 cannot call this mailbox command if flags & PL0_PAUSER_FLAG == 0 { return Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL); } // Avoid stack allocation by reusing the existing ArrayVec in-place. // Instead of creating a temporary ArrayVec, we shift existing content // down and insert the new certificate at the beginning. // Check if we have enough capacity for the new cert plus existing content let current_len = drivers.ecc_cert_chain.len(); if cert_size + current_len > drivers.ecc_cert_chain.capacity() { return Err(CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED); } // Move existing content down by cert_size bytes and copy new cert if current_len > 0 { // Append zeros to make room for the new cert for _ in 0..cert_size { drivers .ecc_cert_chain .try_push(0) .map_err(|_| CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED)?; } // Move existing content down (reverse iteration to avoid overwriting) for i in (0..current_len).rev() { let src_idx = i; let dst_idx = i + cert_size; if let Some(src_val) = drivers.ecc_cert_chain.get(src_idx).copied() { if let Some(dst) = drivers.ecc_cert_chain.get_mut(dst_idx) { *dst = src_val; } else { return Err(CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED); } } else { return Err(CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED); } } } else { // No existing content, just append zeros for _ in 0..cert_size { drivers .ecc_cert_chain .try_push(0) .map_err(|_| CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED)?; } } // Copy new cert data to the beginning drivers .ecc_cert_chain .as_mut_slice() .get_mut(..cert_size) .ok_or(CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED)? .copy_from_slice(&cmd.cert[..cert_size]); Ok(0) } } pub struct PopulateIDevIdMldsa87CertCmd; impl PopulateIDevIdMldsa87CertCmd { #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult<usize> { if cmd_args.len() > core::mem::size_of::<PopulateIdevMldsa87CertReq>() { return Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY); } let mut cmd = PopulateIdevMldsa87CertReq::default(); if cmd_args.len() > cmd.as_bytes().len() { return Err(CaliptraError::RUNTIME_MAILBOX_API_REQUEST_DATA_LEN_TOO_LARGE); } cmd.as_mut_bytes()[..cmd_args.len()].copy_from_slice(cmd_args); let cert_size = cmd.cert_size as usize; if cert_size > cmd.cert.len() { return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); } let flags = drivers.persistent_data.get().rom.manifest1.header.flags; // PL1 cannot call this mailbox command if flags & PL0_PAUSER_FLAG == 0 { return Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL); } // Avoid stack allocation by reusing the existing ArrayVec in-place. // Instead of creating a temporary ArrayVec, we shift existing content // down and insert the new certificate at the beginning. // Check if we have enough capacity for the new cert plus existing content let current_len = drivers.mldsa_cert_chain.len(); if cert_size + current_len > drivers.mldsa_cert_chain.capacity() { return Err(CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED); } // Move existing content down by cert_size bytes and copy new cert if current_len > 0 { // Append zeros to make room for the new cert for _ in 0..cert_size { drivers .mldsa_cert_chain .try_push(0) .map_err(|_| CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED)?; } // Move existing content down (reverse iteration to avoid overwriting) for i in (0..current_len).rev() { let src_idx = i; let dst_idx = i + cert_size; if let Some(src_val) = drivers.mldsa_cert_chain.get(src_idx).copied() { if let Some(dst) = drivers.mldsa_cert_chain.get_mut(dst_idx) { *dst = src_val; } else { return Err(CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED); } } else { return Err(CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED); } } } else { // No existing content, just append zeros for _ in 0..cert_size { drivers .mldsa_cert_chain .try_push(0) .map_err(|_| CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED)?; } } // Copy new cert data to the beginning drivers .mldsa_cert_chain .as_mut_slice() .get_mut(..cert_size) .ok_or(CaliptraError::RUNTIME_IDEV_CERT_POPULATION_FAILED)? .copy_from_slice(&cmd.cert[..cert_size]); 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/runtime/src/recovery_flow.rs
runtime/src/recovery_flow.rs
/*++ Licensed under the Apache-2.0 license. File Name: recovery_flow.rs Abstract: File contains the implementation of the recovery flow for MCU firmware and SoC manifest. --*/ use crate::{ activate_firmware::MCI_TOP_REG_RESET_REASON_OFFSET, authorize_and_stash::AuthorizeAndStashCmd, drivers::{McuFwStatus, McuResetReason}, Drivers, SetAuthManifestCmd, IMAGE_AUTHORIZED, }; use caliptra_auth_man_types::AuthorizationManifest; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::{ cprintln, mailbox_api::{AuthorizeAndStashReq, ImageHashSource}, }; use caliptra_drivers::{printer::HexBytes, AesDmaMode, DmaMmio, DmaRecovery}; use caliptra_kat::{CaliptraError, CaliptraResult}; use ureg::MmioMut; use zerocopy::IntoBytes; const FW_BOOT_UPD_RESET: u32 = 0b1 << 1; pub enum RecoveryFlow {} impl RecoveryFlow { /// Load the SoC Manifest and MCU firwmare #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub(crate) fn recovery_flow(drivers: &mut Drivers) -> CaliptraResult<()> { const SOC_MANIFEST_INDEX: u32 = 1; const MCU_FIRMWARE_INDEX: u32 = 2; // use different scopes since we need to borrow drivers mutably and immutably let mut buffer = [0; size_of::<AuthorizationManifest>() / 4]; let source = { let dma = &drivers.dma; let dma_recovery = DmaRecovery::new( drivers.soc_ifc.recovery_interface_base_addr().into(), drivers.soc_ifc.caliptra_base_axi_addr().into(), drivers.soc_ifc.mci_base_addr().into(), dma, ); // need to make sure the device status is correct to load the next image dma_recovery.set_device_status( DmaRecovery::DEVICE_STATUS_READY_TO_ACCEPT_RECOVERY_IMAGE_VALUE, )?; // download SoC manifest dma_recovery.download_image_to_caliptra(SOC_MANIFEST_INDEX, &mut buffer)?; buffer.as_bytes() }; SetAuthManifestCmd::set_auth_manifest(drivers, source, false)?; let digest = { let dma = &drivers.dma; let dma_recovery = DmaRecovery::new( drivers.soc_ifc.recovery_interface_base_addr().into(), drivers.soc_ifc.caliptra_base_axi_addr().into(), drivers.soc_ifc.mci_base_addr().into(), dma, ); // Reset the RECOVERY_CTRL register Activate Recovery Image field by writing 0x1. dma_recovery.reset_recovery_ctrl_activate_rec_img()?; // need to make sure the device status is correct to load the next image dma_recovery.set_device_status( DmaRecovery::DEVICE_STATUS_READY_TO_ACCEPT_RECOVERY_IMAGE_VALUE, )?; cprintln!("[rt] Uploading MCU firmware"); let mcu_size_bytes = dma_recovery.download_image_to_mcu(MCU_FIRMWARE_INDEX, AesDmaMode::None)?; cprintln!("[rt] Calculating MCU digest"); dma_recovery.sha384_mcu_sram( &mut drivers.sha2_512_384_acc, 0, mcu_size_bytes, AesDmaMode::None, )? }; let digest: [u8; 48] = digest.into(); cprintln!("[rt] Verifying MCU digest: {}", HexBytes(&digest)); // verify the digest let auth_and_stash_req = AuthorizeAndStashReq { fw_id: [2, 0, 0, 0], measurement: digest, source: ImageHashSource::InRequest.into(), ..Default::default() }; let auth_result = AuthorizeAndStashCmd::authorize_and_stash(drivers, &auth_and_stash_req)?; { let mci_base_addr = drivers.soc_ifc.mci_base_addr().into(); let dma = &drivers.dma; let dma_recovery = DmaRecovery::new( drivers.soc_ifc.recovery_interface_base_addr().into(), drivers.soc_ifc.caliptra_base_axi_addr().into(), mci_base_addr, dma, ); if auth_result != IMAGE_AUTHORIZED { dma_recovery.set_recovery_status( DmaRecovery::RECOVERY_STATUS_IMAGE_AUTHENTICATION_ERROR, 0, )?; return Err(CaliptraError::IMAGE_VERIFIER_ERR_RUNTIME_DIGEST_MISMATCH); } // Caliptra sets RESET_REASON.FW_BOOT_UPD_RESET let mmio = &DmaMmio::new(mci_base_addr, dma); unsafe { mmio.write_volatile( MCI_TOP_REG_RESET_REASON_OFFSET as *mut u32, FW_BOOT_UPD_RESET, ) }; cprintln!("[rt] Setting MCU firmware ready"); // notify MCU that it can boot its firmware drivers.soc_ifc.set_mcu_firmware_ready(); cprintln!( "[rt] Setting MCU firmware ready: {:08x}{:08x}{:08x}{:08x}", drivers.soc_ifc.fw_ctrl(0), drivers.soc_ifc.fw_ctrl(1), drivers.soc_ifc.fw_ctrl(2), drivers.soc_ifc.fw_ctrl(3) ); // we're done with recovery dma_recovery.set_recovery_status(DmaRecovery::RECOVERY_STATUS_SUCCESSFUL, 0)?; } // notify MCU that it can boot its firmware drivers.persistent_data.get_mut().fw.mcu_firmware_loaded = McuFwStatus::Loaded.into(); Drivers::request_mcu_reset(drivers, McuResetReason::FwBoot); Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/reallocate_dpe_context_limits.rs
runtime/src/reallocate_dpe_context_limits.rs
/*++ Licensed under the Apache-2.0 license. File Name: reallocate_dpe_context_limits.rs Abstract: File contains mailbox command implementation for reallocating DPE contexts between PL0 and PL1. --*/ use crate::mutrefbytes; use crate::Drivers; use crate::{ PauserPrivileges, PL0_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD, PL0_DPE_ACTIVE_CONTEXT_THRESHOLD_MIN, PL1_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD, }; use caliptra_common::mailbox_api::{ MailboxRespHeader, ReallocateDpeContextLimitsReq, ReallocateDpeContextLimitsResp, }; use caliptra_drivers::{CaliptraError, CaliptraResult}; use zerocopy::FromBytes; pub struct ReallocateDpeContextLimitsCmd; impl ReallocateDpeContextLimitsCmd { #[inline(never)] pub(crate) fn execute( drivers: &mut Drivers, cmd_bytes: &[u8], resp: &mut [u8], ) -> CaliptraResult<usize> { let cmd = ReallocateDpeContextLimitsReq::ref_from_bytes(cmd_bytes) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; const TOTAL_DPE_CONTEXT_LIMIT: usize = PL0_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD + PL1_DPE_ACTIVE_CONTEXT_DEFAULT_THRESHOLD; let pl1_context_limit = TOTAL_DPE_CONTEXT_LIMIT as u32 - cmd.pl0_context_limit; // Only allowed by PL0 if drivers.caller_privilege_level() != PauserPrivileges::PL0 { Err(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL)? } // Error checking for distribution limits if cmd.pl0_context_limit < PL0_DPE_ACTIVE_CONTEXT_THRESHOLD_MIN as u32 { Err(CaliptraError::RUNTIME_REALLOCATE_DPE_CONTEXTS_PL0_LESS_THAN_MIN)? } if cmd.pl0_context_limit > TOTAL_DPE_CONTEXT_LIMIT as u32 { Err(CaliptraError::RUNTIME_REALLOCATE_DPE_CONTEXTS_PL0_GREATER_THAN_MAX)? } // Error checking against used contexts let (used_pl0_dpe_context_count, used_pl1_dpe_context_count) = drivers.dpe_get_used_context_counts()?; if cmd.pl0_context_limit < used_pl0_dpe_context_count as u32 { Err(CaliptraError::RUNTIME_REALLOCATE_DPE_CONTEXTS_PL0_LESS_THAN_USED)? } if pl1_context_limit < used_pl1_dpe_context_count as u32 { Err(CaliptraError::RUNTIME_REALLOCATE_DPE_CONTEXTS_PL1_LESS_THAN_USED)? } // Update limits in persistent data now that error checking has passed drivers.persistent_data.get_mut().fw.dpe.pl0_context_limit = cmd.pl0_context_limit as u8; drivers.persistent_data.get_mut().fw.dpe.pl1_context_limit = pl1_context_limit as u8; // Populate response let resp = mutrefbytes::<ReallocateDpeContextLimitsResp>(resp)?; resp.hdr = MailboxRespHeader::default(); resp.new_pl0_context_limit = drivers.persistent_data.get().fw.dpe.pl0_context_limit as u32; resp.new_pl1_context_limit = drivers.persistent_data.get().fw.dpe.pl1_context_limit as u32; Ok(core::mem::size_of::<ReallocateDpeContextLimitsResp>()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/runtime/src/dpe_platform.rs
runtime/src/dpe_platform.rs
/*++ Licensed under the Apache-2.0 license. File Name: dpe_platform.rs Abstract: File contains DpePlatform implementation. --*/ use core::cmp::min; use arrayvec::ArrayVec; use caliptra_drivers::cprintln; use caliptra_x509::{NotAfter, NotBefore}; use crypto::Digest; use dpe::x509::{CertWriter, DirectoryString, Name}; use platform::{ CertValidity, OtherName, Platform, PlatformError, SignerIdentifier, SubjectAltName, Ueid, MAX_CHUNK_SIZE, MAX_ISSUER_NAME_SIZE, MAX_KEY_IDENTIFIER_SIZE, }; use crate::{subject_alt_name::AddSubjectAltNameCmd, MAX_ECC_CERT_CHAIN_SIZE}; pub struct DpePlatform<'a> { auto_init_locality: u32, hashed_rt_pub_key: &'a Digest, cert_chain: &'a ArrayVec<u8, MAX_ECC_CERT_CHAIN_SIZE>, not_before: &'a NotBefore, not_after: &'a NotAfter, dmtf_device_info: Option<&'a [u8]>, ueid: Option<&'a [u8; 17]>, } pub const VENDOR_ID: u32 = u32::from_be_bytes(*b"CTRA"); pub const VENDOR_SKU: u32 = u32::from_be_bytes(*b"CTRA"); impl<'a> DpePlatform<'a> { pub fn new( auto_init_locality: u32, hashed_rt_pub_key: &'a Digest, cert_chain: &'a ArrayVec<u8, 4096>, not_before: &'a NotBefore, not_after: &'a NotAfter, dmtf_device_info: Option<&'a [u8]>, ueid: Option<&'a [u8; 17]>, ) -> Self { Self { auto_init_locality, hashed_rt_pub_key, cert_chain, not_before, not_after, dmtf_device_info, ueid, } } } impl Platform for DpePlatform<'_> { fn get_certificate_chain( &mut self, offset: u32, size: u32, out: &mut [u8; MAX_CHUNK_SIZE], ) -> Result<u32, PlatformError> { let len = self.cert_chain.len() as u32; if offset >= len { return Err(PlatformError::CertificateChainError); } let cert_chunk_range_end = min(offset + size, len); let bytes_written = cert_chunk_range_end - offset; if bytes_written as usize > MAX_CHUNK_SIZE { return Err(PlatformError::CertificateChainError); } out.get_mut(..bytes_written as usize) .ok_or(PlatformError::CertificateChainError)? .copy_from_slice( self.cert_chain .get(offset as usize..cert_chunk_range_end as usize) .ok_or(PlatformError::CertificateChainError)?, ); Ok(bytes_written) } fn get_vendor_id(&mut self) -> Result<u32, PlatformError> { Ok(VENDOR_ID) } fn get_vendor_sku(&mut self) -> Result<u32, PlatformError> { Ok(VENDOR_SKU) } fn get_auto_init_locality(&mut self) -> Result<u32, PlatformError> { Ok(self.auto_init_locality) } fn get_issuer_name( &mut self, out: &mut [u8; MAX_ISSUER_NAME_SIZE], ) -> Result<usize, PlatformError> { const CALIPTRA_CN: &[u8] = b"Caliptra 2.1 Ecc384 Rt Alias"; let mut issuer_writer = CertWriter::new(out, true); // Caliptra RDN SerialNumber field is always a Sha256 hash let mut serial = [0u8; 64]; Digest::write_hex_str(self.hashed_rt_pub_key, &mut serial) .map_err(|e| PlatformError::IssuerNameError(e.get_error_detail().unwrap_or(0)))?; let name = Name { cn: DirectoryString::Utf8String(CALIPTRA_CN), serial: DirectoryString::PrintableString(&serial), }; let issuer_len = issuer_writer .encode_rdn(&name) .map_err(|e| PlatformError::IssuerNameError(e.get_error_detail().unwrap_or(0)))?; Ok(issuer_len) } /// See X509::subj_key_id in fmc/src/flow/x509.rs for code that generates the /// SubjectKeyIdentifier extension in the RT alias certificate. fn get_signer_identifier(&mut self) -> Result<SignerIdentifier, PlatformError> { let mut ski = [0u8; MAX_KEY_IDENTIFIER_SIZE]; let hashed_rt_pub_key = self.hashed_rt_pub_key.bytes(); if hashed_rt_pub_key.len() < MAX_KEY_IDENTIFIER_SIZE { return Err(PlatformError::SubjectKeyIdentifierError(0)); } ski.copy_from_slice(&hashed_rt_pub_key[..MAX_KEY_IDENTIFIER_SIZE]); let mut ski_vec = ArrayVec::new(); ski_vec .try_extend_from_slice(&ski) .map_err(|_| PlatformError::SubjectKeyIdentifierError(0))?; Ok(SignerIdentifier::SubjectKeyIdentifier(ski_vec)) } fn get_issuer_key_identifier( &mut self, out: &mut [u8; MAX_KEY_IDENTIFIER_SIZE], ) -> Result<(), PlatformError> { let hashed_rt_pub_key = self.hashed_rt_pub_key.bytes(); if hashed_rt_pub_key.len() < MAX_KEY_IDENTIFIER_SIZE { return Err(PlatformError::IssuerKeyIdentifierError(0)); } out.copy_from_slice(&hashed_rt_pub_key[..MAX_KEY_IDENTIFIER_SIZE]); Ok(()) } fn write_str(&mut self, str: &str) -> Result<(), PlatformError> { cprintln!("{}", str); Ok(()) } fn get_cert_validity(&mut self) -> Result<CertValidity, PlatformError> { let mut not_before = ArrayVec::new(); not_before .try_extend_from_slice(&self.not_before.value) .map_err(|_| PlatformError::CertValidityError(0))?; let mut not_after = ArrayVec::new(); not_after .try_extend_from_slice(&self.not_after.value) .map_err(|_| PlatformError::CertValidityError(0))?; Ok(CertValidity { not_before, not_after, }) } fn get_subject_alternative_name(&mut self) -> Result<SubjectAltName, PlatformError> { match &self.dmtf_device_info { None => Err(PlatformError::NotImplemented), Some(dmtf_device_info) => { let mut other_name = ArrayVec::new(); other_name .try_extend_from_slice(dmtf_device_info) .map_err(|_| PlatformError::SubjectAlternativeNameError(0))?; Ok(SubjectAltName::OtherName(OtherName { oid: AddSubjectAltNameCmd::DMTF_OID, other_name, })) } } } fn get_ueid(&mut self) -> Result<Ueid, PlatformError> { let buf = *self.ueid.ok_or(PlatformError::MissingUeidError)?; let buf_size = buf.len() as u32; let mut ueid = Ueid::default(); ueid.buf[..buf_size as usize].clone_from_slice(&buf); ueid.buf_size = buf_size; Ok(ueid) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false