implementation of the ACL APIs and coreuser functionality

'coreuser' is a slightly confusing term from the hardware
system because it's overloaded to mean some conceptually
related items that aren't implementation-wise essentially linked.

coreuser defines both some access protections on the main
array of the RRAM, and also some access protections on key
and data slots.

this patch includes some code that sets up the coreuser
functionality to a very simple scheme where just one PID
is trusted and the rest are not trusted. More complicated
schemes could be introduced with varying levels of trust
and dependencies but I like the analytical simplicity of
two states, so let's start there and complicate only when
absolutely necessary.
This commit is contained in:
bunnie 2025-10-20 02:15:20 +08:00
parent a64337679f
commit 0943b67972
No known key found for this signature in database
7 changed files with 347 additions and 385 deletions

View file

@ -1,22 +1,20 @@
//! Current usage model is that the same process that maps ACRAM is the same
//! process that maps all of Data and Key areas. So we don't have to worry about
//! sharing protection state. However, pages of data/key area can be mapped into
//! different processes, in which case, the processes lose any ability to write
//! or directly manage the areas (it becomes effectively ROM).
//!
//! In the case of baremetal targets of course everything is mapped, so these
//! restrictions are not a concern.
use bao1x_api::OneWayEncoding;
use bitbybit::*;
use bao1x_api::offsets::*;
#[cfg(feature = "std")]
use xous::MemoryRange;
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_LEN: usize = 0x1_0000;
pub const MAX_DATA_SLOTS: usize = DATA_SLOT_LEN / SLOT_ELEMENT_LEN_BYTES;
pub const SLOT_ELEMENT_LEN_BYTES: usize = 256 / 8;
use crate::coreuser::CoreuserId;
use crate::rram::Reram;
pub const ACRAM_DATASLOT_START: usize = 0x603D_C000;
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 ONEWAY_START: usize = 0x603D_A000; // page with 128 counters
pub const ONEWAY2_START: usize = 0x603D_B000; // page with another 128 counters
const ONEWAY_LEN: usize = 256 / 8; // in bytes
@ -24,78 +22,6 @@ const COUNTER_STRIDE_U32: usize = ONEWAY_LEN / size_of::<u32>();
pub const MAX_ONEWAY_COUNTERS: usize = 8192 / ONEWAY_LEN;
pub const CODESEL_END: usize = 0x603D_A000;
#[bitfield(u32)]
#[derive(PartialEq, Eq)]
pub struct DataSlotAccess {
#[bit(24, rw)]
write_mode: bool,
#[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 DataSlotAccess {
// 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_DATASLOT_START as *const DataSlotAccess, 2048) };
slot_array[slot]
}
}
#[bitfield(u32)]
#[derive(PartialEq, Eq)]
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]
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OneWayErr {
OutOfBounds,
@ -202,3 +128,223 @@ impl OneWayCounter {
T::try_from(raw).map_err(|_| OneWayErr::InvalidCoding)
}
}
#[derive(PartialEq, Eq)]
pub enum AccessSettings {
Data(DataSlotAccess),
Key(KeySlotAccess),
}
impl AccessSettings {
pub fn raw_u32(&self) -> u32 {
match self {
Self::Data(d) => d.raw_value(),
Self::Key(d) => d.raw_value(),
}
}
pub fn allows_cpu_read(&self) -> bool {
match self {
Self::Data(d) => !d.core_rd_dis(),
Self::Key(d) => !d.core_rd_dis(),
}
}
pub fn allows_cpu_write(&self) -> bool {
match self {
Self::Data(d) => !d.core_wr_dis(),
Self::Key(d) => !d.core_wr_dis(),
}
}
/// This bit is set if the slot only allows 0->1 transitions
pub fn is_set_only(&self) -> bool {
match self {
Self::Data(d) => d.write_mode(),
Self::Key(_d) => false,
}
}
}
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum AccessType {
Read,
Write,
ReadWrite,
None,
}
pub struct SlotManager {
data_range: xous::MemoryRange,
data_acl_range: xous::MemoryRange,
key_range: xous::MemoryRange,
key_acl_range: xous::MemoryRange,
user_id: CoreuserId,
}
impl SlotManager {
/// Creates a handle to a new slot index
pub fn new() -> Self {
#[cfg(feature = "std")]
let data_range = xous::map_memory(
xous::MemoryAddress::new(DATA_SLOT_START),
None,
DATA_SLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map slot range");
#[cfg(feature = "std")]
let data_acl_range = xous::map_memory(
xous::MemoryAddress::new(ACRAM_DATASLOT_START),
None,
ACRAM_DATASLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map ACL range");
#[cfg(feature = "std")]
let key_range = xous::map_memory(
xous::MemoryAddress::new(KEY_SLOT_START),
None,
KEY_SLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map slot range");
#[cfg(feature = "std")]
let key_acl_range = xous::map_memory(
xous::MemoryAddress::new(ACRAM_KEYSLOT_START),
None,
ACRAM_KEYSLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map ACL range");
#[cfg(not(feature = "std"))]
// safety: these ranges are valid and pre-aligned
let data_range = unsafe { xous::MemoryRange::new(DATA_SLOT_START, DATA_SLOT_LEN).unwrap() };
#[cfg(not(feature = "std"))]
// safety: these ranges are valid and pre-aligned
let data_acl_range =
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")]
let user_id = if xous::process::id() == crate::coreuser::TRUSTED_PID as u32 {
crate::coreuser::TRUSTED_USER
} else {
crate::coreuser::LEAST_TRUSTED_USER
};
// pre-boot, we are in a baremetal context and we have full access to the data slots.
#[cfg(not(feature = "std"))]
let user_id = crate::coreuser::TRUSTED_USER;
Self { data_range, data_acl_range, key_range, key_acl_range, user_id }
}
pub fn read(&self, slot: &SlotIndex) -> Result<&[u8], AccessError> {
// check the ACL first
let acl = self.get_acl(slot)?;
if self.user_id.is_accessible(&acl, &AccessType::Read) {
let offset = slot.try_into_data_offset()?;
// safety: the unsafes below remind us to check that all values are valid during
// the pointer type cast. In this case, there are no invalid values for a `u8`.
Ok(match slot {
SlotIndex::Data(_, _) => unsafe {
let ptr: *const u8 = &self.data_range.as_slice::<u8>()[offset] as *const u8;
crate::println!("data loc: {:x}", ptr as usize);
&self.data_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES]
},
SlotIndex::Key(_, _) => unsafe {
let ptr: *const u8 = &self.data_range.as_slice::<u8>()[offset] as *const u8;
crate::println!("data loc: {:x}", ptr as usize);
&self.key_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES]
},
_ => return Err(AccessError::TypeError),
})
} else {
Err(AccessError::AccessDenied)
}
}
pub fn write(
&self,
writer: &mut Reram,
slot: &SlotIndex,
value: &[u8; SLOT_ELEMENT_LEN_BYTES],
) -> Result<(), AccessError> {
let acl = self.get_acl(slot)?;
if self.user_id.is_accessible(&acl, &AccessType::Write) {
let offset = slot.try_into_data_offset()?;
let range = match slot {
SlotIndex::Data(_, _) => &self.data_range,
SlotIndex::Key(_, _) => &self.key_range,
_ => return Err(AccessError::TypeError),
};
writer
.protected_write_slice(range.as_ptr() as usize + offset, value)
.map_err(|_| AccessError::WriteError)?;
crate::cache_flush();
}
if self.user_id.is_accessible(&acl, &AccessType::Read) {
// read-verify only if we have read access
let readback = self.read(slot)?;
if readback != value { Err(AccessError::WriteError) } else { Ok(()) }
} else {
Ok(())
}
}
pub fn get_acl(&self, slot: &SlotIndex) -> Result<AccessSettings, AccessError> {
let offset = slot.try_into_acl_offset()?;
// 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.
Ok(match slot {
SlotIndex::Data(_, _) => {
AccessSettings::Data(DataSlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe {
self.data_acl_range.as_slice()[offset..offset + size_of::<u32>()].try_into().unwrap()
})))
}
SlotIndex::Key(_, _) => {
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()
})))
}
_ => return Err(AccessError::TypeError),
})
}
pub fn set_acl(
&self,
writer: &mut Reram,
slot: &SlotIndex,
setting: &AccessSettings,
) -> Result<(), AccessError> {
let offset = slot.try_into_acl_offset()?;
// 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.
match slot {
SlotIndex::Data(_, _) => writer
.protected_write_slice(
self.data_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset,
&setting.raw_u32().to_le_bytes(),
)
.map(|_| ())
.map_err(|_| AccessError::WriteError),
SlotIndex::Key(_, _) => 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),
_ => return Err(AccessError::TypeError),
}
}
}

