add keystore master key derivation

the master key is currently derived from a number of factors:

- the key seed
- chaff keys
- nuisance keys

and then a salt of the uuid/cpid and some info based on the
developer bit is added.

The info addition ensures that the key rotates if developer
mode is entered, so in addition to the key material being
deleted, the info itself is different which should cause
the master key to rotate and "be lost" even if the key
erasure routine is flawed.

Chaff keys harden against side channel analysis of data
in flight from the RRAM array - under the theory that
the RRAM array is a big, long set of wires (on the order
of mm's) that should make a great target for EM microprobes.
The chaff keys are read out in a random order every boot,
to make it harder to accumulate enough samples to average
out what's going on.

The nuisance keys are just read straight out of the array.
They might be recoverable by side channel analysis, but
their purpose is to make it annoying for a brute-force
read-out of the key array by a microscopist. The location
and size of the nuisance keys are picked to force the attacker
to really dial in their polishing process so that they have
to hit the right layer across the entire chip (or at least
a couple mm's); and then a set of bits are packed closely
together to try and induce as much cross talk on the word
lines, running under the theory that any attack relying
on stray electrons activating the bitlines to enable read-out
are likely to non-selectively activate bitlines, so the
resulting "glow" of the word line is going to be a superposition
of several bits at once. An attacker could, of course, cap
each bit line with a FIB, read the word lines, then uncap/recap
them one by one - but this drives up the cost of the attack
and ensures that it's not just a single imaging run but
will take at least hours if not days for a skilled adversary
with the most modern equipment to extract the data. Furthermore,
the large amount of bits demands that the attacker read out
the data with better than 97% accuracy (the last 3% can be
cleaned by the ECC coded into the array), so mistakes
are costly.

The chaff/nuisance keys are read out where the chaff keys
(which are order-independent) are interleaved with the nuisance
key readout. The chaff keys are read roughly twice, using
a continuous-time algorithm to pick which version of the
chaff key is read, making it a bit harder for sidechannel
analysis to pick out which key is in flight.

It's an attempt at sidechannel hardening, we'll see how it
holds up. Pretty sure there's still some low hanging fruit
in the read-out, it'll be interesting to see what the red
team comes up with.

Hopefully this at least makes the keystore not the low hanging
fruit, and we're back at looking at bootloader/kernel exploits etc.
to do key extraction, which I'm sure there are many; but at
least those can be patched.
This commit is contained in:
bunnie 2025-10-28 17:29:06 +08:00
parent d8aa8cddd7
commit cb6bc4d2c6
No known key found for this signature in database
4 changed files with 162 additions and 0 deletions

View file

@ -31,6 +31,7 @@ keystore-api = { path = "../../libs/keystore-api" }
zeroize = { version = "1.7.0", features = ["zeroize_derive"] }
rand_core = "0.6.4"
rand = "0.8.5"
aes-kw = { version = "0.2.1", features = ["alloc"] }

View file

@ -0,0 +1,4 @@
pub mod server;
pub use server::*;
pub mod store;
pub use store::*;

View file

@ -2,17 +2,22 @@ use std::convert::TryInto;
use aes::Aes256;
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};
use bao1x_hal::rram::Reram;
use hkdf::Hkdf;
use keystore_api::*;
use sha2::Sha256;
use xous::SID;
use xous_ipc::Buffer;
use crate::platform::KeyStore;
/// Any old key for the hosted mode testing. 0 is as good a number as any other.
const WELL_KNOWN_KEY: &'static str = "0000000000000000000000000000000000000000000000000000000000000000";
pub fn keystore(sid: SID) -> ! {
let hal = bao1x_hal_service::Hal::new();
let mut rram = Reram::new();
let storage = KeyStore::init_from_hw(&mut rram);
let mut msg_opt = None;

View file

@ -0,0 +1,152 @@
use bao1x_api::{BOOT0_PUBKEY_FAIL, CP_ID, DEVELOPER_MODE, OEM_MODE, UUID};
use bao1x_hal::{
acram::{OneWayCounter, SlotManager},
board::{CHAFF_KEYS, NUISANCE_KEYS_0, NUISANCE_KEYS_1, ROOT_SEED},
rram::Reram,
};
use hkdf::Hkdf;
use rand::prelude::*;
use sha2::Sha256;
const KEY_LEN: usize = bao1x_api::SLOT_ELEMENT_LEN_BYTES;
pub struct KeyStore {
slot_mgr: SlotManager,
owc: OneWayCounter,
master_key: [u8; KEY_LEN],
}
impl KeyStore {
pub fn init_from_hw(rram: &mut Reram) -> Self {
let slot_mgr = SlotManager::new();
slot_mgr.register_mapping(rram);
let owc = OneWayCounter::new();
owc.register_mapping(rram);
let mut ikm = Vec::<u8>::new();
let mut salt = Vec::<u8>::new();
let mut info = Vec::<u8>::new();
let mut master_key = [0u8; KEY_LEN];
// All APIs below are .unwrap() because any access errors that occur are hard faults and
// 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());
// build nuisance key offsets - this is direct readout hardening
let nk0 = NUISANCE_KEYS_0.try_into_data_iter().unwrap();
let nk1 = NUISANCE_KEYS_1.try_into_data_iter().unwrap();
let nk = nk0.chain(nk1).collect::<Vec<usize>>();
let nk_len = nk.len();
// get chaff offsets - this is power side channel hardening
let mut chaff = CHAFF_KEYS.try_into_data_iter().unwrap().collect::<Vec<usize>>();
// compute chaff permutation order
let mut rng = rand::thread_rng();
chaff.shuffle(&mut rng);
let mut ct_chaff = chaff.clone();
ct_chaff.shuffle(&mut rng);
let mut chaff_xor = [0u8; KEY_LEN];
let mut ct_xor = [0u8; KEY_LEN]; // constant-time alternative
// reserve enough space so we don't risk invoking the allocator during the extensions
// we don't know what the allocator does, if it's data-dependent, that's a side channel.
// length is the master seed(1) + chaff(1) + nuisance(nk_len)
ikm.reserve((nk_len + 1 + 1) * KEY_LEN);
// guarantee an even distribution of 1/0 in the selectors
let mut selector = vec![true, false].repeat(nk.len() / 2);
// shuffle the order
selector.shuffle(&mut rng);
for nk_offset in nk.into_iter() {
if let Some(branch) = selector.pop() {
if branch {
if let Some(chaff_offset) = chaff.pop() {
// 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) })
{
*cx ^= src;
}
}
} else {
// redundant "dummy" path to make constant time
if let Some(chaff_offset) = ct_chaff.pop() {
// 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) })
{
*cx ^= src;
}
}
}
}
// flush the cache so that the read out chaff isn't cached for the next iteration, thus creating
// a side-channel
bao1x_hal::cache_flush();
// 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) });
}
// 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) }) {
*cx ^= src;
}
}
// log::info!("chaff: {:x?}", chaff_xor);
ikm.extend_from_slice(&chaff_xor);
assert!(ikm.len() == (nk_len + 1 + 1) * KEY_LEN); // sanity check that all keys were in fact added
// add salt
// UUID is a random unique number made by the TRNG
salt.extend_from_slice(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());
// add info
if 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 {
info.extend_from_slice(b"oem");
}
if owc.get(BOOT0_PUBKEY_FAIL).unwrap() != 0 {
info.extend_from_slice(b"tampered");
}
#[cfg(feature = "hazardous-debug")]
for (i, chunk) in ikm.chunks(256).enumerate() {
log::info!("ikm({:4}): {:x?}", i, chunk);
}
log::debug!("salt: {:x?}", salt); // not hazardous, these are public values
let hk = Hkdf::<Sha256>::new(Some(&salt[..]), &ikm);
log::debug!("info: {:x?}", info); // not hazardous, these are public values
hk.expand(&info, &mut master_key).unwrap();
// do something with ct_xor that guarantees it's never optimized out
if ct_xor.iter().all(|&cx| cx == 0) {
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,
"Either we have the most improbable chaff, or (more likely) the chaff is set to all 0's"
);
}
Self { slot_mgr, owc, master_key }
}
}