From c3c86e857bcbb79822a7e2cacb9b440e3d224cec Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 12 Nov 2025 22:08:01 +0800 Subject: [PATCH 01/24] improve pddb init --- services/pddb/src/backend/hw.rs | 2 +- services/pddb/src/main.rs | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) 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 From 10bd1502d0f75ab1b73fb197ca26b3d4b5b2a3a6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 12 Nov 2025 22:08:12 +0800 Subject: [PATCH 02/24] fix ACL to match actual usage of data slots --- libs/bao1x-api/src/offsets/common.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 From 47e8f96ccb86a78c09014cc5b51d49192163ca83 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 12 Nov 2025 22:08:28 +0800 Subject: [PATCH 03/24] update release description --- bao1x-boot/boot1/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bao1x-boot/boot1/src/main.rs b/bao1x-boot/boot1/src/main.rs index 49af9bbee..3fc06b3e0 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)] From d8c2ffe2b19c7f636fb63712d52aa613e8b27bc9 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 12 Nov 2025 23:02:52 +0800 Subject: [PATCH 04/24] fix/update baosign.ps1 added a boot signer that signs the various boot configs --- baosign.ps1 | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/baosign.ps1 b/baosign.ps1 index ec0e19d3f..3a06a6250 100644 --- a/baosign.ps1 +++ b/baosign.ps1 @@ -9,7 +9,7 @@ param( [Parameter(Mandatory = $true)] - [ValidateSet("baremetal", "dabao", "baosec")] + [ValidateSet("baremetal", "dabao", "baosec", "bootloader")] [string]$Config, [Parameter(Mandatory = $false)] @@ -26,19 +26,24 @@ $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 = "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 = "baremetal.img"; FunctionCode = "baremetal" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" } ) - "dabao" = @( + "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" }, @{ 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" = @( + "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" }, @{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } From bd37ffde5cb28e130b89881df9a3a33a1cfd9185 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 10:57:04 +0800 Subject: [PATCH 05/24] Move in-system keying to system code Since in-system keying has to happen in the factory, it doesn't add anything to burn it into the bootloader. Furthermore, the access controls are already set up so that the keys can only be accessed by the OS code. --- bao1x-boot/boot1/src/platform/bao1x/slots.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/bao1x-boot/boot1/src/platform/bao1x/slots.rs b/bao1x-boot/boot1/src/platform/bao1x/slots.rs index 8297713c2..93ac6e026 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(); @@ -168,7 +176,10 @@ fn check_and_fix_acls(rram: &mut Reram, slot_mgr: &mut SlotManager, slot_list: & 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 + // crate::println!("sa.pa {:x?} pa {:x?}", sa.get_partition_access(), pa); + // crate::println!("sa.rw {:x?} rw {:x?}", sa.get_rw_permissions(), rw); + // crate::println!("sa.akeyid: {:x}", sa.akey_id()); + sa.get_partition_access() == pa && sa.get_rw_permissions() == rw && sa.akey_id() == 0xFF } }; if !is_correct || !is_consistent { From f88c801e012967b9ad936730d6b22ed4b35c9be5 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 11:06:16 +0800 Subject: [PATCH 06/24] update key ACL to r/w this allows the OS to initialize the keys note that including write access only gives it to the fw0 user, which is the OS's secure user. thus any write primitive created by this expansion of access should transitively also be a read primitive (which is actually what the adversary desires). In exchange the OS is allowed to initialize the keys, which I think is the right place to do it given that it's too hard at this point to nail down the exact key layout, etc. Note that it is impossible for the OS to change ACLs - that is a feature that can only be updated by the boot user - which is why the boot user can change the ACL to gain access to erase keys, but the OS user can't modify its own ACL. --- libs/bao1x-api/src/offsets/baosec.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/libs/bao1x-api/src/offsets/baosec.rs b/libs/bao1x-api/src/offsets/baosec.rs index aa238e022..e0a00327e 100644 --- a/libs/bao1x-api/src/offsets/baosec.rs +++ b/libs/bao1x-api/src/offsets/baosec.rs @@ -44,13 +44,13 @@ 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::Key(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::Key(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 @@ -58,7 +58,7 @@ pub const RMA_KEY: SlotIndex = SlotIndex::Key(257, PartitionAccess::Fw0, RwPerms pub const CP_COOKIE: SlotIndex = SlotIndex::Key(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::Key(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::KeyRange(8..128, PartitionAccess::Fw0, RwPerms::ReadWrite); pub const NUISANCE_KEYS_1: SlotIndex = - SlotIndex::KeyRange(1920..2048, PartitionAccess::Fw0, RwPerms::ReadOnly); + SlotIndex::KeyRange(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 From 6af2001810a80fe13f86485fb07388b2393c2eff Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 18:20:12 +0800 Subject: [PATCH 07/24] fix write protect bits Each write protect bit in the IFR array covers *8* key slots. This scopes the write protect down to just the 8 slots we care about. --- bao1x-boot/blobs/ifr_0x340.bin | Bin 32 -> 32 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/bao1x-boot/blobs/ifr_0x340.bin b/bao1x-boot/blobs/ifr_0x340.bin index 0dce25f4d7d8bfb2643ebb59fea43e0fecc7335b..9870828e3938f3276a5cd4a38d05b7281f0cd502 100644 GIT binary patch literal 32 KcmZQ%zz+ZbKmY;& literal 32 Kcmd;Qzz+Zd000mG From a7477ec53ba2fe433406f0c63d1cbce8d2b47e3d Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 18:21:52 +0800 Subject: [PATCH 08/24] Remove key slot implementation; migrate keys to data slots The -A1 stepping is going to tie the IFR access control bits for data and key slots together. This is due to an RTL bug where the key slot maps were typo'd and they ended up mapping to the same IFR ACL. We "could" continue to use key slots with a rule that key and data slots would have to coordinate with each other and not use the same slot number. However, because of this linkage, and because there are other bugs suspected in the keyslot implementation, an executive decision was made to disregard the key slot feature in the chip. The main downsides of this are: - fewer slots (2048 vs 4096) - no key access linkage to HMAC auth on SCE I *think* that's it. Fewer slots - 2048 slots is still a lot of slots, about half are used now, I think this is plenty. Key access linkage to HMAC auth on SCE - I have reasons to suspect this feature is broken anyways for subtle reasons related to malleability of the HMAC round constants. Even without that brokenness, it's hard to use HMAC auth to manage the system because it requires per-device unique keys: so, we're using a PKI scheme and no symmetric secrets to handle access controls. Removing the key slots also greatly simplifies the code base analytically. This culling removes the key slot abstraction the "simple" way, but without the weirdness of the keyslots (in particular the key ID chaining which makes them different from data slots) I could remove even more abstractions and simplify the code. One upside is now all elements can enjoy the write mode behavior which can force the slot to be only 0->1 writeable, which could be useful for other things down the road. This was tested to not interfere with Dabao-Alpha 0 bootloaders. --- bao1x-boot/boot1/src/platform/bao1x/slots.rs | 32 +--- libs/bao1x-api/src/offsets.rs | 146 ----------------- libs/bao1x-api/src/offsets/baosec.rs | 16 +- libs/bao1x-hal/src/acram.rs | 155 ++++++------------- libs/bao1x-hal/src/sigcheck.rs | 17 +- 5 files changed, 69 insertions(+), 297 deletions(-) diff --git a/bao1x-boot/boot1/src/platform/bao1x/slots.rs b/bao1x-boot/boot1/src/platform/bao1x/slots.rs index 93ac6e026..216888f3e 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/slots.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/slots.rs @@ -162,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) @@ -175,12 +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) => { - // crate::println!("sa.pa {:x?} pa {:x?}", sa.get_partition_access(), pa); - // crate::println!("sa.rw {:x?} rw {:x?}", sa.get_rw_permissions(), rw); - // crate::println!("sa.akeyid: {:x}", sa.akey_id()); - sa.get_partition_access() == pa && sa.get_rw_permissions() == rw && sa.akey_id() == 0xFF - } }; if !is_correct || !is_consistent { crate::println!( @@ -195,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(); } } } @@ -236,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/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 e0a00327e..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::ReadWrite); +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::ReadWrite); +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::ReadWrite); +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::ReadWrite); +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::ReadWrite); + 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-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/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index 6716c0143..cc9eae8dc 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; @@ -226,7 +226,7 @@ pub fn erase_secrets() { // have access permissions, and panic instead of allowing a boot. const ZERO_ERR_THRESH: usize = 2; 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 +238,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 +253,15 @@ 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!"); + // 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()); } From faecc1cf27315adaec5fa538eae16b3a64d37d6c Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 18:29:06 +0800 Subject: [PATCH 09/24] pin RRAM data onto heap this prevents optimization that move it around and can cause troubles for `std` mode operations --- libs/bao1x-hal/src/rram.rs | 47 +++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 6 deletions(-) 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) } } From 9f8c2deedaf1e2f5298204978c4fd1ac2e7adc3a Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 18:31:15 +0800 Subject: [PATCH 10/24] add more granular signing targets helps with debug --- baosign.ps1 | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/baosign.ps1 b/baosign.ps1 index 3a06a6250..b6af68362 100644 --- a/baosign.ps1 +++ b/baosign.ps1 @@ -9,7 +9,7 @@ param( [Parameter(Mandatory = $true)] - [ValidateSet("baremetal", "dabao", "baosec", "bootloader")] + [ValidateSet("baremetal", "dabao", "baosec", "bootloader", "kernel", "loader", "swap", "apps", "boot1")] [string]$Config, [Parameter(Mandatory = $false)] @@ -50,6 +50,21 @@ $configurations = @{ @{ 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" } + ) } # Color output functions for better visibility From 9213755a6ba60a72b16d7d1794e4513761925e69 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 18:32:04 +0800 Subject: [PATCH 11/24] move keystore init to userspace This moves the key store initialization to the key manager process itself. It has been tested to work with signed images, and to also protect the system in case of another process trying to access the key data as well as in the case of developer keys being used. --- services/keystore/Cargo.toml | 3 + services/keystore/src/main.rs | 13 ++- .../keystore/src/platform/baosec/server.rs | 6 +- .../keystore/src/platform/baosec/store.rs | 98 +++++++++++++++---- 4 files changed, 97 insertions(+), 23 deletions(-) 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..f8c3aa58c 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}, @@ -10,6 +12,7 @@ use hkdf::Hkdf; use keystore_api::KeyWrapper; use rand::prelude::*; use sha2::Sha256; +use utralib::utra::coresub_sramtrm; use crate::*; @@ -18,16 +21,74 @@ 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) { + 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 mut 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 +98,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 +132,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 +143,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 +156,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 +176,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 +211,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 +288,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)); From 52c5400fca81a825eca25de0607eefd6635e612e Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 18:36:03 +0800 Subject: [PATCH 12/24] cleanup debug --- services/keystore/src/platform/baosec/store.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/services/keystore/src/platform/baosec/store.rs b/services/keystore/src/platform/baosec/store.rs index f8c3aa58c..ded278604 100644 --- a/services/keystore/src/platform/baosec/store.rs +++ b/services/keystore/src/platform/baosec/store.rs @@ -12,7 +12,6 @@ use hkdf::Hkdf; use keystore_api::KeyWrapper; use rand::prelude::*; use sha2::Sha256; -use utralib::utra::coresub_sramtrm; use crate::*; @@ -35,6 +34,8 @@ impl KeyStore { } 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, @@ -42,8 +43,10 @@ impl KeyStore { xous::MemoryFlags::R | xous::MemoryFlags::W, ) .expect("Couldn't map coreuser range"); - let mut coreuser = utralib::CSR::new(coreuser_range.as_mut_ptr() as *mut u32); + 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 From fd0f684ee3b633ff140112515921bd04fc664cbe Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 21:57:41 +0800 Subject: [PATCH 13/24] fix stale api in repl --- bao1x-boot/boot1/src/repl.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) 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(); From 22cfaafce4fab08363c53ccce2b9e6af4a6da8ac Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 22:18:37 +0800 Subject: [PATCH 14/24] add force-dabao to alt-boot1 image generation at least for now, with dabao being the only board in the field, this makes sense. --- xtask/src/main.rs | 1 + 1 file changed, 1 insertion(+) 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") From 6f65959adb41473a7c0bbe240c5a7b873c773623 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 22:19:01 +0800 Subject: [PATCH 15/24] add more signing targets --- baosign.ps1 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/baosign.ps1 b/baosign.ps1 index b6af68362..6c8d12c17 100644 --- a/baosign.ps1 +++ b/baosign.ps1 @@ -9,7 +9,7 @@ param( [Parameter(Mandatory = $true)] - [ValidateSet("baremetal", "dabao", "baosec", "bootloader", "kernel", "loader", "swap", "apps", "boot1")] + [ValidateSet("baremetal", "dabao", "baosec", "bootloader", "kernel", "loader", "swap", "apps", "boot1", "alt-boot1")] [string]$Config, [Parameter(Mandatory = $false)] @@ -65,6 +65,9 @@ $configurations = @{ "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 From 1e085a6548e1c49ed37a8412b5ec21e7c4fb3301 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 22:19:13 +0800 Subject: [PATCH 16/24] don't make unknown flash a hard panic this allows an accidental baosec recognition on a dabao board to not brick the board --- libs/bao1x-hal/src/udma/spim.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 From 78f0fcac1a679b14ccdea66a7539bf3a35414578 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 13 Nov 2025 22:20:10 +0800 Subject: [PATCH 17/24] add more differentiation of alt-boot/boot configs also clear the baosec flag when dabao is forced --- bao1x-boot/boot1/src/main.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bao1x-boot/boot1/src/main.rs b/bao1x-boot/boot1/src/main.rs index 3fc06b3e0..dac9958d1 100644 --- a/bao1x-boot/boot1/src/main.rs +++ b/bao1x-boot/boot1/src/main.rs @@ -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); } } From c5fb3f282deba10b36d96ea8c88573375414f543 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 14 Nov 2025 16:15:56 +0800 Subject: [PATCH 18/24] fix handlers to adjust max packet size to enumeration speed this seems to make enumeration more reliable with weird cables --- .../boot1/src/platform/bao1x/usb/handlers.rs | 22 ++++++++++++++----- baremetal/src/platform/bao1x/usb/handlers.rs | 14 +++++++++--- 2 files changed, 28 insertions(+), 8 deletions(-) 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/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) { From c79a89155390fd11a1a64e1db02e1350146b11bf Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 14 Nov 2025 16:16:30 +0800 Subject: [PATCH 19/24] add api to determine current speed --- libs/bao1x-hal/src/usb/driver.rs | 2 ++ 1 file changed, 2 insertions(+) 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"); From ed1f19984f38604b6c6ba25b86799f5222dad972 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 14 Nov 2025 16:16:46 +0800 Subject: [PATCH 20/24] loosen restriction on zero keys seen during wiping this is to handle an edge case where an improperly set ACL on the alpha0 boards would cause a set of keys to be inaccessible to the boot routine --- libs/bao1x-hal/src/sigcheck.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/libs/bao1x-hal/src/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index cc9eae8dc..ef4d8234c 100644 --- a/libs/bao1x-hal/src/sigcheck.rs +++ b/libs/bao1x-hal/src/sigcheck.rs @@ -221,10 +221,9 @@ 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::Data { let (_pa, rw_perms) = slot.get_access_spec(); From 99d10d09a65e7f55d808827cab72766712c270bc Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 14 Nov 2025 18:46:00 +0800 Subject: [PATCH 21/24] cleanup baremetal target signing --- baosign.ps1 | 2 -- 1 file changed, 2 deletions(-) diff --git a/baosign.ps1 b/baosign.ps1 index 6c8d12c17..611bbc1ee 100644 --- a/baosign.ps1 +++ b/baosign.ps1 @@ -32,8 +32,6 @@ $configurations = @{ @{ Image = "bao1x-alt-boot1.img"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" } ) "baremetal" = @( - @{ 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 = "baremetal.img"; FunctionCode = "baremetal" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" } ) "dabao" = @( From 5e805196e607a6c73efc5a1d49a334cc593745b5 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 14 Nov 2025 19:14:25 +0800 Subject: [PATCH 22/24] fix typo --- bao1x-boot/boot1/src/secboot.rs | 2 +- loader/src/main.rs | 4 ++-- loader/src/platform/bao1x/swap.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) 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/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(); } } From ff5cfa7b129ee55e132138e6154a6c9546f0d6c1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 14 Nov 2025 19:14:35 +0800 Subject: [PATCH 23/24] remove panic/resets on errors during secret erase at the moment this runs a risk of boot-loops depending on the configuration of the device. --- libs/bao1x-hal/src/sigcheck.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libs/bao1x-hal/src/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index ef4d8234c..73cef9444 100644 --- a/libs/bao1x-hal/src/sigcheck.rs +++ b/libs/bao1x-hal/src/sigcheck.rs @@ -257,10 +257,12 @@ pub fn erase_secrets() { 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); + /* // 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()); } @@ -268,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!"); } } } From ce168cad74b07636c1f618c5a46573ba823070b6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 14 Nov 2025 19:32:58 +0800 Subject: [PATCH 24/24] make signing flow orthogonal across targets --- baosign.ps1 | 4 ---- 1 file changed, 4 deletions(-) diff --git a/baosign.ps1 b/baosign.ps1 index 611bbc1ee..02a2fa240 100644 --- a/baosign.ps1 +++ b/baosign.ps1 @@ -35,15 +35,11 @@ $configurations = @{ @{ 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" }, @{ 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 = "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" }, @{ 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" }