add basic TRNG service

This commit is contained in:
bunnie 2021-01-13 15:04:14 +08:00
parent 18fbd046f6
commit 8a1991876f
11 changed files with 289 additions and 9 deletions

14
Cargo.lock generated
View file

@ -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"

View file

@ -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

View file

@ -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<xous::CID, U64> = Vec::new();

View file

@ -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"

View file

@ -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(

22
services/trng/Cargo.toml Normal file
View file

@ -0,0 +1,22 @@
[package]
name = "trng"
version = "0.1.0"
authors = ["bunnie <bunnie@kosagi.com>"]
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"

36
services/trng/src/api.rs Normal file
View file

@ -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<Self, Self::Error> {
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<Message> 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"),
}
}
}

22
services/trng/src/lib.rs Normal file
View file

@ -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<u32, xous::Error> {
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<u64, xous::Error> {
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);
}
}

175
services/trng/src/main.rs Normal file
View file

@ -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<u32>,
// 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");
}
}
}

View file

@ -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_";
/*

View file

@ -86,6 +86,7 @@ fn build_hw_image(debug: bool, svd: Option<String>) -> 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![];