View file

@ -55,6 +55,10 @@ pub const CAM_IFRAM_ADDR: usize =
pub const IFRAM0_RESERVED_PAGE_RANGE: [usize; 2] = [31 - 9 - CRG_IFRAM_PAGES, 31];
pub const IFRAM1_RESERVED_PAGE_RANGE: [usize; 2] = [31 - CAM_IFRAM_LEN_PAGES, 31];
// Re-export all of the offsets exposed in the API
pub use bao1x_api::offsets::baosec::*;
pub use bao1x_api::offsets::*;
// Display pins
const SPI_CS_PIN: u8 = 3;
const SPI_CLK_PIN: u8 = 0;

View file

@ -28,6 +28,10 @@ pub const CRG_UDC_MEMBASE: usize =
pub const IFRAM0_RESERVED_PAGE_RANGE: [usize; 2] = [31 - 4, 31];
pub const IFRAM1_RESERVED_PAGE_RANGE: [usize; 2] = [31 - 0, 31];
// Re-export all of the offsets exposed in the API
pub use bao1x_api::offsets::dabao::*;
pub use bao1x_api::offsets::*;
const SE0_PIN: u8 = 13;
const SE0_PORT: IoxPort = IoxPort::PC;
/// Sets the SE0 pin to drive and returns the port number. Note this side-effects the boot switch reading.

