Merge pull request #757 from betrusted-io/simplify-keysetup

Boot security & stability improvements
This commit is contained in:
bunnie 2025-12-19 03:40:18 +08:00 committed by GitHub
commit 9334f22788
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 185 additions and 77 deletions

View file

@ -15,10 +15,10 @@ use alloc::collections::VecDeque;
use core::cell::RefCell;
use bao1x_api::pubkeys::{BOOT0_SELF_CHECK, BOOT0_TO_ALTBOOT1, BOOT0_TO_BOOT1};
use bao1x_api::{BOOT0_PUBKEY_FAIL, DEVELOPER_MODE, bollard};
use bao1x_api::{BOOT0_PUBKEY_FAIL, BOOT1_PUBKEY_FAIL, DEVELOPER_MODE, bollard};
use bao1x_api::{HardenedBool, PARANOID_MODE, PARANOID_MODE_DUPE};
use bao1x_hal::acram::OneWayCounter;
use bao1x_hal::hardening::{check_pll, die, mesh_setup};
use bao1x_hal::hardening::{Csprng, check_pll, die, mesh_setup};
use bao1x_hal::sigcheck::{hardened_erase_policy, jump_to};
#[cfg(feature = "unsafe-dev")]
use critical_section::Mutex;
@ -114,39 +114,26 @@ pub unsafe extern "C" fn rust_entry() -> ! {
bollard!(die, 4);
let owc = OneWayCounter::new();
// check that the boot0 pub keys match those burned into the indelible key area
// glitch_safety: I'd imagine that glitching in this routine would lead to good_compare being `false`,
// so no additional hardening is done.
let pubkey_ptr = bao1x_api::BOOT0_START as *const bao1x_api::signatures::SignatureInFlash;
let pk_src: &bao1x_api::signatures::SignatureInFlash = unsafe { pubkey_ptr.as_ref().unwrap() };
let reference_keys =
[bao1x_api::BAO1_PUBKEY, bao1x_api::BAO2_PUBKEY, bao1x_api::BETA_PUBKEY, bao1x_api::DEV_PUBKEY];
let slot_mgr = bao1x_hal::acram::SlotManager::new();
let mut good_compare = HardenedBool::TRUE;
for (boot0_key, ref_key) in pk_src.sealed_data.pubkeys.iter().zip(reference_keys.iter()) {
let ref_data = slot_mgr.read(&ref_key).unwrap();
if ref_data != &boot0_key.pk {
good_compare = HardenedBool::FALSE;
}
}
csprng.random_delay();
match good_compare.is_true() {
Some(false) => {
bollard!(die, 4);
// safety: the offset is from a pre-validated constant, which meets the safety requirement
unsafe {
owc.inc(BOOT0_PUBKEY_FAIL).unwrap();
}
// erase secrets if the boot0 pubkey doesn't check out.
bollard!(die, 4);
bao1x_hal::sigcheck::erase_secrets(&mut Some(&mut csprng))
.inspect_err(|e| crate::println!("{}", e))
.ok(); // "ok" because the expected error is a check on logic/configuration bugs, not attacks
}
Some(true) => (),
None => die(),
}
// check that the pubkeys in boot0 matches the reference keys
compare_refkeys(
&owc,
&slot_mgr,
&mut csprng,
bao1x_api::BOOT0_START as *const bao1x_api::signatures::SignatureInFlash,
BOOT0_PUBKEY_FAIL,
);
bollard!(die, 4);
// check that the pubkeys in boot1 matches the reference keys
compare_refkeys(
&owc,
&slot_mgr,
&mut csprng,
bao1x_api::BOOT1_START as *const bao1x_api::signatures::SignatureInFlash,
BOOT1_PUBKEY_FAIL,
);
bollard!(die, 4);
let (paranoid1, paranoid2) = owc.hardened_get2(PARANOID_MODE, PARANOID_MODE_DUPE).unwrap();
@ -251,3 +238,51 @@ fn print_ifr() {
}
crate::println!("");
}
/// check that pub keys in the images match those burned into the indelible key area
/// glitch_safety: I'd imagine that glitching in this routine would lead to good_compare being `false`,
/// so no additional hardening is done.
fn compare_refkeys(
owc: &OneWayCounter,
slot_mgr: &bao1x_hal::acram::SlotManager,
csprng: &mut Csprng,
pubkey_ptr: *const bao1x_api::signatures::SignatureInFlash,
fail_counter: usize,
) {
let reference_keys =
[bao1x_api::BAO1_PUBKEY, bao1x_api::BAO2_PUBKEY, bao1x_api::BETA_PUBKEY, bao1x_api::DEV_PUBKEY];
// check that the pub keys match those burned into the indelible key area
// glitch_safety: I'd imagine that glitching in this routine would lead to good_compare being `false`,
// so no additional hardening is done.
let pk_src: &bao1x_api::signatures::SignatureInFlash = unsafe { pubkey_ptr.as_ref().unwrap() };
let mut good_compare = HardenedBool::TRUE;
for (boot0_key, ref_key) in pk_src.sealed_data.pubkeys.iter().zip(reference_keys.iter()) {
let ref_data = slot_mgr.read(&ref_key).unwrap();
if ref_data != &boot0_key.pk {
good_compare = HardenedBool::FALSE;
}
}
csprng.random_delay();
match good_compare.is_true() {
Some(false) => {
bollard!(die, 4);
// don't over-increment this to avoid RRAM wear-out. However, do allow it to increment to higher
// than 1 so we have a higher hamming distance on the counter than a single bit.
if owc.get(fail_counter).unwrap() < 15 {
// safety: the offset is from a pre-validated constant, which meets the safety requirement
unsafe {
owc.inc(fail_counter).unwrap();
}
}
// erase secrets (or ensure they are erased) if the boot pubkey doesn't check out.
bollard!(die, 4);
bao1x_hal::sigcheck::erase_secrets(&mut Some(csprng))
.inspect_err(|e| crate::println!("{}", e))
.ok(); // "ok" because the expected error is a check on logic/configuration bugs, not attacks
}
Some(true) => (),
None => die(),
}
bollard!(die, 4);
}

View file

@ -141,7 +141,8 @@ pub fn early_init() -> Csprng {
// external clock could make the chip very exploitable. See inside the function for details.
let perclk = unsafe { init_clock_asic_350mhz() };
crate::println!("scratch page: {:x}, heap start: {:x}", SCRATCH_PAGE, HEAP_START);
// crate::println!("scratch page: {:x}, heap start: {:x}", SCRATCH_PAGE, HEAP_START);
// the CSPRNG is built *after* we go to high speed mode. Note the discipline that after every
// print, we insert a random_delay - so that you can't use the print as a reliable trigger.
let mut csprng = Csprng::new();
@ -249,8 +250,8 @@ pub fn setup_timer() {
pub fn setup_alloc() {
// Initialize the allocator with heap memory range
crate::println!("Setting up heap @ {:x}-{:x}", HEAP_START, HEAP_START + HEAP_LEN);
crate::println!("Stack @ {:x}-{:x}", HEAP_START + HEAP_LEN, RAM_BASE + RAM_SIZE);
// crate::println!("Setting up heap @ {:x}-{:x}", HEAP_START, HEAP_START + HEAP_LEN);
// crate::println!("Stack @ {:x}-{:x}", HEAP_START + HEAP_LEN, RAM_BASE + RAM_SIZE);
unsafe {
ALLOCATOR.lock().init(HEAP_START as *mut u8, HEAP_LEN);
}
@ -342,7 +343,6 @@ mod panic_handler {
/// speed makes glitches more difficult to time. We also don't want any risk of a glitch bypassing
/// the PLL.
pub unsafe fn init_clock_asic_350mhz() -> u32 {
let freq_hz = 350_000_000;
use utra::sysctrl;
let daric_cgu = sysctrl::HW_SYSCTRL_BASE as *mut u32;
let mut cgu = CSR::new(daric_cgu);
@ -400,16 +400,23 @@ pub unsafe fn init_clock_asic_350mhz() -> u32 {
bao1x_api::bollard!(4);
}
// The frequency of boot0 is ever so slightly different than that of boot1. This originated
// from a bug in the chip - the fractional divider on the PLL doesn't work - but actually
// I currently like that the boot0 PLL is a little different from boot1 PLL from a security
// perspective, because it means any timing worked out on boot0 isn't going to map perfectly
// onto boot1 (the difference is 348MHz vs the target 350MHz; the VCO also runs at a
// lower frequency so it will have different stability & recovery against glitches)
// hard-coded so that there's less chances for glitches to muck with PLL parameters
cgu.wo(sysctrl::SFR_IPCPLLMN, 0x3057);
cgu.wo(sysctrl::SFR_IPCPLLF, 0x1800000);
cgu.wo(sysctrl::SFR_IPCPLLF, 0x0800000); // frac turned off - it doesn't work
cgu.wo(sysctrl::SFR_IPCPLLQ, 0x3311);
cgu.wo(sysctrl::SFR_IPCCR, 0x53);
bao1x_api::bollard!(6);
// written twice - this is safe to do, because values don't take hold until ARIPFLOW is triggered
cgu.wo(sysctrl::SFR_IPCPLLMN, 0x3057);
cgu.wo(sysctrl::SFR_IPCPLLF, 0x1800000);
cgu.wo(sysctrl::SFR_IPCPLLF, 0x0800000); // frac turned off - it doesn't work
cgu.wo(sysctrl::SFR_IPCPLLQ, 0x3311);
cgu.wo(sysctrl::SFR_IPCCR, 0x53);
cgu.wo(sysctrl::SFR_IPCARIPFLOW, 0x32);
@ -435,7 +442,7 @@ pub unsafe fn init_clock_asic_350mhz() -> u32 {
bao1x_hal::hardening::check_pll();
// pll print is put after the routine, so it can't be used as a glitch trigger
crate::println!("PLL configured to {} MHz", freq_hz / 1_000_000);
// crate::println!("PLL configured to 348 MHz");
/*
// these are the prints used to instrument the normal clock setting flow to derive the constants

View file

@ -424,6 +424,10 @@ impl Repl {
crate::println!("== BOOT0 REPORTED PUBKEY CHECK FAILURE ==");
secure = false;
}
if owc.get(BOOT1_PUBKEY_FAIL).unwrap() != 0 {
crate::println!("== BOOT1 REPORTED PUBKEY CHECK FAILURE ==");
secure = false;
}
if owc.get(CP_BOOT_SETUP_DONE).unwrap() == 0 {
crate::println!("== CP SETUP FAILED ==");
secure = false;

View file

@ -151,6 +151,10 @@ pub const OEM_MODE: usize = 86;
/// This is incremented if the boot0 public keys failed to compare against the static keys in
/// the data store.
pub const BOOT0_PUBKEY_FAIL: usize = 87;
/// This is incremented if the boot1 public keys failed to compare against the static keys in
/// the data store. Note that on Alpha-rev dabaos, this was used to track the initialization
/// of dabao security state, and so this may be set already due to that use.
pub const BOOT1_PUBKEY_FAIL: usize = 88;
encode_oneway! {
#[offset = 90]

View file

@ -68,11 +68,7 @@ pub const BOOT0_TO_BOOT1: SecurityConfiguration = SecurityConfiguration {
image_ptr: crate::BOOT1_START as *const u32,
pubkey_ptr: crate::BOOT0_START as *const u32,
revocation_owc: crate::BOOT0_REVOCATION_OFFSET,
function_codes: &[
FunctionCode::Boot1 as u32,
FunctionCode::UpdatedBoot1 as u32,
FunctionCode::Developer as u32,
],
function_codes: &[FunctionCode::Boot1 as u32, FunctionCode::UpdatedBoot1 as u32],
};
/// This is different from a jump directly to loader/baremetal because the
@ -81,11 +77,7 @@ pub const BOOT0_TO_ALTBOOT1: SecurityConfiguration = SecurityConfiguration {
image_ptr: crate::LOADER_START as *const u32,
pubkey_ptr: crate::BOOT0_START as *const u32,
revocation_owc: crate::BOOT0_REVOCATION_OFFSET,
function_codes: &[
FunctionCode::Boot1 as u32,
FunctionCode::UpdatedBoot1 as u32,
FunctionCode::Developer as u32,
],
function_codes: &[FunctionCode::Boot1 as u32, FunctionCode::UpdatedBoot1 as u32],
};
pub const BOOT1_TO_LOADER_OR_BAREMETAL: SecurityConfiguration = SecurityConfiguration {
@ -97,7 +89,6 @@ pub const BOOT1_TO_LOADER_OR_BAREMETAL: SecurityConfiguration = SecurityConfigur
FunctionCode::UpdatedBaremetal as u32,
FunctionCode::Loader as u32,
FunctionCode::UpdatedLoader as u32,
FunctionCode::Developer as u32,
],
};
@ -105,11 +96,7 @@ pub const LOADER_TO_KERNEL: SecurityConfiguration = SecurityConfiguration {
image_ptr: crate::KERNEL_START as *const u32,
pubkey_ptr: crate::LOADER_START as *const u32,
revocation_owc: crate::LOADER_REVOCATION_OFFSET,
function_codes: &[
FunctionCode::Kernel as u32,
FunctionCode::UpdatedKernel as u32,
FunctionCode::Developer as u32,
],
function_codes: &[FunctionCode::Kernel as u32, FunctionCode::UpdatedKernel as u32],
};
pub const LOADER_TO_DETACHED_APP: SecurityConfiguration = SecurityConfiguration {

View file

@ -39,8 +39,6 @@ pub enum FunctionCode {
/// Application region
App = 0x10_0000,
UpdatedApp = 0x10_0001,
/// Developer use - can go in any region, but only usable with secrets wiped.
Developer = 0x1000_0000,
}
pub const BAOCHIP_SIG_VERSION: u32 = 0x1_00;

View file

@ -139,3 +139,56 @@ macro_rules! println
$crate::print!(concat!($fmt, "\r\n"), $($args)+)
});
}
// ==== DUART-only debug print ====
// Used for forcing the use of DUART in debugging
pub struct Duart {}
impl Duart {
/// Print a character
pub fn putc(&self, c: u8) {
let base = utra::duart::HW_DUART_BASE as *mut u32;
let mut uart = CSR::new(base);
if uart.rf(utra::duart::SFR_CR_SFR_CR) == 0 {
uart.wfo(utra::duart::SFR_CR_SFR_CR, 1);
}
while uart.r(utra::duart::SFR_SR) != 0 {}
uart.wo(utra::duart::SFR_TXD, c as u32);
}
}
impl Write for Duart {
fn write_str(&mut self, s: &str) -> Result<(), Error> {
for c in s.bytes() {
self.putc(c);
}
Ok(())
}
}
#[macro_use]
/// Hardware debug print module
pub mod debug_print_duart {
#[macro_export]
macro_rules! print_d
{
($($args:tt)+) => ({
use core::fmt::Write;
let _ = write!(crate::debug::Duart {}, $($args)+);
});
}
}
#[macro_export]
macro_rules! println_d
{
() => ({
$crate::print_d!("\r\n")
});
($fmt:expr) => ({
$crate::print_d!(concat!($fmt, "\r\n"))
});
($fmt:expr, $($args:tt)+) => ({
$crate::print_d!(concat!($fmt, "\r\n"), $($args)+)
});
}

View file

@ -16,7 +16,10 @@ use crate::sigcheck::erase_secrets;
///
/// Pick a number that has a high hamming distance from 0 - and so, prefer e.g. 127 vs 128.
pub const WIPE_THRESHOLD: u32 = 127;
const DISTURB_THRESHOLD: u32 = 3;
/// This number is empirically tuned. The main issue is we don't want to notch up the
/// counter during "slow shutdowns" where the power supply falls gradually enough that
/// the glitch detector can fire.
const DISTURB_THRESHOLD: u32 = 2;
/// This is the range of delays we will pick from whenever we attempt a random delay,
/// expressed as a number of bits.
@ -41,6 +44,7 @@ pub fn check_pll() {
pub fn die() -> ! {
let owc = OneWayCounter::new();
// safety: this is safe because the offset is from a checked, pre-defined value
crate::println_d!("die!die!die!die!");
unsafe {
owc.inc(POSSIBLE_ATTACKS).unwrap();
}
@ -272,6 +276,7 @@ pub fn mesh_check_and_react(csprng: &mut Csprng, one_way: &OneWayCounter) {
unsafe {
one_way.inc(bao1x_api::POSSIBLE_ATTACKS).unwrap();
}
crate::println_d!("mesh");
} else {
die();
}
@ -282,6 +287,7 @@ pub fn mesh_check_and_react(csprng: &mut Csprng, one_way: &OneWayCounter) {
unsafe {
one_way.inc(bao1x_api::POSSIBLE_ATTACKS).unwrap();
}
crate::println_d!("mesh");
} else {
die();
}
@ -352,10 +358,10 @@ pub fn glitch_handler(attacks_since_boot: u32) {
let reason = irq13.r(utra::irqarray13::EV_PENDING);
let mut was_sensor = false;
// figure out which subsystem glitched
let sensor = irq15.r(utra::irqarray15::EV_PENDING);
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
if reason & 0x8 != 0 {
// figure out which subsystem glitched
let sensor = irq15.r(utra::irqarray15::EV_PENDING);
const GLUE_MASK: u32 = 1 << 0;
const SENSOR_MASK: u32 = 1 << 1;
const MESH_MASK: u32 = 1 << 2;
@ -371,6 +377,13 @@ pub fn glitch_handler(attacks_since_boot: u32) {
crate::hardening::reset_sensors();
was_sensor = true;
}
// this transfers the code to a set of GPIOs that can be observed on dabao
#[cfg(feature = "debug-countermeasures")]
{
let iox = crate::iox::Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
iox.set_gpio_bank(bao1x_api::IoxPort::PC, (sensor as u16 & 0x7) << 9, 0b0000_1110_0000_0000);
}
irq15.wo(utra::irqarray15::EV_PENDING, sensor);
}
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
@ -384,14 +397,12 @@ pub fn glitch_handler(attacks_since_boot: u32) {
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
// safety: this is safe because the offset is from a checked, pre-defined value
unsafe {
// the increment is just OK'd because if for some reason it fails we still want
// to execute the following code.
owc.inc(bao1x_api::POSSIBLE_ATTACKS).ok();
}
let attacks = owc.get(bao1x_api::POSSIBLE_ATTACKS).unwrap_or(WIPE_THRESHOLD + 1);
// on the paranoid path: wipe secrets if we exceed a wipe threshold
// this path is measuring the accumulated attacks so far - the assumption is that a glitch attack
// will have to "search" for the right timing with multiple tries, and thus this would rapidly be
// triggered while doing the search.
let (paranoid1, paranoid2) =
owc.hardened_get2(bao1x_api::PARANOID_MODE, bao1x_api::PARANOID_MODE_DUPE).unwrap();
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
@ -410,7 +421,16 @@ pub fn glitch_handler(attacks_since_boot: u32) {
// on the non-paranoid path: just wipe NV elements & halt if we see a lower threshold of attacks
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
// this could be glitched over, but you'd have to have a repeatable glitch to skip it every time
if attacks_since_boot > DISTURB_THRESHOLD {
// don't start logging possible attacks until we've seen more than DISTURB_THRESHOLD
// Reason: the sensors are naturally triggered during a slow power-off or power-on
// and we want to filter out those transients.
unsafe {
// the increment is just OK'd because if for some reason it fails we still want
// to execute the following code.
owc.inc(bao1x_api::POSSIBLE_ATTACKS).ok();
}
// even output something on the DUART - this could be used as a trigger to prevent shutdown
// but at this point diagnostics are useful for seeing why the system shut down unexpectedly.
#[cfg(feature = "debug-countermeasures")]

View file

@ -292,7 +292,7 @@ pub fn erase_secrets(csprng: &mut Option<&mut Csprng>) -> Result<(), String> {
// safety: these words are excluded from the hash check because we need to pass from boot0 through
// to the loader, but the "hard reset" check happens only in boot1
unsafe {
buram.store_slice_no_hash(&[0u8; 32], crate::buram::ERASURE_PROOF_RANGE_BYTES.start);
buram.store_slice_no_hash(&[0u8; 32], ERASURE_PROOF_RANGE_BYTES.start);
}
let mut zero_key_count = 0;
@ -305,6 +305,7 @@ pub fn erase_secrets(csprng: &mut Option<&mut Csprng>) -> Result<(), String> {
csprng.as_deref_mut().map(|rng| rng.random_delay());
if slot.get_type() == SlotType::Data {
let (_pa, rw_perms) = slot.get_access_spec();
let mut erased_keys = 0;
for data_index in slot.try_into_data_iter().unwrap() {
bollard!(die_no_std, 4);
csprng.as_deref_mut().map(|rng| rng.random_delay());
@ -345,13 +346,19 @@ pub fn erase_secrets(csprng: &mut Option<&mut Csprng>) -> Result<(), String> {
rcurst.wo(utralib::utra::sysctrl::SFR_RCURST0, 0x55AA);
*/
} else {
crate::println!("Key range at {} confirmed erased", slot.get_base());
erased_keys += 1;
}
}
_ => {}
}
bollard!(die_no_std, 4);
}
crate::println!(
"Key range at {}: {}/{} keys confirmed erased",
slot.get_base(),
erased_keys,
slot.len()
);
bollard!(die_no_std, 4);
}
bollard!(die_no_std, 4);

View file

@ -249,15 +249,7 @@ fn main() -> ! {
let mut buf = unsafe {
xous_ipc::Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
};
#[cfg(feature = "timestamp")]
buf.replace(version::get_version()).unwrap();
#[cfg(not(feature = "timestamp"))]
{
let v = crate::api::VersionString {
version: String::from("--no-timestamp requested for build"),
};
buf.replace(v).unwrap();
}
}
api::Opcode::LockMutex => {

View file

@ -211,7 +211,8 @@ pub fn sign_image(
Some("kernel") => FunctionCode::Kernel,
Some("app") => FunctionCode::App,
Some("swap") => FunctionCode::Swap,
_ => FunctionCode::Developer,
Some("baremetal") => FunctionCode::Baremetal,
_ => panic!("Invalid function code"),
};
let mut header = SignatureInFlash::default();
header.sealed_data.version = version as u32;