diff --git a/Cargo.lock b/Cargo.lock index c59452bde..a3adb3eb8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -879,6 +879,7 @@ dependencies = [ "log", "log-server", "ticktimer-server", + "trng", "utralib", "xous", "xous-names", @@ -1010,6 +1011,19 @@ dependencies = [ "xmas-elf", ] +[[package]] +name = "trng" +version = "0.1.0" +dependencies = [ + "heapless", + "log", + "log-server", + "ticktimer-server", + "utralib", + "xous", + "xous-names", +] + [[package]] name = "trng-tester" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 8b1a262af..ef59dac54 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ members = [ "services/fcc-agent", "services/xous-names", "services/keyboard", + "services/trng", "svd2utra", "xtask", ] @@ -25,6 +26,7 @@ default-members = [ "services/xous-names", "services/keyboard", "services/com", + "services/trng" ] # These packages have custom RUSTFLAGS, so if they diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index 283116d89..c0a20a964 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -794,7 +794,7 @@ fn xmain() -> ! { let kbd_sid = xous_names::register_name(xous::names::SERVER_NAME_KBD).expect("KBD: can't register server"); info!("KBD: registered with NS -- {:?}", kbd_sid); - // Create a new com object + // Create a new kbd object let mut kbd = Keyboard::new(); let mut normal_conns: Vec = Vec::new(); diff --git a/services/shell/Cargo.toml b/services/shell/Cargo.toml index d9b9e9dfe..111352eec 100644 --- a/services/shell/Cargo.toml +++ b/services/shell/Cargo.toml @@ -13,6 +13,7 @@ ticktimer-server = { path = "../ticktimer-server" } xous-names = { path = "../xous-names" } log-server = { path = "../log-server" } keyboard = { path = "../keyboard" } +trng = { path = "../trng" } heapless = "0.5" log = "0.4" diff --git a/services/shell/src/main.rs b/services/shell/src/main.rs index d563e7f6f..383abaa48 100644 --- a/services/shell/src/main.rs +++ b/services/shell/src/main.rs @@ -50,15 +50,18 @@ impl Bounce { self.bounds } - pub fn next_rand(&mut self) -> i16 { + pub fn next_rand(&mut self, trng_conn: xous::CID) -> i16 { + /* let mut ret = move_lfsr(self.lfsr); self.lfsr = ret; ret *= 3; // make the ball move faster + */ + let ret = trng::get_u32(trng_conn).expect("SHELL: can't get TRNG") * 3; (ret % 12) as i16 } - pub fn update(&mut self) -> &mut Self { + pub fn update(&mut self, trng_conn: xous::CID) -> &mut Self { let mut x: i16; let mut y: i16; // update the new ball location @@ -72,19 +75,19 @@ impl Bounce { || (y <= (self.bounds.tl.y + r)) { if x >= (self.bounds.br.x - r - 1) { - self.vector.x = -self.next_rand(); + self.vector.x = -self.next_rand(trng_conn); x = self.bounds.br.x - r; } if x <= self.bounds.tl.x + r + 1 { - self.vector.x = self.next_rand(); + self.vector.x = self.next_rand(trng_conn); x = self.bounds.tl.x + r; } if y >= (self.bounds.br.y - r - 1) { - self.vector.y = -self.next_rand(); + self.vector.y = -self.next_rand(trng_conn); y = self.bounds.br.y - r; } if y <= (self.bounds.tl.y + r + 1) { - self.vector.y = self.next_rand(); + self.vector.y = self.next_rand(trng_conn); y = self.bounds.tl.y + r; } } @@ -168,6 +171,8 @@ fn shell_main() -> ! { let com_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_COM).expect("SHELL: can't connect to COM"); info!("SHELL: connected to COM: {:?}", com_conn); + let trng_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_TRNG).expect("SHELL: can't connect to TRNG"); + // make a thread to catch responses from the COM xous::create_thread_simple(event_thread, 0).unwrap(); info!("SHELL: COM responder thread started"); @@ -181,7 +186,7 @@ fn shell_main() -> ! { Point::new(screensize.x as _, screensize.y as i16 - 1), ), ); - bouncyball.update(); + bouncyball.update(trng_conn); #[cfg(baremetal)] { @@ -346,7 +351,7 @@ fn shell_main() -> ! { ), ) .expect("unable to clear ball region"); - bouncyball.update(); + bouncyball.update(trng_conn); // draw the top line that contains the ball graphics_server::draw_line( diff --git a/services/trng/Cargo.toml b/services/trng/Cargo.toml new file mode 100644 index 000000000..f82ad83b5 --- /dev/null +++ b/services/trng/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "trng" +version = "0.1.0" +authors = ["bunnie "] +edition = "2018" +description = "TRNG server" + +[dependencies] +xous = { path = "../../xous-rs" } +heapless = "0.5.6" +log-server = { path = "../log-server" } +ticktimer-server = { path = "../ticktimer-server" } +xous-names = { path = "../xous-names" } +log = "0.4" + + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +debugprint = [] +default = [] # "debugprint" diff --git a/services/trng/src/api.rs b/services/trng/src/api.rs new file mode 100644 index 000000000..48a83387d --- /dev/null +++ b/services/trng/src/api.rs @@ -0,0 +1,36 @@ +use xous::{Message, ScalarMessage}; + +#[allow(dead_code)] +#[derive(Debug)] +pub enum Opcode { + /// Get one or two 32-bit words of TRNG data + GetTrng(usize), +} + +impl core::convert::TryFrom<& Message> for Opcode { + type Error = &'static str; + fn try_from(message: & Message) -> Result { + match message { + Message::BlockingScalar(m) => match m.id { + 0 => Ok(Opcode::GetTrng(m.arg1)), + _ => Err("TRNG api: unknown BlockingScalar ID"), + }, + _ => Err("TRNG api: unhandled message type"), + } + } +} + +impl Into for Opcode { + fn into(self) -> Message { + match self { + Opcode::GetTrng(count) => Message::BlockingScalar(ScalarMessage { + id: 0, + arg1: count.into(), + arg2: 0, + arg3: 0, + arg4: 0, + }), + // _ => panic!("TRNG api: Opcode type not handled by Into(), refer to helper method"), + } + } +} diff --git a/services/trng/src/lib.rs b/services/trng/src/lib.rs new file mode 100644 index 000000000..45f98edcb --- /dev/null +++ b/services/trng/src/lib.rs @@ -0,0 +1,22 @@ +#![cfg_attr(target_os = "none", no_std)] + +pub mod api; +use xous::{CID, send_message}; + +pub fn get_u32(cid: CID) -> Result { + let response = send_message(cid, api::Opcode::GetTrng(1).into())?; + if let xous::Result::Scalar2(trng, _) = response { + Ok(trng as u32) + } else { + panic!("unexpected return value: {:#?}", response); + } +} + +pub fn get_u64(cid: CID) -> Result { + let response = send_message(cid, api::Opcode::GetTrng(2).into())?; + if let xous::Result::Scalar2(lo, hi) = response { + Ok( lo as u64 | ((hi as u64) << 32) ) + } else { + panic!("unexpected return value: {:#?}", response); + } +} diff --git a/services/trng/src/main.rs b/services/trng/src/main.rs new file mode 100644 index 000000000..e9d147f11 --- /dev/null +++ b/services/trng/src/main.rs @@ -0,0 +1,175 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +mod api; +use api::*; + +use core::convert::TryFrom; + +use log::{error, info}; + + +#[cfg(target_os = "none")] +mod implementation { + use utralib::generated::*; + // use crate::api::*; + use log::{/*error,*/ info}; + + pub struct Trng { + csr: utralib::CSR, + // TODO: allocate a software buffer for whitened TRNGs + } + + impl Trng { + pub fn new() -> Trng { + let csr = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::trng_server::HW_TRNG_SERVER_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map TRNG CSR range"); + + let mut trng = Trng { + csr: CSR::new(csr.as_mut_ptr() as *mut u32), + }; + + ///// configure power settings and which generator to use + trng.csr.wo(utra::trng_server::CONTROL, + trng.csr.ms(utra::trng_server::CONTROL_ENABLE, 1) + | trng.csr.ms(utra::trng_server::CONTROL_POWERSAVE, 1) + // | self.server_csr.ms(utra::trng_server::CONTROL_AV_DIS, 1) // disable the AV generator to characterize the RO + // | self.server_csr.ms(utra::trng_server::CONTROL_RO_DIS, 1) // disable the RO to characterize only the AV + ); + + /*** TRNG tuning parameters: these were configured and tested in a long run against Dieharder + There is a rate of TRNG generation vs. quality trade-off. The tuning below is toward quality of + TRNG versus rate of TRNG, such that we could use these without any whitening. + ***/ + ///// configure avalanche + // delay in microseconds for avalanche poweron after powersave + trng.csr.wo(utra::trng_server::AV_CONFIG, + trng.csr.ms(utra::trng_server::AV_CONFIG_POWERDELAY, 50_000) + | trng.csr.ms(utra::trng_server::AV_CONFIG_SAMPLES, 32) + ); + + ///// configure ring oscillator + trng.csr.wo(utra::trng_server::RO_CONFIG, + trng.csr.ms(utra::trng_server::RO_CONFIG_DELAY, 4) + | trng.csr.ms(utra::trng_server::RO_CONFIG_DWELL, 100) + | trng.csr.ms(utra::trng_server::RO_CONFIG_GANG, 1) + | trng.csr.ms(utra::trng_server::RO_CONFIG_FUZZ, 1) + | trng.csr.ms(utra::trng_server::RO_CONFIG_OVERSAMPLING, 3) + ); + + info!("TRNG: hardware initialized"); + + trng + } + + pub fn get_data_eager(&self) -> u32 { + while self.csr.rf(utra::trng_server::STATUS_AVAIL) == 0 { + xous::yield_slice(); + } + self.csr.rf(utra::trng_server::DATA_DATA) + } + + #[allow(dead_code)] + pub fn wait_full(&self) { + while self.csr.rf(utra::trng_server::STATUS_FULL) == 0 { + xous::yield_slice(); + } + } + + pub fn get_trng(&self, count: usize) -> [u32; 2] { + // TODO: use SHA hardware unit to robustify the TRNG output against potential hardware failures + // TODO: health monitoring of raw TRNG output + let mut ret: [u32; 2] = [0, 0]; + + /* + in the final implementation the algorithm should be: + 1) check fullness of software-whitened pool + 2) if software pool is full enough, return values from there + 3) if pool is low, activate hardware TRNG and refill the pool (uses SHA unit) + 4) during pool-filling, perform statistics on the hardware TRNG output to check health + 5) confirm health is OK + */ + + // for now, we just take data directly from the hardware-managed raw TRNG pool + ret[0] = self.get_data_eager(); + // we don't just draw down TRNGs if not requested, because they are a finite resource + if count > 1 { + ret[1] = self.get_data_eager(); + } + + ret + } + } +} + +// a stub to try to avoid breaking hosted mode for as long as possible. +#[cfg(not(target_os = "none"))] +mod implementation { + use crate::api::*; + use log::{error, info}; + + pub struct Trng { + seed: u32, + } + + impl Trng { + pub fn new() -> Trng { + Trng { + seed: 0x1afe_cafe, + } + } + + fn move_lfsr(mut lfsr: u32) -> u32 { + lfsr ^= lfsr >> 7; + lfsr ^= lfsr << 9; + lfsr ^= lfsr >> 13; + lfsr + } + + pub fn wait_full(&self) { } + + pub fn get_trng(&mut self, count: usize) -> [u32; 2] { + info!("TRNG: hosted mode TRNG is *not* random, it is an LFSR"); + let ret: [u32; 2]; + self.seed = move_lfsr(self.seed); + ret[0] = self.seed; + self.seed = move_lfsr(self.seed); + ret[1] = self.seed; + + ret + } + } +} + +#[xous::xous_main] +fn xmain() -> ! { + use crate::implementation::Trng; + + log_server::init_wait().unwrap(); + + let trng_sid = xous_names::register_name(xous::names::SERVER_NAME_TRNG).expect("TRNG: can't register server"); + info!("TRNG: registered with NS -- {:?}", trng_sid); + + let trng = Trng::new(); + info!("TRNG: ready to accept requests"); + + loop { + let envelope = xous::receive_message(trng_sid).unwrap(); + if let Ok(opcode) = Opcode::try_from(&envelope.body) { + match opcode { + Opcode::GetTrng(count) => { + let val: [u32; 2] = trng.get_trng(count); + xous::return_scalar2(envelope.sender, val[0] as _, val[1] as _) + .expect("TRNG: couldn't return GetTrng request"); + }, + } + } else { + error!("KBD: couldn't convert opcode"); + } + } +} diff --git a/xous-rs/src/names.rs b/xous-rs/src/names.rs index c605bab02..cf4ccb267 100644 --- a/xous-rs/src/names.rs +++ b/xous-rs/src/names.rs @@ -13,6 +13,7 @@ pub const SERVER_NAME_SHELL: &str = "_Shell_"; pub const SERVER_NAME_GFX: &str = "_Graphics_"; pub const SERVER_NAME_FCCAGENT: &str = "_Agent for EMC Testing_"; pub const SERVER_NAME_KBD: &str = "_Matrix keyboard driver_"; +pub const SERVER_NAME_TRNG: &str = "_TRNG manager_"; /* diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 555c50fd5..ef4c6aad6 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -86,6 +86,7 @@ fn build_hw_image(debug: bool, svd: Option) -> Result<(), DynError> { "com", "xous-names", "keyboard", + "trng", ] { // "fcc-agent" init.push(build(pkg, debug, Some(TARGET), None)?); @@ -188,6 +189,7 @@ fn run(debug: bool) -> Result<(), DynError> { "com", "xous-names", "keyboard", + "trng", ]; // let mut init_paths = vec![];