Merge pull request #561 from betrusted-io/trng-rework

Trng rework
This commit is contained in:
bunnie 2024-06-22 21:23:27 +08:00 committed by GitHub
commit 9ada468c5c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 54 additions and 23 deletions

View file

@ -72,7 +72,9 @@ pub fn init() {
let mut trng_kernel = sce::trng::Trng::new(TRNG_KERNEL_ADDR);
trng_kernel.setup_raw_generation(256);
// setup the initial seeds with stuff out of the TRNG.
// Setup the initial seeds with raw data directly out of the TRNG. You'd think this
// would give you 256 bits of entropy, but TRNGs can be imperfect so we assume it is
// much less than this.
for state in LOCAL_RNG_STATE.iter() {
state.store(trng_kernel.get_u32().expect("TRNG error"), Ordering::SeqCst);
}
@ -82,19 +84,17 @@ pub fn init() {
TRNG_KERNEL = Some(trng_kernel);
}
// Accumulate more TRNG data, because I don't trust it. Note that ChaCha8's seed never changes:
// the output is just the seed + some generation distance from the seed. Thus to change the seed,
// we have to extract it, XOR it with data, and put it back into the machine.
// Accumulate more TRNG data, because I don't trust it.
//
// Repeat N times for good measure:
// 1. XOR in another round of HW TRNG data into the ChaCha8 state
// 2. Create the ChaCha8 cipher from the state
// 3. Run ChaCha8 and XOR its result into the state vector (obfuscate temporary dropouts in HW TRNG)
// 4. Store the state vector
// For the kernel, every 32 bits extracted is accompanied by a reseeding operation. Thus,
// we can effectively improve the seed pool by just requesting u32's out of the pool and throwing
// the result away.
//
// Each round pulls in 8*32 = 256 bits from HW TRNG 64 rounds of this would fold in 16,384 bits total.
// Every subsequent call to get_u32() adds more entropy to the pool. This should give us about 100x safety
// margin. The latest settings improvement on the TRNG makes me think this is extremely conservative, we
// margin to a target of 128 bits of true entropy.
//
// The latest settings improvement on the TRNG makes me think this is extremely conservative, we
// could probably do fine with a 10x margin; but, the operation is fast enough that this allows us
// to be safe even if the TRNG is completely misconfigured.
for _ in 0..64 {
@ -102,11 +102,24 @@ pub fn init() {
}
}
/// Retrieve random `u32`.
/// Retrieve a true random `u32`. The data comes from the output of a CPRNG that is seeded by
/// the TRNG. Every pull of a `u32` adds more TRNG data to the CPRNG seed pool.
///
/// Note that ChaCha8's seed never changes: the output is just the seed + some generation distance from the
/// seed. Thus to change the seed, we have to extract it, XOR it with data, and put it back into the machine.
///
/// 1. XOR in another round of HW TRNG data into the ChaCha8 state
/// 2. Create the ChaCha8 cipher from the state
/// 3. Run ChaCha8 and XOR its result into the state vector (obfuscate temporary dropouts in HW TRNG)
/// 4. Store the state vector
pub fn get_u32() -> u32 {
// Local storage for the seed.
let mut seed = [0u8; 32];
// mix in more data from the TRNG while recovering the state from the kernel holding area
// Pull our true seed data from the static AtomicU32 variables. We have to do this because
// we're the kernel: any machine persistent state is by definition, global mutable state.
//
// Mix in more data from the TRNG while recovering the state from the kernel holding area.
for (s, state) in seed.chunks_mut(4).zip(LOCAL_RNG_STATE.iter()) {
let incoming = get_raw_u32() ^ state.load(Ordering::SeqCst);
for (s_byte, &incoming_byte) in s.iter_mut().zip(incoming.to_le_bytes().iter()) {
@ -114,21 +127,26 @@ pub fn get_u32() -> u32 {
}
}
let mut cstrng = ChaCha8Rng::from_seed(seed);
// mix up the internal state with output from the CSTRNG
// Mix up the internal state with output from the CSPRNG. We do this because the TRNG bits
// could be biased, and by running the CSPRNG forward based on the new seed, we have a chance to
// diffuse any true entropy over all bits in the seed pool.
for s in seed.chunks_mut(8) {
for (s_byte, chacha_byte) in s.iter_mut().zip(cstrng.next_u64().to_le_bytes()) {
*s_byte ^= chacha_byte;
}
}
// now extract one value from the CSPRNG
// Now extract one value from the CSPRNG: this is the number we reveal to the outside world.
// It should not, in theory, be possible to deduce the seed from this value.
let ret_val = cstrng.next_u32();
// save the state into the kernel holding area
// Save the mixed state into the kernel holding area
for (s, state) in seed.chunks(4).zip(LOCAL_RNG_STATE.iter()) {
state.store(u32::from_le_bytes(s.try_into().unwrap()), Ordering::SeqCst);
}
ret_val
}
/// This returns a raw, unwhitened, unprocessed TRNG value.
pub fn get_raw_u32() -> u32 {
unsafe {
TRNG_KERNEL

View file

@ -90,6 +90,8 @@ pub struct Trng {
pub csr: CSR<u32>,
_count: u16, // vestigial, to be removed?
mode: Mode,
/// Buffer some raw entropy inside the kernel, so we can "burst out" entropy
/// for reseed operations without having to wait for the TRNG to regenerate data.
raw: [Option<u32>; RAW_ENTRIES],
#[cfg(feature = "compress-entropy")]
rng_var: u8,
@ -136,13 +138,16 @@ impl Trng {
}
pub fn get_raw(&mut self) -> u32 {
// Pull from the buffered entropy pool, until it's empty.
for d in self.raw.iter_mut() {
if let Some(r) = d.take() {
return r;
}
}
// If empty, refill the buffer.
while self.csr.r(utra::trng::SFR_SR) & Status::BUFREADY.bits() == 0 {}
#[cfg(feature = "compress-entropy")]
let mut sample = self.csr.r(utra::trng::SFR_BUF);
#[cfg(feature = "compress-entropy")]

View file

@ -313,31 +313,39 @@ impl SwapHal {
let mut cstrng = ChaCha8Rng::from_seed(seed);
// Accumulate TRNG data into the seed (which starts at 0).
// Repeat N times for good measure:
// 1. XOR in another round of HW TRNG data into ChaCha8
// 2. create a new ChaCha8 from the resulting data
// 3. Run the ChaCha8 for a few rounds and XOR that back into the state
//
// Each round pulls in 8*32 = 256 bits from HW TRNG
// 64 rounds of this would fold in 16,384 bits total, about 100x safety margin.
// 64 rounds of this would fold in 16,384 bits total, about 100x safety margin
// from the minimum target of 128 bits.
for _ in 0..64 {
// extract the seed of the current version of the CSPRNG
seed = cstrng.get_seed();
// XOR the seed with TRNG data
for s in seed.chunks_mut(4) {
let incoming = trng.get_u32().expect("TRNG error") ^ cstrng.next_u32();
let incoming = trng.get_u32().expect("TRNG error");
for (s_byte, &incoming_byte) in s.iter_mut().zip(incoming.to_le_bytes().iter()) {
*s_byte ^= incoming_byte;
}
}
// println!("seed: {:x?}", seed); // eyeball if things are working correctly
// Make a new CSPRNG from the old seed that was XOR'd with the TRNG data
cstrng = ChaCha8Rng::from_seed(seed);
// mix up the internal state with output from the CSTRNG
// Mix up the seed with output from the CSPRNG (as-seeded). The idea is to diffuse the
// TRNG data across all the bits of the state, just in case the TRNG has some biased bits.
for s in seed.chunks_mut(8) {
for (s_byte, chacha_byte) in s.iter_mut().zip(cstrng.next_u64().to_le_bytes()) {
*s_byte ^= chacha_byte;
}
}
// Make a final version of the CSPRNG based on the mixed state.
cstrng = ChaCha8Rng::from_seed(seed);
}
// now we might have a properly seeded cryptographically secure TRNG...
// now we might have a properly seeded cryptographically secure TRNG...derive the ephemeral
// swap session key.
let mut dest_key = [0u8; 32];
for word in dest_key.chunks_mut(core::mem::size_of::<u32>()) {
word.copy_from_slice(&cstrng.next_u32().to_be_bytes());