diff --git a/bao1x-boot/blobs/ifr_0x340.bin b/bao1x-boot/blobs/ifr_0x340.bin index 0dce25f4d..9870828e3 100644 Binary files a/bao1x-boot/blobs/ifr_0x340.bin and b/bao1x-boot/blobs/ifr_0x340.bin differ diff --git a/bao1x-boot/boot1/src/main.rs b/bao1x-boot/boot1/src/main.rs index 49af9bbee..dac9958d1 100644 --- a/bao1x-boot/boot1/src/main.rs +++ b/bao1x-boot/boot1/src/main.rs @@ -32,7 +32,7 @@ use crate::secboot::try_boot; // Notes: // - "Towards" - not a release yet, but working towards the stated milestone // - Eliminating "Towards" is done at the tag-out point. -const RELEASE_DESCRIPTION: &'static str = "Towards Alpha-1"; +const RELEASE_DESCRIPTION: &'static str = "Alpha-1"; static UART_RX: Mutex>> = Mutex::new(RefCell::new(VecDeque::new())); #[allow(dead_code)] @@ -78,7 +78,10 @@ pub unsafe extern "C" fn rust_entry() -> ! { crate::println_d!("TX_IDLE: {:?}", crate::platform::usb::TX_IDLE.load(Ordering::SeqCst)); let perclk: u32; (board_type, perclk) = crate::platform::early_init(board_type); + #[cfg(not(feature = "alt-boot1"))] crate::println!("\n~~Boot1 up! ({}: {})~~\n", crate::version::SEMVER, RELEASE_DESCRIPTION); + #[cfg(feature = "alt-boot1")] + crate::println!("\n~~Alt-Boot1 up! ({}: {})~~\n", crate::version::SEMVER, RELEASE_DESCRIPTION); crate::println!("Configured board type: {:?}", board_type); if board_type == BoardTypeCoding::Baosec { IS_BAOSEC.store(true, Ordering::SeqCst); @@ -91,6 +94,7 @@ pub unsafe extern "C" fn rust_entry() -> ! { } board_type = one_way.get_decoded::().expect("owc coding error"); crate::println!("Re-configured board type: {:?}", board_type); + IS_BAOSEC.store(false, Ordering::SeqCst); } } diff --git a/bao1x-boot/boot1/src/platform/bao1x/slots.rs b/bao1x-boot/boot1/src/platform/bao1x/slots.rs index 8297713c2..216888f3e 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/slots.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/slots.rs @@ -72,6 +72,13 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) { crate::println!("Public ID init done."); } + // Delegate in-system key setup to the OS. Don't do it in the bootloader. This code is + // too hard to get right to be doing it here, and there is no ostensible security advantage + // in doing it at this stage versus in the system. Reasoning: the in-system key setup would + // be done in the factory, post-wafer probe, regardless. Whether it's hard-coded into the boot1 + // stage or left to be flexible based on the OS's needs doesn't make a difference because the + // point of keying is still going to be the factory. + /* if (*board_type == bao1x_api::BoardTypeCoding::Baosec && owc.get(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() == 0) || (*board_type == bao1x_api::BoardTypeCoding::Dabao @@ -109,6 +116,7 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) { } crate::println!("Secret ID init done."); } + */ #[cfg(feature = "print-ifr")] print_ifr(); @@ -154,10 +162,6 @@ fn check_and_fix_acls(rram: &mut Reram, slot_mgr: &mut SlotManager, slot_list: & let mut is_consistent = true; let mut acl = match slot_mgr.get_acl(&slot_element) { Ok(settings) => settings, - Err(bao1x_api::AccessError::KeyAclInconsistency(prototype)) => { - is_consistent = false; - AccessSettings::Key(prototype) - } Err(bao1x_api::AccessError::DataAclInconsistency(prototype)) => { is_consistent = false; AccessSettings::Data(prototype) @@ -167,9 +171,6 @@ fn check_and_fix_acls(rram: &mut Reram, slot_mgr: &mut SlotManager, slot_list: & let (pa, rw) = slot_element.get_access_spec(); let is_correct = match acl { AccessSettings::Data(sa) => sa.get_partition_access() == pa && sa.get_rw_permissions() == rw, - AccessSettings::Key(sa) => { - sa.get_partition_access() == pa && sa.get_rw_permissions() == rw && sa.akey_id() == 31 - } }; if !is_correct || !is_consistent { crate::println!( @@ -184,14 +185,14 @@ fn check_and_fix_acls(rram: &mut Reram, slot_mgr: &mut SlotManager, slot_list: & sa.set_partition_access(&pa); sa.set_rw_permissions(rw); } - AccessSettings::Key(sa) => { - sa.set_partition_access(&pa); - sa.set_rw_permissions(rw); - sa.set_akey_id(0xFF); // 0xff disables key chaining to access the key + } + crate::println!("Writing ACL raw value: {:x?}", acl); + match slot_mgr.set_acl(rram, slot_element, &acl) { + Ok(_) => {} + Err(e) => { + crate::println!("Couldn't set ACL for {:?} ({:?})", slot_element, e); } } - crate::println!("Fixed ACL raw value: {:x?}", acl); - slot_mgr.set_acl(rram, slot_element, &acl).unwrap(); } } } @@ -225,16 +226,6 @@ fn print_slots(slot_mgr: &SlotManager, slot_list: &[SlotIndex]) { bytes ); }, - SlotType::Key => unsafe { - let bytes = slot_mgr.read_key_slot(data_index); - let acl = slot_mgr.get_key_acl(acl_index); - crate::println!( - " Key {} ({:x?}): {:x?}", - data_index / SLOT_ELEMENT_LEN_BYTES, - acl, - bytes - ); - }, } } } diff --git a/bao1x-boot/boot1/src/platform/bao1x/usb/handlers.rs b/bao1x-boot/boot1/src/platform/bao1x/usb/handlers.rs index 277856cc2..2ca9fbb0d 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/usb/handlers.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/usb/handlers.rs @@ -69,8 +69,12 @@ pub const FS_MAX_PKT_SIZE: usize = 64; pub const HS_MAX_PKT_SIZE: usize = 512; pub(crate) fn enable_mass_storage_eps(this: &mut CorigineUsb, ep_num: u8) { - this.ep_enable(ep_num, USB_RECV, HS_MAX_PKT_SIZE as _, EpType::BulkOutbound); - this.ep_enable(ep_num, USB_SEND, HS_MAX_PKT_SIZE as _, EpType::BulkInbound); + let mps = match this.get_speed() { + PortSpeed::Fs => FS_MAX_PKT_SIZE, + _ => HS_MAX_PKT_SIZE, + }; + this.ep_enable(ep_num, USB_RECV, mps as _, EpType::BulkOutbound); + this.ep_enable(ep_num, USB_SEND, mps as _, EpType::BulkInbound); } // Call from USB_REQ_SET_CONFIGURATION after setting device state to Configured @@ -78,12 +82,20 @@ pub(crate) fn enable_composite_eps(this: &mut CorigineUsb) { // MSD endpoints enable_mass_storage_eps(this, 1); + let int_mps = match this.get_speed() { + PortSpeed::Fs => FS_INT_MPS, + _ => HS_INT_MPS, + }; // CDC notification IN (interrupt) - this.ep_enable(2, USB_SEND, HS_INT_MPS as _, EpType::IntrInbound); + this.ep_enable(2, USB_SEND, int_mps as _, EpType::IntrInbound); + let bulk_mps = match this.get_speed() { + PortSpeed::Fs => FS_BULK_MPS, + _ => HS_BULK_MPS, + }; // CDC data bulk OUT and IN - this.ep_enable(3, USB_RECV, HS_BULK_MPS as _, EpType::BulkOutbound); - this.ep_enable(3, USB_SEND, HS_BULK_MPS as _, EpType::BulkInbound); + this.ep_enable(3, USB_RECV, bulk_mps as _, EpType::BulkOutbound); + this.ep_enable(3, USB_SEND, bulk_mps as _, EpType::BulkInbound); } pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, length: usize) { diff --git a/bao1x-boot/boot1/src/repl.rs b/bao1x-boot/boot1/src/repl.rs index 8dd2417c6..95837a700 100644 --- a/bao1x-boot/boot1/src/repl.rs +++ b/bao1x-boot/boot1/src/repl.rs @@ -479,7 +479,11 @@ impl Repl { crate::println!("Permissions (actual): {:x?}", acl); // attempt to clear the permissions, making the keys malleable slot_mgr - .set_acl(&mut rram, &key, &AccessSettings::Key(KeySlotAccess::new_with_raw_value(0))) + .set_acl( + &mut rram, + &key, + &AccessSettings::Data(DataSlotAccess::new_with_raw_value(0)), + ) .ok(); // if we can't clear, that's by design let acl = slot_mgr.get_acl(&key).unwrap(); diff --git a/bao1x-boot/boot1/src/secboot.rs b/bao1x-boot/boot1/src/secboot.rs index 39fcc1efc..b6ebf15d5 100644 --- a/bao1x-boot/boot1/src/secboot.rs +++ b/bao1x-boot/boot1/src/secboot.rs @@ -49,7 +49,7 @@ pub fn try_boot(or_die: bool) { if tag == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT { - crate::println!("Developer key detected, ensuring secret are erased"); + crate::println!("Developer key detected, ensuring secrets are erased"); bao1x_hal::sigcheck::erase_secrets(); } // this has to be called *after* erase_secrets, because we can't erase the secrets diff --git a/baosign.ps1 b/baosign.ps1 index ec0e19d3f..02a2fa240 100644 --- a/baosign.ps1 +++ b/baosign.ps1 @@ -9,7 +9,7 @@ param( [Parameter(Mandatory = $true)] - [ValidateSet("baremetal", "dabao", "baosec")] + [ValidateSet("baremetal", "dabao", "baosec", "bootloader", "kernel", "loader", "swap", "apps", "boot1", "alt-boot1")] [string]$Config, [Parameter(Mandatory = $false)] @@ -26,25 +26,42 @@ $SIGNING_DIR = ".\signing\fido-signer" # Define configurations and their associated images with function codes # Modify these mappings according to your actual image names and function codes $configurations = @{ - "baremetal" = @( + "bootloader" = @( @{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }, @{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }, + @{ Image = "bao1x-alt-boot1.img"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" } + ) + "baremetal" = @( @{ Image = "baremetal.img"; FunctionCode = "baremetal" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" } ) - "dabao" = @( - @{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }, - @{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }, + "dabao" = @( @{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } @{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } - @{ Image = "app.img"; FunctionCode = "app" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } + @{ Image = "apps.img"; FunctionCode = "app" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } ) - "baosec" = @( - @{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }, - @{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }, + "baosec" = @( @{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } @{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } @{ Image = "swap.img"; FunctionCode = "swap" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } ) + "kernel" = @( + @{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } + ) + "loader" = @( + @{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } + ) + "swap" = @( + @{ Image = "swap.img"; FunctionCode = "swap" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } + ) + "apps" = @( + @{ Image = "apps.img"; FunctionCode = "app" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } + ) + "boot1" = @( + @{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" } + ) + "alt-boot1" = @( + @{ Image = "bao1x-alt-boot1.img"; FunctionCode = "baremetal" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" } + ) } # Color output functions for better visibility diff --git a/baremetal/src/platform/bao1x/usb/handlers.rs b/baremetal/src/platform/bao1x/usb/handlers.rs index bc3921a7b..6a9e6dcd8 100644 --- a/baremetal/src/platform/bao1x/usb/handlers.rs +++ b/baremetal/src/platform/bao1x/usb/handlers.rs @@ -9,12 +9,20 @@ pub static TX_IDLE: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicB // Call from USB_REQ_SET_CONFIGURATION after setting device state to Configured pub(crate) fn enable_serial_eps(this: &mut CorigineUsb) { + let int_mps = match this.get_speed() { + PortSpeed::Fs => FS_INT_MPS, + _ => HS_INT_MPS, + }; // CDC notification IN (interrupt) - this.ep_enable(2, USB_SEND, HS_INT_MPS as _, EpType::IntrInbound); + this.ep_enable(2, USB_SEND, int_mps as _, EpType::IntrInbound); + let bulk_mps = match this.get_speed() { + PortSpeed::Fs => FS_BULK_MPS, + _ => HS_BULK_MPS, + }; // CDC data bulk OUT and IN - this.ep_enable(3, USB_RECV, HS_BULK_MPS as _, EpType::BulkOutbound); - this.ep_enable(3, USB_SEND, HS_BULK_MPS as _, EpType::BulkInbound); + this.ep_enable(3, USB_RECV, bulk_mps as _, EpType::BulkOutbound); + this.ep_enable(3, USB_SEND, bulk_mps as _, EpType::BulkInbound); } pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, length: usize) { diff --git a/libs/bao1x-api/src/offsets.rs b/libs/bao1x-api/src/offsets.rs index 3685693c5..1e7fd3e0e 100644 --- a/libs/bao1x-api/src/offsets.rs +++ b/libs/bao1x-api/src/offsets.rs @@ -7,9 +7,6 @@ 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; @@ -17,10 +14,6 @@ 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? pub const IFR_BASE: usize = 0x6040_0000; pub const IFR_LEN: usize = 0x400; /// This number is special: it only appears during certain portions of the chip life cycle in @@ -101,79 +94,6 @@ impl DataSlotAccess { } } -#[bitfield(u32)] -#[derive(PartialEq, Eq, Debug)] -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)); - } - - pub fn get_rw_permissions(&self) -> RwPerms { - match [self.core_rd_dis(), self.core_wr_dis()] { - [true, true] => RwPerms::Denied, - [false, true] => RwPerms::ReadOnly, - [true, false] => RwPerms::WriteOnly, - [false, false] => RwPerms::ReadWrite, - } - } - - pub fn set_rw_permissions(&mut self, spec: RwPerms) { - match spec { - RwPerms::Denied => { - self.set_core_rd_dis(true); - self.set_core_wr_dis(true); - } - RwPerms::ReadOnly => { - self.set_core_rd_dis(false); - self.set_core_wr_dis(true); - } - RwPerms::WriteOnly => { - self.set_core_rd_dis(true); - self.set_core_wr_dis(false); - } - RwPerms::ReadWrite => { - self.set_core_rd_dis(false); - self.set_core_wr_dis(false); - } - RwPerms::Unspecified => panic!("RwPerms must be specified"), - } - } -} - #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum AccessError { /// Access is anticipated to be denied by the hardware. Users can attempt to still @@ -196,7 +116,6 @@ pub enum AccessError { /// Returned when a set of slots that should have the same ACL don't. The value /// inside is the value of the first ACL in the set. DataAclInconsistency(DataSlotAccess), - KeyAclInconsistency(KeySlotAccess), } /// Enum to specify read/write permissions to a given slot. @@ -279,28 +198,22 @@ impl PartitionAccess { pub enum SlotIndex { Data(usize, PartitionAccess, RwPerms), DataRange(Range, PartitionAccess, RwPerms), - Key(usize, PartitionAccess, RwPerms), - KeyRange(Range, PartitionAccess, RwPerms), } #[derive(PartialEq, Eq, Clone, Debug)] pub enum SlotType { Data, - Key, } impl SlotIndex { pub fn get_access_spec(&self) -> (PartitionAccess, RwPerms) { match self { Self::Data(_, spec, rw) => (*spec, *rw), Self::DataRange(_, spec, rw) => (*spec, *rw), - Self::Key(_, spec, rw) => (*spec, *rw), - Self::KeyRange(_, spec, rw) => (*spec, *rw), } } pub fn get_type(&self) -> SlotType { match self { Self::Data(_, _, _) | Self::DataRange(_, _, _) => SlotType::Data, - Self::Key(_, _, _) | Self::KeyRange(_, _, _) => SlotType::Key, } } @@ -308,8 +221,6 @@ impl SlotIndex { match self { Self::Data(base, _, _) => *base, Self::DataRange(range, _, _) => range.start, - Self::Key(base, _, _) => *base, - Self::KeyRange(range, _, _) => range.start, } } @@ -317,8 +228,6 @@ impl SlotIndex { match self { Self::Data(_, _, _) => 1, Self::DataRange(range, _, _) => range.len(), - Self::Key(_, _, _) => 1, - Self::KeyRange(range, _, _) => range.len(), } } @@ -333,13 +242,6 @@ impl SlotIndex { Err(AccessError::OutOfBounds) } } - Self::Key(index, _, _) => { - if *index < MAX_KEY_SLOTS { - Ok(*index * SLOT_ELEMENT_LEN_BYTES) - } else { - Err(AccessError::OutOfBounds) - } - } Self::DataRange(range, _, _) => { let index = range.start; if range.end <= MAX_DATA_SLOTS { @@ -348,14 +250,6 @@ impl SlotIndex { Err(AccessError::OutOfBounds) } } - Self::KeyRange(range, _, _) => { - let index = range.start; - if range.end <= MAX_KEY_SLOTS { - Ok(index * SLOT_ELEMENT_LEN_BYTES) - } else { - Err(AccessError::OutOfBounds) - } - } } } @@ -374,19 +268,6 @@ impl SlotIndex { } 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))) - } } } @@ -399,13 +280,6 @@ impl SlotIndex { Err(AccessError::OutOfBounds) } } - Self::Key(index, _, _) => { - if *index < MAX_KEY_SLOTS { - Ok(*index * size_of::()) - } else { - Err(AccessError::OutOfBounds) - } - } Self::DataRange(range, _, _) => { if range.end <= MAX_DATA_SLOTS { Ok(range.start * size_of::()) @@ -413,13 +287,6 @@ impl SlotIndex { Err(AccessError::OutOfBounds) } } - Self::KeyRange(range, _, _) => { - if range.end <= MAX_KEY_SLOTS { - Ok(range.start * size_of::()) - } else { - Err(AccessError::OutOfBounds) - } - } } } @@ -440,19 +307,6 @@ impl SlotIndex { } 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))) - } } } } diff --git a/libs/bao1x-api/src/offsets/baosec.rs b/libs/bao1x-api/src/offsets/baosec.rs index aa238e022..d7bd88041 100644 --- a/libs/bao1x-api/src/offsets/baosec.rs +++ b/libs/bao1x-api/src/offsets/baosec.rs @@ -44,21 +44,21 @@ pub const DEFAULT_FCLK_FREQUENCY: u32 = 700_000_000; /// 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, RwPerms::ReadOnly); +pub const ROOT_SEED: SlotIndex = SlotIndex::Data(256, PartitionAccess::Fw0, RwPerms::ReadWrite); /// 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, RwPerms::ReadOnly); +pub const RMA_KEY: SlotIndex = SlotIndex::Data(257, PartitionAccess::Fw0, RwPerms::ReadWrite); /// 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. Blanked on entry /// to developer mode. -pub const CP_COOKIE: SlotIndex = SlotIndex::Key(258, PartitionAccess::Fw0, RwPerms::ReadWrite); +pub const CP_COOKIE: SlotIndex = SlotIndex::Data(258, PartitionAccess::Fw0, RwPerms::ReadWrite); /// The swap encryption key. Used to protect swap images beyond the signing key, if we so desire. -pub const SWAP_KEY: SlotIndex = SlotIndex::Key(259, PartitionAccess::Fw0, RwPerms::ReadOnly); +pub const SWAP_KEY: SlotIndex = SlotIndex::Data(259, PartitionAccess::Fw0, RwPerms::ReadWrite); /// `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 @@ -85,9 +85,9 @@ pub const SWAP_KEY: SlotIndex = SlotIndex::Key(259, PartitionAccess::Fw0, RwPerm /// numbered data slots. Some of the data slots in the first 8 slots will be read-only at CP time, and /// thus they can't be initialized with random data and be used as a nuisance key. This is a minor degradation /// in security margin. -pub const NUISANCE_KEYS_0: SlotIndex = SlotIndex::KeyRange(8..128, PartitionAccess::Fw0, RwPerms::ReadOnly); +pub const NUISANCE_KEYS_0: SlotIndex = SlotIndex::DataRange(8..128, PartitionAccess::Fw0, RwPerms::ReadWrite); pub const NUISANCE_KEYS_1: SlotIndex = - SlotIndex::KeyRange(1920..2048, PartitionAccess::Fw0, RwPerms::ReadOnly); + SlotIndex::DataRange(1920..2048, PartitionAccess::Fw0, RwPerms::ReadWrite); 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 @@ -109,7 +109,7 @@ pub const NUISANCE_KEYS: [SlotIndex; 2] = [NUISANCE_KEYS_0, NUISANCE_KEYS_1]; /// the chaff is cleared, we also don't care as much about side channels since we're now operating /// in a fundamentally insecure regime (e.g. developer mode - you can just read out the data by /// running your own code on the device). -pub const CHAFF_KEYS: SlotIndex = SlotIndex::KeyRange(128..256, PartitionAccess::Fw0, RwPerms::ReadWrite); +pub const CHAFF_KEYS: SlotIndex = SlotIndex::DataRange(128..256, PartitionAccess::Fw0, RwPerms::ReadWrite); /// 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. @@ -127,4 +127,4 @@ pub const DATA_SLOTS: [SlotIndex; 8] = [ /// In addition to these KEY_SLOTS, the DEVELOPER_MODE one way counter is a security-important parameter /// that should be included as domain separation in any KDF. pub const KEY_SLOTS: [SlotIndex; 6] = - [ROOT_SEED, RMA_KEY, CP_COOKIE, NUISANCE_KEYS_0, NUISANCE_KEYS_1, CHAFF_KEYS]; + [CP_COOKIE, RMA_KEY, ROOT_SEED, 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 8348d8a10..ddb4d1be6 100644 --- a/libs/bao1x-api/src/offsets/common.rs +++ b/libs/bao1x-api/src/offsets/common.rs @@ -175,11 +175,11 @@ pub const UUID: SlotIndex = SlotIndex::Data(1, PartitionAccess::Open, RwPerms::R /// `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, RwPerms::ReadOnly); +pub const IFR_HASH: SlotIndex = SlotIndex::Data(2, PartitionAccess::Open, RwPerms::ReadWrite); /// `WAFER_ID` is a copy of the lot ID + wafer ID + x/y position data that should be captured /// during CP. -pub const CP_ID: SlotIndex = SlotIndex::Data(3, PartitionAccess::All, RwPerms::ReadOnly); +pub const CP_ID: SlotIndex = SlotIndex::Data(3, PartitionAccess::Open, RwPerms::ReadWrite); /// Indelible versions of the public keys. The problem with the pubkeys in boot0 region is that /// boot0 itself has the ability to modify its own memory. A copy here can have a bit set in diff --git a/libs/bao1x-hal/src/acram.rs b/libs/bao1x-hal/src/acram.rs index 310f444ab..1ebfc16d0 100644 --- a/libs/bao1x-hal/src/acram.rs +++ b/libs/bao1x-hal/src/acram.rs @@ -137,27 +137,23 @@ impl OneWayCounter { #[derive(PartialEq, Eq, Debug)] pub enum AccessSettings { Data(DataSlotAccess), - Key(KeySlotAccess), } impl AccessSettings { pub fn raw_u32(&self) -> u32 { match self { Self::Data(d) => d.raw_value(), - Self::Key(d) => d.raw_value(), } } pub fn allows_cpu_read(&self) -> bool { match self { Self::Data(d) => !d.core_rd_dis(), - Self::Key(d) => !d.core_rd_dis(), } } pub fn allows_cpu_write(&self) -> bool { match self { Self::Data(d) => !d.core_wr_dis(), - Self::Key(d) => !d.core_wr_dis(), } } @@ -165,7 +161,6 @@ impl AccessSettings { pub fn is_set_only(&self) -> bool { match self { Self::Data(d) => d.write_mode(), - Self::Key(_d) => false, } } } @@ -181,9 +176,11 @@ pub enum AccessType { pub struct SlotManager { data_range: xous::MemoryRange, data_acl_range: xous::MemoryRange, - key_range: xous::MemoryRange, - key_acl_range: xous::MemoryRange, user_id: CoreuserId, + #[cfg(feature = "std")] + data_write_offset: xous::MemoryRange, + #[cfg(feature = "std")] + data_acl_write_offset: xous::MemoryRange, } impl SlotManager { @@ -206,21 +203,13 @@ impl SlotManager { ) .expect("Couldn't map ACL range"); #[cfg(feature = "std")] - let key_range = xous::map_memory( - xous::MemoryAddress::new(KEY_SLOT_START), - None, - KEY_SLOT_LEN, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("Couldn't map slot range"); + // safety: these ranges are valid and pre-aligned + let data_write_offset = unsafe { xous::MemoryRange::new(DATA_SLOT_START, DATA_SLOT_LEN).unwrap() }; #[cfg(feature = "std")] - let key_acl_range = xous::map_memory( - xous::MemoryAddress::new(ACRAM_KEYSLOT_START), - None, - ACRAM_KEYSLOT_LEN, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("Couldn't map ACL range"); + // safety: these ranges are valid and pre-aligned + let data_acl_write_offset = + unsafe { xous::MemoryRange::new(ACRAM_DATASLOT_START, ACRAM_DATASLOT_LEN).unwrap() }; + #[cfg(not(feature = "std"))] // safety: these ranges are valid and pre-aligned let data_range = unsafe { xous::MemoryRange::new(DATA_SLOT_START, DATA_SLOT_LEN).unwrap() }; @@ -228,13 +217,6 @@ impl SlotManager { // safety: these ranges are valid and pre-aligned let data_acl_range = unsafe { xous::MemoryRange::new(ACRAM_DATASLOT_START, ACRAM_DATASLOT_LEN).unwrap() }; - #[cfg(not(feature = "std"))] - // safety: these ranges are valid and pre-aligned - let key_range = unsafe { xous::MemoryRange::new(KEY_SLOT_START, KEY_SLOT_LEN).unwrap() }; - #[cfg(not(feature = "std"))] - // safety: these ranges are valid and pre-aligned - let key_acl_range = - unsafe { xous::MemoryRange::new(ACRAM_KEYSLOT_START, ACRAM_KEYSLOT_LEN).unwrap() }; #[cfg(feature = "std")] let user_id = if xous::process::id() == crate::coreuser::TRUSTED_PID as u32 { @@ -246,15 +228,17 @@ impl SlotManager { #[cfg(not(feature = "std"))] let user_id = crate::coreuser::TRUSTED_USER; - Self { data_range, data_acl_range, key_range, key_acl_range, user_id } + #[cfg(not(feature = "std"))] + let ret = Self { data_range, data_acl_range, user_id }; + #[cfg(feature = "std")] + let ret = Self { data_range, data_acl_range, user_id, data_write_offset, data_acl_write_offset }; + ret } #[cfg(feature = "std")] pub fn register_mapping(&self, rram: &mut Reram) { rram.add_range(DATA_SLOT_START - utralib::HW_RERAM_MEM, self.data_range); rram.add_range(ACRAM_DATASLOT_START - utralib::HW_RERAM_MEM, self.data_acl_range); - rram.add_range(KEY_SLOT_START - utralib::HW_RERAM_MEM, self.key_range); - rram.add_range(ACRAM_KEYSLOT_START - utralib::HW_RERAM_MEM, self.key_acl_range); } pub fn read(&self, slot: &SlotIndex) -> Result<&[u8], AccessError> { @@ -269,15 +253,9 @@ impl SlotManager { SlotIndex::Data(_, _, _) => unsafe { &self.data_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES] }, - SlotIndex::Key(_, _, _) => unsafe { - &self.key_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES] - }, SlotIndex::DataRange(range, _, _) => unsafe { &self.data_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES * range.len()] }, - SlotIndex::KeyRange(range, _, _) => unsafe { - &self.key_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES * range.len()] - }, }) } else { Err(AccessError::AccessDenied) @@ -288,26 +266,22 @@ impl SlotManager { /// There is access or type checking done. This is a "raw read" primitive mostly used for debugging. pub unsafe fn read_data_slot(&self, absolute_offset: usize) -> &[u8] { let ptr: *const u8 = &self.data_range.as_slice::()[absolute_offset] as *const u8; - crate::println!("data loc: {:x}", ptr as usize); + crate::println!("data loc: {:x}, offset: {:x}", ptr as usize, absolute_offset); &self.data_range.as_slice()[absolute_offset..absolute_offset + SLOT_ELEMENT_LEN_BYTES] } - /// Safety: the caller must resolve the index into either the data or the key array correctly. - /// There is access or type checking done. This is a "raw read" primitive mostly used for debugging. - pub unsafe fn read_key_slot(&self, absolute_offset: usize) -> &[u8] { - let ptr: *const u8 = &self.key_range.as_slice::()[absolute_offset] as *const u8; - crate::println!("key loc: {:x}", ptr as usize); - &self.key_range.as_slice()[absolute_offset..absolute_offset + SLOT_ELEMENT_LEN_BYTES] - } - pub fn write(&self, writer: &mut Reram, slot: &SlotIndex, value: &[u8]) -> Result<(), AccessError> { let acl = self.get_acl(slot)?; if self.user_id.is_accessible(&acl, &AccessType::Write) { let offset = slot.try_into_data_offset()?; + #[cfg(not(feature = "std"))] let range = match slot { SlotIndex::Data(_, _, _) | SlotIndex::DataRange(_, _, _) => &self.data_range, - SlotIndex::Key(_, _, _) | SlotIndex::KeyRange(_, _, _) => &self.key_range, + }; + #[cfg(feature = "std")] + let range = match slot { + SlotIndex::Data(_, _, _) | SlotIndex::DataRange(_, _, _) => &self.data_write_offset, }; if value.len() != slot.len() * SLOT_ELEMENT_LEN_BYTES { @@ -322,6 +296,7 @@ impl SlotManager { if self.user_id.is_accessible(&acl, &AccessType::Read) { // read-verify only if we have read access let readback = self.read(slot)?; + crate::println!("rbk: {:x?}", &readback[..8]); if readback != value { Err(AccessError::WriteError) } else { Ok(()) } } else { Ok(()) @@ -338,12 +313,6 @@ impl SlotManager { self.data_acl_range.as_slice()[offset..offset + size_of::()].try_into().unwrap() }))) } - SlotIndex::Key(_, _, _) => { - let offset = slot.try_into_acl_offset()?; - AccessSettings::Key(KeySlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe { - self.key_acl_range.as_slice()[offset..offset + size_of::()].try_into().unwrap() - }))) - } SlotIndex::DataRange(_, _, _) => { let mut range = slot.try_into_acl_iter()?; let offset = range.next().unwrap(); @@ -360,22 +329,6 @@ impl SlotManager { } AccessSettings::Data(prototype) } - SlotIndex::KeyRange(_, _, _) => { - let mut range = slot.try_into_acl_iter()?; - let offset = range.next().unwrap(); - let prototype = KeySlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe { - self.key_acl_range.as_slice()[offset..offset + size_of::()].try_into().unwrap() - })); - for offset in range { - let successor = KeySlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe { - self.key_acl_range.as_slice()[offset..offset + size_of::()].try_into().unwrap() - })); - if prototype != successor { - return Err(AccessError::KeyAclInconsistency(prototype)); - } - } - AccessSettings::Key(prototype) - } }) } @@ -389,22 +342,22 @@ impl SlotManager { })) } - /// Safety: the caller must resolve the index into either the data or the key array correctly. - /// There is access or type checking done. This is a "raw read" primitive mostly used for debugging. - pub unsafe fn get_key_acl(&self, absolute_offset: usize) -> KeySlotAccess { - KeySlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe { - self.key_acl_range.as_slice()[absolute_offset..absolute_offset + size_of::()] - .try_into() - .unwrap() - })) - } - pub fn set_acl( &self, writer: &mut Reram, slot: &SlotIndex, setting: &AccessSettings, ) -> Result<(), AccessError> { + #[cfg(not(feature = "std"))] + let ptr = match slot { + SlotIndex::Data(_, _, _) | SlotIndex::DataRange(_, _, _) => self.data_acl_range.as_ptr() as usize, + }; + #[cfg(feature = "std")] + let ptr = match slot { + SlotIndex::Data(_, _, _) | SlotIndex::DataRange(_, _, _) => { + self.data_acl_write_offset.as_ptr() as usize + } + }; // safety: the unsafe blocks here are concerned that the data types of the resulting // slice are all representable. In this case, all bits are valid in the final representation. match slot { @@ -412,45 +365,27 @@ impl SlotManager { let offset = slot.try_into_acl_offset()?; writer .protected_write_slice( - self.data_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset, - &setting.raw_u32().to_le_bytes(), - ) - .map(|_| ()) - .map_err(|_| AccessError::WriteError) - } - SlotIndex::Key(_, _, _) => { - let offset = slot.try_into_acl_offset()?; - writer - .protected_write_slice( - self.key_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset, + ptr - utralib::HW_RERAM_MEM + offset, &setting.raw_u32().to_le_bytes(), ) .map(|_| ()) .map_err(|_| AccessError::WriteError) } SlotIndex::DataRange(_, _, _) => { + let mut success = true; for offset in slot.try_into_acl_iter()? { - writer - .protected_write_slice( - self.data_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset, - &setting.raw_u32().to_le_bytes(), - ) - .map(|_| ()) - .map_err(|_| AccessError::WriteError)? + match writer.protected_write_slice( + ptr - utralib::HW_RERAM_MEM + offset, + &setting.raw_u32().to_le_bytes(), + ) { + Ok(_) => {} + Err(e) => { + success = false; + crate::println!("Can't write to ACL offset {:x}: {:?}", offset, e); + } + } } - Ok(()) - } - SlotIndex::KeyRange(_, _, _) => { - for offset in slot.try_into_acl_iter()? { - writer - .protected_write_slice( - self.key_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset, - &setting.raw_u32().to_le_bytes(), - ) - .map(|_| ()) - .map_err(|_| AccessError::WriteError)? - } - Ok(()) + if success { Ok(()) } else { Err(AccessError::WriteError) } } } } diff --git a/libs/bao1x-hal/src/rram.rs b/libs/bao1x-hal/src/rram.rs index 58a56ea1b..11760a60c 100644 --- a/libs/bao1x-hal/src/rram.rs +++ b/libs/bao1x-hal/src/rram.rs @@ -1,3 +1,6 @@ +#[cfg(feature = "std")] +use std::pin::Pin; + use utralib::{CSR, utra}; #[cfg(not(feature = "std"))] @@ -57,6 +60,9 @@ const RRC_CR_POWERDOWN: u32 = 1; const RRC_CR_WRITE_DATA: u32 = 0; const RRC_CR_WRITE_CMD: u32 = 2; +// number of attempts allowed before giving up on writes +const ATTEMPTS: usize = 2; + #[cfg(feature = "std")] fn rram_handler(_irq_no: usize, arg: *mut usize) { let rram = unsafe { &mut *(arg as *mut Reram) }; @@ -111,7 +117,7 @@ impl<'a> Reram { /// This returns an object that has a handle to manage the RRAM, but no memory /// ranges mapped that are valid for writing. Memory ranges need to be added /// with `add_range()` before any writes can occur. - pub fn new() -> Self { + pub fn new() -> Pin> { let rram_page = xous::syscall::map_memory( xous::MemoryAddress::new(utra::rrc::HW_RRC_BASE), None, @@ -135,18 +141,18 @@ impl<'a> Reram { let mut irq_csr = CSR::new(irq_page.as_mut_ptr() as *mut u32); // pin the structure on the heap so that it doesn't move around on us. - let mut rram = Reram { + let mut rram = Box::pin(Reram { csr, irq_csr, offset: 0, buf: [0u32; ALIGNMENT / size_of::()], range_map: RangeMap::new(), - }; + }); xous::claim_interrupt( utra::irqarray11::IRQARRAY11_IRQ, rram_handler, - &mut rram as *mut Reram as *mut usize, + Pin::as_mut(&mut rram).get_mut() as *mut Reram as *mut usize, ) .expect("couldn't claim RRAM handler interrupt"); irq_csr.wo(utra::irqarray11::EV_PENDING, 0xFFFF_FFFF); @@ -338,6 +344,33 @@ impl<'a> Reram { Ok(data.len()) } + fn write_slice_retry(&mut self, offset: usize, data: &[u8]) -> Result { + for i in 0..ATTEMPTS { + match self.write_slice_inner(offset, data) { + Ok(len) => { + #[cfg(not(feature = "std"))] + let check_slice = unsafe { + core::slice::from_raw_parts((offset + utralib::HW_RERAM_MEM) as *const u8, data.len()) + }; + #[cfg(feature = "std")] + let check_slice = self.array(offset)?; + + if check_slice[..data.len().min(check_slice.len())] + == data[..data.len().min(check_slice.len())] + { + return Ok(len); + } else { + crate::println!("Write failed to verify retry {}/{}", i + 1, ATTEMPTS); + } + } + Err(e) => { + crate::println!("Write with error {:?}, retrying...", e); + } + } + } + Err(xous::Error::InternalError) + } + /// Bounds-check regular writes to make sure they are in the "standard" memory array region /// Boot0 region is also disallowed for writing because it should be hardware write-protected. /// For testing purposes, that check may be commented out just to make sure the write protection @@ -351,7 +384,7 @@ impl<'a> Reram { { return Err(xous::Error::AccessDenied); } - self.write_slice_inner(offset, data) + self.write_slice_retry(offset, data) } /// This has a separate API not to enforce security but to avoid fat-fingering data @@ -360,9 +393,11 @@ impl<'a> Reram { /// processes, but they only come into effect after the OS is booted. pub fn protected_write_slice(&mut self, offset: usize, data: &[u8]) -> Result { if offset < bao1x_api::RRAM_STORAGE_LEN || offset >= utralib::HW_RERAM_MEM_LEN { + // crate::println!("offset {:x} access denied", offset); return Err(xous::Error::AccessDenied); } - self.write_slice_inner(offset, data) + // crate::println!("Writing to {:x}: {:x?}", offset, &data[..16.min(data.len())]); + self.write_slice_retry(offset, data) } } diff --git a/libs/bao1x-hal/src/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index 6716c0143..73cef9444 100644 --- a/libs/bao1x-hal/src/sigcheck.rs +++ b/libs/bao1x-hal/src/sigcheck.rs @@ -4,7 +4,7 @@ use alloc::vec::Vec; use bao1x_api::signatures::*; #[cfg(not(feature = "std"))] -use bao1x_api::{DEVELOPER_MODE, KeySlotAccess, RwPerms, SLOT_ELEMENT_LEN_BYTES, SlotType}; +use bao1x_api::{DEVELOPER_MODE, DataSlotAccess, RwPerms, SLOT_ELEMENT_LEN_BYTES, SlotType}; use digest::Digest; use sha2_bao1x::{Sha256, Sha512}; use xous::arch::PAGE_SIZE; @@ -221,12 +221,11 @@ pub fn erase_secrets() { let mut rram = crate::rram::Reram::new(); let mut zero_key_count = 0; - // statistically speaking, I suppose, maybe we could have "a" set of keys that are 0 out of a randomly - // generated set. But if we see more than the threshold below of zero keys, conclude that we don't - // have access permissions, and panic instead of allowing a boot. - const ZERO_ERR_THRESH: usize = 2; + // This is set to a higher level because we need to work around an earlier issue + // with overly-broad ACL settings on alpha0 boards + const ZERO_ERR_THRESH: usize = 64; for slot in crate::board::KEY_SLOTS.iter() { - if slot.get_type() == SlotType::Key { + if slot.get_type() == SlotType::Data { let (_pa, rw_perms) = slot.get_access_spec(); for data_index in slot.try_into_data_iter().unwrap() { match rw_perms { @@ -238,11 +237,11 @@ pub fn erase_secrets() { .set_acl( &mut rram, slot, - &AccessSettings::Key(KeySlotAccess::new_with_raw_value(0)), + &AccessSettings::Data(DataSlotAccess::new_with_raw_value(0)), ) .expect("couldn't reset ACL"); } - let bytes = unsafe { slot_mgr.read_key_slot(data_index) }; + let bytes = unsafe { slot_mgr.read_data_slot(data_index) }; if bytes.iter().all(|&b| b == 0) { zero_key_count += 1; } @@ -253,12 +252,17 @@ pub fn erase_secrets() { alloc::vec::Vec::with_capacity(slot.len() * SLOT_ELEMENT_LEN_BYTES); eraser.resize(slot.len() * SLOT_ELEMENT_LEN_BYTES, ERASE_VALUE); - slot_mgr.write(&mut rram, slot, &eraser).expect("couldn't erase key"); + slot_mgr.write(&mut rram, slot, &eraser).ok(); } - let check = unsafe { slot_mgr.read_key_slot(data_index) }; + let check = unsafe { slot_mgr.read_data_slot(data_index) }; if !check.iter().all(|&b| b == ERASE_VALUE) { crate::println!("Failed to erase key at {}: {:x?}", data_index, check); - panic!("Key erasure did not succeed, refusing to boot!"); + /* // commented out - can lead to boot loops + // reboot on failure to erase + let mut rcurst = + utralib::CSR::new(utralib::utra::sysctrl::HW_SYSCTRL_BASE as *mut u32); + rcurst.wo(utralib::utra::sysctrl::SFR_RCURST0, 0x55AA); + */ } else { crate::println!("Key range at {} confirmed erased", slot.get_base()); } @@ -266,9 +270,7 @@ pub fn erase_secrets() { _ => {} } if zero_key_count > ZERO_ERR_THRESH { - panic!( - "Saw too many zero-keys. Insufficient privilege to erase keys, panicing instead of allowing a boot!" - ); + crate::println!("Saw too many zero-keys. Insufficient privilege to erase keys!"); } } } diff --git a/libs/bao1x-hal/src/udma/spim.rs b/libs/bao1x-hal/src/udma/spim.rs index bd6e37533..346fb0537 100644 --- a/libs/bao1x-hal/src/udma/spim.rs +++ b/libs/bao1x-hal/src/udma/spim.rs @@ -1325,7 +1325,10 @@ impl Spim { let qe_set = match self.command_set { Some(CommandSet::Macronix) => 0b0100_0000 & sr != 0, Some(CommandSet::Xtx) => 0b10_0000_0000 & sr != 0, - None => panic!("Attempting to set QE on unknown flash type"), + None => { + crate::println!("Can't set QE on unknown flash type"); + return; + } }; if qe_set { // nothing to do, it's already set diff --git a/libs/bao1x-hal/src/usb/driver.rs b/libs/bao1x-hal/src/usb/driver.rs index d1d374334..e16b315ea 100644 --- a/libs/bao1x-hal/src/usb/driver.rs +++ b/libs/bao1x-hal/src/usb/driver.rs @@ -1630,6 +1630,8 @@ impl CorigineUsb { } } + pub fn get_speed(&self) -> PortSpeed { PortSpeed::from_portsc(self.csr.r(PORTSC)) } + pub fn update_ep0_maxpacketsize(&mut self, size: usize) { let cmd_param = self.csr.ms(CMDPARA0_CMD1_UPDATE_EP0_MPS, size as u32); self.issue_command(CmdType::UpdateEp0, cmd_param, 0).expect("couldn't issue command"); diff --git a/loader/src/main.rs b/loader/src/main.rs index 643c4fbb0..8931ee4af 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -281,7 +281,7 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32) if tag == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT { - crate::println!("Developer key detected, ensuring secret are erased"); + crate::println!("Developer key detected, ensuring secrets are erased"); bao1x_hal::sigcheck::erase_secrets(); } } @@ -315,7 +315,7 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32) == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT { - crate::println!("Developer key detected, ensuring secret are erased"); + crate::println!("Developer key detected, ensuring secrets are erased"); bao1x_hal::sigcheck::erase_secrets(); } true diff --git a/loader/src/platform/bao1x/swap.rs b/loader/src/platform/bao1x/swap.rs index f3f4e53b8..6c5d261c3 100644 --- a/loader/src/platform/bao1x/swap.rs +++ b/loader/src/platform/bao1x/swap.rs @@ -256,7 +256,7 @@ impl SwapHal { [bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT { - crate::println!("Developer key detected, ensuring secret are erased"); + crate::println!("Developer key detected, ensuring secrets are erased"); bao1x_hal::sigcheck::erase_secrets(); } } diff --git a/services/keystore/Cargo.toml b/services/keystore/Cargo.toml index 4d9db3fdb..73480aa2e 100644 --- a/services/keystore/Cargo.toml +++ b/services/keystore/Cargo.toml @@ -75,6 +75,9 @@ hkdf = "0.12.4" [features] bao1x = ["utralib/bao1x", "aes/bao1x"] + +debug-hal = ["bao1x-hal/debug-print-duart"] + board-baosec = [ "utralib/bao1x", "keystore-api/gen2", diff --git a/services/keystore/src/main.rs b/services/keystore/src/main.rs index 21ff99651..8ae6badce 100644 --- a/services/keystore/src/main.rs +++ b/services/keystore/src/main.rs @@ -3,6 +3,8 @@ use keystore_api::*; mod platform; fn main() -> ! { + #[cfg(feature = "debug-hal")] + bao1x_hal::claim_duart(); log_server::init_wait().unwrap(); log::set_max_level(log::LevelFilter::Info); log::info!("my PID is {}", xous::process::id()); @@ -57,8 +59,11 @@ fn attack_keystore() { let slot_mgr = bao1x_hal::acram::SlotManager::new(); // let slot = bao1x_api::baosec::ROOT_SEED; - let slot = - bao1x_api::offsets::SlotIndex::Key(0, bao1x_api::PartitionAccess::Fw0, bao1x_api::RwPerms::ReadOnly); + let slot = bao1x_api::offsets::SlotIndex::Data( + 256, + bao1x_api::PartitionAccess::Fw0, + bao1x_api::RwPerms::ReadOnly, + ); let data_index = slot.try_into_data_offset().unwrap(); let acl_index = slot.try_into_acl_offset().unwrap(); let user_states = [ @@ -74,8 +79,8 @@ fn attack_keystore() { cu.rmwf(utra::coreuser::USERVALUE_USER2, state.as_dense()); log::info!(" COREUSER STATUS {:x}", cu.r(utra::coreuser::STATUS)); unsafe { - let bytes = slot_mgr.read_key_slot(data_index); - let acl = slot_mgr.get_key_acl(acl_index); + let bytes = slot_mgr.read_data_slot(data_index); + let acl = slot_mgr.get_data_acl(acl_index); log::info!( " Key {} ({:x?}): {:x?}", data_index / bao1x_api::offsets::SLOT_ELEMENT_LEN_BYTES, diff --git a/services/keystore/src/platform/baosec/server.rs b/services/keystore/src/platform/baosec/server.rs index 54affb42a..05ad74622 100644 --- a/services/keystore/src/platform/baosec/server.rs +++ b/services/keystore/src/platform/baosec/server.rs @@ -8,7 +8,11 @@ use crate::platform::KeyStore; pub fn keystore(sid: SID) -> ! { let hal = bao1x_hal_service::Hal::new(); let mut rram = Reram::new(); - let mut store = KeyStore::init_from_hw(&mut rram); + let mut store = KeyStore::init_mappings(&mut rram); + // does nothing if the keys are already initialized + store.ensure_system_init(&mut rram); + // derive the master key + store.derive_master_key(); let mut msg_opt = None; diff --git a/services/keystore/src/platform/baosec/store.rs b/services/keystore/src/platform/baosec/store.rs index 7dc5b72f2..ded278604 100644 --- a/services/keystore/src/platform/baosec/store.rs +++ b/services/keystore/src/platform/baosec/store.rs @@ -1,6 +1,8 @@ use aes::Aes256; use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray}; -use bao1x_api::{BOOT0_PUBKEY_FAIL, CP_ID, DEVELOPER_MODE, OEM_MODE, UUID}; +use bao1x_api::{ + BOOT0_PUBKEY_FAIL, BoardTypeCoding, CP_ID, DEVELOPER_MODE, OEM_MODE, SLOT_ELEMENT_LEN_BYTES, UUID, +}; use bao1x_hal::{ acram::{OneWayCounter, SlotManager}, board::{CHAFF_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, ROOT_SEED}, @@ -18,16 +20,78 @@ const KEY_LEN: usize = bao1x_api::SLOT_ELEMENT_LEN_BYTES; pub struct KeyStore { slot_mgr: SlotManager, owc: OneWayCounter, - master_key: [u8; KEY_LEN], + master_key: Option<[u8; KEY_LEN]>, } impl KeyStore { - pub fn init_from_hw(rram: &mut Reram) -> Self { + pub fn init_mappings(rram: &mut Reram) -> Self { let slot_mgr = SlotManager::new(); slot_mgr.register_mapping(rram); let owc = OneWayCounter::new(); owc.register_mapping(rram); + Self { slot_mgr, owc, master_key: None } + } + + pub fn ensure_system_init(&mut self, rram: &mut Reram) { + // debug coreuser status + /* + let coreuser_range = xous::map_memory( + xous::MemoryAddress::new(utralib::utra::coreuser::HW_COREUSER_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("Couldn't map coreuser range"); + let coreuser = utralib::CSR::new(coreuser_range.as_mut_ptr() as *mut u32); + log::info!("coreuser status: {:x}", coreuser.r(utralib::utra::coreuser::STATUS)); + */ + + // one routine works for both dabao and baosec + let board_type = self.owc.get_decoded::().unwrap(); + if (board_type == bao1x_api::BoardTypeCoding::Baosec + && self.owc.get(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() == 0) + || (board_type == bao1x_api::BoardTypeCoding::Dabao + && self.owc.get(bao1x_api::INVOKE_DABAO_KEY_SETUP).unwrap() != 0 + && self.owc.get(bao1x_api::DABAO_KEY_SETUP_DONE).unwrap() == 0) + { + log::info!("System setup not yet done. Initializing secret identifiers..."); + let xns = xous_names::XousNames::new().unwrap(); + let mut trng = bao1x_hal_service::trng::Trng::new(&xns).unwrap(); + // generate all the keys + let key_set = if board_type == bao1x_api::BoardTypeCoding::Baosec { + &bao1x_api::baosec::KEY_SLOTS[..] + } else { + &bao1x_api::dabao::KEY_SLOTS[..] + }; + let mut success = true; + for key_range in key_set.iter() { + let mut storage = Vec::::with_capacity(key_range.len() * SLOT_ELEMENT_LEN_BYTES); + storage.resize(key_range.len() * SLOT_ELEMENT_LEN_BYTES, 0); + trng.fill_bytes(&mut storage); + match self.slot_mgr.write(rram, key_range, &storage) { + Ok(_) => {} + Err(e) => { + success = false; + log::error!("Couldn't initialize slot {:?}: {:?}", key_range, e); + } + } + } + // once all values are written, advance the IN_SYSTEM_BOOT_SETUP_DONE state + // safety: the offset is correct because we're pulling it from our pre-defined constants and + // those are manually checked. + if success { + if board_type == bao1x_api::BoardTypeCoding::Baosec { + unsafe { self.owc.inc(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() }; + } else if board_type == bao1x_api::BoardTypeCoding::Dabao { + unsafe { self.owc.inc(bao1x_api::DABAO_KEY_SETUP_DONE).unwrap() }; + } + } + log::info!("Secret ID init done."); + } + } + + pub fn derive_master_key(&mut self) { let mut ikm = Vec::::new(); let mut salt = Vec::::new(); let mut info = Vec::::new(); @@ -37,7 +101,7 @@ impl KeyStore { // should stop/panic at that line. Kicking the error up the stack isn't useful. // read key material - ikm.extend_from_slice(slot_mgr.read(&ROOT_SEED).unwrap()); + ikm.extend_from_slice(self.slot_mgr.read(&ROOT_SEED).unwrap()); // build nuisance key offsets - this is direct readout hardening let nk0 = NUISANCE_KEYS_0.try_into_data_iter().unwrap(); @@ -71,7 +135,7 @@ impl KeyStore { // safety: the offset is generated by the try_into_data_iter method, which generates // safe offsets for (cx, &src) in - chaff_xor.iter_mut().zip(unsafe { slot_mgr.read_key_slot(chaff_offset) }) + chaff_xor.iter_mut().zip(unsafe { self.slot_mgr.read_data_slot(chaff_offset) }) { *cx ^= src; } @@ -82,7 +146,7 @@ impl KeyStore { // safety: the offset is generated by the try_into_data_iter method, which generates // safe offsets for (cx, &src) in - ct_xor.iter_mut().zip(unsafe { slot_mgr.read_key_slot(chaff_offset) }) + ct_xor.iter_mut().zip(unsafe { self.slot_mgr.read_data_slot(chaff_offset) }) { *cx ^= src; } @@ -95,13 +159,15 @@ impl KeyStore { // get the nuisance key, in-order // safety: the offset is generated by the try_into_data_iter method, which generates safe offsets - ikm.extend_from_slice(unsafe { slot_mgr.read_key_slot(nk_offset) }); + ikm.extend_from_slice(unsafe { self.slot_mgr.read_data_slot(nk_offset) }); } // Drain the remainder. There's always going to be four keys left over because the NUISANCE array // isn't evenly sized due to the -A1 stepping bug. I think this isn't damning because the actual // ordering of the chaff is unknown at this point, and it's always the same amount. for remaining_chaff in chaff.drain(..) { - for (cx, &src) in chaff_xor.iter_mut().zip(unsafe { slot_mgr.read_key_slot(remaining_chaff) }) { + for (cx, &src) in + chaff_xor.iter_mut().zip(unsafe { self.slot_mgr.read_data_slot(remaining_chaff) }) + { *cx ^= src; } } @@ -113,24 +179,24 @@ impl KeyStore { // add salt // UUID is a random unique number made by the TRNG - salt.extend_from_slice(slot_mgr.read(&UUID).unwrap()); + salt.extend_from_slice(self.slot_mgr.read(&UUID).unwrap()); // CP_ID is a sequentially incrementing number that is included just in case something went horribly // wrong with the TRNG during ID generation - this gives us at least *some* guaranteed uniqueness, // but not randomness. - salt.extend_from_slice(slot_mgr.read(&CP_ID).unwrap()); + salt.extend_from_slice(self.slot_mgr.read(&CP_ID).unwrap()); // add info - if owc.get(DEVELOPER_MODE).unwrap() != 0 { + if self.owc.get(DEVELOPER_MODE).unwrap() != 0 { info.extend_from_slice(b"dev"); } else { info.extend_from_slice(b"sec"); } - if owc.get(OEM_MODE).unwrap() != 0 { + if self.owc.get(OEM_MODE).unwrap() != 0 { info.extend_from_slice(b"oem"); } - if owc.get(BOOT0_PUBKEY_FAIL).unwrap() != 0 { + if self.owc.get(BOOT0_PUBKEY_FAIL).unwrap() != 0 { info.extend_from_slice(b"tampered"); } @@ -148,18 +214,17 @@ impl KeyStore { log::warn!("Chaff result is all-0. Confirming that we're in developer mode"); // panic if we're not in developer mode assert!( - owc.get(DEVELOPER_MODE).unwrap() != 0, + self.owc.get(DEVELOPER_MODE).unwrap() != 0, "Either we have the most improbable chaff, or (more likely) the chaff is set to all 0's" ); } - - Self { slot_mgr, owc, master_key } + self.master_key = Some(master_key); } pub fn aes_kwp(&self, kwp: &mut KeyWrapper) -> Result<(), xous::Error> { use aes_kw::Kek; use aes_kw::KekAes256; - let keywrapper: KekAes256 = Kek::from(self.master_key); + let keywrapper: KekAes256 = Kek::from(self.master_key.ok_or(xous::Error::UseBeforeInit)?); match kwp.op { KeyWrapOp::Wrap => { match keywrapper.wrap_with_padding_vec(&kwp.data[..kwp.len as usize]) { @@ -226,7 +291,7 @@ impl KeyStore { AesOpType::Decrypt => AesOpType::Decrypt, AesOpType::Encrypt => AesOpType::Encrypt, }; - let hk = Hkdf::::new(None, &self.master_key); + let hk = Hkdf::::new(None, &self.master_key.ok_or(xous::Error::UseBeforeInit)?); let mut okm = [0u8; 32]; hk.expand(&aes_op.domain.as_bytes(), &mut okm).expect("32 is a valid length for Sha256 to output"); let cipher = Aes256::new(GenericArray::from_slice(&okm)); diff --git a/services/pddb/src/backend/hw.rs b/services/pddb/src/backend/hw.rs index 54791cb33..9eddd154b 100644 --- a/services/pddb/src/backend/hw.rs +++ b/services/pddb/src/backend/hw.rs @@ -2510,7 +2510,7 @@ impl PddbOs { } } self.entropy.borrow_mut().get_slice(&mut temp); - if (offset / PAGE_SIZE) % 256 == 0 { + if (offset / PAGE_SIZE) % 32 == 0 { // ~one update per megabyte log::info!("Cryptographic 'erase': {}/{}", offset, PDDB_A_LEN); if let Some(modals) = progress { diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index 07eecfa19..9d532801b 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -841,7 +841,11 @@ fn wrapped_main() -> ! { unreachable!(); } PasswordState::Incorrect(_failcount) => { - unreachable!(); + log::warn!("PDDB formatted, but keys rotated. Formatting PDDB!"); + pddb_os.pddb_format(false, None).expect("couldn't format PDDB"); + if !try_mount(&mut pddb_os, &mut basis_cache, &mut basis_monitor_notifications) { + panic!("Couldn't format & mount PDDB"); + } } } // the above operation should either succeed or panic, so we are always "success" here diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 08b06f0bf..ee69dab30 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -678,6 +678,7 @@ fn main() -> Result<(), Box> { (bao1x_api::LOADER_START + sigblock_size + STATICS_LEN) as u32, )?; builder.add_loader_feature("alt-boot1"); + builder.add_loader_feature("force-dabao"); builder .set_baremetal(true) .target_baremetal_bao1x("bao1x-alt-boot1")