diff --git a/libs/bao1x-api/Cargo.toml b/libs/bao1x-api/Cargo.toml index 39c5dc95f..9f0a2f54d 100644 --- a/libs/bao1x-api/Cargo.toml +++ b/libs/bao1x-api/Cargo.toml @@ -15,6 +15,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [ ], optional = true } bytemuck = { version = "1.24", features = ["derive"] } bitbybit = "1.4.0" +arbitrary-int = "1.2" [features] std = ["derive-rkyv", "xous-names", "xous-ipc"] diff --git a/libs/bao1x-api/src/offsets.rs b/libs/bao1x-api/src/offsets.rs index c26db0326..f4c91b1b4 100644 --- a/libs/bao1x-api/src/offsets.rs +++ b/libs/bao1x-api/src/offsets.rs @@ -2,3 +2,339 @@ pub mod baosec; pub mod common; pub use common::*; pub mod dabao; +use core::ops::Range; + +use arbitrary_int::{Number, u4}; +use bitbybit::bitfield; + +pub const KEY_SLOT_START: usize = 0x603F_0000; +pub const KEY_SLOT_LEN: usize = 0x1_0000; +pub const MAX_KEY_SLOTS: usize = KEY_SLOT_LEN / SLOT_ELEMENT_LEN_BYTES; +pub const DATA_SLOT_START: usize = 0x603E_0000; +pub const DATA_SLOT_LEN: usize = 0x1_0000; +pub const MAX_DATA_SLOTS: usize = DATA_SLOT_LEN / SLOT_ELEMENT_LEN_BYTES; +pub const SLOT_ELEMENT_LEN_BYTES: usize = 256 / 8; + +pub const ACRAM_DATASLOT_START: usize = 0x603D_C000; +pub const ACRAM_DATASLOT_LEN: usize = 0x2000; +pub const ACRAM_KEYSLOT_START: usize = 0x603D_E000; +pub const ACRAM_KEYSLOT_LEN: usize = 0x2000; +// pub const ACRAM_GKEYSLOT_START: usize = 0x603D_E400; // This is mentioned in the docs but I don't see it in +// the code? + +#[bitfield(u32)] +#[derive(PartialEq, Eq)] +pub struct DataSlotAccess { + #[bit(24, rw)] + write_mode: bool, + #[bit(23, rw)] + fw1: bool, + #[bit(22, rw)] + fw0: bool, + #[bit(21, rw)] + boot1: bool, + #[bit(20, rw)] + boot0: bool, + #[bits(8..=15, rw)] + seg_id: u8, + #[bit(3, rw)] + sce_wr_dis: bool, + #[bit(2, rw)] + sce_rd_dis: bool, + #[bit(1, rw)] + core_wr_dis: bool, + #[bit(0, rw)] + core_rd_dis: bool, +} + +impl DataSlotAccess { + // This method is only valid in no-std currently. Not sure if there is even meaning for us + // to access this in the Xous environment, as this is primarily a secure boot construct + #[cfg(not(feature = "std"))] + pub fn get_entry(slot: usize) -> Self { + let slot_array = + unsafe { core::slice::from_raw_parts(ACRAM_DATASLOT_START as *const DataSlotAccess, 2048) }; + slot_array[slot] + } + + pub fn get_partition_access(&self) -> PartitionAccess { PartitionAccess::from_raw_u32(self.raw_value()) } + + pub fn set_partition_access(&mut self, pa: &PartitionAccess) { + *self = Self::new_with_raw_value((self.raw_value() & !(0xf << 20)) | (pa.to_raw_u4().as_u32() << 20)); + } +} + +#[bitfield(u32)] +#[derive(PartialEq, Eq)] +pub struct KeySlotAccess { + #[bits(24..=31, rw)] + akey_id: u8, + #[bit(23, rw)] + fw1: bool, + #[bit(22, rw)] + fw0: bool, + #[bit(21, rw)] + boot1: bool, + #[bit(20, rw)] + boot0: bool, + #[bits(8..=15, rw)] + seg_id: u8, + #[bit(3, rw)] + sce_wr_dis: bool, + #[bit(2, rw)] + sce_rd_dis: bool, + #[bit(1, rw)] + core_wr_dis: bool, + #[bit(0, rw)] + core_rd_dis: bool, +} + +impl KeySlotAccess { + // This method is only valid in no-std currently. Not sure if there is even meaning for us + // to access this in the Xous environment, as this is primarily a secure boot construct + #[cfg(not(feature = "std"))] + pub fn get_entry(slot: usize) -> Self { + let slot_array = + unsafe { core::slice::from_raw_parts(ACRAM_KEYSLOT_START as *const KeySlotAccess, 2048) }; + slot_array[slot] + } + + pub fn get_partition_access(&self) -> PartitionAccess { PartitionAccess::from_raw_u32(self.raw_value()) } + + pub fn set_partition_access(&mut self, pa: &PartitionAccess) { + *self = Self::new_with_raw_value((self.raw_value() & !(0xf << 20)) | (pa.to_raw_u4().as_u32() << 20)); + } +} + +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +pub enum AccessError { + /// Access is anticipated to be denied by the hardware. Users can attempt to still + /// bypass the access control, but the result will either be invalid data, returned, + /// a failed, write, or a security alarm being raised, depending on the hardware + /// enforcement policy at play. + AccessDenied, + /// Returned when data is written to a slot that only supports 0->1 transitions + /// and the provided data contains 1->0 transitions, but the 0->1 transitions + /// were in fact correctly set + OnlyOnes, + /// Returned when data written did not verify + WriteError, + /// Returned when the wrong type of access settings are passed for setting access + TypeError, + /// Returned when an index request is out of valid bounds + OutOfBounds, +} + +#[derive(PartialEq, Eq, Clone, Copy)] +/// Specifies what partitions can access a given slot. Some common patterns are +/// provided, a Custom field is also provided for other odd combinations. +pub enum PartitionAccess { + None, + All, + Boot0, + Boot1, + Fw0, + Fw1, + AllBoots, + AllFws, + /// Convenience option for API calls and tests that don't care about this portion + /// of the access control field + Unspecified, + /// Stores directly the bit pattern as should be written into the field, + /// complete with the sense inversion where 0 == access allowed. + Custom(u4), +} +impl PartitionAccess { + /// Takes in a raw u32 pattern from either DataSlotAccess or KeySlotAccess and + /// extracts the PartitionAccess code + pub fn from_raw_u32(raw: u32) -> Self { + // raw is inverted because a 0 means access is allowed. Inverting the pattern + // such that 1 means allowed makes the code more readable below. + // the bitfield coding is fw1:fw0:boot1:boot0 from MSB to LSB. + let code: u4 = u4::new(((!raw >> 20) & 0xF) as u8); + match code.value() { + 0b0000 => Self::None, + 0b1111 => Self::All, + 0b0001 => Self::Boot0, + 0b0010 => Self::Boot1, + 0b0100 => Self::Fw0, + 0b1000 => Self::Fw1, + 0b0011 => Self::AllBoots, + 0b1100 => Self::AllFws, + _ => Self::Custom(u4::new(((raw >> 20) & 0xF) as u8)), + } + } + + // internal function that translates the symbolic representation into a u4 that + // can be shifted into place. + fn to_raw_u4(&self) -> u4 { + match self { + Self::None => u4::new(!0b0000), + Self::All => u4::new(!0b1111), + Self::Boot0 => u4::new(!0b0001), + Self::Boot1 => u4::new(!0b0010), + Self::Fw0 => u4::new(!0b0100), + Self::Fw1 => u4::new(!0b1000), + Self::AllBoots => u4::new(!0b0011), + Self::AllFws => u4::new(!0b1100), + // Panic is the correct behavior here because it's a static code bug to try and use this coding in + // this fashion. + Self::Unspecified => panic!("Attempt to resolve an unspecified access pattern"), + Self::Custom(f) => *f, + } + } +} + +/// `SlotIndex` encodes the index of a given slot and the *specification* of what the access +/// rights should be for that slot. The actual enforcement is done by hardware, so if someone +/// tries to "lie" to the API by creating a SlotIndex specifier with an inaccurate `PartitionAccess` +/// spec, hardware will ignore it. +/// +/// The reason the two are bundled together is that semantic priority is given to getting the spec right +/// in the constants in this crate that define the access control tables. +#[derive(PartialEq, Eq, Clone)] +pub enum SlotIndex { + Data(usize, PartitionAccess), + DataRange(Range, PartitionAccess), + Key(usize, PartitionAccess), + KeyRange(Range, PartitionAccess), +} +impl SlotIndex { + /// Returns `OutOfBounds` error if the index specified in the slot is out of bounds. + pub fn try_into_data_offset(&self) -> Result { + match self { + Self::Data(index, _) => { + if *index < MAX_DATA_SLOTS { + Ok(*index * SLOT_ELEMENT_LEN_BYTES) + } else { + Err(AccessError::OutOfBounds) + } + } + Self::Key(index, _) => { + if *index < MAX_KEY_SLOTS { + Ok(*index * SLOT_ELEMENT_LEN_BYTES) + } else { + Err(AccessError::OutOfBounds) + } + } + _ => Err(AccessError::TypeError), + } + } + + pub fn try_into_data_iter(&self) -> Result { + match self { + Self::Data(index, _) => { + if *index < MAX_DATA_SLOTS { + Ok(SlotOffsetIter::Single(core::iter::once(*index * SLOT_ELEMENT_LEN_BYTES))) + } else { + Err(AccessError::OutOfBounds) + } + } + Self::DataRange(range, _) => { + if range.end > MAX_DATA_SLOTS { + return Err(AccessError::OutOfBounds); + } + Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * SLOT_ELEMENT_LEN_BYTES))) + } + Self::Key(index, _) => { + if *index < MAX_KEY_SLOTS { + Ok(SlotOffsetIter::Single(core::iter::once(*index * SLOT_ELEMENT_LEN_BYTES))) + } else { + Err(AccessError::OutOfBounds) + } + } + Self::KeyRange(range, _) => { + if range.end > MAX_KEY_SLOTS { + return Err(AccessError::OutOfBounds); + } + Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * SLOT_ELEMENT_LEN_BYTES))) + } + } + } + + pub fn try_into_acl_offset(&self) -> Result { + match self { + Self::Data(index, _) => { + if *index < MAX_DATA_SLOTS { + Ok(*index * size_of::()) + } else { + Err(AccessError::OutOfBounds) + } + } + Self::Key(index, _) => { + if *index < MAX_KEY_SLOTS { + Ok(*index * size_of::()) + } else { + Err(AccessError::OutOfBounds) + } + } + _ => Err(AccessError::TypeError), + } + } + + pub fn try_into_acl_iter(&self) -> Result { + const ACL_SIZE: usize = core::mem::size_of::(); + + match self { + Self::Data(index, _) => { + if *index < MAX_DATA_SLOTS { + Ok(SlotOffsetIter::Single(core::iter::once(*index * ACL_SIZE))) + } else { + Err(AccessError::OutOfBounds) + } + } + Self::DataRange(range, _) => { + if range.end > MAX_DATA_SLOTS { + return Err(AccessError::OutOfBounds); + } + Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * ACL_SIZE))) + } + Self::Key(index, _) => { + if *index < MAX_KEY_SLOTS { + Ok(SlotOffsetIter::Single(core::iter::once(*index * ACL_SIZE))) + } else { + Err(AccessError::OutOfBounds) + } + } + Self::KeyRange(range, _) => { + if range.end > MAX_KEY_SLOTS { + return Err(AccessError::OutOfBounds); + } + Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * ACL_SIZE))) + } + } + } +} + +// Custom iterator enum for zero-cost abstraction +pub enum SlotOffsetIter { + Single(core::iter::Once), + Range(core::iter::Map, fn(usize) -> usize>), +} + +impl Iterator for SlotOffsetIter { + type Item = usize; + + fn next(&mut self) -> Option { + match self { + Self::Single(iter) => iter.next(), + Self::Range(iter) => iter.next(), + } + } + + fn size_hint(&self) -> (usize, Option) { + match self { + Self::Single(iter) => iter.size_hint(), + Self::Range(iter) => iter.size_hint(), + } + } +} + +impl ExactSizeIterator for SlotOffsetIter { + fn len(&self) -> usize { + match self { + Self::Single(iter) => iter.len(), + Self::Range(iter) => iter.len(), + } + } +} diff --git a/libs/bao1x-api/src/offsets/baosec.rs b/libs/bao1x-api/src/offsets/baosec.rs index 35f9d5942..2989b1e42 100644 --- a/libs/bao1x-api/src/offsets/baosec.rs +++ b/libs/bao1x-api/src/offsets/baosec.rs @@ -1,5 +1,7 @@ use xous::arch::PAGE_SIZE; +use crate::offsets::{PartitionAccess, SlotIndex}; + // we actually have 16MiB on the initial prototypes, but constraining to smaller for cost reduction pub const SPI_FLASH_LEN: usize = 8192 * 1024; pub const SPI_FLASH_ID_MASK: u32 = 0xff_ff_ff; @@ -40,3 +42,63 @@ pub const APP_RRAM_LEN: usize = 0; // Regulator voltage target at boot pub const CPU_VDD_LDO_BOOT_MV: u32 = 810; pub const DEFAULT_FCLK_FREQUENCY: u32 = 700_000_000; + +// =========== KEY SLOTS ============== +/// The `ROOT_SEED` is the "mothership" secret that all device identity and secrets +/// are derived from. The seed may be blended with other bits of data scattered about +/// the RRAM array, other device identifiers and hardware measurements to create the final +/// device secret key. +pub const ROOT_SEED: SlotIndex = SlotIndex::Key(256, PartitionAccess::Fw0); + +/// The `RMA_KEY` is a secret parameter that is unique per-device secret which is recorded +/// at manufacturing time. Its purpose is to facilitate the creation of a signed RMA +/// authorization certificate which upon receipt would blank the device and unlock various +/// features for debugging failed hardware. +pub const RMA_KEY: SlotIndex = SlotIndex::Key(257, PartitionAccess::Fw0); + +/// Reserved for use as a CP to FT tracking cookie. This is used to help track inventory +/// between CP and FT, if such a feature is desired in the supply chain. +pub const CP_COOKIE: SlotIndex = SlotIndex::Key(258, PartitionAccess::Fw0); + +/// `NUISANCE_KEYS` are hashed together with `ROOT_SEED` to derive the core secret. +/// Their primary purpose is to annoy microscopists trying to read the secret key by +/// directly imaging the RRAM array. They also exist to reduce power side channels +/// created upon accessing keys in combination with `CHAFF_KEYS`. Note there is ECC +/// on the data (2C2D on top of 128 bits) so any readout with better than 97% accuracy +/// can trivially rely on ECC to repair the results. +/// +/// The placement is picked based upon two competing theories: +/// - Data stored next to each other will be harder to read out because the simultaneous activation of +/// read-out word lines via secondary electron leakage will cause the data in adjacent cells to +/// super-impose on the bitline. +/// - Data stored far from each other will be harder to read out based on the difficulty of achieving +/// flatness & uniformity in delayering over long distances. +/// +/// Thus 2x 4k pages on either end of the key range are carved out for the nuisance keys. +pub const NUISANCE_KEYS_0: SlotIndex = SlotIndex::KeyRange(0..128, PartitionAccess::Fw0); +pub const NUISANCE_KEYS_1: SlotIndex = SlotIndex::KeyRange(1920..2048, PartitionAccess::Fw0); +pub const NUISANCE_KEYS: [SlotIndex; 2] = [NUISANCE_KEYS_0, NUISANCE_KEYS_1]; + +/// `CHAFF_KEYS` are a bank of keys that are hashed into the key array, but instead of +/// being read out in strict order, they are read in a random permutation every time. +/// The read-out data is XOR'd together into a single 256-bit key, and then hashed into +/// the key. The reason for this procedure is if there are strong power side channels in +/// the key read-out, the CHAFF_KEYS have a random ordering that frustrates attempts to +/// correlate the power signature over repeated reboots. The read-out of the CHAFF_KEYS +/// needs to be strictly constant time, i.e. the permutation function can't leak a +/// side channel that reveals what the ordering is. +pub const CHAFF_KEYS: SlotIndex = SlotIndex::KeyRange(128..256, PartitionAccess::Fw0); + +/// All the slots of concern located in a single iterator. The idea is that everything is +/// condensed here and used to check for access integrity using the array below. +pub const ALL_SLOTS: [SlotIndex; 9] = [ + crate::offsets::SERIAL_NUMBER, + crate::offsets::UUID, + crate::offsets::IFR_HASH, + ROOT_SEED, + RMA_KEY, + CP_COOKIE, + NUISANCE_KEYS_0, + NUISANCE_KEYS_1, + CHAFF_KEYS, +]; diff --git a/libs/bao1x-api/src/offsets/common.rs b/libs/bao1x-api/src/offsets/common.rs index 5e692a325..c9e12b430 100644 --- a/libs/bao1x-api/src/offsets/common.rs +++ b/libs/bao1x-api/src/offsets/common.rs @@ -1,3 +1,6 @@ +use crate::offsets::PartitionAccess; +use crate::offsets::SlotIndex; + // These define the start region of the partition. In general, each partition has signature // metadata in them, but the first word in the signature is a jump instruction that takes you // to the actual boot code. @@ -20,7 +23,6 @@ pub const SWAP_UF2_LEN: usize = 0x0800_0000; // 128 MiB pub trait OneWayEncoding: TryFrom { const OFFSET: usize; } - macro_rules! encode_oneway { ( #[offset = $offset:literal] @@ -61,6 +63,7 @@ macro_rules! encode_oneway { }; } +// =========== ONE WAY COUNTER SLOTS ============== encode_oneway! { #[offset = 80] pub enum BootWaitCoding { @@ -86,6 +89,15 @@ encode_oneway! { } } +/// Incremented from 0 if chip-probe boot setup has been finished. +pub const CP_BOOT_SETUP_DONE: usize = 83; + +/// Incremented from 0 if system boot setup has been finished. This is for systems that have +/// a supplemental entropy source and want to replace the generated keys with keys that are +/// derived from a blend of entropy sources. +pub const SYS_BOOT_SETUP_DONE: usize = 84; + +/// Total number of public key slots in the system. Pubkey revocations are at the "top of range" pub const PUBKEY_SLOTS: usize = 4; /// Offset in the one-way counter array for loader key revocations. Provisions for up to four /// key slots, from [116..=120]. @@ -98,3 +110,24 @@ pub const BOOT1_REVOCATION_OFFSET: usize = LOADER_REVOCATION_OFFSET + PUBKEY_SLO pub const BOOT0_REVOCATION_OFFSET: usize = BOOT1_REVOCATION_OFFSET + PUBKEY_SLOTS; // slots from 128..=255 are totally unused by the boot logic + +// =========== DATA SLOTS ============== + +/// The 'SERIAL_NUMBER` is a publicly readable number that has a "weak" guarantee of +/// uniqueness, in that there is nothing essentially that prevents duplicates, forgeries +/// or procedural errors replicating this. The serial number also is not strictly incrementing +/// nor does it have any guarantee of being a monotonic or smoothly spaced out. It could +/// even be all zeros (in which case LOT_CODE should be used). Its primary +/// purpose is to serve as a debugging hint for practical manufacturing issues. You are +/// free to read it and use it, but beware. +pub const SERIAL_NUMBER: SlotIndex = SlotIndex::Data(0, PartitionAccess::All); + +/// `UUID` is a 256-bit random number that can be used as a UUID for the chip. It is publicly +/// readable and generated by a TRNG. This is suitable for putting into a KDF and generating +/// salts for algorithms that require such a parameter. +pub const UUID: SlotIndex = SlotIndex::Data(1, PartitionAccess::All); + +/// `IFR_HASH` is a provisional slot for a hash of the IFR region. Whether the hash is meaningful +/// or not depends on if the chip is booted before it is sealed. At the time of writing, it's +/// not clear if the wafer probe infrastructure will allow this. +pub const IFR_HASH: SlotIndex = SlotIndex::Data(2, PartitionAccess::All); diff --git a/libs/bao1x-api/src/offsets/dabao.rs b/libs/bao1x-api/src/offsets/dabao.rs index 76b1c556a..d30ddd89e 100644 --- a/libs/bao1x-api/src/offsets/dabao.rs +++ b/libs/bao1x-api/src/offsets/dabao.rs @@ -1,3 +1,5 @@ +use crate::offsets::SlotIndex; + // no external SPI pub const SPI_FLASH_LEN: usize = 0; pub const SPI_FLASH_ID_MASK: u32 = 0xff_ff_ff; @@ -27,3 +29,8 @@ pub const APP_RRAM_LEN: usize = 0xD_A000 + crate::signatures::SIGBLOCK_LEN; // Regulator voltage target at boot pub const CPU_VDD_LDO_BOOT_MV: u32 = 810; pub const DEFAULT_FCLK_FREQUENCY: u32 = 700_000_000; + +/// All the slots of concern located in a single iterator. The idea is that everything is +/// condensed here and used to check for access integrity using the array below. +pub const ALL_SLOTS: [SlotIndex; 3] = + [crate::offsets::SERIAL_NUMBER, crate::offsets::UUID, crate::offsets::IFR_HASH];