View file

@ -1,4 +1,7 @@
use crate::protected_rram::{AccessSettings, AccessType};
#[cfg(not(feature = "std"))]
use utralib::*;
use crate::acram::{AccessSettings, AccessType};
#[repr(usize)]
#[derive(Copy, Clone, Eq, PartialEq)]
@ -29,6 +32,16 @@ impl From<u32> for CoreuserId {
}
}
}
impl CoreuserId {
pub fn as_dense(&self) -> u32 {
match self {
Self::Boot0 => 0,
Self::Boot1 => 1,
Self::Fw0 => 2,
Self::Fw1 => 3,
}
}
}
// what I want is a function that, given a DataSlotAccess, returns if access
// is allowable for a given CoreuserId
@ -56,5 +69,85 @@ impl CoreuserId {
}
}
/// This is the PID of the process that is designated to have trusted access to keys.
pub const TRUSTED_PID: u32 = 3;
/// This is the PID of the process that is designated to have trusted access to keys. This should be
/// the PID of the `keystore` service.
pub const TRUSTED_PID: u8 = 3;
/// This is the "user" of the trusted process. There's four regions defined which have
/// meanings in two different contexts:
/// 1. Read/write control of a hardware-defined region of the main RRAM array. These are hard-defined
/// constants burned into a bank of memory that is only accessible at wafer probe, and then is sealed.
/// The main use of this r/w control is actually just to enforce read-only for the 'boot0' region, so
/// that the public keys that verify a firmware image can't be modified.
/// 2. Access control of a key or data slot. These are managed by a totally different piece of hardware,
/// even though the naming terminology is the same. In the case of the RV32 CPU, the mapping of the four
/// possible regions are dynamically mapped using a LUT, from a given ASID (address space ID) to one of
/// teh four user states. An exploit chain would nominally need to gain code execution in machine mode
/// (e.g. the kernel) to modify the ASID; an ASID-mod gadget can force any process to masquerade as the
/// 'trusted' process.
///
/// In the context for this constant, we are defining (2), i.e., the trusted user target for the access
/// control hardware. Note that boot0 is the default boot state of the machine - so in theory, the bootloader
/// doesn't (easily) have access to the key slots. Nominally one would need to boot into Xous and run
/// the `keystore`; but of course, in bootloader (machine mode), you have the power to conjure any ASID
/// out of thin air so with arbitrary code exec in bootloader one can bypass the controls.
///
/// Thus there are two attack surfaces of concern: the bootloader, and the kernel. Arbitrary code execution
/// in either environment is game over for the hardware access control.
pub const TRUSTED_USER: CoreuserId = CoreuserId::Fw0;
pub const LEAST_TRUSTED_USER: CoreuserId = CoreuserId::Fw1;
#[cfg(not(feature = "std"))]
pub struct Coreuser {
csr: CSR<u32>,
}
#[cfg(not(feature = "std"))]
#[derive(Copy, Clone)]
pub struct AsidMapping {
asid: u8,
uid: CoreuserId,
}
/// Methods are only defined for no-std operation. In all cases, these tables should be
/// set up before Xous runs.
#[cfg(not(feature = "std"))]
impl Coreuser {
pub fn new() -> Self { Self { csr: CSR::new(utra::coreuser::HW_COREUSER_BASE as *mut u32) } }
/// Sets up the coreuser mappings. There's...really no options or arguments, I think this should
/// more or less be a hard-coded table.
///
/// Safety: only safe if `protect()` is called after these are set. `protect` is provided as
/// a "split" call to allow for debugging/testing of this API.
pub unsafe fn set(&mut self) {
// set to 0 so we can safely mask it later on
self.csr.wo(utra::coreuser::USERVALUE, 0);
self.csr.rmwf(utra::coreuser::USERVALUE_DEFAULT, CoreuserId::Fw1.as_dense());
let trusted_asids = [
AsidMapping { asid: 1, uid: LEAST_TRUSTED_USER }, // kernel - untrusted
AsidMapping { asid: 2, uid: LEAST_TRUSTED_USER }, // swapper - untrusted
AsidMapping { asid: TRUSTED_PID, uid: TRUSTED_USER }, // this is the one trusted PID
AsidMapping { asid: 4, uid: LEAST_TRUSTED_USER }, // fillers - untrusted
AsidMapping { asid: 5, uid: LEAST_TRUSTED_USER },
AsidMapping { asid: 6, uid: LEAST_TRUSTED_USER },
AsidMapping { asid: 7, uid: LEAST_TRUSTED_USER },
];
let asid_fields = [
(utra::coreuser::MAP_LO_LUT0, utra::coreuser::USERVALUE_USER0),
(utra::coreuser::MAP_LO_LUT1, utra::coreuser::USERVALUE_USER1),
(utra::coreuser::MAP_LO_LUT2, utra::coreuser::USERVALUE_USER2),
(utra::coreuser::MAP_LO_LUT3, utra::coreuser::USERVALUE_USER3),
(utra::coreuser::MAP_HI_LUT4, utra::coreuser::USERVALUE_USER4),
(utra::coreuser::MAP_HI_LUT5, utra::coreuser::USERVALUE_USER5),
(utra::coreuser::MAP_HI_LUT6, utra::coreuser::USERVALUE_USER6),
(utra::coreuser::MAP_HI_LUT7, utra::coreuser::USERVALUE_USER7),
];
for (&mapping, (map_field, uservalue_field)) in trusted_asids.iter().zip(asid_fields) {
self.csr.rmwf(map_field, mapping.asid as u32);
self.csr.rmwf(uservalue_field, mapping.uid.as_dense());
}
}
/// Sets a "one way door" that disallows any further updating to these fields.
pub fn protect(&mut self) { self.csr.wo(utra::coreuser::PROTECT, 1); }
}

