Merge pull request #751 from betrusted-io/boot-hardening-2

More Boot hardening
This commit is contained in:
bunnie 2025-12-06 20:52:14 +03:00 committed by GitHub
commit 4b3369a767
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
21 changed files with 380 additions and 99 deletions

View file

@ -15,7 +15,7 @@ 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, bollard};
use bao1x_api::{BOOT0_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};
@ -172,6 +172,25 @@ pub unsafe extern "C" fn rust_entry() -> ! {
bollard!(die, 4);
// == end self validation ==
// If the developer bit is set, ensure that keys are erased. The edge case we're worried about is
// if an attacker sets developer bit, even with signed images - this can allow for an easier
// time of booting a malicious kernel because we can't erase secret keys inside the loader
// due to access restrictions.
csprng.random_delay();
let (dev1, dev2) = owc.hardened_get(DEVELOPER_MODE).unwrap();
if dev1 != 0 {
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
}
bollard!(die, 4);
csprng.random_delay();
if dev2 != 0 {
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
}
bollard!(die, 4);
let boot_order = match owc.get_decoded::<bao1x_api::AltBootCoding>() {
// Primary boot selected. Check Boot1 first, then fall back to LOADER/BAREMETAL.

View file

@ -9,10 +9,8 @@ use utralib::utra;
use utralib::utra::sysctrl;
#[cfg(feature = "unsafe-dev")]
use crate::platform::{
debug::setup_rx,
irq::{enable_irq, irq_setup},
};
use crate::platform::debug::setup_rx;
use crate::platform::irq::{enable_irq, irq_setup};
#[global_allocator]
static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty();
@ -149,6 +147,31 @@ pub fn early_init() -> Csprng {
let mut csprng = Csprng::new();
csprng.random_delay();
irq_setup();
// set up the reactive sensors
bao1x_api::bollard!(4);
bao1x_hal::hardening::reset_sensors();
bao1x_api::bollard!(4);
bollard!(die, 4);
csprng.random_delay();
// ensure paranoid mode is respected
if paranoid2 != 0 {
bollard!(die, 4);
paranoid_mode();
}
// set up IRQ to respond to all possible sensor errors
let mut irq13 = CSR::new(utra::irqarray13::HW_IRQARRAY13_BASE as *mut u32);
irq13.wo(utra::irqarray13::EV_EDGE_TRIGGERED, 0xFFFF_FFFF);
irq13.wo(utra::irqarray13::EV_POLARITY, 0xFFFF_FFFF);
irq13.wo(utra::irqarray13::EV_PENDING, 0xFFFF_FFFF);
irq13.wo(utra::irqarray13::EV_ENABLE, 0xFFFF_FFFF);
enable_irq(utra::irqarray13::IRQARRAY13_IRQ);
csprng.random_delay();
if paranoid1 != 0 {
bollard!(die, 4);
paranoid_mode();
}
// setup heap alloc
// glitch_safety: failing to initialize this will generally cause heap allocs to hang
setup_alloc();
@ -193,7 +216,6 @@ pub fn early_init() -> Csprng {
#[cfg(feature = "unsafe-dev")]
let mut udma_uart = {
let mut udma_uart = setup_rx(perclk);
irq_setup();
enable_irq(utra::irqarray5::IRQARRAY5_IRQ);
udma_uart
};

View file

@ -1,13 +1,12 @@
#[cfg(feature = "unsafe-dev")]
use riscv::register::mstatus;
use riscv::register::{mcause, mie};
#[cfg(feature = "unsafe-dev")]
use vexriscv::register::vexriscv::mim;
use vexriscv::register::vexriscv::mip;
use crate::*;
#[cfg(feature = "unsafe-dev")]
static ATTACKS_SINCE_BOOT: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
pub fn irq_setup() {
unsafe {
#[rustfmt::skip]
@ -28,7 +27,6 @@ pub fn irq_setup() {
unsafe { mie::set_mext() };
}
#[cfg(feature = "unsafe-dev")]
pub fn enable_irq(irq_no: usize) {
// Note that the vexriscv "IRQ Mask" register is inverse-logic --
// that is, setting a bit in the "mask" register unmasks (i.e. enables) it.
@ -195,12 +193,17 @@ pub extern "C" fn trap_handler(
} else if (irqs_pending & (1 << utra::irqarray5::IRQARRAY5_IRQ)) != 0 {
#[cfg(feature = "unsafe-dev")]
crate::uart_irq_handler();
} else if (irqs_pending & (1 << utra::irqarray2::IRQARRAY2_IRQ)) != 0 {
// just clear it for now
let mut irqarray2 = CSR::new(utralib::HW_IRQARRAY2_BASE as *mut u32);
let pending = irqarray2.r(utra::irqarray2::EV_PENDING);
crate::println!("keypress interrupt {:x}", pending);
irqarray2.wo(utra::irqarray2::EV_PENDING, pending);
} else if (irqs_pending & (1 << utra::irqarray13::IRQARRAY13_IRQ)) != 0 {
// irq13 -> {aoramerr, secirq, ifsuberr, sceerr, coresuberr}
// this IRQ will trigger an attack response if any of the sensors trigger *or*
// if the ECC-protected memory banks trigger an ECC error
bao1x_hal::hardening::glitch_handler(
ATTACKS_SINCE_BOOT.fetch_add(1, core::sync::atomic::Ordering::SeqCst),
);
} else if (irqs_pending & (1 << utra::irqarray15::IRQARRAY15_IRQ)) != 0 {
// irq15 -> {meshirq, sensorcirq, glcirq}
// those one is kind of redundant with irq13 in this scenario, because secirq is the OR
// of all three IRQs going into this array. So, we handle this simply in irqarray13.
}
}

View file

@ -71,7 +71,10 @@ pub fn setup_backup_region() -> u32 {
let mut bu_mgr = bao1x_hal::buram::BackupManager::new();
if !bu_mgr.is_backup_valid() {
// zeroize the backup RAM
bu_mgr.bu_ram_as_mut().fill(0);
// safety: make_valid is called after this is done.
unsafe {
bu_mgr.bu_ram_as_mut().fill(0);
}
// calculate the hash and mark as valid
bu_mgr.make_valid();
@ -145,6 +148,16 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa
crate::println!("backup region is clean!");
}
irq_setup();
// all sensors & IRQs setup already by boot0, but it doesn't hurt to re-write these registers
// in case they were defeated somehow previously
let mut irq13 = CSR::new(utra::irqarray13::HW_IRQARRAY13_BASE as *mut u32);
irq13.wo(utra::irqarray13::EV_EDGE_TRIGGERED, 0xFFFF_FFFF);
irq13.wo(utra::irqarray13::EV_POLARITY, 0xFFFF_FFFF);
irq13.wo(utra::irqarray13::EV_ENABLE, 0xFFFF_FFFF);
// enable the IRQ because it was disabled by the previous stage's exit
enable_irq(utra::irqarray13::IRQARRAY13_IRQ);
let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
// setup board-specific I/Os - early boot set. These are items that have to be
@ -340,7 +353,6 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa
// Rx setup
let _udma_uart = setup_console(&board_type, &iox, perclk);
irq_setup();
enable_irq(utra::irqarray5::IRQARRAY5_IRQ);
crate::debug::USE_CONSOLE.store(true, core::sync::atomic::Ordering::SeqCst);

View file

@ -6,6 +6,8 @@ use vexriscv::register::vexriscv::{mim, mip};
use crate::usb::USB;
use crate::*;
static ATTACKS_SINCE_BOOT: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
pub fn irq_setup() {
unsafe {
#[rustfmt::skip]
@ -212,12 +214,17 @@ pub extern "C" fn trap_handler(
timer0.wfo(utra::timer0::RELOAD_RELOAD, (DEFAULT_FCLK_FREQUENCY / 1_000) * ms);
} else if (irqs_pending & (1 << utra::irqarray5::IRQARRAY5_IRQ)) != 0 {
crate::uart_irq_handler();
} else if (irqs_pending & (1 << utra::irqarray2::IRQARRAY2_IRQ)) != 0 {
// just clear it for now
let mut irqarray2 = CSR::new(utralib::HW_IRQARRAY2_BASE as *mut u32);
let pending = irqarray2.r(utra::irqarray2::EV_PENDING);
crate::println!("keypress interrupt {:x}", pending);
irqarray2.wo(utra::irqarray2::EV_PENDING, pending);
} else if (irqs_pending & (1 << utra::irqarray13::IRQARRAY13_IRQ)) != 0 {
// irq13 -> {aoramerr, secirq, ifsuberr, sceerr, coresuberr}
// this IRQ will trigger an attack response if any of the sensors trigger *or*
// if the ECC-protected memory banks trigger an ECC error
bao1x_hal::hardening::glitch_handler(
ATTACKS_SINCE_BOOT.fetch_add(1, core::sync::atomic::Ordering::SeqCst),
);
} else if (irqs_pending & (1 << utra::irqarray15::IRQARRAY15_IRQ)) != 0 {
// irq15 -> {meshirq, sensorcirq, glcirq}
// those one is kind of redundant with irq13 in this scenario, because secirq is the OR
// of all three IRQs going into this array. So, we handle this simply in irqarray13.
}
if (irqs_pending & (1 << utralib::utra::irqarray1::IRQARRAY1_IRQ)) != 0 {
// handle USB interrupt

View file

@ -23,6 +23,8 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) {
let mut rram = Reram::new();
// check the lifecycle status
// glitch_safety: this is done in a controlled environment, and not done again later,
// so we don't need to harden it. If it is repeated due to a glitch it actually leads to data loss.
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.
@ -72,52 +74,6 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) {
crate::println!("Public ID init done.");
}
// Delegate in-system key setup to the OS. Don't do it in the bootloader. This code is
// too hard to get right to be doing it here, and there is no ostensible security advantage
// in doing it at this stage versus in the system. Reasoning: the in-system key setup would
// be done in the factory, post-wafer probe, regardless. Whether it's hard-coded into the boot1
// stage or left to be flexible based on the OS's needs doesn't make a difference because the
// point of keying is still going to be the factory.
/*
if (*board_type == bao1x_api::BoardTypeCoding::Baosec
&& owc.get(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() == 0)
|| (*board_type == bao1x_api::BoardTypeCoding::Dabao
&& owc.get(bao1x_api::INVOKE_DABAO_KEY_SETUP).unwrap() != 0
&& owc.get(bao1x_api::DABAO_KEY_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
let key_set = if *board_type == bao1x_api::BoardTypeCoding::Baosec {
&bao1x_api::baosec::KEY_SLOTS[..]
} else {
&bao1x_api::dabao::KEY_SLOTS[..]
};
for key_range in key_set.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());
}
match slot_mgr.write(&mut rram, key_range, &storage) {
Ok(_) => {}
Err(e) => {
crate::println!("Couldn't initialize slot {:?}: {:?}", key_range, e);
}
}
}
// 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.
if *board_type == bao1x_api::BoardTypeCoding::Baosec {
unsafe { owc.inc(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() };
} else if *board_type == bao1x_api::BoardTypeCoding::Dabao {
unsafe { owc.inc(bao1x_api::DABAO_KEY_SETUP_DONE).unwrap() };
}
crate::println!("Secret ID init done.");
}
*/
#[cfg(feature = "print-ifr")]
print_ifr();
@ -128,11 +84,13 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) {
// wear-out on the ACL entries as every time a transition is made into a developer images, a set
// of keys are checked to be erased. While it is possible to bypass the ACL checks by flipping
// the developer mode bit, the key check/erasure would still happen upon launch into developer mode.
//
// glitch_safety: we don't harden this because this is already a "seatbelt" safety measure
// in most cases it should do nothing because the ACLs are already correct. Also, if DEVELOPER_MODE
// is tripped, there is a hardened check that ensures keys are erased when that bit is set.
#[cfg(feature = "unsafe-debug")]
print_slots(&slot_mgr, &bao1x_api::baosec::KEY_SLOTS); // this prints all the keys as they are created
if (*board_type == bao1x_api::BoardTypeCoding::Baosec || *board_type == bao1x_api::BoardTypeCoding::Dabao)
&& owc.get(bao1x_api::DEVELOPER_MODE).unwrap() == 0
{
if owc.get(bao1x_api::DEVELOPER_MODE).unwrap() == 0 {
#[cfg(feature = "unsafe-debug")]
print_slots(&slot_mgr, &bao1x_api::baosec::KEY_SLOTS);
check_and_fix_acls(&mut rram, &mut slot_mgr, &bao1x_api::baosec::KEY_SLOTS);

View file

@ -1,4 +1,6 @@
use bao1x_api::{PARANOID_MODE, PARANOID_MODE_DUPE, bollard, pubkeys::BOOT1_TO_LOADER_OR_BAREMETAL};
use bao1x_api::{
DEVELOPER_MODE, PARANOID_MODE, PARANOID_MODE_DUPE, bollard, pubkeys::BOOT1_TO_LOADER_OR_BAREMETAL,
};
use bao1x_hal::hardening::Csprng;
#[inline(always)]
@ -19,6 +21,22 @@ fn seal_boot1_keys() {
pub fn try_boot(or_die: bool, csprng: &mut Csprng) {
let one_way = bao1x_hal::acram::OneWayCounter::new();
bollard!(bao1x_hal::sigcheck::die_no_std, 4);
// If the developer bit is set, ensure that keys are erased. The edge case we're worried about is
// if an attacker sets developer bit, even with signed images - this can allow for an easier
// time of booting a malicious kernel because we can't erase secret keys inside the loader
// due to access restrictions.
csprng.random_delay();
let (dev1, dev2) = one_way.hardened_get(DEVELOPER_MODE).unwrap();
if dev1 != 0 {
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
}
bollard!(bao1x_hal::sigcheck::die_no_std, 4);
csprng.random_delay();
if dev2 != 0 {
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
}
csprng.random_delay();
let (paranoid1, paranoid2) = one_way.hardened_get2(PARANOID_MODE, PARANOID_MODE_DUPE).unwrap();
csprng.random_delay();

View file

@ -116,6 +116,19 @@ pub const NUISANCE_KEYS: [SlotIndex; 2] = [NUISANCE_KEYS_0, NUISANCE_KEYS_1];
/// running your own code on the device).
pub const CHAFF_KEYS: SlotIndex = SlotIndex::DataRange(128..256, PartitionAccess::Fw0, RwPerms::ReadWrite);
/// This is intentionally the very last key in the chaff key range. It's "sampled" by copying
/// the full value of this key into the BURAM, which is later passed on to the loader. It's then
/// checked for a value being equal to the erasure value to confirm that a device is in developer
/// mode or not. This process does introduce a risk that this one key is leaked but it also
/// closes a loophole where an attacker can simply manipulate the value of the DEVELOPER_KEY
/// one way counter and fool the system into running a developer-key signed image without the
/// secret keys being erased.
///
/// Placing this at the end of the key array ostensibly means that all the keys before it were
/// erased; it might be possible to glitch all the way to the end and just have this one erased
/// but I think that is reasonably unlikely...
pub const ERASE_PROOF: SlotIndex = SlotIndex::Data(256, PartitionAccess::Fw0, RwPerms::ReadWrite);
/// All the slots of concern located in a single iterator. The idea is that everything is
/// condensed here and used to check for access integrity using the array below.
pub const DATA_SLOTS: [SlotIndex; 8] = [

View file

@ -10,7 +10,7 @@ pub const BOOT1_START: usize = 0x6002_0000;
pub const LOADER_START: usize = 0x6006_0000;
pub const BAREMETAL_START: usize = LOADER_START;
// kernel needs to start on a page boundary, so eat into the loader area a bit to allow that to happen.
pub const KERNEL_START: usize = 0x6008_0000 - crate::signatures::SIGBLOCK_LEN;
pub const KERNEL_START: usize = 0x600A_0000 - crate::signatures::SIGBLOCK_LEN;
// total storage area available in RRAM. Above this are reserved vectors for security apparatus.
pub const RRAM_STORAGE_LEN: usize = 0x3D_A000;

View file

@ -43,6 +43,7 @@ pub const DATA_SLOTS: [SlotIndex; 8] = [
crate::offsets::DEV_PUBKEY,
];
pub use crate::baosec::ERASE_PROOF;
pub use crate::baosec::{
CHAFF_KEYS, NUISANCE_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, RMA_KEY, ROOT_SEED, THE_FLAG_1,
};

View file

@ -102,8 +102,9 @@ mpw = ["utralib/bao1x"]
hdl-test = ["utralib/bao1x"]
verbose-debug = []
debug-print = []
debug-print-duart = ["debug-print"]
debug-print-duart = ["debug-print", "debug-countermeasures"]
debug-print-uart = ["debug-print"]
debug-countermeasures = []
udma-stress-test = [
] # For RTL simulation testing - aggravates a key corner case

View file

@ -360,8 +360,8 @@ impl SlotManager {
/// Safety: the caller must resolve the index into either the data or the key array correctly.
/// There is access or type checking done. This is a "raw read" primitive mostly used for debugging.
pub unsafe fn read_data_slot(&self, absolute_offset: usize) -> &[u8] {
let ptr: *const u8 = &self.data_range.as_slice::<u8>()[absolute_offset] as *const u8;
crate::println!("data loc: {:x}, offset: {:x}", ptr as usize, absolute_offset);
// let ptr: *const u8 = &self.data_range.as_slice::<u8>()[absolute_offset] as *const u8;
// crate::println!("data loc: {:x}, offset: {:x}", ptr as usize, absolute_offset);
&self.data_range.as_slice()[absolute_offset..absolute_offset + SLOT_ELEMENT_LEN_BYTES]
}

View file

@ -6,6 +6,8 @@ const HASH_LOC: usize = 0;
#[allow(dead_code)]
const RESERVED_LOC: usize = 1;
pub const ERASURE_PROOF_RANGE_BYTES: Range<usize> = 0..32;
use crate::buram::murmur3::murmur3_32;
const fn range_len(r: Range<usize>) -> usize { r.end - r.start }
@ -86,9 +88,28 @@ impl BackupManager {
}
}
pub fn bu_ram_as_slice(&self) -> &[u8] { unsafe { self.bu_ram.as_slice() } }
pub fn store_slice<T: Copy>(&mut self, input: &[T], byte_offset: usize) {
let type_offset = byte_offset / size_of::<T>();
// safety: safe because make_valid() is called after the slice is accessed
let dest: &mut [T] = unsafe { &mut self.bu_ram_as_mut()[type_offset..type_offset + input.len()] };
dest.copy_from_slice(&input);
pub fn bu_ram_as_mut(&mut self) -> &mut [u8] { unsafe { self.bu_ram.as_slice_mut() } }
self.make_valid();
}
pub fn get_slice<T>(&self, byte_range: core::ops::Range<usize>) -> &[T] {
let type_offset = byte_range.start / size_of::<T>();
let type_len = (byte_range.end - byte_range.start) / size_of::<T>();
&self.bu_ram_as_slice()[type_offset..type_offset + type_len]
}
pub fn bu_ram_as_slice<T>(&self) -> &[T] { unsafe { self.bu_ram.as_slice::<T>() } }
/// Safety: modifications to the backup RAM array need a follow-up call to `make_valid`
/// in order for the boot check to pass.
///
/// Could try to get clever and implement a `Drop` trait which includes a make_valid() call? maybe?
pub unsafe fn bu_ram_as_mut<T>(&mut self) -> &mut [T] { self.bu_ram.as_slice_mut::<T>() }
}
pub mod murmur3 {

View file

@ -9,6 +9,15 @@ use utralib::*;
use crate::acram::OneWayCounter;
use crate::sigcheck::erase_secrets;
/// use a large threshold initially, under the theory that e.g. fault injections tend
/// to take thousands of iterations to succeed, and we really don't want to accidentally
/// wipe customer data. For now, the policy is to only wipe to those who have consented
/// by turning on paranoid mode.
///
/// 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 is the range of delays we will pick from whenever we attempt a random delay,
/// expressed as a number of bits.
const DELAY_MARGIN_BITS: u64 = 8;
@ -97,7 +106,7 @@ impl Csprng {
word.copy_from_slice(&ro_trng.get_raw().to_ne_bytes());
}
crate::println!("seed: {:x?}", seed); // used to eyeball that things are working correctly
// crate::println!("seed: {:x?}", seed); // used to eyeball that things are working correctly
let mut csprng = ChaCha8Rng::from_seed(seed);
let entropy_bank = csprng.next_u64();
@ -128,9 +137,45 @@ pub fn paranoid_mode() {
sensor.wo(utra::sensorc::SFR_VDMASK0, 0);
bao1x_api::bollard!(die, 4);
sensor.wo(utra::sensorc::SFR_VDMASK1, 0); // putting 0 here makes the chip reset on glitch detect
// redundant write in case of glitching
}
// TODO: set up glue cells & interrupts
/// This call clears any current alarms and resets sensors, but does not
/// enable (or re-enable) interrupts
pub fn reset_sensors() {
let glue = CSR::new(utra::gluechain::HW_GLUECHAIN_BASE as *mut u32);
let mut sensor = CSR::new(utra::sensorc::HW_SENSORC_BASE as *mut u32);
// reset the glue chain. Hard-coded constants are used here because
// the UTRA did not extract these constants correctly.
bao1x_api::bollard!(die, 4);
unsafe {
glue.base().add(4).write_volatile(0);
glue.base().add(5).write_volatile(0);
}
// wait for reset to propagate
for _ in 0..100 {
bao1x_api::bollard!(4);
}
// re-arm
bao1x_api::bollard!(die, 4);
unsafe {
glue.base().add(0).write_volatile(0x0);
glue.base().add(1).write_volatile(0x0);
glue.base().add(4).write_volatile(0xFFFF_FFFF);
glue.base().add(5).write_volatile(0xFFFF_FFFF);
glue.base().add(6).write_volatile(0x0);
glue.base().add(7).write_volatile(0x0);
}
// this enables all the sensors to create non-resetting interrupts
bao1x_api::bollard!(die, 4);
sensor.wo(utra::sensorc::SFR_VDFR, 0x3f); // clear any voltage alarms
sensor.wo(utra::sensorc::SFR_VDMASK0, 0);
// DONT TOUCH THIS - paranoid mode sets this, and can set it BEFORE reset_sensors is called!
// sensor.wo(utra::sensorc::SFR_VDMASK1, 0x3f);
sensor.wo(utra::sensorc::SFR_LDIP_FD, 0x1ff); // setup filtering parameters
sensor.wo(utra::sensorc::SFR_LDCFG, 0xc);
sensor.wo(utra::sensorc::SFR_LDMASK, 0x0); // turn on both sensors
bao1x_api::bollard!(die, 4);
}
/// Mesh is a bit challenging to check on a fast-boot system. This is because it
@ -271,14 +316,6 @@ pub fn mesh_check_and_react(csprng: &mut Csprng, one_way: &OneWayCounter) {
}
pub fn apply_attack_policy(csprng: &mut Csprng, one_way: &OneWayCounter) {
// use a large threshold initially, under the theory that e.g. fault injections tend
// to take thousands of iterations to succeed, and we really don't want to accidentally
// wipe customer data. For now, the policy is to only wipe to those who have consented
// by turning on paranoid mode.
//
// Pick a number that has a high hamming distance from 0 - and so, prefer e.g. 127 vs 128.
const WIPE_THRESHOLD: u32 = 127;
bollard!(die, 4);
csprng.random_delay();
let (paranoid1, paranoid2) =
@ -304,3 +341,90 @@ pub fn apply_attack_policy(csprng: &mut Csprng, one_way: &OneWayCounter) {
}
}
}
pub fn glitch_handler(attacks_since_boot: u32) {
let owc = OneWayCounter::new();
let mut irq13 = CSR::new(utra::irqarray13::HW_IRQARRAY13_BASE as *mut u32);
let mut irq15 = CSR::new(utra::irqarray15::HW_IRQARRAY15_BASE as *mut u32);
// Only secirq is recoverable: this is a sensor that has triggered. This is the only
// type of "attack" that we envision would need recovering from, because the sensors
// could be too sensitive. Thus, for all other IRQ types, just halt.
let reason = irq13.r(utra::irqarray13::EV_PENDING);
let mut was_sensor = false;
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;
if sensor & MESH_MASK != 0 {
// mesh events are handled by a separate routine
#[cfg(feature = "debug-countermeasures")]
crate::println!("mesh");
}
if sensor & SENSOR_MASK != 0 || sensor & GLUE_MASK != 0 {
#[cfg(feature = "debug-countermeasures")]
crate::println!("Sensor {:x}", sensor);
// this resets all the sensors that *can* be reset
crate::hardening::reset_sensors();
was_sensor = true;
}
irq15.wo(utra::irqarray15::EV_PENDING, sensor);
}
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
if !was_sensor {
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
// mesh sensor will trigger while settling measurements; and there is no way to mask it
irq13.wo(utra::irqarray13::EV_PENDING, reason);
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
return;
}
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
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);
if paranoid1 != 0 {
if attacks > WIPE_THRESHOLD {
crate::sigcheck::erase_secrets(&mut None).ok();
}
crate::sigcheck::die_no_std();
}
if paranoid2 != 0 {
if attacks > WIPE_THRESHOLD {
crate::sigcheck::erase_secrets(&mut None).ok();
}
crate::sigcheck::die_no_std();
}
// 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);
if attacks_since_boot > DISTURB_THRESHOLD {
// 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")]
crate::println!("Attack thresh");
crate::sigcheck::die_no_std();
}
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
// non-sensor reasons are non-recoverable: we'll just repeatedly re-enter the interrupt state
// in this case, just erase the NV data and die.
if reason & !0x8 != 0 {
#[cfg(feature = "debug-countermeasures")]
crate::println!("Halt {:x}", reason);
crate::sigcheck::die_no_std();
}
irq13.wo(utra::irqarray13::EV_PENDING, reason);
}

View file

@ -188,8 +188,12 @@ impl<'a> Reram {
assert!(data.len() % 8 == 0, "unaligned source data!");
// crate::print!("@ {:x} > ", addr);
for (outer, d) in data.chunks_exact(8).enumerate() {
#[cfg(not(feature = "kernel"))]
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
// write the data to the buffer
for (inner, &datum) in d.iter().enumerate() {
#[cfg(not(feature = "kernel"))]
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
// crate::print!(" {:x}", datum);
self.array
.as_mut_ptr()
@ -199,6 +203,8 @@ impl<'a> Reram {
}
// crate::println!("");
#[cfg(not(feature = "kernel"))]
bao1x_api::bollard!(crate::sigcheck::die_no_std, 4);
self.csr.rmwf(utra::rrc::SFR_RRCCR_SFR_RRCCR, RRC_CR_WRITE_CMD | SECURITY_MODE);
self.array
.as_mut_ptr()

View file

@ -17,6 +17,8 @@ use xous::arch::PAGE_SIZE;
use crate::acram::OneWayCounter;
#[cfg(not(feature = "std"))]
use crate::acram::{AccessSettings, SlotManager};
#[cfg(not(feature = "std"))]
use crate::buram::{BackupManager, ERASURE_PROOF_RANGE_BYTES};
use crate::hardening::Csprng;
use crate::udma::Spim;
@ -191,7 +193,7 @@ pub fn validate_image(
// the function inside the ed25519 crate.
bollard!(die_no_std, 4);
csprng.as_deref_mut().map(|rng| rng.random_delay());
// this match statement is an achille's heel. I don't want to fork the cryptographic
// this match statement is an Achilles's heel. I don't want to fork the cryptographic
// crates, so we have an unhardened comparison of the result. The work-around is
// in paranoid mode, we command the system to verify things *twice*
match verifying_key.verify_prehashed(h, None, &ed25519_signature) {
@ -227,7 +229,7 @@ pub fn validate_image(
bollard!(die_no_std, 4);
csprng.as_deref_mut().map(|rng| rng.random_delay());
// this match statement is an achille's heel. I don't want to fork the cryptographic
// this match statement is an Achilles's heel. I don't want to fork the cryptographic
// crates, so we have an unhardened comparison of the result. The work-around is
// in paranoid mode, we command the system to verify things *twice*
match verifying_key.verify_strict(&msg, &ed25519_signature) {
@ -283,6 +285,12 @@ pub fn erase_secrets(csprng: &mut Option<&mut Csprng>) -> Result<(), String> {
let slot_mgr = SlotManager::new();
let mut rram = crate::rram::Reram::new();
let mut buram = BackupManager::new();
// erase the backup RAM region to 0 that is the erasure proof.
bollard!(die_no_std, 4);
csprng.as_deref_mut().map(|rng| rng.random_delay());
buram.store_slice(&[0u8; 32], crate::buram::ERASURE_PROOF_RANGE_BYTES.start);
let mut zero_key_count = 0;
// This is set to a higher level because we need to work around an earlier issue
// with overly-broad ACL settings on alpha0 boards
@ -345,10 +353,17 @@ pub fn erase_secrets(csprng: &mut Option<&mut Csprng>) -> Result<(), String> {
bollard!(die_no_std, 4);
}
bollard!(die_no_std, 4);
// store the proof that the key array was erased - could lead to disclosure of one key,
// but we also can't simply trust that the oneway counter below is accurate
csprng.as_deref_mut().map(|rng| rng.random_delay());
buram.store_slice(slot_mgr.read(&crate::board::ERASE_PROOF).unwrap(), ERASURE_PROOF_RANGE_BYTES.start);
let owc = OneWayCounter::new();
// once all secrets are erased, advance the DEVELOPER_MODE state
// safety: the offset is correct because we're pulling it from our pre-defined constants and
// those are manually checked.
bollard!(die_no_std, 4);
if owc.get(DEVELOPER_MODE).unwrap() < 15 {
// limit incrementing to avoid memory wear-out, as erase_secrets() can be called every time on boot.
unsafe { owc.inc(DEVELOPER_MODE).unwrap() };

View file

@ -89,6 +89,8 @@ mod platform;
#[cfg(feature = "swap")]
pub mod swap;
#[cfg(feature = "bao1x")]
use core::convert::TryInto;
use core::{mem, ptr, slice};
use asm::*;
@ -266,8 +268,10 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
#[cfg(feature = "bao1x")]
let detached_app = {
use bao1x_api::{PARANOID_MODE, PARANOID_MODE_DUPE, bollard, pubkeys::LOADER_TO_KERNEL};
use bao1x_hal::{buram::ERASURE_PROOF_RANGE_BYTES, sigcheck::ERASE_VALUE};
let owc = bao1x_hal::acram::OneWayCounter::new();
let backup = bao1x_hal::buram::BackupManager::new();
let (paranoid1, paranoid2) = owc.hardened_get2(PARANOID_MODE, PARANOID_MODE_DUPE).unwrap();
let (dev_mode1, dev_mode2) = owc.hardened_get(bao1x_api::DEVELOPER_MODE).unwrap();
csprng.random_delay();
@ -298,7 +302,9 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
|| key == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT
{
csprng.random_delay();
if dev_mode1 == 0 {
let erase_proof: &[u8; 32] =
backup.get_slice(ERASURE_PROOF_RANGE_BYTES).try_into().unwrap();
if dev_mode1 == 0 || erase_proof != &[ERASE_VALUE; 32] {
if paranoid1 == 0 && paranoid2 == 0 {
println!("{}LOADER.KERNDIE,{}", BOOKEND_START, BOOKEND_END);
println!("Kernel is devkey signed, but system is not in developer mode. Dying!");
@ -315,7 +321,9 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
bollard!(bao1x_hal::sigcheck::die_no_std, 4);
if !key_inv == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT {
csprng.random_delay();
if dev_mode2 == 0 {
let erase_proof: &[u8; 32] =
backup.get_slice(ERASURE_PROOF_RANGE_BYTES).try_into().unwrap();
if dev_mode2 == 0 || erase_proof != &[ERASE_VALUE; 32] {
if paranoid1 == 0 && paranoid2 == 0 {
println!("{}LOADER.KERNDIE,{}", BOOKEND_START, BOOKEND_END);
println!("Kernel is devkey signed, but system is not in developer mode. Dying!");
@ -371,9 +379,11 @@ 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]
|| key == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT
{
let erase_proof: &[u8; 32] =
backup.get_slice(ERASURE_PROOF_RANGE_BYTES).try_into().unwrap();
// we can't erase keys in the loader, because the keys have already been locked
// out at this point. Thus, ensure that the system is already in developer mode.
if dev_mode1 == 0 {
if dev_mode1 == 0 || erase_proof != &[ERASE_VALUE; 32] {
if paranoid1 == 0 && paranoid2 == 0 {
println!("{}LOADER.APPDIE,{}", BOOKEND_START, BOOKEND_END);
println!(
@ -389,7 +399,9 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
csprng.random_delay();
bollard!(bao1x_hal::sigcheck::die_no_std, 4);
if !key_inv == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT {
if dev_mode2 == 0 {
let erase_proof: &[u8; 32] =
backup.get_slice(ERASURE_PROOF_RANGE_BYTES).try_into().unwrap();
if dev_mode2 == 0 || erase_proof != &[ERASE_VALUE; 32] {
if paranoid1 == 0 && paranoid2 == 0 {
println!("{}LOADER.APPDIE,{}", BOOKEND_START, BOOKEND_END);
println!(
@ -518,6 +530,14 @@ fn boot_sequence(
check_load(&mut cfg);
}
println!("done initializing for cold boot.");
#[cfg(feature = "bao1x")]
{
// cleanup the leaked key to the backup registers
let mut buram = bao1x_hal::buram::BackupManager::new();
bao1x_api::bollard!(bao1x_hal::sigcheck::die_no_std, 4);
buram.store_slice(&[0u8; 32], bao1x_hal::buram::ERASURE_PROOF_RANGE_BYTES.start);
bao1x_api::bollard!(bao1x_hal::sigcheck::die_no_std, 4);
}
}
#[cfg(feature = "resume")]
if clean {
@ -564,6 +584,15 @@ fn boot_sequence(
// condense debug and resume arguments into a single register, so we have space for XPT
let debug_resume = if cfg.debug { 0x1 } else { 0x0 } | if clean { 0x2 } else { 0x0 };
if !clean {
#[cfg(feature = "bao1x")]
{
// clean it twice, just in case the first cleanup was glitched past
let mut buram = bao1x_hal::buram::BackupManager::new();
bao1x_api::bollard!(bao1x_hal::sigcheck::die_no_std, 4);
buram.store_slice(&[0u8; 32], bao1x_hal::buram::ERASURE_PROOF_RANGE_BYTES.start);
bao1x_api::bollard!(bao1x_hal::sigcheck::die_no_std, 4);
}
// The MMU should be set up now, and memory pages assigned to their
// respective processes.
let krn_struct_start = cfg.sram_start as usize + cfg.sram_size - cfg.init_size + cfg.swap_offset;

View file

@ -43,6 +43,7 @@ pub fn phase_2(cfg: &mut BootConfig, env_variables: EnvVariables) {
for tag in args.iter() {
let mut env_header = crate::env::EnvHeader::default();
#[allow(unused_mut)]
let mut pid_env = env_variables.clone();
#[cfg(feature = "bao1x")]

View file

@ -10,6 +10,7 @@ use bao1x_hal::board::{APP_UART_IFRAM_ADDR, SPIM_FLASH_IFRAM_ADDR, SPIM_RAM_IFRA
use bao1x_hal::ifram::IframRange;
use bao1x_hal::iox::Iox;
use bao1x_hal::sce;
use bao1x_hal::sigcheck::ERASE_VALUE;
use bao1x_hal::udma::{GlobalConfig, Spim, SpimClkPha, SpimClkPol, SpimCs};
use rand_chacha::ChaCha8Rng;
use rand_chacha::rand_core::RngCore;
@ -233,6 +234,11 @@ impl SwapHal {
// check signature only if the swap key is all 0's
// this is not very glitch-hardened because at this point, the adversary has full
// control over the code coming in. A TOCTOU is extremely easy to pull off.
//
// In practice for full security, the swap shall be encrypted to a custom symmetric
// key unique to each device, which takes the place of the signature check. This
// check is thus assumed to be performed only upon the first presentation of
// a signed update.
if swap.key == [0u8; 32] {
crate::println!("Fresh swap image found - checking signature before proceeding");
match bao1x_hal::sigcheck::validate_image(
@ -247,9 +253,11 @@ impl SwapHal {
!k2,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
);
bollard!(bao1x_hal::sigcheck::die_no_std, 4);
if k != !k2 {
bao1x_hal::sigcheck::die_no_std();
}
bollard!(bao1x_hal::sigcheck::die_no_std, 4);
// k is just a nominal slot number. If either match, assume we are dealing
// with a developer image.
if tag
@ -262,6 +270,7 @@ impl SwapHal {
// locked out at this point. Thus,
// ensure that the system is already in developer mode.
let owc = bao1x_hal::acram::OneWayCounter::new();
bollard!(bao1x_hal::sigcheck::die_no_std, 4);
if owc.get(bao1x_api::DEVELOPER_MODE).unwrap() == 0 {
println!("{}LOADER.SWAPDIE,{}", BOOKEND_START, BOOKEND_END);
println!(
@ -274,6 +283,16 @@ impl SwapHal {
"Developer key detected on swap. Proceeding in developer mode!"
);
}
let backup = bao1x_hal::buram::BackupManager::new();
bollard!(bao1x_hal::sigcheck::die_no_std, 4);
let erase_proof: &[u8; 32] = backup
.get_slice(bao1x_hal::buram::ERASURE_PROOF_RANGE_BYTES)
.try_into()
.unwrap();
if erase_proof != &[ERASE_VALUE; 32] {
bao1x_hal::sigcheck::die_no_std();
}
bollard!(bao1x_hal::sigcheck::die_no_std, 4);
}
}
Err(e) => {

View file

@ -255,6 +255,19 @@ pub fn sign_image(
}
dest_file.write_all(&protected)?;
if function_code == FunctionCode::Kernel {
let target = bao1x_api::RRAM_STORAGE_LEN - (bao1x_api::KERNEL_START - bao1x_api::BOOT0_START);
if dest_file.len() > target {
println!(
"ERROR: Xous RRAM image is too big to fit: {} bytes too large ({} bytes; {} limit)",
dest_file.len() - target,
dest_file.len(),
target,
);
return Err(String::from("Image doesn't fit").into());
}
}
Ok(dest_file)
}
}

View file

@ -739,13 +739,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
"xous-names",
"usb-bao1x",
"bao1x-hal-service",
"bao-console",
"modals",
"pddb",
"bao-video",
]
.to_vec();
let bao_swap_pkgs = ["vault2"].to_vec();
let bao_swap_pkgs = ["bao-console", "vault2"].to_vec();
if !builder.is_swap_set() {
// reserve 3MiB for system services: ultimately, "pddb, modals, and bao-video"
builder.set_swap(0, bao1x_api::offsets::baosec::SWAP_RAM_LEN as _);