move keystore init to userspace

This moves the key store initialization to the key manager
process itself.

It has been tested to work with signed images, and to also
protect the system in case of another process trying to access
the key data as well as in the case of developer keys being
used.
This commit is contained in:
bunnie 2025-11-13 18:32:04 +08:00
parent 9f8c2deeda
commit 9213755a6b
No known key found for this signature in database
4 changed files with 97 additions and 23 deletions

View file

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

View file

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

View file

@ -8,7 +8,11 @@ use crate::platform::KeyStore;
pub fn keystore(sid: SID) -> ! {
let hal = bao1x_hal_service::Hal::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;

View file

@ -1,6 +1,8 @@
use aes::Aes256;
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::{
acram::{OneWayCounter, SlotManager},
board::{CHAFF_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, ROOT_SEED},
@ -10,6 +12,7 @@ use hkdf::Hkdf;
use keystore_api::KeyWrapper;
use rand::prelude::*;
use sha2::Sha256;
use utralib::utra::coresub_sramtrm;
use crate::*;
@ -18,16 +21,74 @@ const KEY_LEN: usize = bao1x_api::SLOT_ELEMENT_LEN_BYTES;
pub struct KeyStore {
slot_mgr: SlotManager,
owc: OneWayCounter,
master_key: [u8; KEY_LEN],
master_key: Option<[u8; KEY_LEN]>,
}
impl KeyStore {
pub fn init_from_hw(rram: &mut Reram) -> Self {
pub fn init_mappings(rram: &mut Reram) -> Self {
let slot_mgr = SlotManager::new();
slot_mgr.register_mapping(rram);
let owc = OneWayCounter::new();
owc.register_mapping(rram);
Self { slot_mgr, owc, master_key: None }
}
pub fn ensure_system_init(&mut self, rram: &mut Reram) {
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 mut 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 salt = Vec::<u8>::new();
let mut info = Vec::<u8>::new();
@ -37,7 +98,7 @@ impl KeyStore {
// should stop/panic at that line. Kicking the error up the stack isn't useful.
// 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
let nk0 = NUISANCE_KEYS_0.try_into_data_iter().unwrap();
@ -71,7 +132,7 @@ impl KeyStore {
// safety: the offset is generated by the try_into_data_iter method, which generates
// safe offsets
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;
}
@ -82,7 +143,7 @@ impl KeyStore {
// safety: the offset is generated by the try_into_data_iter method, which generates
// safe offsets
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;
}
@ -95,13 +156,15 @@ impl KeyStore {
// get the nuisance key, in-order
// 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
// 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.
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;
}
}
@ -113,24 +176,24 @@ impl KeyStore {
// add salt
// 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
// wrong with the TRNG during ID generation - this gives us at least *some* guaranteed uniqueness,
// 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
if owc.get(DEVELOPER_MODE).unwrap() != 0 {
if self.owc.get(DEVELOPER_MODE).unwrap() != 0 {
info.extend_from_slice(b"dev");
} else {
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");
}
if owc.get(BOOT0_PUBKEY_FAIL).unwrap() != 0 {
if self.owc.get(BOOT0_PUBKEY_FAIL).unwrap() != 0 {
info.extend_from_slice(b"tampered");
}
@ -148,18 +211,17 @@ impl KeyStore {
log::warn!("Chaff result is all-0. Confirming that we're in developer mode");
// panic if we're not in developer mode
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"
);
}
Self { slot_mgr, owc, master_key }
self.master_key = Some(master_key);
}
pub fn aes_kwp(&self, kwp: &mut KeyWrapper) -> Result<(), xous::Error> {
use aes_kw::Kek;
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 {
KeyWrapOp::Wrap => {
match keywrapper.wrap_with_padding_vec(&kwp.data[..kwp.len as usize]) {
@ -226,7 +288,7 @@ impl KeyStore {
AesOpType::Decrypt => AesOpType::Decrypt,
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];
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));