From d45330e65df1c786058cc725c2bf50bc81a160d8 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 18:11:49 +0800 Subject: [PATCH 01/12] improve the bdma test this makes the output of the bdma test a bit more compact, and adds some features to help CI automation to pick out failures to help validate if fixes are durable --- baremetal/src/platform/bao1x/bio.rs | 9 ++++----- baremetal/src/repl.rs | 15 ++++++++++++--- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/baremetal/src/platform/bao1x/bio.rs b/baremetal/src/platform/bao1x/bio.rs index 9110c828c..929b28c56 100644 --- a/baremetal/src/platform/bao1x/bio.rs +++ b/baremetal/src/platform/bao1x/bio.rs @@ -6,7 +6,7 @@ use utralib::utra::bio_bdma::SFR_CONFIG_CLOCKING_MODE; use utralib::*; use xous_bio_bdma::*; -use crate::{print, println}; +use crate::println; /* pub fn bdma_test(_args: &Vec, seed: u32) -> usize { @@ -204,8 +204,7 @@ impl TestPattern { } } -pub fn bdma_coincident_test(_args: &Vec, seed: u32) -> usize { - let clkmode = 0; +pub fn bdma_coincident_test(_args: &Vec, seed: u32, clkmode: u32) -> usize { const TEST_LEN: usize = 1024; let mut passing = 0; @@ -286,10 +285,10 @@ fn coincident_u32( for (i, &d) in src.iter().enumerate() { let rbk = unsafe { dst.as_ptr().add(i).read_volatile() }; if rbk != d { - if errs < 4 { + if errs < 3 { println!("{} err @{}, {:x} rbk: {:x}", name, i, d, rbk); } else { - print!("."); + // crate::print!("."); } errs += 1; pass = 0; diff --git a/baremetal/src/repl.rs b/baremetal/src/repl.rs index 64a72a4af..f936bdf63 100644 --- a/baremetal/src/repl.rs +++ b/baremetal/src/repl.rs @@ -458,11 +458,20 @@ impl Repl { #[cfg(feature = "bao1x-bio")] "bdma" => { let mut seed = 0; + let mut clkmode: u32 = 3; + let mut passing: bool; loop { - crate::platform::bio::bdma_coincident_test(&args, seed); + crate::println!("seed {}, clkmode {}", seed, clkmode); + if crate::platform::bio::bdma_coincident_test(&args, seed, clkmode) != 4 { + clkmode = (clkmode + 1) % 4; + passing = false; + crate::println!("~~BDMAFAIL~~"); + } else { + passing = true + }; + crate::println!(" pasing: {:?}", passing); seed += 1; - crate::println!("seed {}", seed); - if seed > 32 { + if passing || seed > 8 { break; } } From 4f39532471826c40a5e7e343e1352197ff54e9d7 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 19:34:57 +0800 Subject: [PATCH 02/12] clean up filling API previous implementation was full of too many special cases also add a version that allows us to fill using a seeded CSPRNG for better performance on bulk fills --- services/bao1x-hal-service/src/trng/baosec.rs | 88 +++++++++---------- 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/services/bao1x-hal-service/src/trng/baosec.rs b/services/bao1x-hal-service/src/trng/baosec.rs index 155898a01..b076c3631 100644 --- a/services/bao1x-hal-service/src/trng/baosec.rs +++ b/services/bao1x-hal-service/src/trng/baosec.rs @@ -142,6 +142,24 @@ impl Trng { left.copy_from_slice(&chunk[..n]); } } + + /// This is a version that fills a buffer using a seeded CSPRNG. So every API call + /// only grabs a smaller amount of entropy from the TRNG pool, and generates the rest + /// from the seed. + pub fn fill_seeded_bytes(&mut self, dest: &mut [u8]) { + use rand_chacha::ChaCha8Rng; + use rand_chacha::rand_core::RngCore; + use rand_chacha::rand_core::SeedableRng; + + if dest.len() < 64 { + self.fill_bytes_via_next(dest); + return; + } + let mut seed = [0u8; 32]; + self.fill_bytes_via_next(&mut seed); + let mut cstrng = ChaCha8Rng::from_seed(seed); + cstrng.fill_bytes(dest); + } } impl RngCore for Trng { @@ -153,55 +171,35 @@ impl RngCore for Trng { fn fill_bytes(&mut self, dest: &mut [u8]) { // smaller than 64 bytes (512 bits), just use 8x next_u64 calls to fill. if dest.len() < 64 { - return self.fill_bytes_via_next(dest); + self.fill_bytes_via_next(dest); + return; } - // one page is the max size we can do with the fill_buf() API - let chunks_page = dest.chunks_exact_mut(4096); - for chunks in chunks_page.into_iter() { - let mut data: [u32; 4080 / 4] = [0; 4080 / 4]; - self.fill_buf(&mut data).expect("couldn't fill page-sized TRNG buffer"); - for (&src, dst) in data.iter().zip(chunks.chunks_exact_mut(4)) { - for (&src_byte, dst_byte) in src.to_le_bytes().iter().zip(dst.iter_mut()) { - *dst_byte = src_byte; + // use the api TrngBuf to hold the data so the compiler enforces exact data lengths + // the `len` field is actually disregarded here, we're simply using this structure to + // ensure that the `data` allocated matches the native size of the TrngBuf. + let mut api_buf = api::TrngBuf { data: [0u32; 1020], len: 1020 }; + let buf = &mut api_buf.data; + let mut filled = 0; + while filled < dest.len() { + let fetch_len = ((dest.len() - filled) / size_of::()).min(buf.len()); + self.fill_buf(&mut buf[..fetch_len]).expect("couldn't fill temp buffer"); + for &w in buf[..fetch_len].iter() { + let bytes = w.to_le_bytes(); + let remaining = dest.len() - filled; + + if remaining == 0 { + return; + } else if remaining < 4 { + // Only need a tail that is not a multiple of 4 + dest[filled..filled + remaining].copy_from_slice(&bytes[..remaining]); + return; + } else { + // Can take a full word + dest[filled..filled + 4].copy_from_slice(&bytes); + filled += 4; } } } - // a mid-sized chunk to span the gap between page and our smallest granularity - let chunks_512 = dest.chunks_exact_mut(4096).into_remainder().chunks_exact_mut(512); - for chunks in chunks_512.into_iter() { - let mut data: [u32; 512 / 4] = [0; 512 / 4]; - self.fill_buf(&mut data).expect("couldn't fill mid-sized TRNG buffer"); - for (&src, dst) in data.iter().zip(chunks.chunks_exact_mut(4)) { - for (&src_byte, dst_byte) in src.to_le_bytes().iter().zip(dst.iter_mut()) { - *dst_byte = src_byte; - } - } - } - // our smallest-sized "standard" chunk - let chunks_smallest = dest - .chunks_exact_mut(4096) - .into_remainder() - .chunks_exact_mut(512) - .into_remainder() - .chunks_exact_mut(64); - for chunks in chunks_smallest.into_iter() { - let mut data: [u32; 64 / 4] = [0; 64 / 4]; - self.fill_buf(&mut data).expect("couldn't fill small-sized TRNG buffer"); - for (&src, dst) in data.iter().zip(chunks.chunks_exact_mut(4)) { - for (&src_byte, dst_byte) in src.to_le_bytes().iter().zip(dst.iter_mut()) { - *dst_byte = src_byte; - } - } - } - // any leftover bytes - let leftovers = dest - .chunks_exact_mut(4096) - .into_remainder() - .chunks_exact_mut(512) - .into_remainder() - .chunks_exact_mut(64) - .into_remainder(); - self.fill_bytes_via_next(leftovers); } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { From 0942858bbc2f9dccbcc0946cc027e06c153dfcac Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 19:35:48 +0800 Subject: [PATCH 03/12] add test cases for trng --- services/bao-console/Cargo.toml | 1 + services/bao-console/src/cmds/trng_cmd.rs | 59 +++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/services/bao-console/Cargo.toml b/services/bao-console/Cargo.toml index a9a80b2e1..4ead1e736 100644 --- a/services/bao-console/Cargo.toml +++ b/services/bao-console/Cargo.toml @@ -28,6 +28,7 @@ bytemuck = "1.24.0" # pddb testing rand = { version = "0.8.5", features = ["getrandom"], optional = true } rand_chacha = { version = "0.3.1", optional = true } +rand_core = "0.6.4" aes = { path = "../aes", default-features = false, optional = true } diff --git a/services/bao-console/src/cmds/trng_cmd.rs b/services/bao-console/src/cmds/trng_cmd.rs index 14aa1f39e..2ab8a693d 100644 --- a/services/bao-console/src/cmds/trng_cmd.rs +++ b/services/bao-console/src/cmds/trng_cmd.rs @@ -1,4 +1,5 @@ use String; +use rand_core::RngCore; use crate::{CommonEnv, ShellCmdApi}; @@ -37,6 +38,64 @@ impl<'a> ShellCmdApi<'a> for TrngCmd { "u64" => { log::info!("A u64 trng value: {:x}", env.trng.get_u64().unwrap()); } + "buf" => { + let mut test1 = [0u8; 8192]; + let mut trng = bao1x_hal_service::trng::Trng::new(&env.xns).unwrap(); + trng.fill_bytes(&mut test1); + log::info!("8192 case"); + for chunk in test1.chunks(32) { + for word in chunk.chunks(4) { + if word == &[0, 0, 0, 0] { + log::info!("zeroes found!"); + } + } + log::info!("{:02x?}", chunk); + } + log::info!("4096 case"); + let mut test2 = [0u8; 4096]; + trng.fill_bytes(&mut test2); + for chunk in test2.chunks(32) { + for word in chunk.chunks(4) { + if word == &[0, 0, 0, 0] { + log::info!("zeroes found!"); + } + } + log::info!("{:02x?}", chunk); + } + log::info!("4597 case"); // this is a prime number so it doesn't divide into anything + let mut test3 = [0u8; 4597]; + trng.fill_bytes(&mut test3); + for chunk in test3.chunks(32) { + for word in chunk.chunks(4) { + if word == &[0, 0, 0, 0] { + log::info!("zeroes found!"); + } + } + log::info!("{:02x?}", chunk); + } + log::info!("125 case"); + let mut test4 = [0u8; 125]; + trng.fill_bytes(&mut test4); + for chunk in test4.chunks(32) { + for word in chunk.chunks(4) { + if word == &[0, 0, 0, 0] { + log::info!("zeroes found!"); + } + } + log::info!("{:02x?}", chunk); + } + log::info!("61 case"); + let mut test5 = [0u8; 61]; + trng.fill_bytes(&mut test5); + for chunk in test4.chunks(32) { + for word in chunk.chunks(4) { + if word == &[0, 0, 0, 0] { + log::info!("zeroes found!"); + } + } + log::info!("{:02x?}", chunk); + } + } _ => { write!(ret, "{}", helpstring).unwrap(); } From 69b77f30722c58780ccdf40080039eaae0f294ac Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 19:35:59 +0800 Subject: [PATCH 04/12] allow gen2 to use the seeded trng fill --- services/pddb/src/backend/trngpool.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/services/pddb/src/backend/trngpool.rs b/services/pddb/src/backend/trngpool.rs index 061883ad3..338d0caac 100644 --- a/services/pddb/src/backend/trngpool.rs +++ b/services/pddb/src/backend/trngpool.rs @@ -7,6 +7,7 @@ use aes_gcm_siv::Nonce; use bao1x_emu::trng::Trng; #[cfg(all(feature = "bao1x-hal", not(feature = "hosted-baosec")))] use bao1x_hal_service::trng::Trng; +#[cfg(not(feature = "gen2"))] use rand_core::RngCore; #[cfg(all(not(feature = "bao1x-hal"), not(feature = "hosted-baosec")))] use trng::Trng; @@ -23,14 +24,22 @@ impl TrngPool { let xns = xous_names::XousNames::new().unwrap(); let mut trng = Trng::new(&xns).unwrap(); let mut cache: [u8; 8192] = [0; 8192]; + #[cfg(not(feature = "gen2"))] trng.fill_bytes(&mut cache); + // speed up gen2 ops with seeded fill + #[cfg(feature = "gen2")] + trng.fill_seeded_bytes(&mut cache); TrngPool { trng: RefCell::new(trng), e_cache: RefCell::new(cache.to_vec()) } } pub(crate) fn ensure_entropy(&self, amount: usize) { if self.e_cache.borrow().len() < amount { let mut cache: [u8; 8192] = [0; 8192]; + #[cfg(not(feature = "gen2"))] self.trng.borrow_mut().fill_bytes(&mut cache); + // speed up gen2 ops with seeded fill + #[cfg(feature = "gen2")] + self.trng.borrow_mut().fill_seeded_bytes(&mut cache); self.e_cache.borrow_mut().extend_from_slice(&cache); } } From c98865d2e3a9a35df122ca67d98157014b22fe37 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 19:36:11 +0800 Subject: [PATCH 05/12] update dependencies --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index 6254a5737..f73a71f06 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -355,6 +355,7 @@ dependencies = [ "pddb", "rand 0.8.5", "rand_chacha 0.3.1", + "rand_core 0.6.4", "usb-bao1x", "utralib 0.1.26", "ux-api", From fdb613cfb3ea9bc7a2326092de5b825381fd2853 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 22:40:09 +0800 Subject: [PATCH 06/12] fix corner case on non-word aligned buffers --- services/bao1x-hal-service/src/trng/baosec.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/bao1x-hal-service/src/trng/baosec.rs b/services/bao1x-hal-service/src/trng/baosec.rs index b076c3631..0de21436d 100644 --- a/services/bao1x-hal-service/src/trng/baosec.rs +++ b/services/bao1x-hal-service/src/trng/baosec.rs @@ -151,10 +151,12 @@ impl Trng { use rand_chacha::rand_core::RngCore; use rand_chacha::rand_core::SeedableRng; + // for very short runs, fill directly from the HW TRNG if dest.len() < 64 { self.fill_bytes_via_next(dest); return; } + // larger runs, seed a ChaCha8 and use its results to fill the buffer let mut seed = [0u8; 32]; self.fill_bytes_via_next(&mut seed); let mut cstrng = ChaCha8Rng::from_seed(seed); @@ -181,7 +183,8 @@ impl RngCore for Trng { let buf = &mut api_buf.data; let mut filled = 0; while filled < dest.len() { - let fetch_len = ((dest.len() - filled) / size_of::()).min(buf.len()); + let fetch_len = ((((dest.len() + 3) & !3) - filled) / size_of::()).min(buf.len()); + log::debug!("fetching {} bytes; filled {} so far", fetch_len * 4, filled); self.fill_buf(&mut buf[..fetch_len]).expect("couldn't fill temp buffer"); for &w in buf[..fetch_len].iter() { let bytes = w.to_le_bytes(); From 072330608532955ef8a8dbe9cd36ec5a2904869b Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 22:40:36 +0800 Subject: [PATCH 07/12] update docstring --- services/bao-console/src/cmds/trng_cmd.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/bao-console/src/cmds/trng_cmd.rs b/services/bao-console/src/cmds/trng_cmd.rs index 2ab8a693d..abf028ad6 100644 --- a/services/bao-console/src/cmds/trng_cmd.rs +++ b/services/bao-console/src/cmds/trng_cmd.rs @@ -15,7 +15,7 @@ impl<'a> ShellCmdApi<'a> for TrngCmd { fn process(&mut self, args: String, env: &mut CommonEnv) -> Result, xous::Error> { use core::fmt::Write; let mut ret = String::new(); - let helpstring = "trng [pump] [u32] [u64]"; + let helpstring = "trng [pump] [u32] [u64] [buf]"; let mut tokens = args.split(' '); From ad116b5af6770d31cb037a9f5e392832ab0f4259 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 22:46:20 +0800 Subject: [PATCH 08/12] reduce leakage during hazardous-debug in theory, no production images should be signed that have this feature enabled. But, reducing the amount of leakage just in case an accident happens and this flag is somehow slipped into a signed production image. --- services/keystore/src/platform/baosec/store.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/services/keystore/src/platform/baosec/store.rs b/services/keystore/src/platform/baosec/store.rs index ded278604..bd9536ea3 100644 --- a/services/keystore/src/platform/baosec/store.rs +++ b/services/keystore/src/platform/baosec/store.rs @@ -173,7 +173,9 @@ impl KeyStore { } #[cfg(feature = "hazardous-debug")] - log::info!("chaff: {:x?}", chaff_xor); + // leak only part of the chaff, see below comment about hedging against accidental signing of a debug + // image + log::info!("chaff: {:x?}", chaff_xor[..8]); ikm.extend_from_slice(&chaff_xor); assert!(ikm.len() == (nk_len + 1 + 1) * KEY_LEN); // sanity check that all keys were in fact added @@ -201,8 +203,14 @@ impl KeyStore { } #[cfg(feature = "hazardous-debug")] - for (i, chunk) in ikm.chunks(256).enumerate() { - log::info!("ikm({:4}): {:x?}", i, chunk); + for (i, chunk) in ikm.chunks(32).enumerate() { + // subsample the keyspace - we're using hazardous-debug in CI to confirm correctness + // of keys, which creates some risk that these images are abused in production (e.g. if + // one is accidentally signed where this is on). Subsampling the keys reduces the risk + // in case such an image gets out. + if i % 8 == 0 { + log::info!("ikm({:4}): {:x?}", i * 32, chunk); + } } log::debug!("salt: {:x?}", salt); // not hazardous, these are public values let hk = Hkdf::::new(Some(&salt[..]), &ikm); From 145c2e37b2e9a21f6652ae63ac6c82f758f4d008 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 23:19:28 +0800 Subject: [PATCH 09/12] raise visibility of the erase value --- libs/bao1x-hal/src/sigcheck.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/libs/bao1x-hal/src/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index 73cef9444..11921ce40 100644 --- a/libs/bao1x-hal/src/sigcheck.rs +++ b/libs/bao1x-hal/src/sigcheck.rs @@ -14,6 +14,11 @@ use crate::acram::OneWayCounter; use crate::acram::{AccessSettings, SlotManager}; use crate::udma::Spim; +// An erase value of 0 can be conflated with access permissions being incorrect. Choose a non-0 value +// for the erase value, but also, don't pick a 0-1-0-1 dense pattern because that can assist with +// calibrating microscopy techniques. +pub const ERASE_VALUE: u8 = 0x03; + /// Current draw @ 200MHz CPU ACLK (400MHz FCLK), VDD85 = 0.80V nom (measured @0.797V): ~71mA peak @ 27C, /// measured on VDD33 (LDO path places strict upper bounds on IDD85). Target: < 100mA under all PVT. /// @@ -208,11 +213,6 @@ pub fn erase_secrets() { #[cfg(not(feature = "std"))] pub fn erase_secrets() { - // An erase value of 0 is conflateable with access permissions being incorrect. Choose a non-0 value - // for the erase value, but also, don't pick a 0-1-0-1 dense pattern because that can assist with - // calibrating microscopy techniques. - const ERASE_VALUE: u8 = 0x03; - // ensure coreuser settings, as we could enter from a variety of loader stages let mut cu = crate::coreuser::Coreuser::new(); cu.set(); From 22f44f82b967165c37410f72d822db1b06a88d37 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 23:20:31 +0800 Subject: [PATCH 10/12] add debug telemetry to the keystore this is constructed in a way such that 1. it's gated off in production builds 2. if it was accidentally gated on, there is some security impact but not a significant loss of security We do need the telemetry so that during CI we can confirm that things are actually working. I think the risk of being too buttoned-up and then accidentally doing something like accidentally never initializing keys and leaving them all zero is greater than the risk of accidental partial leakage of information due to a procedural mix-up in the image signing ceremony. --- .../keystore/src/platform/baosec/store.rs | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/services/keystore/src/platform/baosec/store.rs b/services/keystore/src/platform/baosec/store.rs index bd9536ea3..8d57ebf77 100644 --- a/services/keystore/src/platform/baosec/store.rs +++ b/services/keystore/src/platform/baosec/store.rs @@ -3,6 +3,7 @@ use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArr use bao1x_api::{ BOOT0_PUBKEY_FAIL, BoardTypeCoding, CP_ID, DEVELOPER_MODE, OEM_MODE, SLOT_ELEMENT_LEN_BYTES, UUID, }; +use bao1x_hal::board::{BOOKEND_END, BOOKEND_START}; use bao1x_hal::{ acram::{OneWayCounter, SlotManager}, board::{CHAFF_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, ROOT_SEED}, @@ -102,6 +103,23 @@ impl KeyStore { // read key material ikm.extend_from_slice(self.slot_mgr.read(&ROOT_SEED).unwrap()); + #[cfg(feature = "hazardous-debug")] + { + // analyze part of the key and print some informative statements during hazardous-debug + // we want to make sure that keys are actually being initialized, erased, or denied + // look at only 64 bits out of the 256 bit key - it's enough that it's highly unlikely that + // these 64 bits would match any of the zero/erased values, but not so much that if a + // dev image is accidentally signed & released that it'd be a serious threat to security + // as you'd still have 192 bits of secret material + let root_seed = self.slot_mgr.read(&ROOT_SEED).unwrap(); + if root_seed[..8] == [0u8; 8] { + log::info!("{}KEYSTORE.ZERO,{}", BOOKEND_START, BOOKEND_END); + } else if root_seed[..8] == [bao1x_hal::sigcheck::ERASE_VALUE; 8] { + log::info!("{}KEYSTORE.ERASED,{}", BOOKEND_START, BOOKEND_END); + } else { + log::info!("{}KEYSTORE.KEYPASS,{}", BOOKEND_START, BOOKEND_END); + } + } // build nuisance key offsets - this is direct readout hardening let nk0 = NUISANCE_KEYS_0.try_into_data_iter().unwrap(); @@ -175,7 +193,7 @@ impl KeyStore { #[cfg(feature = "hazardous-debug")] // leak only part of the chaff, see below comment about hedging against accidental signing of a debug // image - log::info!("chaff: {:x?}", chaff_xor[..8]); + log::info!("chaff: {:x?}", &chaff_xor[..8]); ikm.extend_from_slice(&chaff_xor); assert!(ikm.len() == (nk_len + 1 + 1) * KEY_LEN); // sanity check that all keys were in fact added @@ -220,11 +238,14 @@ impl KeyStore { // do something with ct_xor that guarantees it's never optimized out if ct_xor.iter().all(|&cx| cx == 0) { log::warn!("Chaff result is all-0. Confirming that we're in developer mode"); + log::info!("{}KEYSTORE.ZEROCHAFF,{}", BOOKEND_START, BOOKEND_END); // panic if we're not in developer mode assert!( 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" ); + } else { + log::info!("{}KEYSTORE.OKCHAFF,{}", BOOKEND_START, BOOKEND_END); } self.master_key = Some(master_key); } From a208d59690c49f33983b15bed3840d405c39a614 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 23:33:33 +0800 Subject: [PATCH 11/12] deny boot to any developer-key signed kernel/detached-app/swap images Secret keys can't be erased after boot1 exits because the protection bits are hardened from modification after that point. thus it is not possible for the loader to switch the device into developer mode. Thus the only way to enter developer mode is through a dev-mode signed loader. A system that has never been put into developer mode will refuse to run any developer-mode xous kernel, app, swap images. Once a system has been exposed to a dev-mode signed loader, the boot1 will flip the developer mode bit and erase the secret keys. Later on, if a production loader is replaced, it doesn't matter that a production loader is loading dev-mode signed successors because the secret keys are already erased. Note that in all cases, the key revocations take precedence so if the developer key is revoked, these cases should never even be encountered. --- loader/src/main.rs | 28 ++++++++++++++++++++++++---- loader/src/platform/bao1x/swap.rs | 16 ++++++++++++++-- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/loader/src/main.rs b/loader/src/main.rs index 8931ee4af..b0f2d33aa 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -281,8 +281,17 @@ 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 secrets are erased"); - bao1x_hal::sigcheck::erase_secrets(); + // 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. + let owc = bao1x_hal::acram::OneWayCounter::new(); + if owc.get(bao1x_api::DEVELOPER_MODE).unwrap() == 0 { + crate::println!( + "Kernel is devkey signed, but system is not in developer mode. Dying!" + ); + bao1x_hal::sigcheck::die_no_std(); + } else { + crate::println!("Developer key detected on kernel. Proceeding in developer mode!"); + } } } Err(e) => { @@ -315,8 +324,19 @@ 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 secrets are erased"); - bao1x_hal::sigcheck::erase_secrets(); + // 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. + let owc = bao1x_hal::acram::OneWayCounter::new(); + if owc.get(bao1x_api::DEVELOPER_MODE).unwrap() == 0 { + crate::println!( + "Detached app is devkey signed, but system is not in developer mode. Dying!" + ); + bao1x_hal::sigcheck::die_no_std(); + } else { + crate::println!( + "Developer key detected on detached app. Proceeding in developer mode!" + ); + } } true } diff --git a/loader/src/platform/bao1x/swap.rs b/loader/src/platform/bao1x/swap.rs index 6c5d261c3..4b0785b00 100644 --- a/loader/src/platform/bao1x/swap.rs +++ b/loader/src/platform/bao1x/swap.rs @@ -256,8 +256,20 @@ impl SwapHal { [bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT { - crate::println!("Developer key detected, ensuring secrets are erased"); - bao1x_hal::sigcheck::erase_secrets(); + // 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. + let owc = bao1x_hal::acram::OneWayCounter::new(); + if owc.get(bao1x_api::DEVELOPER_MODE).unwrap() == 0 { + crate::println!( + "Swap is devkey signed, but system is not in developer mode. Dying!" + ); + bao1x_hal::sigcheck::die_no_std(); + } else { + crate::println!( + "Developer key detected on swap. Proceeding in developer mode!" + ); + } } } Err(e) => { From 90362b260435d3261715abc8033443872a29733d Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 18 Nov 2025 23:59:17 +0800 Subject: [PATCH 12/12] fix hosted mode --- services/bao-console/src/cmds/trng_cmd.rs | 2 ++ services/bao1x-emu/Cargo.toml | 6 ++---- services/bao1x-emu/src/trng.rs | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/services/bao-console/src/cmds/trng_cmd.rs b/services/bao-console/src/cmds/trng_cmd.rs index abf028ad6..0aca2faa9 100644 --- a/services/bao-console/src/cmds/trng_cmd.rs +++ b/services/bao-console/src/cmds/trng_cmd.rs @@ -1,4 +1,5 @@ use String; +#[cfg(not(feature = "hosted-baosec"))] use rand_core::RngCore; use crate::{CommonEnv, ShellCmdApi}; @@ -38,6 +39,7 @@ impl<'a> ShellCmdApi<'a> for TrngCmd { "u64" => { log::info!("A u64 trng value: {:x}", env.trng.get_u64().unwrap()); } + #[cfg(not(feature = "hosted-baosec"))] "buf" => { let mut test1 = [0u8; 8192]; let mut trng = bao1x_hal_service::trng::Trng::new(&env.xns).unwrap(); diff --git a/services/bao1x-emu/Cargo.toml b/services/bao1x-emu/Cargo.toml index fc30dd5d8..34f36b6ea 100644 --- a/services/bao1x-emu/Cargo.toml +++ b/services/bao1x-emu/Cargo.toml @@ -10,6 +10,7 @@ xous-names = { package = "xous-api-names", version = "0.9.68" } "ux-api" = { path = "../../libs/ux-api" } "rand" = "0.8" rand_core = "0.6.4" +rand_chacha = "0.3.1" log = "0.4.14" log-server = { package = "xous-api-log", version = "0.1.66" } num-derive = { version = "0.4.2", default-features = false } @@ -18,10 +19,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [ "std", "alloc", ] } -bao1x-api = { path = "../../libs/bao1x-api", features = [ - "derive-rkyv", - "std", -] } +bao1x-api = { path = "../../libs/bao1x-api", features = ["derive-rkyv", "std"] } [target.'cfg(any(windows,unix))'.dependencies] minifb = "0.26.0" diff --git a/services/bao1x-emu/src/trng.rs b/services/bao1x-emu/src/trng.rs index eee4acc9a..b696ae499 100644 --- a/services/bao1x-emu/src/trng.rs +++ b/services/bao1x-emu/src/trng.rs @@ -34,6 +34,23 @@ impl Trng { left.copy_from_slice(&chunk[..n]); } } + + pub fn fill_seeded_bytes(&mut self, dest: &mut [u8]) { + use rand_chacha::ChaCha8Rng; + use rand_chacha::rand_core::RngCore; + use rand_chacha::rand_core::SeedableRng; + + // for very short runs, fill directly from the HW TRNG + if dest.len() < 64 { + self.fill_bytes_via_next(dest); + return; + } + // larger runs, seed a ChaCha8 and use its results to fill the buffer + let mut seed = [0u8; 32]; + self.fill_bytes_via_next(&mut seed); + let mut cstrng = ChaCha8Rng::from_seed(seed); + cstrng.fill_bytes(dest); + } } impl RngCore for Trng {