From 6080667deb7eeac98e40e7e710d8a9dbb04fb59d Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 6 Dec 2025 18:21:14 +0800 Subject: [PATCH 01/11] move console into swap we've run out of space in the main image, so this gives us some breathing room. --- xtask/src/main.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index c1b5bf37b..656913a4f 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -739,13 +739,12 @@ fn main() -> Result<(), Box> { "xous-names", "usb-bao1x", "bao1x-hal-service", - "bao-console", "modals", "pddb", "bao-video", ] .to_vec(); - let bao_swap_pkgs = ["vault2"].to_vec(); + let bao_swap_pkgs = ["bao-console", "vault2"].to_vec(); if !builder.is_swap_set() { // reserve 3MiB for system services: ultimately, "pddb, modals, and bao-video" builder.set_swap(0, bao1x_api::offsets::baosec::SWAP_RAM_LEN as _); From c4ef7baabb7312ee01378af15400a7cc08846de2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 6 Dec 2025 18:21:57 +0800 Subject: [PATCH 02/11] add image size checking in image generator flags when the kernel is too big now --- tools/src/sign_image.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tools/src/sign_image.rs b/tools/src/sign_image.rs index 0452570b1..ebe04aec1 100644 --- a/tools/src/sign_image.rs +++ b/tools/src/sign_image.rs @@ -255,6 +255,19 @@ pub fn sign_image( } dest_file.write_all(&protected)?; + + if function_code == FunctionCode::Kernel { + let target = bao1x_api::RRAM_STORAGE_LEN - (bao1x_api::KERNEL_START - bao1x_api::BOOT0_START); + if dest_file.len() > target { + println!( + "ERROR: Xous RRAM image is too big to fit: {} bytes too large ({} bytes; {} limit)", + dest_file.len() - target, + dest_file.len(), + target, + ); + return Err(String::from("Image doesn't fit").into()); + } + } Ok(dest_file) } } From 9ddf6beae60688b05cf1aae7a58a9eab28f23b04 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 6 Dec 2025 18:23:10 +0800 Subject: [PATCH 03/11] move the kernel start address this correctly gives the loader 256k of space, which is what its link file specifies. The loader was previously under 128k by chance, but with glitch hardening it's grown past that boundary. --- libs/bao1x-api/src/offsets/common.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/bao1x-api/src/offsets/common.rs b/libs/bao1x-api/src/offsets/common.rs index d0300f0d2..bfcfeaefb 100644 --- a/libs/bao1x-api/src/offsets/common.rs +++ b/libs/bao1x-api/src/offsets/common.rs @@ -10,7 +10,7 @@ pub const BOOT1_START: usize = 0x6002_0000; pub const LOADER_START: usize = 0x6006_0000; pub const BAREMETAL_START: usize = LOADER_START; // kernel needs to start on a page boundary, so eat into the loader area a bit to allow that to happen. -pub const KERNEL_START: usize = 0x6008_0000 - crate::signatures::SIGBLOCK_LEN; +pub const KERNEL_START: usize = 0x600A_0000 - crate::signatures::SIGBLOCK_LEN; // total storage area available in RRAM. Above this are reserved vectors for security apparatus. pub const RRAM_STORAGE_LEN: usize = 0x3D_A000; From eee9cd62c93c4a28d4b0b630133f0c0d833e6545 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 6 Dec 2025 18:24:40 +0800 Subject: [PATCH 04/11] enable secure erase confirmation in loader (leaks one chaff key) A problem was discovered while implementing the secure boot hardening. Namely, an attacker could trick the loader into loading a devkey-signed kernel by incrementing the developer mode counter without actually triggering the secure erase of the keys, and finding a way to glitch over the check of the developer mode counter check. Two countermeasuers are implemented: 1. if the developer mode flag is set, trigger a secure erase even if the image signatures aren't developer mode 2. leak one of the chaff keys into the loader, so there are now at least two indpendent checks of being in developer mode in the loader. One is based on the counter, which is only weakly correlated with the erased state. The other is checking for the erase value in the leaked key, which is a strong indicator of being in developer mode. The leaked key is, of course, erased before entering the kernel (and the key is leaked into a region of memory that is, in theory, securely claimed by the keystore, so it's not like anyone can just read it; however, it is in a less secure location than the protected key area). The impact of an adversary obtaining the key is only a slight weakening of security because the chaff keys are numerous, they still have thousands of bits to guess even if they got a couple hundred of them. The next series of patches implements the scheme outlined above, starting with defining the key to be leaked. The leaked key is intentionally the last key in the slice of keys used in the erasure algorithm, so that presumably if the leaked key is showing an erased value, all other keys have been erased. --- libs/bao1x-api/src/offsets/baosec.rs | 13 +++++++++++++ libs/bao1x-api/src/offsets/dabao.rs | 1 + 2 files changed, 14 insertions(+) diff --git a/libs/bao1x-api/src/offsets/baosec.rs b/libs/bao1x-api/src/offsets/baosec.rs index 1fac3cd1b..d9a245e97 100644 --- a/libs/bao1x-api/src/offsets/baosec.rs +++ b/libs/bao1x-api/src/offsets/baosec.rs @@ -116,6 +116,19 @@ pub const NUISANCE_KEYS: [SlotIndex; 2] = [NUISANCE_KEYS_0, NUISANCE_KEYS_1]; /// running your own code on the device). pub const CHAFF_KEYS: SlotIndex = SlotIndex::DataRange(128..256, PartitionAccess::Fw0, RwPerms::ReadWrite); +/// This is intentionally the very last key in the chaff key range. It's "sampled" by copying +/// the full value of this key into the BURAM, which is later passed on to the loader. It's then +/// checked for a value being equal to the erasure value to confirm that a device is in developer +/// mode or not. This process does introduce a risk that this one key is leaked but it also +/// closes a loophole where an attacker can simply manipulate the value of the DEVELOPER_KEY +/// one way counter and fool the system into running a developer-key signed image without the +/// secret keys being erased. +/// +/// Placing this at the end of the key array ostensibly means that all the keys before it were +/// erased; it might be possible to glitch all the way to the end and just have this one erased +/// but I think that is reasonably unlikely... +pub const ERASE_PROOF: SlotIndex = SlotIndex::Data(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. pub const DATA_SLOTS: [SlotIndex; 8] = [ diff --git a/libs/bao1x-api/src/offsets/dabao.rs b/libs/bao1x-api/src/offsets/dabao.rs index 6c4eb3ba4..24858a9b3 100644 --- a/libs/bao1x-api/src/offsets/dabao.rs +++ b/libs/bao1x-api/src/offsets/dabao.rs @@ -43,6 +43,7 @@ pub const DATA_SLOTS: [SlotIndex; 8] = [ crate::offsets::DEV_PUBKEY, ]; +pub use crate::baosec::ERASE_PROOF; pub use crate::baosec::{ CHAFF_KEYS, NUISANCE_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, RMA_KEY, ROOT_SEED, THE_FLAG_1, }; From b1480fa518bb5535b4af55defa85cbb96e5889c5 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 6 Dec 2025 18:34:20 +0800 Subject: [PATCH 05/11] add secret key erasure value check in the loader --- loader/src/main.rs | 38 +++++++++++++++++++++++++++---- loader/src/platform/bao1x/swap.rs | 19 ++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/loader/src/main.rs b/loader/src/main.rs index 4a7bb6cde..0b4cfbd56 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -89,10 +89,11 @@ mod platform; #[cfg(feature = "swap")] pub mod swap; +#[cfg(feature = "bao1x")] +use core::convert::TryInto; use core::{mem, ptr, slice}; use asm::*; -#[cfg(feature = "bao1x")] use bao1x_hal::board::{BOOKEND_END, BOOKEND_START}; use bootconfig::BootConfig; use consts::*; @@ -266,8 +267,10 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32) #[cfg(feature = "bao1x")] let detached_app = { use bao1x_api::{PARANOID_MODE, PARANOID_MODE_DUPE, bollard, pubkeys::LOADER_TO_KERNEL}; + use bao1x_hal::{buram::ERASURE_PROOF_RANGE_BYTES, sigcheck::ERASE_VALUE}; let owc = bao1x_hal::acram::OneWayCounter::new(); + let backup = bao1x_hal::buram::BackupManager::new(); let (paranoid1, paranoid2) = owc.hardened_get2(PARANOID_MODE, PARANOID_MODE_DUPE).unwrap(); let (dev_mode1, dev_mode2) = owc.hardened_get(bao1x_api::DEVELOPER_MODE).unwrap(); csprng.random_delay(); @@ -298,7 +301,9 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32) || key == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT { csprng.random_delay(); - if dev_mode1 == 0 { + let erase_proof: &[u8; 32] = + backup.get_slice(ERASURE_PROOF_RANGE_BYTES).try_into().unwrap(); + if dev_mode1 == 0 || erase_proof != &[ERASE_VALUE; 32] { if paranoid1 == 0 && paranoid2 == 0 { println!("{}LOADER.KERNDIE,{}", BOOKEND_START, BOOKEND_END); println!("Kernel is devkey signed, but system is not in developer mode. Dying!"); @@ -315,7 +320,9 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32) bollard!(bao1x_hal::sigcheck::die_no_std, 4); if !key_inv == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT { csprng.random_delay(); - if dev_mode2 == 0 { + let erase_proof: &[u8; 32] = + backup.get_slice(ERASURE_PROOF_RANGE_BYTES).try_into().unwrap(); + if dev_mode2 == 0 || erase_proof != &[ERASE_VALUE; 32] { if paranoid1 == 0 && paranoid2 == 0 { println!("{}LOADER.KERNDIE,{}", BOOKEND_START, BOOKEND_END); println!("Kernel is devkey signed, but system is not in developer mode. Dying!"); @@ -371,9 +378,11 @@ 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] || key == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT { + let erase_proof: &[u8; 32] = + backup.get_slice(ERASURE_PROOF_RANGE_BYTES).try_into().unwrap(); // we can't erase keys in the loader, because the keys have already been locked // out at this point. Thus, ensure that the system is already in developer mode. - if dev_mode1 == 0 { + if dev_mode1 == 0 || erase_proof != &[ERASE_VALUE; 32] { if paranoid1 == 0 && paranoid2 == 0 { println!("{}LOADER.APPDIE,{}", BOOKEND_START, BOOKEND_END); println!( @@ -389,7 +398,9 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32) csprng.random_delay(); bollard!(bao1x_hal::sigcheck::die_no_std, 4); if !key_inv == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT { - if dev_mode2 == 0 { + let erase_proof: &[u8; 32] = + backup.get_slice(ERASURE_PROOF_RANGE_BYTES).try_into().unwrap(); + if dev_mode2 == 0 || erase_proof != &[ERASE_VALUE; 32] { if paranoid1 == 0 && paranoid2 == 0 { println!("{}LOADER.APPDIE,{}", BOOKEND_START, BOOKEND_END); println!( @@ -518,6 +529,14 @@ fn boot_sequence( check_load(&mut cfg); } println!("done initializing for cold boot."); + #[cfg(feature = "bao1x")] + { + // cleanup the leaked key to the backup registers + let mut buram = bao1x_hal::buram::BackupManager::new(); + bao1x_api::bollard!(bao1x_hal::sigcheck::die_no_std, 4); + buram.store_slice(&[0u8; 32], bao1x_hal::buram::ERASURE_PROOF_RANGE_BYTES.start); + bao1x_api::bollard!(bao1x_hal::sigcheck::die_no_std, 4); + } } #[cfg(feature = "resume")] if clean { @@ -564,6 +583,15 @@ fn boot_sequence( // condense debug and resume arguments into a single register, so we have space for XPT let debug_resume = if cfg.debug { 0x1 } else { 0x0 } | if clean { 0x2 } else { 0x0 }; if !clean { + #[cfg(feature = "bao1x")] + { + // clean it twice, just in case the first cleanup was glitched past + let mut buram = bao1x_hal::buram::BackupManager::new(); + bao1x_api::bollard!(bao1x_hal::sigcheck::die_no_std, 4); + buram.store_slice(&[0u8; 32], bao1x_hal::buram::ERASURE_PROOF_RANGE_BYTES.start); + bao1x_api::bollard!(bao1x_hal::sigcheck::die_no_std, 4); + } + // The MMU should be set up now, and memory pages assigned to their // respective processes. let krn_struct_start = cfg.sram_start as usize + cfg.sram_size - cfg.init_size + cfg.swap_offset; diff --git a/loader/src/platform/bao1x/swap.rs b/loader/src/platform/bao1x/swap.rs index bc5d6180f..bae565370 100644 --- a/loader/src/platform/bao1x/swap.rs +++ b/loader/src/platform/bao1x/swap.rs @@ -10,6 +10,7 @@ use bao1x_hal::board::{APP_UART_IFRAM_ADDR, SPIM_FLASH_IFRAM_ADDR, SPIM_RAM_IFRA use bao1x_hal::ifram::IframRange; use bao1x_hal::iox::Iox; use bao1x_hal::sce; +use bao1x_hal::sigcheck::ERASE_VALUE; use bao1x_hal::udma::{GlobalConfig, Spim, SpimClkPha, SpimClkPol, SpimCs}; use rand_chacha::ChaCha8Rng; use rand_chacha::rand_core::RngCore; @@ -233,6 +234,11 @@ impl SwapHal { // check signature only if the swap key is all 0's // this is not very glitch-hardened because at this point, the adversary has full // control over the code coming in. A TOCTOU is extremely easy to pull off. + // + // In practice for full security, the swap shall be encrypted to a custom symmetric + // key unique to each device, which takes the place of the signature check. This + // check is thus assumed to be performed only upon the first presentation of + // a signed update. if swap.key == [0u8; 32] { crate::println!("Fresh swap image found - checking signature before proceeding"); match bao1x_hal::sigcheck::validate_image( @@ -247,9 +253,11 @@ impl SwapHal { !k2, core::str::from_utf8(&tag).unwrap_or("invalid tag") ); + bollard!(bao1x_hal::sigcheck::die_no_std, 4); if k != !k2 { bao1x_hal::sigcheck::die_no_std(); } + bollard!(bao1x_hal::sigcheck::die_no_std, 4); // k is just a nominal slot number. If either match, assume we are dealing // with a developer image. if tag @@ -262,6 +270,7 @@ impl SwapHal { // locked out at this point. Thus, // ensure that the system is already in developer mode. let owc = bao1x_hal::acram::OneWayCounter::new(); + bollard!(bao1x_hal::sigcheck::die_no_std, 4); if owc.get(bao1x_api::DEVELOPER_MODE).unwrap() == 0 { println!("{}LOADER.SWAPDIE,{}", BOOKEND_START, BOOKEND_END); println!( @@ -274,6 +283,16 @@ impl SwapHal { "Developer key detected on swap. Proceeding in developer mode!" ); } + let backup = bao1x_hal::buram::BackupManager::new(); + bollard!(bao1x_hal::sigcheck::die_no_std, 4); + let erase_proof: &[u8; 32] = backup + .get_slice(bao1x_hal::buram::ERASURE_PROOF_RANGE_BYTES) + .try_into() + .unwrap(); + if erase_proof != &[ERASE_VALUE; 32] { + bao1x_hal::sigcheck::die_no_std(); + } + bollard!(bao1x_hal::sigcheck::die_no_std, 4); } } Err(e) => { From 09e68291cfc880dbe24f15b9ff0990b07c937e8f Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 6 Dec 2025 18:35:43 +0800 Subject: [PATCH 06/11] during key erasure, add the proof that secret keys were erased --- libs/bao1x-hal/src/sigcheck.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/libs/bao1x-hal/src/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index 1c3b51394..f7a51d1d9 100644 --- a/libs/bao1x-hal/src/sigcheck.rs +++ b/libs/bao1x-hal/src/sigcheck.rs @@ -17,6 +17,8 @@ use xous::arch::PAGE_SIZE; use crate::acram::OneWayCounter; #[cfg(not(feature = "std"))] use crate::acram::{AccessSettings, SlotManager}; +#[cfg(not(feature = "std"))] +use crate::buram::{BackupManager, ERASURE_PROOF_RANGE_BYTES}; use crate::hardening::Csprng; use crate::udma::Spim; @@ -191,7 +193,7 @@ pub fn validate_image( // the function inside the ed25519 crate. bollard!(die_no_std, 4); csprng.as_deref_mut().map(|rng| rng.random_delay()); - // this match statement is an achille's heel. I don't want to fork the cryptographic + // this match statement is an Achilles's heel. I don't want to fork the cryptographic // crates, so we have an unhardened comparison of the result. The work-around is // in paranoid mode, we command the system to verify things *twice* match verifying_key.verify_prehashed(h, None, &ed25519_signature) { @@ -227,7 +229,7 @@ pub fn validate_image( bollard!(die_no_std, 4); csprng.as_deref_mut().map(|rng| rng.random_delay()); - // this match statement is an achille's heel. I don't want to fork the cryptographic + // this match statement is an Achilles's heel. I don't want to fork the cryptographic // crates, so we have an unhardened comparison of the result. The work-around is // in paranoid mode, we command the system to verify things *twice* match verifying_key.verify_strict(&msg, &ed25519_signature) { @@ -283,6 +285,12 @@ pub fn erase_secrets(csprng: &mut Option<&mut Csprng>) -> Result<(), String> { let slot_mgr = SlotManager::new(); let mut rram = crate::rram::Reram::new(); + let mut buram = BackupManager::new(); + // erase the backup RAM region to 0 that is the erasure proof. + bollard!(die_no_std, 4); + csprng.as_deref_mut().map(|rng| rng.random_delay()); + buram.store_slice(&[0u8; 32], crate::buram::ERASURE_PROOF_RANGE_BYTES.start); + let mut zero_key_count = 0; // This is set to a higher level because we need to work around an earlier issue // with overly-broad ACL settings on alpha0 boards @@ -345,10 +353,17 @@ pub fn erase_secrets(csprng: &mut Option<&mut Csprng>) -> Result<(), String> { bollard!(die_no_std, 4); } bollard!(die_no_std, 4); + + // store the proof that the key array was erased - could lead to disclosure of one key, + // but we also can't simply trust that the oneway counter below is accurate + csprng.as_deref_mut().map(|rng| rng.random_delay()); + buram.store_slice(slot_mgr.read(&crate::board::ERASE_PROOF).unwrap(), ERASURE_PROOF_RANGE_BYTES.start); + let owc = OneWayCounter::new(); // once all secrets are erased, advance the DEVELOPER_MODE state // safety: the offset is correct because we're pulling it from our pre-defined constants and // those are manually checked. + bollard!(die_no_std, 4); if owc.get(DEVELOPER_MODE).unwrap() < 15 { // limit incrementing to avoid memory wear-out, as erase_secrets() can be called every time on boot. unsafe { owc.inc(DEVELOPER_MODE).unwrap() }; From 15ac4d8529b1e86475b174cbc56d1be4307f2b81 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 6 Dec 2025 18:36:51 +0800 Subject: [PATCH 07/11] add primitives to buram for storing slices this is used by the key erase proof routine, but will be useful in general for storing data in the buram also, the ranges of slices are currently defined at the top of the file but might be moved somewhere more maintainable later. RRAM writing got bollards added to it, as RRAM write could be a glitch target: if a glitch could manipulate the address somehow to stick stuff at an arbitrary location, during write, that would be bad. However, it's probably also reasonably dangerous to try and glitch RRAM writes because there's a chance you spray over off-target items and thus trigger a signature check failure on your next boot. --- libs/bao1x-hal/src/buram.rs | 25 +++++++++++++++++++++++-- libs/bao1x-hal/src/hardening.rs | 2 +- libs/bao1x-hal/src/rram.rs | 6 ++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/libs/bao1x-hal/src/buram.rs b/libs/bao1x-hal/src/buram.rs index 43112a5d0..636e2fd97 100644 --- a/libs/bao1x-hal/src/buram.rs +++ b/libs/bao1x-hal/src/buram.rs @@ -6,6 +6,8 @@ const HASH_LOC: usize = 0; #[allow(dead_code)] const RESERVED_LOC: usize = 1; +pub const ERASURE_PROOF_RANGE_BYTES: Range = 0..32; + use crate::buram::murmur3::murmur3_32; const fn range_len(r: Range) -> usize { r.end - r.start } @@ -86,9 +88,28 @@ impl BackupManager { } } - pub fn bu_ram_as_slice(&self) -> &[u8] { unsafe { self.bu_ram.as_slice() } } + pub fn store_slice(&mut self, input: &[T], byte_offset: usize) { + let type_offset = byte_offset / size_of::(); + // safety: safe because make_valid() is called after the slice is accessed + let dest: &mut [T] = unsafe { &mut self.bu_ram_as_mut()[type_offset..type_offset + input.len()] }; + dest.copy_from_slice(&input); - pub fn bu_ram_as_mut(&mut self) -> &mut [u8] { unsafe { self.bu_ram.as_slice_mut() } } + self.make_valid(); + } + + pub fn get_slice(&self, byte_range: core::ops::Range) -> &[T] { + let type_offset = byte_range.start / size_of::(); + let type_len = (byte_range.end - byte_range.start) / size_of::(); + &self.bu_ram_as_slice()[type_offset..type_offset + type_len] + } + + pub fn bu_ram_as_slice(&self) -> &[T] { unsafe { self.bu_ram.as_slice::() } } + + /// Safety: modifications to the backup RAM array need a follow-up call to `make_valid` + /// in order for the boot check to pass. + /// + /// Could try to get clever and implement a `Drop` trait which includes a make_valid() call? maybe? + pub unsafe fn bu_ram_as_mut(&mut self) -> &mut [T] { self.bu_ram.as_slice_mut::() } } pub mod murmur3 { diff --git a/libs/bao1x-hal/src/hardening.rs b/libs/bao1x-hal/src/hardening.rs index d92f87d19..c85bd0edd 100644 --- a/libs/bao1x-hal/src/hardening.rs +++ b/libs/bao1x-hal/src/hardening.rs @@ -97,7 +97,7 @@ impl Csprng { word.copy_from_slice(&ro_trng.get_raw().to_ne_bytes()); } - crate::println!("seed: {:x?}", seed); // used to eyeball that things are working correctly + // crate::println!("seed: {:x?}", seed); // used to eyeball that things are working correctly let mut csprng = ChaCha8Rng::from_seed(seed); let entropy_bank = csprng.next_u64(); diff --git a/libs/bao1x-hal/src/rram.rs b/libs/bao1x-hal/src/rram.rs index 11760a60c..5a1e7e29e 100644 --- a/libs/bao1x-hal/src/rram.rs +++ b/libs/bao1x-hal/src/rram.rs @@ -188,8 +188,12 @@ impl<'a> Reram { assert!(data.len() % 8 == 0, "unaligned source data!"); // crate::print!("@ {:x} > ", addr); for (outer, d) in data.chunks_exact(8).enumerate() { + #[cfg(not(feature = "kernel"))] + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); // write the data to the buffer for (inner, &datum) in d.iter().enumerate() { + #[cfg(not(feature = "kernel"))] + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); // crate::print!(" {:x}", datum); self.array .as_mut_ptr() @@ -199,6 +203,8 @@ impl<'a> Reram { } // crate::println!(""); + #[cfg(not(feature = "kernel"))] + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); self.csr.rmwf(utra::rrc::SFR_RRCCR_SFR_RRCCR, RRC_CR_WRITE_CMD | SECURITY_MODE); self.array .as_mut_ptr() From 66272a82e49b5c2e739e9902fccba26d5589aacc Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 6 Dec 2025 18:39:58 +0800 Subject: [PATCH 08/11] ensure secret erasure if developer mode bit is set this is the final part of the developer mode bit hardening. If an adversary manages to increment the developer mode bit, the next reboot they have to contend with active counter- measures that would attempt to erase the secrets due to the developer mode bit being set. As noted in the top of the commit set, previously, without this, the attacker would have the luxury of being able to flip the bit and try many times to bypass the developer mode check. --- bao1x-boot/boot0/src/main.rs | 21 +++++++- bao1x-boot/boot1/src/platform/bao1x/bao1x.rs | 5 +- bao1x-boot/boot1/src/platform/bao1x/slots.rs | 56 +++----------------- bao1x-boot/boot1/src/secboot.rs | 20 ++++++- 4 files changed, 50 insertions(+), 52 deletions(-) diff --git a/bao1x-boot/boot0/src/main.rs b/bao1x-boot/boot0/src/main.rs index 50f08d93e..e47359ea7 100644 --- a/bao1x-boot/boot0/src/main.rs +++ b/bao1x-boot/boot0/src/main.rs @@ -15,7 +15,7 @@ use alloc::collections::VecDeque; use core::cell::RefCell; use bao1x_api::pubkeys::{BOOT0_SELF_CHECK, BOOT0_TO_ALTBOOT1, BOOT0_TO_BOOT1}; -use bao1x_api::{BOOT0_PUBKEY_FAIL, bollard}; +use bao1x_api::{BOOT0_PUBKEY_FAIL, DEVELOPER_MODE, bollard}; use bao1x_api::{HardenedBool, PARANOID_MODE, PARANOID_MODE_DUPE}; use bao1x_hal::acram::OneWayCounter; use bao1x_hal::hardening::{check_pll, die, mesh_setup}; @@ -172,6 +172,25 @@ pub unsafe extern "C" fn rust_entry() -> ! { bollard!(die, 4); // == end self validation == + // If the developer bit is set, ensure that keys are erased. The edge case we're worried about is + // if an attacker sets developer bit, even with signed images - this can allow for an easier + // time of booting a malicious kernel because we can't erase secret keys inside the loader + // due to access restrictions. + csprng.random_delay(); + let (dev1, dev2) = owc.hardened_get(DEVELOPER_MODE).unwrap(); + if dev1 != 0 { + bao1x_hal::sigcheck::erase_secrets(&mut Some(&mut csprng)) + .inspect_err(|e| crate::println!("{}", e)) + .ok(); // "ok" because the expected error is a check on logic/configuration bugs, not attacks + } + bollard!(die, 4); + csprng.random_delay(); + if dev2 != 0 { + bao1x_hal::sigcheck::erase_secrets(&mut Some(&mut csprng)) + .inspect_err(|e| crate::println!("{}", e)) + .ok(); // "ok" because the expected error is a check on logic/configuration bugs, not attacks + } + bollard!(die, 4); let boot_order = match owc.get_decoded::() { // Primary boot selected. Check Boot1 first, then fall back to LOADER/BAREMETAL. diff --git a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs index 0e0d62e6b..aeb0d2c1c 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs @@ -71,7 +71,10 @@ pub fn setup_backup_region() -> u32 { let mut bu_mgr = bao1x_hal::buram::BackupManager::new(); if !bu_mgr.is_backup_valid() { // zeroize the backup RAM - bu_mgr.bu_ram_as_mut().fill(0); + // safety: make_valid is called after this is done. + unsafe { + bu_mgr.bu_ram_as_mut().fill(0); + } // calculate the hash and mark as valid bu_mgr.make_valid(); diff --git a/bao1x-boot/boot1/src/platform/bao1x/slots.rs b/bao1x-boot/boot1/src/platform/bao1x/slots.rs index 216888f3e..995fcbf87 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/slots.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/slots.rs @@ -23,6 +23,8 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) { let mut rram = Reram::new(); // check the lifecycle status + // glitch_safety: this is done in a controlled environment, and not done again later, + // so we don't need to harden it. If it is repeated due to a glitch it actually leads to data loss. if owc.get(bao1x_api::CP_BOOT_SETUP_DONE).unwrap() == 0 { crate::println!("CP setup not yet done. Initializing public identifiers..."); // CP boot setup is not done. Initialize the basic identifiers. @@ -72,52 +74,6 @@ 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 - && owc.get(bao1x_api::INVOKE_DABAO_KEY_SETUP).unwrap() != 0 - && owc.get(bao1x_api::DABAO_KEY_SETUP_DONE).unwrap() == 0) - { - crate::println!("System setup not yet done. Initializing secret identifiers..."); - let trng = maybe_trng.get_or_insert_with(|| super::trng::ManagedTrng::new(&board_type)); - // 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[..] - }; - for key_range in key_set.iter() { - let mut storage = alloc::vec::Vec::with_capacity(key_range.len() * SLOT_ELEMENT_LEN_BYTES); - storage.resize(key_range.len() * SLOT_ELEMENT_LEN_BYTES, 0); - for chunk in storage.chunks_mut(SLOT_ELEMENT_LEN_BYTES) { - chunk.copy_from_slice(&trng.generate_key()); - } - match slot_mgr.write(&mut rram, key_range, &storage) { - Ok(_) => {} - Err(e) => { - crate::println!("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 *board_type == bao1x_api::BoardTypeCoding::Baosec { - unsafe { owc.inc(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() }; - } else if *board_type == bao1x_api::BoardTypeCoding::Dabao { - unsafe { owc.inc(bao1x_api::DABAO_KEY_SETUP_DONE).unwrap() }; - } - crate::println!("Secret ID init done."); - } - */ - #[cfg(feature = "print-ifr")] print_ifr(); @@ -128,11 +84,13 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) { // wear-out on the ACL entries as every time a transition is made into a developer images, a set // of keys are checked to be erased. While it is possible to bypass the ACL checks by flipping // the developer mode bit, the key check/erasure would still happen upon launch into developer mode. + // + // glitch_safety: we don't harden this because this is already a "seatbelt" safety measure + // in most cases it should do nothing because the ACLs are already correct. Also, if DEVELOPER_MODE + // is tripped, there is a hardened check that ensures keys are erased when that bit is set. #[cfg(feature = "unsafe-debug")] print_slots(&slot_mgr, &bao1x_api::baosec::KEY_SLOTS); // this prints all the keys as they are created - if (*board_type == bao1x_api::BoardTypeCoding::Baosec || *board_type == bao1x_api::BoardTypeCoding::Dabao) - && owc.get(bao1x_api::DEVELOPER_MODE).unwrap() == 0 - { + if owc.get(bao1x_api::DEVELOPER_MODE).unwrap() == 0 { #[cfg(feature = "unsafe-debug")] print_slots(&slot_mgr, &bao1x_api::baosec::KEY_SLOTS); check_and_fix_acls(&mut rram, &mut slot_mgr, &bao1x_api::baosec::KEY_SLOTS); diff --git a/bao1x-boot/boot1/src/secboot.rs b/bao1x-boot/boot1/src/secboot.rs index e8764c741..4927bfc16 100644 --- a/bao1x-boot/boot1/src/secboot.rs +++ b/bao1x-boot/boot1/src/secboot.rs @@ -1,4 +1,6 @@ -use bao1x_api::{PARANOID_MODE, PARANOID_MODE_DUPE, bollard, pubkeys::BOOT1_TO_LOADER_OR_BAREMETAL}; +use bao1x_api::{ + DEVELOPER_MODE, PARANOID_MODE, PARANOID_MODE_DUPE, bollard, pubkeys::BOOT1_TO_LOADER_OR_BAREMETAL, +}; use bao1x_hal::hardening::Csprng; #[inline(always)] @@ -19,6 +21,22 @@ fn seal_boot1_keys() { pub fn try_boot(or_die: bool, csprng: &mut Csprng) { let one_way = bao1x_hal::acram::OneWayCounter::new(); bollard!(bao1x_hal::sigcheck::die_no_std, 4); + + // If the developer bit is set, ensure that keys are erased. The edge case we're worried about is + // if an attacker sets developer bit, even with signed images - this can allow for an easier + // time of booting a malicious kernel because we can't erase secret keys inside the loader + // due to access restrictions. + csprng.random_delay(); + let (dev1, dev2) = one_way.hardened_get(DEVELOPER_MODE).unwrap(); + if dev1 != 0 { + bao1x_hal::sigcheck::erase_secrets(&mut Some(csprng)).inspect_err(|e| crate::println!("{}", e)).ok(); // "ok" because the expected error is a check on logic/configuration bugs, not attacks + } + bollard!(bao1x_hal::sigcheck::die_no_std, 4); + csprng.random_delay(); + if dev2 != 0 { + bao1x_hal::sigcheck::erase_secrets(&mut Some(csprng)).inspect_err(|e| crate::println!("{}", e)).ok(); // "ok" because the expected error is a check on logic/configuration bugs, not attacks + } + csprng.random_delay(); let (paranoid1, paranoid2) = one_way.hardened_get2(PARANOID_MODE, PARANOID_MODE_DUPE).unwrap(); csprng.random_delay(); From 03d318d2a94a82993bac1d6dbeca6df8a81c5f60 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 6 Dec 2025 20:44:20 +0800 Subject: [PATCH 09/11] fix precursor target --- loader/src/main.rs | 1 + loader/src/phase2.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/loader/src/main.rs b/loader/src/main.rs index 0b4cfbd56..f83803bd3 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -94,6 +94,7 @@ use core::convert::TryInto; use core::{mem, ptr, slice}; use asm::*; +#[cfg(feature = "bao1x")] use bao1x_hal::board::{BOOKEND_END, BOOKEND_START}; use bootconfig::BootConfig; use consts::*; diff --git a/loader/src/phase2.rs b/loader/src/phase2.rs index b71231ee5..1c8b0490a 100644 --- a/loader/src/phase2.rs +++ b/loader/src/phase2.rs @@ -43,6 +43,7 @@ pub fn phase_2(cfg: &mut BootConfig, env_variables: EnvVariables) { for tag in args.iter() { let mut env_header = crate::env::EnvHeader::default(); + #[allow(unused_mut)] let mut pid_env = env_variables.clone(); #[cfg(feature = "bao1x")] From 53c7a729f787fe2dcd51af4367dae6efe8f2a6c8 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 7 Dec 2025 01:33:53 +0800 Subject: [PATCH 10/11] add primitives for interrupt-based glitch handlers glitches can trigger interrupts from several sources: - ECC errors on multiple blocks - consistency check errors on hardened logic - light sensor - voltage sensor - glue cells These primitives respond to these glitches in an interrupt context. At the moment, by default a fairly lax approach is taken to responding to the glitches: partially, we want to make sure that the sensors aren't too sensitive and trigger by accident. The final thresholds can be adjusted fairly readily. In addition, the mesh can trigger an interrupt, and typically, that interrupt is a false reading (because the mesh takes a long time to settle, and we boot the system while the mesh settles). Thus, we take an approach of polling the mesh effectively, and when interrupts happen due to the mesh we just clear it and ignore it and allow the polling routine to manage the mesh. The mesh is theorized to be a static attack, anyways. --- libs/bao1x-hal/Cargo.toml | 3 +- libs/bao1x-hal/src/acram.rs | 4 +- libs/bao1x-hal/src/hardening.rs | 144 +++++++++++++++++++++++++++++--- 3 files changed, 138 insertions(+), 13 deletions(-) diff --git a/libs/bao1x-hal/Cargo.toml b/libs/bao1x-hal/Cargo.toml index 1478af469..17b02ae17 100644 --- a/libs/bao1x-hal/Cargo.toml +++ b/libs/bao1x-hal/Cargo.toml @@ -102,8 +102,9 @@ mpw = ["utralib/bao1x"] hdl-test = ["utralib/bao1x"] verbose-debug = [] debug-print = [] -debug-print-duart = ["debug-print"] +debug-print-duart = ["debug-print", "debug-countermeasures"] debug-print-uart = ["debug-print"] +debug-countermeasures = [] udma-stress-test = [ ] # For RTL simulation testing - aggravates a key corner case diff --git a/libs/bao1x-hal/src/acram.rs b/libs/bao1x-hal/src/acram.rs index ae3ec184e..acf6dd43d 100644 --- a/libs/bao1x-hal/src/acram.rs +++ b/libs/bao1x-hal/src/acram.rs @@ -360,8 +360,8 @@ 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 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}, offset: {:x}", ptr as usize, absolute_offset); + // let ptr: *const u8 = &self.data_range.as_slice::()[absolute_offset] as *const u8; + // 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] } diff --git a/libs/bao1x-hal/src/hardening.rs b/libs/bao1x-hal/src/hardening.rs index c85bd0edd..77299bedd 100644 --- a/libs/bao1x-hal/src/hardening.rs +++ b/libs/bao1x-hal/src/hardening.rs @@ -9,6 +9,15 @@ use utralib::*; use crate::acram::OneWayCounter; use crate::sigcheck::erase_secrets; +/// use a large threshold initially, under the theory that e.g. fault injections tend +/// to take thousands of iterations to succeed, and we really don't want to accidentally +/// wipe customer data. For now, the policy is to only wipe to those who have consented +/// by turning on paranoid mode. +/// +/// Pick a number that has a high hamming distance from 0 - and so, prefer e.g. 127 vs 128. +pub const WIPE_THRESHOLD: u32 = 127; +const DISTURB_THRESHOLD: u32 = 3; + /// This is the range of delays we will pick from whenever we attempt a random delay, /// expressed as a number of bits. const DELAY_MARGIN_BITS: u64 = 8; @@ -128,9 +137,45 @@ pub fn paranoid_mode() { sensor.wo(utra::sensorc::SFR_VDMASK0, 0); bao1x_api::bollard!(die, 4); sensor.wo(utra::sensorc::SFR_VDMASK1, 0); // putting 0 here makes the chip reset on glitch detect - // redundant write in case of glitching +} - // TODO: set up glue cells & interrupts +/// This call clears any current alarms and resets sensors, but does not +/// enable (or re-enable) interrupts +pub fn reset_sensors() { + let glue = CSR::new(utra::gluechain::HW_GLUECHAIN_BASE as *mut u32); + let mut sensor = CSR::new(utra::sensorc::HW_SENSORC_BASE as *mut u32); + // reset the glue chain. Hard-coded constants are used here because + // the UTRA did not extract these constants correctly. + bao1x_api::bollard!(die, 4); + unsafe { + glue.base().add(4).write_volatile(0); + glue.base().add(5).write_volatile(0); + } + // wait for reset to propagate + for _ in 0..100 { + bao1x_api::bollard!(4); + } + // re-arm + bao1x_api::bollard!(die, 4); + unsafe { + glue.base().add(0).write_volatile(0x0); + glue.base().add(1).write_volatile(0x0); + glue.base().add(4).write_volatile(0xFFFF_FFFF); + glue.base().add(5).write_volatile(0xFFFF_FFFF); + glue.base().add(6).write_volatile(0x0); + glue.base().add(7).write_volatile(0x0); + } + + // this enables all the sensors to create non-resetting interrupts + bao1x_api::bollard!(die, 4); + sensor.wo(utra::sensorc::SFR_VDFR, 0x3f); // clear any voltage alarms + sensor.wo(utra::sensorc::SFR_VDMASK0, 0); + // DONT TOUCH THIS - paranoid mode sets this, and can set it BEFORE reset_sensors is called! + // sensor.wo(utra::sensorc::SFR_VDMASK1, 0x3f); + sensor.wo(utra::sensorc::SFR_LDIP_FD, 0x1ff); // setup filtering parameters + sensor.wo(utra::sensorc::SFR_LDCFG, 0xc); + sensor.wo(utra::sensorc::SFR_LDMASK, 0x0); // turn on both sensors + bao1x_api::bollard!(die, 4); } /// Mesh is a bit challenging to check on a fast-boot system. This is because it @@ -271,14 +316,6 @@ pub fn mesh_check_and_react(csprng: &mut Csprng, one_way: &OneWayCounter) { } pub fn apply_attack_policy(csprng: &mut Csprng, one_way: &OneWayCounter) { - // use a large threshold initially, under the theory that e.g. fault injections tend - // to take thousands of iterations to succeed, and we really don't want to accidentally - // wipe customer data. For now, the policy is to only wipe to those who have consented - // by turning on paranoid mode. - // - // Pick a number that has a high hamming distance from 0 - and so, prefer e.g. 127 vs 128. - const WIPE_THRESHOLD: u32 = 127; - bollard!(die, 4); csprng.random_delay(); let (paranoid1, paranoid2) = @@ -304,3 +341,90 @@ pub fn apply_attack_policy(csprng: &mut Csprng, one_way: &OneWayCounter) { } } } + +pub fn glitch_handler(attacks_since_boot: u32) { + let owc = OneWayCounter::new(); + let mut irq13 = CSR::new(utra::irqarray13::HW_IRQARRAY13_BASE as *mut u32); + let mut irq15 = CSR::new(utra::irqarray15::HW_IRQARRAY15_BASE as *mut u32); + // Only secirq is recoverable: this is a sensor that has triggered. This is the only + // type of "attack" that we envision would need recovering from, because the sensors + // could be too sensitive. Thus, for all other IRQ types, just halt. + let reason = irq13.r(utra::irqarray13::EV_PENDING); + + let mut was_sensor = false; + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); + if reason & 0x8 != 0 { + // figure out which subsystem glitched + let sensor = irq15.r(utra::irqarray15::EV_PENDING); + const GLUE_MASK: u32 = 1 << 0; + const SENSOR_MASK: u32 = 1 << 1; + const MESH_MASK: u32 = 1 << 2; + if sensor & MESH_MASK != 0 { + // mesh events are handled by a separate routine + #[cfg(feature = "debug-countermeasures")] + crate::println!("mesh"); + } + if sensor & SENSOR_MASK != 0 || sensor & GLUE_MASK != 0 { + #[cfg(feature = "debug-countermeasures")] + crate::println!("Sensor {:x}", sensor); + // this resets all the sensors that *can* be reset + crate::hardening::reset_sensors(); + was_sensor = true; + } + irq15.wo(utra::irqarray15::EV_PENDING, sensor); + } + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); + if !was_sensor { + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); + // mesh sensor will trigger while settling measurements; and there is no way to mask it + irq13.wo(utra::irqarray13::EV_PENDING, reason); + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); + return; + } + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); + + // safety: this is safe because the offset is from a checked, pre-defined value + unsafe { + // the increment is just OK'd because if for some reason it fails we still want + // to execute the following code. + owc.inc(bao1x_api::POSSIBLE_ATTACKS).ok(); + } + let attacks = owc.get(bao1x_api::POSSIBLE_ATTACKS).unwrap_or(WIPE_THRESHOLD + 1); + + // on the paranoid path: wipe secrets if we exceed a wipe threshold + let (paranoid1, paranoid2) = + owc.hardened_get2(bao1x_api::PARANOID_MODE, bao1x_api::PARANOID_MODE_DUPE).unwrap(); + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); + if paranoid1 != 0 { + if attacks > WIPE_THRESHOLD { + crate::sigcheck::erase_secrets(&mut None).ok(); + } + crate::sigcheck::die_no_std(); + } + if paranoid2 != 0 { + if attacks > WIPE_THRESHOLD { + crate::sigcheck::erase_secrets(&mut None).ok(); + } + crate::sigcheck::die_no_std(); + } + + // on the non-paranoid path: just wipe NV elements & halt if we see a lower threshold of attacks + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); + if attacks_since_boot > DISTURB_THRESHOLD { + // even output something on the DUART - this could be used as a trigger to prevent shutdown + // but at this point diagnostics are useful for seeing why the system shut down unexpectedly. + #[cfg(feature = "debug-countermeasures")] + crate::println!("Attack thresh"); + crate::sigcheck::die_no_std(); + } + + bao1x_api::bollard!(crate::sigcheck::die_no_std, 4); + // non-sensor reasons are non-recoverable: we'll just repeatedly re-enter the interrupt state + // in this case, just erase the NV data and die. + if reason & !0x8 != 0 { + #[cfg(feature = "debug-countermeasures")] + crate::println!("Halt {:x}", reason); + crate::sigcheck::die_no_std(); + } + irq13.wo(utra::irqarray13::EV_PENDING, reason); +} From c85425ae91b4954e31494a641543dd6db363c218 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 7 Dec 2025 01:37:55 +0800 Subject: [PATCH 11/11] add dynamic glitch response via IRQs non-paranoid mode responses happen through IRQs (recall that paranoid mode is a hair-trigger hardware reset with no exceptions). This patch installs the IRQ handlers in boot0 and boot1. - boot0 in particular now even has an IRQ handler. Previously, it didn't have the IRQ facility configured, because there was no need for one. - boot0 sets up the sensors, and the IRQs - boot1 merely continues with boot0's settings, but re-installing the trap handler to be its own and double-checking some register settings. An old testing IRQ handler stub for keyboard presses was also removed, as it can never be triggered as that IRQ is never set up. --- bao1x-boot/boot0/src/platform/bao1x/bao1x.rs | 32 +++++++++++++++++--- bao1x-boot/boot0/src/platform/bao1x/irq.rs | 23 ++++++++------ bao1x-boot/boot1/src/platform/bao1x/bao1x.rs | 11 ++++++- bao1x-boot/boot1/src/platform/bao1x/irq.rs | 19 ++++++++---- 4 files changed, 63 insertions(+), 22 deletions(-) diff --git a/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs b/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs index 15944de51..bef13a2a3 100644 --- a/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs +++ b/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs @@ -9,10 +9,8 @@ use utralib::utra; use utralib::utra::sysctrl; #[cfg(feature = "unsafe-dev")] -use crate::platform::{ - debug::setup_rx, - irq::{enable_irq, irq_setup}, -}; +use crate::platform::debug::setup_rx; +use crate::platform::irq::{enable_irq, irq_setup}; #[global_allocator] static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty(); @@ -149,6 +147,31 @@ pub fn early_init() -> Csprng { let mut csprng = Csprng::new(); csprng.random_delay(); + irq_setup(); + // set up the reactive sensors + bao1x_api::bollard!(4); + bao1x_hal::hardening::reset_sensors(); + bao1x_api::bollard!(4); + bollard!(die, 4); + csprng.random_delay(); + // ensure paranoid mode is respected + if paranoid2 != 0 { + bollard!(die, 4); + paranoid_mode(); + } + // set up IRQ to respond to all possible sensor errors + let mut irq13 = CSR::new(utra::irqarray13::HW_IRQARRAY13_BASE as *mut u32); + irq13.wo(utra::irqarray13::EV_EDGE_TRIGGERED, 0xFFFF_FFFF); + irq13.wo(utra::irqarray13::EV_POLARITY, 0xFFFF_FFFF); + irq13.wo(utra::irqarray13::EV_PENDING, 0xFFFF_FFFF); + irq13.wo(utra::irqarray13::EV_ENABLE, 0xFFFF_FFFF); + enable_irq(utra::irqarray13::IRQARRAY13_IRQ); + csprng.random_delay(); + if paranoid1 != 0 { + bollard!(die, 4); + paranoid_mode(); + } + // setup heap alloc // glitch_safety: failing to initialize this will generally cause heap allocs to hang setup_alloc(); @@ -193,7 +216,6 @@ pub fn early_init() -> Csprng { #[cfg(feature = "unsafe-dev")] let mut udma_uart = { let mut udma_uart = setup_rx(perclk); - irq_setup(); enable_irq(utra::irqarray5::IRQARRAY5_IRQ); udma_uart }; diff --git a/bao1x-boot/boot0/src/platform/bao1x/irq.rs b/bao1x-boot/boot0/src/platform/bao1x/irq.rs index 2e2af1706..76f2a284e 100644 --- a/bao1x-boot/boot0/src/platform/bao1x/irq.rs +++ b/bao1x-boot/boot0/src/platform/bao1x/irq.rs @@ -1,13 +1,12 @@ -#[cfg(feature = "unsafe-dev")] use riscv::register::mstatus; use riscv::register::{mcause, mie}; -#[cfg(feature = "unsafe-dev")] use vexriscv::register::vexriscv::mim; use vexriscv::register::vexriscv::mip; use crate::*; -#[cfg(feature = "unsafe-dev")] +static ATTACKS_SINCE_BOOT: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); + pub fn irq_setup() { unsafe { #[rustfmt::skip] @@ -28,7 +27,6 @@ pub fn irq_setup() { unsafe { mie::set_mext() }; } -#[cfg(feature = "unsafe-dev")] pub fn enable_irq(irq_no: usize) { // Note that the vexriscv "IRQ Mask" register is inverse-logic -- // that is, setting a bit in the "mask" register unmasks (i.e. enables) it. @@ -195,12 +193,17 @@ pub extern "C" fn trap_handler( } else if (irqs_pending & (1 << utra::irqarray5::IRQARRAY5_IRQ)) != 0 { #[cfg(feature = "unsafe-dev")] crate::uart_irq_handler(); - } else if (irqs_pending & (1 << utra::irqarray2::IRQARRAY2_IRQ)) != 0 { - // just clear it for now - let mut irqarray2 = CSR::new(utralib::HW_IRQARRAY2_BASE as *mut u32); - let pending = irqarray2.r(utra::irqarray2::EV_PENDING); - crate::println!("keypress interrupt {:x}", pending); - irqarray2.wo(utra::irqarray2::EV_PENDING, pending); + } else if (irqs_pending & (1 << utra::irqarray13::IRQARRAY13_IRQ)) != 0 { + // irq13 -> {aoramerr, secirq, ifsuberr, sceerr, coresuberr} + // this IRQ will trigger an attack response if any of the sensors trigger *or* + // if the ECC-protected memory banks trigger an ECC error + bao1x_hal::hardening::glitch_handler( + ATTACKS_SINCE_BOOT.fetch_add(1, core::sync::atomic::Ordering::SeqCst), + ); + } else if (irqs_pending & (1 << utra::irqarray15::IRQARRAY15_IRQ)) != 0 { + // irq15 -> {meshirq, sensorcirq, glcirq} + // those one is kind of redundant with irq13 in this scenario, because secirq is the OR + // of all three IRQs going into this array. So, we handle this simply in irqarray13. } } diff --git a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs index aeb0d2c1c..998cac84c 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs @@ -148,6 +148,16 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa crate::println!("backup region is clean!"); } + irq_setup(); + // all sensors & IRQs setup already by boot0, but it doesn't hurt to re-write these registers + // in case they were defeated somehow previously + let mut irq13 = CSR::new(utra::irqarray13::HW_IRQARRAY13_BASE as *mut u32); + irq13.wo(utra::irqarray13::EV_EDGE_TRIGGERED, 0xFFFF_FFFF); + irq13.wo(utra::irqarray13::EV_POLARITY, 0xFFFF_FFFF); + irq13.wo(utra::irqarray13::EV_ENABLE, 0xFFFF_FFFF); + // enable the IRQ because it was disabled by the previous stage's exit + enable_irq(utra::irqarray13::IRQARRAY13_IRQ); + let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32); // setup board-specific I/Os - early boot set. These are items that have to be @@ -343,7 +353,6 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa // Rx setup let _udma_uart = setup_console(&board_type, &iox, perclk); - irq_setup(); enable_irq(utra::irqarray5::IRQARRAY5_IRQ); crate::debug::USE_CONSOLE.store(true, core::sync::atomic::Ordering::SeqCst); diff --git a/bao1x-boot/boot1/src/platform/bao1x/irq.rs b/bao1x-boot/boot1/src/platform/bao1x/irq.rs index 728b75b47..38092a06f 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/irq.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/irq.rs @@ -6,6 +6,8 @@ use vexriscv::register::vexriscv::{mim, mip}; use crate::usb::USB; use crate::*; +static ATTACKS_SINCE_BOOT: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); + pub fn irq_setup() { unsafe { #[rustfmt::skip] @@ -212,12 +214,17 @@ pub extern "C" fn trap_handler( timer0.wfo(utra::timer0::RELOAD_RELOAD, (DEFAULT_FCLK_FREQUENCY / 1_000) * ms); } else if (irqs_pending & (1 << utra::irqarray5::IRQARRAY5_IRQ)) != 0 { crate::uart_irq_handler(); - } else if (irqs_pending & (1 << utra::irqarray2::IRQARRAY2_IRQ)) != 0 { - // just clear it for now - let mut irqarray2 = CSR::new(utralib::HW_IRQARRAY2_BASE as *mut u32); - let pending = irqarray2.r(utra::irqarray2::EV_PENDING); - crate::println!("keypress interrupt {:x}", pending); - irqarray2.wo(utra::irqarray2::EV_PENDING, pending); + } else if (irqs_pending & (1 << utra::irqarray13::IRQARRAY13_IRQ)) != 0 { + // irq13 -> {aoramerr, secirq, ifsuberr, sceerr, coresuberr} + // this IRQ will trigger an attack response if any of the sensors trigger *or* + // if the ECC-protected memory banks trigger an ECC error + bao1x_hal::hardening::glitch_handler( + ATTACKS_SINCE_BOOT.fetch_add(1, core::sync::atomic::Ordering::SeqCst), + ); + } else if (irqs_pending & (1 << utra::irqarray15::IRQARRAY15_IRQ)) != 0 { + // irq15 -> {meshirq, sensorcirq, glcirq} + // those one is kind of redundant with irq13 in this scenario, because secirq is the OR + // of all three IRQs going into this array. So, we handle this simply in irqarray13. } if (irqs_pending & (1 << utralib::utra::irqarray1::IRQARRAY1_IRQ)) != 0 { // handle USB interrupt