diff --git a/services/keystore/Cargo.toml b/services/keystore/Cargo.toml index 523bb209b..bf17c71ba 100644 --- a/services/keystore/Cargo.toml +++ b/services/keystore/Cargo.toml @@ -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"] } diff --git a/services/keystore/src/platform/baosec/mod.rs b/services/keystore/src/platform/baosec/mod.rs new file mode 100644 index 000000000..a6016cd8a --- /dev/null +++ b/services/keystore/src/platform/baosec/mod.rs @@ -0,0 +1,4 @@ +pub mod server; +pub use server::*; +pub mod store; +pub use store::*; diff --git a/services/keystore/src/platform/baosec.rs b/services/keystore/src/platform/baosec/server.rs similarity index 98% rename from services/keystore/src/platform/baosec.rs rename to services/keystore/src/platform/baosec/server.rs index 6e9a47dbc..66cb9a5bf 100644 --- a/services/keystore/src/platform/baosec.rs +++ b/services/keystore/src/platform/baosec/server.rs @@ -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; diff --git a/services/keystore/src/platform/baosec/store.rs b/services/keystore/src/platform/baosec/store.rs new file mode 100644 index 000000000..cfe013dd4 --- /dev/null +++ b/services/keystore/src/platform/baosec/store.rs @@ -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::::new(); + let mut salt = Vec::::new(); + let mut info = Vec::::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::>(); + 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::>(); + // 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::::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 } + } +}