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", 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; } } 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(); 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) => { 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..0aca2faa9 100644 --- a/services/bao-console/src/cmds/trng_cmd.rs +++ b/services/bao-console/src/cmds/trng_cmd.rs @@ -1,4 +1,6 @@ use String; +#[cfg(not(feature = "hosted-baosec"))] +use rand_core::RngCore; use crate::{CommonEnv, ShellCmdApi}; @@ -14,7 +16,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(' '); @@ -37,6 +39,65 @@ 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(); + 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(); } 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 { diff --git a/services/bao1x-hal-service/src/trng/baosec.rs b/services/bao1x-hal-service/src/trng/baosec.rs index 155898a01..0de21436d 100644 --- a/services/bao1x-hal-service/src/trng/baosec.rs +++ b/services/bao1x-hal-service/src/trng/baosec.rs @@ -142,6 +142,26 @@ 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; + + // 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 { @@ -153,55 +173,36 @@ 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() + 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(); + 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> { diff --git a/services/keystore/src/platform/baosec/store.rs b/services/keystore/src/platform/baosec/store.rs index ded278604..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(); @@ -173,7 +191,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 +221,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); @@ -212,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); } 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); } }