Merge pull request #728 from betrusted-io/alpha1

Alpha1 release tag
This commit is contained in:
bunnie 2025-11-16 23:05:25 +08:00 committed by GitHub
commit 0a2c57686c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 307 additions and 358 deletions

Binary file not shown.

View file

@ -32,7 +32,7 @@ use crate::secboot::try_boot;
// Notes: // Notes:
// - "Towards" - not a release yet, but working towards the stated milestone // - "Towards" - not a release yet, but working towards the stated milestone
// - Eliminating "Towards" is done at the tag-out point. // - Eliminating "Towards" is done at the tag-out point.
const RELEASE_DESCRIPTION: &'static str = "Towards Alpha-1"; const RELEASE_DESCRIPTION: &'static str = "Alpha-1";
static UART_RX: Mutex<RefCell<VecDeque<u8>>> = Mutex::new(RefCell::new(VecDeque::new())); static UART_RX: Mutex<RefCell<VecDeque<u8>>> = Mutex::new(RefCell::new(VecDeque::new()));
#[allow(dead_code)] #[allow(dead_code)]
@ -78,7 +78,10 @@ pub unsafe extern "C" fn rust_entry() -> ! {
crate::println_d!("TX_IDLE: {:?}", crate::platform::usb::TX_IDLE.load(Ordering::SeqCst)); crate::println_d!("TX_IDLE: {:?}", crate::platform::usb::TX_IDLE.load(Ordering::SeqCst));
let perclk: u32; let perclk: u32;
(board_type, perclk) = crate::platform::early_init(board_type); (board_type, perclk) = crate::platform::early_init(board_type);
#[cfg(not(feature = "alt-boot1"))]
crate::println!("\n~~Boot1 up! ({}: {})~~\n", crate::version::SEMVER, RELEASE_DESCRIPTION); crate::println!("\n~~Boot1 up! ({}: {})~~\n", crate::version::SEMVER, RELEASE_DESCRIPTION);
#[cfg(feature = "alt-boot1")]
crate::println!("\n~~Alt-Boot1 up! ({}: {})~~\n", crate::version::SEMVER, RELEASE_DESCRIPTION);
crate::println!("Configured board type: {:?}", board_type); crate::println!("Configured board type: {:?}", board_type);
if board_type == BoardTypeCoding::Baosec { if board_type == BoardTypeCoding::Baosec {
IS_BAOSEC.store(true, Ordering::SeqCst); IS_BAOSEC.store(true, Ordering::SeqCst);
@ -91,6 +94,7 @@ pub unsafe extern "C" fn rust_entry() -> ! {
} }
board_type = one_way.get_decoded::<bao1x_api::BoardTypeCoding>().expect("owc coding error"); board_type = one_way.get_decoded::<bao1x_api::BoardTypeCoding>().expect("owc coding error");
crate::println!("Re-configured board type: {:?}", board_type); crate::println!("Re-configured board type: {:?}", board_type);
IS_BAOSEC.store(false, Ordering::SeqCst);
} }
} }

View file

@ -72,6 +72,13 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) {
crate::println!("Public ID init done."); crate::println!("Public ID init done.");
} }
// Delegate in-system key setup to the OS. Don't do it in the bootloader. This code is
// too hard to get right to be doing it here, and there is no ostensible security advantage
// in doing it at this stage versus in the system. Reasoning: the in-system key setup would
// be done in the factory, post-wafer probe, regardless. Whether it's hard-coded into the boot1
// stage or left to be flexible based on the OS's needs doesn't make a difference because the
// point of keying is still going to be the factory.
/*
if (*board_type == bao1x_api::BoardTypeCoding::Baosec if (*board_type == bao1x_api::BoardTypeCoding::Baosec
&& owc.get(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() == 0) && owc.get(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() == 0)
|| (*board_type == bao1x_api::BoardTypeCoding::Dabao || (*board_type == bao1x_api::BoardTypeCoding::Dabao
@ -109,6 +116,7 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) {
} }
crate::println!("Secret ID init done."); crate::println!("Secret ID init done.");
} }
*/
#[cfg(feature = "print-ifr")] #[cfg(feature = "print-ifr")]
print_ifr(); print_ifr();
@ -154,10 +162,6 @@ fn check_and_fix_acls(rram: &mut Reram, slot_mgr: &mut SlotManager, slot_list: &
let mut is_consistent = true; let mut is_consistent = true;
let mut acl = match slot_mgr.get_acl(&slot_element) { let mut acl = match slot_mgr.get_acl(&slot_element) {
Ok(settings) => settings, Ok(settings) => settings,
Err(bao1x_api::AccessError::KeyAclInconsistency(prototype)) => {
is_consistent = false;
AccessSettings::Key(prototype)
}
Err(bao1x_api::AccessError::DataAclInconsistency(prototype)) => { Err(bao1x_api::AccessError::DataAclInconsistency(prototype)) => {
is_consistent = false; is_consistent = false;
AccessSettings::Data(prototype) AccessSettings::Data(prototype)
@ -167,9 +171,6 @@ fn check_and_fix_acls(rram: &mut Reram, slot_mgr: &mut SlotManager, slot_list: &
let (pa, rw) = slot_element.get_access_spec(); let (pa, rw) = slot_element.get_access_spec();
let is_correct = match acl { let is_correct = match acl {
AccessSettings::Data(sa) => sa.get_partition_access() == pa && sa.get_rw_permissions() == rw, AccessSettings::Data(sa) => sa.get_partition_access() == pa && sa.get_rw_permissions() == rw,
AccessSettings::Key(sa) => {
sa.get_partition_access() == pa && sa.get_rw_permissions() == rw && sa.akey_id() == 31
}
}; };
if !is_correct || !is_consistent { if !is_correct || !is_consistent {
crate::println!( crate::println!(
@ -184,14 +185,14 @@ fn check_and_fix_acls(rram: &mut Reram, slot_mgr: &mut SlotManager, slot_list: &
sa.set_partition_access(&pa); sa.set_partition_access(&pa);
sa.set_rw_permissions(rw); sa.set_rw_permissions(rw);
} }
AccessSettings::Key(sa) => { }
sa.set_partition_access(&pa); crate::println!("Writing ACL raw value: {:x?}", acl);
sa.set_rw_permissions(rw); match slot_mgr.set_acl(rram, slot_element, &acl) {
sa.set_akey_id(0xFF); // 0xff disables key chaining to access the key Ok(_) => {}
Err(e) => {
crate::println!("Couldn't set ACL for {:?} ({:?})", slot_element, e);
} }
} }
crate::println!("Fixed ACL raw value: {:x?}", acl);
slot_mgr.set_acl(rram, slot_element, &acl).unwrap();
} }
} }
} }
@ -225,16 +226,6 @@ fn print_slots(slot_mgr: &SlotManager, slot_list: &[SlotIndex]) {
bytes bytes
); );
}, },
SlotType::Key => unsafe {
let bytes = slot_mgr.read_key_slot(data_index);
let acl = slot_mgr.get_key_acl(acl_index);
crate::println!(
" Key {} ({:x?}): {:x?}",
data_index / SLOT_ELEMENT_LEN_BYTES,
acl,
bytes
);
},
} }
} }
} }

View file

