From 7162b05a7f8f9898e5a2b5bce1ab0647259485fe Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 4 Jul 2022 04:06:53 +0800 Subject: [PATCH] add routines for testing secret basis When the "autobasis" feature is selected, the hardware block will track all basis that have been opened and unlock them when it comes time to scan/generate more FSCB space. It also bypasses all UX normally invoked. This allows us to create tests that open and close Bases automatically, but of course, totally destroys the notion of plausible deniability. So, don't turn the feature on for production. --- services/pddb/src/api.rs | 6 +- services/pddb/src/backend/basis.rs | 2 +- services/pddb/src/backend/hw.rs | 118 ++++++++++++++++++++++++++++- services/pddb/src/lib.rs | 15 ++++ services/pddb/src/main.rs | 18 +++++ 5 files changed, 155 insertions(+), 4 deletions(-) diff --git a/services/pddb/src/api.rs b/services/pddb/src/api.rs index 53cf542d3..d2361c90b 100644 --- a/services/pddb/src/api.rs +++ b/services/pddb/src/api.rs @@ -39,8 +39,8 @@ pub(crate) const PDDB_VERSION: u32 = 0x00_00_02_01; #[allow(dead_code)] // PDDB_A_LEN may be shorter than xous::PDDB_LEN, to speed up testing. #[allow(dead_code)] -// pub(crate) const PDDB_A_LEN: usize = xous::PDDB_LEN as usize; -pub(crate) const PDDB_A_LEN: usize = 4 * 1024 * 1024; +pub(crate) const PDDB_A_LEN: usize = xous::PDDB_LEN as usize; +// pub(crate) const PDDB_A_LEN: usize = 4 * 1024 * 1024; /// range for the starting point of a journal number, picked from a random seed /// the goal is to reduce info leakage about the age of structures relative to each other @@ -133,6 +133,8 @@ pub(crate) enum Opcode { /// Write debug dump (only available in hosted mode) #[cfg(not(any(target_os = "none", target_os = "xous")))] DangerousDebug = 25, + #[cfg(feature="pddbtest")] + BasisTesting = 26, /// This key type could not be decoded InvalidOpcode = u32::MAX as _, diff --git a/services/pddb/src/backend/basis.rs b/services/pddb/src/backend/basis.rs index 984ae61e9..1be8cff21 100644 --- a/services/pddb/src/backend/basis.rs +++ b/services/pddb/src/backend/basis.rs @@ -946,7 +946,7 @@ impl BasisCache { } } else { for basis in self.cache.iter_mut() { - log::info!("syncing {}", basis.name); + log::debug!("syncing {}", basis.name); basis.sync(hw)?; } } diff --git a/services/pddb/src/backend/hw.rs b/services/pddb/src/backend/hw.rs index b1650d366..581f24272 100644 --- a/services/pddb/src/backend/hw.rs +++ b/services/pddb/src/backend/hw.rs @@ -12,7 +12,7 @@ use core::ops::{Deref, DerefMut}; use core::mem::size_of; use std::collections::HashMap; -#[cfg(not(feature="deterministic"))] +#[cfg(any(all(feature="pddbtest", feature="autobasis"), not(feature="deterministic")))] use std::collections::HashSet; #[cfg(feature="deterministic")] use std::collections::BTreeSet; @@ -47,6 +47,9 @@ pub const KCOM_CT_LEN: usize = 4004; pub(crate) const WRAPPED_AES_KEYSIZE: usize = AES_KEYSIZE + 8; const SCD_VERSION: u32 = 2; +#[cfg(feature="pddbtest")] +pub const BASIS_TEST_ROOTNAME: &'static str = "test"; + #[derive(Zeroize)] #[zeroize(drop)] #[repr(C)] // this can map directly into Flash @@ -132,6 +135,8 @@ pub(crate) struct PddbOs { entropy: Rc>, /// connection to the password request manager pw_cid: xous::CID, + #[cfg(all(feature="pddbtest", feature="autobasis"))] + testnames: HashSet::, } impl PddbOs { @@ -178,6 +183,8 @@ impl PddbOs { dna: llio.soc_dna().unwrap(), entropy: trngpool, pw_cid, + #[cfg(all(feature="pddbtest", feature="autobasis"))] + testnames: HashSet::new(), }; // emulated #[cfg(not(any(target_os = "none", target_os = "xous")))] @@ -201,6 +208,8 @@ impl PddbOs { dna: llio.soc_dna().unwrap(), entropy: trngpool, pw_cid, + #[cfg(all(feature="pddbtest", feature="autobasis"))] + testnames: HashSet::new(), } }; ret @@ -1778,6 +1787,7 @@ impl PddbOs { /// valid (it'll scan up and stop as soon as one Pte checks out). Note that it then only returns /// a Vec of keys & names, not a BasisCacheEntry -- so it means that the Basis still are "closed" /// at the conclusion of the sweep, but their page use can be accounted for. + #[cfg(not(all(feature="pddbtest", feature="autobasis")))] pub(crate) fn pddb_get_all_keys(&self, cache: &Vec::) -> Option> { const SWAP_DELAY_MS: usize = 300; let mut ret = Vec::<([u8; AES_KEYSIZE], String)>::new(); @@ -1978,6 +1988,112 @@ impl PddbOs { } } + //-------------------------------- TESTING ----------------------------------------- + // always gated behind a feature flag. Includes routines that are nonsensicle in normal operation at best, + // and very dangerous from a security perspective at worst. + + /// basis_testing takes an argument a vector of supplemental test Bases to mount or unmount. + /// If the basis does not exist, it is created. This accompanies a warning, because we can't know + /// if the intention was to create the basis or just mount it; but for testing, the diagnosis is always + /// going to be in the test logs, so it's more direct to print the error here instead of percolating + /// it back toward the caller. + /// The `Vec` is interpretd as follows: + /// - index of `vec` corresponds to the test basis number. + /// - the `Option` if `true` means to mount; if `false` means to unmount; None means skip + /// The basis always has the naming format of `test#`, where # is the index in the Vec. This allows + /// testing routines to selectively write to one basis by designating it as, for example + /// `test0`, `test1`, `test2`,...; the password is the same name as the Basis, for simplicity. + /// + /// The tooling and argument spec on this is deliberately sparse because this routine is meant to + /// be only used "if you know what you're doing" and we want to make the arg passing as minimal/easy + /// as possible (just a scalar) to cut down on testing overhead. + #[cfg(all(feature="pddbtest", feature="autobasis"))] + pub(crate) fn basis_testing(&mut self, cache: &mut BasisCache, config: &[Option; 32]) { + for (index, &maybe_op) in config.iter().enumerate() { + let name = format!("{}{}", BASIS_TEST_ROOTNAME, index); + if let Some(op) = maybe_op { + if op { // try to mount the basis, or create it if it does not exist. + self.testnames.insert(name.to_string()); + let maybe_basis = cache.basis_unlock( + self, &name, &name, BasisRetentionPolicy::Persist); + + if maybe_basis.is_some() { + cache.basis_add(maybe_basis.unwrap()); + } else { + cache.basis_create(self, &name, &name).expect("couldn't create basis"); + let basis = cache.basis_unlock(self, &name, &name, BasisRetentionPolicy::Persist) + .expect("couldn't open just created basis"); + cache.basis_add(basis); + } + } else { + let blist = cache.basis_list(); + if blist.contains(&name) { + match cache.basis_unmount(self, &name) { + Ok(_) => {}, + Err(e) => log::error!("error unmounting basis {}: {:?}", name, e), + } + } else { + log::info!("attempted to unmount {} but it does not exist or is already locked", name); + } + } + } + } + } + /// In testing, we want a way to automatically unlock all known test Bases. This stand-in feature automates that. + #[cfg(all(feature="pddbtest", feature="autobasis"))] + pub(crate) fn pddb_get_all_keys(&self, cache: &Vec::) -> Option> { + // populate the "known" entries + let mut ret = Vec::<([u8; AES_KEYSIZE], String)>::new(); + for entry in cache { + ret.push((entry.key.into(), entry.name.to_string())); + } + + // now iterate through the bases that have been enumerated so far, and populate the missing ones. + for name in self.testnames.iter() { + // if the entry isn't known already, add it + // yah, this is O(n^2) awful. yolo! + let mut exists = false; + for (_key, bname) in ret.iter() { + if bname == name { + exists = true; + break; + } + } + if !exists { + let basis_key = self.basis_derive_key( + name, + name + ); + ret.push((basis_key.pt, name.to_string())); + } + } + log::info!("for FSCB testing, we auto-unlocked {} bases", ret.len()); + Some(ret) + } + #[cfg(all(feature="pddbtest", feature="autobasis"))] + pub(crate) fn dbg_extra(&self) -> Vec { + let mut ret = Vec::::new(); + for name in self.testnames.iter() { + let basis_key = self.basis_derive_key( + name, + name + ); + let mut basis_name = [0 as u8; 64]; + for (&src, dst) in name.as_bytes().iter().zip(basis_name.iter_mut()) { + *dst = src; + } + ret.push(KeyExport { + basis_name, + key: basis_key.data, + pt_key: basis_key.pt, + }); + } + ret + } + + //-------------------------------- MIGRATIONS ----------------------------------------- + // these are always gated behind feature flags, and disabled in builds once obsolete. + /// legacy key derivation for migrations. This can be removed once the migration is de-supported. /// Must be within this structure because it accesses the rootkeys, and we don't want to make that public. /// Need to pass this the old version of the StaticCryptoData, because it's already erased and replaced diff --git a/services/pddb/src/lib.rs b/services/pddb/src/lib.rs index 7d0ddbbc9..fbab48180 100644 --- a/services/pddb/src/lib.rs +++ b/services/pddb/src/lib.rs @@ -653,6 +653,21 @@ impl Pddb { buf.lend(self.conn, Opcode::DangerousDebug.to_u32().unwrap()) .or(Err(Error::new(ErrorKind::Other, "Xous internal error"))).map(|_| ()) } + + #[cfg(feature="pddbtest")] + pub fn basis_testing(&self, config: &[Option; 32]) { + let mut op = 0; + let mut valid = 0; + for (index, &c) in config.iter().enumerate() { + if let Some(opt) = c { + valid |= 1 << index; + op |= (if opt {1} else {0}) << index; + } + } + send_message(self.conn, + Message::new_scalar(Opcode::BasisTesting.to_usize().unwrap(), op, valid, 0, 0) + ).expect("couldn't send basis test message"); + } } impl Drop for Pddb { diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index aa4cfcf9a..c2aad1065 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -1245,7 +1245,13 @@ fn wrapped_main() -> ! { match dbg.request { DebugRequest::Dump => { log::info!("dumping pddb to {}", dbg.dump_name.as_str().unwrap()); + #[cfg(not(feature="autobasis"))] pddb_os.dbg_dump(Some(dbg.dump_name.as_str().unwrap().to_string()), None); + #[cfg(feature="autobasis")] + { + let export_extra = pddb_os.dbg_extra(); + pddb_os.dbg_dump(Some(dbg.dump_name.as_str().unwrap().to_string()), Some(&export_extra)); + } }, DebugRequest::Remount => { log::info!("attempting remount"); @@ -1259,6 +1265,18 @@ fn wrapped_main() -> ! { } } } + #[cfg(feature="pddbtest")] + Opcode::BasisTesting => xous::msg_scalar_unpack!(msg, op, valid, _, _, { + let mut config: [Option; 32] = [None::; 32]; + for i in 0..32 { + if ((1 << i) & valid) != 0 { + config[i] = Some( + ((1 << i) & op) != 0 + ) + } + } + pddb_os.basis_testing(&mut basis_cache, &config); + }), Opcode::Quit => { log::warn!("quitting the PDDB server"); send_message(