add the code for initializing keys & setting up ACLs

this code audits the status of the data/key slots,
initializes them according to the platform, and sets
the permissions on them to prevent read-out later on.

A TRNG routine is built into boot1 now, I think it's
reasonably conservatively coded but more testing/inspection
is always good.
This commit is contained in:
bunnie 2025-10-20 23:39:04 +08:00
parent 1eeaa23516
commit 4affb7e979
No known key found for this signature in database
5 changed files with 369 additions and 4 deletions

View file

@ -16,13 +16,17 @@ linked_list_allocator = { version = "0.10.5", optional = true }
critical-section = "1.2.0"
ux-api = { path = "../../libs/ux-api", optional = true, default-features = false }
simple-fatfs = { git = "https://github.com/betrusted-io/simple-fatfs.git", branch = "baosec", default-features = false }
sha2 = { version = "0.10.8", default-features = false }
sha2-bao1x = { path = "../sha2-bao1x", default-features = false }
digest = { version = "0.10.7" }
ed25519-dalek = { package = "ed25519-dalek-bao1x", path = "../ed25519-dalek-bao1x", default-features = false, features = [
"digest",
"zeroize",
], optional = true }
base64 = { version = "0.22.1", default-features = false, features = ["alloc"] }
xous-bio-bdma = { path = "../../libs/xous-bio-bdma", default-features = false, features = [
"baremetal",
] }
rand_chacha = { version = "0.3.1", default-features = false }
[features]
# Baochip feature tree below
@ -30,7 +34,7 @@ bao1x = [
"utralib/bao1x",
"linked_list_allocator",
"bao1x-hal/loader-baosec",
# "bao1x-hal/debug-print-uart",
"bao1x-hal/debug-print-duart",
"bao1x-api",
# needed for the boot logo
"ux-api/loader-baosec",

View file

@ -4,6 +4,7 @@ pub mod debug;
pub mod gfx;
pub mod irq;
pub mod slots;
pub mod trng;
pub mod usb;
pub const UART_BAUD: u32 = 1_000_000;

View file

@ -70,7 +70,12 @@ pub fn setup_dabao_se0_pin<T: IoSetup + IoGpio>(iox: &T) -> (IoxPort, u8) {
/// This can change the board type coding to a safer, simpler board type if the declared board type has
/// problems booting.
pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::BoardTypeCoding, u32) {
crate::platform::slots::check_slots(&board_type);
// This is a security-critical initialization. Failure to do this correctly breaks
// the hardware access control scheme for key/data slots.
let mut cu = bao1x_hal::coreuser::Coreuser::new();
// safety: this is safe because it's followed by a `protect()` call.
unsafe { cu.set() };
cu.protect(); // locks out future modifications to the Coreuser setting
let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
@ -242,6 +247,9 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa
setup_timer(fclk_freq);
// check key slots for integrity
crate::platform::slots::check_slots(&board_type);
// Rx setup
let _udma_uart = setup_console(&board_type, &iox, perclk);
irq_setup();

View file

@ -1,3 +1,13 @@
use core::convert::TryInto;
use bao1x_api::{
CP_ID, IFR_CP_ID_BASE, IFR_HASH, SERIAL_NUMBER, SLOT_ELEMENT_LEN_BYTES, SlotIndex, SlotType, UUID,
};
use bao1x_hal::{
acram::{AccessSettings, SlotManager},
rram::Reram,
};
/// This function is designed to be called "frequently" to audit the state
/// of the security slots. Its role is to:
/// - Initialize any keys that have not yet been initialized
@ -6,4 +16,156 @@
/// - Repair any ACLs that are not set correctly. "Repair" is expected on first boot at the factory, since
/// the chip comes blank. But repair is also useful in case an adversary manages to flip any ACL states
/// on us.
pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) {}
pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) {
let owc = bao1x_hal::acram::OneWayCounter::new();
let mut slot_mgr = bao1x_hal::acram::SlotManager::new();
let mut maybe_trng: Option<super::trng::ManagedTrng> = None;
let mut rram = Reram::new();
// check the lifecycle status
if owc.get(bao1x_api::CP_BOOT_SETUP_DONE).unwrap() == 0 {
crate::println!("CP setup not yet done. Initializing public identifiers...");
// CP boot setup is not done. Initialize the basic identifiers.
// Each ID is checked first to see if it is non-zero. If it is non-zero, don't replace it.
// The reason this is done is because the ID capture/generation may happen at a time when
// power is unstable, so we may be recovering from a previous early power-down.
// Note the test condition b == 0 || b == 0xFF allows for a mix of 0x0 or 0xFF *only* as a
// trigger condition to update the values. This is intentional, as after CP the array may have
// some locations that are all 0 or all 1 (there's a checkerboard pattern test as part of the
// CP). However, all of the values under test should be *random* and thus a value that consists
// solely of those two numbers is highly unlikely to occur.
// Grab the CP ID first. This is the hardest one to capture as it is only available for a fixed time
// during CP and we can't strictly control how long we are powered on for.
if slot_mgr.read(&CP_ID).unwrap().iter().all(|&b| b == 0 || b == 0xFF) {
let cp_id =
unsafe { core::slice::from_raw_parts(IFR_CP_ID_BASE as *const u8, SLOT_ELEMENT_LEN_BYTES) };
slot_mgr.write(&mut rram, &CP_ID, cp_id.try_into().unwrap()).unwrap();
}
// this one may allocate a TRNG, which takes >50 ms to warm up.
if slot_mgr.read(&SERIAL_NUMBER).unwrap().iter().all(|&b| b == 0 || b == 0xFF) {
let trng = maybe_trng.get_or_insert_with(|| super::trng::ManagedTrng::new(&board_type));
let k = trng.generate_key();
slot_mgr.write(&mut rram, &SERIAL_NUMBER, &k).unwrap();
}
if slot_mgr.read(&UUID).unwrap().iter().all(|&b| b == 0 || b == 0xFF) {
let trng = maybe_trng.get_or_insert_with(|| super::trng::ManagedTrng::new(&board_type));
let k = trng.generate_key();
slot_mgr.write(&mut rram, &UUID, &k).unwrap();
}
if slot_mgr.read(&IFR_HASH).unwrap().iter().all(|&b| b == 0 || b == 0xFF) {
use digest::Digest;
use sha2_bao1x::Sha256;
let mut hasher = Sha256::new();
let ifr_slice =
unsafe { core::slice::from_raw_parts(bao1x_api::IFR_BASE as *const u8, bao1x_api::IFR_LEN) };
hasher.update(&ifr_slice);
let digest = hasher.finalize();
slot_mgr.write(&mut rram, &IFR_HASH, digest.as_slice().try_into().unwrap()).unwrap();
}
// once all values are written, advance the CP_BOOT_SETUP_DONE state
// safety: the offset is correct because we're pulling it from our pre-defined constants and
// those are manually checked.
unsafe { owc.inc(bao1x_api::CP_BOOT_SETUP_DONE).unwrap() };
crate::println!("Public ID init done.");
}
if *board_type == bao1x_api::BoardTypeCoding::Baosec
&& owc.get(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() == 0
{
crate::println!("System setup not yet done. Initializing secret identifiers...");
let trng = maybe_trng.get_or_insert_with(|| super::trng::ManagedTrng::new(&board_type));
// generate all the keys
for key_range in bao1x_api::baosec::KEY_SLOTS.iter() {
let mut storage = alloc::vec::Vec::with_capacity(key_range.len() * SLOT_ELEMENT_LEN_BYTES);
storage.resize(key_range.len() * SLOT_ELEMENT_LEN_BYTES, 0);
for chunk in storage.chunks_mut(SLOT_ELEMENT_LEN_BYTES) {
chunk.copy_from_slice(&trng.generate_key());
}
slot_mgr.write(&mut rram, key_range, &storage).unwrap();
}
// once all values are written, advance the IN_SYSTEM_BOOT_SETUP_DONE state
// safety: the offset is correct because we're pulling it from our pre-defined constants and
// those are manually checked.
unsafe { owc.inc(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() };
crate::println!("Secret ID init done.");
}
print_slots(&slot_mgr, &bao1x_hal::board::DATA_SLOTS);
check_and_fix_acls(&mut rram, &mut slot_mgr, &bao1x_hal::board::DATA_SLOTS);
if *board_type == bao1x_api::BoardTypeCoding::Baosec {
#[cfg(feature = "unsafe-debug")]
print_slots(&slot_mgr, &bao1x_hal::board::KEY_SLOTS);
check_and_fix_acls(&mut rram, &mut slot_mgr, &bao1x_hal::board::KEY_SLOTS);
}
}
fn check_and_fix_acls(rram: &mut Reram, slot_mgr: &mut SlotManager, slot_list: &[SlotIndex]) {
// now check & set any ACL bits that aren't set yet
for slot_element in slot_list.iter() {
let mut is_consistent = true;
let mut acl = match slot_mgr.get_acl(&slot_element) {
Ok(settings) => settings,
Err(bao1x_api::AccessError::KeyAclInconsistency(prototype)) => {
is_consistent = false;
AccessSettings::Key(prototype)
}
Err(bao1x_api::AccessError::DataAclInconsistency(prototype)) => {
is_consistent = false;
AccessSettings::Data(prototype)
}
_ => panic!("Unhandled error in get_acl()"),
};
let (pa, rw) = slot_element.get_access_spec();
let is_correct = match acl {
AccessSettings::Data(sa) => sa.get_partition_access() == pa && sa.get_rw_permissions() == rw,
AccessSettings::Key(sa) => sa.get_partition_access() == pa && sa.get_rw_permissions() == rw,
};
if !is_correct || !is_consistent {
crate::println!(
"Fixing ACL for {:?} (is_correct: {:?}, is_consistent: {:?})",
slot_element,
is_correct,
is_consistent
);
match &mut acl {
AccessSettings::Data(sa) => {
sa.set_partition_access(&pa);
sa.set_rw_permissions(rw);
}
AccessSettings::Key(sa) => {
sa.set_partition_access(&pa);
sa.set_rw_permissions(rw);
}
}
slot_mgr.set_acl(rram, slot_element, &acl).unwrap();
}
}
}
fn print_slots(slot_mgr: &SlotManager, slot_list: &[SlotIndex]) {
for slot in slot_list.iter() {
let access = slot.get_access_spec();
crate::println!("== Slot starting at {} ==", slot.get_base());
crate::println!(" Spec permissions: {:?}", access);
let slot_type = slot.get_type();
for (data_index, acl_index) in
slot.try_into_data_iter().unwrap().zip(slot.try_into_acl_iter().unwrap())
{
match slot_type {
// safety: we have checked the slot type before entering these low level functions
SlotType::Data => unsafe {
let bytes = slot_mgr.read_data_slot(data_index);
let acl = slot_mgr.get_data_acl(acl_index);
crate::println!(" Data {} ({:?}): {:x?}", data_index, acl, bytes);
},
SlotType::Key => unsafe {
let bytes = slot_mgr.read_key_slot(data_index);
let acl = slot_mgr.get_key_acl(acl_index);
crate::println!(" Key {} ({:?}): {:x?}", data_index, acl, bytes);
},
}
}
}
}

View file

@ -0,0 +1,190 @@
use bao1x_hal::iox::Iox;
use rand_chacha::ChaCha8Rng;
use rand_chacha::rand_core::RngCore;
use rand_chacha::rand_core::SeedableRng;
use utralib::*;
use xous_bio_bdma::*;
const BITS_PER_SAMPLE: usize = 4;
pub struct ManagedTrng {
ro_trng: bao1x_hal::sce::trng::Trng,
av_trng: Option<BioSharedState>,
csprng: ChaCha8Rng,
}
impl ManagedTrng {
pub fn new(board_type: &bao1x_api::BoardTypeCoding) -> Self {
let mut ro_trng = bao1x_hal::sce::trng::Trng::new(utra::trng::HW_TRNG_BASE);
ro_trng.setup_raw_generation(32);
let av_trng = if *board_type == bao1x_api::BoardTypeCoding::Baosec {
let mut bio_ss = BioSharedState::new();
let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
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(trng_power.0, trng_power.1, bao1x_api::IoxValue::High);
crate::delay(50); // 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
// check if the TRNG seems to be working. If not, reject the board setting and reboot
let mut timer = utralib::CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32);
timer.wfo(utra::timer0::EV_PENDING_ZERO, 1);
let av_good: bool;
let mut ms_passed = 0;
let mut samples_collected = 0;
const TIMEOUT_MS: usize = 10;
const SAMPLES_REQUIRED: usize = 10;
loop {
if timer.rf(utra::timer0::EV_PENDING_ZERO) != 0 {
ms_passed += 1;
timer.wfo(utra::timer0::EV_PENDING_ZERO, 1);
}
if ms_passed > TIMEOUT_MS {
av_good = false;
break;
}
if bio_ss.bio.rf(utra::bio_bdma::SFR_FLEVEL_PCLK_REGFIFO_LEVEL0) != 0 {
let _ = bio_ss.bio.r(utra::bio_bdma::SFR_RXF0);
samples_collected += 1;
ms_passed = 0;
}
if samples_collected > SAMPLES_REQUIRED {
av_good = true;
break;
}
}
if av_good {
Some(bio_ss)
} else {
crate::println!(
"AV TRNG is not present or functioning. Setting board type to dabao, and rebooting!"
);
let one_way = bao1x_hal::acram::OneWayCounter::new();
while one_way.get_decoded::<bao1x_api::BoardTypeCoding>().expect("owc coding error")
!= bao1x_api::BoardTypeCoding::Dabao
{
one_way.inc_coded::<bao1x_api::BoardTypeCoding>().expect("increment error");
}
// reset the system
let mut rcurst = CSR::new(utra::sysctrl::HW_SYSCTRL_BASE as *mut u32);
rcurst.wo(utra::sysctrl::SFR_RCURST0, 0x55AA);
// this is actually unreachable
None
}
} else {
None
};
// The first seed is always 0.
let mut seed = [0u8; 32];
// println!("seed: {:x?}", seed); // used to eyeball that things are working correctly
let mut csprng = ChaCha8Rng::from_seed(seed);
// Accumulate TRNG data into the seed (which starts at 0).
//
// 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
// from the minimum target of 128 bits. This process is done to hedge against
// potentially broken/damaged TRNGs that are hard to detect. In practice all the
// TRNGs are measured to generate at least 7.9 bits/byte of entropy, but this
// is a really important step so belt-and-suspenders are warranted.
for _ in 0..64 {
// extract the seed of the current version of the CSPRNG
seed = csprng.get_seed();
reseed(&mut ro_trng, &av_trng, &mut seed);
// Make a new CSPRNG from the old seed that was XOR'd with the TRNG data
csprng = ChaCha8Rng::from_seed(seed);
// 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(csprng.next_u64().to_le_bytes()) {
*s_byte ^= chacha_byte;
}
}
// Make a final version of the CSPRNG based on the mixed state.
csprng = ChaCha8Rng::from_seed(seed);
}
Self { ro_trng, av_trng, csprng }
}
pub fn generate_key(&mut self) -> [u8; 32] {
let mut key = [0u8; 32];
self.csprng.fill_bytes(&mut key);
// reseed the csprng with more random data
let mut seed = self.csprng.get_seed();
reseed(&mut self.ro_trng, &self.av_trng, &mut seed);
self.csprng = ChaCha8Rng::from_seed(seed);
// mix the reseeded data against the csprng itself
for s in seed.chunks_mut(8) {
for (s_byte, chacha_byte) in s.iter_mut().zip(self.csprng.next_u64().to_le_bytes()) {
*s_byte ^= chacha_byte;
}
}
self.csprng = ChaCha8Rng::from_seed(seed);
key
}
}
fn reseed(trng: &mut bao1x_hal::sce::trng::Trng, av_trng: &Option<BioSharedState>, seed: &mut [u8]) {
// XOR the seed with TRNG data
for s in seed.chunks_mut(4) {
let incoming = trng.get_u32().expect("TRNG error");
for (s_byte, &ro_byte) in s.iter_mut().zip(incoming.to_le_bytes().iter()) {
*s_byte ^= ro_byte;
}
// if the avalanche generator is available, use that too.
if let Some(bio_ss) = av_trng {
let mut raw32 = 0;
for _ in 0..(size_of::<u32>() * 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;
}
}
}
}
#[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
);