From 5f137aac96421047ca227b14445dfc4190fa9fae Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 28 Oct 2025 17:55:06 +0800 Subject: [PATCH] add TRNG service for baosec target dabao has no external TRNG, and so it can "cheat" and use the server ID api call from the kernel to get random numbers (the server ID is just TRNG output from the kernel's TRNG). baosec has an external TRNG, and it needs a userspace server to blend both kernel TRNG output and this external TRNG. the TRNG requires the BIO block to aggregate the random data. This commit adds that implementation. --- services/bao1x-hal-service/Cargo.toml | 10 + services/bao1x-hal-service/src/hw.rs | 1 - services/bao1x-hal-service/src/main.rs | 13 +- services/bao1x-hal-service/src/servers.rs | 7 + .../src/servers/baosec_hw.rs | 202 +++++++++++ .../src/{hw => servers}/keyboard.rs | 0 .../bao1x-hal-service/src/servers/trng.rs | 125 +++++++ services/bao1x-hal-service/src/trng/baosec.rs | 313 ++++++++++++++++++ .../src/{trng.rs => trng/dabao.rs} | 4 + services/bao1x-hal-service/src/trng/mod.rs | 8 + 10 files changed, 680 insertions(+), 3 deletions(-) delete mode 100644 services/bao1x-hal-service/src/hw.rs create mode 100644 services/bao1x-hal-service/src/servers.rs create mode 100644 services/bao1x-hal-service/src/servers/baosec_hw.rs rename services/bao1x-hal-service/src/{hw => servers}/keyboard.rs (100%) create mode 100644 services/bao1x-hal-service/src/servers/trng.rs create mode 100644 services/bao1x-hal-service/src/trng/baosec.rs rename services/bao1x-hal-service/src/{trng.rs => trng/dabao.rs} (96%) create mode 100644 services/bao1x-hal-service/src/trng/mod.rs diff --git a/services/bao1x-hal-service/Cargo.toml b/services/bao1x-hal-service/Cargo.toml index d9b8ea461..eb998e240 100644 --- a/services/bao1x-hal-service/Cargo.toml +++ b/services/bao1x-hal-service/Cargo.toml @@ -18,6 +18,16 @@ log = "0.4.14" bao1x-hal = { path = "../../libs/bao1x-hal", default-features = false } bao1x-api = { path = "../../libs/bao1x-api", features = ["derive-rkyv", "std"] } # xous-pl230 = { path = "../../libs/xous-pl230", features = ["bao1x"] } +xous-bio-bdma = { path = "../../libs/xous-bio-bdma", default-features = false, features = [ + "bao1x", + "bio-mul", + "std", +] } +# I'm not entirely in love with the aborted attempt to use flatipc in Xous, but we use +# this because it makes the API backward-compatible with older Xous code. +flatipc = { path = "../../libs/flatipc" } +flatipc-derive = { path = "../../libs/flatipc-derive" } +rand = "0.8.5" rand_core = "0.6.4" rand_chacha = "0.3.1" bitfield = "0.13.2" diff --git a/services/bao1x-hal-service/src/hw.rs b/services/bao1x-hal-service/src/hw.rs deleted file mode 100644 index 45f5b56d0..000000000 --- a/services/bao1x-hal-service/src/hw.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod keyboard; diff --git a/services/bao1x-hal-service/src/main.rs b/services/bao1x-hal-service/src/main.rs index 974d4e989..9bb0dcb7d 100644 --- a/services/bao1x-hal-service/src/main.rs +++ b/services/bao1x-hal-service/src/main.rs @@ -1,5 +1,7 @@ mod api; -mod hw; +mod servers; +#[cfg(feature = "board-baosec")] +use std::sync::{Arc, Mutex}; use bao1x_api::*; use bao1x_hal::{iox::Iox, udma::GlobalConfig}; @@ -255,7 +257,14 @@ fn main() { let mut irq_table: [Option; 8] = [None; 8]; // start keyboard emulator service - hw::keyboard::start_keyboard_service(); + servers::keyboard::start_keyboard_service(); + + // claim BIO + #[cfg(feature = "board-baosec")] + let bio_ss = Arc::new(Mutex::new(xous_bio_bdma::BioSharedState::new())); + // setup TRNG server - baosec only because it has an external AV generator + #[cfg(feature = "board-baosec")] + servers::trng::start_trng_service(&bio_ss); let mut msg_opt = None; log::debug!("Starting main loop"); diff --git a/services/bao1x-hal-service/src/servers.rs b/services/bao1x-hal-service/src/servers.rs new file mode 100644 index 000000000..4073913d9 --- /dev/null +++ b/services/bao1x-hal-service/src/servers.rs @@ -0,0 +1,7 @@ +pub mod keyboard; + +// TRNG server is only needed for baosec; dabao can cheat and use the kernel TRNG port +#[cfg(feature = "board-baosec")] +mod baosec_hw; +#[cfg(feature = "board-baosec")] +pub mod trng; // not public - for internal use only diff --git a/services/bao1x-hal-service/src/servers/baosec_hw.rs b/services/bao1x-hal-service/src/servers/baosec_hw.rs new file mode 100644 index 000000000..6420b4200 --- /dev/null +++ b/services/bao1x-hal-service/src/servers/baosec_hw.rs @@ -0,0 +1,202 @@ +use core::sync::atomic::{AtomicU32, Ordering}; +use std::cell::RefCell; +use std::sync::{Arc, Mutex}; + +use bao1x_hal_service::trng::api; +use rand_chacha::ChaCha8Rng; +// the 0.5.1 API is necessary for compatibility with curve25519-dalek crates +use rand_core::{CryptoRng, RngCore, SeedableRng}; +use utralib::*; +use xous_bio_bdma::*; +const RESEED_INTERVAL: u32 = 128; +static RESEED: AtomicU32 = AtomicU32::new(0); +const BITS_PER_SAMPLE: usize = 4; + +pub struct HwTrng { + csprng: RefCell, + bio_ss: Arc>, +} +impl HwTrng { + pub fn new(bio_ss_guarded: Arc>) -> Self { + let mut seed = [0u8; 32]; + { + let mut bio_ss = bio_ss_guarded.lock().unwrap(); + + let tt = ticktimer::Ticktimer::new().unwrap(); + + let iox = crate::iox::IoxHal::new(); + let trng_pin = bao1x_hal::board::setup_trng_input_pin(&iox); + let trng_power = bao1x_hal::board::setup_trng_power_pin(&iox); + iox.set_gpio_pin_value(trng_power.0, trng_power.1, bao1x_api::IoxValue::High); + tt.sleep_ms(50).ok(); // wait for power to stabilize on the avalanche generator + + // avalanche generator TRNG - maybe replace this with a proper API call once this has + // been baked into something a little friendlier/easier to maintain? + // stop all the machines, so that code can be loaded + bio_ss.bio.wo(utra::bio_bdma::SFR_CTRL, 0x0); + bio_ss.load_code(avtrng_bio_code(), 0, BioCore::Core0); + + // don't use QDIV + bio_ss.bio.wo(utra::bio_bdma::SFR_QDIV0, 0x1_0000); + + // use extclock on channel 0, tied to the trng pin + bio_ss.bio.wo( + utra::bio_bdma::SFR_EXTCLOCK, + bio_ss.bio.ms(utra::bio_bdma::SFR_EXTCLOCK_USE_EXTCLK, 0b0001) + | bio_ss.bio.ms(utra::bio_bdma::SFR_EXTCLOCK_EXTCLK_GPIO_0, trng_pin as u32), + ); + + // start the machine + bio_ss.set_core_run_states([true, false, false, true]); + bio_ss.bio.wo(utra::bio_bdma::SFR_TXF0, trng_pin as u32); // start the sampling + + // server_id is a random number from the hardware entropy pool. Note that this + // has already been conditioned and whitened, so we can use it directly. + let seed_l = xous::create_server_id().unwrap().to_array(); + let seed_h = xous::create_server_id().unwrap().to_array(); + for chunk in seed[..16].chunks_mut(4) { + for s in seed_l { + chunk.copy_from_slice(&s.to_le_bytes()) + } + } + for chunk in seed[16..].chunks_mut(4) { + for s in seed_h { + chunk.copy_from_slice(&s.to_le_bytes()) + } + } + + // add AV TRNG data + let mut raw32 = 0; + for s in seed.chunks_mut(4) { + for _ in 0..(size_of::() * 8) / BITS_PER_SAMPLE { + // wait for the next interval to arrive + while bio_ss.bio.rf(utra::bio_bdma::SFR_FLEVEL_PCLK_REGFIFO_LEVEL0) == 0 {} + let raw = bio_ss.bio.r(utra::bio_bdma::SFR_RXF0); + raw32 <<= BITS_PER_SAMPLE; + // shift right by one because bit 0 always samples as 0, due to instruction timing + raw32 |= (raw >> 1) & ((1 << BITS_PER_SAMPLE) - 1) + } + for (s_byte, &av_byte) in s.iter_mut().zip(raw32.to_le_bytes().iter()) { + *s_byte ^= av_byte; + } + } + } + HwTrng { csprng: RefCell::new(ChaCha8Rng::from_seed(seed)), bio_ss: bio_ss_guarded } + } + + fn reseed(&self) { + let reseed_ctr = match RESEED.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)) { + Ok(x) => x, + Err(x) => x, + }; + if reseed_ctr > RESEED_INTERVAL { + log::debug!("reseeding CSPRNG from hardware TRNG sources"); + RESEED.store(0, Ordering::SeqCst); + // incorporate randomness from the TRNG + let mut seed = self.csprng.borrow_mut().get_seed(); + // server_id is a random number from the hardware entropy pool + let seed_l = xous::create_server_id().unwrap().to_array(); + let seed_h = xous::create_server_id().unwrap().to_array(); + for (sd, pool) in seed[..16].chunks_mut(4).into_iter().zip(seed_l.iter().map(|s| s.to_le_bytes())) + { + for (sd_byte, &pool_byte) in sd.iter_mut().zip(pool.iter()) { + *sd_byte ^= pool_byte; + } + } + for (sd, pool) in seed[16..].chunks_mut(4).into_iter().zip(seed_h.iter().map(|s| s.to_le_bytes())) + { + for (sd_byte, &pool_byte) in sd.iter_mut().zip(pool.iter()) { + *sd_byte ^= pool_byte; + } + } + // add AV TRNG data + let mut raw32 = 0; + let bio_ss = self.bio_ss.lock().unwrap(); + for s in seed.chunks_mut(4) { + for _ in 0..(size_of::() * 8) / BITS_PER_SAMPLE { + // wait for the next interval to arrive + while bio_ss.bio.rf(utra::bio_bdma::SFR_FLEVEL_PCLK_REGFIFO_LEVEL0) == 0 {} + let raw = bio_ss.bio.r(utra::bio_bdma::SFR_RXF0); + raw32 <<= BITS_PER_SAMPLE; + // shift right by one because bit 0 always samples as 0, due to instruction timing + raw32 |= (raw >> 1) & ((1 << BITS_PER_SAMPLE) - 1) + } + for (s_byte, &av_byte) in s.iter_mut().zip(raw32.to_ne_bytes().iter()) { + *s_byte ^= av_byte; + } + } + self.csprng.replace(rand_chacha::ChaCha8Rng::from_seed(seed)); + } + } + + pub fn get_u32(&self) -> Result { + self.reseed(); + Ok(self.csprng.borrow_mut().next_u32()) + } + + pub fn get_u64(&self) -> Result { + self.reseed(); + Ok(self.csprng.borrow_mut().next_u64()) + } + + pub fn fill_buf(&self, data: &mut [u32]) -> Result<(), xous::Error> { + for d in data.iter_mut() { + *d = self.get_u32()?; + } + Ok(()) + } + + /// This is copied out of the 0.5 API for rand_core + pub fn fill_bytes_via_next(&mut self, dest: &mut [u8]) { + let mut left = dest; + while left.len() >= 8 { + let (l, r) = { left }.split_at_mut(8); + left = r; + let chunk: [u8; 8] = self.next_u64().to_ne_bytes(); + l.copy_from_slice(&chunk); + } + let n = left.len(); + if n > 4 { + let chunk: [u8; 8] = self.next_u64().to_ne_bytes(); + left.copy_from_slice(&chunk[..n]); + } else if n > 0 { + let chunk: [u8; 4] = self.next_u32().to_ne_bytes(); + left.copy_from_slice(&chunk[..n]); + } + } + + pub fn get_tests(&self) -> api::HealthTests { + todo!(); + } + + pub fn get_errors(&self) -> api::TrngErrors { + todo!(); + } +} + +impl RngCore for HwTrng { + fn next_u32(&mut self) -> u32 { self.get_u32().expect("couldn't get random u32 from server") } + + fn next_u64(&mut self) -> u64 { self.get_u64().expect("couldn't get random u64 from server") } + + fn fill_bytes(&mut self, dest: &mut [u8]) { self.fill_bytes_via_next(dest); } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { + Ok(self.fill_bytes(dest)) + } +} + +impl CryptoRng for HwTrng {} + +#[rustfmt::skip] +bio_code!(avtrng_bio_code, BM_AVTRNG_BIO_START, BM_AVTRNG_BIO_END, + "mv x1, x16", // get pin for trng input + "li x2, 1", + "sll x1, x2, x1", // shift the pin into a bitmask + "mv x25, x1", // make it an input +"10:", + "mv x20, x0", // wait for quantum: this time, the toggle from the TRNG + "mv x1, x31", // remember aclk time + "mv x16, x1", // save result to FIFO + "j 10b" // and do it again +); diff --git a/services/bao1x-hal-service/src/hw/keyboard.rs b/services/bao1x-hal-service/src/servers/keyboard.rs similarity index 100% rename from services/bao1x-hal-service/src/hw/keyboard.rs rename to services/bao1x-hal-service/src/servers/keyboard.rs diff --git a/services/bao1x-hal-service/src/servers/trng.rs b/services/bao1x-hal-service/src/servers/trng.rs new file mode 100644 index 000000000..e1fcbcfdc --- /dev/null +++ b/services/bao1x-hal-service/src/servers/trng.rs @@ -0,0 +1,125 @@ +use std::sync::{Arc, Mutex}; + +use bao1x_hal_service::trng::api; +use flatipc::Ipc; +use num_traits::*; +use rand::RngCore; +use xous::CID; +use xous_bio_bdma::BioSharedState; +use xous_ipc::Buffer; + +use crate::servers::baosec_hw::HwTrng; + +#[derive(Copy, Clone, Debug)] +struct ScalarCallback { + server_to_cb_cid: CID, + cb_to_client_cid: CID, + cb_to_client_id: u32, +} + +pub fn start_trng_service(bio_ss: &Arc>) { + std::thread::spawn({ + let bio_ss = bio_ss.clone(); + move || { + trng_service(bio_ss); + } + }); +} + +fn trng_service(bio_ss: Arc>) -> ! { + let xns = xous_names::XousNames::new().unwrap(); + // unlimited connections allowed, anyone including less-trusted processes can get a random number + let trng_sid = xns.register_name(api::SERVER_NAME_TRNG, None).expect("can't register server"); + + let mut trng = Box::new(HwTrng::new(bio_ss)); + + let mut error_cb_conns = Vec::::new(); + + loop { + let mut msg = xous::receive_message(trng_sid).unwrap(); + let op: Option = FromPrimitive::from_usize(msg.body.id()); + log::debug!("{:?}", op); + match op { + Some(api::Opcode::GetTrng) => xous::msg_blocking_scalar_unpack!(msg, count, _, _, _, { + if count == 1 { + xous::return_scalar2(msg.sender, trng.next_u32() as usize, 0xdead_beef) + .expect("couldn't return GetTrng request"); + } else { + xous::return_scalar2(msg.sender, trng.next_u32() as usize, trng.next_u32() as usize) + .expect("couldn't return GetTrng request"); + } + }), + Some(api::Opcode::ErrorSubscribe) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let hookdata = buffer.to_original::().unwrap(); + do_hook(hookdata, &mut error_cb_conns); + } + Some(api::Opcode::ErrorNotification) => { + log::error!("Got a notification interrupt from the TRNG. Syndrome: {:?}", trng.get_errors()); + log::error!("Stats: {:?}", trng.get_tests()); + send_event(&error_cb_conns); + } + Some(api::Opcode::HealthStats) => { + let mut buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + buffer.replace(trng.get_tests()).unwrap(); + } + Some(api::Opcode::ErrorStats) => { + let mut buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + buffer.replace(trng.get_errors()).unwrap(); + } + Some(api::Opcode::FillTrng) => { + let mm = msg.body.memory_message_mut().unwrap(); + let buffer = + api::IpcTrngBuf::from_memory_message_mut(mm).expect("couldn't unpack FillTrng buffer"); + let len = buffer.len as usize; + trng.fill_buf(&mut buffer.data[..len]).expect("couldn't fill TRNG buffer"); + } + None => { + log::error!("couldn't convert opcode, ignoring"); + } + } + } +} + +fn do_hook(hookdata: api::ScalarHook, cb_conns: &mut Vec) { + let (s0, s1, s2, s3) = hookdata.sid; + let sid = xous::SID::from_u32(s0, s1, s2, s3); + let server_to_cb_cid = xous::connect(sid).unwrap(); + let cb_dat = + ScalarCallback { server_to_cb_cid, cb_to_client_cid: hookdata.cid, cb_to_client_id: hookdata.id }; + cb_conns.push(cb_dat); +} +#[allow(dead_code)] +/// called if the server exits, which we don't. Keep around for reference in case for some reason we need to +/// do that... +fn unhook(cb_conns: &mut Vec) { + for scb in cb_conns.drain(..) { + xous::send_message( + scb.server_to_cb_cid, + xous::Message::new_blocking_scalar(api::EventCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0), + ) + .unwrap(); + unsafe { + xous::disconnect(scb.server_to_cb_cid).unwrap(); + } + } +} +fn send_event(cb_conns: &Vec) { + for scb in cb_conns.iter() { + // note that the "which" argument is only used for GPIO events, to indicate which pin had the + // event + xous::send_message( + scb.server_to_cb_cid, + xous::Message::new_scalar( + api::EventCallback::Event.to_usize().unwrap(), + scb.cb_to_client_cid as usize, + scb.cb_to_client_id as usize, + 0, + 0, + ), + ) + .unwrap(); + } +} diff --git a/services/bao1x-hal-service/src/trng/baosec.rs b/services/bao1x-hal-service/src/trng/baosec.rs new file mode 100644 index 000000000..b19e51adc --- /dev/null +++ b/services/bao1x-hal-service/src/trng/baosec.rs @@ -0,0 +1,313 @@ +//! Baosec's TRNG implementation blends entropy from an external TRNG generator +//! (nominally an avalanche TRNG) to supplement the on-chip ring oscillator TRNG. +//! This belt-and-suspenders approach ensures high quality entropy even if one +//! of the entropy sources experiences some sort of unforeseen wear-out mechanism, +//! or in particular if the RO TRNG has some sort of process-based bias drift +//! over lot-to-lot variation that causes the output quality to degrade in a way +//! that is hard to measure/characterize on every unit produced, or if there is +//! some sort of phase locking mechanism that is subtle and hard to see with just +//! Dieharder runs but maybe a more advanced analytical technique can find it. +//! +//! Using the Avalanche TRNG requires access to the BIO, and thus a slower +//! (compared to Dabao's kernel-direct path), server-based mechanism for +//! generating random numbers is needed. + +use flatipc::{IntoIpc, Ipc}; +use num_traits::*; +// the 0.5.1 API is necessary for compatibility with curve25519-dalek crates +use rand_core::{CryptoRng, RngCore}; +use xous::{CID, send_message}; +use xous_ipc::Buffer; + +pub struct Trng { + conn: CID, + error_sid: Option, +} +impl Trng { + pub fn new(xns: &xous_names::XousNames) -> Result { + REFCOUNT.fetch_add(1, Ordering::Relaxed); + let conn = + xns.request_connection_blocking(api::SERVER_NAME_TRNG).expect("Can't connect to TRNG server"); + Ok(Trng { conn, error_sid: None }) + } + + pub fn get_u32(&self) -> Result { + let response = send_message( + self.conn, + xous::Message::new_blocking_scalar( + api::Opcode::GetTrng.to_usize().unwrap(), + 1, /* count */ + 0, + 0, + 0, + ), + ) + .expect("TRNG|LIB: can't get_u32"); + if let xous::Result::Scalar2(trng, _) = response { + Ok(trng as u32) + } else { + panic!("unexpected return value: {:#?}", response); + } + } + + pub fn get_u64(&self) -> Result { + let response = send_message( + self.conn, + xous::Message::new_blocking_scalar( + api::Opcode::GetTrng.to_usize().unwrap(), + 2, /* count */ + 0, + 0, + 0, + ), + ) + .expect("TRNG|LIB: can't get_u32"); + if let xous::Result::Scalar2(lo, hi) = response { + Ok(lo as u64 | ((hi as u64) << 32)) + } else { + panic!("unexpected return value: {:#?}", response); + } + } + + pub fn fill_buf(&self, data: &mut [u32]) -> Result<(), xous::Error> { + let mut tb = api::TrngBuf { data: [0; 1020], len: 0 }; + if data.len() > tb.data.len() { + return Err(xous::Error::OutOfMemory); + } + tb.len = data.len() as u16; + let mut buf = tb.into_ipc(); + buf.lend_mut(self.conn, api::Opcode::FillTrng.to_usize().unwrap()) + .or(Err(xous::Error::InternalError))?; + if buf.len as usize != data.len() { + return Err(xous::Error::InternalError); + } + data.copy_from_slice(&buf.data[..data.len()]); + Ok(()) + } + + pub fn hook_error_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> { + if self.error_sid.is_none() { + let sid = xous::create_server().unwrap(); + self.error_sid = Some(sid); + let sid_tuple = sid.to_u32(); + xous::create_thread_4( + error_cb_server, + sid_tuple.0 as usize, + sid_tuple.1 as usize, + sid_tuple.2 as usize, + sid_tuple.3 as usize, + ) + .unwrap(); + let hookdata = api::ScalarHook { sid: sid_tuple, id, cid }; + let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?; + buf.lend(self.conn, api::Opcode::ErrorSubscribe.to_u32().unwrap()).map(|_| ()) + } else { + Err(xous::Error::MemoryInUse) // can't hook it twice + } + } + + pub fn get_health_tests(&self) -> Result { + let ht = api::HealthTests::default(); + let mut buf = Buffer::into_buf(ht).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, api::Opcode::HealthStats.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; + Ok(buf.to_original().unwrap()) + } + + pub fn get_error_stats(&self) -> Result { + let errs = api::TrngErrors::default(); + let mut buf = Buffer::into_buf(errs).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, api::Opcode::ErrorStats.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; + Ok(buf.to_original().unwrap()) + } + + /// This is copied out of the 0.5 API for rand_core + pub fn fill_bytes_via_next(&mut self, dest: &mut [u8]) { + let mut left = dest; + while left.len() >= 8 { + let (l, r) = { left }.split_at_mut(8); + left = r; + let chunk: [u8; 8] = self.next_u64().to_ne_bytes(); + l.copy_from_slice(&chunk); + } + let n = left.len(); + if n > 4 { + let chunk: [u8; 8] = self.next_u64().to_ne_bytes(); + left.copy_from_slice(&chunk[..n]); + } else if n > 0 { + let chunk: [u8; 4] = self.next_u32().to_ne_bytes(); + left.copy_from_slice(&chunk[..n]); + } + } +} + +impl RngCore for Trng { + // legacy (0.5) trng apis + fn next_u32(&mut self) -> u32 { self.get_u32().expect("couldn't get random u32 from server") } + + fn next_u64(&mut self) -> u64 { self.get_u64().expect("couldn't get random u64 from server") } + + 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); + } + // 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; + } + } + } + // 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> { + Ok(self.fill_bytes(dest)) + } +} + +impl CryptoRng for Trng {} + +use core::sync::atomic::{AtomicU32, Ordering}; +static REFCOUNT: AtomicU32 = AtomicU32::new(0); +impl Drop for Trng { + fn drop(&mut self) { + // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the + // connection. + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { + unsafe { + xous::disconnect(self.conn).unwrap(); + } + } + } +} + +fn error_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { + let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32); + loop { + let msg = xous::receive_message(sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(api::EventCallback::Event) => xous::msg_scalar_unpack!(msg, cid, id, _, _, { + // directly pass the scalar message onto the CID with the ID memorized in the original hook + send_message(cid as u32, xous::Message::new_scalar(id, 0, 0, 0, 0)).unwrap(); + }), + Some(api::EventCallback::Drop) => { + break; // this exits the loop and kills the thread + } + None => (), + } + } + xous::destroy_server(sid).unwrap(); +} + +pub mod api { + pub const SERVER_NAME_TRNG: &str = "_TRNG manager_"; // depended upon by getrandom, do not change + + /// These opcode numbers are partially baked into the `getrandom` library -- + /// which kind of acts as a `std`-lib-ish style interface for the trng, so, + /// by design it can't have a dependency on this crate :-/ + #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] + pub enum Opcode { + /// Get one or two 32-bit words of TRNG data + GetTrng = 0, + + /// Fill a buffer with random data + FillTrng = 1, + + /// Notification of an error from the interrupt handler + ErrorNotification = 3, + + /// Subscribe to error notifications + ErrorSubscribe = 4, + + /// Get TRNG health stats + HealthStats = 5, + + /// Get Error stats + ErrorStats = 6, + } + + #[derive(Debug, flatipc::Ipc)] + #[allow(dead_code)] + /// Note that this structure is mirrored in imports/getrandom/src/xous.rs + #[repr(C)] + pub struct TrngBuf { + pub data: [u32; 1020], + pub len: u16, + } + + #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] + pub enum EventCallback { + Event, + Drop, + } + + #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] + pub struct ScalarHook { + pub sid: (u32, u32, u32, u32), + pub id: u32, /* ID of the scalar message to send through (e.g. the discriminant of the Enum on the + * caller's side API) */ + pub cid: xous::CID, /* caller-side connection ID for the scalar message to route to. Created by + * the caller before hooking. */ + } + + #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)] + pub struct NistTests { + pub adaptive_b: u16, + pub repcount_b: u16, + pub fresh: bool, + } + + #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)] + pub struct HealthTests { + pub av_nist: NistTests, + pub ro_nist: NistTests, + } + + #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)] + pub struct TrngErrors { + pub nist_errs: u32, + pub pending_mask: u32, + } +} diff --git a/services/bao1x-hal-service/src/trng.rs b/services/bao1x-hal-service/src/trng/dabao.rs similarity index 96% rename from services/bao1x-hal-service/src/trng.rs rename to services/bao1x-hal-service/src/trng/dabao.rs index 1f0489064..5fd118d3f 100644 --- a/services/bao1x-hal-service/src/trng.rs +++ b/services/bao1x-hal-service/src/trng/dabao.rs @@ -1,3 +1,7 @@ +//! Dabao's TRNG implementation pulls directly from the kernel TRNG, which is +//! a pass-through from the on-chip ring-oscillator based TRNG. Characterization +//! indicates it's a reasonable source of entropy on its own. + use std::cell::RefCell; use std::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/bao1x-hal-service/src/trng/mod.rs b/services/bao1x-hal-service/src/trng/mod.rs new file mode 100644 index 000000000..7cb900550 --- /dev/null +++ b/services/bao1x-hal-service/src/trng/mod.rs @@ -0,0 +1,8 @@ +#[cfg(feature = "board-baosec")] +pub mod baosec; +#[cfg(feature = "board-baosec")] +pub use baosec::*; +#[cfg(feature = "board-dabao")] +pub mod dabao; +#[cfg(feature = "board-dabao")] +pub use dabao::*;