View file

@ -35,8 +35,6 @@ pub mod coreuser;
#[cfg(not(feature = "hosted-baosec"))]
pub mod mbox;
#[cfg(not(feature = "hosted-baosec"))]
pub mod protected_rram;
#[cfg(not(feature = "hosted-baosec"))]
pub mod rram;
// no signature checking in the kernel
#[cfg(all(

View file

@ -1,290 +0,0 @@
//! Current usage model is that the same process that maps ACRAM is the same
//! process that maps all of Data and Key areas. So we don't have to worry about
//! sharing protection state. However, pages of data/key area can be mapped into
//! different processes, in which case, the processes lose any ability to write
//! or directly manage the areas (it becomes effectively ROM).
//!
//! In the case of baremetal targets of course everything is mapped, so these
//! restrictions are not a concern.
use crate::acram::*;
use crate::coreuser::CoreuserId;
use crate::rram::Reram;
#[derive(PartialEq, Eq)]
pub enum AccessSettings {
Data(DataSlotAccess),
Key(KeySlotAccess),
}
impl AccessSettings {
pub fn raw_u32(&self) -> u32 {
match self {
Self::Data(d) => d.raw_value(),
Self::Key(d) => d.raw_value(),
}
}
pub fn allows_cpu_read(&self) -> bool {
match self {
Self::Data(d) => !d.core_rd_dis(),
Self::Key(d) => !d.core_rd_dis(),
}
}
pub fn allows_cpu_write(&self) -> bool {
match self {
Self::Data(d) => !d.core_wr_dis(),
Self::Key(d) => !d.core_wr_dis(),
}
}
/// This bit is set if the slot only allows 0->1 transitions
pub fn is_set_only(&self) -> bool {
match self {
Self::Data(d) => d.write_mode(),
Self::Key(_d) => false,
}
}
}
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum AccessType {
Read,
Write,
ReadWrite,
None,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum Error {
/// Access is anticipated to be denied by the hardware. Users can attempt to still
/// bypass the access control, but the result will either be invalid data, returned,
/// a failed, write, or a security alarm being raised, depending on the hardware
/// enforcement policy at play.
AccessDenied,
/// Returned when data is written to a slot that only supports 0->1 transitions
/// and the provided data contains 1->0 transitions, but the 0->1 transitions
/// were in fact correctly set
OnlyOnes,
/// Returned when data written did not verify
WriteError,
/// Returned when the wrong type of access settings are passed for setting access
TypeError,
/// Returned when an index request is out of valid bounds
OutOfBounds,
}
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum SlotIndex {
Data(usize),
Key(usize),
}
impl SlotIndex {
/// Returns `OutOfBounds` error if the index specified in the slot is out of bounds.
pub fn try_into_data_offset(&self) -> Result<usize, Error> {
match self {
Self::Data(index) => {
if *index < MAX_DATA_SLOTS {
Ok(*index * SLOT_ELEMENT_LEN_BYTES)
} else {
Err(Error::OutOfBounds)
}
}
Self::Key(index) => {
if *index < MAX_KEY_SLOTS {
Ok(*index * SLOT_ELEMENT_LEN_BYTES)
} else {
Err(Error::OutOfBounds)
}
}
}
}
pub fn try_into_acl_offset(&self) -> Result<usize, Error> {
match self {
Self::Data(index) => {
if *index < MAX_DATA_SLOTS {
Ok(*index * size_of::<u32>())
} else {
Err(Error::OutOfBounds)
}
}
Self::Key(index) => {
if *index < MAX_KEY_SLOTS {
Ok(*index * size_of::<u32>())
} else {
Err(Error::OutOfBounds)
}
}
}
}
}
pub struct SlotManager {
data_range: xous::MemoryRange,
data_acl_range: xous::MemoryRange,
key_range: xous::MemoryRange,
key_acl_range: xous::MemoryRange,
user_id: CoreuserId,
}
impl SlotManager {
/// Creates a handle to a new slot index
pub fn new() -> Self {
#[cfg(feature = "std")]
let data_range = xous::map_memory(
xous::MemoryAddress::new(DATA_SLOT_START),
None,
DATA_SLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map slot range");
#[cfg(feature = "std")]
let data_range = xous::map_memory(
xous::MemoryAddress::new(ACRAM_DATASLOT_START),
None,
ACRAM_DATASLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map ACL range");
#[cfg(feature = "std")]
let key_range = xous::map_memory(
xous::MemoryAddress::new(KEY_SLOT_START),
None,
KEY_SLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map slot range");
#[cfg(feature = "std")]
let data_range = xous::map_memory(
xous::MemoryAddress::new(ACRAM_KEYSLOT_START),
None,
ACRAM_KEYSLOT_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map ACL range");
#[cfg(not(feature = "std"))]
// safety: these ranges are valid and pre-aligned
let data_range = unsafe { xous::MemoryRange::new(DATA_SLOT_START, DATA_SLOT_LEN).unwrap() };
#[cfg(not(feature = "std"))]
// safety: these ranges are valid and pre-aligned
let data_acl_range =
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")]
let user_id = if xous::process::id() == crate::coreuser::TRUSTED_PID {
CoreuserId::Boot1
} else {
CoreuserId::Fw0
};
// pre-boot, we are in a baremetal context and we have full access to the data slots.
#[cfg(not(feature = "std"))]
let user_id = CoreuserId::Boot1;
Self { data_range, data_acl_range, key_range, key_acl_range, user_id }
}
pub fn read(&self, slot: &SlotIndex) -> Result<&[u8], Error> {
// check the ACL first
let acl = self.get_acl(slot)?;
if self.user_id.is_accessible(&acl, &AccessType::Read) {
let offset = slot.try_into_data_offset()?;
// safety: the unsafes below remind us to check that all values are valid during
// the pointer type cast. In this case, there are no invalid values for a `u8`.
Ok(match slot {
SlotIndex::Data(_) => unsafe {
let ptr: *const u8 = &self.data_range.as_slice::<u8>()[offset] as *const u8;
crate::println!("data loc: {:x}", ptr as usize);
&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]
},
})
} else {
Err(Error::AccessDenied)
}
}
pub fn write(
&self,
writer: &mut Reram,
slot: &SlotIndex,
value: &[u8; SLOT_ELEMENT_LEN_BYTES],
) -> Result<(), Error> {
let acl = self.get_acl(slot)?;
if self.user_id.is_accessible(&acl, &AccessType::Write) {
let offset = slot.try_into_data_offset()?;
let range = match slot {
SlotIndex::Data(_) => &self.data_range,
SlotIndex::Key(_) => &self.key_range,
};
writer
.protected_write_slice(range.as_ptr() as usize + offset, value)
.map_err(|_| Error::WriteError)?;
crate::cache_flush();
}
if self.user_id.is_accessible(&acl, &AccessType::Read) {
// read-verify only if we have read access
let readback = self.read(slot)?;
if readback != value { Err(Error::WriteError) } else { Ok(()) }
} else {
Ok(())
}
}
pub fn get_acl(&self, slot: &SlotIndex) -> Result<AccessSettings, Error> {
let offset = slot.try_into_acl_offset()?;
// 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.
Ok(match slot {
SlotIndex::Data(_) => {
AccessSettings::Data(DataSlotAccess::new_with_raw_value(u32::from_le_bytes(unsafe {
self.data_acl_range.as_slice()[offset..offset + size_of::<u32>()].try_into().unwrap()
})))
}
SlotIndex::Key(_) => {
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()
})))
}
})
}
pub fn set_acl(
&self,
writer: &mut Reram,
slot: &SlotIndex,
setting: &AccessSettings,
) -> Result<(), Error> {
let offset = slot.try_into_acl_offset()?;
// 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.
match slot {
SlotIndex::Data(_) => writer
.protected_write_slice(
self.data_acl_range.as_ptr() as usize - utralib::HW_RERAM_MEM + offset,
&setting.raw_u32().to_le_bytes(),
)
.map(|_| ())
.map_err(|_| Error::WriteError),
SlotIndex::Key(_) => 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(|_| Error::WriteError),
}
}
}

