From f76b85c95e2df6b8febe824d4013975badc9400a Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 26 Sep 2025 22:56:49 +0800 Subject: [PATCH] signature checking now works also some light benchmarking code. --- bao1x-boot/boot0/Cargo.toml | 4 +- bao1x-boot/boot0/src/main.rs | 1 + bao1x-boot/boot0/src/platform/bao1x/bao1x.rs | 2 +- bao1x-boot/boot0/src/repl.rs | 28 +++++ bao1x-boot/boot0/src/sigcheck.rs | 117 ++++++++++++------- 5 files changed, 109 insertions(+), 43 deletions(-) diff --git a/bao1x-boot/boot0/Cargo.toml b/bao1x-boot/boot0/Cargo.toml index 4ec1afbde..0004d5455 100644 --- a/bao1x-boot/boot0/Cargo.toml +++ b/bao1x-boot/boot0/Cargo.toml @@ -18,9 +18,9 @@ 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 = { version = "=2.1.0", optional = true, default-features = false, features = [ - "rand_core", +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", diff --git a/bao1x-boot/boot0/src/main.rs b/bao1x-boot/boot0/src/main.rs index c5b1ff97d..e6413e8cd 100644 --- a/bao1x-boot/boot0/src/main.rs +++ b/bao1x-boot/boot0/src/main.rs @@ -7,6 +7,7 @@ mod asm; mod platform; mod repl; +mod sigcheck; use alloc::collections::VecDeque; use core::cell::RefCell; diff --git a/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs b/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs index 061615d68..6bd7dec03 100644 --- a/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs +++ b/bao1x-boot/boot0/src/platform/bao1x/bao1x.rs @@ -1,3 +1,4 @@ +use bao1x_api::signatures::SIGBLOCK_LEN; use bao1x_hal::udma; use utralib::CSR; use utralib::utra; @@ -14,7 +15,6 @@ static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::Loc pub const RAM_SIZE: usize = utralib::generated::HW_SRAM_MEM_LEN; pub const RAM_BASE: usize = utralib::generated::HW_SRAM_MEM; pub const FLASH_BASE: usize = utralib::generated::HW_RERAM_MEM; -pub const SIGBLOCK_LEN: usize = 768; // this is adjusted inside builder.rs, in the sign-image invocation // This may not be a great assumption. TODO: fix this by deriving from the static boot constants. // also fix this in the baremetal/loader configs. diff --git a/bao1x-boot/boot0/src/repl.rs b/bao1x-boot/boot0/src/repl.rs index 6150108a1..74ca0ee3e 100644 --- a/bao1x-boot/boot0/src/repl.rs +++ b/bao1x-boot/boot0/src/repl.rs @@ -245,6 +245,34 @@ impl Repl { crate::println!("Sha512 failed: {:x?}", digest); } } + "check" => match crate::sigcheck::validate_image(crate::FLASH_BASE as *const u32) { + Ok(_) => crate::println!("sigcheck passed"), + Err(e) => crate::println!("sigcheck failed: {}", e), + }, + "reps" => { + crate::println!("start test"); + // start the RTC + unsafe { (0x4006100c as *mut u32).write_volatile(1) }; + let mut count = 0; + let start_time = unsafe { (0x40061000 as *mut u32).read_volatile() }; + loop { + let new_time = unsafe { (0x40061000 as *mut u32).read_volatile() }; + if new_time != start_time { + break; + } + } + let start_time = unsafe { (0x40061000 as *mut u32).read_volatile() }; + loop { + let new_time = unsafe { (0x40061000 as *mut u32).read_volatile() }; + if new_time >= start_time + 5 { + break; + } + crate::sigcheck::validate_image(crate::FLASH_BASE as *const u32).ok(); + count += 1; + } + crate::println!("{} reps/sec", count / 5); + crate::platform::setup_timer(); + } _ => { 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 index 296cd386e..c1133f457 100644 --- a/bao1x-boot/boot0/src/sigcheck.rs +++ b/bao1x-boot/boot0/src/sigcheck.rs @@ -1,59 +1,96 @@ use alloc::string::String; -use core::convert::TryInto; +use bao1x_api::signatures::*; +use bao1x_hal::acram::OneWayCounter; use digest::Digest; use sha2_bao1x::Sha512; -#[repr(C)] -struct SignatureInFlash { - pub _jal_instruction: u32, - pub version: u32, - pub signed_len: u32, - pub signature: [u8; 64], - pub pubkey: [u8; 32], -} +/// Offset in the one-way counter array for key revocations +pub const REVOCATION_OFFSET: usize = 124; -pub fn validate_image(img_offset: *const u32, fs_prehash: &mut [u8; 64]) -> Result<(), String> { +/// 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<(), String> { // 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.signed_len; + let signed_len = sig.sealed_data.signed_len; let image: &[u8] = unsafe { - core::slice::from_raw_parts( - (img_offset as usize + crate::SIGBLOCK_LEN + size_of::()) as *const u8, - signed_len as usize, - ) + core::slice::from_raw_parts((img_offset as usize + UNSIGNED_LEN) as *const u8, signed_len as usize) }; - let verifying_key = - ed25519_dalek::VerifyingKey::from_bytes(&sig.pubkey).or(Err(String::from("invalid public key")))?; - - // extract the version and length from the signed region - crate::println!("signed_len: {}, image_len: {}", signed_len, image.len()); - let protected_version = - u32::from_le_bytes(image[signed_len as usize - 8..signed_len as usize - 4].try_into().unwrap()); - let protected_len = u32::from_le_bytes(image[signed_len as usize - 4..].try_into().unwrap()); - // check that the signed versions match the version reported in the header - if sig.version != 2 || (sig.version != protected_version) { - crate::println!("version {}, protected_version {}", sig.version, protected_version); + 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")); } - if protected_len != signed_len - 4 { - return Err(String::from("header length doesn't match protected length")); + + // 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 ed25519_signature = ed25519_dalek::Signature::from(sig.signature); - crate::println!("Checking signature..."); - let mut h: Sha512 = Sha512::new(); - h.update(&image); - // The prehash needs to be finalized before we create a new hasher instance. We - // only have one hardware hasher available. - if verifying_key.verify_prehashed(h.clone(), None, &ed25519_signature).is_ok() { - let prehash = h.finalize(); - fs_prehash.copy_from_slice(prehash.as_slice()); - Ok(()) - } else { - Err(String::from("sigcheck failed")) + let one_way_counters = OneWayCounter::new(); + let mut valid = false; + let mut secure = false; + 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(_) => { + if i != sig.sealed_data.pubkeys.len() - 1 { + valid = true; + secure = true; + break; + } else if i == sig.sealed_data.pubkeys.len() - 1 { + // this is the developer key slot + valid = true; + secure = false; + break; + } + } + _ => {} + } } + + if !secure { + erase_secrets(); + } + if valid { Ok(()) } 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!"); }