From 8cbdb75dc86629f5700811e498ff9e095541ddd7 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 29 Sep 2025 13:46:42 +0800 Subject: [PATCH] cleanup boot0 code remove things that we don't need in boot0. Boot0 originated from a much larger, more featureful space and needs to be whittled down to remove attack surface and space for bugs. Some further cleanup to do would include: - hardening the PLL setting. Right now it's done computationally based on the demanded frequency. But in practice, because the target frequency is hard-coded, we could just compute the actual PLL value results and jam them into the register and lose a whole bunch of code. Actually I think that's all that needs to be cleaned up off the top of my head. --- bao1x-boot/boot0/Cargo.toml | 23 +- bao1x-boot/boot0/link.x | 2 +- bao1x-boot/boot0/src/asm.rs | 5 +- bao1x-boot/boot0/src/main.rs | 71 ++++- bao1x-boot/boot0/src/platform/bao1x/bao1x.rs | 284 +++---------------- bao1x-boot/boot0/src/platform/bao1x/debug.rs | 67 +++-- bao1x-boot/boot0/src/platform/bao1x/irq.rs | 25 +- bao1x-boot/boot0/src/repl.rs | 126 +------- bao1x-boot/boot0/src/sigcheck.rs | 99 ------- 9 files changed, 180 insertions(+), 522 deletions(-) delete mode 100644 bao1x-boot/boot0/src/sigcheck.rs diff --git a/bao1x-boot/boot0/Cargo.toml b/bao1x-boot/boot0/Cargo.toml index 0004d5455..241b2ef18 100644 --- a/bao1x-boot/boot0/Cargo.toml +++ b/bao1x-boot/boot0/Cargo.toml @@ -2,8 +2,8 @@ name = "bao1x-boot0" version = "0.1.0" authors = ["bunnie "] -edition = "2018" -description = "Boot0 loader" +edition = "2021" +description = "Boot0 partition" [dependencies] xous = "0.9.66" @@ -13,20 +13,7 @@ bao1x-api = { path = "../../libs/bao1x-api", optional = true, default-features = vexriscv = { version = "0.5.6", package = "xous-riscv" } riscv = { version = "0.14.0", features = ["critical-section-single-hart"] } linked_list_allocator = { version = "0.10.5", optional = true } -xous-bio-bdma = { path = "../../libs/xous-bio-bdma", optional = true, default-features = false } 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", optional = true, default-features = false } -digest = { version = "^0.10.7", optional = true } -ed25519-dalek = { package = "ed25519-dalek-bao1x", path = "../ed25519-dalek-bao1x", default-features = false, features = [ - "digest", - "debug", -] } -base64 = { version = "0.22.1", optional = true, default-features = false, features = [ - "alloc", -] } -sha2-bao1x = { path = "../sha2-bao1x", optional = true, default-features = false } -hex-literal = "1.0.0" [features] # Baochip feature tree below @@ -34,10 +21,10 @@ bao1x = [ "utralib/bao1x", "linked_list_allocator", "bao1x-hal/loader-baosec", - # "bao1x-hal/debug-print-usb", "bao1x-api", - "sha2-bao1x/bao1x", - "digest", ] +# turns on a bunch of developer debug features. No production build should have this feature activated! +unsafe-dev = [] + default = ["bao1x"] diff --git a/bao1x-boot/boot0/link.x b/bao1x-boot/boot0/link.x index 7d926abec..678ef9471 100644 --- a/bao1x-boot/boot0/link.x +++ b/bao1x-boot/boot0/link.x @@ -2,7 +2,7 @@ MEMORY { /* Note: ORIGIN is updated by xtask for baremetal targets */ - FLASH : ORIGIN = 0x60000400, LENGTH = 256k - 1024 + FLASH : ORIGIN = 0x60000400, LENGTH = 127k RAM : ORIGIN = 0x61000000, LENGTH = 2048k } diff --git a/bao1x-boot/boot0/src/asm.rs b/bao1x-boot/boot0/src/asm.rs index 51c6c5eae..b6563e611 100644 --- a/bao1x-boot/boot0/src/asm.rs +++ b/bao1x-boot/boot0/src/asm.rs @@ -3,7 +3,6 @@ use core::arch::asm; use crate::platform; #[link_section = ".text.init"] #[export_name = "_start"] -#[cfg(feature = "bao1x")] pub extern "C" fn _start() { unsafe { #[rustfmt::skip] @@ -21,8 +20,8 @@ pub extern "C" fn _start() { "sw t1, 0xc(t0)", "li t1, 0x1", "sw t1, 0x4(t0)", // CR is 1 - // print 32 instances of 'Z' (0x5A) (provided to measure baud) - "li t2, 32", + // print 8 instances of 'Z' (0x5A) (provided to help measure baud) + "li t2, 8", "li t1, 0x5A", "10:", "sw t1, 0x0(t0)", diff --git a/bao1x-boot/boot0/src/main.rs b/bao1x-boot/boot0/src/main.rs index e6413e8cd..95ed88e23 100644 --- a/bao1x-boot/boot0/src/main.rs +++ b/bao1x-boot/boot0/src/main.rs @@ -6,11 +6,14 @@ extern crate alloc; mod asm; mod platform; +#[cfg(feature = "unsafe-dev")] mod repl; -mod sigcheck; +#[cfg(feature = "unsafe-dev")] use alloc::collections::VecDeque; +#[cfg(feature = "unsafe-dev")] use core::cell::RefCell; +#[cfg(feature = "unsafe-dev")] use critical_section::Mutex; use platform::*; #[allow(unused_imports)] @@ -19,11 +22,10 @@ use utralib::*; #[allow(unused_imports)] use crate::delay; +#[cfg(feature = "unsafe-dev")] static UART_RX: Mutex>> = Mutex::new(RefCell::new(VecDeque::new())); -#[allow(dead_code)] -static USB_RX: Mutex>> = Mutex::new(RefCell::new(VecDeque::new())); -static USB_TX: Mutex>> = Mutex::new(RefCell::new(VecDeque::new())); +#[cfg(feature = "unsafe-dev")] pub fn uart_irq_handler() { use crate::debug::SerialRead; let mut uart = crate::debug::Uart {}; @@ -50,8 +52,10 @@ pub unsafe extern "C" fn rust_entry() -> ! { crate::platform::early_init(); crate::println!("\n~~boot0 up!~~\n"); + #[cfg(feature = "unsafe-dev")] let mut repl = crate::repl::Repl::new(); // do the main loop through the serial port + #[cfg(feature = "unsafe-dev")] loop { // Handle keyboard events. critical_section::with(|cs| { @@ -72,4 +76,63 @@ pub unsafe extern "C" fn rust_entry() -> ! { _ => (), }; } + if bao1x_hal::sigcheck::validate_image( + bao1x_api::BOOT0_START as *const u32, + bao1x_api::BOOT0_REVOCATION_OFFSET, + false, + ) + .is_ok() + { + seal_boot0_keys(); + let one_way_access = bao1x_hal::acram::OneWayCounter::new(); + match one_way_access.get_decoded::() { + Ok(bao1x_api::AltBootCoding::PrimaryPartition) => { + // Primary boot selected. Check Boot1 first, then fall back to LOADER/BAREMETAL. + bao1x_hal::sigcheck::validate_image( + bao1x_api::BOOT1_START as *const u32, + bao1x_api::BOOT1_REVOCATION_OFFSET, + true, + ) + .ok(); + bao1x_hal::sigcheck::validate_image( + bao1x_api::LOADER_START as *const u32, + bao1x_api::LOADER_REVOCATION_OFFSET, + true, + ) + .ok(); + } + Ok(bao1x_api::AltBootCoding::AlternatePartition) => { + // Alternate boot selected. Check LOADER/BAREMETAL, then fall back to Boot1. + bao1x_hal::sigcheck::validate_image( + bao1x_api::LOADER_START as *const u32, + bao1x_api::LOADER_REVOCATION_OFFSET, + true, + ) + .ok(); + bao1x_hal::sigcheck::validate_image( + bao1x_api::BOOT1_START as *const u32, + bao1x_api::BOOT1_REVOCATION_OFFSET, + true, + ) + .ok(); + } + Err(_) => { + crate::println!("Internal error: alt boot encoding is invalid!"); + bao1x_hal::sigcheck::die_no_std(); + } + } + } + bao1x_hal::sigcheck::die_no_std(); +} + +fn seal_boot0_keys() { + // TODO: + // - setup an initial coreuser table + // - set an ASID that locks out any boot0 secrets (currently none, as it's PK based) + // - this does not offer strong security, but prevents someone with an arbitrary read primitive from + // accessing any boot0 secrets. An arbitrary-exec primitive at this point can, of course, undo the ASID + // mapping. + // + // Only necessary if we have secrets to seal. The current implementation only contains a public key, + // so there's no secrets to seal. } diff --git a/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs b/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs index 6bd7dec03..de57cd6c2 100644 --- a/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs +++ b/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs @@ -1,9 +1,9 @@ use bao1x_api::signatures::SIGBLOCK_LEN; -use bao1x_hal::udma; use utralib::CSR; use utralib::utra; use utralib::utra::sysctrl; +#[cfg(feature = "unsafe-dev")] use crate::platform::{ debug::setup_rx, irq::{enable_irq, irq_setup}, @@ -22,14 +22,18 @@ const DATA_SIZE_BYTES: usize = 0x6000; pub const HEAP_START: usize = RAM_BASE + DATA_SIZE_BYTES; pub const HEAP_LEN: usize = 1024 * 256; -// scratch page for exceptions located at top of RAM -// NOTE: there is an additional page above this for exception stack -pub const SCRATCH_PAGE: usize = HEAP_START - 8192; +// scratch page for exceptions +// - scratch data is stored in positive offsets from here +// - exception stack is stored in negative offsets from here, hence the +4096 +// total occupied area is [HEAP_START + HEAP_LEN..HEAP_START + HEAP_LEN + 8192] +pub const SCRATCH_PAGE: usize = HEAP_START + HEAP_LEN + 4096; pub const UART_IFRAM_ADDR: usize = bao1x_hal::board::UART_DMA_TX_BUF_PHYS; -// Run at 400MHz to ensure we can boot even without an external VDD85 regulator! -pub const SYSTEM_CLOCK_FREQUENCY: u32 = 400_000_000; +/// Run at 400MHz to ensure we can boot even without an external VDD85 regulator! +/// Also relying on the IFR region setting the SRAM trimming to work at this safe default +/// so we don't have to initialize it in boot0. +pub const DEFAULT_FCLK_FREQUENCY: u32 = 400_000_000; pub const SYSTEM_TICK_INTERVAL_MS: u32 = 1; pub fn early_init() { @@ -62,7 +66,6 @@ pub fn early_init() { // sram0 requires 1 wait state for writes let mut sramtrm = CSR::new(utra::coresub_sramtrm::HW_CORESUB_SRAMTRM_BASE as *mut u32); sramtrm.wo(utra::coresub_sramtrm::SFR_SRAM0, 0x8); - sramtrm.wo(utra::coresub_sramtrm::SFR_SRAM1, 0x8); // Now that SRAM trims are setup, initialize all the statics by writing to memory. // For baremetal, the statics structure is just at the flash base. @@ -86,11 +89,8 @@ pub fn early_init() { } } - let uart = crate::debug::Uart {}; - uart.putc('*' as u32 as u8); - - // set the clock - let perclk = unsafe { init_clock_asic(SYSTEM_CLOCK_FREQUENCY) }; + // set the clock. + let perclk = unsafe { init_clock_asic(DEFAULT_FCLK_FREQUENCY) }; crate::println!("scratch page: {:x}, heap start: {:x}", SCRATCH_PAGE, HEAP_START); @@ -99,16 +99,25 @@ pub fn early_init() { setup_timer(); + // this is a security-critical initialization. Failure to do this correctly breaks + // all the hardware hashes. It's done once, in boot0. Note that the constants *are* + // malleable (no hardware lock to prevent update), which is a potential vulnerability. init_hash(); - // Rx setup - let mut udma_uart = setup_rx(perclk); - irq_setup(); - enable_irq(utra::irqarray5::IRQARRAY5_IRQ); + // TxRx setup + #[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 + }; + // Tx-only setup + #[cfg(not(feature = "unsafe-dev"))] + let _udma_uart = crate::debug::setup_tx(perclk); - udma_uart.write("console up\r\n".as_bytes()); crate::debug::USE_CONSOLE.store(true, core::sync::atomic::Ordering::SeqCst); - crate::println!("This debug print should be on the UDMA UART"); + crate::println!("boot0 console up"); } pub fn setup_timer() { @@ -122,7 +131,7 @@ pub fn setup_timer() { timer.wfo(utra::timer0::EN_EN, 0b0); // disable the timer // load its values timer.wfo(utra::timer0::LOAD_LOAD, 0); - timer.wfo(utra::timer0::RELOAD_RELOAD, (SYSTEM_CLOCK_FREQUENCY / 1_000) * ms); + timer.wfo(utra::timer0::RELOAD_RELOAD, (DEFAULT_FCLK_FREQUENCY / 1_000) * ms); // enable the timer timer.wfo(utra::timer0::EN_EN, 0b1); } @@ -138,7 +147,7 @@ pub fn setup_alloc() { /// This function loads all the round constants into the combohasher's local memory. pub fn init_hash() { - use bao1x_hal::sce::combohash::*; + use bao1x_api::sce::combohash::*; // safety: this one is a little less clear from the register set extraction. But in the case of // system initialization, the SCE uses its entire RAM range (10kiB worth) as a single buffer, so // none of the buffer boundaries are respected. Thus we set the length of the segment to 10kiB @@ -196,6 +205,7 @@ pub fn delay_at_sysfreq(ms: usize, sysclk_freq: u32) { } /// Delay function that delays a given number of milliseconds. +#[allow(dead_code)] pub fn delay(ms: usize) { let mut timer = utralib::CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32); timer.wfo(utra::timer0::EV_PENDING_ZERO, 1); @@ -215,28 +225,6 @@ mod panic_handler { } } -/// This takes in the FD input frequency (the frequency to be divided) in MHz -/// and the fd value, and returns the resulting divided frequency. -/// *not tested* -#[allow(dead_code)] -pub fn fd_to_clk(fd_in_mhz: u32, fd_val: u32) -> u32 { (fd_in_mhz * (fd_val + 1)) / 256 } - -/// Takes in the FD input frequencyin MHz, and then the desired frequency. -/// Returns Some((fd value, deviation in *hz*, not MHz)) if the requirement is satisfiable -/// Returns None if the equation is ill-formed. -/// *not tested* -#[allow(dead_code)] -pub fn clk_to_fd(fd_in_mhz: u32, desired_mhz: u32) -> Option<(u32, i32)> { - let platonic_fd: u32 = (desired_mhz * 256) / fd_in_mhz; - if platonic_fd > 0 { - let actual_fd = platonic_fd - 1; - let actual_clk = fd_to_clk(fd_in_mhz, actual_fd); - Some((actual_fd, desired_mhz as i32 - actual_clk as i32)) - } else { - None - } -} - /// Takes in the top clock in MHz, desired perclk in MHz, and returns a tuple of /// (min cycle, fd, actual freq) /// *tested* @@ -258,13 +246,7 @@ pub fn clk_to_per(top_in_mhz: u32, perclk_in_mhz: u32) -> Option<(u8, u8, u32)> } } -// This function supercedes init_clock_asic() and needs to be back-ported -// into xous-core -// TODO: -// - [ ] Case of clocks <= 48MHz: turn off PLL, divide directly from OSC -// - [ ] Derive clock dividers from freq targets, instead of hard-coding them -// - [ ] Maybe improve dividers to optimize hclk/iclk/pclk settings in lower power? -// - [ ] Very maybe consider setting hclk/iclk/pclk in case of overclocking +/// TODO: pare this down for the boot0 function pub unsafe fn init_clock_asic(freq_hz: u32) -> u32 { use utra::sysctrl; let daric_cgu = sysctrl::HW_SYSCTRL_BASE as *mut u32; @@ -313,35 +295,19 @@ pub unsafe fn init_clock_asic(freq_hz: u32) -> u32 { // perclk divider - set to divide by 8 off of an 800Mhz base. Only found on bao1x. // TODO: this only works for two clock settings. Broken @ 600. Need to fix this to instead derive // what pclk is instead of always reporting 100mhz - let (min_cycle, fd, perclk) = if let Some((min_cycle, fd, perclk)) = clk_to_per(freq_hz / 1_000_000, 100) - { - daric_cgu - .add(utra::sysctrl::SFR_CGUFDPER.offset()) - .write_volatile((min_cycle as u32) << 16 | (fd as u32) << 8 | fd as u32); - (min_cycle, fd, perclk * 1_000_000) - } else if freq_hz > 400_000_000 { - daric_cgu.add(utra::sysctrl::SFR_CGUFDPER.offset()).write_volatile(0x07_ff_ff); - (7, 0xff, freq_hz / 8) - } else { - daric_cgu.add(utra::sysctrl::SFR_CGUFDPER.offset()).write_volatile(0x03_ff_ff); - (3, 0xff, freq_hz / 4) - }; - - /* - perclk fields: min-cycle-lp | min-cycle | fd-lp | fd - clkper fd - 0xff : Fperclk = Fclktop/2 - 0x7f: Fperclk = Fclktop/4 - 0x3f : Fperclk = Fclktop/8 - 0x1f : Fperclk = Fclktop/16 - 0x0f : Fperclk = Fclktop/32 - 0x07 : Fperclk = Fclktop/64 - 0x03: Fperclk = Fclktop/128 - 0x01: Fperclk = Fclktop/256 - - min cycle of clktop, F means frequency - Fperclk Max = Fperclk/(min cycle+1)*2 - */ + let (_min_cycle, _fd, perclk) = + if let Some((min_cycle, fd, perclk)) = clk_to_per(freq_hz / 1_000_000, 100) { + daric_cgu + .add(utra::sysctrl::SFR_CGUFDPER.offset()) + .write_volatile((min_cycle as u32) << 16 | (fd as u32) << 8 | fd as u32); + (min_cycle, fd, perclk * 1_000_000) + } else if freq_hz > 400_000_000 { + daric_cgu.add(utra::sysctrl::SFR_CGUFDPER.offset()).write_volatile(0x07_ff_ff); + (7, 0xff, freq_hz / 8) + } else { + daric_cgu.add(utra::sysctrl::SFR_CGUFDPER.offset()).write_volatile(0x03_ff_ff); + (3, 0xff, freq_hz / 4) + }; // turn off gates daric_cgu.add(utra::sysctrl::SFR_ACLKGR.offset()).write_volatile(0xff); @@ -465,180 +431,18 @@ pub unsafe fn init_clock_asic(freq_hz: u32) -> u32 { } crate::println!("PLL delay 2"); - //printf("read reg a0 : %08" PRIx32"\n", *((volatile uint32_t* )0x400400a0)); - //printf("read reg a4 : %04" PRIx16"\n", *((volatile uint16_t* )0x400400a4)); - //printf("read reg a8 : %04" PRIx16"\n", *((volatile uint16_t* )0x400400a8)); - - // TODO wait/poll lock status? // DARIC_CGU->cgusel0 = 1; // clktop sel, 0:clksys, 1:clkpll0 cgu.wo(sysctrl::SFR_CGUSEL0, 1); // __DSB(); // DARIC_CGU->cguset = 0x32; // commit cgu.wo(sysctrl::SFR_CGUSET, 0x32); crate::println!("clocks set"); - - // __DSB(); - - // printf (" MN: 0x%05x, F: 0x%06x, Q: 0x%04x\n", - // DARIC_IPC->pll_mn, DARIC_IPC->pll_f, DARIC_IPC->pll_q); - // printf (" LPEN: 0x%01x, OSC: 0x%04x, BIAS: 0x%04x,\n", - // DARIC_IPC->lpen, DARIC_IPC->osc, DARIC_IPC->ipc); } - crate::println!( - "mn {:x}, q{:x}", - (0x400400a0 as *const u32).read_volatile(), - (0x400400a8 as *const u32).read_volatile() - ); - crate::println!("fsvalid: {}", daric_cgu.add(sysctrl::SFR_CGUFSVLD.offset()).read_volatile()); - let clk_desc: [(&'static str, u32, usize); 8] = [ - ("fclk", 16, 0x40 / size_of::()), - ("pke", 0, 0x40 / size_of::()), - ("ao", 16, 0x44 / size_of::()), - ("aoram", 0, 0x44 / size_of::()), - ("osc", 16, 0x48 / size_of::()), - ("xtal", 0, 0x48 / size_of::()), - ("pll0", 16, 0x4c / size_of::()), - ("pll1", 0, 0x4c / size_of::()), - ]; - for (name, shift, offset) in clk_desc { - let fsfreq = (daric_cgu.add(offset).read_volatile() >> shift) & 0xffff; - crate::println!("{}: {} MHz", name, fsfreq); - } // Taken in from latest daric_util.c let mut udmacore = CSR::new(utra::udma_ctrl::HW_UDMA_CTRL_BASE as *mut u32); udmacore.wo(utra::udma_ctrl::REG_CG, 0xFFFF_FFFF); - crate::println!("Perclk solution: {:x}|{:x} -> {} MHz", min_cycle, fd, perclk / 1_000_000); crate::println!("PLL configured to {} MHz", freq_hz / 1_000_000); perclk } - -/// used to generate some test vectors -#[allow(dead_code)] -pub fn lfsr_next_u32(state: u32) -> u32 { - let bit = ((state >> 31) ^ (state >> 21) ^ (state >> 1) ^ (state >> 0)) & 1; - - (state << 1) + bit -} - -pub fn clockset_wrapper(freq: u32) -> u32 { - // reset the baud rate on the console UART - let perclk = unsafe { crate::platform::init_clock_asic(freq) }; - let uart_buf_addr = crate::platform::UART_IFRAM_ADDR; - let mut udma_uart = unsafe { - // safety: this is safe to call, because we set up clock and events prior to calling - // new. - udma::Uart::get_handle(utra::udma_uart_2::HW_UDMA_UART_2_BASE, uart_buf_addr, uart_buf_addr) - }; - let baudrate: u32 = crate::UART_BAUD; - let freq: u32 = perclk / 2; - udma_uart.set_baud(baudrate, freq); - - crate::println!("clock set done, perclk is {} MHz", perclk / 1_000_000); - udma_uart.write("console up with clocks\r\n".as_bytes()); - - perclk -} - -#[allow(dead_code)] -pub unsafe fn low_power() -> u32 { - const FREQ_OSC_MHZ: u32 = 48; // 48MHz - - use utra::sysctrl; - let daric_cgu = sysctrl::HW_SYSCTRL_BASE as *mut u32; - let mut cgu = CSR::new(daric_cgu); - - daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_0.offset()).write_volatile(0x3f3f); // fclk - daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_1.offset()).write_volatile(0x3f3f); // aclk - daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_2.offset()).write_volatile(0x1f1f); // hclk - daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_3.offset()).write_volatile(0x0f0f); // iclk - daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_4.offset()).write_volatile(0x0707); // pclk - - let (min_cycle, fd, perclk) = if let Some((min_cycle, fd, perclk)) = clk_to_per(48, 24) { - daric_cgu - .add(utra::sysctrl::SFR_CGUFDPER.offset()) - .write_volatile((min_cycle as u32) << 16 | (fd as u32) << 8 | fd as u32); - crate::println!("perclk {}", perclk); - (min_cycle, fd, perclk * 1_000_000) - } else { - crate::println!("couldn't find perclk solution"); - daric_cgu.add(utra::sysctrl::SFR_CGUFDPER.offset()).write_volatile(0x03_ff_ff); - (3, 0xff, 48_000_000 / 4) - }; - let perclk = perclk; - - // DARIC_CGU->cgusel1 = 1; // 0: RC, 1: XTAL - cgu.wo(sysctrl::SFR_CGUSEL0, 0); - cgu.wo(sysctrl::SFR_CGUSEL1, 1); - cgu.wo(sysctrl::SFR_CGUFSCR, FREQ_OSC_MHZ); - cgu.wo(sysctrl::SFR_CGUSET, 0x32); - - let duart = utra::duart::HW_DUART_BASE as *mut u32; - duart.add(utra::duart::SFR_CR.offset()).write_volatile(0); - // set the ETUC now that we're on the xosc. - duart.add(utra::duart::SFR_ETUC.offset()).write_volatile(FREQ_OSC_MHZ); - duart.add(utra::duart::SFR_CR.offset()).write_volatile(1); - - cgu.wo(sysctrl::SFR_IPCOSC, FREQ_OSC_MHZ * 1_000_000); - cgu.wo(sysctrl::SFR_IPCARIPFLOW, 0x32); - - // lower core voltage to 0.7v - let mut ao_sysctrl = CSR::new(utralib::HW_AO_SYSCTRL_BASE as *mut u32); - ao_sysctrl.wo(utra::ao_sysctrl::SFR_PMUTRM0CSR, 0x08420002); - // ao_sysctrl.wo(utra::ao_sysctrl::SFR_PMUTRM1CSR, 0x1); - cgu.wo(sysctrl::SFR_IPCARIPFLOW, 0x57); - - // power down the PLL - cgu.wo(sysctrl::SFR_IPCLPEN, cgu.r(sysctrl::SFR_IPCLPEN) & !0x2); - cgu.wo(sysctrl::SFR_IPCCR, 0x53); - cgu.wo(sysctrl::SFR_IPCARIPFLOW, 0x32); - - for _ in 0..1024 { - unsafe { core::arch::asm!("nop") }; - } - crate::println!("PLL pd delay 1"); - - crate::println!("fsvalid: {}", daric_cgu.add(sysctrl::SFR_CGUFSVLD.offset()).read_volatile()); - let clk_desc: [(&'static str, u32, usize); 8] = [ - ("fclk", 16, 0x40 / size_of::()), - ("pke", 0, 0x40 / size_of::()), - ("ao", 16, 0x44 / size_of::()), - ("aoram", 0, 0x44 / size_of::()), - ("osc", 16, 0x48 / size_of::()), - ("xtal", 0, 0x48 / size_of::()), - ("pll0", 16, 0x4c / size_of::()), - ("pll1", 0, 0x4c / size_of::()), - ]; - for (name, shift, offset) in clk_desc { - let fsfreq = (daric_cgu.add(offset).read_volatile() >> shift) & 0xffff; - crate::println!("{}: {} MHz", name, fsfreq); - } - - // gates off - daric_cgu.add(utra::sysctrl::SFR_ACLKGR.offset()).write_volatile(0x00); - daric_cgu.add(utra::sysctrl::SFR_HCLKGR.offset()).write_volatile(0x00); - daric_cgu.add(utra::sysctrl::SFR_ICLKGR.offset()).write_volatile(0x00); - daric_cgu.add(utra::sysctrl::SFR_PCLKGR.offset()).write_volatile(0x00); - // commit dividers - daric_cgu.add(utra::sysctrl::SFR_CGUSET.offset()).write_volatile(0x32); - let mut udmacore = CSR::new(utra::udma_ctrl::HW_UDMA_CTRL_BASE as *mut u32); - udmacore.wo(utra::udma_ctrl::REG_CG, 0x0000_000F); // lower four are the UART - - // reset the UART - let uart_buf_addr = crate::platform::UART_IFRAM_ADDR; - let mut udma_uart = unsafe { - // safety: this is safe to call, because we set up clock and events prior to calling - // new. - udma::Uart::get_handle(utra::udma_uart_2::HW_UDMA_UART_2_BASE, uart_buf_addr, uart_buf_addr) - }; - let baudrate: u32 = crate::UART_BAUD; - let freq: u32 = perclk / 2; - udma_uart.set_baud(baudrate, freq); - - crate::println!("Perclk solution: {:x}|{:x} -> {} MHz", min_cycle, fd, perclk / 1_000_000); - crate::println!("powerdown: perclk is {} MHz", perclk / 1_000_000); - udma_uart.write("powerdown with clocks\r\n".as_bytes()); - - perclk -} diff --git a/bao1x-boot/boot0/src/platform/bao1x/debug.rs b/bao1x-boot/boot0/src/platform/bao1x/debug.rs index 4b8086c07..7901669d3 100644 --- a/bao1x-boot/boot0/src/platform/bao1x/debug.rs +++ b/bao1x-boot/boot0/src/platform/bao1x/debug.rs @@ -2,6 +2,7 @@ use core::sync::atomic::{AtomicBool, Ordering::SeqCst}; use bao1x_api::*; use bao1x_hal::iox::Iox; +#[cfg(feature = "unsafe-dev")] use bao1x_hal::udma::UartIrq; use bao1x_hal::{udma, udma::GlobalConfig}; use utralib::generated::*; @@ -9,14 +10,13 @@ use utralib::generated::*; pub static USE_CONSOLE: AtomicBool = AtomicBool::new(false); /// A trait for serial like drivers which allows reading from a source. -#[allow(dead_code)] +#[cfg(feature = "unsafe-dev")] pub trait SerialRead { /// Read a single byte. fn getc(&mut self) -> Option; } pub struct Uart {} -#[allow(dead_code)] impl Uart { pub fn putc(&self, c: u8) { if !USE_CONSOLE.load(SeqCst) { @@ -37,35 +37,6 @@ impl Uart { udma_uart.write(&buf); } } - - fn put_digit(&mut self, d: u8) { - let nyb = d & 0xF; - let c = if nyb < 10 { nyb + 0x30 } else { nyb + 0x61 - 10 }; - assert!(c >= 0x30, "conversion failed!"); - self.putc(c); - } - - pub fn put_hex(&mut self, c: u8) { - self.put_digit(c >> 4); - self.put_digit(c & 0xF); - } - - pub fn newline(&mut self) { - self.putc(0xa); - self.putc(0xd); - } - - pub fn print_hex_word(&mut self, word: u32) { - for &byte in word.to_be_bytes().iter() { - self.put_hex(byte); - } - } - - pub fn tiny_write_str(&mut self, s: &str) { - for c in s.bytes() { - self.putc(c); - } - } } use core::fmt::{Error, Write}; @@ -78,6 +49,7 @@ impl Write for Uart { } } +#[cfg(feature = "unsafe-dev")] impl SerialRead for Uart { fn getc(&mut self) -> Option { let uart_buf_addr = crate::platform::UART_IFRAM_ADDR; @@ -123,6 +95,7 @@ macro_rules! println }); } +#[cfg(feature = "unsafe-dev")] pub fn setup_rx(perclk: u32) -> bao1x_hal::udma::Uart { let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32); let udma_global = GlobalConfig::new(); @@ -168,3 +141,35 @@ pub fn setup_rx(perclk: u32) -> bao1x_hal::udma::Uart { udma_uart } + +#[cfg(not(feature = "unsafe-dev"))] +pub fn setup_tx(perclk: u32) -> bao1x_hal::udma::Uart { + let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32); + let udma_global = GlobalConfig::new(); + + iox.set_alternate_function(IoxPort::PB, 14, IoxFunction::AF1); + // tx as output + iox.set_gpio_dir(IoxPort::PB, 14, IoxDir::Output); + + udma_global.clock_on(PeriphId::Uart2); + udma_global.map_event( + PeriphId::Uart2, + PeriphEventType::Uart(EventUartOffset::Tx), + EventChannel::Channel1, + ); + + let baudrate: u32 = crate::UART_BAUD; + let freq: u32 = perclk / 2; + + // the address of the UART buffer is "hard-allocated" at an offset one page from the top of + // IFRAM0. This is a convention that must be respected by the UDMA UART library implementation + // for things to work. + let uart_buf_addr = crate::platform::UART_IFRAM_ADDR; + let udma_uart = unsafe { + // safety: this is safe to call, because we set up clock and events prior to calling new. + udma::Uart::get_handle(utra::udma_uart_2::HW_UDMA_UART_2_BASE, uart_buf_addr, uart_buf_addr) + }; + udma_uart.set_baud(baudrate, freq); + + udma_uart +} diff --git a/bao1x-boot/boot0/src/platform/bao1x/irq.rs b/bao1x-boot/boot0/src/platform/bao1x/irq.rs index baea62237..8a74da799 100644 --- a/bao1x-boot/boot0/src/platform/bao1x/irq.rs +++ b/bao1x-boot/boot0/src/platform/bao1x/irq.rs @@ -1,8 +1,13 @@ -use riscv::register::{mcause, mie, mstatus}; -use vexriscv::register::vexriscv::{mim, mip}; +#[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")] pub fn irq_setup() { unsafe { #[rustfmt::skip] @@ -23,6 +28,7 @@ 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. @@ -43,7 +49,7 @@ pub unsafe extern "C" fn _start_trap() -> ! { #[rustfmt::skip] core::arch::asm!( "csrw mscratch, sp", - "li sp, {scratch_page}", // crate::platform::SCRATCH_PAGE - has to be hard-coded + "li sp, {scratch_page}", // scratch_page, grows up "sw x1, 0*4(sp)", // Skip SP for now "sw x3, 2*4(sp)", @@ -79,23 +85,17 @@ pub unsafe extern "C" fn _start_trap() -> ! { // Save MEPC "csrr t0, mepc", "sw t0, 31*4(sp)", - // Save x1, which was used to calculate the offset. Prior to - // calculating, it was stashed at 0x61006000. - //"li t0, 0x61006000", - //"lw t1, 0*4(t0)", - //"sw t1, 0*4(sp)", // Finally, save SP "csrr t0, mscratch", "sw t0, 1*4(sp)", // Restore a default stack pointer - "li sp, {heap_base}", // heap base, grows down + "li sp, {scratch_page}", // scratch_page, grows down // Note that registers $a0-$a7 still contain the arguments "j _start_trap_rust", - scratch_page = const SCRATCH_PAGE, - heap_base = const HEAP_START + scratch_page = const SCRATCH_PAGE ); } _start_trap_aligned(); @@ -191,8 +191,9 @@ pub extern "C" fn trap_handler( let ms = SYSTEM_TICK_INTERVAL_MS; let mut timer0 = CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32); timer0.wfo(utra::timer0::EV_PENDING_ZERO, 1); - timer0.wfo(utra::timer0::RELOAD_RELOAD, (SYSTEM_CLOCK_FREQUENCY / 1_000) * ms); + timer0.wfo(utra::timer0::RELOAD_RELOAD, (crate::DEFAULT_FCLK_FREQUENCY / 1_000) * ms); } 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 diff --git a/bao1x-boot/boot0/src/repl.rs b/bao1x-boot/boot0/src/repl.rs index 1e0f2671c..3ac34b083 100644 --- a/bao1x-boot/boot0/src/repl.rs +++ b/bao1x-boot/boot0/src/repl.rs @@ -22,17 +22,6 @@ pub struct Repl { do_cmd: bool, } -// courtesy of claude -const K_DATA: &'static [u8; 853] = b"The quick brown fox jumps over the lazy dog while contemplating \ -the meaning of existence in a digital world. Numbers like 123456789 and symbols @#$%^&*() add variety to this test \ -message. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore \ -magna aliqua. Testing patterns: ABCDEFGHIJKLMNOPQRSTUVWXYZ and abcdefghijklmnopqrstuvwxyz provide full alphabet coverage. \ -Special characters !@#$%^&*()_+-=[]{}|;':.,.<>?/ enhance the diversity of this sample text. The year 2024 brings new \ -challenges and opportunities for software development and testing methodologies. Random words like elephant, butterfly, \ -quantum, nebula, crystalline, harmonic, and serendipity fill the remaining space. Pi equals 3.14159265358979323846 \ -approximately. This text serves as a placeholder for various testing scenarios!!!"; -const COLUMNS: usize = 4; - impl Repl { pub fn new() -> Self { Self { cmdline: String::new(), do_cmd: false } } @@ -117,53 +106,6 @@ impl Repl { crate::println!("{}.{} bogomips", (count * 2 * 10_000) / 1_000_000, (count * 2) % 10_000); crate::platform::setup_timer(); } - "peek" => { - if args.len() == 1 || args.len() == 2 { - let addr = usize::from_str_radix(&args[0], 16) - .map_err(|_| Error::help("Peek address is in hex"))?; - - let count = if args.len() == 2 { - if let Ok(count) = u32::from_str_radix(&args[1], 10) { count } else { 1 } - } else { - 1 - }; - // safety: it's not safe to do this, the user peeks at their own risk - let peek = unsafe { core::slice::from_raw_parts(addr as *const u32, count as usize) }; - for (i, &d) in peek.iter().enumerate() { - if (i % COLUMNS) == 0 { - crate::print!("\n\r{:08x}: ", addr + i * size_of::()); - } - crate::print!("{:08x} ", d); - } - crate::println!(""); - } else { - return Err(Error::help("Help: peek [count], addr is in hex, count in decimal")); - } - } - "poke" => { - if args.len() == 2 || args.len() == 3 { - let addr = u32::from_str_radix(&args[0], 16) - .map_err(|_| Error::help("Poke address is in hex"))?; - - let value = - u32::from_str_radix(&args[1], 16).map_err(|_| Error::help("Poke value is in hex"))?; - let count = if args.len() == 3 { - if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } else { 1 } - } else { - 1 - }; - // safety: it's not safe to do this, the user pokes at their own risk - let poke = unsafe { core::slice::from_raw_parts_mut(addr as *mut u32, count as usize) }; - for d in poke.iter_mut() { - *d = value; - } - crate::println!("Poked {:x} into {:x}, {} times", value, addr, count); - } else { - return Err(Error::help( - "Help: poke [count], addr/value is in hex, count in decimal", - )); - } - } "reset" => { let mut rcurst = CSR::new(utra::sysctrl::HW_SYSCTRL_BASE as *mut u32); rcurst.wo(utra::sysctrl::SFR_RCURST0, 0x55AA); @@ -191,61 +133,10 @@ impl Repl { } crate::println!(""); } - "sha2" => { - use digest::Digest; - use hex_literal::hex; - use sha2_bao1x::Sha256; - - const K_EXPECTED_DIGEST_256: [u8; 32] = - hex!("de1b3b58e16d6b12c906898025d4bc5a594075f4fd4252fa88128b2e0b7a266a"); - - let mut pass: bool = true; - let mut hasher = Sha256::new(); - - hasher.update(K_DATA); - // hasher.update(data); - let digest = hasher.finalize(); - - for (&expected, result) in K_EXPECTED_DIGEST_256.iter().zip(digest) { - if expected != result { - pass = false; - } - } - if pass { - crate::println!("Sha256 passed."); - } else { - crate::println!("Sha256 failed: {:x?}", digest); - } - } - "sha5" => { - use digest::Digest; - use hex_literal::hex; - use sha2_bao1x::Sha512; - - // generated by claude. - const K_EXPECTED_DIGEST_512: [u8; 64] = hex!( - "e827276a7d5f2653fe27abc0b0c86533e75acfd4d75253b1229bf86aee19e4a0722691e9ef60510892dc60f4edff795d7875d0d8293a39a7a327a7e1bf07000a" - ); - - let mut pass: bool = true; - let mut hasher = Sha512::new(); - - hasher.update(K_DATA); - // hasher.update(data); - let digest = hasher.finalize(); - - for (&expected, result) in K_EXPECTED_DIGEST_512.iter().zip(digest) { - if expected != result { - pass = false; - } - } - if pass { - crate::println!("Sha512 passed."); - } else { - crate::println!("Sha512 failed: {:x?}", digest); - } - } - "check" => match crate::sigcheck::validate_image(crate::FLASH_BASE as *const u32) { + "check" => match bao1x_hal::sigcheck::validate_image( + crate::FLASH_BASE as *const u32, + bao1x_api::BOOT0_REVOCATION_OFFSET, + ) { Ok(key_number) => crate::println!("sigcheck passed on key {}", key_number), Err(e) => crate::println!("sigcheck failed: {}", e), }, @@ -267,12 +158,19 @@ impl Repl { if new_time >= start_time + 5 { break; } - crate::sigcheck::validate_image(crate::FLASH_BASE as *const u32).ok(); + bao1x_hal::sigcheck::validate_image( + crate::FLASH_BASE as *const u32, + bao1x_api::BOOT0_REVOCATION_OFFSET, + ) + .ok(); count += 1; } crate::println!("{} reps/sec", count / 5); crate::platform::setup_timer(); } + "boot1" => unsafe { + crate::asm::jump_to(bao1x_api::BOOT1_START); + }, _ => { crate::println!("Command not recognized: {}", cmd); crate::print!("Commands include: echo, bogomips, peek, poke, sha256check"); diff --git a/bao1x-boot/boot0/src/sigcheck.rs b/bao1x-boot/boot0/src/sigcheck.rs deleted file mode 100644 index 79fca5ab2..000000000 --- a/bao1x-boot/boot0/src/sigcheck.rs +++ /dev/null @@ -1,99 +0,0 @@ -use alloc::string::String; - -use bao1x_api::signatures::*; -use bao1x_hal::acram::OneWayCounter; -use digest::Digest; -use sha2_bao1x::Sha512; - -/// Offset in the one-way counter array for key revocations -pub const REVOCATION_OFFSET: usize = 124; - -/// 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. -/// -/// Other notes: active current is only 2-4mA over idle current for this loop, so idle current is a good -/// proxy for current draw in boot0. -/// -/// Why this matters: boot0 has to boot the chip under all modes. An external power source is needed for -/// IDD85 > 100mA. Thus we can't boot at max speed config, as not all system configurations have the -/// external regulator. So, we have to work at reduced VDD/frequency and make sure this constraint is met. -pub fn validate_image(img_offset: *const u32) -> Result { - // conjure the signature struct directly out of memory. super unsafe. - let sig_ptr = img_offset as *const SignatureInFlash; - let sig: &SignatureInFlash = unsafe { sig_ptr.as_ref().unwrap() }; - - let signed_len = sig.sealed_data.signed_len; - let image: &[u8] = unsafe { - core::slice::from_raw_parts((img_offset as usize + UNSIGNED_LEN) as *const u8, signed_len as usize) - }; - - if sig.sealed_data.version != BAOCHIP_SIG_VERSION { - crate::println!( - "Version {:x} sig found, should be {:x}", - sig.sealed_data.version, - BAOCHIP_SIG_VERSION - ); - return Err(String::from("invalid sigblock version")); - } - - // checking the function code prevents exploiting code meant for other partitions signed - // with a valid signature as code for the next stage boot. - if !(sig.sealed_data.function_code == FunctionCode::Boot0 as u32 - || sig.sealed_data.function_code == FunctionCode::Boot1 as u32 - || sig.sealed_data.function_code == FunctionCode::UpdatedBoot1 as u32) - { - return Err(String::from("Partition has invalid function code")); - } - - let one_way_counters = OneWayCounter::new(); - let mut secure = false; - let mut passing_key: Option = None; - for (i, key) in sig.sealed_data.pubkeys.iter().enumerate() { - if key.iter().all(|&x| x == 0) { - continue; - } - let revocation_value = one_way_counters.get(REVOCATION_OFFSET + i).expect("internal error"); - if revocation_value != 0 { - crate::println!("Key at index {} is revoked ({}), skipping", i, revocation_value); - continue; - } - - let verifying_key = - ed25519_dalek::VerifyingKey::from_bytes(key).or(Err(String::from("invalid public key")))?; - - let ed25519_signature = ed25519_dalek::Signature::from(sig.signature); - let mut h: Sha512 = Sha512::new(); - h.update(&image); - // debugging note: h.clone() does *not* work. You have to print the hash by modifying - // the function inside the ed25519 crate. - match verifying_key.verify_prehashed(h, None, &ed25519_signature) { - Ok(_) => { - passing_key = Some(i); - if i != sig.sealed_data.pubkeys.len() - 1 { - secure = true; - break; - } else if i == sig.sealed_data.pubkeys.len() - 1 { - // this is the developer key slot - secure = false; - break; - } - } - _ => {} - } - } - - if !secure { - erase_secrets(); - } - if let Some(valid_key) = passing_key { - Ok(valid_key) - } else { - Err(String::from("No valid pubkeys found or signature invalid")) - } -} - -fn erase_secrets() { - // actually, this should check first if the data is 0, then 0 it. Can't afford - // to wear-out the memory every boot by repeatedly overwriting it... - crate::println!("TODO: erase secret data stores on boot to devmode!"); -}