mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-15 08:30:02 +00:00
basic mounting of the PDDB & readout of system basis
This commit is contained in:
parent
d7cc518552
commit
49d00c783e
7 changed files with 276 additions and 24 deletions
|
|
@ -8,7 +8,7 @@ pub(crate) const PDDB_MAX_KEY_NAME_LEN: usize = 128;
|
|||
#[allow(dead_code)]
|
||||
pub(crate) const PDDB_MAGIC: [u8; 4] = [0x50, 0x44, 0x44, 0x42];
|
||||
#[allow(dead_code)]
|
||||
pub(crate) const PDDB_VERSION: u16 = 0x00_00;
|
||||
pub(crate) const PDDB_VERSION: u32 = 0x00_00_00_01;
|
||||
/// PDDB_A_LEN may be shorter than xous::PDDB_LEN, to speed up testing
|
||||
#[allow(dead_code)]
|
||||
pub(crate) const PDDB_A_LEN: usize = 4 * 1024 * 1024;
|
||||
|
|
@ -23,9 +23,11 @@ pub(crate) const PDDB_A_LEN: usize = 4 * 1024 * 1024;
|
|||
/// to grow a record, you'd have to unlock all your Basis and do a brute force scan, otherwise
|
||||
/// you risk overwriting hidden data by mistaking it as free space. The initial setting is
|
||||
/// 0.5: with this setting, we won't be more than a factor of 2 off from the ideal setting!
|
||||
#[allow(dead_code)]
|
||||
pub(crate) const FSCB_FILL_COEFFICIENT: f32 = 0.5;
|
||||
|
||||
pub const PDDB_DEFAULT_SYSTEM_BASIS: &'static str = ".System";
|
||||
// this isn't an "official" basis, but it is used for the AAD for encrypting the FastSpace structure
|
||||
pub(crate) const PDDB_FAST_SPACE_SYSTEM_BASIS: &'static str = ".FastSpace";
|
||||
|
||||
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
|
||||
|
|
|
|||
|
|
@ -13,9 +13,15 @@ use aes_gcm_siv::aead::{Aead, Payload};
|
|||
use rkyv::Aligned;
|
||||
use rkyv::ser::serializers::BufferSerializer;
|
||||
use std::iter::IntoIterator;
|
||||
use std::collections::HashMap;
|
||||
|
||||
|
||||
pub type BasisRootName = [u8; PDDB_MAX_BASIS_NAME_LEN];
|
||||
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
|
||||
pub struct BasisRootName(pub [u8; PDDB_MAX_BASIS_NAME_LEN]);
|
||||
impl Default for BasisRootName {
|
||||
fn default() -> BasisRootName {
|
||||
BasisRootName([0; PDDB_MAX_BASIS_NAME_LEN])
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes in the constituents of the Basis area, and encrypts them into
|
||||
/// PAGE_SIZE blocks. Can be called as an iterator, or as a single-shot
|
||||
|
|
@ -41,7 +47,7 @@ pub(crate) struct BasisEncryptor<'a> {
|
|||
impl<'a> BasisEncryptor<'a> {
|
||||
pub(crate) fn new(root: &'a BasisRoot, dicts: &'a [DictPointer], dna: u64, cipher: Aes256GcmSiv, rev: JournalType, entropy: Rc<RefCell<TrngPool>>) -> Self {
|
||||
let mut aad = Vec::<u8>::new();
|
||||
aad.extend_from_slice(&root.name);
|
||||
aad.extend_from_slice(&root.name.0);
|
||||
aad.extend_from_slice(&PDDB_VERSION.to_le_bytes());
|
||||
aad.extend_from_slice(&dna.to_le_bytes());
|
||||
|
||||
|
|
@ -176,7 +182,7 @@ impl<'a> Iterator for BasisEncryptorIter<'a> {
|
|||
/// wrapped, we're using a NonZeroU64 format. The compiler knows how to turn that into a 64-bit C-friendly
|
||||
/// structure and serialize/deserialize that into the correct Rust structure. See
|
||||
/// https://doc.rust-lang.org/nomicon/other-reprs.html for a citation on that.
|
||||
#[derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, PartialEq, Debug)]
|
||||
#[derive(PartialEq, Debug, Default)]
|
||||
#[repr(C, align(8))]
|
||||
pub(crate) struct BasisRoot {
|
||||
// everything below here is encrypted using AES-GCM-SIV
|
||||
|
|
@ -226,8 +232,9 @@ impl BasisRoot {
|
|||
)
|
||||
}
|
||||
}*/
|
||||
/*
|
||||
use rkyv::ser::Serializer;
|
||||
impl BasisRoot { // note: example wraps u8 in "Aligned"...
|
||||
impl BasisRoot {
|
||||
pub(crate) fn ser(&self) -> (u32, Aligned<[u8; size_of::<rkyv::ser::serializers::BufferSerializer<BasisRoot>>()]>) {
|
||||
let mut ser = BufferSerializer::new(Aligned([0u8; size_of::<rkyv::ser::serializers::BufferSerializer<BasisRoot>>()]));
|
||||
let pos = match ser.serialize_value(self) {
|
||||
|
|
@ -236,7 +243,7 @@ impl BasisRoot { // note: example wraps u8 in "Aligned"...
|
|||
};
|
||||
(pos as u32, ser.into_inner())
|
||||
}
|
||||
}
|
||||
}*/
|
||||
impl Deref for BasisRoot {
|
||||
type Target = [u8];
|
||||
fn deref(&self) -> &[u8] {
|
||||
|
|
@ -256,6 +263,36 @@ impl DerefMut for BasisRoot {
|
|||
}
|
||||
}
|
||||
|
||||
/// This is the RAM cached copy of a basis as maintained in the PDDB.
|
||||
pub(crate) struct BasisCache {
|
||||
/// set if synched to what's on disk
|
||||
pub clean: bool,
|
||||
/// last sync time, in systicks, if any
|
||||
pub last_sync: Option<u64>,
|
||||
/// the basis root record, as read in from disk
|
||||
pub root: BasisRoot,
|
||||
/// dictionary array
|
||||
pub dicts: HashMap::<String, DictCache>,
|
||||
/// the cipher for the basis
|
||||
pub cipher: Aes256GcmSiv,
|
||||
/// the AAD associated with this Basis
|
||||
pub aad: Vec::<u8>,
|
||||
}
|
||||
|
||||
pub(crate) struct DictCache {
|
||||
pointer: DictPointer,
|
||||
keys: HashMap::<String, HashKey>,
|
||||
}
|
||||
|
||||
/// used to identify cached/chunked data from a key
|
||||
#[derive(Hash)]
|
||||
pub(crate) struct KeyChunkId {
|
||||
basis: String,
|
||||
dict: String,
|
||||
key: HashKey,
|
||||
offset: u64,
|
||||
cache_page: [u8; VPAGE_SIZE],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct DictPointer {
|
||||
|
|
@ -286,6 +323,7 @@ pub(crate) struct Dictionary {
|
|||
|
||||
/// This defines a key's name, along with a pointer to its location in memory.
|
||||
/// HashKeys are packed at the end of a Dictionary.
|
||||
#[derive(Hash)]
|
||||
pub(crate) struct HashKey {
|
||||
name: [u8; PDDB_MAX_KEY_NAME_LEN],
|
||||
journal_rev: u32,
|
||||
|
|
|
|||
|
|
@ -60,6 +60,7 @@ type EmuSpinor = spinor::Spinor;
|
|||
pub(crate) struct PddbOs {
|
||||
spinor: EmuSpinor,
|
||||
rootkeys: root_keys::RootKeys,
|
||||
tt: ticktimer_server::Ticktimer,
|
||||
pddb_mr: EmuMemoryRange,
|
||||
/// page table base -- location in FLASH, offset from physical bottom of pddb_mr
|
||||
pt_phys_base: PageAlignedPa,
|
||||
|
|
@ -73,7 +74,7 @@ pub(crate) struct PddbOs {
|
|||
data_phys_base: PageAlignedPa,
|
||||
system_basis_key: Option<[u8; AES_KEYSIZE]>,
|
||||
/// virtual to physical page map. It's the reverse mapping of the physical page table on disk.
|
||||
v2p_map: HashMap<BasisRootName, HashMap<VirtAddr, PhysPage>>,
|
||||
v2p_map: HashMap<String, HashMap<VirtAddr, PhysPage>>,
|
||||
/// fast space cache
|
||||
fspace_cache: HashSet<PhysPage>,
|
||||
/// memoize the location of the fscb log pages
|
||||
|
|
@ -88,6 +89,12 @@ pub(crate) struct PddbOs {
|
|||
/// We don't blend the System basis into this one because we need to refer to the System basis specifically
|
||||
/// for decrypting management structures like the FSCB.
|
||||
basis_keys: Vec::<[u8; AES_KEYSIZE]>,
|
||||
/// An in-memory "hot cache" of Basis root data that have been unlocked. Right now, we keep all data resident,
|
||||
/// but, keep in mind: even if the data isn't found here, it could have been evicted from the cache due to
|
||||
/// memory pressure. In which case, a direct search through the disk may be necessary to find your data.
|
||||
/// Basis root data should be fairly compact, however -- it's just the directory data to find the keys and
|
||||
/// dictionaries, so unless you create 1k's of dictionaries and keys, it'll probably all fit in RAM.
|
||||
basis_cache: HashMap<String, BasisCache>,
|
||||
}
|
||||
|
||||
impl PddbOs {
|
||||
|
|
@ -113,6 +120,7 @@ impl PddbOs {
|
|||
let ret = PddbOs {
|
||||
spinor: spinor::Spinor::new(&xns).unwrap(),
|
||||
rootkeys: root_keys::RootKeys::new(&xns, Some(AesRootkeyType::User0)).expect("FATAL: couldn't access RootKeys!"),
|
||||
tt: ticktimer_server::Ticktimer::new().unwrap(),
|
||||
pddb_mr: pddb,
|
||||
pt_phys_base: PageAlignedPa::from(0 as u32),
|
||||
key_phys_base,
|
||||
|
|
@ -120,13 +128,14 @@ impl PddbOs {
|
|||
fscb_phys_base,
|
||||
data_phys_base: PageAlignedPa::from(fscb_phys_base.as_u32() + FSCB_PAGES as u32 * PAGE_SIZE as u32),
|
||||
system_basis_key: None,
|
||||
v2p_map: HashMap::<BasisRootName, HashMap<VirtAddr, PhysPage>>::new(),
|
||||
v2p_map: HashMap::<String, HashMap<VirtAddr, PhysPage>>::new(),
|
||||
fspace_cache: HashSet::<PhysPage>::new(),
|
||||
fspace_log_addrs: Vec::<PageAlignedPa>::new(),
|
||||
fspace_log_next_addr: None,
|
||||
dna: llio.soc_dna().unwrap(),
|
||||
entropy: trngpool,
|
||||
basis_keys: Vec::new(),
|
||||
basis_cache: HashMap::<String, BasisCache>::new(),
|
||||
};
|
||||
// emulated
|
||||
#[cfg(not(any(target_os = "none", target_os = "xous")))]
|
||||
|
|
@ -134,6 +143,7 @@ impl PddbOs {
|
|||
PddbOs {
|
||||
spinor: HostedSpinor::new(),
|
||||
rootkeys: root_keys::RootKeys::new(&xns, Some(AesRootkeyType::User0)).expect("FATAL: couldn't access RootKeys!"),
|
||||
tt: ticktimer_server::Ticktimer::new().unwrap(),
|
||||
pddb_mr: EmuStorage::new(),
|
||||
pt_phys_base: PageAlignedPa::from(0 as u32),
|
||||
key_phys_base,
|
||||
|
|
@ -141,13 +151,14 @@ impl PddbOs {
|
|||
fscb_phys_base,
|
||||
data_phys_base: PageAlignedPa::from(fscb_phys_base.as_u32() + FSCB_PAGES as u32 * PAGE_SIZE as u32),
|
||||
system_basis_key: None,
|
||||
v2p_map: HashMap::<BasisRootName, HashMap<VirtAddr, PhysPage>>::new(),
|
||||
v2p_map: HashMap::<String, HashMap<VirtAddr, PhysPage>>::new(),
|
||||
fspace_cache: HashSet::<PhysPage>::new(),
|
||||
fspace_log_addrs: Vec::<PageAlignedPa>::new(),
|
||||
fspace_log_next_addr: None,
|
||||
dna: llio.soc_dna().unwrap(),
|
||||
entropy: trngpool,
|
||||
basis_keys: Vec::new(),
|
||||
basis_cache: HashMap::<String, BasisCache>::new(),
|
||||
}
|
||||
};
|
||||
ret
|
||||
|
|
@ -282,7 +293,7 @@ impl PddbOs {
|
|||
/// This would want to be optimized or cached for a much larger filesystem.
|
||||
/// Returns the physical address of the erased slot as an offset from the pt_phys_base()
|
||||
fn pt_find_erased_slot(&self) -> Option<PhysAddr> {
|
||||
let pt = &self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::<PageTableInFlash>()];
|
||||
let pt: &[u8] = &self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::<PageTableInFlash>()];
|
||||
let blank = [0xffu8; aes::BLOCK_SIZE];
|
||||
for (index, page) in pt.chunks(PAGE_SIZE).enumerate() {
|
||||
if page[..aes::BLOCK_SIZE] == blank {
|
||||
|
|
@ -291,6 +302,57 @@ impl PddbOs {
|
|||
}
|
||||
None
|
||||
}
|
||||
fn pt_as_slice(&self) -> &[u8] {
|
||||
&self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::<PageTableInFlash>()]
|
||||
}
|
||||
|
||||
/// scans the page tables and returns all entries for a given basis
|
||||
/// basis_name is needed to decrypt pages in case of a journal conflict
|
||||
fn pt_scan_key(&self, key: &[u8; AES_KEYSIZE], basis_name: &str) -> Option<HashMap::<VirtAddr, PhysPage>> {
|
||||
let cipher = Aes256::new(&GenericArray::from_slice(key));
|
||||
let pt = self.pt_as_slice();
|
||||
let mut map = HashMap::<VirtAddr, PhysPage>::new();
|
||||
for (index, candidate) in pt.chunks(aes::BLOCK_SIZE).enumerate() {
|
||||
// encryption is in-place, but the candidates are read-only, so we have to copy them to a new location
|
||||
let mut block = Block::clone_from_slice(candidate);
|
||||
cipher.decrypt_block(&mut block);
|
||||
if let Some(pte) = Pte::try_from_slice(block.as_slice()) {
|
||||
let mut pp = PhysPage(0);
|
||||
pp.set_page_number(index as PhysAddr);
|
||||
pp.set_clean(true);
|
||||
// handle conflicting journal versions here
|
||||
if let Some(prev_page) = map.get(&pte.vaddr()) {
|
||||
let cipher = Aes256GcmSiv::new(Key::from_slice(key));
|
||||
let aad = self.data_aad(PDDB_DEFAULT_SYSTEM_BASIS);
|
||||
let prev_data = self.data_decrypt_page(&cipher, &aad, prev_page);
|
||||
let new_data = self.data_decrypt_page(&cipher, &aad, &pp);
|
||||
if let Some(new_d) = new_data {
|
||||
if let Some(prev_d) = prev_data {
|
||||
let prev_j = JournalType::from_le_bytes(prev_d[..size_of::<JournalType>()].try_into().unwrap());
|
||||
let new_j = JournalType::from_le_bytes(new_d[..size_of::<JournalType>()].try_into().unwrap());
|
||||
if new_j > prev_j {
|
||||
map.insert(pte.vaddr(), pp);
|
||||
} else if new_j == prev_j {
|
||||
log::error!("Found duplicate blocks with same journal age, picking arbitrary block and moving on...");
|
||||
}
|
||||
} else {
|
||||
// prev data was bogus anyways, replace with the new entry
|
||||
map.insert(pte.vaddr(), pp);
|
||||
}
|
||||
} else {
|
||||
// new data is bogus, ignore it
|
||||
}
|
||||
} else {
|
||||
map.insert(pte.vaddr(), pp);
|
||||
}
|
||||
}
|
||||
}
|
||||
if map.len() > 0 {
|
||||
Some(map)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// maps a StaticCryptoData structure into the key area of the PDDB.
|
||||
fn static_crypto_data_get(&self) -> &StaticCryptoData {
|
||||
|
|
@ -333,7 +395,7 @@ impl PddbOs {
|
|||
// Invariant: MBBB pages should be blank, unless a page is stashed there. So, just check the first
|
||||
// AES key size region for "blankness"
|
||||
let blank = [0xffu8; aes::BLOCK_SIZE];
|
||||
for (index, page) in self.mbbb_as_slice().chunks(PAGE_SIZE).enumerate() {
|
||||
for page in self.mbbb_as_slice().chunks(PAGE_SIZE) {
|
||||
if page[..aes::BLOCK_SIZE] == blank {
|
||||
continue;
|
||||
} else {
|
||||
|
|
@ -664,6 +726,7 @@ impl PddbOs {
|
|||
}
|
||||
}
|
||||
/// returns a count of the number of pages in the fspace cache
|
||||
#[allow(dead_code)]
|
||||
pub fn fast_space_len(&self) -> usize {
|
||||
self.fspace_cache.len()
|
||||
}
|
||||
|
|
@ -813,8 +876,103 @@ impl PddbOs {
|
|||
unimplemented!();
|
||||
}
|
||||
|
||||
pub(crate) fn pddb_mount(&mut self) {
|
||||
pub(crate) fn data_aad(&self, name: &str) -> Vec::<u8> {
|
||||
let mut full_name = [0u8; PDDB_MAX_BASIS_NAME_LEN];
|
||||
for (&src, dst) in name.as_bytes().iter().zip(full_name.iter_mut()) {
|
||||
*dst = src;
|
||||
}
|
||||
let mut aad = Vec::<u8>::new();
|
||||
aad.extend_from_slice(&full_name);
|
||||
aad.extend_from_slice(&PDDB_VERSION.to_le_bytes());
|
||||
aad.extend_from_slice(&self.dna.to_le_bytes());
|
||||
aad
|
||||
}
|
||||
/// returns a decrypted page that still includes the journal number at the very beginning
|
||||
/// We don't clip it off because it would require re-allocating a vector, and it's cheaper (although less elegant) to later
|
||||
/// just index past it.
|
||||
pub(crate) fn data_decrypt_page(&self, cipher: &Aes256GcmSiv, aad: &[u8], page: &PhysPage) -> Option<Vec::<u8>> {
|
||||
let ct_slice = &self.pddb_mr.as_slice()[
|
||||
self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE ..
|
||||
self.data_phys_base.as_usize() + (page.page_number() as usize + 1) * PAGE_SIZE];
|
||||
let nonce = &ct_slice[..size_of::<Nonce>()];
|
||||
let ct = &ct_slice[size_of::<Nonce>()..];
|
||||
match cipher.decrypt(
|
||||
Nonce::from_slice(nonce),
|
||||
Payload {
|
||||
aad,
|
||||
msg: ct,
|
||||
}
|
||||
) {
|
||||
Ok(data) => {
|
||||
assert!(data.len() == VPAGE_SIZE + size_of::<JournalType>(), "authentication successful, but wrong amount of data was recovered");
|
||||
Some(data)
|
||||
},
|
||||
Err(e) => {
|
||||
log::info!("Error decrypting page: {:?}", e);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Meant to be called on boot. This will read the FastSpace record, and then attempt to load
|
||||
/// in the system basis.
|
||||
pub(crate) fn pddb_mount(&mut self) -> bool {
|
||||
self.fast_space_read();
|
||||
self.syskey_ensure();
|
||||
// this call will nuke whatever hashmap existed before
|
||||
self.v2p_map = HashMap::<String, HashMap<VirtAddr, PhysPage>>::new();
|
||||
if let Some(syskey) = self.system_basis_key {
|
||||
if let Some(sysbasis_map) = self.pt_scan_key(&syskey, PDDB_DEFAULT_SYSTEM_BASIS) {
|
||||
let cipher = Aes256GcmSiv::new(Key::from_slice(&syskey));
|
||||
let aad = self.data_aad(PDDB_DEFAULT_SYSTEM_BASIS);
|
||||
// get the first page, where the basis root is guaranteed to be
|
||||
if let Some(root_page) = sysbasis_map.get(&VirtAddr::new(VPAGE_SIZE as u64).unwrap()) {
|
||||
let vpage = match self.data_decrypt_page(&cipher, &aad, root_page) {
|
||||
Some(data) => data,
|
||||
None => {log::error!("System basis decryption did not authenticate. Unrecoverable error."); return false;},
|
||||
};
|
||||
// if the below assertion fails, you will need to re-code this to decrypt more than one VPAGE and stripe into a basis root struct
|
||||
assert!(size_of::<BasisRoot>() <= VPAGE_SIZE, "BasisRoot has grown past a single VPAGE, this routine needs to be re-coded to accommodate the extra bulk");
|
||||
let mut basis_root = BasisRoot::default();
|
||||
for (&src, dst) in vpage[size_of::<JournalType>()..].iter().zip(basis_root.deref_mut().iter_mut()) {
|
||||
*dst = src;
|
||||
}
|
||||
if basis_root.magic != PDDB_MAGIC {
|
||||
log::error!("Basis root did not deserialize correctly, unrecoverable error.");
|
||||
return false;
|
||||
}
|
||||
if basis_root.version != PDDB_VERSION {
|
||||
log::error!("PDDB version mismatch in system basis root. Unrecoverable error.");
|
||||
return false;
|
||||
}
|
||||
let null_index = basis_root.name.0.iter().position(|&c| c == 0).expect("couldn't find null terminator on name");
|
||||
let basis_name = String::from_utf8(basis_root.name.0[..null_index].to_vec()).expect("Basis name has invalid characters");
|
||||
if basis_name != String::from(PDDB_DEFAULT_SYSTEM_BASIS) {
|
||||
log::error!("PDDB system basis name is incorrect: {}; aborting mount operation.", basis_name);
|
||||
return false;
|
||||
}
|
||||
// at this point, we would fill out the cache more, but let's just put in the minimal info so we can do some testing
|
||||
let bcache = BasisCache {
|
||||
clean: true,
|
||||
last_sync: Some(self.tt.elapsed_ms()),
|
||||
root: basis_root,
|
||||
dicts: HashMap::<String, DictCache>::new(),
|
||||
cipher,
|
||||
aad,
|
||||
};
|
||||
log::info!("System BasisRoot record found, saving in cache");
|
||||
self.basis_cache.insert(basis_name.clone(), bcache);
|
||||
// save the v2p reverse mapping too.
|
||||
self.v2p_map.insert(basis_name, sysbasis_map);
|
||||
return true;
|
||||
} else {
|
||||
// i guess technically we could try a brute-force search for the page, but meh.
|
||||
log::error!("System basis did not contain a root page -- unrecoverable error.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// this function is dangerous in that calling it will completely erase all of the previous data
|
||||
|
|
@ -925,7 +1083,7 @@ impl PddbOs {
|
|||
let basis_root = BasisRoot {
|
||||
magic: api::PDDB_MAGIC,
|
||||
version: api::PDDB_VERSION,
|
||||
name,
|
||||
name: BasisRootName(name),
|
||||
age: 0,
|
||||
prealloc_open_end: PageAlignedVa::from(INITIAL_BASIS_ALLOC * VPAGE_SIZE),
|
||||
num_dictionaries: 0,
|
||||
|
|
@ -952,7 +1110,7 @@ impl PddbOs {
|
|||
//for (&k, &v) in basis_v2p_map.iter() {
|
||||
// log::info!("basis_v2p_map va: {:x?} pp: {:x?}", k, v);
|
||||
//}
|
||||
self.v2p_map.insert(basis_root.name, basis_v2p_map);
|
||||
self.v2p_map.insert(String::from(PDDB_DEFAULT_SYSTEM_BASIS), basis_v2p_map);
|
||||
}
|
||||
|
||||
// step 8. write the System basis to Flash, at the physical locations noted above
|
||||
|
|
@ -967,7 +1125,7 @@ impl PddbOs {
|
|||
0,
|
||||
Rc::clone(&self.entropy),
|
||||
);
|
||||
if let Some(basis_v2p_map) = self.v2p_map.get(&basis_root.name) {
|
||||
if let Some(basis_v2p_map) = self.v2p_map.get(&String::from(PDDB_DEFAULT_SYSTEM_BASIS)) {
|
||||
for (&k, &v) in basis_v2p_map.iter() {
|
||||
log::info!("basis_v2p_map retrieved va: {:x?} pp: {:x?}", k, v);
|
||||
}
|
||||
|
|
@ -996,7 +1154,7 @@ impl PddbOs {
|
|||
if let Some(system_key) = self.system_basis_key {
|
||||
log::info!("encryption key: {:x?}", system_key);
|
||||
let cipher = Aes256::new(GenericArray::from_slice(&system_key));
|
||||
if let Some(basis_v2p_map) = self.v2p_map.get(&basis_root.name) {
|
||||
if let Some(basis_v2p_map) = self.v2p_map.get(&String::from(PDDB_DEFAULT_SYSTEM_BASIS)) {
|
||||
for (&virt, &phys) in basis_v2p_map.into_iter() {
|
||||
let mut pte = Pte::new(virt, PtFlags::CLEAN, Rc::clone(&self.entropy));
|
||||
let mut block = Block::from_mut_slice(pte.deref_mut());
|
||||
|
|
|
|||
|
|
@ -16,7 +16,10 @@ bitflags! {
|
|||
/// set for records that are synced to the copy in Flash. Every valid record
|
||||
/// from Flash should have this set; it should only be cleared for blocks in Cache.
|
||||
const CLEAN = 0b0000_0001;
|
||||
|
||||
/// set for records that are confirmed to be valid through a subsequent decryption op.
|
||||
/// This flag exists because there is a chance that the 32-bit checksum used to protect
|
||||
/// a page table entry experiences a collision.
|
||||
const CHECKED = 0b0000_0010;
|
||||
}
|
||||
}
|
||||
impl Default for PtFlags {
|
||||
|
|
@ -67,6 +70,33 @@ impl Pte {
|
|||
|
||||
pte
|
||||
}
|
||||
pub fn vaddr(&self) -> VirtAddr {
|
||||
let mut full_addr = [0u8; 8];
|
||||
// LSB encoded, so this loop deposits the partial pddb_addr in the LSBs, and the MSBs are correctly 0 from above initializer
|
||||
for (&src, dst) in self.pddb_addr.iter().zip(full_addr.iter_mut()) {
|
||||
*dst = src;
|
||||
}
|
||||
VirtAddr::new(u64::from_le_bytes(full_addr)).unwrap()
|
||||
}
|
||||
pub fn flags(&self) -> PtFlags {
|
||||
self.flags
|
||||
}
|
||||
pub fn try_from_slice(slice: &[u8]) -> Option<Self> {
|
||||
if slice.len() == size_of::<Pte>() {
|
||||
let mut maybe_pt = Pte::default();
|
||||
for (&src, dst) in slice.iter().zip(maybe_pt.deref_mut().iter_mut()) {
|
||||
*dst = src;
|
||||
}
|
||||
let nonce_u32 = u32::from_le_bytes(maybe_pt.nonce);
|
||||
if u32::from_le_bytes(maybe_pt.checksum) == murmur3_32(&slice[..12], nonce_u32) {
|
||||
Some(maybe_pt)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Deref for Pte {
|
||||
type Target = [u8];
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ pub type VirtAddr = NonZeroU64;
|
|||
#[derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, PartialEq, Eq, Copy, Clone, Debug)]
|
||||
pub(crate) struct PageAlignedVa(VirtAddr);
|
||||
impl PageAlignedVa {
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn as_u32(&self) -> u32 {
|
||||
if self.0 <= VirtAddr::new(u32::MAX as u64).unwrap() {
|
||||
self.0.get() as u32
|
||||
|
|
@ -79,14 +80,21 @@ impl PageAlignedVa {
|
|||
panic!("PageAlignedVa would not fit into a u32");
|
||||
}
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn as_u64(&self) -> u64 {self.0.get()}
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn as_usize(&self) -> usize {self.0.get() as usize}
|
||||
/// This will turn a PageAlignedVa into a page number
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn as_vpage_num(&self) -> usize {
|
||||
// we're page-aligned, so we don't have to deal with remainders. This should divide cleanly.
|
||||
self.0.get() as usize / VPAGE_SIZE
|
||||
}
|
||||
}
|
||||
impl Default for PageAlignedVa {
|
||||
// 0 is not a valid address; the offset at VPAGE_SIZE is the location of BasisRoot, and that is the default value.
|
||||
fn default() -> Self {PageAlignedVa(VirtAddr::new(VPAGE_SIZE as u64).unwrap())}
|
||||
}
|
||||
impl From<u64> for PageAlignedVa {
|
||||
fn from(arg: u64) -> Self {
|
||||
if arg % VPAGE_SIZE as u64 == 0 {
|
||||
|
|
@ -131,8 +139,11 @@ impl Add for PageAlignedVa {
|
|||
#[derive(Copy, Clone)]
|
||||
pub(crate) struct PageAlignedPa(PhysAddr);
|
||||
impl PageAlignedPa {
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn as_u32(&self) -> u32 {self.0 as u32}
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn as_u64(&self) -> u64 {self.0 as u64}
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn as_usize(&self) -> usize {self.0 as usize}
|
||||
pub(crate) fn as_phys_addr(&self) -> PhysAddr {self.0}
|
||||
}
|
||||
|
|
@ -179,6 +190,7 @@ mod tests {
|
|||
/// the generated getter and setter, it woudln't matter.
|
||||
/// However, in our application, we fully expect a true to be a 1. This test exists to ensure this seemingly
|
||||
/// obvious but not explicitly stated fact always remains true.
|
||||
#[test]
|
||||
fn test_bitfield_bool() {
|
||||
bitfield! {
|
||||
pub struct Test(u8);
|
||||
|
|
@ -190,6 +202,7 @@ mod tests {
|
|||
assert!(t.0 == 0x2, "polarity of boolean bit is not as expected");
|
||||
assert!(t.test() == true, "bool getter did not work as expected");
|
||||
}
|
||||
#[test]
|
||||
fn test_journal_range() {
|
||||
let pp = PhysPage(u32::MAX);
|
||||
assert!(pp.journal() == PHYS_PAGE_JOURNAL_MAX, "PHYS_PAGE_JOURNAL_MAX is incorrect");
|
||||
|
|
|
|||
|
|
@ -374,6 +374,13 @@ fn xmain() -> ! {
|
|||
#[cfg(not(any(target_os = "none", target_os = "xous")))]
|
||||
pddb_os.dbg_dump();
|
||||
|
||||
log::info!("Attempting to mount the PDDB");
|
||||
if pddb_os.pddb_mount() {
|
||||
log::info!("PDDB mount operation finished successfully");
|
||||
} else {
|
||||
log::info!("PDDB did not mount; did you remember to format the PDDB region?");
|
||||
}
|
||||
|
||||
// register a suspend/resume listener
|
||||
let sr_cid = xous::connect(pddb_sid).expect("couldn't create suspend callback connection");
|
||||
let susres = susres::Susres::new(&xns, api::Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object");
|
||||
|
|
|
|||
|
|
@ -233,10 +233,10 @@ class Basis:
|
|||
desc += ' DictPtr: {:x}\n'.format(self.dict_ptr)
|
||||
return desc
|
||||
|
||||
def basis_aad(name, version=0, dna=0):
|
||||
def basis_aad(name, version=1, dna=0):
|
||||
name_bytes = bytearray(name, 'utf-8')
|
||||
name_bytes += bytearray(([0] * (Basis.MAX_NAME_LEN - len(name))))
|
||||
name_bytes += version.to_bytes(2, 'little')
|
||||
name_bytes += version.to_bytes(4, 'little')
|
||||
name_bytes += dna.to_bytes(8, 'little')
|
||||
|
||||
return name_bytes
|
||||
|
|
@ -258,6 +258,10 @@ class Pte:
|
|||
def flags(self):
|
||||
if self.bytes[6] == 1:
|
||||
return 'CLN'
|
||||
elif self.bytes[6] == 2:
|
||||
return 'CHK'
|
||||
elif self.bytes[6] == 3:
|
||||
return 'COK'
|
||||
else:
|
||||
return 'INV'
|
||||
def nonce(self):
|
||||
|
|
@ -388,8 +392,8 @@ class Fscb:
|
|||
self.free_space[pp.page_number() * 4096] = pp
|
||||
|
||||
# this is the "AAD" used to encrypt the FastSpace
|
||||
def aad(version=0, dna=0):
|
||||
return bytearray([46, 70, 97, 115, 116, 83, 112, 97, 99, 101]) + version.to_bytes(2, 'little') + dna.to_bytes(8, 'little')
|
||||
def aad(version=1, dna=0):
|
||||
return bytearray([46, 70, 97, 115, 116, 83, 112, 97, 99, 101]) + version.to_bytes(4, 'little') + dna.to_bytes(8, 'little')
|
||||
|
||||
class SpaceUpdate:
|
||||
SU_LEN = 16
|
||||
|
|
@ -437,8 +441,8 @@ def decode_fscb(img, keys, FSCB_LEN_PAGES=2):
|
|||
nonce = fscb_enc[:12]
|
||||
print("key: {}, nonce: {}".format(key.hex(), nonce.hex()))
|
||||
cipher = AES_GCM_SIV(key, nonce)
|
||||
#print("aad: {}".format(Fscb.aad().hex()))
|
||||
#print("mac: {}".format(fscb_enc[-16:].hex()))
|
||||
print("aad: {}".format(Fscb.aad().hex()))
|
||||
print("mac: {}".format(fscb_enc[-16:].hex()))
|
||||
#print("data: {}".format(fscb_enc[12:-16].hex()))
|
||||
fscb_dec = cipher.decrypt(fscb_enc[12:], Fscb.aad())
|
||||
fscb = Fscb(fscb_dec)
|
||||
|
|
|
|||
Loading…
Reference in a new issue