@ -69,8 +69,12 @@ pub const FS_MAX_PKT_SIZE: usize = 64;
pub const HS_MAX_PKT_SIZE: usize = 512; pub const HS_MAX_PKT_SIZE: usize = 512;
pub(crate) fn enable_mass_storage_eps(this: &mut CorigineUsb, ep_num: u8) { pub(crate) fn enable_mass_storage_eps(this: &mut CorigineUsb, ep_num: u8) {
this.ep_enable(ep_num, USB_RECV, HS_MAX_PKT_SIZE as _, EpType::BulkOutbound); let mps = match this.get_speed() {
this.ep_enable(ep_num, USB_SEND, HS_MAX_PKT_SIZE as _, EpType::BulkInbound); PortSpeed::Fs => FS_MAX_PKT_SIZE,
_ => HS_MAX_PKT_SIZE,
};
this.ep_enable(ep_num, USB_RECV, mps as _, EpType::BulkOutbound);
this.ep_enable(ep_num, USB_SEND, mps as _, EpType::BulkInbound);
} }
// Call from USB_REQ_SET_CONFIGURATION after setting device state to Configured // Call from USB_REQ_SET_CONFIGURATION after setting device state to Configured
@ -78,12 +82,20 @@ pub(crate) fn enable_composite_eps(this: &mut CorigineUsb) {
// MSD endpoints // MSD endpoints
enable_mass_storage_eps(this, 1); enable_mass_storage_eps(this, 1);
let int_mps = match this.get_speed() {
PortSpeed::Fs => FS_INT_MPS,
_ => HS_INT_MPS,
};
// CDC notification IN (interrupt) // CDC notification IN (interrupt)
this.ep_enable(2, USB_SEND, HS_INT_MPS as _, EpType::IntrInbound); this.ep_enable(2, USB_SEND, int_mps as _, EpType::IntrInbound);
let bulk_mps = match this.get_speed() {
PortSpeed::Fs => FS_BULK_MPS,
_ => HS_BULK_MPS,
};
// CDC data bulk OUT and IN // CDC data bulk OUT and IN
this.ep_enable(3, USB_RECV, HS_BULK_MPS as _, EpType::BulkOutbound); this.ep_enable(3, USB_RECV, bulk_mps as _, EpType::BulkOutbound);
this.ep_enable(3, USB_SEND, HS_BULK_MPS as _, EpType::BulkInbound); this.ep_enable(3, USB_SEND, bulk_mps as _, EpType::BulkInbound);
} }
pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, length: usize) { pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, length: usize) {

View file

@ -479,7 +479,11 @@ impl Repl {
crate::println!("Permissions (actual): {:x?}", acl); crate::println!("Permissions (actual): {:x?}", acl);
// attempt to clear the permissions, making the keys malleable // attempt to clear the permissions, making the keys malleable
slot_mgr slot_mgr
.set_acl(&mut rram, &key, &AccessSettings::Key(KeySlotAccess::new_with_raw_value(0))) .set_acl(
&mut rram,
&key,
&AccessSettings::Data(DataSlotAccess::new_with_raw_value(0)),
)
.ok(); // if we can't clear, that's by design .ok(); // if we can't clear, that's by design
let acl = slot_mgr.get_acl(&key).unwrap(); let acl = slot_mgr.get_acl(&key).unwrap();

View file

@ -49,7 +49,7 @@ pub fn try_boot(or_die: bool) {
if tag == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] if tag == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT]
|| k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT
{ {
crate::println!("Developer key detected, ensuring secret are erased"); crate::println!("Developer key detected, ensuring secrets are erased");
bao1x_hal::sigcheck::erase_secrets(); bao1x_hal::sigcheck::erase_secrets();
} }
// this has to be called *after* erase_secrets, because we can't erase the secrets // this has to be called *after* erase_secrets, because we can't erase the secrets

View file

@ -9,7 +9,7 @@
param( param(
[Parameter(Mandatory = $true)] [Parameter(Mandatory = $true)]
[ValidateSet("baremetal", "dabao", "baosec")] [ValidateSet("baremetal", "dabao", "baosec", "bootloader", "kernel", "loader", "swap", "apps", "boot1", "alt-boot1")]
[string]$Config, [string]$Config,
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
@ -26,25 +26,42 @@ $SIGNING_DIR = ".\signing\fido-signer"
# Define configurations and their associated images with function codes # Define configurations and their associated images with function codes
# Modify these mappings according to your actual image names and function codes # Modify these mappings according to your actual image names and function codes
$configurations = @{ $configurations = @{
"baremetal" = @( "bootloader" = @(
@{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }, @{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }, @{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "bao1x-alt-boot1.img"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }
)
"baremetal" = @(
@{ Image = "baremetal.img"; FunctionCode = "baremetal" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" } @{ Image = "baremetal.img"; FunctionCode = "baremetal" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }
) )
"dabao" = @( "dabao" = @(
@{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } @{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
@{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } @{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
@{ Image = "app.img"; FunctionCode = "app" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } @{ Image = "apps.img"; FunctionCode = "app" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
) )
"baosec" = @( "baosec" = @(
@{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } @{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
@{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } @{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
@{ Image = "swap.img"; FunctionCode = "swap" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" } @{ Image = "swap.img"; FunctionCode = "swap" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
) )
"kernel" = @(
@{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
)
"loader" = @(
@{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
)
"swap" = @(
@{ Image = "swap.img"; FunctionCode = "swap" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
)
"apps" = @(
@{ Image = "apps.img"; FunctionCode = "app" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
)
"boot1" = @(
@{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }
)
"alt-boot1" = @(
@{ Image = "bao1x-alt-boot1.img"; FunctionCode = "baremetal" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }
)
} }
# Color output functions for better visibility # Color output functions for better visibility

View file

@ -9,12 +9,20 @@ pub static TX_IDLE: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicB
// Call from USB_REQ_SET_CONFIGURATION after setting device state to Configured // Call from USB_REQ_SET_CONFIGURATION after setting device state to Configured
pub(crate) fn enable_serial_eps(this: &mut CorigineUsb) { pub(crate) fn enable_serial_eps(this: &mut CorigineUsb) {
let int_mps = match this.get_speed() {
PortSpeed::Fs => FS_INT_MPS,
_ => HS_INT_MPS,
};
// CDC notification IN (interrupt) // CDC notification IN (interrupt)
this.ep_enable(2, USB_SEND, HS_INT_MPS as _, EpType::IntrInbound); this.ep_enable(2, USB_SEND, int_mps as _, EpType::IntrInbound);
let bulk_mps = match this.get_speed() {
PortSpeed::Fs => FS_BULK_MPS,
_ => HS_BULK_MPS,
};
// CDC data bulk OUT and IN // CDC data bulk OUT and IN
this.ep_enable(3, USB_RECV, HS_BULK_MPS as _, EpType::BulkOutbound); this.ep_enable(3, USB_RECV, bulk_mps as _, EpType::BulkOutbound);
this.ep_enable(3, USB_SEND, HS_BULK_MPS as _, EpType::BulkInbound); this.ep_enable(3, USB_SEND, bulk_mps as _, EpType::BulkInbound);
} }
pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, length: usize) { pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, length: usize) {

View file

@ -7,9 +7,6 @@ use core::ops::Range;
use arbitrary_int::{Number, u4}; use arbitrary_int::{Number, u4};
use bitbybit::bitfield; use bitbybit::bitfield;
pub const KEY_SLOT_START: usize = 0x603F_0000;
pub const KEY_SLOT_LEN: usize = 0x1_0000;
pub const MAX_KEY_SLOTS: usize = KEY_SLOT_LEN / SLOT_ELEMENT_LEN_BYTES;
pub const DATA_SLOT_START: usize = 0x603E_0000; pub const DATA_SLOT_START: usize = 0x603E_0000;
pub const DATA_SLOT_LEN: usize = 0x1_0000; pub const DATA_SLOT_LEN: usize = 0x1_0000;
pub const MAX_DATA_SLOTS: usize = DATA_SLOT_LEN / SLOT_ELEMENT_LEN_BYTES; pub const MAX_DATA_SLOTS: usize = DATA_SLOT_LEN / SLOT_ELEMENT_LEN_BYTES;
@ -17,10 +14,6 @@ pub const SLOT_ELEMENT_LEN_BYTES: usize = 256 / 8;
pub const ACRAM_DATASLOT_START: usize = 0x603D_C000; pub const ACRAM_DATASLOT_START: usize = 0x603D_C000;
pub const ACRAM_DATASLOT_LEN: usize = 0x2000; pub const ACRAM_DATASLOT_LEN: usize = 0x2000;
pub const ACRAM_KEYSLOT_START: usize = 0x603D_E000;
pub const ACRAM_KEYSLOT_LEN: usize = 0x2000;
// pub const ACRAM_GKEYSLOT_START: usize = 0x603D_E400; // This is mentioned in the docs but I don't see it in
// the code?
pub const IFR_BASE: usize = 0x6040_0000; pub const IFR_BASE: usize = 0x6040_0000;
pub const IFR_LEN: usize = 0x400; pub const IFR_LEN: usize = 0x400;
/// This number is special: it only appears during certain portions of the chip life cycle in /// This number is special: it only appears during certain portions of the chip life cycle in
@ -101,79 +94,6 @@ impl DataSlotAccess {
} }
} }
#[bitfield(u32)]
#[derive(PartialEq, Eq, Debug)]
pub struct KeySlotAccess {
#[bits(24..=31, rw)]
akey_id: u8,
#[bit(23, rw)]
fw1: bool,
#[bit(22, rw)]
fw0: bool,
#[bit(21, rw)]
boot1: bool,
#[bit(20, rw)]
boot0: bool,
#[bits(8..=15, rw)]
seg_id: u8,
#[bit(3, rw)]
sce_wr_dis: bool,
#[bit(2, rw)]
sce_rd_dis: bool,
#[bit(1, rw)]
core_wr_dis: bool,
#[bit(0, rw)]
core_rd_dis: bool,
}
impl KeySlotAccess {
// This method is only valid in no-std currently. Not sure if there is even meaning for us
// to access this in the Xous environment, as this is primarily a secure boot construct
#[cfg(not(feature = "std"))]
pub fn get_entry(slot: usize) -> Self {
let slot_array =
unsafe { core::slice::from_raw_parts(ACRAM_KEYSLOT_START as *const KeySlotAccess, 2048) };
slot_array[slot]
}
pub fn get_partition_access(&self) -> PartitionAccess { PartitionAccess::from_raw_u32(self.raw_value()) }
pub fn set_partition_access(&mut self, pa: &PartitionAccess) {
*self = Self::new_with_raw_value((self.raw_value() & !(0xf << 20)) | (pa.to_raw_u4().as_u32() << 20));
}
pub fn get_rw_permissions(&self) -> RwPerms {
match [self.core_rd_dis(), self.core_wr_dis()] {
[true, true] => RwPerms::Denied,
[false, true] => RwPerms::ReadOnly,
[true, false] => RwPerms::WriteOnly,
[false, false] => RwPerms::ReadWrite,
}
}
pub fn set_rw_permissions(&mut self, spec: RwPerms) {
match spec {
RwPerms::Denied => {
self.set_core_rd_dis(true);
self.set_core_wr_dis(true);
}
RwPerms::ReadOnly => {
self.set_core_rd_dis(false);
self.set_core_wr_dis(true);
}
RwPerms::WriteOnly => {
self.set_core_rd_dis(true);
self.set_core_wr_dis(false);
}
RwPerms::ReadWrite => {
self.set_core_rd_dis(false);
self.set_core_wr_dis(false);
}
RwPerms::Unspecified => panic!("RwPerms must be specified"),
}
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)] #[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum AccessError { pub enum AccessError {
/// Access is anticipated to be denied by the hardware. Users can attempt to still /// Access is anticipated to be denied by the hardware. Users can attempt to still
@ -196,7 +116,6 @@ pub enum AccessError {
/// Returned when a set of slots that should have the same ACL don't. The value /// Returned when a set of slots that should have the same ACL don't. The value
/// inside is the value of the first ACL in the set. /// inside is the value of the first ACL in the set.
DataAclInconsistency(DataSlotAccess), DataAclInconsistency(DataSlotAccess),
KeyAclInconsistency(KeySlotAccess),
} }
/// Enum to specify read/write permissions to a given slot. /// Enum to specify read/write permissions to a given slot.
@ -279,28 +198,22 @@ impl PartitionAccess {
pub enum SlotIndex { pub enum SlotIndex {
Data(usize, PartitionAccess, RwPerms), Data(usize, PartitionAccess, RwPerms),
DataRange(Range<usize>, PartitionAccess, RwPerms), DataRange(Range<usize>, PartitionAccess, RwPerms),
Key(usize, PartitionAccess, RwPerms),
KeyRange(Range<usize>, PartitionAccess, RwPerms),
} }
#[derive(PartialEq, Eq, Clone, Debug)] #[derive(PartialEq, Eq, Clone, Debug)]
pub enum SlotType { pub enum SlotType {
Data, Data,
Key,
} }
impl SlotIndex { impl SlotIndex {
pub fn get_access_spec(&self) -> (PartitionAccess, RwPerms) { pub fn get_access_spec(&self) -> (PartitionAccess, RwPerms) {
match self { match self {
Self::Data(_, spec, rw) => (*spec, *rw), Self::Data(_, spec, rw) => (*spec, *rw),
Self::DataRange(_, spec, rw) => (*spec, *rw), Self::DataRange(_, spec, rw) => (*spec, *rw),
Self::Key(_, spec, rw) => (*spec, *rw),
Self::KeyRange(_, spec, rw) => (*spec, *rw),
} }
} }
pub fn get_type(&self) -> SlotType { pub fn get_type(&self) -> SlotType {
match self { match self {
Self::Data(_, _, _) | Self::DataRange(_, _, _) => SlotType::Data, Self::Data(_, _, _) | Self::DataRange(_, _, _) => SlotType::Data,
Self::Key(_, _, _) | Self::KeyRange(_, _, _) => SlotType::Key,
} }
} }
@ -308,8 +221,6 @@ impl SlotIndex {
match self { match self {
Self::Data(base, _, _) => *base, Self::Data(base, _, _) => *base,
Self::DataRange(range, _, _) => range.start, Self::DataRange(range, _, _) => range.start,
Self::Key(base, _, _) => *base,
Self::KeyRange(range, _, _) => range.start,
} }
} }
@ -317,8 +228,6 @@ impl SlotIndex {
match self { match self {
Self::Data(_, _, _) => 1, Self::Data(_, _, _) => 1,
Self::DataRange(range, _, _) => range.len(), Self::DataRange(range, _, _) => range.len(),
Self::Key(_, _, _) => 1,
Self::KeyRange(range, _, _) => range.len(),
} }
} }
@ -333,13 +242,6 @@ impl SlotIndex {
Err(AccessError::OutOfBounds) Err(AccessError::OutOfBounds)
} }
} }
Self::Key(index, _, _) => {
if *index < MAX_KEY_SLOTS {
Ok(*index * SLOT_ELEMENT_LEN_BYTES)
} else {
Err(AccessError::OutOfBounds)
}
}
Self::DataRange(range, _, _) => { Self::DataRange(range, _, _) => {
let index = range.start; let index = range.start;
if range.end <= MAX_DATA_SLOTS { if range.end <= MAX_DATA_SLOTS {
@ -348,14 +250,6 @@ impl SlotIndex {
Err(AccessError::OutOfBounds) Err(AccessError::OutOfBounds)
} }
} }
Self::KeyRange(range, _, _) => {
let index = range.start;
if range.end <= MAX_KEY_SLOTS {
Ok(index * SLOT_ELEMENT_LEN_BYTES)
} else {
Err(AccessError::OutOfBounds)
}
}
} }
} }
@ -374,19 +268,6 @@ impl SlotIndex {
} }
Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * SLOT_ELEMENT_LEN_BYTES))) Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * SLOT_ELEMENT_LEN_BYTES)))
} }
Self::Key(index, _, _) => {
if *index < MAX_KEY_SLOTS {
Ok(SlotOffsetIter::Single(core::iter::once(*index * SLOT_ELEMENT_LEN_BYTES)))
} else {
Err(AccessError::OutOfBounds)
}
}
Self::KeyRange(range, _, _) => {
if range.end > MAX_KEY_SLOTS {
return Err(AccessError::OutOfBounds);
}
Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * SLOT_ELEMENT_LEN_BYTES)))
}
} }
} }
@ -399,13 +280,6 @@ impl SlotIndex {
Err(AccessError::OutOfBounds) Err(AccessError::OutOfBounds)
} }
} }
Self::Key(index, _, _) => {
if *index < MAX_KEY_SLOTS {
Ok(*index * size_of::<u32>())
} else {
Err(AccessError::OutOfBounds)
}
}
Self::DataRange(range, _, _) => { Self::DataRange(range, _, _) => {
if range.end <= MAX_DATA_SLOTS { if range.end <= MAX_DATA_SLOTS {
Ok(range.start * size_of::<u32>()) Ok(range.start * size_of::<u32>())
@ -413,13 +287,6 @@ impl SlotIndex {
Err(AccessError::OutOfBounds) Err(AccessError::OutOfBounds)
} }
} }
Self::KeyRange(range, _, _) => {
if range.end <= MAX_KEY_SLOTS {
Ok(range.start * size_of::<u32>())
} else {
Err(AccessError::OutOfBounds)
}
}
} }
} }
@ -440,19 +307,6 @@ impl SlotIndex {
} }
Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * ACL_SIZE))) Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * ACL_SIZE)))
} }
Self::Key(index, _, _) => {
if *index < MAX_KEY_SLOTS {
Ok(SlotOffsetIter::Single(core::iter::once(*index * ACL_SIZE)))
} else {
Err(AccessError::OutOfBounds)
}
}
Self::KeyRange(range, _, _) => {
if range.end > MAX_KEY_SLOTS {
return Err(AccessError::OutOfBounds);
}
Ok(SlotOffsetIter::Range(range.clone().map(|idx| idx * ACL_SIZE)))
}
} }
} }
} }

