mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-21 09:14:34 +00:00
commit
b678d53165
13 changed files with 242 additions and 10 deletions
3
Cargo.lock
generated
3
Cargo.lock
generated
|
|
@ -421,6 +421,7 @@ dependencies = [
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"num-derive 0.4.2",
|
"num-derive 0.4.2",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
|
"num_enum 0.5.11",
|
||||||
"rkyv 0.8.8",
|
"rkyv 0.8.8",
|
||||||
"xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)",
|
"xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"xous-api-names",
|
"xous-api-names",
|
||||||
|
|
@ -6292,6 +6293,8 @@ dependencies = [
|
||||||
"pkcs8 0.8.0",
|
"pkcs8 0.8.0",
|
||||||
"rand 0.8.5",
|
"rand 0.8.5",
|
||||||
"ring",
|
"ring",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
"svd2utra 0.1.24",
|
"svd2utra 0.1.24",
|
||||||
"xmas-elf",
|
"xmas-elf",
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,9 @@ use alloc::collections::VecDeque;
|
||||||
use core::cell::RefCell;
|
use core::cell::RefCell;
|
||||||
|
|
||||||
use bao1x_api::pubkeys::{BOOT0_SELF_CHECK, BOOT0_TO_ALTBOOT1, BOOT0_TO_BOOT1};
|
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_api::{PARANOID_MODE, PARANOID_MODE_DUPE};
|
||||||
use bao1x_hal::acram::OneWayCounter;
|
use bao1x_hal::acram::OneWayCounter;
|
||||||
use bao1x_hal::hardening::{check_pll, die, mesh_setup};
|
use bao1x_hal::hardening::{check_pll, die, mesh_setup};
|
||||||
|
|
@ -156,7 +158,8 @@ pub unsafe extern "C" fn rust_entry() -> ! {
|
||||||
};
|
};
|
||||||
bollard!(die, 4);
|
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
|
// 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
|
// 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);
|
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();
|
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 ==
|
// == self-validate the image with the keys we put in, just to make sure our code wasn't tampered with ==
|
||||||
|
|
|
||||||
|
|
@ -457,6 +457,49 @@ impl Repl {
|
||||||
} else {
|
} else {
|
||||||
crate::println!("Collateral is set");
|
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 {
|
if !secure {
|
||||||
crate::println!("** System did not meet minimum requirements for security **");
|
crate::println!("** System did not meet minimum requirements for security **");
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [
|
||||||
bytemuck = { version = "1.24", features = ["derive"] }
|
bytemuck = { version = "1.24", features = ["derive"] }
|
||||||
bitbybit = "1.4.0"
|
bitbybit = "1.4.0"
|
||||||
arbitrary-int = "1.2"
|
arbitrary-int = "1.2"
|
||||||
|
num_enum = { version = "0.5", default-features = false }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
std = ["derive-rkyv", "xous-names", "xous-ipc"]
|
std = ["derive-rkyv", "xous-names", "xous-ipc"]
|
||||||
|
|
|
||||||
|
|
@ -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
|
/// 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.
|
/// 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::SERIAL_NUMBER,
|
||||||
crate::offsets::UUID,
|
crate::offsets::UUID,
|
||||||
crate::offsets::IFR_HASH,
|
crate::offsets::IFR_HASH,
|
||||||
|
|
@ -142,6 +142,10 @@ pub const DATA_SLOTS: [SlotIndex; 8] = [
|
||||||
crate::offsets::BAO2_PUBKEY,
|
crate::offsets::BAO2_PUBKEY,
|
||||||
crate::offsets::BETA_PUBKEY,
|
crate::offsets::BETA_PUBKEY,
|
||||||
crate::offsets::DEV_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
|
/// In addition to these KEY_SLOTS, the DEVELOPER_MODE one way counter is a security-important parameter
|
||||||
|
|
|
||||||
|
|
@ -66,6 +66,21 @@ macro_rules! encode_oneway {
|
||||||
|
|
||||||
// =========== ONE WAY COUNTER SLOTS ==============
|
// =========== 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
|
/// 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
|
/// 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
|
/// 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.
|
/// inspecting the value of the high key slot.
|
||||||
pub const COLLATERAL: SlotIndex = SlotIndex::DataRange(261..265, PartitionAccess::Fw0, RwPerms::ReadWrite);
|
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.
|
// Notes on defining the boot0 IFR region.
|
||||||
// RISC-V boot0 region start is defined by IFR slot 6, bits [55:48]
|
// 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]
|
// RISC-V boot1 region start (which is boot0 end) is defined by IFR slot 6, bits[47:40]
|
||||||
|
|
|
||||||
|
|
@ -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
|
/// 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.
|
/// 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::SERIAL_NUMBER,
|
||||||
crate::offsets::UUID,
|
crate::offsets::UUID,
|
||||||
crate::offsets::IFR_HASH,
|
crate::offsets::IFR_HASH,
|
||||||
|
|
@ -41,6 +41,10 @@ pub const DATA_SLOTS: [SlotIndex; 8] = [
|
||||||
crate::offsets::BAO2_PUBKEY,
|
crate::offsets::BAO2_PUBKEY,
|
||||||
crate::offsets::BETA_PUBKEY,
|
crate::offsets::BETA_PUBKEY,
|
||||||
crate::offsets::DEV_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;
|
pub use crate::baosec::ERASE_PROOF;
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
use bytemuck::{Pod, Zeroable};
|
use bytemuck::{Pod, Zeroable};
|
||||||
|
|
||||||
|
use crate::*;
|
||||||
|
|
||||||
/// Total reserved space for the signature block
|
/// Total reserved space for the signature block
|
||||||
pub const SIGBLOCK_LEN: usize = 768;
|
pub const SIGBLOCK_LEN: usize = 768;
|
||||||
/// The jump instruction and the signature itself are not protected
|
/// 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
|
/// These are notional and subject to change
|
||||||
#[repr(u32)]
|
#[repr(u32)]
|
||||||
#[derive(PartialEq, Eq, Clone, Copy)]
|
#[derive(num_enum::TryFromPrimitive, PartialEq, Eq, Clone, Copy)]
|
||||||
pub enum FunctionCode {
|
pub enum FunctionCode {
|
||||||
/// Should never be used
|
/// Should never be used
|
||||||
Invalid = 0,
|
Invalid = 0,
|
||||||
|
|
@ -41,6 +43,21 @@ pub enum FunctionCode {
|
||||||
UpdatedApp = 0x10_0001,
|
UpdatedApp = 0x10_0001,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl FunctionCode {
|
||||||
|
pub fn to_anti_rollback_counter(&self) -> Option<usize> {
|
||||||
|
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 BAOCHIP_SIG_VERSION: u32 = 0x1_00;
|
||||||
pub const PADDING_LEN: usize = SIGBLOCK_LEN - size_of::<SignatureInFlash>();
|
pub const PADDING_LEN: usize = SIGBLOCK_LEN - size_of::<SignatureInFlash>();
|
||||||
pub const MAGIC_NUMBER: [u32; 2] = [u32::from_be_bytes(*b"yumy"), u32::from_be_bytes(*b"Bao3")];
|
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
|
/// Function code of the signed block. Used to provide metadata about what is inside the signed
|
||||||
/// block. See `FunctionCode`.
|
/// block. See `FunctionCode`.
|
||||||
pub function_code: u32,
|
pub function_code: u32,
|
||||||
/// Reserved for future use
|
/// Anti-rollback version number. This is matched against a one-way counter stored in the
|
||||||
pub reserved: u32,
|
/// one-way counter memory bank.
|
||||||
|
pub anti_rollback: u32,
|
||||||
/// Minimum version of target code that can process this update. This allows us to break
|
/// 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.
|
/// compatibility with extremely old code bases, should we need to.
|
||||||
pub min_semver: [u8; 16],
|
pub min_semver: [u8; 16],
|
||||||
|
|
@ -156,7 +174,7 @@ impl Default for SealedFields {
|
||||||
magic: MAGIC_NUMBER,
|
magic: MAGIC_NUMBER,
|
||||||
signed_len: 0,
|
signed_len: 0,
|
||||||
function_code: 0,
|
function_code: 0,
|
||||||
reserved: 0,
|
anti_rollback: 0,
|
||||||
min_semver: [0u8; 16],
|
min_semver: [0u8; 16],
|
||||||
semver: [0u8; 16],
|
semver: [0u8; 16],
|
||||||
pubkeys: [Pubkey::default(); 4],
|
pubkeys: [Pubkey::default(); 4],
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,9 @@ const COUNTER_STRIDE_U32: usize = ONEWAY_LEN / size_of::<u32>();
|
||||||
pub const MAX_ONEWAY_COUNTERS: usize = 8192 / ONEWAY_LEN;
|
pub const MAX_ONEWAY_COUNTERS: usize = 8192 / ONEWAY_LEN;
|
||||||
pub const CODESEL_END: usize = 0x603D_A000;
|
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)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub enum OneWayErr {
|
pub enum OneWayErr {
|
||||||
OutOfBounds,
|
OutOfBounds,
|
||||||
|
|
|
||||||
|
|
@ -123,10 +123,10 @@ pub fn validate_image(
|
||||||
return Err(String::from("Partition has invalid function code"));
|
return Err(String::from("Partition has invalid function code"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let one_way_counters = OneWayCounter::new();
|
||||||
bollard!(die_no_std, 4);
|
bollard!(die_no_std, 4);
|
||||||
|
|
||||||
// crate::println!("Signature: {:x?}", sig.signature);
|
// crate::println!("Signature: {:x?}", sig.signature);
|
||||||
let one_way_counters = OneWayCounter::new();
|
|
||||||
let mut passing_key: Option<usize> = None;
|
let mut passing_key: Option<usize> = None;
|
||||||
let mut passing_key2: Option<usize> = None;
|
let mut passing_key2: Option<usize> = None;
|
||||||
csprng.as_deref_mut().map(|rng| rng.random_delay());
|
csprng.as_deref_mut().map(|rng| rng.random_delay());
|
||||||
|
|
@ -254,6 +254,42 @@ pub fn validate_image(
|
||||||
if let Some(valid_key2) = passing_key2 {
|
if let Some(valid_key2) = passing_key2 {
|
||||||
csprng.as_deref_mut().map(|rng| rng.random_delay());
|
csprng.as_deref_mut().map(|rng| rng.random_delay());
|
||||||
if let Some(valid_key) = passing_key {
|
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);
|
bollard!(die_no_std, 4);
|
||||||
Ok((
|
Ok((
|
||||||
valid_key,
|
valid_key,
|
||||||
|
|
|
||||||
22
signing/anti-rollback.hjson
Normal file
22
signing/anti-rollback.hjson
Normal file
|
|
@ -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"
|
||||||
|
}
|
||||||
|
|
@ -29,6 +29,8 @@ aes-gcm-siv = "0.11.1"
|
||||||
bao1x-api = { path = "../libs/bao1x-api" }
|
bao1x-api = { path = "../libs/bao1x-api" }
|
||||||
hex-literal = "1.0.0"
|
hex-literal = "1.0.0"
|
||||||
byteorder = "1.2"
|
byteorder = "1.2"
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1.0"
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "copy-object"
|
name = "copy-object"
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fs;
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
|
@ -186,6 +188,8 @@ pub fn sign_image(
|
||||||
Ok(dest_file)
|
Ok(dest_file)
|
||||||
}
|
}
|
||||||
Version::Bao1xV1 => {
|
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))?;
|
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
|
// First 2 bytes of the `private_key` are a record specifier and length field. Check they are
|
||||||
// correct.
|
// correct.
|
||||||
|
|
@ -203,6 +207,9 @@ pub fn sign_image(
|
||||||
.map_err(|e| format!("{}", e))?;
|
.map_err(|e| format!("{}", e))?;
|
||||||
let pubkey = sk.public_key();
|
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 {
|
let function_code = match function_code {
|
||||||
Some("boot0") => FunctionCode::Boot0,
|
Some("boot0") => FunctionCode::Boot0,
|
||||||
|
|
@ -218,7 +225,7 @@ pub fn sign_image(
|
||||||
header.sealed_data.version = version as u32;
|
header.sealed_data.version = version as u32;
|
||||||
header.sealed_data.signed_len = (source.len() + SIGBLOCK_LEN - UNSIGNED_LEN) 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.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.min_semver = minver_bytes;
|
||||||
header.sealed_data.semver = semver;
|
header.sealed_data.semver = semver;
|
||||||
|
|
||||||
|
|
@ -407,3 +414,33 @@ pub fn bin_to_uf2(bytes: &Vec<u8>, family_id: u32, app_start_addr: u32) -> Resul
|
||||||
}
|
}
|
||||||
Ok(outp)
|
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::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads HJSON config file and returns a HashMap for lookups
|
||||||
|
fn read_anti_rollback<P: AsRef<Path>>(path: P) -> Result<HashMap<String, u32>, Box<dyn std::error::Error>> {
|
||||||
|
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<String, String> = 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)
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue