Merge pull request #732 from betrusted-io/minor-fixes

Minor fixes
This commit is contained in:
bunnie 2025-11-19 00:06:17 +08:00 committed by GitHub
commit 09cecfc899
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 229 additions and 72 deletions

1
Cargo.lock generated
View file

@ -355,6 +355,7 @@ dependencies = [
"pddb", "pddb",
"rand 0.8.5", "rand 0.8.5",
"rand_chacha 0.3.1", "rand_chacha 0.3.1",
"rand_core 0.6.4",
"usb-bao1x", "usb-bao1x",
"utralib 0.1.26", "utralib 0.1.26",
"ux-api", "ux-api",

View file

@ -6,7 +6,7 @@ use utralib::utra::bio_bdma::SFR_CONFIG_CLOCKING_MODE;
use utralib::*; use utralib::*;
use xous_bio_bdma::*; use xous_bio_bdma::*;
use crate::{print, println}; use crate::println;
/* /*
pub fn bdma_test(_args: &Vec<String>, seed: u32) -> usize { pub fn bdma_test(_args: &Vec<String>, seed: u32) -> usize {
@ -204,8 +204,7 @@ impl TestPattern {
} }
} }
pub fn bdma_coincident_test(_args: &Vec<String>, seed: u32) -> usize { pub fn bdma_coincident_test(_args: &Vec<String>, seed: u32, clkmode: u32) -> usize {
let clkmode = 0;
const TEST_LEN: usize = 1024; const TEST_LEN: usize = 1024;
let mut passing = 0; let mut passing = 0;
@ -286,10 +285,10 @@ fn coincident_u32(
for (i, &d) in src.iter().enumerate() { for (i, &d) in src.iter().enumerate() {
let rbk = unsafe { dst.as_ptr().add(i).read_volatile() }; let rbk = unsafe { dst.as_ptr().add(i).read_volatile() };
if rbk != d { if rbk != d {
if errs < 4 { if errs < 3 {
println!("{} err @{}, {:x} rbk: {:x}", name, i, d, rbk); println!("{} err @{}, {:x} rbk: {:x}", name, i, d, rbk);
} else { } else {
print!("."); // crate::print!(".");
} }
errs += 1; errs += 1;
pass = 0; pass = 0;

View file

@ -458,11 +458,20 @@ impl Repl {
#[cfg(feature = "bao1x-bio")] #[cfg(feature = "bao1x-bio")]
"bdma" => { "bdma" => {
let mut seed = 0; let mut seed = 0;
let mut clkmode: u32 = 3;
let mut passing: bool;
loop { 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; seed += 1;
crate::println!("seed {}", seed); if passing || seed > 8 {
if seed > 32 {
break; break;
} }
} }

View file

@ -14,6 +14,11 @@ use crate::acram::OneWayCounter;
use crate::acram::{AccessSettings, SlotManager}; use crate::acram::{AccessSettings, SlotManager};
use crate::udma::Spim; 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, /// 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. /// 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"))] #[cfg(not(feature = "std"))]
pub fn erase_secrets() { 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 // ensure coreuser settings, as we could enter from a variety of loader stages
let mut cu = crate::coreuser::Coreuser::new(); let mut cu = crate::coreuser::Coreuser::new();
cu.set(); cu.set();

View file

@ -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] if tag == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT]
|| k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT
{ {
crate::println!("Developer key detected, ensuring secrets are erased"); // we can't erase keys in the loader, because the keys have already been locked
bao1x_hal::sigcheck::erase_secrets(); // 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) => { 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] == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT]
|| k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT
{ {
crate::println!("Developer key detected, ensuring secrets are erased"); // we can't erase keys in the loader, because the keys have already been locked
bao1x_hal::sigcheck::erase_secrets(); // 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 true
} }

View file

@ -256,8 +256,20 @@ impl SwapHal {
[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] [bao1x_api::pubkeys::DEVELOPER_KEY_SLOT]
|| k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT
{ {
crate::println!("Developer key detected, ensuring secrets are erased"); // we can't erase keys in the loader, because the keys have already been
bao1x_hal::sigcheck::erase_secrets(); // 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) => { Err(e) => {

View file

@ -28,6 +28,7 @@ bytemuck = "1.24.0"
# pddb testing # pddb testing
rand = { version = "0.8.5", features = ["getrandom"], optional = true } rand = { version = "0.8.5", features = ["getrandom"], optional = true }
rand_chacha = { version = "0.3.1", optional = true } rand_chacha = { version = "0.3.1", optional = true }
rand_core = "0.6.4"
aes = { path = "../aes", default-features = false, optional = true } aes = { path = "../aes", default-features = false, optional = true }

View file

@ -1,4 +1,6 @@
use String; use String;
#[cfg(not(feature = "hosted-baosec"))]
use rand_core::RngCore;
use crate::{CommonEnv, ShellCmdApi}; use crate::{CommonEnv, ShellCmdApi};
@ -14,7 +16,7 @@ impl<'a> ShellCmdApi<'a> for TrngCmd {
fn process(&mut self, args: String, env: &mut CommonEnv) -> Result<Option<String>, xous::Error> { fn process(&mut self, args: String, env: &mut CommonEnv) -> Result<Option<String>, xous::Error> {
use core::fmt::Write; use core::fmt::Write;
let mut ret = String::new(); let mut ret = String::new();
let helpstring = "trng [pump] [u32] [u64]"; let helpstring = "trng [pump] [u32] [u64] [buf]";
let mut tokens = args.split(' '); let mut tokens = args.split(' ');
@ -37,6 +39,65 @@ impl<'a> ShellCmdApi<'a> for TrngCmd {
"u64" => { "u64" => {
log::info!("A u64 trng value: {:x}", env.trng.get_u64().unwrap()); 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(); write!(ret, "{}", helpstring).unwrap();
} }

View file

@ -10,6 +10,7 @@ xous-names = { package = "xous-api-names", version = "0.9.68" }
"ux-api" = { path = "../../libs/ux-api" } "ux-api" = { path = "../../libs/ux-api" }
"rand" = "0.8" "rand" = "0.8"
rand_core = "0.6.4" rand_core = "0.6.4"
rand_chacha = "0.3.1"
log = "0.4.14" log = "0.4.14"
log-server = { package = "xous-api-log", version = "0.1.66" } log-server = { package = "xous-api-log", version = "0.1.66" }
num-derive = { version = "0.4.2", default-features = false } num-derive = { version = "0.4.2", default-features = false }
@ -18,10 +19,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [
"std", "std",
"alloc", "alloc",
] } ] }
bao1x-api = { path = "../../libs/bao1x-api", features = [ bao1x-api = { path = "../../libs/bao1x-api", features = ["derive-rkyv", "std"] }
"derive-rkyv",
"std",
] }
[target.'cfg(any(windows,unix))'.dependencies] [target.'cfg(any(windows,unix))'.dependencies]
minifb = "0.26.0" minifb = "0.26.0"

View file

@ -34,6 +34,23 @@ impl Trng {
left.copy_from_slice(&chunk[..n]); 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 { impl RngCore for Trng {

View file

@ -142,6 +142,26 @@ impl Trng {
left.copy_from_slice(&chunk[..n]); 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 { impl RngCore for Trng {
@ -153,55 +173,36 @@ impl RngCore for Trng {
fn fill_bytes(&mut self, dest: &mut [u8]) { fn fill_bytes(&mut self, dest: &mut [u8]) {
// smaller than 64 bytes (512 bits), just use 8x next_u64 calls to fill. // smaller than 64 bytes (512 bits), just use 8x next_u64 calls to fill.
if dest.len() < 64 { 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 // use the api TrngBuf to hold the data so the compiler enforces exact data lengths
let chunks_page = dest.chunks_exact_mut(4096); // the `len` field is actually disregarded here, we're simply using this structure to
for chunks in chunks_page.into_iter() { // ensure that the `data` allocated matches the native size of the TrngBuf.
let mut data: [u32; 4080 / 4] = [0; 4080 / 4]; let mut api_buf = api::TrngBuf { data: [0u32; 1020], len: 1020 };
self.fill_buf(&mut data).expect("couldn't fill page-sized TRNG buffer"); let buf = &mut api_buf.data;
for (&src, dst) in data.iter().zip(chunks.chunks_exact_mut(4)) { let mut filled = 0;
for (&src_byte, dst_byte) in src.to_le_bytes().iter().zip(dst.iter_mut()) { while filled < dest.len() {
*dst_byte = src_byte; let fetch_len = ((((dest.len() + 3) & !3) - filled) / size_of::<u32>()).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> { fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {

View file

@ -3,6 +3,7 @@ use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArr
use bao1x_api::{ use bao1x_api::{
BOOT0_PUBKEY_FAIL, BoardTypeCoding, CP_ID, DEVELOPER_MODE, OEM_MODE, SLOT_ELEMENT_LEN_BYTES, UUID, 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::{ use bao1x_hal::{
acram::{OneWayCounter, SlotManager}, acram::{OneWayCounter, SlotManager},
board::{CHAFF_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, ROOT_SEED}, board::{CHAFF_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, ROOT_SEED},
@ -102,6 +103,23 @@ impl KeyStore {
// read key material // read key material
ikm.extend_from_slice(self.slot_mgr.read(&ROOT_SEED).unwrap()); 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 // build nuisance key offsets - this is direct readout hardening
let nk0 = NUISANCE_KEYS_0.try_into_data_iter().unwrap(); let nk0 = NUISANCE_KEYS_0.try_into_data_iter().unwrap();
@ -173,7 +191,9 @@ impl KeyStore {
} }
#[cfg(feature = "hazardous-debug")] #[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); ikm.extend_from_slice(&chaff_xor);
assert!(ikm.len() == (nk_len + 1 + 1) * KEY_LEN); // sanity check that all keys were in fact added 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")] #[cfg(feature = "hazardous-debug")]
for (i, chunk) in ikm.chunks(256).enumerate() { for (i, chunk) in ikm.chunks(32).enumerate() {
log::info!("ikm({:4}): {:x?}", i, chunk); // 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 log::debug!("salt: {:x?}", salt); // not hazardous, these are public values
let hk = Hkdf::<Sha256>::new(Some(&salt[..]), &ikm); let hk = Hkdf::<Sha256>::new(Some(&salt[..]), &ikm);
@ -212,11 +238,14 @@ impl KeyStore {
// do something with ct_xor that guarantees it's never optimized out // do something with ct_xor that guarantees it's never optimized out
if ct_xor.iter().all(|&cx| cx == 0) { if ct_xor.iter().all(|&cx| cx == 0) {
log::warn!("Chaff result is all-0. Confirming that we're in developer mode"); 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 // panic if we're not in developer mode
assert!( assert!(
self.owc.get(DEVELOPER_MODE).unwrap() != 0, 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" "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); self.master_key = Some(master_key);
} }

View file

@ -7,6 +7,7 @@ use aes_gcm_siv::Nonce;
use bao1x_emu::trng::Trng; use bao1x_emu::trng::Trng;
#[cfg(all(feature = "bao1x-hal", not(feature = "hosted-baosec")))] #[cfg(all(feature = "bao1x-hal", not(feature = "hosted-baosec")))]
use bao1x_hal_service::trng::Trng; use bao1x_hal_service::trng::Trng;
#[cfg(not(feature = "gen2"))]
use rand_core::RngCore; use rand_core::RngCore;
#[cfg(all(not(feature = "bao1x-hal"), not(feature = "hosted-baosec")))] #[cfg(all(not(feature = "bao1x-hal"), not(feature = "hosted-baosec")))]
use trng::Trng; use trng::Trng;
@ -23,14 +24,22 @@ impl TrngPool {
let xns = xous_names::XousNames::new().unwrap(); let xns = xous_names::XousNames::new().unwrap();
let mut trng = Trng::new(&xns).unwrap(); let mut trng = Trng::new(&xns).unwrap();
let mut cache: [u8; 8192] = [0; 8192]; let mut cache: [u8; 8192] = [0; 8192];
#[cfg(not(feature = "gen2"))]
trng.fill_bytes(&mut cache); 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()) } TrngPool { trng: RefCell::new(trng), e_cache: RefCell::new(cache.to_vec()) }
} }
pub(crate) fn ensure_entropy(&self, amount: usize) { pub(crate) fn ensure_entropy(&self, amount: usize) {
if self.e_cache.borrow().len() < amount { if self.e_cache.borrow().len() < amount {
let mut cache: [u8; 8192] = [0; 8192]; let mut cache: [u8; 8192] = [0; 8192];
#[cfg(not(feature = "gen2"))]
self.trng.borrow_mut().fill_bytes(&mut cache); 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); self.e_cache.borrow_mut().extend_from_slice(&cache);
} }
} }