View file

@ -44,21 +44,21 @@ pub const DEFAULT_FCLK_FREQUENCY: u32 = 700_000_000;
/// are derived from. The seed may be blended with other bits of data scattered about /// are derived from. The seed may be blended with other bits of data scattered about
/// the RRAM array, other device identifiers and hardware measurements to create the final /// the RRAM array, other device identifiers and hardware measurements to create the final
/// device secret key. /// device secret key.
pub const ROOT_SEED: SlotIndex = SlotIndex::Key(256, PartitionAccess::Fw0, RwPerms::ReadOnly); pub const ROOT_SEED: SlotIndex = SlotIndex::Data(256, PartitionAccess::Fw0, RwPerms::ReadWrite);
/// The `RMA_KEY` is a secret parameter that is unique per-device secret which is recorded /// The `RMA_KEY` is a secret parameter that is unique per-device secret which is recorded
/// at manufacturing time. Its purpose is to facilitate the creation of a signed RMA /// at manufacturing time. Its purpose is to facilitate the creation of a signed RMA
/// authorization certificate which upon receipt would blank the device and unlock various /// authorization certificate which upon receipt would blank the device and unlock various
/// features for debugging failed hardware. /// features for debugging failed hardware.
pub const RMA_KEY: SlotIndex = SlotIndex::Key(257, PartitionAccess::Fw0, RwPerms::ReadOnly); pub const RMA_KEY: SlotIndex = SlotIndex::Data(257, PartitionAccess::Fw0, RwPerms::ReadWrite);
/// Reserved for use as a CP to FT tracking cookie. This is used to help track inventory /// Reserved for use as a CP to FT tracking cookie. This is used to help track inventory
/// between CP and FT, if such a feature is desired in the supply chain. Blanked on entry /// between CP and FT, if such a feature is desired in the supply chain. Blanked on entry
/// to developer mode. /// to developer mode.
pub const CP_COOKIE: SlotIndex = SlotIndex::Key(258, PartitionAccess::Fw0, RwPerms::ReadWrite); pub const CP_COOKIE: SlotIndex = SlotIndex::Data(258, PartitionAccess::Fw0, RwPerms::ReadWrite);
/// The swap encryption key. Used to protect swap images beyond the signing key, if we so desire. /// The swap encryption key. Used to protect swap images beyond the signing key, if we so desire.
pub const SWAP_KEY: SlotIndex = SlotIndex::Key(259, PartitionAccess::Fw0, RwPerms::ReadOnly); pub const SWAP_KEY: SlotIndex = SlotIndex::Data(259, PartitionAccess::Fw0, RwPerms::ReadWrite);
/// `NUISANCE_KEYS` are hashed together with `ROOT_SEED` to derive the core secret. /// `NUISANCE_KEYS` are hashed together with `ROOT_SEED` to derive the core secret.
/// Their primary purpose is to annoy microscopists trying to read the secret key by /// Their primary purpose is to annoy microscopists trying to read the secret key by
@ -85,9 +85,9 @@ pub const SWAP_KEY: SlotIndex = SlotIndex::Key(259, PartitionAccess::Fw0, RwPerm
/// numbered data slots. Some of the data slots in the first 8 slots will be read-only at CP time, and /// numbered data slots. Some of the data slots in the first 8 slots will be read-only at CP time, and
/// thus they can't be initialized with random data and be used as a nuisance key. This is a minor degradation /// thus they can't be initialized with random data and be used as a nuisance key. This is a minor degradation
/// in security margin. /// in security margin.
pub const NUISANCE_KEYS_0: SlotIndex = SlotIndex::KeyRange(8..128, PartitionAccess::Fw0, RwPerms::ReadOnly); pub const NUISANCE_KEYS_0: SlotIndex = SlotIndex::DataRange(8..128, PartitionAccess::Fw0, RwPerms::ReadWrite);
pub const NUISANCE_KEYS_1: SlotIndex = pub const NUISANCE_KEYS_1: SlotIndex =
SlotIndex::KeyRange(1920..2048, PartitionAccess::Fw0, RwPerms::ReadOnly); SlotIndex::DataRange(1920..2048, PartitionAccess::Fw0, RwPerms::ReadWrite);
pub const NUISANCE_KEYS: [SlotIndex; 2] = [NUISANCE_KEYS_0, NUISANCE_KEYS_1]; pub const NUISANCE_KEYS: [SlotIndex; 2] = [NUISANCE_KEYS_0, NUISANCE_KEYS_1];
/// `CHAFF_KEYS` are a bank of keys that are hashed into the key array, but instead of /// `CHAFF_KEYS` are a bank of keys that are hashed into the key array, but instead of
@ -109,7 +109,7 @@ pub const NUISANCE_KEYS: [SlotIndex; 2] = [NUISANCE_KEYS_0, NUISANCE_KEYS_1];
/// the chaff is cleared, we also don't care as much about side channels since we're now operating /// the chaff is cleared, we also don't care as much about side channels since we're now operating
/// in a fundamentally insecure regime (e.g. developer mode - you can just read out the data by /// in a fundamentally insecure regime (e.g. developer mode - you can just read out the data by
/// running your own code on the device). /// running your own code on the device).
pub const CHAFF_KEYS: SlotIndex = SlotIndex::KeyRange(128..256, PartitionAccess::Fw0, RwPerms::ReadWrite); pub const CHAFF_KEYS: SlotIndex = SlotIndex::DataRange(128..256, PartitionAccess::Fw0, RwPerms::ReadWrite);
/// 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.
@ -127,4 +127,4 @@ pub const DATA_SLOTS: [SlotIndex; 8] = [
/// 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
/// that should be included as domain separation in any KDF. /// that should be included as domain separation in any KDF.
pub const KEY_SLOTS: [SlotIndex; 6] = pub const KEY_SLOTS: [SlotIndex; 6] =
[ROOT_SEED, RMA_KEY, CP_COOKIE, NUISANCE_KEYS_0, NUISANCE_KEYS_1, CHAFF_KEYS]; [CP_COOKIE, RMA_KEY, ROOT_SEED, NUISANCE_KEYS_0, NUISANCE_KEYS_1, CHAFF_KEYS];

View file

@ -175,11 +175,11 @@ pub const UUID: SlotIndex = SlotIndex::Data(1, PartitionAccess::Open, RwPerms::R
/// `IFR_HASH` is a provisional slot for a hash of the IFR region. Whether the hash is meaningful /// `IFR_HASH` is a provisional slot for a hash of the IFR region. Whether the hash is meaningful
/// or not depends on if the chip is booted before it is sealed. At the time of writing, it's /// or not depends on if the chip is booted before it is sealed. At the time of writing, it's
/// not clear if the wafer probe infrastructure will allow this. /// not clear if the wafer probe infrastructure will allow this.
pub const IFR_HASH: SlotIndex = SlotIndex::Data(2, PartitionAccess::All, RwPerms::ReadOnly); pub const IFR_HASH: SlotIndex = SlotIndex::Data(2, PartitionAccess::Open, RwPerms::ReadWrite);
/// `WAFER_ID` is a copy of the lot ID + wafer ID + x/y position data that should be captured /// `WAFER_ID` is a copy of the lot ID + wafer ID + x/y position data that should be captured
/// during CP. /// during CP.
pub const CP_ID: SlotIndex = SlotIndex::Data(3, PartitionAccess::All, RwPerms::ReadOnly); pub const CP_ID: SlotIndex = SlotIndex::Data(3, PartitionAccess::Open, RwPerms::ReadWrite);
/// Indelible versions of the public keys. The problem with the pubkeys in boot0 region is that /// Indelible versions of the public keys. The problem with the pubkeys in boot0 region is that
/// boot0 itself has the ability to modify its own memory. A copy here can have a bit set in /// boot0 itself has the ability to modify its own memory. A copy here can have a bit set in

View file

@ -137,27 +137,23 @@ impl OneWayCounter {
#[derive(PartialEq, Eq, Debug)] #[derive(PartialEq, Eq, Debug)]
pub enum AccessSettings { pub enum AccessSettings {
Data(DataSlotAccess), Data(DataSlotAccess),
Key(KeySlotAccess),
} }
impl AccessSettings { impl AccessSettings {
pub fn raw_u32(&self) -> u32 { pub fn raw_u32(&self) -> u32 {
match self { match self {
Self::Data(d) => d.raw_value(), Self::Data(d) => d.raw_value(),
Self::Key(d) => d.raw_value(),
} }
} }
pub fn allows_cpu_read(&self) -> bool { pub fn allows_cpu_read(&self) -> bool {
match self { match self {
Self::Data(d) => !d.core_rd_dis(), Self::Data(d) => !d.core_rd_dis(),
Self::Key(d) => !d.core_rd_dis(),
} }
} }
pub fn allows_cpu_write(&self) -> bool { pub fn allows_cpu_write(&self) -> bool {
match self { match self {
Self::Data(d) => !d.core_wr_dis(), Self::Data(d) => !d.core_wr_dis(),
Self::Key(d) => !d.core_wr_dis(),
} }
} }
@ -165,7 +161,6 @@ impl AccessSettings {
pub fn is_set_only(&self) -> bool { pub fn is_set_only(&self) -> bool {
match self { match self {
Self::Data(d) => d.write_mode(), Self::Data(d) => d.write_mode(),
Self::Key(_d) => false,
} }
} }
} }
@ -181,9 +176,11 @@ pub enum AccessType {
pub struct SlotManager { pub struct SlotManager {
data_range: xous::MemoryRange, data_range: xous::MemoryRange,
data_acl_range: xous::MemoryRange, data_acl_range: xous::MemoryRange,
key_range: xous::MemoryRange,
key_acl_range: xous::MemoryRange,
user_id: CoreuserId, user_id: CoreuserId,
#[cfg(feature = "std")]
data_write_offset: xous::MemoryRange,
#[cfg(feature = "std")]
data_acl_write_offset: xous::MemoryRange,
} }
impl SlotManager { impl SlotManager {
@ -206,21 +203,13 @@ impl SlotManager {
) )
.expect("Couldn't map ACL range"); .expect("Couldn't map ACL range");
#[cfg(feature = "std")] #[cfg(feature = "std")]
let key_range = xous::map_memory( // safety: these ranges are valid and pre-aligned
xous::MemoryAddress::new(KEY_SLOT_START), let data_write_offset = unsafe { xous::MemoryRange::new(DATA_SLOT_START, DATA_SLOT_LEN).unwrap() };
None,
KEY_SLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map slot range");
#[cfg(feature = "std")] #[cfg(feature = "std")]
let key_acl_range = xous::map_memory( // safety: these ranges are valid and pre-aligned
xous::MemoryAddress::new(ACRAM_KEYSLOT_START), let data_acl_write_offset =
None, unsafe { xous::MemoryRange::new(ACRAM_DATASLOT_START, ACRAM_DATASLOT_LEN).unwrap() };
ACRAM_KEYSLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map ACL range");
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
// safety: these ranges are valid and pre-aligned // safety: these ranges are valid and pre-aligned
let data_range = unsafe { xous::MemoryRange::new(DATA_SLOT_START, DATA_SLOT_LEN).unwrap() }; let data_range = unsafe { xous::MemoryRange::new(DATA_SLOT_START, DATA_SLOT_LEN).unwrap() };
@ -228,13 +217,6 @@ impl SlotManager {
// safety: these ranges are valid and pre-aligned // safety: these ranges are valid and pre-aligned
let data_acl_range = let data_acl_range =
unsafe { xous::MemoryRange::new(ACRAM_DATASLOT_START, ACRAM_DATASLOT_LEN).unwrap() }; unsafe { xous::MemoryRange::new(ACRAM_DATASLOT_START, ACRAM_DATASLOT_LEN).unwrap() };
#[cfg(not(feature = "std"))]
// safety: these ranges are valid and pre-aligned
let key_range = unsafe { xous::MemoryRange::new(KEY_SLOT_START, KEY_SLOT_LEN).unwrap() };
#[cfg(not(feature = "std"))]
// safety: these ranges are valid and pre-aligned
let key_acl_range =
unsafe { xous::MemoryRange::new(ACRAM_KEYSLOT_START, ACRAM_KEYSLOT_LEN).unwrap() };
#[cfg(feature = "std")] #[cfg(feature = "std")]
let user_id = if xous::process::id() == crate::coreuser::TRUSTED_PID as u32 { let user_id = if xous::process::id() == crate::coreuser::TRUSTED_PID as u32 {
@ -246,15 +228,17 @@ impl SlotManager {
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
let user_id = crate::coreuser::TRUSTED_USER; let user_id = crate::coreuser::TRUSTED_USER;
Self { data_range, data_acl_range, key_range, key_acl_range, user_id } #[cfg(not(feature = "std"))]
let ret = Self { data_range, data_acl_range, user_id };
#[cfg(feature = "std")]
let ret = Self { data_range, data_acl_range, user_id, data_write_offset, data_acl_write_offset };
ret
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub fn register_mapping(&self, rram: &mut Reram) { pub fn register_mapping(&self, rram: &mut Reram) {
rram.add_range(DATA_SLOT_START - utralib::HW_RERAM_MEM, self.data_range); rram.add_range(DATA_SLOT_START - utralib::HW_RERAM_MEM, self.data_range);
rram.add_range(ACRAM_DATASLOT_START - utralib::HW_RERAM_MEM, self.data_acl_range); rram.add_range(ACRAM_DATASLOT_START - utralib::HW_RERAM_MEM, self.data_acl_range);
rram.add_range(KEY_SLOT_START - utralib::HW_RERAM_MEM, self.key_range);
rram.add_range(ACRAM_KEYSLOT_START - utralib::HW_RERAM_MEM, self.key_acl_range);
} }
pub fn read(&self, slot: &SlotIndex) -> Result<&[u8], AccessError> { pub fn read(&self, slot: &SlotIndex) -> Result<&[u8], AccessError> {
@ -269,15 +253,9 @@ impl SlotManager {
SlotIndex::Data(_, _, _) => unsafe { SlotIndex::Data(_, _, _) => unsafe {
&self.data_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES] &self.data_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES]
}, },
SlotIndex::Key(_, _, _) => unsafe {
&self.key_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES]
},
SlotIndex::DataRange(range, _, _) => unsafe { SlotIndex::DataRange(range, _, _) => unsafe {
&self.data_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES * range.len()] &self.data_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES * range.len()]
}, },
SlotIndex::KeyRange(range, _, _) => unsafe {
&self.key_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES * range.len()]
},
}) })
} else { } else {
Err(AccessError::AccessDenied) Err(AccessError::AccessDenied)
@ -288,26 +266,22 @@ impl SlotManager {
/// There is access or type checking done. This is a "raw read" primitive mostly used for debugging. /// There is access or type checking done. This is a "raw read" primitive mostly used for debugging.
pub unsafe fn read_data_slot(&self, absolute_offset: usize) -> &[u8] { pub unsafe fn read_data_slot(&self, absolute_offset: usize) -> &[u8] {
let ptr: *const u8 = &self.data_range.as_slice::<u8>()[absolute_offset] as *const u8; let ptr: *const u8 = &self.data_range.as_slice::<u8>()[absolute_offset] as *const u8;
crate::println!("data loc: {:x}", ptr as usize); crate::println!("data loc: {:x}, offset: {:x}", ptr as usize, absolute_offset);
&self.data_range.as_slice()[absolute_offset..absolute_offset + SLOT_ELEMENT_LEN_BYTES] &self.data_range.as_slice()[absolute_offset..absolute_offset + SLOT_ELEMENT_LEN_BYTES]
} }
/// Safety: the caller must resolve the index into either the data or the key array correctly.
/// There is access or type checking done. This is a "raw read" primitive mostly used for debugging.
pub unsafe fn read_key_slot(&self, absolute_offset: usize) -> &[u8] {
let ptr: *const u8 = &self.key_range.as_slice::<u8>()[absolute_offset] as *const u8;
crate::println!("key loc: {:x}", ptr as usize);
&self.key_range.as_slice()[absolute_offset..absolute_offset + SLOT_ELEMENT_LEN_BYTES]
}
pub fn write(&self, writer: &mut Reram, slot: &SlotIndex, value: &[u8]) -> Result<(), AccessError> { pub fn write(&self, writer: &mut Reram, slot: &SlotIndex, value: &[u8]) -> Result<(), AccessError> {
let acl = self.get_acl(slot)?; let acl = self.get_acl(slot)?;
if self.user_id.is_accessible(&acl, &AccessType::Write) { if self.user_id.is_accessible(&acl, &AccessType::Write) {
let offset = slot.try_into_data_offset()?; let offset = slot.try_into_data_offset()?;
#[cfg(not(feature = "std"))]
let range = match slot { let range = match slot {
SlotIndex::Data(_, _, _) | SlotIndex::DataRange(_, _, _) => &self.data_range, SlotIndex::Data(_, _, _) | SlotIndex::DataRange(_, _, _) => &self.data_range,
SlotIndex::Key(_, _, _) | SlotIndex::KeyRange(_, _, _) => &self.key_range, };
#[cfg(feature = "std")]
let range = match slot {
SlotIndex::Data(_, _, _) | SlotIndex::DataRange(_, _, _) => &self.data_write_offset,
}; };
if value.len() != slot.len() * SLOT_ELEMENT_LEN_BYTES { if value.len() != slot.len() * SLOT_ELEMENT_LEN_BYTES {
@ -322,6 +296,7 @@ impl SlotManager {
if self.user_id.is_accessible(&acl, &AccessType::Read) { if self.user_id.is_accessible(&acl, &AccessType::Read) {
// read-verify only if we have read access // read-verify only if we have read access
let readback = self.read(slot)?; let readback = self.read(slot)?;
crate::println!("rbk: {:x?}", &readback[..8]);
if readback != value { Err(AccessError::WriteError) } else { Ok(()) } if readback != value { Err(AccessError::WriteError) } else { Ok(()) }
} else { } else {
Ok(()) Ok(())
@ -338,12 +313,6 @@ impl SlotManager {
self.data_acl_range.as_slice()[offset..offset + size_of::<u32>()].try_into().unwrap() self.data_acl_range.as_slice()[offset..offset + size_of::<u32>()].try_into().unwrap()
}))) })))
} }
SlotIndex::Key(_, _, _) => {
let offset = slot.try_into_acl_offset()?;
AccessSettings::Key(KeySlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe {
self.key_acl_range.as_slice()[offset..offset + size_of::<u32>()].try_into().unwrap()
})))
}
SlotIndex::DataRange(_, _, _) => { SlotIndex::DataRange(_, _, _) => {
let mut range = slot.try_into_acl_iter()?; let mut range = slot.try_into_acl_iter()?;
let offset = range.next().unwrap(); let offset = range.next().unwrap();
@ -360,22 +329,6 @@ impl SlotManager {
} }
AccessSettings::Data(prototype) AccessSettings::Data(prototype)
} }
SlotIndex::KeyRange(_, _, _) => {
let mut range = slot.try_into_acl_iter()?;
let offset = range.next().unwrap();
let prototype = KeySlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe {
self.key_acl_range.as_slice()[offset..offset + size_of::<u32>()].try_into().unwrap()
}));
for offset in range {
let successor = KeySlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe {
self.key_acl_range.as_slice()[offset..offset + size_of::<u32>()].try_into().unwrap()
}));
if prototype != successor {
return Err(AccessError::KeyAclInconsistency(prototype));
}
}
AccessSettings::Key(prototype)
}
}) })
} }
@ -389,22 +342,22 @@ impl SlotManager {
})) }))
} }
/// Safety: the caller must resolve the index into either the data or the key array correctly.
/// There is access or type checking done. This is a "raw read" primitive mostly used for debugging.
pub unsafe fn get_key_acl(&self, absolute_offset: usize) -> KeySlotAccess {
KeySlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe {
self.key_acl_range.as_slice()[absolute_offset..absolute_offset + size_of::<u32>()]
.try_into()
.unwrap()
}))
}
pub fn set_acl( pub fn set_acl(
&self, &self,
writer: &mut Reram, writer: &mut Reram,
slot: &SlotIndex, slot: &SlotIndex,
setting: &AccessSettings, setting: &AccessSettings,
) -> Result<(), AccessError> { ) -> Result<(), AccessError> {
#[cfg(not(feature = "std"))]
let ptr = match slot {
SlotIndex::Data(_, _, _) | SlotIndex::DataRange(_, _, _) => self.data_acl_range.as_ptr() as usize,
};
#[cfg(feature = "std")]
let ptr = match slot {
SlotIndex::Data(_, _, _) | SlotIndex::DataRange(_, _, _) => {
self.data_acl_write_offset.as_ptr() as usize
}
};
// safety: the unsafe blocks here are concerned that the data types of the resulting // safety: the unsafe blocks here are concerned that the data types of the resulting
// slice are all representable. In this case, all bits are valid in the final representation. // slice are all representable. In this case, all bits are valid in the final representation.
match slot { match slot {
@ -412,45 +365,27 @@ impl SlotManager {
let offset = slot.try_into_acl_offset()?; let offset = slot.try_into_acl_offset()?;
writer writer
.protected_write_slice( .protected_write_slice(
self.data_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset, ptr - utralib::HW_RERAM_MEM + offset,
&setting.raw_u32().to_le_bytes(),
)
.map(|_| ())
.map_err(|_| AccessError::WriteError)
}
SlotIndex::Key(_, _, _) => {
let offset = slot.try_into_acl_offset()?;
writer
.protected_write_slice(
self.key_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset,
&setting.raw_u32().to_le_bytes(), &setting.raw_u32().to_le_bytes(),
) )
.map(|_| ()) .map(|_| ())
.map_err(|_| AccessError::WriteError) .map_err(|_| AccessError::WriteError)
} }
SlotIndex::DataRange(_, _, _) => { SlotIndex::DataRange(_, _, _) => {
let mut success = true;
for offset in slot.try_into_acl_iter()? { for offset in slot.try_into_acl_iter()? {
writer match writer.protected_write_slice(
.protected_write_slice( ptr - utralib::HW_RERAM_MEM + offset,
self.data_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset, &setting.raw_u32().to_le_bytes(),
&setting.raw_u32().to_le_bytes(), ) {
) Ok(_) => {}
.map(|_| ()) Err(e) => {
.map_err(|_| AccessError::WriteError)? success = false;
crate::println!("Can't write to ACL offset {:x}: {:?}", offset, e);
}
}
} }
Ok(()) if success { Ok(()) } else { Err(AccessError::WriteError) }
}
SlotIndex::KeyRange(_, _, _) => {
for offset in slot.try_into_acl_iter()? {
writer
.protected_write_slice(
self.key_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset,
&setting.raw_u32().to_le_bytes(),
)
.map(|_| ())
.map_err(|_| AccessError::WriteError)?
}
Ok(())
} }
} }
} }

View file

@ -1,3 +1,6 @@
#[cfg(feature = "std")]
use std::pin::Pin;
use utralib::{CSR, utra}; use utralib::{CSR, utra};
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
@ -57,6 +60,9 @@ const RRC_CR_POWERDOWN: u32 = 1;
const RRC_CR_WRITE_DATA: u32 = 0; const RRC_CR_WRITE_DATA: u32 = 0;
const RRC_CR_WRITE_CMD: u32 = 2; const RRC_CR_WRITE_CMD: u32 = 2;
// number of attempts allowed before giving up on writes
const ATTEMPTS: usize = 2;
#[cfg(feature = "std")] #[cfg(feature = "std")]
fn rram_handler(_irq_no: usize, arg: *mut usize) { fn rram_handler(_irq_no: usize, arg: *mut usize) {
let rram = unsafe { &mut *(arg as *mut Reram) }; let rram = unsafe { &mut *(arg as *mut Reram) };
@ -111,7 +117,7 @@ impl<'a> Reram {
/// This returns an object that has a handle to manage the RRAM, but no memory /// This returns an object that has a handle to manage the RRAM, but no memory
/// ranges mapped that are valid for writing. Memory ranges need to be added /// ranges mapped that are valid for writing. Memory ranges need to be added
/// with `add_range()` before any writes can occur. /// with `add_range()` before any writes can occur.
pub fn new() -> Self { pub fn new() -> Pin<Box<Self>> {
let rram_page = xous::syscall::map_memory( let rram_page = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::rrc::HW_RRC_BASE), xous::MemoryAddress::new(utra::rrc::HW_RRC_BASE),
None, None,
@ -135,18 +141,18 @@ impl<'a> Reram {
let mut irq_csr = CSR::new(irq_page.as_mut_ptr() as *mut u32); let mut irq_csr = CSR::new(irq_page.as_mut_ptr() as *mut u32);
// pin the structure on the heap so that it doesn't move around on us. // pin the structure on the heap so that it doesn't move around on us.
let mut rram = Reram { let mut rram = Box::pin(Reram {
csr, csr,
irq_csr, irq_csr,
offset: 0, offset: 0,
buf: [0u32; ALIGNMENT / size_of::<u32>()], buf: [0u32; ALIGNMENT / size_of::<u32>()],
range_map: RangeMap::new(), range_map: RangeMap::new(),
}; });
xous::claim_interrupt( xous::claim_interrupt(
utra::irqarray11::IRQARRAY11_IRQ, utra::irqarray11::IRQARRAY11_IRQ,
rram_handler, rram_handler,
&mut rram as *mut Reram as *mut usize, Pin::as_mut(&mut rram).get_mut() as *mut Reram as *mut usize,
) )
.expect("couldn't claim RRAM handler interrupt"); .expect("couldn't claim RRAM handler interrupt");
irq_csr.wo(utra::irqarray11::EV_PENDING, 0xFFFF_FFFF); irq_csr.wo(utra::irqarray11::EV_PENDING, 0xFFFF_FFFF);
@ -338,6 +344,33 @@ impl<'a> Reram {
Ok(data.len()) Ok(data.len())
} }
fn write_slice_retry(&mut self, offset: usize, data: &[u8]) -> Result<usize, xous::Error> {
for i in 0..ATTEMPTS {
match self.write_slice_inner(offset, data) {
Ok(len) => {
#[cfg(not(feature = "std"))]
let check_slice = unsafe {
core::slice::from_raw_parts((offset + utralib::HW_RERAM_MEM) as *const u8, data.len())
};
#[cfg(feature = "std")]
let check_slice = self.array(offset)?;
if check_slice[..data.len().min(check_slice.len())]
== data[..data.len().min(check_slice.len())]
{
return Ok(len);
} else {
crate::println!("Write failed to verify retry {}/{}", i + 1, ATTEMPTS);
}
}
Err(e) => {
crate::println!("Write with error {:?}, retrying...", e);
}
}
}
Err(xous::Error::InternalError)
}
/// Bounds-check regular writes to make sure they are in the "standard" memory array region /// Bounds-check regular writes to make sure they are in the "standard" memory array region
/// Boot0 region is also disallowed for writing because it should be hardware write-protected. /// Boot0 region is also disallowed for writing because it should be hardware write-protected.
/// For testing purposes, that check may be commented out just to make sure the write protection /// For testing purposes, that check may be commented out just to make sure the write protection
@ -351,7 +384,7 @@ impl<'a> Reram {
{ {
return Err(xous::Error::AccessDenied); return Err(xous::Error::AccessDenied);
} }
self.write_slice_inner(offset, data) self.write_slice_retry(offset, data)
} }
/// This has a separate API not to enforce security but to avoid fat-fingering data /// This has a separate API not to enforce security but to avoid fat-fingering data
@ -360,9 +393,11 @@ impl<'a> Reram {
/// processes, but they only come into effect after the OS is booted. /// processes, but they only come into effect after the OS is booted.
pub fn protected_write_slice(&mut self, offset: usize, data: &[u8]) -> Result<usize, xous::Error> { pub fn protected_write_slice(&mut self, offset: usize, data: &[u8]) -> Result<usize, xous::Error> {
if offset < bao1x_api::RRAM_STORAGE_LEN || offset >= utralib::HW_RERAM_MEM_LEN { if offset < bao1x_api::RRAM_STORAGE_LEN || offset >= utralib::HW_RERAM_MEM_LEN {
// crate::println!("offset {:x} access denied", offset);
return Err(xous::Error::AccessDenied); return Err(xous::Error::AccessDenied);
} }
self.write_slice_inner(offset, data) // crate::println!("Writing to {:x}: {:x?}", offset, &data[..16.min(data.len())]);
self.write_slice_retry(offset, data)
} }
} }