View file

@ -54,7 +54,7 @@ const RRC_CR_POWERDOWN: u32 = 1;
const RRC_CR_WRITE_DATA: u32 = 0;
const RRC_CR_WRITE_CMD: u32 = 2;
impl Reram {
impl<'a> Reram {
#[cfg(not(feature = "std"))]
pub fn new() -> Self {
let mut csr = CSR::new(utra::rrc::HW_RRC_BASE as *mut u32);
@ -81,7 +81,7 @@ impl Reram {
let mut csr = CSR::new(utra::rrc::HW_RRC_BASE as *mut u32);
// this enables access control protections. In metal-mask stepping A1, this will
// be hard-wired as enabled without an option to turn it off.
csr.wo(utra::rrc::SFR_RRCCR_SFR_RRCCR, SECURITY_MODE);
csr.wfo(utra::rrc::SFR_RRCCR_SFR_RRCCR, SECURITY_MODE);
// register an IRQ handler for atomic updates of RRAM
todo!(
@ -96,9 +96,9 @@ impl Reram {
/// to where this range maps to. This is necessary because `range` is virtually
/// mapped and we cannot infer the actual offset into the RRAM array from
/// that artifact alone.
pub fn add_range(&'a mut self, base: usize, range: xous::MemoryRange) -> &'a self {
pub fn add_range(&'a mut self, base: usize, range: xous::MemoryRange) -> &'a Self {
let top = base + range.len();
self.range_map.insert(base..top, value);
self.range_map.insert(base..top, base);
}
pub fn read_slice(&self) -> &[u32] { self.array }
@ -261,6 +261,13 @@ impl Reram {
// TODO: write interrupt-handler based variant of the above that happens in an interrupt
// context.
#[cfg(feature = "std")]
pub fn write_slice(&mut self, offset: usize, data: &[u8]) -> Result<usize, xous::Error> { todo!() }
#[cfg(feature = "std")]
pub fn protected_write_slice(&mut self, offset: usize, data: &[u8]) -> Result<usize, xous::Error> {
todo!()
}
}
#[cfg(feature = "std")]