From 3050fead414f588fa01a3d83a1df65ed01002110 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 22 Jan 2026 19:40:38 +0800 Subject: [PATCH 1/9] add anti-rollback to image creation tool --- tools/Cargo.toml | 2 ++ tools/src/sign_image.rs | 39 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/tools/Cargo.toml b/tools/Cargo.toml index c4b9b31dd..13a51b2bf 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -29,6 +29,8 @@ aes-gcm-siv = "0.11.1" bao1x-api = { path = "../libs/bao1x-api" } hex-literal = "1.0.0" byteorder = "1.2" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" [[bin]] name = "copy-object" diff --git a/tools/src/sign_image.rs b/tools/src/sign_image.rs index 36146448b..bac9256ef 100644 --- a/tools/src/sign_image.rs +++ b/tools/src/sign_image.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; +use std::fs; use std::io::{Read, Write}; use std::path::Path; @@ -186,6 +188,8 @@ pub fn sign_image( Ok(dest_file) } Version::Bao1xV1 => { + let anti_rollback = read_anti_rollback("./signing/anti-rollback.hjson")?; + let pkinfo = PrivateKeyInfo::from_der(&private_key.contents).map_err(|e| format!("{}", e))?; // First 2 bytes of the `private_key` are a record specifier and length field. Check they are // correct. @@ -203,6 +207,9 @@ pub fn sign_image( .map_err(|e| format!("{}", e))?; let pubkey = sk.public_key(); */ + let anti_rollback = anti_rollback + .get(function_code.unwrap_or("unspecified")) + .expect("anti-rollback code not specified"); let function_code = match function_code { Some("boot0") => FunctionCode::Boot0, @@ -218,7 +225,7 @@ pub fn sign_image( header.sealed_data.version = version as u32; header.sealed_data.signed_len = (source.len() + SIGBLOCK_LEN - UNSIGNED_LEN) as u32; header.sealed_data.function_code = function_code as u32; - header.sealed_data.reserved = 0; + header.sealed_data.anti_rollback = *anti_rollback; header.sealed_data.min_semver = minver_bytes; header.sealed_data.semver = semver; @@ -407,3 +414,33 @@ pub fn bin_to_uf2(bytes: &Vec, family_id: u32, app_start_addr: u32) -> Resul } Ok(outp) } + +/// Strips // comments from HJSON and returns valid JSON +fn hjson_to_json(hjson: &str) -> String { + hjson + .lines() + .map(|line| { + // Find the position of // comment marker + if let Some(pos) = line.find("//") { &line[..pos] } else { line } + }) + .collect::>() + .join("\n") +} + +/// Reads HJSON config file and returns a HashMap for lookups +fn read_anti_rollback>(path: P) -> Result, Box> { + let content = fs::read_to_string(path)?; + let json_content = hjson_to_json(&content); + + // Parse as HashMap with string values first + let string_map: HashMap = serde_json::from_str(&json_content)?; + + // Convert string values to u32 + let mut result = HashMap::new(); + for (key, value) in string_map { + let version: u32 = value.parse()?; + result.insert(key, version); + } + + Ok(result) +} From 672f04bcff2c86a5fe4ef90e9bdb33a576e0fa08 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 22 Jan 2026 19:40:52 +0800 Subject: [PATCH 2/9] add anti-rollback specification file this contains the anti-rollback codes for images signable by the signing tool. --- signing/anti-rollback.hjson | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 signing/anti-rollback.hjson diff --git a/signing/anti-rollback.hjson b/signing/anti-rollback.hjson new file mode 100644 index 000000000..13ca5ac26 --- /dev/null +++ b/signing/anti-rollback.hjson @@ -0,0 +1,22 @@ +// Anti-rollback version numbers. Increment these only when there is a security-relevant +// event that requires anti-rollback. In practice the maximum value of these counters is limited +// by the wear-out of the flash memory and the time it takes to set the anti-rollback counter +// to the current rollback level. So in general, we would aim for the maximum value of the counter +// to be in the "teens to dozens" count over the entire product lifetime. +// +// The 0 value is reserved to denote an uninitialized anti-rollback counter +// +// All variants of an image share the same anti-rollback counter. So, for example, dabao and baosec +// images must share a common loader/kernel anit-rollback level. This prevents a weak dabao image from +// being used to hack a baosec image. I have concerns about the scalability of this across more +// and more device types; this might have to be handled with the reserved rollback counters and/or +// reserved function codes in the future. +{ + "boot0": "1", + "boot1": "1", + "loader": "1", + "kernel": "1", + "app": "1", + "swap": "1", + "baremetal": "1" +} \ No newline at end of file From 9d972f59d55a7206bf852f8e6909cd2a1e90d5d3 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 22 Jan 2026 19:42:51 +0800 Subject: [PATCH 3/9] add specifications for anti-rollback and receipt tracking anti-rollback is a number that is stored in a monatomic counter inside the device that is compared against the firmware images presented to the device. If the image version is lower than the anti-rollback counter, the image is rejected. If the image is higher, the anti-rollback counter is incremented until it equals the vesrion in the image. the receipt mechanism is a method for ensuring that cross-third party signed images can't be used to dump keys on other third party images. Every time a boot1 is accepted, a copy of the key block that was used to accept the third party image is stored in the receipt block. If those keys rotate, then the collateral keys are rotated. this prevents a rotation of third-party images from being used to dump other third party images. it does mean that third party signers have to be careful to not rotate any of their signing keys uninitentially. --- libs/bao1x-api/Cargo.toml | 1 + libs/bao1x-api/src/offsets/baosec.rs | 6 +++++- libs/bao1x-api/src/offsets/common.rs | 27 +++++++++++++++++++++++++++ libs/bao1x-api/src/offsets/dabao.rs | 6 +++++- libs/bao1x-api/src/signatures.rs | 26 ++++++++++++++++++++++---- 5 files changed, 60 insertions(+), 6 deletions(-) diff --git a/libs/bao1x-api/Cargo.toml b/libs/bao1x-api/Cargo.toml index c3c834ac3..a21fbcb58 100644 --- a/libs/bao1x-api/Cargo.toml +++ b/libs/bao1x-api/Cargo.toml @@ -16,6 +16,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [ bytemuck = { version = "1.24", features = ["derive"] } bitbybit = "1.4.0" arbitrary-int = "1.2" +num_enum = { version = "0.5", default-features = false } [features] std = ["derive-rkyv", "xous-names", "xous-ipc"] diff --git a/libs/bao1x-api/src/offsets/baosec.rs b/libs/bao1x-api/src/offsets/baosec.rs index 8073fcacd..3b82d6516 100644 --- a/libs/bao1x-api/src/offsets/baosec.rs +++ b/libs/bao1x-api/src/offsets/baosec.rs @@ -133,7 +133,7 @@ pub const ERASE_PROOF: SlotIndex = SlotIndex::Data(256, PartitionAccess::Fw0, Rw /// 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] = [ +pub const DATA_SLOTS: [SlotIndex; 12] = [ crate::offsets::SERIAL_NUMBER, crate::offsets::UUID, crate::offsets::IFR_HASH, @@ -142,6 +142,10 @@ pub const DATA_SLOTS: [SlotIndex; 8] = [ crate::offsets::BAO2_PUBKEY, crate::offsets::BETA_PUBKEY, crate::offsets::DEV_PUBKEY, + crate::offsets::BOOT1_PK_RECEIPT_SLOT0, + crate::offsets::BOOT1_PK_RECEIPT_SLOT1, + crate::offsets::BOOT1_PK_RECEIPT_SLOT2, + crate::offsets::BOOT1_PK_RECEIPT_SLOT3, ]; /// In addition to these KEY_SLOTS, the DEVELOPER_MODE one way counter is a security-important parameter diff --git a/libs/bao1x-api/src/offsets/common.rs b/libs/bao1x-api/src/offsets/common.rs index 9eb49d1a3..12741c764 100644 --- a/libs/bao1x-api/src/offsets/common.rs +++ b/libs/bao1x-api/src/offsets/common.rs @@ -66,6 +66,21 @@ macro_rules! encode_oneway { // =========== ONE WAY COUNTER SLOTS ============== +/// Anti-rollback counters only count up and are used to note what is the minimum rollback +/// version allowed for a firmware stage. Note that this is different from a semver because +/// semvers can change without there being security problems. Anti-rollback counter is in +/// principle limited to 10k increments due to wear out of the underlying memory, so we +/// use a separate counter for that. +pub const RESERVED0_ANTI_ROLLBACK: usize = 56; +pub const RESERVED1_ANTI_ROLLBACK: usize = 57; +pub const BOOT0_ANTI_ROLLBACK: usize = 58; +pub const BOOT1_ANTI_ROLLBACK: usize = 59; +pub const LOADER_ANTI_ROLLBACK: usize = 60; +pub const KERNEL_ANTI_ROLLBACK: usize = 61; +pub const SWAP_ANTI_ROLLBACK: usize = 62; +pub const APP_ANTI_ROLLBACK: usize = 63; +pub const BAREMETAL_ANTI_ROLLBACK: usize = 64; + /// Paranoid mode is written twice; either being non-zero invokes paranoid mode /// In paranoid mode, the glitch detectors are set to trigger aggressively and reset the /// system through automatic hardware means. This can lead to false positives that can @@ -236,6 +251,18 @@ pub const DEV_PUBKEY: SlotIndex = SlotIndex::Data(7, PartitionAccess::All, RwPer /// inspecting the value of the high key slot. pub const COLLATERAL: SlotIndex = SlotIndex::DataRange(261..265, PartitionAccess::Fw0, RwPerms::ReadWrite); +/// Boot1 pubkey `receipt` fields record the last accepted public key used when running boot1. +/// If this changes, the collateral keys need to be erased. This prevents one third-party signed firmware +/// from being used to attack another third-party signed firmware. These keys have a 1:1 correlation +/// with the BAO1, BAO2, BETA, and DEV _PUBKEY slots; the data type doesn't use a range so that iterators +/// can have a cleaner parallel structure when comparing against these. +pub const BOOT1_PK_RECEIPT_SLOT0: SlotIndex = SlotIndex::Data(265, PartitionAccess::Open, RwPerms::ReadWrite); +pub const BOOT1_PK_RECEIPT_SLOT1: SlotIndex = SlotIndex::Data(266, PartitionAccess::Open, RwPerms::ReadWrite); +pub const BOOT1_PK_RECEIPT_SLOT2: SlotIndex = SlotIndex::Data(267, PartitionAccess::Open, RwPerms::ReadWrite); +pub const BOOT1_PK_RECEIPT_SLOT3: SlotIndex = SlotIndex::Data(268, PartitionAccess::Open, RwPerms::ReadWrite); +pub const BOOT1_RECEIPT_SLOTS: [SlotIndex; 4] = + [BOOT1_PK_RECEIPT_SLOT0, BOOT1_PK_RECEIPT_SLOT1, BOOT1_PK_RECEIPT_SLOT2, BOOT1_PK_RECEIPT_SLOT3]; + // Notes on defining the boot0 IFR region. // RISC-V boot0 region start is defined by IFR slot 6, bits [55:48] // RISC-V boot1 region start (which is boot0 end) is defined by IFR slot 6, bits[47:40] diff --git a/libs/bao1x-api/src/offsets/dabao.rs b/libs/bao1x-api/src/offsets/dabao.rs index 24858a9b3..9091fc629 100644 --- a/libs/bao1x-api/src/offsets/dabao.rs +++ b/libs/bao1x-api/src/offsets/dabao.rs @@ -32,7 +32,7 @@ pub const DEFAULT_FCLK_FREQUENCY: u32 = 700_000_000; /// 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] = [ +pub const DATA_SLOTS: [SlotIndex; 12] = [ crate::offsets::SERIAL_NUMBER, crate::offsets::UUID, crate::offsets::IFR_HASH, @@ -41,6 +41,10 @@ pub const DATA_SLOTS: [SlotIndex; 8] = [ crate::offsets::BAO2_PUBKEY, crate::offsets::BETA_PUBKEY, crate::offsets::DEV_PUBKEY, + crate::offsets::BOOT1_PK_RECEIPT_SLOT0, + crate::offsets::BOOT1_PK_RECEIPT_SLOT1, + crate::offsets::BOOT1_PK_RECEIPT_SLOT2, + crate::offsets::BOOT1_PK_RECEIPT_SLOT3, ]; pub use crate::baosec::ERASE_PROOF; diff --git a/libs/bao1x-api/src/signatures.rs b/libs/bao1x-api/src/signatures.rs index 191337446..cbde26ff4 100644 --- a/libs/bao1x-api/src/signatures.rs +++ b/libs/bao1x-api/src/signatures.rs @@ -1,5 +1,7 @@ use bytemuck::{Pod, Zeroable}; +use crate::*; + /// Total reserved space for the signature block pub const SIGBLOCK_LEN: usize = 768; /// The jump instruction and the signature itself are not protected @@ -12,7 +14,7 @@ pub const AAD_LENGTH: usize = 60; // at least 37 bytes, rounded up to the neares /// These are notional and subject to change #[repr(u32)] -#[derive(PartialEq, Eq, Clone, Copy)] +#[derive(num_enum::TryFromPrimitive, PartialEq, Eq, Clone, Copy)] pub enum FunctionCode { /// Should never be used Invalid = 0, @@ -41,6 +43,21 @@ pub enum FunctionCode { UpdatedApp = 0x10_0001, } +impl FunctionCode { + pub fn to_anti_rollback_counter(&self) -> Option { + match self { + Self::Boot0 => Some(BOOT0_ANTI_ROLLBACK), + Self::Boot1 | Self::UpdatedBoot1 => Some(BOOT1_ANTI_ROLLBACK), + Self::Loader | Self::UpdatedLoader => Some(LOADER_ANTI_ROLLBACK), + Self::Kernel | Self::UpdatedKernel => Some(KERNEL_ANTI_ROLLBACK), + Self::Swap | Self::UpdatedSwap => Some(SWAP_ANTI_ROLLBACK), + Self::App | Self::UpdatedApp => Some(APP_ANTI_ROLLBACK), + Self::Baremetal | Self::UpdatedBaremetal => Some(BAREMETAL_ANTI_ROLLBACK), + _ => None, + } + } +} + pub const BAOCHIP_SIG_VERSION: u32 = 0x1_00; pub const PADDING_LEN: usize = SIGBLOCK_LEN - size_of::(); pub const MAGIC_NUMBER: [u32; 2] = [u32::from_be_bytes(*b"yumy"), u32::from_be_bytes(*b"Bao3")]; @@ -121,8 +138,9 @@ pub struct SealedFields { /// Function code of the signed block. Used to provide metadata about what is inside the signed /// block. See `FunctionCode`. pub function_code: u32, - /// Reserved for future use - pub reserved: u32, + /// Anti-rollback version number. This is matched against a one-way counter stored in the + /// one-way counter memory bank. + pub anti_rollback: u32, /// Minimum version of target code that can process this update. This allows us to break /// compatibility with extremely old code bases, should we need to. pub min_semver: [u8; 16], @@ -156,7 +174,7 @@ impl Default for SealedFields { magic: MAGIC_NUMBER, signed_len: 0, function_code: 0, - reserved: 0, + anti_rollback: 0, min_semver: [0u8; 16], semver: [0u8; 16], pubkeys: [Pubkey::default(); 4], From 23b7bc0142d63ecf0664821e3a7c51dca813c38a Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 22 Jan 2026 19:46:07 +0800 Subject: [PATCH 4/9] add an upper limit for counter increments this is a sanity check number that can be used by firmware to vet a counter value before incrementing to it. it's particularly useful to thwart wear-out attacks agaisnt anti-rollback firmware versions, i.e. by specifying an extremely high anti-rollback number one might be able to cause a reset-to-0 failure and this prevents that from happening by limiting the maximum value of the the counter that can be requested. --- libs/bao1x-hal/src/acram.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libs/bao1x-hal/src/acram.rs b/libs/bao1x-hal/src/acram.rs index acf6dd43d..68106a8a0 100644 --- a/libs/bao1x-hal/src/acram.rs +++ b/libs/bao1x-hal/src/acram.rs @@ -24,6 +24,9 @@ const COUNTER_STRIDE_U32: usize = ONEWAY_LEN / size_of::(); pub const MAX_ONEWAY_COUNTERS: usize = 8192 / ONEWAY_LEN; pub const CODESEL_END: usize = 0x603D_A000; +/// This is set by the wear-out limit of the underlying RRAM. +pub const ONEWAY_MAX_VALUE: u32 = 10_0000; + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum OneWayErr { OutOfBounds, From 04dd447745b901f10e33c70515f0538e1ed17323 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 22 Jan 2026 19:48:37 +0800 Subject: [PATCH 5/9] add anti-rollback checking to the signature check routine one minor issue with this implemnetation is it requires dev images to have an anti-rollback counter that matches or exceed the last signed image seen. This is more of a developr ergonomics issue - this will certainly lead to some surprise by developers who are trying to take production devices and "downgrade" them to an old dev tree that has an old anti-rollback firmware number in it. However, I think this is navigable and probably the simplicity of not having an "escape" path for dev-signed imgaes is worth it. All a developer has to do is to set the anti-rollback version number to be equal to or greater than what was reported in the device. --- libs/bao1x-hal/src/sigcheck.rs | 36 +++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/libs/bao1x-hal/src/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index f140ed57a..2f8b557f5 100644 --- a/libs/bao1x-hal/src/sigcheck.rs +++ b/libs/bao1x-hal/src/sigcheck.rs @@ -123,10 +123,44 @@ pub fn validate_image( return Err(String::from("Partition has invalid function code")); } + let one_way_counters = OneWayCounter::new(); + + // It is safe to check the anti-rollback counter before the signature because the + // anti-rollback field is part of the signed data. Thus even if the anti-rollback data + // is forged, it should be caught due to a failing signature check later on. + let claimed_function: FunctionCode = + sig.sealed_data.function_code.try_into().unwrap_or(FunctionCode::Invalid); + let arb_offset = claimed_function.to_anti_rollback_counter(); + match arb_offset { + Some(arb) => { + let arb_value = one_way_counters.get(arb).expect("Can't read anti-rollback value"); + csprng.as_deref_mut().map(|rng| rng.random_delay()); + bollard!(die_no_std, 4); + if arb_value > sig.sealed_data.anti_rollback { + return Err(String::from("Anti-rollback code too old, refusing image")); + } + bollard!(die_no_std, 4); + if arb_value < sig.sealed_data.anti_rollback { + csprng.as_deref_mut().map(|rng| rng.random_delay()); + if sig.sealed_data.anti_rollback >= crate::acram::ONEWAY_MAX_VALUE { + return Err(String::from("Proposed anti-rollback value out of range")); + } + // increment anti-rollback counter to match the current value of the signed image + bollard!(die_no_std, 4); + while one_way_counters.get(arb).unwrap() < sig.sealed_data.anti_rollback { + bollard!(die_no_std, 4); + // safety: anti-rollback counter argument is from a set of constants in bao1x_api that + // are pre-validated. + unsafe { one_way_counters.inc(arb).ok() }; + } + } + } + _ => return Err(String::from("Invalid anti-rollback code, aborting")), + } + bollard!(die_no_std, 4); // crate::println!("Signature: {:x?}", sig.signature); - let one_way_counters = OneWayCounter::new(); let mut passing_key: Option = None; let mut passing_key2: Option = None; csprng.as_deref_mut().map(|rng| rng.random_delay()); From 27250c65dcc4edeeb9588f03d374ce3859cb3355 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 22 Jan 2026 23:15:53 +0800 Subject: [PATCH 6/9] move anti-rollback check to after the signature has been validated I decided i feel too uncomfortable doing any state changes based on unvalidated data. I can't see a downside to moving the check to only after the signature has been verified. --- libs/bao1x-hal/src/sigcheck.rs | 70 +++++++++++++++++----------------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/libs/bao1x-hal/src/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index 2f8b557f5..59469b25d 100644 --- a/libs/bao1x-hal/src/sigcheck.rs +++ b/libs/bao1x-hal/src/sigcheck.rs @@ -124,40 +124,6 @@ pub fn validate_image( } let one_way_counters = OneWayCounter::new(); - - // It is safe to check the anti-rollback counter before the signature because the - // anti-rollback field is part of the signed data. Thus even if the anti-rollback data - // is forged, it should be caught due to a failing signature check later on. - let claimed_function: FunctionCode = - sig.sealed_data.function_code.try_into().unwrap_or(FunctionCode::Invalid); - let arb_offset = claimed_function.to_anti_rollback_counter(); - match arb_offset { - Some(arb) => { - let arb_value = one_way_counters.get(arb).expect("Can't read anti-rollback value"); - csprng.as_deref_mut().map(|rng| rng.random_delay()); - bollard!(die_no_std, 4); - if arb_value > sig.sealed_data.anti_rollback { - return Err(String::from("Anti-rollback code too old, refusing image")); - } - bollard!(die_no_std, 4); - if arb_value < sig.sealed_data.anti_rollback { - csprng.as_deref_mut().map(|rng| rng.random_delay()); - if sig.sealed_data.anti_rollback >= crate::acram::ONEWAY_MAX_VALUE { - return Err(String::from("Proposed anti-rollback value out of range")); - } - // increment anti-rollback counter to match the current value of the signed image - bollard!(die_no_std, 4); - while one_way_counters.get(arb).unwrap() < sig.sealed_data.anti_rollback { - bollard!(die_no_std, 4); - // safety: anti-rollback counter argument is from a set of constants in bao1x_api that - // are pre-validated. - unsafe { one_way_counters.inc(arb).ok() }; - } - } - } - _ => return Err(String::from("Invalid anti-rollback code, aborting")), - } - bollard!(die_no_std, 4); // crate::println!("Signature: {:x?}", sig.signature); @@ -288,6 +254,42 @@ pub fn validate_image( if let Some(valid_key2) = passing_key2 { csprng.as_deref_mut().map(|rng| rng.random_delay()); if let Some(valid_key) = passing_key { + // Check anti-rollback only after we have confirmed a signature to mitigate the + // possibility of wear-out attacks by unsigned images that set the anti-rollback + // field to a high number + let claimed_function: FunctionCode = + sig.sealed_data.function_code.try_into().unwrap_or(FunctionCode::Invalid); + let arb_offset = claimed_function.to_anti_rollback_counter(); + match arb_offset { + Some(arb) => { + let arb_value = one_way_counters.get(arb).expect("Can't read anti-rollback value"); + csprng.as_deref_mut().map(|rng| rng.random_delay()); + bollard!(die_no_std, 4); + if arb_value > sig.sealed_data.anti_rollback { + let mut err_msg = String::from("Anti-rollback code too old, refusing image: "); + use alloc::string::ToString; + err_msg.push_str(&arb_value.to_string()); + return Err(err_msg); + } + bollard!(die_no_std, 4); + if arb_value < sig.sealed_data.anti_rollback { + csprng.as_deref_mut().map(|rng| rng.random_delay()); + if sig.sealed_data.anti_rollback >= crate::acram::ONEWAY_MAX_VALUE { + return Err(String::from("Proposed anti-rollback value out of range")); + } + // increment anti-rollback counter to match the current value of the signed image + bollard!(die_no_std, 4); + while one_way_counters.get(arb).unwrap() < sig.sealed_data.anti_rollback { + bollard!(die_no_std, 4); + // safety: anti-rollback counter argument is from a set of constants in bao1x_api + // that are pre-validated. + unsafe { one_way_counters.inc(arb).ok() }; + } + } + } + _ => return Err(String::from("Invalid anti-rollback code, aborting")), + } + bollard!(die_no_std, 4); Ok(( valid_key, From dce0bac16e7cb98fe883441501699e6497d66976 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 22 Jan 2026 23:17:26 +0800 Subject: [PATCH 7/9] add receipt processing to boot0 --- bao1x-boot/boot0/src/main.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/bao1x-boot/boot0/src/main.rs b/bao1x-boot/boot0/src/main.rs index 6df2ba214..d446621ef 100644 --- a/bao1x-boot/boot0/src/main.rs +++ b/bao1x-boot/boot0/src/main.rs @@ -15,7 +15,9 @@ 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, BOOT1_PUBKEY_FAIL, DEVELOPER_MODE, HardenedBool, bollard}; +use bao1x_api::{ + BOOT0_PUBKEY_FAIL, BOOT1_PUBKEY_FAIL, BOOT1_RECEIPT_SLOTS, DEVELOPER_MODE, HardenedBool, bollard, +}; use bao1x_api::{PARANOID_MODE, PARANOID_MODE_DUPE}; use bao1x_hal::acram::OneWayCounter; use bao1x_hal::hardening::{check_pll, die, mesh_setup}; @@ -156,7 +158,8 @@ pub unsafe extern "C" fn rust_entry() -> ! { }; bollard!(die, 4); - // mutual distrust: if any boot1 keys match those in the indelible array, erase the collateral + // mutual distrust - don't trust Baochip. If any boot1 keys match those in the indelible array, erase the + // collateral // The IFR (indelible) copy is weird, because the highest byte doesn't match (it's actually a flag that // indicates the region has to be write protected). Thus, the IFR keys are a set of four, disjointed @@ -202,6 +205,35 @@ pub unsafe extern "C" fn rust_entry() -> ! { } bollard!(die, 4); + // mutual distrust - don't trust other third party firmware. If the boot1 key block doesn't match the + // previously captured receipt, erase collateral + for (key, slot) in boot1_block.sealed_data.pubkeys.iter().zip(BOOT1_RECEIPT_SLOTS) { + csprng.random_delay(); + bollard!(die, 4); + let receipt = slot_mgr.read(&slot).unwrap(); + if &key.pk != receipt { + // first, erase collateral + bao1x_hal::sigcheck::erase_collateral(&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 + + // next, copy all the keys into the receipt array + let mut rram = bao1x_hal::rram::Reram::new(); + for (key, slot) in boot1_block.sealed_data.pubkeys.iter().zip(BOOT1_RECEIPT_SLOTS) { + csprng.random_delay(); + bollard!(die, 4); + // make the error handling permissive so we don't fail to boot on coding errors + match slot_mgr.write(&mut rram, &slot, &key.pk) { + Ok(_) => {} + Err(e) => crate::println!("Warning: couldn't update receipt slots {:?}", e), + }; + } + + // finally break out of the loop - no need to compare any further + break; + } + } + let (paranoid1, paranoid2) = owc.hardened_get2(PARANOID_MODE, PARANOID_MODE_DUPE).unwrap(); // == self-validate the image with the keys we put in, just to make sure our code wasn't tampered with == From 013a4e87716ce671a3737fc949161ac7e9f0213b Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 22 Jan 2026 23:17:50 +0800 Subject: [PATCH 8/9] add anti-rollback and receipt processing to security audit command --- bao1x-boot/boot1/src/repl.rs | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/bao1x-boot/boot1/src/repl.rs b/bao1x-boot/boot1/src/repl.rs index aa7c564cf..776e36577 100644 --- a/bao1x-boot/boot1/src/repl.rs +++ b/bao1x-boot/boot1/src/repl.rs @@ -457,6 +457,49 @@ impl Repl { } else { crate::println!("Collateral is set"); } + let boot1_block_ptr = + bao1x_api::BOOT1_START as *const bao1x_api::signatures::SignatureInFlash; + let boot1_block: &bao1x_api::signatures::SignatureInFlash = + unsafe { boot1_block_ptr.as_ref().unwrap() }; + let mut receipts_ok = true; + for (key, slot) in boot1_block.sealed_data.pubkeys.iter().zip(BOOT1_RECEIPT_SLOTS) { + let receipt = slot_mgr.read(&slot).unwrap(); + if &key.pk != receipt { + receipts_ok = false; + break; + } + } + if !receipts_ok { + crate::println!("Boot1 receipts do not match"); + secure = false; + } else { + crate::println!("Boot1 receipts OK"); + } + let claimed_function: bao1x_api::signatures::FunctionCode = boot1_block + .sealed_data + .function_code + .try_into() + .unwrap_or(bao1x_api::signatures::FunctionCode::Invalid); + let arb_offset = claimed_function.to_anti_rollback_counter(); + match arb_offset { + Some(arb) => { + let arb_value = owc.get(arb).expect("Can't read anti-rollback value"); + if arb_value != boot1_block.sealed_data.anti_rollback { + crate::println!( + "Anti-rollback code mismatch! Counter {} / image {}", + arb_value, + boot1_block.sealed_data.anti_rollback + ); + secure = false; + } else { + crate::println!("Boot1 anti-rollback OK"); + } + } + None => { + crate::println!("Anti-rollback counter offset invalid!"); + secure = false; + } + } if !secure { crate::println!("** System did not meet minimum requirements for security **"); From d96f0ad654c92c99853a8464b33964d08ceef0e4 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 22 Jan 2026 23:18:18 +0800 Subject: [PATCH 9/9] update dependencies --- Cargo.lock | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 8055db5f0..c8f265c62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -421,6 +421,7 @@ dependencies = [ "bytemuck", "num-derive 0.4.2", "num-traits", + "num_enum 0.5.11", "rkyv 0.8.8", "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-names", @@ -6292,6 +6293,8 @@ dependencies = [ "pkcs8 0.8.0", "rand 0.8.5", "ring", + "serde", + "serde_json", "sha2", "svd2utra 0.1.24", "xmas-elf",