View file

@ -4,7 +4,7 @@ use alloc::vec::Vec;
use bao1x_api::signatures::*; use bao1x_api::signatures::*;
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
use bao1x_api::{DEVELOPER_MODE, KeySlotAccess, RwPerms, SLOT_ELEMENT_LEN_BYTES, SlotType}; use bao1x_api::{DEVELOPER_MODE, DataSlotAccess, RwPerms, SLOT_ELEMENT_LEN_BYTES, SlotType};
use digest::Digest; use digest::Digest;
use sha2_bao1x::{Sha256, Sha512}; use sha2_bao1x::{Sha256, Sha512};
use xous::arch::PAGE_SIZE; use xous::arch::PAGE_SIZE;
@ -221,12 +221,11 @@ pub fn erase_secrets() {
let mut rram = crate::rram::Reram::new(); let mut rram = crate::rram::Reram::new();
let mut zero_key_count = 0; let mut zero_key_count = 0;
// statistically speaking, I suppose, maybe we could have "a" set of keys that are 0 out of a randomly // This is set to a higher level because we need to work around an earlier issue
// generated set. But if we see more than the threshold below of zero keys, conclude that we don't // with overly-broad ACL settings on alpha0 boards
// have access permissions, and panic instead of allowing a boot. const ZERO_ERR_THRESH: usize = 64;
const ZERO_ERR_THRESH: usize = 2;
for slot in crate::board::KEY_SLOTS.iter() { for slot in crate::board::KEY_SLOTS.iter() {
if slot.get_type() == SlotType::Key { if slot.get_type() == SlotType::Data {
let (_pa, rw_perms) = slot.get_access_spec(); let (_pa, rw_perms) = slot.get_access_spec();
for data_index in slot.try_into_data_iter().unwrap() { for data_index in slot.try_into_data_iter().unwrap() {
match rw_perms { match rw_perms {
@ -238,11 +237,11 @@ pub fn erase_secrets() {
.set_acl( .set_acl(
&mut rram, &mut rram,
slot, slot,
&AccessSettings::Key(KeySlotAccess::new_with_raw_value(0)), &AccessSettings::Data(DataSlotAccess::new_with_raw_value(0)),
) )
.expect("couldn't reset ACL"); .expect("couldn't reset ACL");
} }
let bytes = unsafe { slot_mgr.read_key_slot(data_index) }; let bytes = unsafe { slot_mgr.read_data_slot(data_index) };
if bytes.iter().all(|&b| b == 0) { if bytes.iter().all(|&b| b == 0) {
zero_key_count += 1; zero_key_count += 1;
} }
@ -253,12 +252,17 @@ pub fn erase_secrets() {
alloc::vec::Vec::with_capacity(slot.len() * SLOT_ELEMENT_LEN_BYTES); alloc::vec::Vec::with_capacity(slot.len() * SLOT_ELEMENT_LEN_BYTES);
eraser.resize(slot.len() * SLOT_ELEMENT_LEN_BYTES, ERASE_VALUE); eraser.resize(slot.len() * SLOT_ELEMENT_LEN_BYTES, ERASE_VALUE);
slot_mgr.write(&mut rram, slot, &eraser).expect("couldn't erase key"); slot_mgr.write(&mut rram, slot, &eraser).ok();
} }
let check = unsafe { slot_mgr.read_key_slot(data_index) }; let check = unsafe { slot_mgr.read_data_slot(data_index) };
if !check.iter().all(|&b| b == ERASE_VALUE) { if !check.iter().all(|&b| b == ERASE_VALUE) {
crate::println!("Failed to erase key at {}: {:x?}", data_index, check); crate::println!("Failed to erase key at {}: {:x?}", data_index, check);
panic!("Key erasure did not succeed, refusing to boot!"); /* // commented out - can lead to boot loops
// reboot on failure to erase
let mut rcurst =
utralib::CSR::new(utralib::utra::sysctrl::HW_SYSCTRL_BASE as *mut u32);
rcurst.wo(utralib::utra::sysctrl::SFR_RCURST0, 0x55AA);
*/
} else { } else {
crate::println!("Key range at {} confirmed erased", slot.get_base()); crate::println!("Key range at {} confirmed erased", slot.get_base());
} }
@ -266,9 +270,7 @@ pub fn erase_secrets() {
_ => {} _ => {}
} }
if zero_key_count > ZERO_ERR_THRESH { if zero_key_count > ZERO_ERR_THRESH {
panic!( crate::println!("Saw too many zero-keys. Insufficient privilege to erase keys!");
"Saw too many zero-keys. Insufficient privilege to erase keys, panicing instead of allowing a boot!"
);
} }
} }
} }

View file

@ -1325,7 +1325,10 @@ impl Spim {
let qe_set = match self.command_set { let qe_set = match self.command_set {
Some(CommandSet::Macronix) => 0b0100_0000 & sr != 0, Some(CommandSet::Macronix) => 0b0100_0000 & sr != 0,
Some(CommandSet::Xtx) => 0b10_0000_0000 & sr != 0, Some(CommandSet::Xtx) => 0b10_0000_0000 & sr != 0,
None => panic!("Attempting to set QE on unknown flash type"), None => {
crate::println!("Can't set QE on unknown flash type");
return;
}
}; };
if qe_set { if qe_set {
// nothing to do, it's already set // nothing to do, it's already set

View file

@ -1630,6 +1630,8 @@ impl CorigineUsb {
} }
} }
pub fn get_speed(&self) -> PortSpeed { PortSpeed::from_portsc(self.csr.r(PORTSC)) }
pub fn update_ep0_maxpacketsize(&mut self, size: usize) { pub fn update_ep0_maxpacketsize(&mut self, size: usize) {
let cmd_param = self.csr.ms(CMDPARA0_CMD1_UPDATE_EP0_MPS, size as u32); let cmd_param = self.csr.ms(CMDPARA0_CMD1_UPDATE_EP0_MPS, size as u32);
self.issue_command(CmdType::UpdateEp0, cmd_param, 0).expect("couldn't issue command"); self.issue_command(CmdType::UpdateEp0, cmd_param, 0).expect("couldn't issue command");

View file

@ -281,7 +281,7 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
if tag == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] if tag == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT]
|| k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT
{ {
crate::println!("Developer key detected, ensuring secret are erased"); crate::println!("Developer key detected, ensuring secrets are erased");
bao1x_hal::sigcheck::erase_secrets(); bao1x_hal::sigcheck::erase_secrets();
} }
} }
@ -315,7 +315,7 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
== *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] == *bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT]
|| k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT
{ {
crate::println!("Developer key detected, ensuring secret are erased"); crate::println!("Developer key detected, ensuring secrets are erased");
bao1x_hal::sigcheck::erase_secrets(); bao1x_hal::sigcheck::erase_secrets();
} }
true true

