From ec111ab50176f06f824c5771e2b6f49eee28766c Mon Sep 17 00:00:00 2001 From: Carl Lundin Date: Thu, 10 Oct 2024 16:43:04 -0700 Subject: [PATCH] Update zerocopy from 0.6.6 to 0.8.8. This PR does not optimize out a large portion of copies. Ideally it will be done in follow up PRs. There are portions of code that are slightly modified to keep panics out of the final binary. --- Cargo.lock | 15 +- Cargo.toml | 2 +- FROZEN_IMAGES.sha384sum | 4 +- api/src/mailbox.rs | 190 +++++++++--------- api/src/soc_mgr.rs | 11 +- auth-manifest/app/src/main.rs | 2 +- auth-manifest/gen/src/generator.rs | 2 +- auth-manifest/types/src/lib.rs | 16 +- builder/src/lib.rs | 2 +- dpe | 2 +- drivers/src/array.rs | 22 +- drivers/src/bounded_address.rs | 52 +++-- drivers/src/ecc384.rs | 30 ++- drivers/src/fuse_bank.rs | 2 +- drivers/src/fuse_log.rs | 4 +- drivers/src/hand_off.rs | 6 +- drivers/src/lms.rs | 2 +- drivers/src/mailbox.rs | 26 +-- drivers/src/pcr_log.rs | 6 +- drivers/src/pcr_reset.rs | 4 +- drivers/src/persistent.rs | 10 +- drivers/test-fw/src/bin/doe_tests.rs | 2 +- .../src/bin/mailbox_driver_responder.rs | 10 +- .../test-fw/src/bin/trng_driver_responder.rs | 2 +- drivers/test-fw/src/lib.rs | 4 +- .../tests/drivers_integration_tests/main.rs | 6 +- fmc/src/flow/pcr.rs | 4 +- fmc/src/flow/tci.rs | 2 +- .../fmc_integration_tests/test_rtalias.rs | 10 +- hw-model/src/lib.rs | 40 ++-- image/crypto/src/lib.rs | 26 +-- image/fake-keys/src/lib.rs | 2 +- image/gen/src/generator.rs | 2 +- image/serde/src/lib.rs | 2 +- image/types/src/lib.rs | 56 ++++-- lms-types/src/lib.rs | 90 +++++---- rom/dev/src/flow/cold_reset/fw_processor.rs | 30 ++- rom/dev/src/flow/fake.rs | 2 +- rom/dev/src/flow/update_reset.rs | 6 +- rom/dev/src/fuse.rs | 4 +- rom/dev/src/pcr.rs | 4 +- .../test_capabilities.rs | 4 +- .../test_fmcalias_derivation.rs | 88 ++++---- .../test_idevid_derivation.rs | 4 +- .../test_image_validation.rs | 2 +- .../test_mailbox_errors.rs | 2 +- .../test_rom_integrity.rs | 15 +- .../test_update_reset.rs | 14 +- .../rom_integration_tests/test_version.rs | 4 +- .../rom_integration_tests/test_warm_reset.rs | 2 +- .../tests_get_idev_csr.rs | 4 +- rom/dev/tools/test-fmc/src/main.rs | 2 +- runtime/src/authorize_and_stash.rs | 4 +- runtime/src/certify_key_extended.rs | 10 +- runtime/src/dice.rs | 4 +- runtime/src/dpe_crypto.rs | 2 +- runtime/src/dpe_platform.rs | 2 +- runtime/src/drivers.rs | 2 +- runtime/src/fips.rs | 2 +- runtime/src/get_idev_csr.rs | 58 +++--- runtime/src/hmac.rs | 2 +- runtime/src/invoke_dpe.rs | 15 +- runtime/src/mailbox.rs | 13 +- runtime/src/packet.rs | 7 +- runtime/src/pcr.rs | 12 +- runtime/src/populate_idev.rs | 4 +- runtime/src/set_auth_manifest.rs | 14 +- runtime/src/stash_measurement.rs | 6 +- runtime/src/subject_alt_name.rs | 4 +- runtime/src/tagging.rs | 8 +- runtime/src/verify.rs | 22 +- runtime/test-fw/src/mbox_responder.rs | 16 +- .../test-fw/src/mock_rt_test_interactive.rs | 2 +- .../tests/runtime_integration_tests/common.rs | 38 ++-- .../test_authorize_and_stash.rs | 25 +-- .../runtime_integration_tests/test_boot.rs | 2 +- .../test_certify_key_extended.rs | 17 +- .../runtime_integration_tests/test_certs.rs | 18 +- .../runtime_integration_tests/test_disable.rs | 18 +- .../runtime_integration_tests/test_ecdsa.rs | 9 +- .../runtime_integration_tests/test_fips.rs | 6 +- .../test_get_idev_csr.rs | 4 +- .../runtime_integration_tests/test_info.rs | 13 +- .../test_invoke_dpe.rs | 24 ++- .../runtime_integration_tests/test_lms.rs | 17 +- .../runtime_integration_tests/test_mailbox.rs | 2 +- .../test_pauser_privilege_levels.rs | 32 +-- .../runtime_integration_tests/test_pcr.rs | 8 +- .../test_populate_idev.rs | 4 +- .../test_set_auth_manifest.rs | 2 +- .../test_stash_measurement.rs | 6 +- .../runtime_integration_tests/test_tagging.rs | 10 +- .../test_update_reset.rs | 14 +- .../test_warm_reset.rs | 2 +- sw-emulator/lib/periph/src/hash_sha512.rs | 4 +- sw-emulator/lib/periph/src/hmac_sha384.rs | 8 +- test/src/derive.rs | 8 +- .../fake_collateral_boot_test.rs | 6 +- .../caliptra_integration_tests/jtag_test.rs | 2 +- .../caliptra_integration_tests/smoke_test.rs | 2 +- .../caliptra_integration_tests/warm_reset.rs | 2 +- test/tests/fips_test_suite/common.rs | 43 ++-- test/tests/fips_test_suite/fw_load.rs | 2 +- .../fips_test_suite/security_parameters.rs | 4 +- test/tests/fips_test_suite/self_tests.rs | 2 +- test/tests/fips_test_suite/services.rs | 20 +- 106 files changed, 763 insertions(+), 675 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e0303892f0..96c8367ee7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -202,12 +202,6 @@ version = "3.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b1ce199063694f33ffb7dd4e0ee620741495c32833cde5aa08f02a0bf96f0c8" -[[package]] -name = "byteorder" -version = "1.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" - [[package]] name = "caliptra-api" version = "0.1.0" @@ -2951,19 +2945,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.6.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "854e949ac82d619ee9a14c66a1b674ac730422372ccb759ce0c39cabcf2bf8e6" +checksum = "5a4e33e6dce36f2adba29746927f8e848ba70989fdb61c772773bbdda8b5d6a7" dependencies = [ - "byteorder", "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.6.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "125139de3f6b9d625c39e2efdd73d41bdac468ccd556556440e322be0e1bbd91" +checksum = "3cd137b4cc21bde6ecce3bbbb3350130872cda0be2c6888874279ea76e17d4c1" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index ad3a1b5fa4..d5fcf4509d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -183,7 +183,7 @@ ureg-schema = { path = "ureg/lib/schema" } ureg-systemrdl = { path = "ureg/lib/systemrdl" } wycheproof = "0.5.1" x509-parser = "0.15.0" -zerocopy = "0.6.6" +zerocopy = { version = "0.8.8", features = ["derive"] } serial_test = "2.0.0" nix = "0.26.2" libc = "0.2" diff --git a/FROZEN_IMAGES.sha384sum b/FROZEN_IMAGES.sha384sum index 149f78dccc..00a4725f92 100644 --- a/FROZEN_IMAGES.sha384sum +++ b/FROZEN_IMAGES.sha384sum @@ -1,3 +1,3 @@ # WARNING: Do not update this file without the approval of the Caliptra TAC -df4a72ee4a88d12d7216f8d23c6567b479694dec959e7332d69094098d312ea2dbf35de1117db156635ad41a78bf3c14 caliptra-rom-no-log.bin -02db1204eea812bee28904ce877ec7604746169fa7bfa82471cf10af239852466c1a16b2d5b3b9ad26b4ccfe2ca0a1b5 caliptra-rom-with-log.bin +a0c760bba301d669c7d7ce3f60d9451d2b4ed9f3d9b237a6eaabd6b7d8a7172573d7664c4d1dfc3f519d0babeae702de caliptra-rom-no-log.bin +92c38d0f250cb2eee89536ab7b9b81e356c0197b365da2ef04aef946347db46690ea51dad0447cf3acf0a9fc235f7951 caliptra-rom-with-log.bin diff --git a/api/src/mailbox.rs b/api/src/mailbox.rs index a8ba102251..0a0906fbbd 100644 --- a/api/src/mailbox.rs +++ b/api/src/mailbox.rs @@ -3,7 +3,7 @@ use bitflags::bitflags; use caliptra_error::{CaliptraError, CaliptraResult}; use core::mem::size_of; -use zerocopy::{AsBytes, FromBytes, LayoutVerified}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Ref}; use crate::CaliptraApiError; use caliptra_registers::mbox; @@ -70,12 +70,12 @@ impl From for u32 { /// A trait implemented by request types. Describes the associated command ID /// and response type. -pub trait Request: AsBytes + FromBytes { +pub trait Request: IntoBytes + FromBytes + Immutable + KnownLayout { const ID: CommandId; type Resp: Response; } -pub trait Response: AsBytes + FromBytes +pub trait Response: IntoBytes + FromBytes where Self: Sized, { @@ -86,31 +86,29 @@ where fn populate_chksum(&mut self) { // Note: This will panic if sizeof::() < 4 - populate_checksum(self.as_bytes_mut()); + populate_checksum(self.as_mut_bytes()); } } #[repr(C)] -#[derive(Debug, AsBytes, Default, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, Default, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct MailboxRespHeaderVarSize { pub hdr: MailboxRespHeader, pub data_len: u32, } -pub trait ResponseVarSize: AsBytes + FromBytes { +pub trait ResponseVarSize: IntoBytes + FromBytes + Immutable + KnownLayout { fn data(&self) -> CaliptraResult<&[u8]> { // Will panic if sizeof() is smaller than MailboxRespHeaderVarSize // or Self doesn't have compatible alignment with - // MailboxRespHeaderVarSize (should be impossible if MailboxRespHeaderVarSize is the first field) - let (hdr, data) = - LayoutVerified::<_, MailboxRespHeaderVarSize>::new_from_prefix(self.as_bytes()) - .ok_or(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE)?; + // MailboxRespHeaderVarSize (should be impossible if MailboxRespHeaderVarSiz is the first field) .. + let (hdr, data) = MailboxRespHeaderVarSize::ref_from_prefix(self.as_bytes()) + .map_err(|_| CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE)?; data.get(..hdr.data_len as usize) .ok_or(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE) } fn partial_len(&self) -> CaliptraResult { - let (hdr, _) = - LayoutVerified::<_, MailboxRespHeaderVarSize>::new_from_prefix(self.as_bytes()) - .ok_or(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE)?; + let (hdr, _) = MailboxRespHeaderVarSize::ref_from_prefix(self.as_bytes()) + .map_err(|_| CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE)?; Ok(size_of::() + hdr.data_len as usize) } fn as_bytes_partial(&self) -> CaliptraResult<&[u8]> { @@ -120,7 +118,7 @@ pub trait ResponseVarSize: AsBytes + FromBytes { } fn as_bytes_partial_mut(&mut self) -> CaliptraResult<&mut [u8]> { let partial_len = self.partial_len()?; - self.as_bytes_mut() + self.as_mut_bytes() .get_mut(..partial_len) .ok_or(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE) } @@ -179,24 +177,24 @@ impl MailboxResp { } } - pub fn as_bytes_mut(&mut self) -> CaliptraResult<&mut [u8]> { + pub fn as_mut_bytes(&mut self) -> CaliptraResult<&mut [u8]> { match self { - MailboxResp::Header(resp) => Ok(resp.as_bytes_mut()), + MailboxResp::Header(resp) => Ok(resp.as_mut_bytes()), MailboxResp::GetIdevCert(resp) => resp.as_bytes_partial_mut(), - MailboxResp::GetIdevInfo(resp) => Ok(resp.as_bytes_mut()), + MailboxResp::GetIdevInfo(resp) => Ok(resp.as_mut_bytes()), MailboxResp::GetLdevCert(resp) => resp.as_bytes_partial_mut(), - MailboxResp::StashMeasurement(resp) => Ok(resp.as_bytes_mut()), + MailboxResp::StashMeasurement(resp) => Ok(resp.as_mut_bytes()), MailboxResp::InvokeDpeCommand(resp) => resp.as_bytes_partial_mut(), - MailboxResp::FipsVersion(resp) => Ok(resp.as_bytes_mut()), - MailboxResp::FwInfo(resp) => Ok(resp.as_bytes_mut()), - MailboxResp::Capabilities(resp) => Ok(resp.as_bytes_mut()), - MailboxResp::GetTaggedTci(resp) => Ok(resp.as_bytes_mut()), + MailboxResp::FipsVersion(resp) => Ok(resp.as_mut_bytes()), + MailboxResp::FwInfo(resp) => Ok(resp.as_mut_bytes()), + MailboxResp::Capabilities(resp) => Ok(resp.as_mut_bytes()), + MailboxResp::GetTaggedTci(resp) => Ok(resp.as_mut_bytes()), MailboxResp::GetFmcAliasCert(resp) => resp.as_bytes_partial_mut(), MailboxResp::GetRtAliasCert(resp) => resp.as_bytes_partial_mut(), - MailboxResp::QuotePcrs(resp) => Ok(resp.as_bytes_mut()), - MailboxResp::CertifyKeyExtended(resp) => Ok(resp.as_bytes_mut()), - MailboxResp::AuthorizeAndStash(resp) => Ok(resp.as_bytes_mut()), - MailboxResp::GetIdevCsr(resp) => Ok(resp.as_bytes_mut()), + MailboxResp::QuotePcrs(resp) => Ok(resp.as_mut_bytes()), + MailboxResp::CertifyKeyExtended(resp) => Ok(resp.as_mut_bytes()), + MailboxResp::AuthorizeAndStash(resp) => Ok(resp.as_mut_bytes()), + MailboxResp::GetIdevCsr(resp) => Ok(resp.as_mut_bytes()), } } @@ -210,16 +208,14 @@ impl MailboxResp { } let checksum = crate::checksum::calc_checksum(0, &resp_bytes[size_of::()..]); - let mut_resp_bytes = self.as_bytes_mut()?; + let mut_resp_bytes = self.as_mut_bytes()?; if size_of::() > mut_resp_bytes.len() { return Err(CaliptraError::RUNTIME_MAILBOX_API_RESPONSE_DATA_LEN_TOO_LARGE); } - // cast as header struct - let hdr: &mut MailboxRespHeader = LayoutVerified::<&mut [u8], MailboxRespHeader>::new( + let hdr: &mut MailboxRespHeader = MailboxRespHeader::mut_from_bytes( &mut mut_resp_bytes[..size_of::()], ) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)? - .into_mut(); + .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; // Set the chksum field hdr.chksum = checksum; @@ -285,28 +281,28 @@ impl MailboxReq { } } - pub fn as_bytes_mut(&mut self) -> CaliptraResult<&mut [u8]> { + pub fn as_mut_bytes(&mut self) -> CaliptraResult<&mut [u8]> { match self { - MailboxReq::EcdsaVerify(req) => Ok(req.as_bytes_mut()), - MailboxReq::LmsVerify(req) => Ok(req.as_bytes_mut()), - MailboxReq::GetLdevCert(req) => Ok(req.as_bytes_mut()), - MailboxReq::StashMeasurement(req) => Ok(req.as_bytes_mut()), + MailboxReq::EcdsaVerify(req) => Ok(req.as_mut_bytes()), + MailboxReq::LmsVerify(req) => Ok(req.as_mut_bytes()), + MailboxReq::GetLdevCert(req) => Ok(req.as_mut_bytes()), + MailboxReq::StashMeasurement(req) => Ok(req.as_mut_bytes()), MailboxReq::InvokeDpeCommand(req) => req.as_bytes_partial_mut(), - MailboxReq::FipsVersion(req) => Ok(req.as_bytes_mut()), - MailboxReq::FwInfo(req) => Ok(req.as_bytes_mut()), + MailboxReq::FipsVersion(req) => Ok(req.as_mut_bytes()), + MailboxReq::FwInfo(req) => Ok(req.as_mut_bytes()), MailboxReq::PopulateIdevCert(req) => req.as_bytes_partial_mut(), MailboxReq::GetIdevCert(req) => req.as_bytes_partial_mut(), - MailboxReq::TagTci(req) => Ok(req.as_bytes_mut()), - MailboxReq::GetTaggedTci(req) => Ok(req.as_bytes_mut()), - MailboxReq::GetFmcAliasCert(req) => Ok(req.as_bytes_mut()), - MailboxReq::GetRtAliasCert(req) => Ok(req.as_bytes_mut()), - MailboxReq::IncrementPcrResetCounter(req) => Ok(req.as_bytes_mut()), - MailboxReq::QuotePcrs(req) => Ok(req.as_bytes_mut()), - MailboxReq::ExtendPcr(req) => Ok(req.as_bytes_mut()), + MailboxReq::TagTci(req) => Ok(req.as_mut_bytes()), + MailboxReq::GetTaggedTci(req) => Ok(req.as_mut_bytes()), + MailboxReq::GetFmcAliasCert(req) => Ok(req.as_mut_bytes()), + MailboxReq::GetRtAliasCert(req) => Ok(req.as_mut_bytes()), + MailboxReq::IncrementPcrResetCounter(req) => Ok(req.as_mut_bytes()), + MailboxReq::QuotePcrs(req) => Ok(req.as_mut_bytes()), + MailboxReq::ExtendPcr(req) => Ok(req.as_mut_bytes()), MailboxReq::AddSubjectAltName(req) => req.as_bytes_partial_mut(), - MailboxReq::CertifyKeyExtended(req) => Ok(req.as_bytes_mut()), - MailboxReq::SetAuthManifest(req) => Ok(req.as_bytes_mut()), - MailboxReq::AuthorizeAndStash(req) => Ok(req.as_bytes_mut()), + MailboxReq::CertifyKeyExtended(req) => Ok(req.as_mut_bytes()), + MailboxReq::SetAuthManifest(req) => Ok(req.as_mut_bytes()), + MailboxReq::AuthorizeAndStash(req) => Ok(req.as_mut_bytes()), } } @@ -343,12 +339,10 @@ impl MailboxReq { &self.as_bytes()?[size_of::()..], ); - // cast as header struct - let hdr: &mut MailboxReqHeader = LayoutVerified::<&mut [u8], MailboxReqHeader>::new( - &mut self.as_bytes_mut()?[..size_of::()], + let hdr: &mut MailboxReqHeader = MailboxReqHeader::mut_from_bytes( + &mut self.as_mut_bytes()?[..size_of::()], ) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)? - .into_mut(); + .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; // Set the chksum field hdr.chksum = checksum; @@ -359,13 +353,13 @@ impl MailboxReq { // HEADER #[repr(C)] -#[derive(Default, Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Default, Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct MailboxReqHeader { pub chksum: u32, } #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, KnownLayout, Immutable, PartialEq, Eq)] pub struct MailboxRespHeader { pub chksum: u32, pub fips_status: u32, @@ -387,7 +381,7 @@ impl Default for MailboxRespHeader { // GET_IDEV_CERT #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetIdevCertReq { pub hdr: MailboxReqHeader, pub tbs_size: u32, @@ -411,7 +405,7 @@ impl GetIdevCertReq { return Err(CaliptraError::RUNTIME_MAILBOX_API_REQUEST_DATA_LEN_TOO_LARGE); } let unused_byte_count = Self::DATA_MAX_SIZE - self.tbs_size as usize; - Ok(&mut self.as_bytes_mut()[..size_of::() - unused_byte_count]) + Ok(&mut self.as_mut_bytes()[..size_of::() - unused_byte_count]) } } impl Default for GetIdevCertReq { @@ -427,7 +421,7 @@ impl Default for GetIdevCertReq { } #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetIdevCertResp { pub hdr: MailboxRespHeader, pub cert_size: u32, @@ -451,7 +445,7 @@ impl Default for GetIdevCertResp { // GET_IDEV_INFO // No command-specific input args #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetIdevInfoResp { pub hdr: MailboxRespHeader, pub idev_pub_x: [u8; 48], @@ -460,7 +454,7 @@ pub struct GetIdevInfoResp { // GET_LDEV_CERT #[repr(C)] -#[derive(Default, Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Default, Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetLdevCertReq { header: MailboxReqHeader, } @@ -471,7 +465,7 @@ impl Request for GetLdevCertReq { } #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetLdevCertResp { pub hdr: MailboxRespHeader, pub data_size: u32, @@ -494,7 +488,7 @@ impl Default for GetLdevCertResp { // GET_RT_ALIAS_CERT #[repr(C)] -#[derive(Default, Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Default, Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetRtAliasCertReq { header: MailboxReqHeader, } @@ -504,7 +498,7 @@ impl Request for GetRtAliasCertReq { } #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetRtAliasCertResp { pub hdr: MailboxRespHeader, pub data_size: u32, @@ -531,7 +525,7 @@ impl Default for GetRtAliasCertResp { // ECDSA384_SIGNATURE_VERIFY #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct EcdsaVerifyReq { pub hdr: MailboxReqHeader, pub pub_key_x: [u8; 48], @@ -547,7 +541,7 @@ impl Request for EcdsaVerifyReq { // LMS_SIGNATURE_VERIFY #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct LmsVerifyReq { pub hdr: MailboxReqHeader, pub pub_key_tree_type: u32, @@ -567,7 +561,7 @@ impl Request for LmsVerifyReq { // STASH_MEASUREMENT #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct StashMeasurementReq { pub hdr: MailboxReqHeader, pub metadata: [u8; 4], @@ -592,7 +586,7 @@ impl Request for StashMeasurementReq { } #[repr(C)] -#[derive(Debug, Default, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Default, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct StashMeasurementResp { pub hdr: MailboxRespHeader, pub dpe_result: u32, @@ -605,7 +599,7 @@ impl Response for StashMeasurementResp {} // CERTIFY_KEY_EXTENDED #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct CertifyKeyExtendedReq { pub hdr: MailboxReqHeader, pub flags: CertifyKeyExtendedFlags, @@ -620,7 +614,7 @@ impl Request for CertifyKeyExtendedReq { } #[repr(C)] -#[derive(Debug, PartialEq, Eq, FromBytes, AsBytes)] +#[derive(Debug, PartialEq, Eq, FromBytes, Immutable, KnownLayout, IntoBytes)] pub struct CertifyKeyExtendedFlags(pub u32); bitflags! { @@ -630,7 +624,7 @@ bitflags! { } #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct CertifyKeyExtendedResp { pub hdr: MailboxRespHeader, pub certify_key_resp: [u8; CertifyKeyExtendedResp::CERTIFY_KEY_RESP_SIZE], @@ -642,7 +636,7 @@ impl Response for CertifyKeyExtendedResp {} // INVOKE_DPE_COMMAND #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct InvokeDpeReq { pub hdr: MailboxReqHeader, pub data_size: u32, @@ -665,7 +659,7 @@ impl InvokeDpeReq { return Err(CaliptraError::RUNTIME_MAILBOX_API_REQUEST_DATA_LEN_TOO_LARGE); } let unused_byte_count = Self::DATA_MAX_SIZE - self.data_size as usize; - Ok(&mut self.as_bytes_mut()[..size_of::() - unused_byte_count]) + Ok(&mut self.as_mut_bytes()[..size_of::() - unused_byte_count]) } } impl Default for InvokeDpeReq { @@ -684,7 +678,7 @@ impl Request for InvokeDpeReq { // EXTEND_PCR #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct ExtendPcrReq { pub hdr: MailboxReqHeader, pub pcr_idx: u32, @@ -699,7 +693,7 @@ impl Request for ExtendPcrReq { // No command-specific output args #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct InvokeDpeResp { pub hdr: MailboxRespHeader, pub data_size: u32, @@ -722,7 +716,7 @@ impl Default for InvokeDpeResp { // GET_FMC_ALIAS_CERT #[repr(C)] -#[derive(Debug, Default, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Default, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetFmcAliasCertReq { header: MailboxReqHeader, } @@ -732,7 +726,7 @@ impl Request for GetFmcAliasCertReq { } #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetFmcAliasCertResp { pub hdr: MailboxRespHeader, pub data_size: u32, @@ -760,7 +754,7 @@ impl Default for GetFmcAliasCertResp { // FIPS_GET_VERSION // No command-specific input args #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct FipsVersionResp { pub hdr: MailboxRespHeader, pub mode: u32, @@ -772,7 +766,7 @@ impl Response for FipsVersionResp {} // FW_INFO // No command-specific input args #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct FwInfoResp { pub hdr: MailboxRespHeader, pub pl0_pauser: u32, @@ -792,7 +786,7 @@ pub struct FwInfoResp { // CAPABILITIES // No command-specific input args #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct CapabilitiesResp { pub hdr: MailboxRespHeader, pub capabilities: [u8; crate::capabilities::Capabilities::SIZE_IN_BYTES], @@ -802,7 +796,7 @@ impl Response for CapabilitiesResp {} // ADD_SUBJECT_ALT_NAME // No command-specific output args #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct AddSubjectAltNameReq { pub hdr: MailboxReqHeader, pub dmtf_device_info_size: u32, @@ -824,7 +818,7 @@ impl AddSubjectAltNameReq { return Err(CaliptraError::RUNTIME_MAILBOX_API_REQUEST_DATA_LEN_TOO_LARGE); } let unused_byte_count = Self::MAX_DEVICE_INFO_LEN - self.dmtf_device_info_size as usize; - Ok(&mut self.as_bytes_mut()[..size_of::() - unused_byte_count]) + Ok(&mut self.as_mut_bytes()[..size_of::() - unused_byte_count]) } } impl Default for AddSubjectAltNameReq { @@ -840,7 +834,7 @@ impl Default for AddSubjectAltNameReq { // POPULATE_IDEV_CERT // No command-specific output args #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct PopulateIdevCertReq { pub hdr: MailboxReqHeader, pub cert_size: u32, @@ -862,7 +856,7 @@ impl PopulateIdevCertReq { return Err(CaliptraError::RUNTIME_MAILBOX_API_REQUEST_DATA_LEN_TOO_LARGE); } let unused_byte_count = Self::MAX_CERT_SIZE - self.cert_size as usize; - Ok(&mut self.as_bytes_mut()[..size_of::() - unused_byte_count]) + Ok(&mut self.as_mut_bytes()[..size_of::() - unused_byte_count]) } } impl Default for PopulateIdevCertReq { @@ -878,7 +872,7 @@ impl Default for PopulateIdevCertReq { // DPE_TAG_TCI // No command-specific output args #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct TagTciReq { pub hdr: MailboxReqHeader, pub handle: [u8; 16], @@ -887,13 +881,13 @@ pub struct TagTciReq { // DPE_GET_TAGGED_TCI #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetTaggedTciReq { pub hdr: MailboxReqHeader, pub tag: u32, } #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct GetTaggedTciResp { pub hdr: MailboxRespHeader, pub tci_cumulative: [u8; 48], @@ -903,7 +897,7 @@ pub struct GetTaggedTciResp { // INCREMENT_PCR_RESET_COUNTER request // No command specific output #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct IncrementPcrResetCounterReq { pub hdr: MailboxReqHeader, pub index: u32, @@ -916,7 +910,7 @@ impl Request for IncrementPcrResetCounterReq { /// QUOTE_PCRS input arguments #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct QuotePcrsReq { pub hdr: MailboxReqHeader, pub nonce: [u8; 32], @@ -926,7 +920,7 @@ pub type PcrValue = [u8; 48]; /// QUOTE_PCRS output #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct QuotePcrsResp { pub hdr: MailboxRespHeader, /// The PCR values @@ -947,7 +941,7 @@ impl Request for QuotePcrsReq { // SET_AUTH_MANIFEST #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct SetAuthManifestReq { pub hdr: MailboxReqHeader, pub manifest_size: u32, @@ -969,7 +963,7 @@ impl SetAuthManifestReq { return Err(CaliptraError::RUNTIME_MAILBOX_API_REQUEST_DATA_LEN_TOO_LARGE); } let unused_byte_count = Self::MAX_MAN_SIZE - self.manifest_size as usize; - Ok(&mut self.as_bytes_mut()[..size_of::() - unused_byte_count]) + Ok(&mut self.as_mut_bytes()[..size_of::() - unused_byte_count]) } } impl Default for SetAuthManifestReq { @@ -984,7 +978,7 @@ impl Default for SetAuthManifestReq { // GET_IDEVID_CSR #[repr(C)] -#[derive(Default, Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Default, Debug, IntoBytes, FromBytes, KnownLayout, Immutable, PartialEq, Eq)] pub struct GetIdevCsrReq { pub hdr: MailboxReqHeader, } @@ -995,7 +989,7 @@ impl Request for GetIdevCsrReq { } #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, KnownLayout, Immutable, PartialEq, Eq)] pub struct GetIdevCsrResp { pub hdr: MailboxRespHeader, pub data_size: u32, @@ -1055,7 +1049,7 @@ impl AuthAndStashFlags { // AUTHORIZE_AND_STASH #[repr(C)] -#[derive(Debug, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct AuthorizeAndStashReq { pub hdr: MailboxReqHeader, pub fw_id: [u8; 4], @@ -1084,7 +1078,7 @@ impl Request for AuthorizeAndStashReq { } #[repr(C)] -#[derive(Debug, Default, AsBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Default, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)] pub struct AuthorizeAndStashResp { pub hdr: MailboxRespHeader, pub auth_req_result: u32, @@ -1127,15 +1121,15 @@ pub fn mbox_read_fifo( .ok_or(CaliptraApiError::UnableToReadMailbox)?; let len_words = buf.len() / size_of::(); - let (mut buf_words, suffix) = LayoutVerified::new_slice_unaligned_from_prefix(buf, len_words) - .ok_or(CaliptraApiError::ReadBuffTooSmall)?; + let (mut buf_words, suffix) = Ref::from_prefix_with_elems(buf, len_words) + .map_err(|_| CaliptraApiError::ReadBuffTooSmall)?; dequeue_words(&mbox, &mut buf_words); if !suffix.is_empty() { let last_word = mbox.dataout().read(); let suffix_len = suffix.len(); suffix - .as_bytes_mut() + .as_mut_bytes() .copy_from_slice(&last_word.as_bytes()[..suffix_len]); } diff --git a/api/src/soc_mgr.rs b/api/src/soc_mgr.rs index 51dc967bd5..69a3f45eb6 100644 --- a/api/src/soc_mgr.rs +++ b/api/src/soc_mgr.rs @@ -11,7 +11,7 @@ use crate::{ use caliptra_api_types::Fuses; use core::mem; use ureg::MmioMut; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, FromZeros, IntoBytes}; pub const NUM_PAUSERS: usize = 5; @@ -311,12 +311,11 @@ pub trait SocManager { return Err(CaliptraApiError::MailboxRespTypeTooSmall); } let (header_bytes, payload_bytes) = req - .as_bytes_mut() + .as_mut_bytes() .split_at_mut(mem::size_of::()); - let mut header = MailboxReqHeader::read_from(header_bytes as &[u8]).unwrap(); + let mut header = MailboxReqHeader::mut_from_bytes(header_bytes as &mut [u8]).unwrap(); header.chksum = calc_checksum(R::ID.into(), payload_bytes); - header_bytes.copy_from_slice(header.as_bytes()); let Some(data) = SocManager::mailbox_exec(self, R::ID.into(), req.as_bytes(), resp_bytes)? else { return Err(CaliptraApiError::MailboxNoResponseData); @@ -331,9 +330,9 @@ pub trait SocManager { } let mut response = R::Resp::new_zeroed(); - response.as_bytes_mut()[..data.len()].copy_from_slice(data); + response.as_mut_bytes()[..data.len()].copy_from_slice(data); - let response_header = MailboxRespHeader::read_from_prefix(data).unwrap(); + let (response_header, _) = MailboxRespHeader::read_from_prefix(data).unwrap(); let actual_checksum = calc_checksum(0, &data[4..]); if actual_checksum != response_header.chksum { return Err(CaliptraApiError::MailboxRespInvalidChecksum { diff --git a/auth-manifest/app/src/main.rs b/auth-manifest/app/src/main.rs index 18f789baf1..aaa51aa1ad 100644 --- a/auth-manifest/app/src/main.rs +++ b/auth-manifest/app/src/main.rs @@ -23,7 +23,7 @@ use clap::ArgMatches; use clap::{arg, value_parser, Command}; use std::io::Write; use std::path::PathBuf; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; mod config; diff --git a/auth-manifest/gen/src/generator.rs b/auth-manifest/gen/src/generator.rs index d9d487f8af..27a1da0ab9 100644 --- a/auth-manifest/gen/src/generator.rs +++ b/auth-manifest/gen/src/generator.rs @@ -13,7 +13,7 @@ Abstract: --*/ use caliptra_image_gen::ImageGeneratorCrypto; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::*; use core::mem::size_of; diff --git a/auth-manifest/types/src/lib.rs b/auth-manifest/types/src/lib.rs index 5b4818cc91..c16df53d5e 100644 --- a/auth-manifest/types/src/lib.rs +++ b/auth-manifest/types/src/lib.rs @@ -19,7 +19,7 @@ use caliptra_image_types::*; use core::default::Default; use core::ops::Range; use memoffset::span_of; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use zeroize::Zeroize; pub const AUTH_MANIFEST_MARKER: u32 = 0x4154_4D4E; @@ -40,7 +40,7 @@ impl From for AuthManifestFlags { } #[repr(C)] -#[derive(AsBytes, FromBytes, Default, Debug, Clone, Copy, Zeroize)] +#[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, @@ -49,7 +49,7 @@ pub struct AuthManifestPubKeys { } #[repr(C)] -#[derive(AsBytes, FromBytes, Default, Debug, Clone, Copy, Zeroize)] +#[derive(IntoBytes, FromBytes, KnownLayout, Immutable, Default, Debug, Clone, Copy, Zeroize)] pub struct AuthManifestPrivKeys { pub ecc_priv_key: ImageEccPrivKey, #[zeroize(skip)] @@ -57,7 +57,7 @@ pub struct AuthManifestPrivKeys { } #[repr(C)] -#[derive(AsBytes, Clone, Copy, FromBytes, Default, Debug, Zeroize)] +#[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthManifestSignatures { pub ecc_sig: ImageEccSignature, @@ -67,7 +67,7 @@ pub struct AuthManifestSignatures { /// Caliptra Authorization Image Manifest Preamble #[repr(C)] -#[derive(AsBytes, FromBytes, Clone, Copy, Debug, Zeroize, Default)] +#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Clone, Copy, Debug, Zeroize, Default)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthManifestPreamble { pub marker: u32, @@ -138,7 +138,7 @@ bitfield! { /// Caliptra Authorization Manifest Image Metadata #[repr(C)] -#[derive(AsBytes, FromBytes, Clone, Copy, Debug, Zeroize)] +#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Clone, Copy, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthManifestImageMetadata { pub fw_id: u32, @@ -160,7 +160,7 @@ impl Default for AuthManifestImageMetadata { /// Caliptra Authorization Manifest Image Metadata Collection #[repr(C)] -#[derive(AsBytes, FromBytes, Clone, Copy, Debug, Zeroize)] +#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Clone, Copy, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthManifestImageMetadataCollection { pub entry_count: u32, @@ -180,7 +180,7 @@ impl Default for AuthManifestImageMetadataCollection { /// Caliptra Image Authorization Manifest #[repr(C)] -#[derive(AsBytes, FromBytes, Clone, Copy, Debug, Zeroize, Default)] +#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Clone, Copy, Debug, Zeroize, Default)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct AuthorizationManifest { pub preamble: AuthManifestPreamble, diff --git a/builder/src/lib.rs b/builder/src/lib.rs index 8db888bb56..d5dab664e9 100644 --- a/builder/src/lib.rs +++ b/builder/src/lib.rs @@ -23,7 +23,7 @@ use caliptra_image_gen::{ use caliptra_image_types::{ImageBundle, ImageRevision, RomInfo}; use elf::endian::LittleEndian; use nix::fcntl::FlockArg; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; mod elf_symbols; pub mod firmware; diff --git a/dpe b/dpe index 98fe815909..3575e8de1f 160000 --- a/dpe +++ b/dpe @@ -1 +1 @@ -Subproject commit 98fe815909fcc285ad9a52a5c8c8a5fc897708ee +Subproject commit 3575e8de1f22ce3486df79e0d95a48af186085e9 diff --git a/drivers/src/array.rs b/drivers/src/array.rs index 59e4f43469..8f7cc26b48 100644 --- a/drivers/src/array.rs +++ b/drivers/src/array.rs @@ -15,7 +15,7 @@ Abstract: use caliptra_cfi_derive::Launder; use core::mem::MaybeUninit; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use zeroize::Zeroize; macro_rules! static_assert { @@ -27,7 +27,19 @@ macro_rules! static_assert { /// The `Array4xN` type represents large arrays in the native format of the Caliptra /// cryptographic hardware, and provides From traits for converting to/from byte arrays. #[repr(transparent)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Launder, Zeroize)] +#[derive( + Debug, + Clone, + Copy, + IntoBytes, + FromBytes, + Immutable, + KnownLayout, + PartialEq, + Eq, + Launder, + Zeroize, +)] pub struct Array4xN(pub [u32; W]); impl Array4xN { pub const fn new(val: [u32; W]) -> Self { @@ -43,15 +55,9 @@ impl Default for Array4xN { //// Ensure there is no padding in the struct static_assert!(core::mem::size_of::>() == 4); -unsafe impl AsBytes for Array4xN { - fn only_derive_is_allowed_to_implement_this_trait() {} -} //// Ensure there is no padding in the struct static_assert!(core::mem::size_of::>() == 4); -unsafe impl FromBytes for Array4xN { - fn only_derive_is_allowed_to_implement_this_trait() {} -} impl Array4xN { #[inline(always)] diff --git a/drivers/src/bounded_address.rs b/drivers/src/bounded_address.rs index 28316f12e7..cdfdf015b5 100644 --- a/drivers/src/bounded_address.rs +++ b/drivers/src/bounded_address.rs @@ -4,7 +4,7 @@ use core::fmt::Debug; use core::marker::PhantomData; use caliptra_error::CaliptraError; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, TryFromBytes, Unalign}; use zeroize::Zeroize; use crate::memory_layout; @@ -24,31 +24,41 @@ impl MemBounds for RomBounds { pub type RomAddr = BoundedAddr; #[repr(C)] -#[derive(Zeroize)] -pub struct BoundedAddr { - addr: u32, +#[derive(TryFromBytes, IntoBytes, Immutable)] +pub struct BoundedAddr { + addr: Unalign, _phantom: PhantomData<(T, B)>, } -unsafe impl FromBytes for BoundedAddr { - fn only_derive_is_allowed_to_implement_this_trait() {} -} -unsafe impl AsBytes for BoundedAddr { - fn only_derive_is_allowed_to_implement_this_trait() {} + +impl Zeroize for BoundedAddr +where + T: IntoBytes + FromBytes, + B: MemBounds, +{ + fn zeroize(&mut self) { + // This should never fail, and always be aligned. + if let Ok(addr) = self.addr.try_deref_mut() { + addr.zeroize(); + } + // NOP since PhantomData has no data, but might as well be thorough. + self._phantom.zeroize(); + } } -impl BoundedAddr { + +impl BoundedAddr { pub fn new(addr: u32) -> Self { Self { - addr, + addr: Unalign::new(addr), _phantom: Default::default(), } } pub fn get(&self) -> Result<&T, CaliptraError> { assert!(core::mem::size_of::() == core::mem::size_of::()); - Self::validate_addr(self.addr)?; - Ok(unsafe { &*(self.addr as *const T) }) + Self::validate_addr(self.addr.get())?; + Ok(unsafe { &*(self.addr.get() as *const T) }) } pub fn is_valid(&self) -> bool { - Self::validate_addr(self.addr).is_ok() + Self::validate_addr(self.addr.get()).is_ok() } pub fn validate_addr(addr: u32) -> Result<(), CaliptraError> { let addr = addr as usize; @@ -63,17 +73,19 @@ impl BoundedAddr { Ok(()) } } -impl Clone for BoundedAddr { +impl Clone for BoundedAddr { fn clone(&self) -> Self { - Self::new(self.addr) + Self::new(self.addr.get()) } } -impl Debug for BoundedAddr { +impl Debug for BoundedAddr { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("RomAddr").field("addr", &self.addr).finish() + f.debug_struct("RomAddr") + .field("addr", &self.addr.get()) + .finish() } } -impl From<&'static T> for BoundedAddr { +impl From<&'static T> for BoundedAddr { fn from(value: &'static T) -> Self { Self::new(value as *const T as u32) } @@ -84,7 +96,7 @@ mod tests { use super::*; use crate::memory_layout::{ROM_ORG, ROM_SIZE}; - #[derive(AsBytes, FromBytes)] + #[derive(IntoBytes, FromBytes)] #[repr(C)] struct MyStruct { a: u32, diff --git a/drivers/src/ecc384.rs b/drivers/src/ecc384.rs index d41f61e54b..2c582f1ac0 100644 --- a/drivers/src/ecc384.rs +++ b/drivers/src/ecc384.rs @@ -21,7 +21,7 @@ use crate::{ use caliptra_cfi_derive::cfi_impl_fn; use caliptra_registers::ecc::{EccReg, RegisterBlock}; use core::cmp::Ordering; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use zeroize::Zeroize; /// ECC-384 Coordinate @@ -116,7 +116,19 @@ impl<'a> From> for Ecc384PrivKeyIn<'a> { /// ECC-384 Public Key #[repr(C)] -#[derive(AsBytes, FromBytes, Debug, Default, Copy, Clone, Eq, PartialEq, Zeroize)] +#[derive( + IntoBytes, + FromBytes, + Immutable, + KnownLayout, + Debug, + Default, + Copy, + Clone, + Eq, + PartialEq, + Zeroize, +)] pub struct Ecc384PubKey { /// X coordinate pub x: Ecc384Scalar, @@ -135,7 +147,19 @@ impl Ecc384PubKey { /// ECC-384 Signature #[repr(C)] -#[derive(Debug, Default, AsBytes, FromBytes, Copy, Clone, Eq, PartialEq, Zeroize)] +#[derive( + Debug, + Default, + IntoBytes, + FromBytes, + Immutable, + KnownLayout, + Copy, + Clone, + Eq, + PartialEq, + Zeroize, +)] pub struct Ecc384Signature { /// Random point pub r: Ecc384Scalar, diff --git a/drivers/src/fuse_bank.rs b/drivers/src/fuse_bank.rs index fdc213b79c..2ad6928ce5 100644 --- a/drivers/src/fuse_bank.rs +++ b/drivers/src/fuse_bank.rs @@ -15,7 +15,7 @@ Abstract: use crate::Array4x12; use caliptra_cfi_derive::Launder; use caliptra_registers::soc_ifc::SocIfcReg; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; pub struct FuseBank<'a> { pub(crate) soc_ifc: &'a SocIfcReg, diff --git a/drivers/src/fuse_log.rs b/drivers/src/fuse_log.rs index 1e09f6f321..6c4309a7c5 100644 --- a/drivers/src/fuse_log.rs +++ b/drivers/src/fuse_log.rs @@ -11,7 +11,7 @@ Abstract: --*/ -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use zeroize::Zeroize; #[repr(u32)] @@ -51,7 +51,7 @@ impl From for FuseLogEntryId { /// Fuse log entry #[repr(C)] -#[derive(AsBytes, Clone, Copy, Debug, Default, FromBytes, Zeroize)] +#[derive(IntoBytes, Clone, Copy, Debug, Default, FromBytes, KnownLayout, Immutable, Zeroize)] pub struct FuseLogEntry { /// Entry identifier pub entry_id: u32, diff --git a/drivers/src/hand_off.rs b/drivers/src/hand_off.rs index a1162353f1..1e8ad9e1bf 100644 --- a/drivers/src/hand_off.rs +++ b/drivers/src/hand_off.rs @@ -10,14 +10,14 @@ use bitfield::{bitfield_bitrange, bitfield_fields}; use caliptra_error::CaliptraError; use caliptra_image_types::RomInfo; use core::mem::size_of; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, TryFromBytes}; use zeroize::Zeroize; pub const FHT_MARKER: u32 = 0x54484643; pub const FHT_INVALID_ADDRESS: u32 = u32::MAX; #[repr(C)] -#[derive(AsBytes, Copy, Clone, Debug, FromBytes, PartialEq, Zeroize)] +#[derive(IntoBytes, Immutable, KnownLayout, Copy, Clone, Debug, FromBytes, PartialEq, Zeroize)] pub struct HandOffDataHandle(pub u32); pub const FHT_INVALID_HANDLE: HandOffDataHandle = HandOffDataHandle(u32::MAX); @@ -179,7 +179,7 @@ impl From for HandOffDataHandle { const _: () = assert!(size_of::() == 2048); const _: () = assert!(size_of::() <= memory_layout::FHT_SIZE as usize); #[repr(C)] -#[derive(Clone, Debug, AsBytes, FromBytes, Zeroize)] +#[derive(Clone, Debug, IntoBytes, TryFromBytes, Immutable, KnownLayout, Zeroize)] pub struct FirmwareHandoffTable { /// Magic Number marking start of table. Value must be 0x54484643 /// (‘CFHT’ when viewed as little-endian ASCII). diff --git a/drivers/src/lms.rs b/drivers/src/lms.rs index 7e2a239953..358a3187b8 100644 --- a/drivers/src/lms.rs +++ b/drivers/src/lms.rs @@ -21,7 +21,7 @@ use caliptra_error::CaliptraError; use caliptra_lms_types::{ LmotsAlgorithmType, LmsAlgorithmType, LmsIdentifier, LmsPublicKey, LmsSignature, }; -use zerocopy::{AsBytes, LittleEndian, U32}; +use zerocopy::{IntoBytes, LittleEndian, U32}; use zeroize::Zeroize; pub const D_PBLC: u16 = 0x8080; diff --git a/drivers/src/mailbox.rs b/drivers/src/mailbox.rs index df84d7bee6..6d80ddb256 100644 --- a/drivers/src/mailbox.rs +++ b/drivers/src/mailbox.rs @@ -21,7 +21,7 @@ use caliptra_registers::soc_ifc::SocIfcReg; use core::cmp::min; use core::mem::size_of; use core::slice; -use zerocopy::{AsBytes, LayoutVerified, Unalign}; +use zerocopy::{FromBytes, IntoBytes, Unalign}; #[derive(Copy, Clone, Default, Eq, PartialEq)] /// Malbox operational states @@ -305,15 +305,14 @@ mod fifo { } let len_words = buf.len() / size_of::(); - let (mut buf_words, suffix) = - LayoutVerified::new_slice_unaligned_from_prefix(buf, len_words).unwrap(); - - dequeue_words(mbox, &mut buf_words); - if !suffix.is_empty() { + let (buf_words, suffix) = + <[Unalign]>::mut_from_prefix_with_elems(buf, len_words).unwrap(); + dequeue_words(mbox, buf_words); + if !suffix.is_empty() && suffix.len() <= size_of::() { let last_word = mbox.regs().dataout().read(); let suffix_len = suffix.len(); suffix - .as_bytes_mut() + .as_mut_bytes() .copy_from_slice(&last_word.as_bytes()[..suffix_len]); } } @@ -331,17 +330,14 @@ mod fifo { if mbox.regs().dlen().read() as usize != buf.len() { return Err(CaliptraError::DRIVER_MAILBOX_ENQUEUE_ERR); } - - let (buf_words, suffix) = - LayoutVerified::new_slice_unaligned_from_prefix(buf, buf.len() / size_of::()) - .unwrap(); - enqueue_words(mbox, &buf_words); - if !suffix.is_empty() { + let count = buf.len() / size_of::(); + let (buf_words, suffix) = <[Unalign]>::ref_from_prefix_with_elems(buf, count).unwrap(); + enqueue_words(mbox, buf_words); + if !suffix.is_empty() && suffix.len() <= size_of::() { let mut last_word = 0_u32; - last_word.as_bytes_mut()[..suffix.len()].copy_from_slice(suffix); + last_word.as_mut_bytes()[..suffix.len()].copy_from_slice(suffix); enqueue_words(mbox, &[Unalign::new(last_word)]); } - Ok(()) } } diff --git a/drivers/src/pcr_log.rs b/drivers/src/pcr_log.rs index 1296adc84e..9900bb7130 100644 --- a/drivers/src/pcr_log.rs +++ b/drivers/src/pcr_log.rs @@ -12,7 +12,7 @@ Abstract: --*/ use crate::PcrId; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use zeroize::Zeroize; pub const PCR_ID_FMC_CURRENT: PcrId = PcrId::PcrId0; @@ -52,7 +52,7 @@ impl From for PcrLogEntryId { /// PCR log entry #[repr(C)] -#[derive(AsBytes, Clone, Copy, Debug, Default, FromBytes, Zeroize)] +#[derive(IntoBytes, Clone, Copy, Debug, Default, FromBytes, Immutable, KnownLayout, Zeroize)] pub struct PcrLogEntry { /// Entry identifier pub id: u16, @@ -85,7 +85,7 @@ impl PcrLogEntry { /// Measurement log entry #[repr(C)] -#[derive(AsBytes, Clone, Copy, Debug, Default, FromBytes, Zeroize)] +#[derive(IntoBytes, Clone, Copy, Debug, Default, FromBytes, Immutable, KnownLayout, Zeroize)] pub struct MeasurementLogEntry { pub pcr_entry: PcrLogEntry, pub metadata: [u8; 4], diff --git a/drivers/src/pcr_reset.rs b/drivers/src/pcr_reset.rs index 5e31009d78..8b5c4fbb00 100644 --- a/drivers/src/pcr_reset.rs +++ b/drivers/src/pcr_reset.rs @@ -13,11 +13,11 @@ Abstract: use crate::pcr_bank::{PcrBank, PcrId}; use core::ops::{Index, IndexMut}; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use zeroize::Zeroize; #[repr(C, align(4))] -#[derive(AsBytes, FromBytes, Zeroize)] +#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Zeroize)] pub struct PcrResetCounter { counter: [u32; PcrBank::ALL_PCR_IDS.len()], } diff --git a/drivers/src/persistent.rs b/drivers/src/persistent.rs index e0bb49de67..c5f75d411e 100644 --- a/drivers/src/persistent.rs +++ b/drivers/src/persistent.rs @@ -11,7 +11,7 @@ use caliptra_error::{CaliptraError, CaliptraResult}; use caliptra_image_types::ImageManifest; #[cfg(feature = "runtime")] use dpe::{DpeInstance, U8Bool, MAX_HANDLES}; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{IntoBytes, KnownLayout, TryFromBytes}; use zeroize::Zeroize; use crate::{ @@ -45,7 +45,7 @@ pub type StashMeasurementArray = [MeasurementLogEntry; MEASUREMENT_MAX_COUNT]; pub type AuthManifestImageMetadataList = [AuthManifestImageMetadata; AUTH_MANIFEST_IMAGE_METADATA_MAX_COUNT]; -#[derive(Clone, FromBytes, AsBytes, Zeroize)] +#[derive(Clone, TryFromBytes, IntoBytes, Zeroize)] #[repr(C)] pub struct IdevIdCsr { csr_len: u32, @@ -104,7 +104,7 @@ impl IdevIdCsr { const _: () = assert!(size_of::() < memory_layout::IDEVID_CSR_SIZE as usize); -#[derive(FromBytes, AsBytes, Zeroize)] +#[derive(TryFromBytes, IntoBytes, KnownLayout, Zeroize)] #[repr(C)] pub struct PersistentData { pub manifest1: ImageManifest, @@ -244,7 +244,7 @@ impl PersistentDataAccessor { } #[inline(always)] -unsafe fn ref_from_addr<'a, T: FromBytes>(addr: u32) -> &'a T { +unsafe fn ref_from_addr<'a, T: TryFromBytes>(addr: u32) -> &'a T { // LTO should be able to optimize out the assertions to maintain panic_is_missing // dereferencing zero is undefined behavior @@ -255,7 +255,7 @@ unsafe fn ref_from_addr<'a, T: FromBytes>(addr: u32) -> &'a T { } #[inline(always)] -unsafe fn ref_mut_from_addr<'a, T: FromBytes>(addr: u32) -> &'a mut T { +unsafe fn ref_mut_from_addr<'a, T: TryFromBytes>(addr: u32) -> &'a mut T { // LTO should be able to optimize out the assertions to maintain panic_is_missing // dereferencing zero is undefined behavior diff --git a/drivers/test-fw/src/bin/doe_tests.rs b/drivers/test-fw/src/bin/doe_tests.rs index cf7f8a4ec9..5eb8a1cd2e 100644 --- a/drivers/test-fw/src/bin/doe_tests.rs +++ b/drivers/test-fw/src/bin/doe_tests.rs @@ -29,7 +29,7 @@ use caliptra_registers::{ csrng::CsrngReg, doe::DoeReg, entropy_src::EntropySrcReg, hmac::HmacReg, mbox::MboxCsr, }; use caliptra_test_harness::test_suite; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; fn export_result_from_kv(ecc: &mut Ecc384, trng: &mut Trng, key_id: KeyId) -> Ecc384PubKey { ecc.key_pair( diff --git a/drivers/test-fw/src/bin/mailbox_driver_responder.rs b/drivers/test-fw/src/bin/mailbox_driver_responder.rs index 6aaf4d2f2c..d69d39eb96 100644 --- a/drivers/test-fw/src/bin/mailbox_driver_responder.rs +++ b/drivers/test-fw/src/bin/mailbox_driver_responder.rs @@ -11,7 +11,7 @@ use caliptra_test_harness::{self, println}; use caliptra_drivers::{self, Mailbox}; use caliptra_registers::mbox::MboxCsr; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { @@ -32,7 +32,7 @@ extern "C" fn main() { let mut buf = [0u32; 4]; let dlen = txn.dlen(); println!("dlen: {dlen}"); - txn.recv_request(buf.as_bytes_mut()).unwrap(); + txn.recv_request(buf.as_mut_bytes()).unwrap(); println!("buf: {:08x?}", buf); } // Test recv_request with non-multiple-of-4 result buffer @@ -50,7 +50,7 @@ extern "C" fn main() { let dlen_words = (dlen + 3) / 4; println!("dlen: {dlen}"); for _ in 0..((dlen_words + (buf.len() - 1)) / buf.len()) { - txn.copy_request(buf.as_bytes_mut()).unwrap(); + txn.copy_request(buf.as_mut_bytes()).unwrap(); println!("buf: {:08x?}", buf); } txn.complete(true).unwrap(); @@ -72,7 +72,7 @@ extern "C" fn main() { let rem_words = dlen_words / 2; let mut buf = [0u32; 1]; for _ in 0..rem_words { - txn.copy_request(buf.as_bytes_mut()).unwrap(); + txn.copy_request(buf.as_mut_bytes()).unwrap(); println!("buf: {:08x?}", buf); } txn.complete(true).unwrap(); @@ -88,7 +88,7 @@ extern "C" fn main() { let dlen_words = (dlen + 3) / 4; println!("dlen: {dlen}"); for _ in 0..((dlen_words + (buf.len() - 1)) / buf.len()) { - txn.copy_request(buf.as_bytes_mut()).unwrap(); + txn.copy_request(buf.as_mut_bytes()).unwrap(); println!("buf: {:08x?}", buf); } txn.send_response(&[0x98, 0x76]).unwrap(); diff --git a/drivers/test-fw/src/bin/trng_driver_responder.rs b/drivers/test-fw/src/bin/trng_driver_responder.rs index 94eb7dd685..8810867728 100644 --- a/drivers/test-fw/src/bin/trng_driver_responder.rs +++ b/drivers/test-fw/src/bin/trng_driver_responder.rs @@ -14,7 +14,7 @@ use caliptra_registers::{ csrng::CsrngReg, entropy_src::EntropySrcReg, mbox::MboxCsr, soc_ifc::SocIfcReg, soc_ifc_trng::SocIfcTrngReg, }; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { diff --git a/drivers/test-fw/src/lib.rs b/drivers/test-fw/src/lib.rs index 903227d934..00d1b1065b 100644 --- a/drivers/test-fw/src/lib.rs +++ b/drivers/test-fw/src/lib.rs @@ -7,7 +7,7 @@ use caliptra_drivers::Ecc384PubKey; /// Code shared between the caliptra-drivers integration_test.rs (running on the /// host) and the test binaries (running inside the hw-model). use core::fmt::Debug; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; pub const DOE_TEST_IV: [u32; 4] = [0xc6b407a2, 0xd119a37d, 0xb7a5bdeb, 0x26214aed]; @@ -16,7 +16,7 @@ pub const DOE_TEST_HMAC_KEY: [u32; 12] = [ 0xc6879874, 0x0aa49a0f, 0x4e740e9c, 0x2c9f9aad, ]; -#[derive(AsBytes, Clone, Copy, Default, Eq, PartialEq, FromBytes)] +#[derive(IntoBytes, KnownLayout, Immutable, Clone, Copy, Default, Eq, PartialEq, FromBytes)] #[repr(C)] pub struct DoeTestResults { /// HMAC result of the UDS as key, and b"Hello world!" as data. diff --git a/drivers/tests/drivers_integration_tests/main.rs b/drivers/tests/drivers_integration_tests/main.rs index 206d8e3cf0..9f55ce33f5 100644 --- a/drivers/tests/drivers_integration_tests/main.rs +++ b/drivers/tests/drivers_integration_tests/main.rs @@ -23,7 +23,7 @@ use caliptra_test::{ }; use openssl::{hash::MessageDigest, pkey::PKey}; use ureg::ResettableReg; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; fn default_init_params() -> InitParams<'static> { InitParams { @@ -221,7 +221,7 @@ fn test_doe_when_debug_not_locked() { .unwrap(); let txn = model.wait_for_mailbox_receive().unwrap(); - let test_results = DoeTestResults::read_from(txn.req.data.as_slice()).unwrap(); + let test_results = DoeTestResults::read_from_bytes(txn.req.data.as_slice()).unwrap(); assert_eq!( test_results, DOE_TEST_VECTORS_DEBUG_MODE.expected_test_results @@ -315,7 +315,7 @@ fn test_doe_when_debug_locked() { .unwrap(); let txn = model.wait_for_mailbox_receive().unwrap(); - let test_results = DoeTestResults::read_from(txn.req.data.as_slice()).unwrap(); + let test_results = DoeTestResults::read_from_bytes(txn.req.data.as_slice()).unwrap(); assert_eq!(test_results, DOE_TEST_VECTORS.expected_test_results); txn.respond_success(); model.step_until_exit_success().unwrap(); diff --git a/fmc/src/flow/pcr.rs b/fmc/src/flow/pcr.rs index eb1f9124f6..158caef086 100644 --- a/fmc/src/flow/pcr.rs +++ b/fmc/src/flow/pcr.rs @@ -31,7 +31,7 @@ use caliptra_drivers::{ CaliptraResult, PersistentData, }; use caliptra_error::CaliptraError; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; /// Extend common data into the RT current and journey PCRs /// @@ -92,7 +92,7 @@ fn log_pcr( pcr_ids, ..Default::default() }; - dst.pcr_data.as_bytes_mut()[..data.len()].copy_from_slice(data); + dst.pcr_data.as_mut_bytes()[..data.len()].copy_from_slice(data); fht.pcr_log_index += 1; Ok(()) diff --git a/fmc/src/flow/tci.rs b/fmc/src/flow/tci.rs index f5ac359f5b..d5e1a409d2 100644 --- a/fmc/src/flow/tci.rs +++ b/fmc/src/flow/tci.rs @@ -19,7 +19,7 @@ Environment: use crate::flow::crypto::Crypto; use crate::fmc_env::FmcEnv; use caliptra_drivers::{Array4x12, CaliptraResult}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; pub struct Tci {} diff --git a/fmc/tests/fmc_integration_tests/test_rtalias.rs b/fmc/tests/fmc_integration_tests/test_rtalias.rs index 498dba8462..3147421820 100644 --- a/fmc/tests/fmc_integration_tests/test_rtalias.rs +++ b/fmc/tests/fmc_integration_tests/test_rtalias.rs @@ -13,7 +13,7 @@ use caliptra_drivers::{ use caliptra_hw_model::{BootParams, HwModel, InitParams}; use caliptra_test::swap_word_bytes; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes, TryFromBytes}; use openssl::hash::{Hasher, MessageDigest}; @@ -89,7 +89,7 @@ fn test_fht_info() { .unwrap(); let data = hw.mailbox_execute(TEST_CMD_READ_FHT, &[]).unwrap().unwrap(); - let fht = FirmwareHandoffTable::read_from_prefix(data.as_bytes()).unwrap(); + let fht = FirmwareHandoffTable::try_ref_from_bytes(data.as_bytes()).unwrap(); assert_eq!(fht.ldevid_tbs_size, 552); match get_ci_rom_version() { CiRomVersion::Rom1_0 | CiRomVersion::Rom1_1 => assert_eq!(fht.fmcalias_tbs_size, 786), @@ -128,7 +128,7 @@ fn test_pcr_log() { .unwrap(); let data = hw.mailbox_execute(TEST_CMD_READ_FHT, &[]).unwrap().unwrap(); - let fht = FirmwareHandoffTable::read_from_prefix(data.as_bytes()).unwrap(); + let fht = FirmwareHandoffTable::try_ref_from_bytes(data.as_bytes()).unwrap(); let pcr_entry_arr = hw .mailbox_execute(TEST_CMD_READ_PCR_LOG, &[]) @@ -253,7 +253,7 @@ fn check_pcr_log_entry( pcr_data: &[u8], ) { let offset = pcr_entry_index as usize * PCR_ENTRY_SIZE; - let entry = PcrLogEntry::read_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap(); + let (entry, _) = PcrLogEntry::read_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap(); assert_eq!(entry.id, entry_id as u16); assert_eq!(entry.pcr_ids, pcr_ids); @@ -272,7 +272,7 @@ fn hash_pcr_log_entries(initial_pcr: &[u8; 48], pcr_entry_arr: &[u8], pcr_id: Pc break; } - let entry = PcrLogEntry::read_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap(); + let (entry, _) = PcrLogEntry::read_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap(); offset += PCR_ENTRY_SIZE; if (entry.pcr_ids & (1 << pcr_id as u8)) == 0 { diff --git a/hw-model/src/lib.rs b/hw-model/src/lib.rs index cd221f70ec..9f80ba5b19 100644 --- a/hw-model/src/lib.rs +++ b/hw-model/src/lib.rs @@ -18,7 +18,7 @@ use caliptra_hw_model_types::{ ErrorInjectionMode, EtrngResponse, HexBytes, HexSlice, RandomEtrngResponses, RandomNibbles, DEFAULT_CPTRA_OBF_KEY, }; -use zerocopy::{AsBytes, FromBytes, LayoutVerified, Unalign}; +use zerocopy::{FromBytes, FromZeros, IntoBytes, Ref, Unalign}; use caliptra_registers::mbox; use caliptra_registers::mbox::enums::{MboxFsmE, MboxStatusE}; @@ -837,7 +837,7 @@ pub trait HwModel: SocManager { ) -> std::result::Result { let mut response = R::Resp::new_zeroed(); - self.mailbox_exec_req(req, response.as_bytes_mut()) + self.mailbox_exec_req(req, response.as_mut_bytes()) .map_err(ModelError::from) } @@ -974,13 +974,9 @@ pub trait HwModel: SocManager { // Unwrap cannot fail, count * sizeof(u32) is always smaller than data.len() let (prefix_words, suffix_bytes) = - LayoutVerified::<_, [Unalign]>::new_slice_unaligned_from_prefix( - data, - data.len() / 4, - ) - .unwrap(); + Ref::<_, [Unalign]>::from_prefix_with_elems(data, data.len() / 4).unwrap(); - for word in prefix_words.into_slice() { + for word in Ref::into_ref(prefix_words) { self.soc_sha512_acc() .datain() .write(|_| word.get().swap_bytes()); @@ -1054,8 +1050,8 @@ pub trait HwModel: SocManager { let response = response.ok_or(ModelError::UploadMeasurementResponseError)?; // Get response as a response header struct - let response = api::mailbox::StashMeasurementResp::read_from(response.as_slice()) - .ok_or(ModelError::UploadMeasurementResponseError)?; + let response = api::mailbox::StashMeasurementResp::ref_from_bytes(response.as_slice()) + .map_err(|_| ModelError::UploadMeasurementResponseError)?; // Verify checksum and FIPS status if !api::verify_checksum( @@ -1085,7 +1081,7 @@ mod tests { use caliptra_emu_bus::Bus; use caliptra_emu_types::RvSize; use caliptra_registers::{mbox::enums::MboxStatusE, soc_ifc}; - use zerocopy::{AsBytes, FromBytes}; + use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use crate as caliptra_hw_model; @@ -1432,7 +1428,7 @@ mod tests { // Send command that echoes the command and input message let mut resp_data = [0u8; 128]; assert_eq!( - model.mailbox_exec(0x1000_0000, &message[..8], resp_data.as_bytes_mut()), + model.mailbox_exec(0x1000_0000, &message[..8], resp_data.as_mut_bytes()), Ok(Some( [0x00, 0x00, 0x00, 0x10, 0x90, 0x5e, 0x1f, 0xad, 0x8b, 0x60, 0xb0, 0xbf].as_slice() )), @@ -1443,19 +1439,19 @@ mod tests { let mut resp_data = [0u8; 128]; assert_eq!( - model.mailbox_exec(0x1000_1000, &[42], resp_data.as_bytes_mut()), + model.mailbox_exec(0x1000_1000, &[42], resp_data.as_mut_bytes()), Ok(Some([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd].as_slice())), ); // Send command that returns success with no output assert_eq!( - model.mailbox_exec(0x2000_0000, &[], resp_data.as_bytes_mut()), + model.mailbox_exec(0x2000_0000, &[], resp_data.as_mut_bytes()), Ok(None) ); // Send command that returns failure assert_eq!( - model.mailbox_exec(0x4000_0000, &message, resp_data.as_bytes_mut()), + model.mailbox_exec(0x4000_0000, &message, resp_data.as_mut_bytes()), Err(CaliptraApiError::MailboxCmdFailed(0)) ); } @@ -1596,7 +1592,7 @@ mod tests { const GET_RESPONSE_CMD: u32 = 0x3000_0001; #[repr(C)] - #[derive(AsBytes, FromBytes, Default)] + #[derive(IntoBytes, FromBytes, Default, Immutable, KnownLayout)] struct TestReq { hdr: MailboxReqHeader, data: [u8; 4], @@ -1606,7 +1602,7 @@ mod tests { type Resp = TestResp; } #[repr(C)] - #[derive(AsBytes, Debug, FromBytes, PartialEq, Eq)] + #[derive(IntoBytes, Immutable, KnownLayout, Debug, FromBytes, PartialEq, Eq)] struct TestResp { hdr: MailboxRespHeader, data: [u8; 4], @@ -1614,7 +1610,7 @@ mod tests { impl mailbox::Response for TestResp {} #[repr(C)] - #[derive(AsBytes, FromBytes, Default)] + #[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Default)] struct TestReqNoData { hdr: MailboxReqHeader, data: [u8; 4], @@ -1710,7 +1706,7 @@ mod tests { data: *b"Hi!!", ..Default::default() }, - packet.as_bytes_mut(), + packet.as_mut_bytes(), ) .map_err(ModelError::from); assert_eq!( @@ -1760,7 +1756,7 @@ mod tests { const GET_RESPONSE_CMD: u32 = 0x3000_0001; #[repr(C)] - #[derive(AsBytes, FromBytes, Default)] + #[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Default)] struct TestReq { hdr: MailboxReqHeader, data: [u8; 4], @@ -1770,7 +1766,7 @@ mod tests { type Resp = TestResp; } #[repr(C)] - #[derive(AsBytes, Debug, FromBytes, PartialEq, Eq)] + #[derive(IntoBytes, Debug, FromBytes, PartialEq, Eq)] struct TestResp { hdr: MailboxRespHeader, data: [u8; 4], @@ -1778,7 +1774,7 @@ mod tests { impl mailbox::Response for TestResp {} #[repr(C)] - #[derive(AsBytes, FromBytes, Default)] + #[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Default)] struct TestReqNoData { hdr: MailboxReqHeader, data: [u8; 4], diff --git a/image/crypto/src/lib.rs b/image/crypto/src/lib.rs index e07c197ff6..95c14dbf91 100644 --- a/image/crypto/src/lib.rs +++ b/image/crypto/src/lib.rs @@ -29,7 +29,7 @@ pub use crate::openssl::*; #[cfg(feature = "rustcrypto")] pub use crate::rustcrypto::*; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; const LMS_TREE_GEN_SUPPORTED_FULL_HEIGHT: u8 = 10u8; const SUPPORTED_LMS_Q_VALUE: u32 = 5u32; @@ -67,7 +67,8 @@ pub fn lms_pub_key_from_pem(path: &PathBuf) -> anyhow::Result let key_bytes = std::fs::read(path) .with_context(|| format!("Failed to read public key PEM file {}", path.display()))?; - ImageLmsPublicKey::read_from(&key_bytes[..]).ok_or(anyhow!("Error parsing LMS public key")) + ImageLmsPublicKey::read_from_bytes(&key_bytes[..]) + .map_err(|_| anyhow!("Error parsing LMS public key")) } /// Read LMS SHA192 private Key from PEM file @@ -75,7 +76,8 @@ pub fn lms_priv_key_from_pem(path: &PathBuf) -> anyhow::Result let key_bytes = std::fs::read(path) .with_context(|| format!("Failed to read private key PEM file {}", path.display()))?; - ImageLmsPrivKey::read_from(&key_bytes[..]).ok_or(anyhow!("Error parsing LMS priv key")) + ImageLmsPrivKey::read_from_bytes(&key_bytes[..]) + .map_err(|_| anyhow!("Error parsing LMS priv key")) } /// Convert the slice to hardware format @@ -250,7 +252,7 @@ fn generate_lms_pubkey_helper( if cur_node == target_node + 1 { if let Some(sig_val) = sig.as_mut() { sig_val.tree_path[level] - .as_bytes_mut() + .as_mut_bytes() .copy_from_slice(stack_top(&pub_key_stack, stack_idx)); level += 1; } @@ -262,7 +264,7 @@ fn generate_lms_pubkey_helper( if cur_node == target_node { if let Some(sig_val) = sig.as_mut() { sig_val.tree_path[level] - .as_bytes_mut() + .as_mut_bytes() .copy_from_slice(&k[..]); level += 1; } @@ -291,7 +293,7 @@ fn generate_lms_pubkey_helper( stack_idx -= 1; pub_key_val .digest - .as_bytes_mut() + .as_mut_bytes() .clone_from_slice(stack_top(&pub_key_stack, stack_idx)); } } @@ -313,7 +315,7 @@ fn generate_ots_signature_helper( ots_type: ots_alg, ..Default::default() }; - sig.nonce.as_bytes_mut().clone_from_slice(rand); + sig.nonce.as_mut_bytes().clone_from_slice(rand); let mut q_arr = [0u8; SHA192_DIGEST_BYTE_SIZE]; let mut hasher = T::new(); @@ -358,7 +360,7 @@ fn generate_ots_signature_helper( tmp.copy_from_slice(&hasher.finish()[..SHA192_DIGEST_BYTE_SIZE]); } let sig_val = &mut sig.y[i]; - sig_val.as_bytes_mut().clone_from_slice(tmp); + sig_val.as_mut_bytes().clone_from_slice(tmp); } sig @@ -474,11 +476,11 @@ mod tests { #[cfg(feature = "openssl")] rand_bytes(&mut priv_key.id).unwrap(); #[cfg(feature = "openssl")] - rand_bytes(priv_key.seed.as_bytes_mut()).unwrap(); + rand_bytes(priv_key.seed.as_mut_bytes()).unwrap(); #[cfg(feature = "rustcrypto")] OsRng.fill_bytes(&mut priv_key.id); #[cfg(feature = "rustcrypto")] - OsRng.fill_bytes(priv_key.seed.as_bytes_mut()); + OsRng.fill_bytes(priv_key.seed.as_mut_bytes()); #[cfg(feature = "openssl")] let pub_key = generate_lms_pubkey::(&priv_key).unwrap(); #[cfg(feature = "rustcrypto")] @@ -490,11 +492,11 @@ mod tests { #[cfg(feature = "openssl")] rand_bytes(&mut priv_key.id).unwrap(); #[cfg(feature = "openssl")] - rand_bytes(priv_key.seed.as_bytes_mut()).unwrap(); + rand_bytes(priv_key.seed.as_mut_bytes()).unwrap(); #[cfg(feature = "rustcrypto")] OsRng.fill_bytes(&mut priv_key.id); #[cfg(feature = "rustcrypto")] - OsRng.fill_bytes(priv_key.seed.as_bytes_mut()); + OsRng.fill_bytes(priv_key.seed.as_mut_bytes()); #[cfg(feature = "openssl")] let pub_key = generate_lms_pubkey::(&priv_key).unwrap(); #[cfg(feature = "rustcrypto")] diff --git a/image/fake-keys/src/lib.rs b/image/fake-keys/src/lib.rs index 554e511d8f..a10f186792 100644 --- a/image/fake-keys/src/lib.rs +++ b/image/fake-keys/src/lib.rs @@ -13,7 +13,7 @@ use std::fs; #[cfg(test)] use std::io::Write; // bring trait into scope #[cfg(test)] -use zerocopy::AsBytes; +use zerocopy::IntoBytes; /// Generated with /// diff --git a/image/gen/src/generator.rs b/image/gen/src/generator.rs index 5ef8309e53..6a75bc2376 100644 --- a/image/gen/src/generator.rs +++ b/image/gen/src/generator.rs @@ -14,7 +14,7 @@ Abstract: use anyhow::bail; use caliptra_image_types::*; use memoffset::offset_of; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::*; diff --git a/image/serde/src/lib.rs b/image/serde/src/lib.rs index 308a78b618..7648d5810f 100644 --- a/image/serde/src/lib.rs +++ b/image/serde/src/lib.rs @@ -13,7 +13,7 @@ Abstract: --*/ use caliptra_image_types::*; use std::io::Write; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; /// Image Bundle Writer pub struct ImageBundleWriter { diff --git a/image/types/src/lib.rs b/image/types/src/lib.rs index 35279d2c8e..1f02d83645 100644 --- a/image/types/src/lib.rs +++ b/image/types/src/lib.rs @@ -23,7 +23,7 @@ use caliptra_lms_types::{ LmotsAlgorithmType, LmotsSignature, LmsAlgorithmType, LmsPrivateKey, LmsPublicKey, LmsSignature, }; use memoffset::{offset_of, span_of}; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; pub const MANIFEST_MARKER: u32 = 0x4E414D43; pub const VENDOR_ECC_KEY_COUNT: u32 = 4; @@ -52,7 +52,19 @@ pub type ImageRevision = [u8; IMAGE_REVISION_BYTE_SIZE]; pub type ImageEccPrivKey = ImageScalar; #[repr(C)] -#[derive(AsBytes, FromBytes, Default, Debug, Copy, Clone, Eq, PartialEq, Zeroize)] +#[derive( + IntoBytes, + FromBytes, + Immutable, + KnownLayout, + Default, + Debug, + Copy, + Clone, + Eq, + PartialEq, + Zeroize, +)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct ImageEccPubKey { /// X Coordinate @@ -66,7 +78,19 @@ pub type ImageLmsPublicKey = LmsPublicKey; pub type ImageLmsPrivKey = LmsPrivateKey; #[repr(C)] -#[derive(AsBytes, FromBytes, Default, Debug, Copy, Clone, Eq, PartialEq, Zeroize)] +#[derive( + IntoBytes, + FromBytes, + Immutable, + KnownLayout, + Default, + Debug, + Copy, + Clone, + Eq, + PartialEq, + Zeroize, +)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct ImageEccSignature { /// Random point @@ -132,7 +156,7 @@ impl ImageBundle { /// Calipatra Image Manifest #[repr(C)] -#[derive(AsBytes, FromBytes, Clone, Copy, Debug, Zeroize)] +#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Clone, Copy, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct ImageManifest { /// Marker @@ -141,7 +165,7 @@ pub struct ImageManifest { /// Size of `Manifest` structure pub size: u32, - /// Preabmle + /// Preamble pub preamble: ImagePreamble, /// Header @@ -195,7 +219,7 @@ impl ImageManifest { } #[repr(C)] -#[derive(AsBytes, FromBytes, Default, Debug, Clone, Copy, Zeroize)] +#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Clone, Copy, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct ImageVendorPubKeys { pub ecc_pub_keys: [ImageEccPubKey; VENDOR_ECC_KEY_COUNT as usize], @@ -204,7 +228,7 @@ pub struct ImageVendorPubKeys { } #[repr(C)] -#[derive(AsBytes, FromBytes, Default, Debug, Clone, Copy, Zeroize)] +#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Clone, Copy, Zeroize)] pub struct ImageVendorPrivKeys { pub ecc_priv_keys: [ImageEccPrivKey; VENDOR_ECC_KEY_COUNT as usize], #[zeroize(skip)] @@ -212,7 +236,7 @@ pub struct ImageVendorPrivKeys { } #[repr(C)] -#[derive(AsBytes, FromBytes, Default, Debug, Clone, Copy, Zeroize)] +#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Clone, Copy, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct ImageOwnerPubKeys { pub ecc_pub_key: ImageEccPubKey, @@ -221,7 +245,7 @@ pub struct ImageOwnerPubKeys { } #[repr(C)] -#[derive(AsBytes, FromBytes, Default, Debug, Clone, Copy, Zeroize)] +#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Clone, Copy, Zeroize)] pub struct ImageOwnerPrivKeys { pub ecc_priv_key: ImageEccPrivKey, #[zeroize(skip)] @@ -229,7 +253,7 @@ pub struct ImageOwnerPrivKeys { } #[repr(C)] -#[derive(AsBytes, Clone, Copy, FromBytes, Default, Debug, Zeroize)] +#[derive(Clone, Copy, IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct ImageSignatures { pub ecc_sig: ImageEccSignature, @@ -239,7 +263,7 @@ pub struct ImageSignatures { /// Calipatra Image Bundle Preamble #[repr(C)] -#[derive(AsBytes, Clone, Copy, FromBytes, Default, Debug, Zeroize)] +#[derive(Clone, Copy, IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct ImagePreamble { /// Vendor Public Keys @@ -264,7 +288,7 @@ pub struct ImagePreamble { } #[repr(C)] -#[derive(AsBytes, Clone, Copy, FromBytes, Default, Debug, Zeroize)] +#[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct VendorSignedData { /// Vendor Start Date [ASN1 Time Format] For FMC alias certificate. @@ -277,7 +301,7 @@ pub struct VendorSignedData { } #[repr(C)] -#[derive(AsBytes, Clone, Copy, FromBytes, Default, Debug, Zeroize)] +#[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct OwnerSignedData { /// Owner Start Date [ASN1 Time Format] For FMC alias certificate: Takes Preference over vendor start date @@ -294,7 +318,7 @@ pub struct OwnerSignedData { /// Caliptra Image header #[repr(C)] -#[derive(AsBytes, Clone, Copy, FromBytes, Default, Debug, Zeroize)] +#[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct ImageHeader { /// Revision @@ -358,7 +382,7 @@ impl From for u32 { /// Caliptra Table of contents entry #[repr(C)] -#[derive(AsBytes, Clone, Copy, FromBytes, Default, Debug, Zeroize)] +#[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct ImageTocEntry { /// ID @@ -414,7 +438,7 @@ impl ImageTocEntry { /// Information about the ROM image. #[repr(C)] -#[derive(AsBytes, FromBytes, Default, Debug)] +#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Default, Debug)] pub struct RomInfo { // sha256 digest with big-endian words, where each 4-byte segment of the // digested data has the bytes reversed. diff --git a/lms-types/src/lib.rs b/lms-types/src/lib.rs index d5d1423a3e..f3eaa4a16d 100644 --- a/lms-types/src/lib.rs +++ b/lms-types/src/lib.rs @@ -5,7 +5,9 @@ use core::mem::size_of; use caliptra_cfi_derive::Launder; -use zerocopy::{AsBytes, BigEndian, FromBytes, LittleEndian, U32}; +use zerocopy::{ + BigEndian, FromBytes, Immutable, IntoBytes, KnownLayout, LittleEndian, Unaligned, U32, +}; use zeroize::Zeroize; pub type LmsIdentifier = [u8; 16]; @@ -17,7 +19,19 @@ macro_rules! static_assert { } #[repr(transparent)] -#[derive(AsBytes, FromBytes, Copy, Clone, Debug, Default, PartialEq, Eq)] +#[derive( + IntoBytes, + FromBytes, + Copy, + Clone, + Debug, + KnownLayout, + Immutable, + Unaligned, + Default, + PartialEq, + Eq, +)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct LmsAlgorithmType(pub U32); impl LmsAlgorithmType { @@ -40,7 +54,19 @@ impl LmsAlgorithmType { } #[repr(transparent)] -#[derive(AsBytes, FromBytes, Debug, Default, PartialEq, Eq, Hash, Clone, Copy)] +#[derive( + IntoBytes, + FromBytes, + Debug, + Immutable, + KnownLayout, + Unaligned, + Default, + PartialEq, + Eq, + Clone, + Copy, +)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct LmotsAlgorithmType(pub U32); @@ -61,7 +87,9 @@ impl LmotsAlgorithmType { pub const LmotsSha256N24W8: Self = Self::new(8); } -#[derive(Copy, Clone, Debug, PartialEq, Eq, Launder)] +#[derive( + Copy, Clone, Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq, Launder, +)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] #[repr(C)] pub struct LmsPublicKey { @@ -81,7 +109,7 @@ impl Default for LmsPublicKey { } } } -// Ensure there is no padding (required for AsBytes safety) +// Ensure there is no padding (required for IntoBytes safety) static_assert!( size_of::>() == (size_of::() @@ -89,16 +117,21 @@ static_assert!( + size_of::<[u8; 16]>() + size_of::<[U32; 1]>()) ); -// Derive doesn't support const generic arrays -unsafe impl AsBytes for LmsPublicKey { - fn only_derive_is_allowed_to_implement_this_trait() {} -} -unsafe impl FromBytes for LmsPublicKey { - fn only_derive_is_allowed_to_implement_this_trait() {} -} #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] -#[derive(Copy, Clone, Debug, PartialEq, Eq, Zeroize)] +#[derive( + Copy, + Clone, + Debug, + IntoBytes, + Immutable, + KnownLayout, + Unaligned, + FromBytes, + PartialEq, + Eq, + Zeroize, +)] #[repr(C)] pub struct LmotsSignature { #[zeroize(skip)] @@ -119,23 +152,18 @@ impl Default for LmotsSignature { } } } -// Ensure there is no padding (required for AsBytes safety) +// Ensure there is no padding (required for IntoBytes safety) static_assert!( size_of::>() == (size_of::() + size_of::<[U32; 1]>() + size_of::<[[U32; 1]; 1]>()) ); -// Derive doesn't support const generic arrays -unsafe impl AsBytes for LmotsSignature { - fn only_derive_is_allowed_to_implement_this_trait() {} -} -unsafe impl FromBytes for LmotsSignature { - fn only_derive_is_allowed_to_implement_this_trait() {} -} #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] -#[derive(Copy, Clone, Debug, PartialEq, Eq, Launder)] +#[derive( + Copy, Clone, Debug, IntoBytes, Immutable, KnownLayout, FromBytes, PartialEq, Eq, Launder, +)] #[repr(C)] pub struct LmsSignature { pub q: U32, @@ -156,7 +184,7 @@ impl Default for LmsSignature>() == (size_of::>() @@ -164,15 +192,8 @@ static_assert!( + size_of::() + size_of::<[[U32; 1]; 1]>()) ); -// Derive doesn't support const generic arrays -unsafe impl AsBytes for LmsSignature { - fn only_derive_is_allowed_to_implement_this_trait() {} -} -unsafe impl FromBytes for LmsSignature { - fn only_derive_is_allowed_to_implement_this_trait() {} -} -#[derive(Debug, Copy, Clone, Eq, PartialEq)] +#[derive(Debug, Copy, Clone, IntoBytes, Immutable, KnownLayout, FromBytes, Eq, PartialEq)] #[repr(C)] pub struct LmsPrivateKey { pub tree_type: LmsAlgorithmType, @@ -200,13 +221,6 @@ static_assert!( + size_of::() + size_of::<[U32; 1]>()) ); -// Derive doesn't support const generic arrays -unsafe impl AsBytes for LmsPrivateKey { - fn only_derive_is_allowed_to_implement_this_trait() {} -} -unsafe impl FromBytes for LmsPrivateKey { - fn only_derive_is_allowed_to_implement_this_trait() {} -} /// Converts a byte array to word arrays as used in the LMS types. Intended for /// use at compile-time or in tests / host utilities; not optimized for use in diff --git a/rom/dev/src/flow/cold_reset/fw_processor.rs b/rom/dev/src/flow/cold_reset/fw_processor.rs index adced6ffee..289b153540 100644 --- a/rom/dev/src/flow/cold_reset/fw_processor.rs +++ b/rom/dev/src/flow/cold_reset/fw_processor.rs @@ -37,7 +37,7 @@ use caliptra_image_verify::{ImageVerificationInfo, ImageVerificationLogInfo, Ima use caliptra_kat::KatsEnv; use caliptra_x509::{NotAfter, NotBefore}; use core::mem::ManuallyDrop; -use zerocopy::{AsBytes, LayoutVerified}; +use zerocopy::{FromBytes, IntoBytes}; use zeroize::Zeroize; const RESERVED_PAUSER: u32 = 0xFFFFFFFF; @@ -222,7 +222,7 @@ impl FirmwareProcessor { match CommandId::from(txn.cmd()) { CommandId::VERSION => { let mut request = MailboxReqHeader::default(); - Self::copy_req_verify_chksum(&mut txn, request.as_bytes_mut())?; + Self::copy_req_verify_chksum(&mut txn, request.as_mut_bytes())?; let mut resp = FipsVersionCmd::execute(soc_ifc)?; resp.populate_chksum(); @@ -230,7 +230,7 @@ impl FirmwareProcessor { } CommandId::SELF_TEST_START => { let mut request = MailboxReqHeader::default(); - Self::copy_req_verify_chksum(&mut txn, request.as_bytes_mut())?; + Self::copy_req_verify_chksum(&mut txn, request.as_mut_bytes())?; if self_test_in_progress { // TODO: set non-fatal error register? @@ -245,7 +245,7 @@ impl FirmwareProcessor { } CommandId::SELF_TEST_GET_RESULTS => { let mut request = MailboxReqHeader::default(); - Self::copy_req_verify_chksum(&mut txn, request.as_bytes_mut())?; + Self::copy_req_verify_chksum(&mut txn, request.as_mut_bytes())?; if !self_test_in_progress { // TODO: set non-fatal error register? @@ -259,7 +259,7 @@ impl FirmwareProcessor { } CommandId::SHUTDOWN => { let mut request = MailboxReqHeader::default(); - Self::copy_req_verify_chksum(&mut txn, request.as_bytes_mut())?; + Self::copy_req_verify_chksum(&mut txn, request.as_mut_bytes())?; let mut resp = MailboxRespHeader::default(); resp.populate_chksum(); @@ -270,7 +270,7 @@ impl FirmwareProcessor { } CommandId::CAPABILITIES => { let mut request = MailboxReqHeader::default(); - Self::copy_req_verify_chksum(&mut txn, request.as_bytes_mut())?; + Self::copy_req_verify_chksum(&mut txn, request.as_mut_bytes())?; let mut capabilities = Capabilities::default(); capabilities |= Capabilities::ROM_BASE; @@ -306,7 +306,7 @@ impl FirmwareProcessor { } CommandId::GET_IDEV_CSR => { let mut request = MailboxReqHeader::default(); - Self::copy_req_verify_chksum(&mut txn, request.as_bytes_mut())?; + Self::copy_req_verify_chksum(&mut txn, request.as_mut_bytes())?; let csr_persistent_mem = &persistent_data.idevid_csr; let mut resp = GetIdevCsrResp::default(); @@ -352,7 +352,7 @@ impl FirmwareProcessor { txn: &mut MailboxRecvTxn, ) -> CaliptraResult { let manifest = &mut persistent_data.get_mut().manifest1; - txn.copy_request(manifest.as_bytes_mut())?; + txn.copy_request(manifest.as_mut_bytes())?; report_boot_status(FwProcessorManifestLoadComplete.into()); Ok(*manifest) } @@ -511,7 +511,7 @@ impl FirmwareProcessor { core::slice::from_raw_parts_mut(addr, manifest.fmc.size as usize / 4) }; - txn.copy_request(fmc_dest.as_bytes_mut())?; + txn.copy_request(fmc_dest.as_mut_bytes())?; cprintln!( "[fwproc] Load Runtime at address 0x{:08x} len {}", @@ -524,7 +524,7 @@ impl FirmwareProcessor { core::slice::from_raw_parts_mut(addr, manifest.runtime.size as usize / 4) }; - txn.copy_request(runtime_dest.as_bytes_mut())?; + txn.copy_request(runtime_dest.as_mut_bytes())?; report_boot_status(FwProcessorLoadImageComplete.into()); Ok(()) @@ -632,11 +632,9 @@ impl FirmwareProcessor { txn.copy_request(data)?; // Extract header out from the rest of the request - let req_hdr: &MailboxReqHeader = LayoutVerified::<&[u8], MailboxReqHeader>::new( - &data[..core::mem::size_of::()], - ) - .ok_or(CaliptraError::FW_PROC_MAILBOX_PROCESS_FAILURE)? - .into_ref(); + let req_hdr = + MailboxReqHeader::ref_from_bytes(&data[..core::mem::size_of::()]) + .map_err(|_| CaliptraError::FW_PROC_MAILBOX_PROCESS_FAILURE)?; // Verify checksum if !caliptra_common::checksum::verify_checksum( @@ -668,7 +666,7 @@ impl FirmwareProcessor { txn: &mut MailboxRecvTxn, ) -> CaliptraResult<()> { let mut measurement = StashMeasurementReq::default(); - Self::copy_req_verify_chksum(txn, measurement.as_bytes_mut())?; + Self::copy_req_verify_chksum(txn, measurement.as_mut_bytes())?; // Extend measurement into PCR31. Self::extend_measurement(pcr_bank, sha384, persistent_data, &measurement)?; diff --git a/rom/dev/src/flow/fake.rs b/rom/dev/src/flow/fake.rs index 57dd203d53..2d0348f020 100644 --- a/rom/dev/src/flow/fake.rs +++ b/rom/dev/src/flow/fake.rs @@ -159,7 +159,7 @@ impl FakeRomFlow { // In real ROM, this is done as part of executing the SHA-ACC KAT. let sha_op = env .sha2_512_384_acc - .try_start_operation(ShaAccLockState::AssumedLocked)? + .try_start_operation(ShaAccLockState::AssumedLocked) .unwrap(); drop(sha_op); diff --git a/rom/dev/src/flow/update_reset.rs b/rom/dev/src/flow/update_reset.rs index b30cc5f750..8f89cb72e4 100644 --- a/rom/dev/src/flow/update_reset.rs +++ b/rom/dev/src/flow/update_reset.rs @@ -27,7 +27,7 @@ use caliptra_drivers::{DataVault, PersistentData}; use caliptra_error::{CaliptraError, CaliptraResult}; use caliptra_image_types::ImageManifest; use caliptra_image_verify::{ImageVerificationInfo, ImageVerifier}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; #[derive(Default)] pub struct UpdateResetFlow {} @@ -184,7 +184,7 @@ impl UpdateResetFlow { core::slice::from_raw_parts_mut(addr, manifest.runtime.size as usize / 4) }; - txn.copy_request(runtime_dest.as_bytes_mut())?; + txn.copy_request(runtime_dest.as_mut_bytes())?; //Call the complete here to reset the execute bit txn.complete(true)?; @@ -202,7 +202,7 @@ impl UpdateResetFlow { persistent_data: &mut PersistentData, txn: &mut MailboxRecvTxn, ) -> CaliptraResult<()> { - txn.copy_request(persistent_data.manifest2.as_bytes_mut())?; + txn.copy_request(persistent_data.manifest2.as_mut_bytes())?; Ok(()) } diff --git a/rom/dev/src/fuse.rs b/rom/dev/src/fuse.rs index 2a873825b9..4efad45559 100644 --- a/rom/dev/src/fuse.rs +++ b/rom/dev/src/fuse.rs @@ -13,7 +13,7 @@ Abstract: use caliptra_cfi_derive::cfi_mod_fn; use caliptra_common::{FuseLogEntry, FuseLogEntryId}; use caliptra_drivers::{CaliptraError, CaliptraResult, FuseLogArray}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; /// Log Fuse data /// @@ -42,7 +42,7 @@ pub fn log_fuse_data( entry_id: entry_id as u32, ..Default::default() }; - let Some(data_dest) = log_entry.log_data.as_bytes_mut().get_mut(..data.len()) else { + let Some(data_dest) = log_entry.log_data.as_mut_bytes().get_mut(..data.len()) else { return Err(CaliptraError::ROM_GLOBAL_FUSE_LOG_UNSUPPORTED_DATA_LENGTH); }; data_dest.copy_from_slice(data); diff --git a/rom/dev/src/pcr.rs b/rom/dev/src/pcr.rs index 9eb58ac0a3..37989de2f5 100644 --- a/rom/dev/src/pcr.rs +++ b/rom/dev/src/pcr.rs @@ -32,7 +32,7 @@ use caliptra_drivers::{ }; use caliptra_image_verify::ImageVerificationInfo; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; struct PcrExtender<'a> { persistent_data: &'a mut PersistentData, @@ -144,7 +144,7 @@ pub fn log_pcr( pcr_ids, ..Default::default() }; - let Some(dest_data) = pcr_log_entry.pcr_data.as_bytes_mut().get_mut(..data.len()) else { + let Some(dest_data) = pcr_log_entry.pcr_data.as_mut_bytes().get_mut(..data.len()) else { return Err(CaliptraError::ROM_GLOBAL_PCR_LOG_UNSUPPORTED_DATA_LENGTH); }; dest_data.copy_from_slice(data); diff --git a/rom/dev/tests/rom_integration_tests/test_capabilities.rs b/rom/dev/tests/rom_integration_tests/test_capabilities.rs index 6b75989a46..2773f4214a 100644 --- a/rom/dev/tests/rom_integration_tests/test_capabilities.rs +++ b/rom/dev/tests/rom_integration_tests/test_capabilities.rs @@ -6,7 +6,7 @@ use caliptra_common::mailbox_api::{ CapabilitiesResp, CommandId, MailboxReqHeader, MailboxRespHeader, }; use caliptra_hw_model::{Fuses, HwModel}; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; use crate::helpers; @@ -24,7 +24,7 @@ fn test_capabilities() { .unwrap() .unwrap(); - let capabilities_resp = CapabilitiesResp::read_from(response.as_bytes()).unwrap(); + let capabilities_resp = CapabilitiesResp::ref_from_bytes(response.as_bytes()).unwrap(); // Verify response checksum assert!(caliptra_common::checksum::verify_checksum( diff --git a/rom/dev/tests/rom_integration_tests/test_fmcalias_derivation.rs b/rom/dev/tests/rom_integration_tests/test_fmcalias_derivation.rs index ce93544014..1081d22d59 100644 --- a/rom/dev/tests/rom_integration_tests/test_fmcalias_derivation.rs +++ b/rom/dev/tests/rom_integration_tests/test_fmcalias_derivation.rs @@ -25,7 +25,7 @@ use caliptra_image_gen::ImageGenerator; use caliptra_image_types::IMAGE_BYTE_SIZE; use caliptra_test::swap_word_bytes; use openssl::hash::{Hasher, MessageDigest}; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes, TryFromBytes}; use crate::helpers; @@ -98,7 +98,7 @@ fn check_pcr_log_entry( pcr_data: &[u8], ) { let offset = pcr_entry_index * PCR_ENTRY_SIZE; - let entry = PcrLogEntry::read_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap(); + let (entry, _) = PcrLogEntry::ref_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap(); assert_eq!(entry.id, entry_id as u16); assert_eq!(entry.pcr_ids, pcr_ids); @@ -111,8 +111,8 @@ fn check_measurement_log_entry( measurement_req: &StashMeasurementReq, ) { let offset = measurement_entry_index * MEASUREMENT_ENTRY_SIZE; - let entry = - MeasurementLogEntry::read_from_prefix(measurement_entry_arr[offset..].as_bytes()).unwrap(); + let (entry, _) = + MeasurementLogEntry::ref_from_prefix(measurement_entry_arr[offset..].as_bytes()).unwrap(); assert_eq!(entry.pcr_entry.id, PcrLogEntryId::StashMeasurement as u16); assert_eq!(entry.pcr_entry.pcr_ids, PCR31_EXTENDED_ID); @@ -424,14 +424,14 @@ fn hash_pcr_log_entries(initial_pcr: &[u8; 48], pcr_entry_arr: &[u8], pcr_id: Pc break; } - let entry = PcrLogEntry::read_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap(); + let (entry, _) = PcrLogEntry::ref_from_prefix(pcr_entry_arr[offset..].as_bytes()).unwrap(); offset += PCR_ENTRY_SIZE; if (entry.pcr_ids & (1 << pcr_id as u8)) == 0 { continue; } - hash_pcr_log_entry(&entry, &mut pcr); + hash_pcr_log_entry(entry, &mut pcr); } pcr @@ -448,8 +448,8 @@ fn hash_measurement_log_entries(measurement_entry_arr: &[u8]) -> [u8; 48] { break; } - let entry = - MeasurementLogEntry::read_from_prefix(measurement_entry_arr[offset..].as_bytes()) + let (entry, _) = + MeasurementLogEntry::ref_from_prefix(measurement_entry_arr[offset..].as_bytes()) .unwrap(); offset += MEASUREMENT_ENTRY_SIZE; @@ -619,8 +619,8 @@ fn test_fuse_log() { let mut fuse_log_entry_offset = 0; // Check entry for VendorPubKeyIndex. - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!( fuse_log_entry.entry_id, @@ -631,8 +631,8 @@ fn test_fuse_log() { // Validate that the ID is VendorPubKeyRevocation fuse_log_entry_offset += core::mem::size_of::(); - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!( fuse_log_entry.entry_id, FuseLogEntryId::VendorEccPubKeyRevocation as u32 @@ -641,8 +641,8 @@ fn test_fuse_log() { // Validate the ManifestFmcSvn fuse_log_entry_offset += core::mem::size_of::(); - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!( fuse_log_entry.entry_id, FuseLogEntryId::ManifestFmcSvn as u32 @@ -651,8 +651,8 @@ fn test_fuse_log() { // Validate the ManifestReserved0 fuse_log_entry_offset += core::mem::size_of::(); - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!( fuse_log_entry.entry_id, FuseLogEntryId::ManifestReserved0 as u32 @@ -661,15 +661,15 @@ fn test_fuse_log() { // Validate the FuseFmcSvn fuse_log_entry_offset += core::mem::size_of::(); - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!(fuse_log_entry.entry_id, FuseLogEntryId::FuseFmcSvn as u32); assert_eq!(fuse_log_entry.log_data[0], FMC_SVN); // Validate the ManifestRtSvn fuse_log_entry_offset += core::mem::size_of::(); - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!( fuse_log_entry.entry_id, FuseLogEntryId::ManifestRtSvn as u32 @@ -678,8 +678,8 @@ fn test_fuse_log() { // Validate the ManifestReserved1 fuse_log_entry_offset += core::mem::size_of::(); - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!( fuse_log_entry.entry_id, FuseLogEntryId::ManifestReserved1 as u32 @@ -688,15 +688,15 @@ fn test_fuse_log() { // Validate the FuseRtSvn fuse_log_entry_offset += core::mem::size_of::(); - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!(fuse_log_entry.entry_id, FuseLogEntryId::FuseRtSvn as u32); assert_eq!(fuse_log_entry.log_data[0], FMC_SVN); // Validate the VendorLmsPubKeyIndex fuse_log_entry_offset += core::mem::size_of::(); - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!( fuse_log_entry.entry_id, FuseLogEntryId::VendorLmsPubKeyIndex as u32 @@ -705,8 +705,8 @@ fn test_fuse_log() { // Validate that the ID is VendorPubKeyRevocation fuse_log_entry_offset += core::mem::size_of::(); - let fuse_log_entry = - FuseLogEntry::read_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); + let (fuse_log_entry, _) = + FuseLogEntry::ref_from_prefix(fuse_entry_arr[fuse_log_entry_offset..].as_bytes()).unwrap(); assert_eq!( fuse_log_entry.entry_id, FuseLogEntryId::VendorLmsPubKeyRevocation as u32 @@ -741,7 +741,7 @@ fn test_fht_info() { hw.step_until_boot_status(u32::from(ColdResetComplete), true); let data = hw.mailbox_execute(0x1000_0003, &[]).unwrap().unwrap(); - let fht = FirmwareHandoffTable::read_from_prefix(data.as_bytes()).unwrap(); + let fht = FirmwareHandoffTable::try_ref_from_bytes(data.as_bytes()).unwrap(); assert_eq!(fht.ldevid_tbs_size, 552); assert_eq!(fht.fmcalias_tbs_size, 753); assert_eq!(fht.ldevid_tbs_addr, LDEVID_TBS_ORG); @@ -787,16 +787,16 @@ fn test_check_no_lms_info_in_datavault_on_lms_unavailable() { let mut coldresetentry4_offset = core::mem::size_of::() * 8; // Skip first 4 entries // Check LmsVendorPubKeyIndex datavault value. - let coldresetentry4_id = - u32::read_from_prefix(coldresetentry4_array[coldresetentry4_offset..].as_bytes()).unwrap(); + let (coldresetentry4_id, _) = + u32::ref_from_prefix(coldresetentry4_array[coldresetentry4_offset..].as_bytes()).unwrap(); assert_eq!( - coldresetentry4_id, + *coldresetentry4_id, ColdResetEntry4::LmsVendorPubKeyIndex as u32 ); coldresetentry4_offset += core::mem::size_of::(); - let coldresetentry4_value = - u32::read_from_prefix(coldresetentry4_array[coldresetentry4_offset..].as_bytes()).unwrap(); - assert_eq!(coldresetentry4_value, u32::MAX); + let (coldresetentry4_value, _) = + u32::ref_from_prefix(coldresetentry4_array[coldresetentry4_offset..].as_bytes()).unwrap(); + assert_eq!(*coldresetentry4_value, u32::MAX); } #[test] @@ -835,16 +835,16 @@ fn test_check_rom_cold_boot_status_reg() { let mut coldresetentry4_offset = core::mem::size_of::() * 2; // Skip first entry // Check RomColdBootStatus datavault value. - let coldresetentry4_id = - u32::read_from_prefix(coldresetentry4_array[coldresetentry4_offset..].as_bytes()).unwrap(); + let (coldresetentry4_id, _) = + u32::ref_from_prefix(coldresetentry4_array[coldresetentry4_offset..].as_bytes()).unwrap(); assert_eq!( - coldresetentry4_id, + *coldresetentry4_id, ColdResetEntry4::RomColdBootStatus as u32 ); coldresetentry4_offset += core::mem::size_of::(); - let coldresetentry4_value = - u32::read_from_prefix(coldresetentry4_array[coldresetentry4_offset..].as_bytes()).unwrap(); - assert_eq!(coldresetentry4_value, u32::from(ColdResetComplete)); + let (coldresetentry4_value, _) = + u32::ref_from_prefix(coldresetentry4_array[coldresetentry4_offset..].as_bytes()).unwrap(); + assert_eq!(*coldresetentry4_value, u32::from(ColdResetComplete)); } #[test] @@ -911,7 +911,7 @@ fn test_upload_single_measurement() { assert_eq!(pcr31.as_bytes(), expected_pcr); let data = hw.mailbox_execute(0x1000_0003, &[]).unwrap().unwrap(); - let fht = FirmwareHandoffTable::read_from_prefix(data.as_bytes()).unwrap(); + let fht = FirmwareHandoffTable::try_ref_from_bytes(data.as_bytes()).unwrap(); assert_eq!(fht.meas_log_index, 1); } @@ -992,7 +992,7 @@ fn test_upload_measurement_limit() { assert_eq!(pcr31.as_bytes(), expected_pcr); let data = hw.mailbox_execute(0x1000_0003, &[]).unwrap().unwrap(); - let fht = FirmwareHandoffTable::read_from_prefix(data.as_bytes()).unwrap(); + let fht = FirmwareHandoffTable::try_ref_from_bytes(data.as_bytes()).unwrap(); assert_eq!(fht.meas_log_index, MEASUREMENT_MAX_COUNT as u32); } @@ -1097,6 +1097,6 @@ fn test_upload_no_measurement() { assert_eq!(measurement_log.len(), 0); let data = hw.mailbox_execute(0x1000_0003, &[]).unwrap().unwrap(); - let fht = FirmwareHandoffTable::read_from_prefix(data.as_bytes()).unwrap(); + let fht = FirmwareHandoffTable::try_ref_from_bytes(data.as_bytes()).unwrap(); assert_eq!(fht.meas_log_index, 0); } diff --git a/rom/dev/tests/rom_integration_tests/test_idevid_derivation.rs b/rom/dev/tests/rom_integration_tests/test_idevid_derivation.rs index cb77cceca2..d1fbbdd125 100644 --- a/rom/dev/tests/rom_integration_tests/test_idevid_derivation.rs +++ b/rom/dev/tests/rom_integration_tests/test_idevid_derivation.rs @@ -9,7 +9,7 @@ use caliptra_image_types::ImageBundle; use openssl::pkey::{PKey, Public}; use openssl::x509::X509; use openssl::{rand::rand_bytes, x509::X509Req}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::helpers; @@ -146,7 +146,7 @@ fn verify_key( assert!(resp.len() <= std::mem::size_of::()); let mut cert_resp = GetLdevCertResp::default(); - cert_resp.as_bytes_mut()[..resp.len()].copy_from_slice(&resp); + cert_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp); // Extract the certificate from the response let cert_der = &cert_resp.data[..(cert_resp.data_size as usize)]; diff --git a/rom/dev/tests/rom_integration_tests/test_image_validation.rs b/rom/dev/tests/rom_integration_tests/test_image_validation.rs index 650c7ff6f7..280a56ade8 100644 --- a/rom/dev/tests/rom_integration_tests/test_image_validation.rs +++ b/rom/dev/tests/rom_integration_tests/test_image_validation.rs @@ -35,7 +35,7 @@ use openssl::rsa::Rsa; use openssl::x509::X509Req; use openssl::x509::X509; use std::str; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::helpers; diff --git a/rom/dev/tests/rom_integration_tests/test_mailbox_errors.rs b/rom/dev/tests/rom_integration_tests/test_mailbox_errors.rs index b9dd96a036..6f9486f49b 100644 --- a/rom/dev/tests/rom_integration_tests/test_mailbox_errors.rs +++ b/rom/dev/tests/rom_integration_tests/test_mailbox_errors.rs @@ -4,7 +4,7 @@ use caliptra_builder::ImageOptions; use caliptra_common::mailbox_api::{CommandId, MailboxReqHeader, StashMeasurementReq}; use caliptra_error::CaliptraError; use caliptra_hw_model::{Fuses, HwModel, ModelError}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::helpers; diff --git a/rom/dev/tests/rom_integration_tests/test_rom_integrity.rs b/rom/dev/tests/rom_integration_tests/test_rom_integrity.rs index db2344e52a..69e2074c44 100644 --- a/rom/dev/tests/rom_integration_tests/test_rom_integrity.rs +++ b/rom/dev/tests/rom_integration_tests/test_rom_integrity.rs @@ -8,7 +8,7 @@ use caliptra_builder::{ use caliptra_error::CaliptraError; use caliptra_hw_model::{BootParams, HwModel, InitParams}; use caliptra_image_types::RomInfo; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; fn find_rom_info_offset(rom: &[u8]) -> usize { for i in (0..rom.len()).step_by(64).rev() { @@ -55,8 +55,8 @@ fn test_rom_integrity_failure() { #[test] fn test_read_rom_info_from_fmc() { let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env()).unwrap(); - let rom_info_from_image = - RomInfo::read_from_prefix(&rom[find_rom_info_offset(&rom)..]).unwrap(); + let (rom_info_from_image, _) = + RomInfo::ref_from_prefix(&rom[find_rom_info_offset(&rom)..]).unwrap(); let image_bundle = caliptra_builder::build_and_sign_image( &TEST_FMC_WITH_UART, &APP_WITH_UART, @@ -78,13 +78,8 @@ fn test_read_rom_info_from_fmc() { ) .unwrap(); + let bytes = hw.mailbox_execute(0x1000_0008, &[]).unwrap().unwrap(); // 0x1000_0008 is test-fmc/read_rom_info() - let rom_info_from_fw = RomInfo::read_from( - hw.mailbox_execute(0x1000_0008, &[]) - .unwrap() - .unwrap() - .as_slice(), - ) - .unwrap(); + let rom_info_from_fw = RomInfo::ref_from_bytes(bytes.as_slice()).unwrap(); assert_eq!(rom_info_from_fw.as_bytes(), rom_info_from_image.as_bytes()); } diff --git a/rom/dev/tests/rom_integration_tests/test_update_reset.rs b/rom/dev/tests/rom_integration_tests/test_update_reset.rs index 234509d6db..2134358116 100644 --- a/rom/dev/tests/rom_integration_tests/test_update_reset.rs +++ b/rom/dev/tests/rom_integration_tests/test_update_reset.rs @@ -19,7 +19,7 @@ use caliptra_error::CaliptraError; use caliptra_hw_model::{BootParams, HwModel, InitParams}; use caliptra_image_fake_keys::VENDOR_CONFIG_KEY_0; use caliptra_image_gen::ImageGeneratorVendorConfig; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; const TEST_FMC_CMD_RESET_FOR_UPDATE: u32 = 0x1000_0004; const TEST_FMC_CMD_RESET_FOR_UPDATE_KEEP_MBOX_CMD: u32 = 0x1000_000B; @@ -456,16 +456,16 @@ fn test_check_rom_update_reset_status_reg() { let mut warmresetentry4_offset = core::mem::size_of::() * 8; // Skip first four entries // Check RomUpdateResetStatus datavault value. - let warmresetentry4_id = - u32::read_from_prefix(warmresetentry4_array[warmresetentry4_offset..].as_bytes()).unwrap(); + let (warmresetentry4_id, _) = + u32::ref_from_prefix(warmresetentry4_array[warmresetentry4_offset..].as_bytes()).unwrap(); assert_eq!( - warmresetentry4_id, + *warmresetentry4_id, WarmResetEntry4::RomUpdateResetStatus as u32 ); warmresetentry4_offset += core::mem::size_of::(); - let warmresetentry4_value = - u32::read_from_prefix(warmresetentry4_array[warmresetentry4_offset..].as_bytes()).unwrap(); - assert_eq!(warmresetentry4_value, u32::from(UpdateResetComplete)); + let (warmresetentry4_value, _) = + u32::ref_from_prefix(warmresetentry4_array[warmresetentry4_offset..].as_bytes()).unwrap(); + assert_eq!(*warmresetentry4_value, u32::from(UpdateResetComplete)); } #[test] diff --git a/rom/dev/tests/rom_integration_tests/test_version.rs b/rom/dev/tests/rom_integration_tests/test_version.rs index 662a616d53..1f65eb3540 100755 --- a/rom/dev/tests/rom_integration_tests/test_version.rs +++ b/rom/dev/tests/rom_integration_tests/test_version.rs @@ -6,7 +6,7 @@ use caliptra_common::mailbox_api::{ CommandId, FipsVersionResp, MailboxReqHeader, MailboxRespHeader, }; use caliptra_hw_model::{Fuses, HwModel}; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; use crate::helpers; @@ -28,7 +28,7 @@ fn test_version() { .unwrap() .unwrap(); - let version_resp = FipsVersionResp::read_from(response.as_bytes()).unwrap(); + let version_resp = FipsVersionResp::ref_from_bytes(response.as_bytes()).unwrap(); // Verify response checksum assert!(caliptra_common::checksum::verify_checksum( diff --git a/rom/dev/tests/rom_integration_tests/test_warm_reset.rs b/rom/dev/tests/rom_integration_tests/test_warm_reset.rs index 453f550ac2..8bebf36fb1 100644 --- a/rom/dev/tests/rom_integration_tests/test_warm_reset.rs +++ b/rom/dev/tests/rom_integration_tests/test_warm_reset.rs @@ -11,7 +11,7 @@ use caliptra_hw_model::DeviceLifecycle; use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams, SecurityState}; use caliptra_test::swap_word_bytes_inplace; use openssl::sha::sha384; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::helpers; diff --git a/rom/dev/tests/rom_integration_tests/tests_get_idev_csr.rs b/rom/dev/tests/rom_integration_tests/tests_get_idev_csr.rs index 2327d013ad..2802e6e54e 100644 --- a/rom/dev/tests/rom_integration_tests/tests_get_idev_csr.rs +++ b/rom/dev/tests/rom_integration_tests/tests_get_idev_csr.rs @@ -6,7 +6,7 @@ use caliptra_common::mailbox_api::{CommandId, GetIdevCsrResp, MailboxReqHeader}; use caliptra_drivers::MfgFlags; use caliptra_error::CaliptraError; use caliptra_hw_model::{Fuses, HwModel, ModelError}; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; use crate::helpers; @@ -36,7 +36,7 @@ fn test_get_csr() { .unwrap() .unwrap(); - let get_idv_csr_resp = GetIdevCsrResp::read_from(response.as_bytes()).unwrap(); + let get_idv_csr_resp = GetIdevCsrResp::ref_from_bytes(response.as_bytes()).unwrap(); assert!(caliptra_common::checksum::verify_checksum( get_idv_csr_resp.hdr.chksum, diff --git a/rom/dev/tools/test-fmc/src/main.rs b/rom/dev/tools/test-fmc/src/main.rs index a75f87ee9b..8fb22e8518 100644 --- a/rom/dev/tools/test-fmc/src/main.rs +++ b/rom/dev/tools/test-fmc/src/main.rs @@ -27,7 +27,7 @@ use caliptra_registers::pv::PvReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_x509::{Ecdsa384CertBuilder, Ecdsa384Signature, FmcAliasCertTbs, LocalDevIdCertTbs}; use ureg::RealMmioMut; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; #[cfg(not(feature = "std"))] core::arch::global_asm!(include_str!("start.S")); diff --git a/runtime/src/authorize_and_stash.rs b/runtime/src/authorize_and_stash.rs index 748cc5147e..ad70c999f0 100644 --- a/runtime/src/authorize_and_stash.rs +++ b/runtime/src/authorize_and_stash.rs @@ -43,7 +43,7 @@ use dpe::{ response::DpeErrorCode, }; use memoffset::offset_of; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; 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. @@ -54,7 +54,7 @@ impl AuthorizeAndStashCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { - if let Some(cmd) = AuthorizeAndStashReq::read_from(cmd_args) { + if let Ok(cmd) = AuthorizeAndStashReq::ref_from_bytes(cmd_args) { if ImageHashSource::from(cmd.source) != ImageHashSource::InRequest { Err(CaliptraError::RUNTIME_AUTH_AND_STASH_UNSUPPORTED_IMAGE_SOURCE)?; } diff --git a/runtime/src/certify_key_extended.rs b/runtime/src/certify_key_extended.rs index 44e4d0a2bd..78a738a7da 100644 --- a/runtime/src/certify_key_extended.rs +++ b/runtime/src/certify_key_extended.rs @@ -25,7 +25,7 @@ use dpe::{ commands::{CertifyKeyCmd, Command, CommandExecution}, response::Response, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; use crate::{ CptraDpeTypes, DpeCrypto, DpeEnv, DpePlatform, Drivers, PauserPrivileges, MAX_CERT_CHAIN_SIZE, @@ -36,8 +36,8 @@ pub struct CertifyKeyExtendedCmd; impl CertifyKeyExtendedCmd { #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { - let cmd = CertifyKeyExtendedReq::read_from(cmd_args) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; + 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 @@ -85,8 +85,8 @@ impl CertifyKeyExtendedCmd { }; let mut dpe = &mut pdata.dpe; - let certify_key_cmd = CertifyKeyCmd::read_from(&cmd.certify_key_req[..]) - .ok_or(CaliptraError::RUNTIME_DPE_COMMAND_DESERIALIZATION_FAILED)?; + let certify_key_cmd = CertifyKeyCmd::ref_from_bytes(&cmd.certify_key_req[..]) + .map_err(|_| CaliptraError::RUNTIME_DPE_COMMAND_DESERIALIZATION_FAILED)?; let locality = drivers.mbox.user(); let resp = certify_key_cmd.execute(dpe, &mut env, locality); diff --git a/runtime/src/dice.rs b/runtime/src/dice.rs index cca1659125..4ec03584e9 100644 --- a/runtime/src/dice.rs +++ b/runtime/src/dice.rs @@ -24,7 +24,7 @@ use caliptra_drivers::{ PersistentData, }; use caliptra_x509::{Ecdsa384CertBuilder, Ecdsa384Signature}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; pub struct IDevIdCertCmd; impl IDevIdCertCmd { @@ -32,7 +32,7 @@ impl IDevIdCertCmd { pub(crate) fn execute(cmd_args: &[u8]) -> CaliptraResult { if cmd_args.len() <= core::mem::size_of::() { let mut cmd = GetIdevCertReq::default(); - cmd.as_bytes_mut()[..cmd_args.len()].copy_from_slice(cmd_args); + cmd.as_mut_bytes()[..cmd_args.len()].copy_from_slice(cmd_args); // Validate tbs if cmd.tbs_size as usize > cmd.tbs.len() { diff --git a/runtime/src/dpe_crypto.rs b/runtime/src/dpe_crypto.rs index 1d11761a4b..1093469f85 100644 --- a/runtime/src/dpe_crypto.rs +++ b/runtime/src/dpe_crypto.rs @@ -23,7 +23,7 @@ use caliptra_drivers::{ KeyVault, KeyWriteArgs, Sha384, Sha384DigestOp, Trng, }; use crypto::{AlgLen, Crypto, CryptoBuf, CryptoError, Digest, EcdsaPub, EcdsaSig, Hasher, HmacSig}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use zeroize::Zeroize; pub struct DpeCrypto<'a> { diff --git a/runtime/src/dpe_platform.rs b/runtime/src/dpe_platform.rs index ab53d6122f..46abb3080d 100644 --- a/runtime/src/dpe_platform.rs +++ b/runtime/src/dpe_platform.rs @@ -28,7 +28,7 @@ use platform::{ MAX_CHUNK_SIZE, MAX_ISSUER_NAME_SIZE, MAX_KEY_IDENTIFIER_SIZE, MAX_OTHER_NAME_SIZE, MAX_SN_SIZE, }; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::{subject_alt_name::AddSubjectAltNameCmd, MAX_CERT_CHAIN_SIZE}; diff --git a/runtime/src/drivers.rs b/runtime/src/drivers.rs index edc4f81cfb..107aa4fc21 100644 --- a/runtime/src/drivers.rs +++ b/runtime/src/drivers.rs @@ -59,7 +59,7 @@ use dpe::{ use core::cmp::Ordering::{Equal, Greater}; use crypto::{AlgLen, Crypto, CryptoBuf, Hasher}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; #[derive(PartialEq, Clone)] pub enum PauserPrivileges { diff --git a/runtime/src/fips.rs b/runtime/src/fips.rs index d4600503a4..82f8a3825e 100644 --- a/runtime/src/fips.rs +++ b/runtime/src/fips.rs @@ -71,7 +71,7 @@ pub mod fips_self_test_cmd { use caliptra_drivers::{ResetReason, ShaAccLockState}; use caliptra_image_types::{ImageTocEntry, RomInfo}; use caliptra_image_verify::ImageVerifier; - use zerocopy::AsBytes; + use zerocopy::IntoBytes; // Helper function to create a slice from a memory region unsafe fn create_slice(toc: &ImageTocEntry) -> &'static [u8] { diff --git a/runtime/src/get_idev_csr.rs b/runtime/src/get_idev_csr.rs index 5ec4b2ef60..107fab3d96 100644 --- a/runtime/src/get_idev_csr.rs +++ b/runtime/src/get_idev_csr.rs @@ -13,44 +13,40 @@ use caliptra_error::{CaliptraError, CaliptraResult}; use caliptra_drivers::IdevIdCsr; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; pub struct GetIdevCsrCmd; impl GetIdevCsrCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { - if let Some(cmd) = GetIdevCsrReq::read_from(cmd_args) { - let csr_persistent_mem = &drivers.persistent_data.get().idevid_csr; - - match csr_persistent_mem.get_csr_len() { - IdevIdCsr::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 mut resp = GetIdevCsrResp { - data_size: len, - ..Default::default() - }; - // 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 `MAX_CSR_SIZE`, which is the max - // size of the buffer in `GetIdevCsrResp` - resp.data[..resp.data_size as usize].copy_from_slice(csr); - - Ok(MailboxResp::GetIdevCsr(resp)) - } + let cmd = GetIdevCsrReq::ref_from_bytes(cmd_args) + .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; + let csr_persistent_mem = &drivers.persistent_data.get().idevid_csr; + + match csr_persistent_mem.get_csr_len() { + IdevIdCsr::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 mut resp = GetIdevCsrResp { + data_size: len, + ..Default::default() + }; + // 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 `MAX_CSR_SIZE`, which is the max + // size of the buffer in `GetIdevIdCsrResp` + resp.data[..resp.data_size as usize].copy_from_slice(csr); + + Ok(MailboxResp::GetIdevCsr(resp)) } - } else { - Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY) } } } diff --git a/runtime/src/hmac.rs b/runtime/src/hmac.rs index 37f3b48a44..25e43c5326 100644 --- a/runtime/src/hmac.rs +++ b/runtime/src/hmac.rs @@ -20,7 +20,7 @@ use caliptra_drivers::{ KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, }; use caliptra_error::CaliptraResult; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use zeroize::Zeroize; use crate::Drivers; diff --git a/runtime/src/invoke_dpe.rs b/runtime/src/invoke_dpe.rs index b65fa6f5cf..cd30837368 100644 --- a/runtime/src/invoke_dpe.rs +++ b/runtime/src/invoke_dpe.rs @@ -27,7 +27,7 @@ use dpe::{ response::{Response, ResponseHdr}, DpeInstance, U8Bool, MAX_HANDLES, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; pub struct InvokeDpeCmd; impl InvokeDpeCmd { @@ -36,7 +36,7 @@ impl InvokeDpeCmd { pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { if cmd_args.len() <= core::mem::size_of::() { let mut cmd = InvokeDpeReq::default(); - cmd.as_bytes_mut()[..cmd_args.len()].copy_from_slice(cmd_args); + cmd.as_mut_bytes()[..cmd_args.len()].copy_from_slice(cmd_args); // Validate data length if cmd.data_size as usize > cmd.data.len() { @@ -76,6 +76,11 @@ impl InvokeDpeCmd { }; let locality = drivers.mbox.user(); + // This check already happened, but without it the compiler believes the below slice is + // out of bounds. + if cmd.data_size as usize > cmd.data.len() { + return Err(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS); + } let command = Command::deserialize(&cmd.data[..cmd.data_size as usize]) .map_err(|_| CaliptraError::RUNTIME_DPE_COMMAND_DESERIALIZATION_FAILED)?; let flags = pdata.manifest1.header.flags; @@ -90,7 +95,7 @@ impl InvokeDpeCmd { )), Command::InitCtx(cmd) => { // InitCtx can only create new contexts if they are simulation contexts. - if InitCtxCmd::flag_is_simulation(&cmd) { + if InitCtxCmd::flag_is_simulation(cmd) { dpe_context_threshold_err?; } cmd.execute(dpe, &mut env, locality) @@ -99,10 +104,10 @@ impl InvokeDpeCmd { // 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) { + if !DeriveContextCmd::is_recursive(cmd) { dpe_context_threshold_err?; } - if DeriveContextCmd::changes_locality(&cmd) + if DeriveContextCmd::changes_locality(cmd) && cmd.target_locality == pl0_pauser && caller_privilege_level != PauserPrivileges::PL0 { diff --git a/runtime/src/mailbox.rs b/runtime/src/mailbox.rs index 2a4620b67a..d6c93d93c2 100644 --- a/runtime/src/mailbox.rs +++ b/runtime/src/mailbox.rs @@ -12,6 +12,7 @@ Abstract: --*/ +use core::mem::size_of; use core::slice; use caliptra_drivers::{memory_layout, CaliptraResult}; @@ -20,7 +21,7 @@ use caliptra_registers::mbox::{ enums::{MboxFsmE, MboxStatusE}, MboxCsr, }; -use zerocopy::{AsBytes, LayoutVerified, Unalign}; +use zerocopy::{FromBytes, IntoBytes, Unalign}; use crate::CommandId; @@ -133,12 +134,12 @@ impl Mailbox { /// Copies word-aligned `buf` to the mailbox pub fn copy_bytes_to_mbox(&mut self, buf: &[u8]) -> CaliptraResult<()> { - let (buf_words, suffix) = - LayoutVerified::new_slice_unaligned_from_prefix(buf, buf.len() / 4).unwrap(); - self.copy_words_to_mbox(&buf_words); - if !suffix.is_empty() { + let count = buf.len() / size_of::(); + let (buf_words, suffix) = <[Unalign]>::ref_from_prefix_with_elems(buf, count).unwrap(); + self.copy_words_to_mbox(buf_words); + if !suffix.is_empty() && suffix.len() <= size_of::() { let mut last_word = 0_u32; - last_word.as_bytes_mut()[..suffix.len()].copy_from_slice(suffix); + last_word.as_mut_bytes()[..suffix.len()].copy_from_slice(suffix); self.copy_words_to_mbox(&[Unalign::new(last_word)]); } Ok(()) diff --git a/runtime/src/packet.rs b/runtime/src/packet.rs index 1a925fb32b..3bc703efb4 100644 --- a/runtime/src/packet.rs +++ b/runtime/src/packet.rs @@ -16,7 +16,7 @@ use caliptra_drivers::CaliptraResult; use caliptra_common::mailbox_api::{MailboxReqHeader, MailboxResp}; use caliptra_drivers::CaliptraError; -use zerocopy::{AsBytes, LayoutVerified}; +use zerocopy::{FromBytes, IntoBytes}; #[derive(Debug, Clone)] pub struct Packet { @@ -69,11 +69,10 @@ impl Packet { // Assumes chksum is always offset 0 let payload_bytes = packet.as_bytes()?; - let req_hdr: &MailboxReqHeader = LayoutVerified::<&[u8], MailboxReqHeader>::new( + let req_hdr: &MailboxReqHeader = MailboxReqHeader::ref_from_bytes( &payload_bytes[..core::mem::size_of::()], ) - .ok_or(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)? - .into_ref(); + .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; if !caliptra_common::checksum::verify_checksum( req_hdr.chksum, diff --git a/runtime/src/pcr.rs b/runtime/src/pcr.rs index 1cbd1a1875..2fa9d7552c 100644 --- a/runtime/src/pcr.rs +++ b/runtime/src/pcr.rs @@ -26,8 +26,8 @@ impl IncrementPcrResetCounterCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { - let cmd = IncrementPcrResetCounterReq::read_from(cmd_args) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; + 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)?; @@ -48,8 +48,8 @@ impl GetPcrQuoteCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_bytes: &[u8]) -> CaliptraResult { - let args: QuotePcrsReq = QuotePcrsReq::read_from(cmd_bytes) - .ok_or(CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; + let args: &QuotePcrsReq = QuotePcrsReq::ref_from_bytes(cmd_bytes) + .map_err(|_| CaliptraError::RUNTIME_MAILBOX_INVALID_PARAMS)?; let pcr_hash = drivers.sha384.gen_pcr_hash(args.nonce.into())?; let signature = drivers.ecc384.pcr_sign_flow(&mut drivers.trng)?; @@ -77,8 +77,8 @@ impl ExtendPcrCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { - let cmd = - ExtendPcrReq::read_from(cmd_args).ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; + 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)?; diff --git a/runtime/src/populate_idev.rs b/runtime/src/populate_idev.rs index 7c397ce3aa..61da55e436 100644 --- a/runtime/src/populate_idev.rs +++ b/runtime/src/populate_idev.rs @@ -15,7 +15,7 @@ Abstract: use arrayvec::ArrayVec; use caliptra_common::mailbox_api::{MailboxResp, PopulateIdevCertReq}; use caliptra_error::{CaliptraError, CaliptraResult}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::{Drivers, MAX_CERT_CHAIN_SIZE, PL0_PAUSER_FLAG}; @@ -25,7 +25,7 @@ impl PopulateIDevIdCertCmd { pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { if cmd_args.len() <= core::mem::size_of::() { let mut cmd = PopulateIdevCertReq::default(); - cmd.as_bytes_mut()[..cmd_args.len()].copy_from_slice(cmd_args); + 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() { diff --git a/runtime/src/set_auth_manifest.rs b/runtime/src/set_auth_manifest.rs index e3a50849da..3ca77d406c 100644 --- a/runtime/src/set_auth_manifest.rs +++ b/runtime/src/set_auth_manifest.rs @@ -43,7 +43,7 @@ use dpe::{ response::DpeErrorCode, }; use memoffset::offset_of; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; use zeroize::Zeroize; pub struct SetAuthManifestCmd; @@ -425,7 +425,7 @@ impl SetAuthManifestCmd { metadata_persistent.zeroize(); // Copy the image metadata collection to the persistent data. - metadata_persistent.as_bytes_mut()[..buf.len()].copy_from_slice(buf); + metadata_persistent.as_mut_bytes()[..buf.len()].copy_from_slice(buf); Ok(()) } @@ -489,8 +489,8 @@ impl SetAuthManifestCmd { let preamble_size = size_of::(); let auth_manifest_preamble = { let err = CaliptraError::RUNTIME_AUTH_MANIFEST_PREAMBLE_SIZE_LT_MIN; - AuthManifestPreamble::read_from(manifest_buf.get(..preamble_size).ok_or(err)?) - .ok_or(err)? + let bytes = manifest_buf.get(..preamble_size).ok_or(err)?; + AuthManifestPreamble::ref_from_bytes(bytes).map_err(|_| err)? }; // Check if the preamble has the required marker. @@ -506,7 +506,7 @@ impl SetAuthManifestCmd { let persistent_data = drivers.persistent_data.get_mut(); // Verify the vendor signed data (vendor public keys + flags). Self::verify_vendor_signed_data( - &auth_manifest_preamble, + auth_manifest_preamble, &persistent_data.manifest1.preamble, &mut drivers.sha384, &mut drivers.ecc384, @@ -516,7 +516,7 @@ impl SetAuthManifestCmd { // Verify the owner public keys. Self::verify_owner_pub_keys( - &auth_manifest_preamble, + auth_manifest_preamble, &persistent_data.manifest1.preamble, &mut drivers.sha384, &mut drivers.ecc384, @@ -528,7 +528,7 @@ impl SetAuthManifestCmd { manifest_buf .get(preamble_size..) .ok_or(CaliptraError::RUNTIME_AUTH_MANIFEST_IMAGE_METADATA_LIST_INVALID_SIZE)?, - &auth_manifest_preamble, + auth_manifest_preamble, &mut persistent_data.auth_manifest_image_metadata_col, &mut drivers.sha384, &mut drivers.ecc384, diff --git a/runtime/src/stash_measurement.rs b/runtime/src/stash_measurement.rs index a72538ab31..22eb960273 100644 --- a/runtime/src/stash_measurement.rs +++ b/runtime/src/stash_measurement.rs @@ -25,7 +25,7 @@ use dpe::{ dpe_instance::DpeEnv, response::DpeErrorCode, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; pub struct StashMeasurementCmd; impl StashMeasurementCmd { @@ -115,8 +115,8 @@ impl StashMeasurementCmd { } pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { - let cmd = StashMeasurementReq::read_from(cmd_args) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; + 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)?; diff --git a/runtime/src/subject_alt_name.rs b/runtime/src/subject_alt_name.rs index 68166d09f8..daad1e127b 100644 --- a/runtime/src/subject_alt_name.rs +++ b/runtime/src/subject_alt_name.rs @@ -17,7 +17,7 @@ use core::str::from_utf8; use arrayvec::ArrayVec; use caliptra_common::mailbox_api::{AddSubjectAltNameReq, MailboxResp}; use caliptra_error::{CaliptraError, CaliptraResult}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::{Drivers, MAX_CERT_CHAIN_SIZE, PL0_PAUSER_FLAG}; @@ -31,7 +31,7 @@ impl AddSubjectAltNameCmd { pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { if cmd_args.len() <= core::mem::size_of::() { let mut cmd = AddSubjectAltNameReq::default(); - cmd.as_bytes_mut()[..cmd_args.len()].copy_from_slice(cmd_args); + 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() { diff --git a/runtime/src/tagging.rs b/runtime/src/tagging.rs index 99e681e1cb..21c5b5459c 100644 --- a/runtime/src/tagging.rs +++ b/runtime/src/tagging.rs @@ -33,8 +33,8 @@ impl TagTciCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { - let cmd = - TagTciReq::read_from(cmd_args).ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; + let cmd = TagTciReq::ref_from_bytes(cmd_args) + .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; let pdata_mut = drivers.persistent_data.get_mut(); let mut dpe = &mut pdata_mut.dpe; let mut context_has_tag = &mut pdata_mut.context_has_tag; @@ -72,8 +72,8 @@ impl GetTaggedTciCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &Drivers, cmd_args: &[u8]) -> CaliptraResult { - let cmd = GetTaggedTciReq::read_from(cmd_args) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; + 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.context_has_tag; let context_tags = &persistent_data.context_tags; diff --git a/runtime/src/verify.rs b/runtime/src/verify.rs index 3ac5350f26..c3a84adfe6 100644 --- a/runtime/src/verify.rs +++ b/runtime/src/verify.rs @@ -22,7 +22,7 @@ use caliptra_drivers::{ use caliptra_lms_types::{ LmotsAlgorithmType, LmotsSignature, LmsAlgorithmType, LmsPublicKey, LmsSignature, }; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use zerocopy::{BigEndian, FromBytes, LittleEndian, U32}; pub struct EcdsaVerifyCmd; @@ -30,8 +30,8 @@ impl EcdsaVerifyCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { - let cmd = EcdsaVerifyReq::read_from(cmd_args) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; + let cmd = EcdsaVerifyReq::ref_from_bytes(cmd_args) + .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; // Won't panic, full_digest is always larger than digest let full_digest = drivers.sha_acc.regs().digest().read(); let mut digest = Array4x12::default(); @@ -78,8 +78,8 @@ impl LmsVerifyCmd { const LMS_ALGORITHM_TYPE: LmsAlgorithmType = LmsAlgorithmType::new(12); const LMOTS_ALGORITHM_TYPE: LmotsAlgorithmType = LmotsAlgorithmType::new(7); - let cmd = - LmsVerifyReq::read_from(cmd_args).ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; + let cmd = LmsVerifyReq::ref_from_bytes(cmd_args) + .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; // Get the digest from the SHA accelerator let msg_digest_be = drivers.sha_acc.regs().digest().truncate::<12>().read(); // Flip the endianness since LMS treats this as raw message bytes @@ -90,21 +90,21 @@ impl LmsVerifyCmd { let lms_pub_key: LmsPublicKey = LmsPublicKey { id: cmd.pub_key_id, - digest: <[U32; LMS_N]>::read_from(&cmd.pub_key_digest[..]) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?, + digest: <[U32; LMS_N]>::read_from_bytes(&cmd.pub_key_digest[..]) + .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?, tree_type: LmsAlgorithmType::new(cmd.pub_key_tree_type), otstype: LmotsAlgorithmType::new(cmd.pub_key_ots_type), }; let lms_sig: LmsSignature = LmsSignature { q: >::from(cmd.signature_q), - ots: >::read_from(&cmd.signature_ots[..]) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?, + ots: >::read_from_bytes(&cmd.signature_ots[..]) + .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?, tree_type: LmsAlgorithmType::new(cmd.signature_tree_type), - tree_path: <[[U32; LMS_N]; LMS_H]>::read_from( + tree_path: <[[U32; LMS_N]; LMS_H]>::read_from_bytes( &cmd.signature_tree_path[..], ) - .ok_or(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?, + .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?, }; // Check that fixed params are correct diff --git a/runtime/test-fw/src/mbox_responder.rs b/runtime/test-fw/src/mbox_responder.rs index 39b85aeb4a..1a52e70404 100644 --- a/runtime/test-fw/src/mbox_responder.rs +++ b/runtime/test-fw/src/mbox_responder.rs @@ -17,7 +17,7 @@ use caliptra_runtime::{ MAX_HANDLES, }; use caliptra_test_harness::{runtime_handlers, test_suite}; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes, TryFromBytes}; const OPCODE_READ_RT_FW_JOURNEY: u32 = 0x1000_0000; const OPCODE_READ_MBOX_PAUSER_HASH: u32 = 0x2000_0000; @@ -167,16 +167,22 @@ pub fn handle_command(drivers: &mut Drivers) -> CaliptraResult { CommandId(OPCODE_CORRUPT_CONTEXT_TAGS) => { let input_bytes = read_request(&drivers.mbox); - let corrupted_context_tags = <[u32; MAX_HANDLES]>::read_from(input_bytes).unwrap(); + let corrupted_context_tags = + <[u32; MAX_HANDLES]>::read_from_bytes(input_bytes).unwrap(); drivers.persistent_data.get_mut().context_tags = corrupted_context_tags; write_response(&mut drivers.mbox, &[]); } CommandId(OPCODE_CORRUPT_CONTEXT_HAS_TAG) => { let input_bytes = read_request(&drivers.mbox); + // NOTE: `read_from_bytes` is not used here to avoid an alignment exception. let corrupted_context_has_tag = - <[U8Bool; MAX_HANDLES]>::read_from(input_bytes).unwrap(); - drivers.persistent_data.get_mut().context_has_tag = corrupted_context_has_tag; + <[U8Bool; MAX_HANDLES]>::ref_from_bytes(input_bytes).unwrap(); + drivers + .persistent_data + .get_mut() + .context_has_tag + .clone_from_slice(corrupted_context_has_tag); write_response(&mut drivers.mbox, &[]); } CommandId(OPCODE_READ_DPE_INSTANCE) => { @@ -188,7 +194,7 @@ pub fn handle_command(drivers: &mut Drivers) -> CaliptraResult { CommandId(OPCODE_CORRUPT_DPE_INSTANCE) => { let input_bytes = read_request(&drivers.mbox); - let corrupted_dpe = DpeInstance::read_from(input_bytes).unwrap(); + let corrupted_dpe = DpeInstance::try_read_from_bytes(input_bytes).unwrap(); drivers.persistent_data.get_mut().dpe = corrupted_dpe; write_response(&mut drivers.mbox, &[]); } diff --git a/runtime/test-fw/src/mock_rt_test_interactive.rs b/runtime/test-fw/src/mock_rt_test_interactive.rs index ead4f66871..c71b8ad127 100644 --- a/runtime/test-fw/src/mock_rt_test_interactive.rs +++ b/runtime/test-fw/src/mock_rt_test_interactive.rs @@ -12,7 +12,7 @@ use caliptra_registers::pv::PvReg; use caliptra_registers::{mbox::enums::MboxStatusE, soc_ifc::SocIfcReg}; use caliptra_runtime::{mailbox::Mailbox, Drivers, RtBootStatus}; use caliptra_test_harness::{runtime_handlers, test_suite}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; const OPCODE_FW_LOAD: u32 = CommandId::FIRMWARE_LOAD.0; diff --git a/runtime/tests/runtime_integration_tests/common.rs b/runtime/tests/runtime_integration_tests/common.rs index b3417d804b..020df5fc08 100644 --- a/runtime/tests/runtime_integration_tests/common.rs +++ b/runtime/tests/runtime_integration_tests/common.rs @@ -34,7 +34,7 @@ use openssl::{ x509::{X509Builder, X509}, x509::{X509Name, X509NameBuilder}, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; 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, @@ -167,7 +167,7 @@ fn get_cmd_id(dpe_cmd: &mut Command) -> u32 { } } -fn as_bytes(dpe_cmd: &mut Command) -> &[u8] { +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(), @@ -183,19 +183,27 @@ fn as_bytes(dpe_cmd: &mut Command) -> &[u8] { fn parse_dpe_response(dpe_cmd: &mut Command, resp_bytes: &[u8]) -> Response { match dpe_cmd { Command::CertifyKey(_) => { - Response::CertifyKey(CertifyKeyResp::read_from(resp_bytes).unwrap()) + Response::CertifyKey(CertifyKeyResp::read_from_bytes(resp_bytes).unwrap()) } Command::DeriveContext(_) => { - Response::DeriveContext(DeriveContextResp::read_from(resp_bytes).unwrap()) + Response::DeriveContext(DeriveContextResp::read_from_bytes(resp_bytes).unwrap()) } - Command::GetCertificateChain(_) => { - Response::GetCertificateChain(GetCertificateChainResp::read_from(resp_bytes).unwrap()) + Command::GetCertificateChain(_) => Response::GetCertificateChain( + GetCertificateChainResp::read_from_bytes(resp_bytes).unwrap(), + ), + Command::DestroyCtx(_) => { + Response::DestroyCtx(ResponseHdr::read_from_bytes(resp_bytes).unwrap()) + } + Command::GetProfile => { + Response::GetProfile(GetProfileResp::read_from_bytes(resp_bytes).unwrap()) + } + Command::InitCtx(_) => { + Response::InitCtx(NewHandleResp::read_from_bytes(resp_bytes).unwrap()) + } + Command::RotateCtx(_) => { + Response::RotateCtx(NewHandleResp::read_from_bytes(resp_bytes).unwrap()) } - Command::DestroyCtx(_) => Response::DestroyCtx(ResponseHdr::read_from(resp_bytes).unwrap()), - Command::GetProfile => Response::GetProfile(GetProfileResp::read_from(resp_bytes).unwrap()), - Command::InitCtx(_) => Response::InitCtx(NewHandleResp::read_from(resp_bytes).unwrap()), - Command::RotateCtx(_) => Response::RotateCtx(NewHandleResp::read_from(resp_bytes).unwrap()), - Command::Sign(_) => Response::Sign(SignResp::read_from(resp_bytes).unwrap()), + Command::Sign(_) => Response::Sign(SignResp::read_from_bytes(resp_bytes).unwrap()), } } @@ -236,7 +244,7 @@ pub fn execute_dpe_cmd( assert!(resp.len() <= std::mem::size_of::()); let mut resp_hdr = InvokeDpeResp::default(); - resp_hdr.as_bytes_mut()[..resp.len()].copy_from_slice(&resp); + resp_hdr.as_mut_bytes()[..resp.len()].copy_from_slice(&resp); assert!(caliptra_common::checksum::verify_checksum( resp_hdr.hdr.chksum, @@ -247,7 +255,7 @@ pub fn execute_dpe_cmd( let resp_bytes = &resp_hdr.data[..resp_hdr.data_size as usize]; Some(match expected_result { DpeResult::Success => parse_dpe_response(dpe_cmd, resp_bytes), - DpeResult::DpeCmdFailure => Response::Error(ResponseHdr::read_from(resp_bytes).unwrap()), + DpeResult::DpeCmdFailure => Response::Error(ResponseHdr::read_from_bytes(resp_bytes).unwrap()), DpeResult::MboxCmdFailure(_) => unreachable!("If MboxCmdFailure is the expected DPE result, the function would have returned None earlier."), }) } @@ -281,7 +289,7 @@ pub fn get_fmc_alias_cert(model: &mut DefaultHwModel) -> GetFmcAliasCertResp { .unwrap(); assert!(resp.len() <= std::mem::size_of::()); let mut fmc_resp = GetFmcAliasCertResp::default(); - fmc_resp.as_bytes_mut()[..resp.len()].copy_from_slice(&resp); + fmc_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp); fmc_resp } @@ -298,6 +306,6 @@ pub fn get_rt_alias_cert(model: &mut DefaultHwModel) -> GetRtAliasCertResp { .unwrap(); assert!(resp.len() <= std::mem::size_of::()); let mut rt_resp = GetRtAliasCertResp::default(); - rt_resp.as_bytes_mut()[..resp.len()].copy_from_slice(&resp); + rt_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp); rt_resp } diff --git a/runtime/tests/runtime_integration_tests/test_authorize_and_stash.rs b/runtime/tests/runtime_integration_tests/test_authorize_and_stash.rs index cbe9fbc3cd..b246aa3f36 100644 --- a/runtime/tests/runtime_integration_tests/test_authorize_and_stash.rs +++ b/runtime/tests/runtime_integration_tests/test_authorize_and_stash.rs @@ -18,8 +18,7 @@ use caliptra_hw_model::{DefaultHwModel, HwModel}; use caliptra_runtime::RtBootStatus; use caliptra_runtime::{IMAGE_AUTHORIZED, IMAGE_NOT_AUTHORIZED}; use sha2::{Digest, Sha384}; -use zerocopy::AsBytes; -use zerocopy::FromBytes; +use zerocopy::{FromBytes, IntoBytes}; const IMAGE_HASH_MISMATCH: u32 = 0x8BFB95CB; // FW ID matched, but image digest mismatched. @@ -100,7 +99,7 @@ fn test_authorize_and_stash_cmd_deny_authorization() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = AuthorizeAndStashResp::ref_from_bytes(resp.as_slice()).unwrap(); assert_eq!( authorize_and_stash_resp.auth_req_result, IMAGE_NOT_AUTHORIZED @@ -159,7 +158,7 @@ fn test_authorize_and_stash_cmd_success() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = AuthorizeAndStashResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!(authorize_and_stash_resp.auth_req_result, IMAGE_AUTHORIZED); // create a new fw image with the runtime replaced by the mbox responder @@ -214,7 +213,7 @@ fn test_authorize_and_stash_cmd_deny_authorization_no_hash_or_id() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = AuthorizeAndStashResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!( authorize_and_stash_resp.auth_req_result, IMAGE_NOT_AUTHORIZED @@ -242,7 +241,7 @@ fn test_authorize_and_stash_cmd_deny_authorization_wrong_id_no_hash() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = AuthorizeAndStashResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!( authorize_and_stash_resp.auth_req_result, IMAGE_NOT_AUTHORIZED @@ -271,7 +270,7 @@ fn test_authorize_and_stash_cmd_deny_authorization_wrong_hash() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = AuthorizeAndStashResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!( authorize_and_stash_resp.auth_req_result, IMAGE_HASH_MISMATCH @@ -300,7 +299,7 @@ fn test_authorize_and_stash_cmd_success_skip_auth() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = AuthorizeAndStashResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!(authorize_and_stash_resp.auth_req_result, IMAGE_AUTHORIZED); } @@ -338,7 +337,7 @@ fn test_authorize_and_stash_fwid_0() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = AuthorizeAndStashResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!(authorize_and_stash_resp.auth_req_result, IMAGE_AUTHORIZED); } @@ -376,7 +375,7 @@ fn test_authorize_and_stash_fwid_127() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = AuthorizeAndStashResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!(authorize_and_stash_resp.auth_req_result, IMAGE_AUTHORIZED); } @@ -403,7 +402,8 @@ fn test_authorize_and_stash_cmd_deny_second_bad_hash() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = + AuthorizeAndStashResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!(authorize_and_stash_resp.auth_req_result, IMAGE_AUTHORIZED); } @@ -438,7 +438,8 @@ fn test_authorize_and_stash_cmd_deny_second_bad_hash() { .unwrap() .expect("We should have received a response"); - let authorize_and_stash_resp = AuthorizeAndStashResp::read_from(resp.as_slice()).unwrap(); + let authorize_and_stash_resp = + AuthorizeAndStashResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!( authorize_and_stash_resp.auth_req_result, IMAGE_HASH_MISMATCH diff --git a/runtime/tests/runtime_integration_tests/test_boot.rs b/runtime/tests/runtime_integration_tests/test_boot.rs index 55baa7d047..7fc0875e7c 100644 --- a/runtime/tests/runtime_integration_tests/test_boot.rs +++ b/runtime/tests/runtime_integration_tests/test_boot.rs @@ -11,7 +11,7 @@ use caliptra_common::{ use caliptra_hw_model::{BootParams, Fuses, HwModel, InitParams, SecurityState}; use caliptra_runtime::RtBootStatus; use sha2::{Digest, Sha384}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::common::{run_rt_test, RuntimeTestArgs, DEFAULT_APP_VERSION, DEFAULT_FMC_VERSION}; diff --git a/runtime/tests/runtime_integration_tests/test_certify_key_extended.rs b/runtime/tests/runtime_integration_tests/test_certify_key_extended.rs index 400b352486..393e9f5a1c 100644 --- a/runtime/tests/runtime_integration_tests/test_certify_key_extended.rs +++ b/runtime/tests/runtime_integration_tests/test_certify_key_extended.rs @@ -15,7 +15,7 @@ use dpe::{ use x509_parser::{ certificate::X509Certificate, extensions::GeneralName, oid_registry::asn1_rs::FromDer, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; use crate::common::{assert_error, run_rt_test, RuntimeTestArgs, TEST_LABEL}; @@ -99,9 +99,10 @@ fn test_dmtf_other_name_extension_present() { ) .unwrap() .expect("We should have received a response"); - let certify_key_extended_resp = CertifyKeyExtendedResp::read_from(resp.as_slice()).unwrap(); + let certify_key_extended_resp = + CertifyKeyExtendedResp::read_from_bytes(resp.as_slice()).unwrap(); let certify_key_resp = - CertifyKeyResp::read_from(&certify_key_extended_resp.certify_key_resp[..]).unwrap(); + CertifyKeyResp::read_from_bytes(&certify_key_extended_resp.certify_key_resp[..]).unwrap(); let (_, cert) = X509Certificate::from_der(&certify_key_resp.cert[..certify_key_resp.cert_size as usize]) @@ -151,9 +152,10 @@ fn test_dmtf_other_name_extension_not_present() { ) .unwrap() .expect("We should have received a response"); - let certify_key_extended_resp = CertifyKeyExtendedResp::read_from(resp.as_slice()).unwrap(); + let certify_key_extended_resp = + CertifyKeyExtendedResp::read_from_bytes(resp.as_slice()).unwrap(); let certify_key_resp = - CertifyKeyResp::read_from(&certify_key_extended_resp.certify_key_resp[..]).unwrap(); + CertifyKeyResp::read_from_bytes(&certify_key_extended_resp.certify_key_resp[..]).unwrap(); let (_, cert) = X509Certificate::from_der(&certify_key_resp.cert[..certify_key_resp.cert_size as usize]) .unwrap(); @@ -194,9 +196,10 @@ fn test_dmtf_other_name_extension_not_present() { ) .unwrap() .expect("We should have received a response"); - let certify_key_extended_resp = CertifyKeyExtendedResp::read_from(resp.as_slice()).unwrap(); + let certify_key_extended_resp = + CertifyKeyExtendedResp::read_from_bytes(resp.as_slice()).unwrap(); let certify_key_resp = - CertifyKeyResp::read_from(&certify_key_extended_resp.certify_key_resp[..]).unwrap(); + CertifyKeyResp::read_from_bytes(&certify_key_extended_resp.certify_key_resp[..]).unwrap(); let (_, cert) = X509Certificate::from_der(&certify_key_resp.cert[..certify_key_resp.cert_size as usize]) .unwrap(); diff --git a/runtime/tests/runtime_integration_tests/test_certs.rs b/runtime/tests/runtime_integration_tests/test_certs.rs index c94c761a41..3306681e43 100644 --- a/runtime/tests/runtime_integration_tests/test_certs.rs +++ b/runtime/tests/runtime_integration_tests/test_certs.rs @@ -29,7 +29,7 @@ use openssl::{ store::X509StoreBuilder, verify::X509VerifyFlags, X509StoreContext, X509VerifyResult, X509, }, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; #[test] // Check if the owner and vendor cert validity dates are present in RT Alias cert @@ -76,7 +76,7 @@ fn test_rt_cert_with_custom_dates() { .unwrap(); assert!(resp.len() <= std::mem::size_of::()); let mut rt_resp = GetRtAliasCertResp::default(); - rt_resp.as_bytes_mut()[..resp.len()].copy_from_slice(&resp); + rt_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp); let rt_cert: X509 = X509::from_der(&rt_resp.data[..rt_resp.data_size as usize]).unwrap(); @@ -131,7 +131,7 @@ fn test_idev_id_cert() { assert!(resp.len() <= std::mem::size_of::()); let mut cert = GetIdevCertResp::default(); - cert.as_bytes_mut()[..resp.len()].copy_from_slice(&resp); + cert.as_mut_bytes()[..resp.len()].copy_from_slice(&resp); assert!(caliptra_common::checksum::verify_checksum( cert.hdr.chksum, @@ -170,7 +170,7 @@ fn get_ldev_cert(model: &mut DefaultHwModel) -> GetLdevCertResp { .unwrap(); assert!(resp.len() <= std::mem::size_of::()); let mut ldev_resp = GetLdevCertResp::default(); - ldev_resp.as_bytes_mut()[..resp.len()].copy_from_slice(&resp); + ldev_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp); ldev_resp } @@ -189,7 +189,7 @@ fn test_ldev_cert() { .mailbox_execute(u32::from(CommandId::GET_IDEV_INFO), payload.as_bytes()) .unwrap() .unwrap(); - let idev_resp = GetIdevInfoResp::read_from(resp.as_slice()).unwrap(); + let idev_resp = GetIdevInfoResp::read_from_bytes(resp.as_slice()).unwrap(); // Check the LDevID is signed by IDevID let group = EcGroup::from_curve_name(Nid::SECP384R1).unwrap(); @@ -259,7 +259,7 @@ fn test_dpe_leaf_cert() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::CertifyKey(certify_key_cmd), + &mut Command::CertifyKey(&certify_key_cmd), DpeResult::Success, ); let Some(Response::CertifyKey(certify_key_resp)) = resp else { @@ -324,7 +324,7 @@ fn get_dpe_leaf_cert(model: &mut DefaultHwModel) -> CertifyKeyResp { }; let resp = execute_dpe_cmd( model, - &mut Command::CertifyKey(certify_key_cmd), + &mut Command::CertifyKey(&certify_key_cmd), DpeResult::Success, ); let Some(Response::CertifyKey(certify_key_resp)) = resp else { @@ -450,12 +450,12 @@ pub fn test_all_measurement_apis() { flags: DeriveContextFlags::MAKE_DEFAULT | DeriveContextFlags::INPUT_ALLOW_CA | DeriveContextFlags::INPUT_ALLOW_X509, - tci_type: u32::read_from(&tci_type[..]).unwrap(), + tci_type: u32::read_from_bytes(&tci_type[..]).unwrap(), target_locality: 0, }; let resp = execute_dpe_cmd( &mut hw, - &mut Command::DeriveContext(derive_context_cmd), + &mut Command::DeriveContext(&derive_context_cmd), DpeResult::Success, ); let Some(Response::DeriveContext(_derive_ctx_resp)) = resp else { diff --git a/runtime/tests/runtime_integration_tests/test_disable.rs b/runtime/tests/runtime_integration_tests/test_disable.rs index a5eaea0c68..b4a0e31282 100644 --- a/runtime/tests/runtime_integration_tests/test_disable.rs +++ b/runtime/tests/runtime_integration_tests/test_disable.rs @@ -18,7 +18,7 @@ use openssl::{ nid::Nid, x509::X509, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; use crate::common::{ execute_dpe_cmd, get_rt_alias_cert, run_rt_test, DpeResult, RuntimeTestArgs, TEST_DIGEST, @@ -36,7 +36,11 @@ fn test_disable_attestation_cmd() { flags: SignFlags::empty(), digest: TEST_DIGEST, }; - let resp = execute_dpe_cmd(&mut model, &mut Command::Sign(sign_cmd), DpeResult::Success); + let resp = execute_dpe_cmd( + &mut model, + &mut Command::Sign(&sign_cmd), + DpeResult::Success, + ); let Some(Response::Sign(sign_resp)) = resp else { panic!("Wrong response type!"); }; @@ -54,7 +58,7 @@ fn test_disable_attestation_cmd() { ) .unwrap() .unwrap(); - let resp_hdr = MailboxRespHeader::read_from(resp.as_bytes()).unwrap(); + let resp_hdr = MailboxRespHeader::read_from_bytes(resp.as_bytes()).unwrap(); assert_eq!( resp_hdr.fips_status, MailboxRespHeader::FIPS_STATUS_APPROVED @@ -69,7 +73,7 @@ fn test_disable_attestation_cmd() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::CertifyKey(certify_key_cmd), + &mut Command::CertifyKey(&certify_key_cmd), DpeResult::Success, ); let Some(Response::CertifyKey(certify_key_resp)) = resp else { @@ -109,7 +113,7 @@ fn test_attestation_disabled_flag_after_update_reset() { ) .unwrap() .unwrap(); - let resp_hdr = MailboxRespHeader::read_from(resp.as_bytes()).unwrap(); + let resp_hdr = MailboxRespHeader::read_from_bytes(resp.as_bytes()).unwrap(); assert_eq!( resp_hdr.fips_status, MailboxRespHeader::FIPS_STATUS_APPROVED @@ -136,7 +140,7 @@ fn test_attestation_disabled_flag_after_update_reset() { .mailbox_execute(u32::from(CommandId::FW_INFO), payload.as_bytes()) .unwrap() .unwrap(); - let info = FwInfoResp::read_from(resp.as_slice()).unwrap(); + let info = FwInfoResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!(info.attestation_disabled, 1); // test that attestation is really disabled by checking that @@ -152,7 +156,7 @@ fn test_attestation_disabled_flag_after_update_reset() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::CertifyKey(certify_key_cmd), + &mut Command::CertifyKey(&certify_key_cmd), DpeResult::Success, ); let Some(Response::CertifyKey(certify_key_resp)) = resp else { diff --git a/runtime/tests/runtime_integration_tests/test_ecdsa.rs b/runtime/tests/runtime_integration_tests/test_ecdsa.rs index 634341fbdb..ddff8eac0d 100644 --- a/runtime/tests/runtime_integration_tests/test_ecdsa.rs +++ b/runtime/tests/runtime_integration_tests/test_ecdsa.rs @@ -7,7 +7,7 @@ use caliptra_common::mailbox_api::{ }; use caliptra_hw_model::{HwModel, ShaAccMode}; use caliptra_runtime::RtBootStatus; -use zerocopy::{AsBytes, FromBytes, LayoutVerified}; +use zerocopy::{FromBytes, IntoBytes}; // This file includes some tests from Wycheproof to testing specific common // ECDSA problems. @@ -117,7 +117,7 @@ fn ecdsa_cmd_run_wycheproof() { } Ok(Some(resp)) => { // Verify the checksum and FIPS status - let resp_hdr = MailboxRespHeader::read_from(resp.as_slice()).unwrap(); + let resp_hdr = MailboxRespHeader::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!( resp_hdr.fips_status, MailboxRespHeader::FIPS_STATUS_APPROVED @@ -211,10 +211,7 @@ fn test_ecdsa_verify_cmd() { .unwrap() .expect("We should have received a response"); - let resp_hdr: &MailboxRespHeader = - LayoutVerified::<&[u8], MailboxRespHeader>::new(resp.as_bytes()) - .unwrap() - .into_ref(); + let resp_hdr: &MailboxRespHeader = MailboxRespHeader::ref_from_bytes(resp.as_bytes()).unwrap(); assert_eq!( resp_hdr.fips_status, diff --git a/runtime/tests/runtime_integration_tests/test_fips.rs b/runtime/tests/runtime_integration_tests/test_fips.rs index eb5acea50e..a25d71e88c 100644 --- a/runtime/tests/runtime_integration_tests/test_fips.rs +++ b/runtime/tests/runtime_integration_tests/test_fips.rs @@ -8,7 +8,7 @@ use caliptra_common::mailbox_api::{ }; use caliptra_hw_model::HwModel; use caliptra_runtime::FipsVersionCmd; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; const HW_REV_ID: u32 = if cfg!(feature = "hw-1.0") { 0x1 } else { 0x11 }; @@ -40,7 +40,7 @@ fn test_fips_version() { let fips_version_bytes: &[u8] = fips_version_resp.as_bytes(); // Check values against expected. - let fips_version = FipsVersionResp::read_from(fips_version_bytes).unwrap(); + let fips_version = FipsVersionResp::read_from_bytes(fips_version_bytes).unwrap(); assert!(caliptra_common::checksum::verify_checksum( fips_version.hdr.chksum, 0x0, @@ -86,7 +86,7 @@ fn test_fips_shutdown() { .unwrap() .unwrap(); - let resp = MailboxRespHeader::read_from(resp.as_slice()).unwrap(); + let resp = MailboxRespHeader::read_from_bytes(resp.as_slice()).unwrap(); // Verify checksum and FIPS status assert!(caliptra_common::checksum::verify_checksum( resp.chksum, diff --git a/runtime/tests/runtime_integration_tests/test_get_idev_csr.rs b/runtime/tests/runtime_integration_tests/test_get_idev_csr.rs index 43082c0817..e00c100b78 100644 --- a/runtime/tests/runtime_integration_tests/test_get_idev_csr.rs +++ b/runtime/tests/runtime_integration_tests/test_get_idev_csr.rs @@ -8,7 +8,7 @@ use caliptra_error::CaliptraError; use caliptra_hw_model::{HwModel, ModelError}; use caliptra_runtime::RtBootStatus; use openssl::x509::X509Req; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; use crate::common::{run_rt_test, RuntimeTestArgs}; @@ -37,7 +37,7 @@ fn test_get_csr() { _ => { let response = result.unwrap().unwrap(); - let get_idv_csr_resp = GetIdevCsrResp::read_from(response.as_bytes()).unwrap(); + let get_idv_csr_resp = GetIdevCsrResp::ref_from_bytes(response.as_bytes()).unwrap(); assert_ne!(IdevIdCsr::UNPROVISIONED_CSR, get_idv_csr_resp.data_size); assert_ne!(0, get_idv_csr_resp.data_size); diff --git a/runtime/tests/runtime_integration_tests/test_info.rs b/runtime/tests/runtime_integration_tests/test_info.rs index 00d4f76afb..4367e35a43 100644 --- a/runtime/tests/runtime_integration_tests/test_info.rs +++ b/runtime/tests/runtime_integration_tests/test_info.rs @@ -18,7 +18,7 @@ use caliptra_image_gen::ImageGenerator; use caliptra_image_types::RomInfo; use core::mem::size_of; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; const RT_READY_FOR_COMMANDS: u32 = 0x600; @@ -31,8 +31,9 @@ fn find_rom_info(rom: &[u8]) -> Option { // Check if the chunk contains non-zero data if chunk.iter().any(|&byte| byte != 0) { // Found non-zero data, return RomInfo constructed from the data - let rom_info = RomInfo::read_from(&rom[i..i + size_of::()])?; - return Some(rom_info); + if let Ok(rom_info) = RomInfo::read_from_bytes(&rom[i..i + size_of::()]) { + return Some(rom_info); + } } } @@ -94,7 +95,7 @@ fn test_fw_info() { .unwrap() .unwrap(); - let info = FwInfoResp::read_from(resp.as_slice()).unwrap(); + let info = FwInfoResp::read_from_bytes(resp.as_slice()).unwrap(); // Verify checksum and FIPS status assert!(caliptra_common::checksum::verify_checksum( @@ -183,7 +184,7 @@ fn test_idev_id_info() { .mailbox_execute(u32::from(CommandId::GET_IDEV_INFO), payload.as_bytes()) .unwrap() .unwrap(); - GetIdevInfoResp::read_from(resp.as_slice()).unwrap(); + GetIdevInfoResp::read_from_bytes(resp.as_slice()).unwrap(); } #[test] @@ -196,7 +197,7 @@ fn test_capabilities() { .mailbox_execute(u32::from(CommandId::CAPABILITIES), payload.as_bytes()) .unwrap() .unwrap(); - let capabilities_resp = CapabilitiesResp::read_from(resp.as_slice()).unwrap(); + let capabilities_resp = CapabilitiesResp::read_from_bytes(resp.as_slice()).unwrap(); let capabilities = Capabilities::try_from(capabilities_resp.capabilities.as_bytes()).unwrap(); assert!(capabilities.contains(Capabilities::RT_BASE)); } diff --git a/runtime/tests/runtime_integration_tests/test_invoke_dpe.rs b/runtime/tests/runtime_integration_tests/test_invoke_dpe.rs index c900212ae9..8a2fd226cf 100644 --- a/runtime/tests/runtime_integration_tests/test_invoke_dpe.rs +++ b/runtime/tests/runtime_integration_tests/test_invoke_dpe.rs @@ -78,7 +78,7 @@ fn test_invoke_dpe_get_certificate_chain_cmd() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::GetCertificateChain(get_cert_chain_cmd), + &mut Command::GetCertificateChain(&get_cert_chain_cmd), DpeResult::Success, ); let Some(Response::GetCertificateChain(cert_chain)) = resp else { @@ -99,7 +99,11 @@ fn test_invoke_dpe_sign_and_certify_key_cmds() { flags: SignFlags::empty(), digest: TEST_DIGEST, }; - let resp = execute_dpe_cmd(&mut model, &mut Command::Sign(sign_cmd), DpeResult::Success); + let resp = execute_dpe_cmd( + &mut model, + &mut Command::Sign(&sign_cmd), + DpeResult::Success, + ); let Some(Response::Sign(sign_resp)) = resp else { panic!("Wrong response type!"); }; @@ -112,7 +116,7 @@ fn test_invoke_dpe_sign_and_certify_key_cmds() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::CertifyKey(certify_key_cmd), + &mut Command::CertifyKey(&certify_key_cmd), DpeResult::Success, ); let Some(Response::CertifyKey(certify_key_resp)) = resp else { @@ -148,7 +152,11 @@ fn test_invoke_dpe_symmetric_sign() { flags: SignFlags::IS_SYMMETRIC, digest: TEST_DIGEST, }; - let resp = execute_dpe_cmd(&mut model, &mut Command::Sign(sign_cmd), DpeResult::Success); + let resp = execute_dpe_cmd( + &mut model, + &mut Command::Sign(&sign_cmd), + DpeResult::Success, + ); let Some(Response::Sign(sign_resp)) = resp else { panic!("Wrong response type!"); }; @@ -171,7 +179,7 @@ fn test_dpe_header_error_code() { let init_ctx_cmd = InitCtxCmd::new_use_default(); let resp = execute_dpe_cmd( &mut model, - &mut Command::InitCtx(init_ctx_cmd), + &mut Command::InitCtx(&init_ctx_cmd), DpeResult::DpeCmdFailure, ); let Some(Response::Error(hdr)) = resp else { @@ -199,7 +207,7 @@ fn test_invoke_dpe_certify_key_csr() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::CertifyKey(certify_key_cmd), + &mut Command::CertifyKey(&certify_key_cmd), DpeResult::Success, ); let Some(Response::CertifyKey(certify_key_resp)) = resp else { @@ -266,7 +274,7 @@ fn test_invoke_dpe_rotate_context() { let resp = execute_dpe_cmd( &mut model, - &mut Command::RotateCtx(rotate_ctx_cmd), + &mut Command::RotateCtx(&rotate_ctx_cmd), DpeResult::Success, ); let Some(Response::RotateCtx(rotate_ctx_resp)) = resp else { @@ -282,7 +290,7 @@ fn test_invoke_dpe_rotate_context() { let resp = execute_dpe_cmd( &mut model, - &mut Command::RotateCtx(rotate_ctx_cmd), + &mut Command::RotateCtx(&rotate_ctx_cmd), DpeResult::Success, ); let Some(Response::RotateCtx(rotate_ctx_resp)) = resp else { diff --git a/runtime/tests/runtime_integration_tests/test_lms.rs b/runtime/tests/runtime_integration_tests/test_lms.rs index 038e19776b..15df03bdd2 100644 --- a/runtime/tests/runtime_integration_tests/test_lms.rs +++ b/runtime/tests/runtime_integration_tests/test_lms.rs @@ -8,7 +8,7 @@ use caliptra_common::mailbox_api::{ use caliptra_hw_model::{HwModel, ModelError, ShaAccMode}; use caliptra_lms_types::{LmotsAlgorithmType, LmsAlgorithmType, LmsPublicKey, LmsSignature}; use caliptra_runtime::RtBootStatus; -use zerocopy::{AsBytes, FromBytes, LayoutVerified}; +use zerocopy::{FromBytes, IntoBytes}; // Constants from fixed LMS param set const LMS_N: usize = 6; @@ -768,8 +768,8 @@ fn execute_lms_cmd( pub_key_bytes: &[u8], signature_bytes: &[u8], ) -> Result<(), ModelError> { - let pub_key = >::read_from(pub_key_bytes).unwrap(); - let signature = >::read_from(signature_bytes).unwrap(); + let pub_key = >::read_from_bytes(pub_key_bytes).unwrap(); + let signature = >::read_from_bytes(signature_bytes).unwrap(); let mut cmd = MailboxReq::LmsVerify(LmsVerifyReq { hdr: MailboxReqHeader { chksum: 0 }, @@ -795,10 +795,7 @@ fn execute_lms_cmd( .mailbox_execute(u32::from(CommandId::LMS_VERIFY), cmd.as_bytes().unwrap())? .expect("We should have received a response"); - let resp_hdr: &MailboxRespHeader = - LayoutVerified::<&[u8], MailboxRespHeader>::new(resp.as_bytes()) - .unwrap() - .into_ref(); + let resp_hdr: &MailboxRespHeader = MailboxRespHeader::ref_from_bytes(resp.as_bytes()).unwrap(); assert_eq!( resp_hdr.fips_status, @@ -864,7 +861,7 @@ fn test_lms_verify_invalid_sig_lms_type() { // Select an invalid LMS type let mut signature = - >::read_from(&MSG_1_KEY_1_SIG_1[..]).unwrap(); + >::read_from_bytes(&MSG_1_KEY_1_SIG_1[..]).unwrap(); signature.tree_type = LmsAlgorithmType::new(10); let resp = @@ -886,7 +883,7 @@ fn test_lms_verify_invalid_key_lms_type() { }); // Select an invalid LMS type - let mut pub_key = >::read_from(&MSG_1_PUB_KEY_1[..]).unwrap(); + let mut pub_key = >::read_from_bytes(&MSG_1_PUB_KEY_1[..]).unwrap(); pub_key.tree_type = LmsAlgorithmType::new(10); let resp = @@ -908,7 +905,7 @@ fn test_lms_verify_invalid_lmots_type() { }); // Select an invalid otstype - let mut pub_key = >::read_from(&MSG_1_PUB_KEY_1[..]).unwrap(); + let mut pub_key = >::read_from_bytes(&MSG_1_PUB_KEY_1[..]).unwrap(); pub_key.otstype = LmotsAlgorithmType::new(6); let resp = diff --git a/runtime/tests/runtime_integration_tests/test_mailbox.rs b/runtime/tests/runtime_integration_tests/test_mailbox.rs index 11efc30074..ebc73f4971 100644 --- a/runtime/tests/runtime_integration_tests/test_mailbox.rs +++ b/runtime/tests/runtime_integration_tests/test_mailbox.rs @@ -3,7 +3,7 @@ use caliptra_api::SocManager; use caliptra_common::mailbox_api::{CommandId, MailboxReqHeader}; use caliptra_hw_model::HwModel; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::common::{assert_error, run_rt_test, RuntimeTestArgs}; diff --git a/runtime/tests/runtime_integration_tests/test_pauser_privilege_levels.rs b/runtime/tests/runtime_integration_tests/test_pauser_privilege_levels.rs index d97506b605..42e3e85c8e 100644 --- a/runtime/tests/runtime_integration_tests/test_pauser_privilege_levels.rs +++ b/runtime/tests/runtime_integration_tests/test_pauser_privilege_levels.rs @@ -28,7 +28,7 @@ use dpe::{ response::Response, DPE_PROFILE, }; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::common::{ assert_error, execute_dpe_cmd, run_rt_test, DpeResult, RuntimeTestArgs, TEST_LABEL, @@ -52,7 +52,7 @@ fn test_pl0_derive_context_dpe_context_thresholds() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::RotateCtx(rotate_ctx_cmd), + &mut Command::RotateCtx(&rotate_ctx_cmd), DpeResult::Success, ); let Some(Response::RotateCtx(rotate_ctx_resp)) = resp else { @@ -78,7 +78,7 @@ fn test_pl0_derive_context_dpe_context_thresholds() { if i == num_iterations - 1 { let resp = execute_dpe_cmd( &mut model, - &mut Command::DeriveContext(derive_context_cmd), + &mut Command::DeriveContext(&derive_context_cmd), DpeResult::MboxCmdFailure( caliptra_drivers::CaliptraError::RUNTIME_PL0_USED_DPE_CONTEXT_THRESHOLD_REACHED, ), @@ -89,7 +89,7 @@ fn test_pl0_derive_context_dpe_context_thresholds() { let resp = execute_dpe_cmd( &mut model, - &mut Command::DeriveContext(derive_context_cmd), + &mut Command::DeriveContext(&derive_context_cmd), DpeResult::Success, ); let Some(Response::DeriveContext(derive_context_resp)) = resp else { @@ -121,7 +121,7 @@ fn test_pl1_derive_context_dpe_context_thresholds() { let init_ctx_cmd = InitCtxCmd::new_simulation(); let resp = execute_dpe_cmd( &mut model, - &mut Command::InitCtx(init_ctx_cmd), + &mut Command::InitCtx(&init_ctx_cmd), DpeResult::Success, ); let Some(Response::InitCtx(init_ctx_resp)) = resp else { @@ -148,7 +148,7 @@ fn test_pl1_derive_context_dpe_context_thresholds() { if i == num_iterations - 1 { let resp = execute_dpe_cmd( &mut model, - &mut Command::DeriveContext(derive_context_cmd), + &mut Command::DeriveContext(&derive_context_cmd), DpeResult::MboxCmdFailure( caliptra_drivers::CaliptraError::RUNTIME_PL1_USED_DPE_CONTEXT_THRESHOLD_REACHED, ), @@ -159,7 +159,7 @@ fn test_pl1_derive_context_dpe_context_thresholds() { let resp = execute_dpe_cmd( &mut model, - &mut Command::DeriveContext(derive_context_cmd), + &mut Command::DeriveContext(&derive_context_cmd), DpeResult::Success, ); let Some(Response::DeriveContext(derive_context_resp)) = resp else { @@ -185,7 +185,7 @@ fn test_pl0_init_ctx_dpe_context_thresholds() { if i == num_iterations - 1 { let resp = execute_dpe_cmd( &mut model, - &mut Command::InitCtx(init_ctx_cmd), + &mut Command::InitCtx(&init_ctx_cmd), DpeResult::MboxCmdFailure( caliptra_drivers::CaliptraError::RUNTIME_PL0_USED_DPE_CONTEXT_THRESHOLD_REACHED, ), @@ -196,7 +196,7 @@ fn test_pl0_init_ctx_dpe_context_thresholds() { let resp = execute_dpe_cmd( &mut model, - &mut Command::InitCtx(init_ctx_cmd), + &mut Command::InitCtx(&init_ctx_cmd), DpeResult::Success, ); let Some(Response::InitCtx(_)) = resp else { @@ -231,7 +231,7 @@ fn test_pl1_init_ctx_dpe_context_thresholds() { if i == num_iterations - 1 { let resp = execute_dpe_cmd( &mut model, - &mut Command::InitCtx(init_ctx_cmd), + &mut Command::InitCtx(&init_ctx_cmd), DpeResult::MboxCmdFailure( caliptra_drivers::CaliptraError::RUNTIME_PL1_USED_DPE_CONTEXT_THRESHOLD_REACHED, ), @@ -242,7 +242,7 @@ fn test_pl1_init_ctx_dpe_context_thresholds() { let resp = execute_dpe_cmd( &mut model, - &mut Command::InitCtx(init_ctx_cmd), + &mut Command::InitCtx(&init_ctx_cmd), DpeResult::Success, ); let Some(Response::InitCtx(_)) = resp else { @@ -337,7 +337,7 @@ fn test_certify_key_x509_cannot_be_called_from_pl1() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::CertifyKey(certify_key_cmd), + &mut Command::CertifyKey(&certify_key_cmd), DpeResult::MboxCmdFailure(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL), ); assert!(resp.is_none()); @@ -399,7 +399,7 @@ fn test_derive_context_cannot_be_called_from_pl1_if_changes_locality_to_pl0() { let init_ctx_cmd = InitCtxCmd::new_simulation(); let resp = execute_dpe_cmd( &mut model, - &mut Command::InitCtx(init_ctx_cmd), + &mut Command::InitCtx(&init_ctx_cmd), DpeResult::Success, ); let Some(Response::InitCtx(init_ctx_resp)) = resp else { @@ -415,7 +415,7 @@ fn test_derive_context_cannot_be_called_from_pl1_if_changes_locality_to_pl0() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::DeriveContext(derive_context_cmd), + &mut Command::DeriveContext(&derive_context_cmd), DpeResult::MboxCmdFailure( caliptra_drivers::CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL, ), @@ -595,7 +595,7 @@ fn test_pl0_unset_in_header() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::CertifyKey(certify_key_cmd), + &mut Command::CertifyKey(&certify_key_cmd), DpeResult::MboxCmdFailure(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL), ); assert!(resp.is_none()); @@ -640,7 +640,7 @@ fn test_user_not_pl0() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::CertifyKey(certify_key_cmd), + &mut Command::CertifyKey(&certify_key_cmd), DpeResult::MboxCmdFailure(CaliptraError::RUNTIME_INCORRECT_PAUSER_PRIVILEGE_LEVEL), ); assert!(resp.is_none()); diff --git a/runtime/tests/runtime_integration_tests/test_pcr.rs b/runtime/tests/runtime_integration_tests/test_pcr.rs index 10a5a8bc1b..47a9763a96 100644 --- a/runtime/tests/runtime_integration_tests/test_pcr.rs +++ b/runtime/tests/runtime_integration_tests/test_pcr.rs @@ -16,7 +16,7 @@ use openssl::{ hash::{Hasher, MessageDigest}, x509::X509, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; #[test] fn test_pcr_quote() { @@ -51,7 +51,7 @@ fn test_pcr_quote() { .unwrap() .unwrap(); - let resp = QuotePcrsResp::read_from(resp.as_slice()).unwrap(); + let resp = QuotePcrsResp::read_from_bytes(resp.as_slice()).unwrap(); // Compute the digest and compare to mailbox result let mut h = Hasher::new(MessageDigest::sha384()).unwrap(); @@ -100,7 +100,9 @@ pub fn get_model_pcrs(model: &mut DefaultHwModel) -> [[u8; 48]; 32] { .unwrap() .unwrap(); - return QuotePcrsResp::read_from(resp.as_slice()).unwrap().pcrs; + return QuotePcrsResp::read_from_bytes(resp.as_slice()) + .unwrap() + .pcrs; } #[test] diff --git a/runtime/tests/runtime_integration_tests/test_populate_idev.rs b/runtime/tests/runtime_integration_tests/test_populate_idev.rs index e6c972cc27..f40fb4e954 100644 --- a/runtime/tests/runtime_integration_tests/test_populate_idev.rs +++ b/runtime/tests/runtime_integration_tests/test_populate_idev.rs @@ -27,7 +27,7 @@ fn get_full_cert_chain(model: &mut DefaultHwModel, out: &mut [u8; 4096]) -> usiz }; let resp = execute_dpe_cmd( model, - &mut Command::GetCertificateChain(get_cert_chain_cmd), + &mut Command::GetCertificateChain(&get_cert_chain_cmd), DpeResult::Success, ); let Some(Response::GetCertificateChain(cert_chunk_1)) = resp else { @@ -43,7 +43,7 @@ fn get_full_cert_chain(model: &mut DefaultHwModel, out: &mut [u8; 4096]) -> usiz }; let resp = execute_dpe_cmd( model, - &mut Command::GetCertificateChain(get_cert_chain_cmd), + &mut Command::GetCertificateChain(&get_cert_chain_cmd), DpeResult::Success, ); let Some(Response::GetCertificateChain(cert_chunk_2)) = resp else { diff --git a/runtime/tests/runtime_integration_tests/test_set_auth_manifest.rs b/runtime/tests/runtime_integration_tests/test_set_auth_manifest.rs index 6b89a64af3..0bb11e9f70 100644 --- a/runtime/tests/runtime_integration_tests/test_set_auth_manifest.rs +++ b/runtime/tests/runtime_integration_tests/test_set_auth_manifest.rs @@ -18,7 +18,7 @@ use caliptra_hw_model::HwModel; use caliptra_image_crypto::OsslCrypto as Crypto; use caliptra_image_fake_keys::*; use caliptra_runtime::RtBootStatus; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; pub fn create_auth_manifest(manifest_flags: AuthManifestFlags) -> AuthorizationManifest { let vendor_fw_key_info: AuthManifestGeneratorKeyConfig = AuthManifestGeneratorKeyConfig { diff --git a/runtime/tests/runtime_integration_tests/test_stash_measurement.rs b/runtime/tests/runtime_integration_tests/test_stash_measurement.rs index 8c3625edcd..457ab2e415 100644 --- a/runtime/tests/runtime_integration_tests/test_stash_measurement.rs +++ b/runtime/tests/runtime_integration_tests/test_stash_measurement.rs @@ -11,7 +11,7 @@ use caliptra_common::mailbox_api::{ use caliptra_hw_model::HwModel; use caliptra_runtime::RtBootStatus; use sha2::{Digest, Sha384}; -use zerocopy::{AsBytes, LayoutVerified}; +use zerocopy::{FromBytes, IntoBytes}; use crate::common::{run_rt_test, RuntimeTestArgs}; @@ -42,9 +42,7 @@ fn test_stash_measurement() { .expect("We should have received a response"); let resp_hdr: &StashMeasurementResp = - LayoutVerified::<&[u8], StashMeasurementResp>::new(resp.as_bytes()) - .unwrap() - .into_ref(); + StashMeasurementResp::ref_from_bytes(resp.as_bytes()).unwrap(); assert_eq!(resp_hdr.dpe_result, 0); diff --git a/runtime/tests/runtime_integration_tests/test_tagging.rs b/runtime/tests/runtime_integration_tests/test_tagging.rs index bde33746cb..f6badcede8 100644 --- a/runtime/tests/runtime_integration_tests/test_tagging.rs +++ b/runtime/tests/runtime_integration_tests/test_tagging.rs @@ -47,7 +47,7 @@ fn test_tagging_default_context() { ) .unwrap() .expect("We expected a response"); - let _ = GetTaggedTciResp::read_from(resp.as_slice()).unwrap(); + let _ = GetTaggedTciResp::read_from_bytes(resp.as_slice()).unwrap(); } #[test] @@ -182,7 +182,7 @@ fn test_tagging_destroyed_context() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::DestroyCtx(destroy_ctx_cmd), + &mut Command::DestroyCtx(&destroy_ctx_cmd), DpeResult::Success, ); let Some(Response::DestroyCtx(_)) = resp else { @@ -222,7 +222,7 @@ fn test_tagging_retired_context() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::DeriveContext(derive_context_cmd), + &mut Command::DeriveContext(&derive_context_cmd), DpeResult::Success, ); let Some(Response::DeriveContext(derive_context_resp)) = resp else { @@ -268,7 +268,7 @@ fn test_tagging_retired_context() { }; let resp = execute_dpe_cmd( &mut model, - &mut Command::DeriveContext(derive_context_cmd), + &mut Command::DeriveContext(&derive_context_cmd), DpeResult::Success, ); let Some(Response::DeriveContext(_)) = resp else { @@ -288,5 +288,5 @@ fn test_tagging_retired_context() { ) .unwrap() .expect("We expected a response"); - let _ = GetTaggedTciResp::read_from(resp.as_slice()).unwrap(); + let _ = GetTaggedTciResp::read_from_bytes(resp.as_slice()).unwrap(); } diff --git a/runtime/tests/runtime_integration_tests/test_update_reset.rs b/runtime/tests/runtime_integration_tests/test_update_reset.rs index 3049a24075..73c793f02f 100644 --- a/runtime/tests/runtime_integration_tests/test_update_reset.rs +++ b/runtime/tests/runtime_integration_tests/test_update_reset.rs @@ -21,7 +21,7 @@ use dpe::{ validation::ValidationError, DpeInstance, U8Bool, DPE_PROFILE, MAX_HANDLES, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes, TryFromBytes}; use crate::common::{run_rt_test, RuntimeTestArgs}; @@ -157,7 +157,7 @@ fn test_dpe_validation_deformed_structure() { // read DPE after RT initialization let dpe_resp = model.mailbox_execute(0xA000_0000, &[]).unwrap().unwrap(); - let mut dpe = DpeInstance::read_from(dpe_resp.as_bytes()).unwrap(); + let mut dpe = DpeInstance::try_read_from_bytes(dpe_resp.as_bytes()).unwrap(); // corrupt DPE structure by creating multiple normal connected components dpe.contexts[0].children = 0; @@ -193,7 +193,7 @@ fn test_dpe_validation_deformed_structure() { .mailbox_execute(u32::from(CommandId::FW_INFO), payload.as_bytes()) .unwrap() .unwrap(); - let info = FwInfoResp::read_from(resp.as_slice()).unwrap(); + let info = FwInfoResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!(info.attestation_disabled, 1); } @@ -207,7 +207,7 @@ fn test_dpe_validation_illegal_state() { // read DPE after RT initialization let dpe_resp = model.mailbox_execute(0xA000_0000, &[]).unwrap().unwrap(); - let mut dpe = DpeInstance::read_from(dpe_resp.as_bytes()).unwrap(); + let mut dpe = DpeInstance::try_read_from_bytes(dpe_resp.as_bytes()).unwrap(); // corrupt DPE state by messing up parent-child links dpe.contexts[1].children = 0b1; @@ -241,7 +241,7 @@ fn test_dpe_validation_illegal_state() { .mailbox_execute(u32::from(CommandId::FW_INFO), payload.as_bytes()) .unwrap() .unwrap(); - let info = FwInfoResp::read_from(resp.as_slice()).unwrap(); + let info = FwInfoResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!(info.attestation_disabled, 1); } @@ -255,7 +255,7 @@ fn test_dpe_validation_used_context_threshold_exceeded() { // read DPE after RT initialization let dpe_resp = model.mailbox_execute(0xA000_0000, &[]).unwrap().unwrap(); - let mut dpe = DpeInstance::read_from(dpe_resp.as_bytes()).unwrap(); + let mut dpe = DpeInstance::try_read_from_bytes(dpe_resp.as_bytes()).unwrap(); // corrupt DPE structure by creating PL0_DPE_ACTIVE_CONTEXT_THRESHOLD contexts let pl0_pauser = ImageOptions::default().vendor_config.pl0_pauser.unwrap(); @@ -295,7 +295,7 @@ fn test_dpe_validation_used_context_threshold_exceeded() { .mailbox_execute(u32::from(CommandId::FW_INFO), payload.as_bytes()) .unwrap() .unwrap(); - let info = FwInfoResp::read_from(resp.as_slice()).unwrap(); + let info = FwInfoResp::read_from_bytes(resp.as_slice()).unwrap(); assert_eq!(info.attestation_disabled, 1); } diff --git a/runtime/tests/runtime_integration_tests/test_warm_reset.rs b/runtime/tests/runtime_integration_tests/test_warm_reset.rs index c40fb6d861..7228b598c0 100644 --- a/runtime/tests/runtime_integration_tests/test_warm_reset.rs +++ b/runtime/tests/runtime_integration_tests/test_warm_reset.rs @@ -10,7 +10,7 @@ use caliptra_hw_model::{BootParams, DeviceLifecycle, Fuses, HwModel, InitParams, use caliptra_registers::mbox::enums::MboxStatusE; use dpe::DPE_PROFILE; use openssl::sha::sha384; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; fn swap_word_bytes_inplace(words: &mut [u32]) { for word in words.iter_mut() { diff --git a/sw-emulator/lib/periph/src/hash_sha512.rs b/sw-emulator/lib/periph/src/hash_sha512.rs index a781edb1fb..4ff2ce867d 100644 --- a/sw-emulator/lib/periph/src/hash_sha512.rs +++ b/sw-emulator/lib/periph/src/hash_sha512.rs @@ -28,7 +28,7 @@ use std::rc::Rc; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; use tock_registers::register_bitfields; use tock_registers::registers::InMemoryRegister; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; register_bitfields! [ u32, @@ -669,7 +669,7 @@ impl HashSha512Regs { self.sha512.update_bytes(self.pcr_gen_hash_nonce.as_bytes()); self.sha512 .finalize((PCR_COUNT * PCR_SIZE + NONCE_SIZE).try_into().unwrap()); - self.sha512.copy_hash(self.pcr_hash_digest.as_bytes_mut()); + self.sha512.copy_hash(self.pcr_hash_digest.as_mut_bytes()); self.pcr_hash_status .reg diff --git a/sw-emulator/lib/periph/src/hmac_sha384.rs b/sw-emulator/lib/periph/src/hmac_sha384.rs index 35daaf08a6..d9a3475761 100644 --- a/sw-emulator/lib/periph/src/hmac_sha384.rs +++ b/sw-emulator/lib/periph/src/hmac_sha384.rs @@ -22,7 +22,7 @@ use caliptra_emu_types::{RvData, RvSize}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; use tock_registers::register_bitfields; use tock_registers::registers::InMemoryRegister; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; register_bitfields! [ u32, @@ -484,7 +484,7 @@ impl HmacSha384 { fn op_complete(&mut self) { // Retrieve the tag - self.hmac.tag(self.tag.as_bytes_mut()); + self.hmac.tag(self.tag.as_mut_bytes()); // Don't reveal the tag to the CPU if the inputs came from the // key-vault. self.hide_tag_from_cpu = self.block_from_kv || self.key_from_kv; @@ -533,7 +533,7 @@ impl HmacSha384 { if let Some(key) = &key { self.key_from_kv = true; self.key - .as_bytes_mut() + .as_mut_bytes() .copy_from_slice(&key[..HMAC_KEY_SIZE]); } @@ -598,7 +598,7 @@ impl HmacSha384 { block_arr[HMAC_BLOCK_SIZE - 16..].copy_from_slice(&len.to_be_bytes()); block_arr.to_big_endian(); - self.block.as_bytes_mut().copy_from_slice(&block_arr); + self.block.as_mut_bytes().copy_from_slice(&block_arr); } fn tag_write_complete(&mut self) { diff --git a/test/src/derive.rs b/test/src/derive.rs index 8de6a12299..5c7964dac3 100644 --- a/test/src/derive.rs +++ b/test/src/derive.rs @@ -10,7 +10,7 @@ use openssl::{ pkey::{PKey, Public}, sha::{sha256, sha384}, }; -use zerocopy::{transmute, AsBytes}; +use zerocopy::{transmute, IntoBytes}; #[cfg(test)] use caliptra_api_types::DeviceLifecycle; @@ -98,7 +98,7 @@ impl DoeOutput { result .uds - .as_bytes_mut() + .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(), @@ -107,7 +107,7 @@ impl DoeOutput { swap_word_bytes_inplace(&mut result.uds); result.field_entropy[0..8] - .as_bytes_mut() + .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(), @@ -464,7 +464,7 @@ impl RtAliasKey { 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_bytes_mut() + .as_mut_bytes() .copy_from_slice(&sha384(tci_input.manifest.as_bytes())); let mut cdi: [u32; 12] = transmute!(hmac384_kdf( diff --git a/test/tests/caliptra_integration_tests/fake_collateral_boot_test.rs b/test/tests/caliptra_integration_tests/fake_collateral_boot_test.rs index 1fbbfd4ae4..7460870fe7 100755 --- a/test/tests/caliptra_integration_tests/fake_collateral_boot_test.rs +++ b/test/tests/caliptra_integration_tests/fake_collateral_boot_test.rs @@ -16,7 +16,7 @@ use caliptra_test::{ }; use openssl::sha::sha384; use std::io::Write; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; const RT_READY_FOR_COMMANDS: u32 = 0x600; @@ -114,7 +114,7 @@ fn fake_boot_test() { assert!(resp.len() <= std::mem::size_of::()); let mut ldev_cert_resp = GetLdevCertResp::default(); - ldev_cert_resp.as_bytes_mut()[..resp.len()].copy_from_slice(&resp); + ldev_cert_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp); // Verify checksum and FIPS approval assert!(caliptra_common::checksum::verify_checksum( @@ -180,7 +180,7 @@ fn fake_boot_test() { assert!(resp.len() <= std::mem::size_of::()); let mut fmc_alias_cert_resp = GetFmcAliasCertResp::default(); - fmc_alias_cert_resp.as_bytes_mut()[..resp.len()].copy_from_slice(&resp); + fmc_alias_cert_resp.as_mut_bytes()[..resp.len()].copy_from_slice(&resp); // Verify checksum and FIPS approval assert!(caliptra_common::checksum::verify_checksum( diff --git a/test/tests/caliptra_integration_tests/jtag_test.rs b/test/tests/caliptra_integration_tests/jtag_test.rs index 0d048592d2..77131fae84 100644 --- a/test/tests/caliptra_integration_tests/jtag_test.rs +++ b/test/tests/caliptra_integration_tests/jtag_test.rs @@ -8,7 +8,7 @@ use caliptra_test::swap_word_bytes_inplace; use openssl::sha::sha384; use std::io::{BufRead, BufReader, Write}; use std::process::{ChildStdin, Command, Stdio}; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; fn bytes_to_be_words_48(buf: &[u8; 48]) -> [u32; 12] { let mut result: [u32; 12] = zerocopy::transmute!(*buf); diff --git a/test/tests/caliptra_integration_tests/smoke_test.rs b/test/tests/caliptra_integration_tests/smoke_test.rs index f5477f21fd..792172019d 100644 --- a/test/tests/caliptra_integration_tests/smoke_test.rs +++ b/test/tests/caliptra_integration_tests/smoke_test.rs @@ -23,7 +23,7 @@ use rand::rngs::StdRng; use rand::SeedableRng; use regex::Regex; use std::mem; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; // Support testing against older versions of ROM in CI // More constants may need to be added here as the ROMs further diverge diff --git a/test/tests/caliptra_integration_tests/warm_reset.rs b/test/tests/caliptra_integration_tests/warm_reset.rs index a390722645..79b03f9521 100644 --- a/test/tests/caliptra_integration_tests/warm_reset.rs +++ b/test/tests/caliptra_integration_tests/warm_reset.rs @@ -10,7 +10,7 @@ use caliptra_common::mailbox_api::CommandId; use caliptra_hw_model::{mbox_write_fifo, BootParams, HwModel, InitParams, SecurityState}; use caliptra_test::swap_word_bytes_inplace; use openssl::sha::sha384; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; fn bytes_to_be_words_48(buf: &[u8; 48]) -> [u32; 12] { let mut result: [u32; 12] = zerocopy::transmute!(*buf); diff --git a/test/tests/fips_test_suite/common.rs b/test/tests/fips_test_suite/common.rs index c91c71198a..9261c29e9e 100755 --- a/test/tests/fips_test_suite/common.rs +++ b/test/tests/fips_test_suite/common.rs @@ -14,7 +14,7 @@ use dpe::{ Response, ResponseHdr, SignResp, }, }; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; pub const HOOK_CODE_MASK: u32 = 0x00FF0000; pub const HOOK_CODE_OFFSET: u32 = 16; @@ -253,7 +253,7 @@ pub fn fips_test_init_to_rt( // HW model will complete FW upload cmd, nothing to wait for } -pub fn mbx_send_and_check_resp_hdr( +pub fn mbx_send_and_check_resp_hdr( hw: &mut T, cmd: u32, req_payload: &[u8], @@ -261,9 +261,10 @@ pub fn mbx_send_and_check_resp_hdr( let resp_bytes = hw.mailbox_execute(cmd, req_payload)?.unwrap(); // Check values against expected. - let resp_hdr = - MailboxRespHeader::read_from(&resp_bytes[..core::mem::size_of::()]) - .unwrap(); + let resp_hdr = MailboxRespHeader::read_from_bytes( + &resp_bytes[..core::mem::size_of::()], + ) + .unwrap(); assert!(caliptra_common::checksum::verify_checksum( resp_hdr.chksum, 0x0, @@ -277,11 +278,11 @@ pub fn mbx_send_and_check_resp_hdr( // Handle variable-sized responses assert!(resp_bytes.len() <= std::mem::size_of::()); let mut typed_resp = U::new_zeroed(); - typed_resp.as_bytes_mut()[..resp_bytes.len()].copy_from_slice(&resp_bytes); + 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(resp_bytes.as_bytes()).unwrap()) + //Ok(U::read_from_bytes(resp_bytes.as_bytes()).unwrap()) } fn get_cmd_id(dpe_cmd: &mut Command) -> u32 { @@ -296,7 +297,7 @@ fn get_cmd_id(dpe_cmd: &mut Command) -> u32 { Command::GetCertificateChain(_) => Command::GET_CERTIFICATE_CHAIN, } } -pub fn as_bytes(dpe_cmd: &mut Command) -> &[u8] { +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(), @@ -312,19 +313,27 @@ pub fn as_bytes(dpe_cmd: &mut Command) -> &[u8] { pub fn parse_dpe_response(dpe_cmd: &mut Command, resp_bytes: &[u8]) -> Response { match dpe_cmd { Command::CertifyKey(_) => { - Response::CertifyKey(CertifyKeyResp::read_from(resp_bytes).unwrap()) + Response::CertifyKey(CertifyKeyResp::read_from_bytes(resp_bytes).unwrap()) } Command::DeriveContext(_) => { - Response::DeriveContext(DeriveContextResp::read_from(resp_bytes).unwrap()) + Response::DeriveContext(DeriveContextResp::read_from_bytes(resp_bytes).unwrap()) + } + Command::GetCertificateChain(_) => Response::GetCertificateChain( + GetCertificateChainResp::read_from_bytes(resp_bytes).unwrap(), + ), + Command::DestroyCtx(_) => { + Response::DestroyCtx(ResponseHdr::read_from_bytes(resp_bytes).unwrap()) + } + Command::GetProfile => { + Response::GetProfile(GetProfileResp::read_from_bytes(resp_bytes).unwrap()) + } + Command::InitCtx(_) => { + Response::InitCtx(NewHandleResp::read_from_bytes(resp_bytes).unwrap()) } - Command::GetCertificateChain(_) => { - Response::GetCertificateChain(GetCertificateChainResp::read_from(resp_bytes).unwrap()) + Command::RotateCtx(_) => { + Response::RotateCtx(NewHandleResp::read_from_bytes(resp_bytes).unwrap()) } - Command::DestroyCtx(_) => Response::DestroyCtx(ResponseHdr::read_from(resp_bytes).unwrap()), - Command::GetProfile => Response::GetProfile(GetProfileResp::read_from(resp_bytes).unwrap()), - Command::InitCtx(_) => Response::InitCtx(NewHandleResp::read_from(resp_bytes).unwrap()), - Command::RotateCtx(_) => Response::RotateCtx(NewHandleResp::read_from(resp_bytes).unwrap()), - Command::Sign(_) => Response::Sign(SignResp::read_from(resp_bytes).unwrap()), + Command::Sign(_) => Response::Sign(SignResp::read_from_bytes(resp_bytes).unwrap()), } } diff --git a/test/tests/fips_test_suite/fw_load.rs b/test/tests/fips_test_suite/fw_load.rs index abbdd698ec..97e40d5866 100755 --- a/test/tests/fips_test_suite/fw_load.rs +++ b/test/tests/fips_test_suite/fw_load.rs @@ -19,7 +19,7 @@ use caliptra_image_types::{ImageBundle, VENDOR_ECC_KEY_COUNT, VENDOR_LMS_KEY_COU use openssl::sha::sha384; use common::*; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; #[allow(dead_code)] #[derive(PartialEq, Eq)] diff --git a/test/tests/fips_test_suite/security_parameters.rs b/test/tests/fips_test_suite/security_parameters.rs index 795a2649e2..cebf9eef3b 100755 --- a/test/tests/fips_test_suite/security_parameters.rs +++ b/test/tests/fips_test_suite/security_parameters.rs @@ -157,7 +157,7 @@ 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 (manifest, _) = ImageManifest::read_from_prefix(&fw_image).unwrap(); let gen = ImageGenerator::new(Crypto::default()); let vendor_pubkey_digest = gen.vendor_pubkey_digest(&manifest.preamble).unwrap(); @@ -208,7 +208,7 @@ pub fn attempt_ssp_access_fw_load() { #[test] pub fn attempt_ssp_access_rt() { let fw_image = fips_fw_image(); - let manifest = ImageManifest::read_from_prefix(&*fw_image).unwrap(); + let (manifest, _) = ImageManifest::read_from_prefix(&fw_image).unwrap(); let gen = ImageGenerator::new(Crypto::default()); let vendor_pubkey_digest = gen.vendor_pubkey_digest(&manifest.preamble).unwrap(); diff --git a/test/tests/fips_test_suite/self_tests.rs b/test/tests/fips_test_suite/self_tests.rs index 1168527ec2..0bb2787c08 100755 --- a/test/tests/fips_test_suite/self_tests.rs +++ b/test/tests/fips_test_suite/self_tests.rs @@ -12,7 +12,7 @@ use caliptra_drivers::CaliptraError; use caliptra_drivers::FipsTestHook; use caliptra_hw_model::{BootParams, HwModel, InitParams, ModelError, ShaAccMode}; use common::*; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; #[test] #[cfg(not(feature = "test_env_immutable_rom"))] diff --git a/test/tests/fips_test_suite/services.rs b/test/tests/fips_test_suite/services.rs index e05788902c..a1fd791d13 100755 --- a/test/tests/fips_test_suite/services.rs +++ b/test/tests/fips_test_suite/services.rs @@ -12,7 +12,7 @@ use caliptra_image_types::ImageManifest; use common::*; use dpe::{commands::*, context::ContextHandle, response::Response, DPE_PROFILE}; use openssl::sha::{sha384, sha512}; -use zerocopy::{AsBytes, FromBytes}; +use zerocopy::{FromBytes, IntoBytes}; pub fn exec_cmd_sha_acc(hw: &mut T) { let msg: &[u8] = &[0u8; 4]; @@ -329,7 +329,7 @@ pub fn exec_cmd_stash_measurement(hw: &mut T) { assert_eq!(stash_measurement_resp.dpe_result, 0); } -pub fn exec_fw_info(hw: &mut T, fw_image: &Vec) { +pub fn exec_fw_info(hw: &mut T, fw_image: &[u8]) { let payload = MailboxReqHeader { chksum: caliptra_common::checksum::calc_checksum(u32::from(CommandId::FW_INFO), &[]), }; @@ -340,7 +340,7 @@ pub fn exec_fw_info(hw: &mut T, fw_image: &Vec) { ) .unwrap(); - let manifest = ImageManifest::read_from_prefix(&**fw_image).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); @@ -454,7 +454,7 @@ pub fn exec_dpe_get_profile(hw: &mut T) { } pub fn exec_dpe_init_ctx(hw: &mut T) { - let resp = execute_dpe_cmd(hw, &mut Command::InitCtx(InitCtxCmd::new_simulation())); + let resp = execute_dpe_cmd(hw, &mut Command::InitCtx(&InitCtxCmd::new_simulation())); let Response::InitCtx(init_ctx_resp) = resp else { panic!("Wrong response type!"); @@ -470,7 +470,7 @@ pub fn exec_dpe_derive_ctx(hw: &mut T) { tci_type: 0, target_locality: 0, }; - let resp = execute_dpe_cmd(hw, &mut Command::DeriveContext(derive_context_cmd)); + let resp = execute_dpe_cmd(hw, &mut Command::DeriveContext(&derive_context_cmd)); let Response::DeriveContext(derive_ctx_resp) = resp else { panic!("Wrong response type!"); }; @@ -490,7 +490,7 @@ pub fn exec_dpe_certify_key(hw: &mut T) { flags: CertifyKeyFlags::empty(), format: CertifyKeyCmd::FORMAT_CSR, }; - let resp = execute_dpe_cmd(hw, &mut Command::CertifyKey(certify_key_cmd)); + let resp = execute_dpe_cmd(hw, &mut Command::CertifyKey(&certify_key_cmd)); let Response::CertifyKey(certify_key_resp) = resp else { panic!("Wrong response type!"); @@ -522,7 +522,7 @@ pub fn exec_dpe_sign(hw: &mut T) { digest: TEST_DIGEST, }; - let resp = execute_dpe_cmd(hw, &mut Command::Sign(sign_cmd)); + let resp = execute_dpe_cmd(hw, &mut Command::Sign(&sign_cmd)); let Response::Sign(sign_resp) = resp else { panic!("Wrong response type!"); @@ -537,7 +537,7 @@ pub fn exec_rotate_ctx(hw: &mut T) { handle: ContextHandle::default(), flags: RotateCtxFlags::empty(), }; - let resp = execute_dpe_cmd(hw, &mut Command::RotateCtx(rotate_ctx_cmd)); + let resp = execute_dpe_cmd(hw, &mut Command::RotateCtx(&rotate_ctx_cmd)); let Response::RotateCtx(rotate_ctx_resp) = resp else { panic!("Wrong response type!"); @@ -550,7 +550,7 @@ pub fn exec_get_cert_chain(hw: &mut T) { offset: 0, size: 2048, }; - let resp = execute_dpe_cmd(hw, &mut Command::GetCertificateChain(get_cert_chain_cmd)); + 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!"); @@ -563,7 +563,7 @@ pub fn exec_destroy_ctx(hw: &mut T) { let destroy_ctx_cmd = DestroyCtxCmd { handle: ContextHandle::default(), }; - execute_dpe_cmd(hw, &mut Command::DestroyCtx(destroy_ctx_cmd)); + execute_dpe_cmd(hw, &mut Command::DestroyCtx(&destroy_ctx_cmd)); } pub fn exec_cmd_disable_attestation(hw: &mut T) {