View file

@ -256,7 +256,7 @@ impl SwapHal {
[bao1x_api::pubkeys::DEVELOPER_KEY_SLOT] [bao1x_api::pubkeys::DEVELOPER_KEY_SLOT]
|| k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT || k == bao1x_api::pubkeys::DEVELOPER_KEY_SLOT
{ {
crate::println!("Developer key detected, ensuring secret are erased"); crate::println!("Developer key detected, ensuring secrets are erased");
bao1x_hal::sigcheck::erase_secrets(); bao1x_hal::sigcheck::erase_secrets();
} }
} }

View file

@ -75,6 +75,9 @@ hkdf = "0.12.4"
[features] [features]
bao1x = ["utralib/bao1x", "aes/bao1x"] bao1x = ["utralib/bao1x", "aes/bao1x"]
debug-hal = ["bao1x-hal/debug-print-duart"]
board-baosec = [ board-baosec = [
"utralib/bao1x", "utralib/bao1x",
"keystore-api/gen2", "keystore-api/gen2",

View file

@ -3,6 +3,8 @@ use keystore_api::*;
mod platform; mod platform;
fn main() -> ! { fn main() -> ! {
#[cfg(feature = "debug-hal")]
bao1x_hal::claim_duart();
log_server::init_wait().unwrap(); log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Info); log::set_max_level(log::LevelFilter::Info);
log::info!("my PID is {}", xous::process::id()); log::info!("my PID is {}", xous::process::id());
@ -57,8 +59,11 @@ fn attack_keystore() {
let slot_mgr = bao1x_hal::acram::SlotManager::new(); let slot_mgr = bao1x_hal::acram::SlotManager::new();
// let slot = bao1x_api::baosec::ROOT_SEED; // let slot = bao1x_api::baosec::ROOT_SEED;
let slot = let slot = bao1x_api::offsets::SlotIndex::Data(
bao1x_api::offsets::SlotIndex::Key(0, bao1x_api::PartitionAccess::Fw0, bao1x_api::RwPerms::ReadOnly); 256,
bao1x_api::PartitionAccess::Fw0,
bao1x_api::RwPerms::ReadOnly,
);
let data_index = slot.try_into_data_offset().unwrap(); let data_index = slot.try_into_data_offset().unwrap();
let acl_index = slot.try_into_acl_offset().unwrap(); let acl_index = slot.try_into_acl_offset().unwrap();
let user_states = [ let user_states = [
@ -74,8 +79,8 @@ fn attack_keystore() {
cu.rmwf(utra::coreuser::USERVALUE_USER2, state.as_dense()); cu.rmwf(utra::coreuser::USERVALUE_USER2, state.as_dense());
log::info!(" COREUSER STATUS {:x}", cu.r(utra::coreuser::STATUS)); log::info!(" COREUSER STATUS {:x}", cu.r(utra::coreuser::STATUS));
unsafe { unsafe {
let bytes = slot_mgr.read_key_slot(data_index); let bytes = slot_mgr.read_data_slot(data_index);
let acl = slot_mgr.get_key_acl(acl_index); let acl = slot_mgr.get_data_acl(acl_index);
log::info!( log::info!(
" Key {} ({:x?}): {:x?}", " Key {} ({:x?}): {:x?}",
data_index / bao1x_api::offsets::SLOT_ELEMENT_LEN_BYTES, data_index / bao1x_api::offsets::SLOT_ELEMENT_LEN_BYTES,

View file

@ -8,7 +8,11 @@ use crate::platform::KeyStore;
pub fn keystore(sid: SID) -> ! { pub fn keystore(sid: SID) -> ! {
let hal = bao1x_hal_service::Hal::new(); let hal = bao1x_hal_service::Hal::new();
let mut rram = Reram::new(); let mut rram = Reram::new();
let mut store = KeyStore::init_from_hw(&mut rram); let mut store = KeyStore::init_mappings(&mut rram);
// does nothing if the keys are already initialized
store.ensure_system_init(&mut rram);
// derive the master key
store.derive_master_key();
let mut msg_opt = None; let mut msg_opt = None;

View file

@ -1,6 +1,8 @@
use aes::Aes256; use aes::Aes256;
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray}; use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};
use bao1x_api::{BOOT0_PUBKEY_FAIL, CP_ID, DEVELOPER_MODE, OEM_MODE, UUID}; use bao1x_api::{
BOOT0_PUBKEY_FAIL, BoardTypeCoding, CP_ID, DEVELOPER_MODE, OEM_MODE, SLOT_ELEMENT_LEN_BYTES, UUID,
};
use bao1x_hal::{ use bao1x_hal::{
acram::{OneWayCounter, SlotManager}, acram::{OneWayCounter, SlotManager},
board::{CHAFF_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, ROOT_SEED}, board::{CHAFF_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, ROOT_SEED},
@ -18,16 +20,78 @@ const KEY_LEN: usize = bao1x_api::SLOT_ELEMENT_LEN_BYTES;
pub struct KeyStore { pub struct KeyStore {
slot_mgr: SlotManager, slot_mgr: SlotManager,
owc: OneWayCounter, owc: OneWayCounter,
master_key: [u8; KEY_LEN], master_key: Option<[u8; KEY_LEN]>,
} }
impl KeyStore { impl KeyStore {
pub fn init_from_hw(rram: &mut Reram) -> Self { pub fn init_mappings(rram: &mut Reram) -> Self {
let slot_mgr = SlotManager::new(); let slot_mgr = SlotManager::new();
slot_mgr.register_mapping(rram); slot_mgr.register_mapping(rram);
let owc = OneWayCounter::new(); let owc = OneWayCounter::new();
owc.register_mapping(rram); owc.register_mapping(rram);
Self { slot_mgr, owc, master_key: None }
}
pub fn ensure_system_init(&mut self, rram: &mut Reram) {
// debug coreuser status
/*
let coreuser_range = xous::map_memory(
xous::MemoryAddress::new(utralib::utra::coreuser::HW_COREUSER_BASE),
None,
4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map coreuser range");
let coreuser = utralib::CSR::new(coreuser_range.as_mut_ptr() as *mut u32);
log::info!("coreuser status: {:x}", coreuser.r(utralib::utra::coreuser::STATUS));
*/
// one routine works for both dabao and baosec
let board_type = self.owc.get_decoded::<BoardTypeCoding>().unwrap();
if (board_type == bao1x_api::BoardTypeCoding::Baosec
&& self.owc.get(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() == 0)
|| (board_type == bao1x_api::BoardTypeCoding::Dabao
&& self.owc.get(bao1x_api::INVOKE_DABAO_KEY_SETUP).unwrap() != 0
&& self.owc.get(bao1x_api::DABAO_KEY_SETUP_DONE).unwrap() == 0)
{
log::info!("System setup not yet done. Initializing secret identifiers...");
let xns = xous_names::XousNames::new().unwrap();
let mut trng = bao1x_hal_service::trng::Trng::new(&xns).unwrap();
// generate all the keys
let key_set = if board_type == bao1x_api::BoardTypeCoding::Baosec {
&bao1x_api::baosec::KEY_SLOTS[..]
} else {
&bao1x_api::dabao::KEY_SLOTS[..]
};
let mut success = true;
for key_range in key_set.iter() {
let mut storage = Vec::<u8>::with_capacity(key_range.len() * SLOT_ELEMENT_LEN_BYTES);
storage.resize(key_range.len() * SLOT_ELEMENT_LEN_BYTES, 0);
trng.fill_bytes(&mut storage);
match self.slot_mgr.write(rram, key_range, &storage) {
Ok(_) => {}
Err(e) => {
success = false;
log::error!("Couldn't initialize slot {:?}: {:?}", key_range, e);
}
}
}
// once all values are written, advance the IN_SYSTEM_BOOT_SETUP_DONE state
// safety: the offset is correct because we're pulling it from our pre-defined constants and
// those are manually checked.
if success {
if board_type == bao1x_api::BoardTypeCoding::Baosec {
unsafe { self.owc.inc(bao1x_api::IN_SYSTEM_BOOT_SETUP_DONE).unwrap() };
} else if board_type == bao1x_api::BoardTypeCoding::Dabao {
unsafe { self.owc.inc(bao1x_api::DABAO_KEY_SETUP_DONE).unwrap() };
}
}
log::info!("Secret ID init done.");
}
}
pub fn derive_master_key(&mut self) {
let mut ikm = Vec::<u8>::new(); let mut ikm = Vec::<u8>::new();
let mut salt = Vec::<u8>::new(); let mut salt = Vec::<u8>::new();
let mut info = Vec::<u8>::new(); let mut info = Vec::<u8>::new();
@ -37,7 +101,7 @@ impl KeyStore {
// should stop/panic at that line. Kicking the error up the stack isn't useful. // should stop/panic at that line. Kicking the error up the stack isn't useful.
// read key material // read key material
ikm.extend_from_slice(slot_mgr.read(&ROOT_SEED).unwrap()); ikm.extend_from_slice(self.slot_mgr.read(&ROOT_SEED).unwrap());
// build nuisance key offsets - this is direct readout hardening // build nuisance key offsets - this is direct readout hardening
let nk0 = NUISANCE_KEYS_0.try_into_data_iter().unwrap(); let nk0 = NUISANCE_KEYS_0.try_into_data_iter().unwrap();
@ -71,7 +135,7 @@ impl KeyStore {
// safety: the offset is generated by the try_into_data_iter method, which generates // safety: the offset is generated by the try_into_data_iter method, which generates
// safe offsets // safe offsets
for (cx, &src) in for (cx, &src) in
chaff_xor.iter_mut().zip(unsafe { slot_mgr.read_key_slot(chaff_offset) }) chaff_xor.iter_mut().zip(unsafe { self.slot_mgr.read_data_slot(chaff_offset) })
{ {
*cx ^= src; *cx ^= src;
} }
@ -82,7 +146,7 @@ impl KeyStore {
// safety: the offset is generated by the try_into_data_iter method, which generates // safety: the offset is generated by the try_into_data_iter method, which generates
// safe offsets // safe offsets
for (cx, &src) in for (cx, &src) in
ct_xor.iter_mut().zip(unsafe { slot_mgr.read_key_slot(chaff_offset) }) ct_xor.iter_mut().zip(unsafe { self.slot_mgr.read_data_slot(chaff_offset) })
{ {
*cx ^= src; *cx ^= src;
} }
@ -95,13 +159,15 @@ impl KeyStore {
// get the nuisance key, in-order // get the nuisance key, in-order
// safety: the offset is generated by the try_into_data_iter method, which generates safe offsets // safety: the offset is generated by the try_into_data_iter method, which generates safe offsets
ikm.extend_from_slice(unsafe { slot_mgr.read_key_slot(nk_offset) }); ikm.extend_from_slice(unsafe { self.slot_mgr.read_data_slot(nk_offset) });
} }
// Drain the remainder. There's always going to be four keys left over because the NUISANCE array // Drain the remainder. There's always going to be four keys left over because the NUISANCE array
// isn't evenly sized due to the -A1 stepping bug. I think this isn't damning because the actual // isn't evenly sized due to the -A1 stepping bug. I think this isn't damning because the actual
// ordering of the chaff is unknown at this point, and it's always the same amount. // ordering of the chaff is unknown at this point, and it's always the same amount.
for remaining_chaff in chaff.drain(..) { for remaining_chaff in chaff.drain(..) {
for (cx, &src) in chaff_xor.iter_mut().zip(unsafe { slot_mgr.read_key_slot(remaining_chaff) }) { for (cx, &src) in
chaff_xor.iter_mut().zip(unsafe { self.slot_mgr.read_data_slot(remaining_chaff) })
{
*cx ^= src; *cx ^= src;
} }
} }
@ -113,24 +179,24 @@ impl KeyStore {
// add salt // add salt
// UUID is a random unique number made by the TRNG // UUID is a random unique number made by the TRNG
salt.extend_from_slice(slot_mgr.read(&UUID).unwrap()); salt.extend_from_slice(self.slot_mgr.read(&UUID).unwrap());
// CP_ID is a sequentially incrementing number that is included just in case something went horribly // CP_ID is a sequentially incrementing number that is included just in case something went horribly
// wrong with the TRNG during ID generation - this gives us at least *some* guaranteed uniqueness, // wrong with the TRNG during ID generation - this gives us at least *some* guaranteed uniqueness,
// but not randomness. // but not randomness.
salt.extend_from_slice(slot_mgr.read(&CP_ID).unwrap()); salt.extend_from_slice(self.slot_mgr.read(&CP_ID).unwrap());
// add info // add info
if owc.get(DEVELOPER_MODE).unwrap() != 0 { if self.owc.get(DEVELOPER_MODE).unwrap() != 0 {
info.extend_from_slice(b"dev"); info.extend_from_slice(b"dev");
} else { } else {
info.extend_from_slice(b"sec"); info.extend_from_slice(b"sec");
} }
if owc.get(OEM_MODE).unwrap() != 0 { if self.owc.get(OEM_MODE).unwrap() != 0 {
info.extend_from_slice(b"oem"); info.extend_from_slice(b"oem");
} }
if owc.get(BOOT0_PUBKEY_FAIL).unwrap() != 0 { if self.owc.get(BOOT0_PUBKEY_FAIL).unwrap() != 0 {
info.extend_from_slice(b"tampered"); info.extend_from_slice(b"tampered");
} }
@ -148,18 +214,17 @@ impl KeyStore {
log::warn!("Chaff result is all-0. Confirming that we're in developer mode"); log::warn!("Chaff result is all-0. Confirming that we're in developer mode");
// panic if we're not in developer mode // panic if we're not in developer mode
assert!( assert!(
owc.get(DEVELOPER_MODE).unwrap() != 0, self.owc.get(DEVELOPER_MODE).unwrap() != 0,
"Either we have the most improbable chaff, or (more likely) the chaff is set to all 0's" "Either we have the most improbable chaff, or (more likely) the chaff is set to all 0's"
); );
} }
self.master_key = Some(master_key);
Self { slot_mgr, owc, master_key }
} }
pub fn aes_kwp(&self, kwp: &mut KeyWrapper) -> Result<(), xous::Error> { pub fn aes_kwp(&self, kwp: &mut KeyWrapper) -> Result<(), xous::Error> {
use aes_kw::Kek; use aes_kw::Kek;
use aes_kw::KekAes256; use aes_kw::KekAes256;
let keywrapper: KekAes256 = Kek::from(self.master_key); let keywrapper: KekAes256 = Kek::from(self.master_key.ok_or(xous::Error::UseBeforeInit)?);
match kwp.op { match kwp.op {
KeyWrapOp::Wrap => { KeyWrapOp::Wrap => {
match keywrapper.wrap_with_padding_vec(&kwp.data[..kwp.len as usize]) { match keywrapper.wrap_with_padding_vec(&kwp.data[..kwp.len as usize]) {
@ -226,7 +291,7 @@ impl KeyStore {
AesOpType::Decrypt => AesOpType::Decrypt, AesOpType::Decrypt => AesOpType::Decrypt,
AesOpType::Encrypt => AesOpType::Encrypt, AesOpType::Encrypt => AesOpType::Encrypt,
}; };
let hk = Hkdf::<Sha256>::new(None, &self.master_key); let hk = Hkdf::<Sha256>::new(None, &self.master_key.ok_or(xous::Error::UseBeforeInit)?);
let mut okm = [0u8; 32]; let mut okm = [0u8; 32];
hk.expand(&aes_op.domain.as_bytes(), &mut okm).expect("32 is a valid length for Sha256 to output"); hk.expand(&aes_op.domain.as_bytes(), &mut okm).expect("32 is a valid length for Sha256 to output");
let cipher = Aes256::new(GenericArray::from_slice(&okm)); let cipher = Aes256::new(GenericArray::from_slice(&okm));

View file

@ -2510,7 +2510,7 @@ impl PddbOs {
} }
} }
self.entropy.borrow_mut().get_slice(&mut temp); self.entropy.borrow_mut().get_slice(&mut temp);
if (offset / PAGE_SIZE) % 256 == 0 { if (offset / PAGE_SIZE) % 32 == 0 {
// ~one update per megabyte // ~one update per megabyte
log::info!("Cryptographic 'erase': {}/{}", offset, PDDB_A_LEN); log::info!("Cryptographic 'erase': {}/{}", offset, PDDB_A_LEN);
if let Some(modals) = progress { if let Some(modals) = progress {

View file

@ -841,7 +841,11 @@ fn wrapped_main() -> ! {
unreachable!(); unreachable!();
} }
PasswordState::Incorrect(_failcount) => { PasswordState::Incorrect(_failcount) => {
unreachable!(); log::warn!("PDDB formatted, but keys rotated. Formatting PDDB!");
pddb_os.pddb_format(false, None).expect("couldn't format PDDB");
if !try_mount(&mut pddb_os, &mut basis_cache, &mut basis_monitor_notifications) {
panic!("Couldn't format & mount PDDB");
}
} }
} }
// the above operation should either succeed or panic, so we are always "success" here // the above operation should either succeed or panic, so we are always "success" here

View file

@ -678,6 +678,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
(bao1x_api::LOADER_START + sigblock_size + STATICS_LEN) as u32, (bao1x_api::LOADER_START + sigblock_size + STATICS_LEN) as u32,
)?; )?;
builder.add_loader_feature("alt-boot1"); builder.add_loader_feature("alt-boot1");
builder.add_loader_feature("force-dabao");
builder builder
.set_baremetal(true) .set_baremetal(true)
.target_baremetal_bao1x("bao1x-alt-boot1") .target_baremetal_bao1x("bao1x-alt-boot1")