gen2 apis now compiling clean

system doesn't work yet because none of the keystore is there, but
at least we don't have conflicting/missing APIs
This commit is contained in:
bunnie 2025-05-05 01:49:39 +08:00
parent 86b079f2f4
commit 34e9a1f1ce
5 changed files with 248 additions and 49 deletions

View file

@ -50,7 +50,8 @@ blowfish = { version = "0.9.1", features = ["bcrypt"] }
# UX (for password entry and notifications)
gam = { path = "../gam", optional = true }
locales = { path = "../../locales", optional = true }
ux-api = { path = "../../libs/ux-api" }
locales = { path = "../../locales" }
modals = { path = "../modals", optional = true }
utralib = { version = "0.1.25", optional = true, default-features = false }
@ -67,8 +68,13 @@ hex = { version = "0.4.3", default-features = false, features = [
], optional = true }
# Gen-2 dependencies
keystore = { path = "../keystore", optional = true } # contains all key handlers
keystore = { path = "../keystore", optional = true } # contains all key handlers
xous-swapper = { path = "../xous-swapper", optional = true } # contains spinor
cram-hal-service = { path = "../cram-hal-service", optional = true }
cramium-emu = { path = "../cramium-emu", optional = true }
cramium-hal = { path = "../../libs/cramium-hal", features = [
"std",
], optional = true }
[features]
gen1 = [
@ -80,7 +86,6 @@ gen1 = [
"llio",
"tts-frontend",
"gam",
"locales",
"modals",
]
gen2 = ["keystore", "keystore-api/gen2"]
@ -90,9 +95,24 @@ hosted = ["utralib/hosted", "sha2/hosted", "gen1"]
renode = ["utralib/renode", "sha2/renode", "gen1"]
# gen 2 targets
board-baosec = ["gen2", "xous-swapper/board-baosec"] # USB form factor token
hosted-baosec = ["gen2"] # emulated hardware on x86 platform
board-baosor = ["gen2", "xous-swapper/board-baosor"] # Precursor form factor
board-baosec = [
"gen2",
"xous-swapper/board-baosec",
"cram-hal-service",
"cramium-hal",
"modals/board-baosec",
] # USB form factor token
hosted-baosec = [
"gen2",
"cramium-emu",
"modals/hosted-baosec",
] # emulated hardware on x86 platform
board-baosor = [
"gen2",
"xous-swapper/board-baosor",
"cram-hal-service",
"cramium-hal",
] # Precursor form factor
# board-dabao is not a valid target as it lacks external SPI flash
# when selected, physical disk addresses are set to 64 bits, otherwise, they are 32 bits.

View file

@ -154,6 +154,7 @@ pub(crate) enum Opcode {
IsEfuseSecured = 22,
/// Suspend/resume callback
#[cfg(feature = "gen1")]
SuspendResume = 23,
/// quit the server
Quit = 24,

View file

@ -15,11 +15,17 @@ use aes::{Aes256, BLOCK_SIZE, Block};
use aes_gcm_siv::aead::{Aead, Payload};
use aes_gcm_siv::{Aes256GcmSiv, Nonce, Tag};
use backend::bcrypt::*;
use keystore_api::rootkeys_api::*;
use keystore_api::*;
#[cfg(all(feature = "gen2", feature = "cramium-emu"))]
use cramium_emu::{SPINOR_BULK_ERASE_SIZE, SPINOR_ERASE_SIZE};
#[cfg(all(feature = "gen2", not(feature = "cramium-emu")))]
use cramium_hal::board::{SPINOR_BULK_ERASE_SIZE, SPINOR_ERASE_SIZE};
#[cfg(feature = "gen1")]
use keystore_api::AesRootkeyType;
use keystore_api::{Checksums, KeywrapError};
use modals::Modals;
use sha2::{Digest, Sha512_256Hw, Sha512_256Sw};
use spinor::SPINOR_BULK_ERASE_SIZE;
#[cfg(feature = "gen1")]
use spinor::{SPINOR_BULK_ERASE_SIZE, SPINOR_ERASE_SIZE};
use subtle::ConstantTimeEq;
use crate::*;
@ -43,7 +49,7 @@ pub(crate) const MBBB_PAGES: usize = 10;
pub(crate) const FSCB_PAGES: usize = 16;
/// size of a physical page
pub const PAGE_SIZE: usize = spinor::SPINOR_ERASE_SIZE as usize;
pub const PAGE_SIZE: usize = SPINOR_ERASE_SIZE as usize;
/// size of a virtual page -- after the AES encryption and journaling overhead is subtracted
pub const VPAGE_SIZE: usize = PAGE_SIZE - size_of::<Nonce>() - size_of::<Tag>() - size_of::<JournalType>();
@ -139,7 +145,10 @@ type EmuSpinor = spinor::Spinor;
pub(crate) struct PddbOs {
spinor: EmuSpinor,
#[cfg(feature = "gen1")]
rootkeys: root_keys::RootKeys,
#[cfg(feature = "gen2")]
rootkeys: keystore::Keystore,
tt: ticktimer_server::Ticktimer,
pddb_mr: EmuMemoryRange,
/// page table base -- location in FLASH, offset from physical bottom of pddb_mr
@ -221,8 +230,14 @@ impl PddbOs {
PageAlignedPa::from(mbbb_phys_base.as_u32() + MBBB_PAGES as u32 * PAGE_SIZE as u32);
log::debug!("fscb_phys_base: {:x?}", fscb_phys_base);
#[cfg(feature = "gen1")]
let llio = llio::Llio::new(&xns);
#[cfg(feature = "gen1")]
let dna = llio.soc_dna().unwrap();
#[cfg(feature = "gen2")]
let keystore = keystore::Keystore::new(&xns);
#[cfg(feature = "gen2")]
let dna = keystore.get_dna();
// performance counter infrastructure, if selected
#[cfg(feature = "perfcounter")]
@ -280,8 +295,11 @@ impl PddbOs {
let ret = {
PddbOs {
spinor: HostedSpinor::new(),
#[cfg(feature = "gen1")]
rootkeys: root_keys::RootKeys::new(&xns, Some(AesRootkeyType::User0))
.expect("FATAL: couldn't access RootKeys!"),
#[cfg(feature = "gen2")]
rootkeys: keystore::Keystore::new_key(&xns, "pddb"),
tt: ticktimer_server::Ticktimer::new().unwrap(),
pddb_mr: EmuStorage::new(),
pt_phys_base: PageAlignedPa::from(0 as u32),
@ -363,7 +381,12 @@ impl PddbOs {
}
pub(crate) fn is_efuse_secured(&self) -> bool {
self.rootkeys.is_efuse_secured().expect("couldn't query efuse security state") == Some(true)
#[cfg(feature = "gen1")]
{
self.rootkeys.is_efuse_secured().expect("couldn't query efuse security state") == Some(true)
}
#[cfg(feature = "gen2")]
true
}
pub(crate) fn nonce_gen(&self) -> Nonce {
@ -384,7 +407,16 @@ impl PddbOs {
/// checks if the root keys are initialized, which is a prerequisite to formatting and mounting
pub(crate) fn rootkeys_initialized(&self) -> bool {
self.rootkeys.is_initialized().expect("couldn't query initialization state of the rootkeys server")
#[cfg(feature = "gen1")]
{
self.rootkeys
.is_initialized()
.expect("couldn't query initialization state of the rootkeys server")
}
// on gen-2 devices, the key is automatically filled in. We don't have to go through a user-mixing
// password step because we don't have the Starbleed vulnerability.
#[cfg(feature = "gen2")]
true
}
/// patches data at an offset starting from the data physical base address, which corresponds
@ -771,7 +803,15 @@ impl PddbOs {
self.cipher_ecb = None;
}
pub(crate) fn clear_password(&self) { self.rootkeys.clear_password(AesRootkeyType::User0); }
pub(crate) fn clear_password(&self) {
#[cfg(feature = "gen1")]
self.rootkeys.clear_password(AesRootkeyType::User0);
#[cfg(feature = "gen2")]
self.rootkeys.clear_password();
}
#[cfg(feature = "gen2")]
pub(crate) fn ensure_password(&self) -> PasswordState { self.rootkeys.ensure_password() }
pub(crate) fn try_login(&mut self) -> PasswordState {
use aes::cipher::KeyInit;
@ -2043,6 +2083,7 @@ impl PddbOs {
/// reference to the Spinor object allocated to the PDDB implementation for this operation.
pub(crate) fn pddb_format(&mut self, fast: bool, progress: Option<&modals::Modals>) -> Result<()> {
use aes::cipher::KeyInit;
#[cfg(feature = "gen1")]
if !self.rootkeys.is_initialized().unwrap() {
return Err(Error::new(
ErrorKind::Unsupported,
@ -2776,13 +2817,30 @@ impl PddbOs {
match modals.alert_builder(t!("pddb.freespace.name", locales::LANG)).field(None, None).build() {
Ok(bname) => {
let name = bname.first().as_str().to_string();
let request =
BasisRequestPassword { db_name: String::from(name.to_string()), plaintext_pw: None };
let mut buf = Buffer::into_buf(request).unwrap();
buf.lend_mut(self.pw_cid, PwManagerOpcode::RequestPassword.to_u32().unwrap()).unwrap();
let retpass = buf.to_original::<BasisRequestPassword, _>().unwrap();
#[cfg(feature = "gen1")]
let retpass = {
let request = BasisRequestPassword {
db_name: String::from(name.to_string()),
plaintext_pw: None,
};
let mut buf = Buffer::into_buf(request).unwrap();
buf.lend_mut(self.pw_cid, PwManagerOpcode::RequestPassword.to_u32().unwrap())
.unwrap();
buf.to_original::<BasisRequestPassword, _>().unwrap().plaintext_pw.unwrap().as_str()
};
#[cfg(feature = "gen2")]
let retpass = match modals
.alert_builder(
format!("{}'{}'", t!("pddb.password_for", locales::LANG), &name).as_str(),
)
.field(None, None)
.build()
{
Ok(text) => &text.content()[0].content,
_ => panic!("failure retrieving password"),
};
// 2. validate the name/password combo
let basis_key = self.basis_derive_key(&name, retpass.plaintext_pw.unwrap().as_str());
let basis_key = self.basis_derive_key(&name, retpass);
// validate the password by finding the root block of the basis. We rely entirely
// upon the AEAD with key commit to ensure the password is correct.
let maybe_entry = if let Some(basis_map) =
@ -2937,7 +2995,10 @@ impl PddbOs {
BasisKeys { pt: okm_pt, data: okm_data }
}
pub(crate) fn reset_dont_ask_init(&self) { self.rootkeys.do_reset_dont_ask_init(); }
pub(crate) fn reset_dont_ask_init(&self) {
#[cfg(feature = "gen1")]
self.rootkeys.do_reset_dont_ask_init();
}
pub(crate) fn checksums(&self, modals: Option<&Modals>) -> Checksums {
let mut checksums = Checksums::default();
@ -2947,10 +3008,10 @@ impl PddbOs {
.ok();
}
for (index, region) in
pddb.chunks(keystore_api::rootkeys_api::CHECKSUM_BLOCKLEN_PAGE as usize * PAGE_SIZE).enumerate()
pddb.chunks(keystore_api::CHECKSUM_BLOCKLEN_PAGE as usize * PAGE_SIZE).enumerate()
{
assert!(
region.len() == keystore_api::rootkeys_api::CHECKSUM_BLOCKLEN_PAGE as usize * PAGE_SIZE,
region.len() == keystore_api::CHECKSUM_BLOCKLEN_PAGE as usize * PAGE_SIZE,
"CHECKSUM_BLOCKLEN_PAGE is not an even divisor of the PDDB size"
);
let mut hasher = Sha512_256Hw::new();

View file

@ -3,11 +3,17 @@ use core::mem::size_of;
use std::convert::TryInto;
use aes_gcm_siv::Nonce;
#[cfg(feature = "cramium-hal")]
use cram_hal_service::trng::Trng;
#[cfg(feature = "hosted-baosec")]
use cramium_emu::trng::Trng;
use rand_core::RngCore;
#[cfg(all(not(feature = "cramium-hal"), not(feature = "hosted-baosec")))]
use trng::Trng;
/// Crate-shared resource for TRNGs.
pub(crate) struct TrngPool {
trng: RefCell<trng::Trng>,
trng: RefCell<Trng>,
/// The PDDB eats a lot of entropy. Keep a local pool of entropy, so we're not wasting a lot of
/// overhead passing messages to the TRNG hardware server.
e_cache: RefCell<Vec<u8>>,
@ -15,7 +21,7 @@ pub(crate) struct TrngPool {
impl TrngPool {
pub fn new() -> Self {
let xns = xous_names::XousNames::new().unwrap();
let mut trng = trng::Trng::new(&xns).unwrap();
let mut trng = Trng::new(&xns).unwrap();
let mut cache: [u8; 8192] = [0; 8192];
trng.fill_bytes(&mut cache);
TrngPool { trng: RefCell::new(trng), e_cache: RefCell::new(cache.to_vec()) }

View file

@ -408,10 +408,15 @@ mod api;
use api::*;
mod backend;
use backend::*;
#[cfg(feature = "gen1")]
mod ux;
use rkyv::with::Identity;
#[cfg(feature = "gen1")]
use ux::*;
#[cfg(feature = "gen1")]
mod menu;
use keystore_api::PasswordState;
#[cfg(feature = "gen1")]
use menu::*;
mod libstd;
@ -460,19 +465,6 @@ pub(crate) struct BasisRequestPassword {
db_name: String,
plaintext_pw: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum PasswordState {
/// Mounted successfully.
Correct,
/// User-initiated aborted. The main purpose for this path is to facilitate
/// developers who want shellchat access but don't want to mount the PDDB.
Incorrect(u64),
/// Abort initiated by system policy due to too many failed attempts
ForcedAbort(u64),
/// Failure because the PDDB hasn't been initialized yet (can't mount because nothing to mount)
Uninit,
}
#[derive(Debug)]
struct TokenRecord {
pub dict: String,
@ -547,15 +539,22 @@ fn wrapped_main() -> ! {
// our very own password modal. Password modals are precious and privately owned, to avoid
// other processes from crafting them.
#[cfg(feature = "gen1")]
let pw_sid = xous::create_server().expect("couldn't create a server for the password UX handler");
#[cfg(feature = "gen1")]
let pw_cid = xous::connect(pw_sid).expect("couldn't connect to the password UX handler");
#[cfg(feature = "gen1")]
let pw_handle = thread::spawn({
// this comment keeps rustfmt from flattening this block
move || password_ux_manager(xous::connect(pddb_sid).unwrap(), pw_sid)
});
// OS-specific PDDB driver
#[cfg(feature = "gen1")]
let mut pddb_os = PddbOs::new(Rc::clone(&entropy), pw_cid);
#[cfg(feature = "gen2")]
// pw_cid is a dummy field in gen2
let mut pddb_os = PddbOs::new(Rc::clone(&entropy), 0);
// storage for the basis cache
let mut basis_cache = BasisCache::new();
// storage for the token lookup: given an ApiToken, return a dict/key/basis set. Basis can be None or
@ -596,6 +595,7 @@ fn wrapped_main() -> ! {
// our menu handler
let my_cid = xous::connect(pddb_sid).unwrap();
#[cfg(feature = "gen1")]
let _ = thread::spawn({
let my_cid = my_cid.clone();
move || {
@ -703,6 +703,7 @@ fn wrapped_main() -> ! {
let mut scratch = [MaybeUninit::<u8>::uninit(); 256];
// register a suspend/resume listener
#[cfg(feature = "gen1")]
let mut susres =
susres::Susres::new(Some(susres::SuspendOrder::Early), &xns, Opcode::SuspendResume as u32, my_cid)
.expect("couldn't create suspend/resume object");
@ -711,6 +712,7 @@ fn wrapped_main() -> ! {
let op: Opcode = FromPrimitive::from_usize(msg.body.id() & 0xffff).unwrap_or(Opcode::InvalidOpcode);
log::debug!("{:x?}", op);
match op {
#[cfg(feature = "gen1")]
Opcode::SuspendResume => xous::msg_scalar_unpack!(msg, token, _, _, _, {
basis_cache.suspend(&mut pddb_os);
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");
@ -753,6 +755,74 @@ fn wrapped_main() -> ! {
// retries.
// If we need more nuance out of this routine, consider creating a custom public enum type to help
// marshall this.
#[cfg(feature = "gen2")]
Opcode::TryMount => {
xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
match pddb_os.ensure_password() {
PasswordState::Correct => {
if try_mount_or_format(
&modals,
&mut pddb_os,
&mut basis_cache,
PasswordState::Correct,
time_resetter,
&mut basis_monitor_notifications,
) {
is_mounted.store(true, Ordering::SeqCst);
for requester in mount_notifications.drain(..) {
xous::return_scalar2(requester, 0, 0).expect("couldn't return scalar");
}
assert!(
mount_notifications.len() == 0,
"apparently I don't understand what drain() does"
);
log::info!("{}PDDB.MOUNTED,{}", xous::BOOKEND_START, xous::BOOKEND_END);
xous::return_scalar2(msg.sender, 0, 0).expect("couldn't return scalar");
} else {
xous::return_scalar2(msg.sender, 1, 0).expect("couldn't return scalar");
}
}
PasswordState::Uninit => {
if try_mount_or_format(
&modals,
&mut pddb_os,
&mut basis_cache,
PasswordState::Uninit,
time_resetter,
&mut basis_monitor_notifications,
) {
for requester in mount_notifications.drain(..) {
xous::return_scalar2(requester, 0, 0).expect("couldn't return scalar");
}
assert!(
mount_notifications.len() == 0,
"apparently I don't understand what drain() does"
);
log::info!("{}PDDB.MOUNTED,{}", xous::BOOKEND_START, xous::BOOKEND_END);
xous::return_scalar2(msg.sender, 0, 0).expect("couldn't return scalar");
is_mounted.store(true, Ordering::SeqCst);
} else {
xous::return_scalar2(msg.sender, 1, 0).expect("couldn't return scalar");
}
}
PasswordState::ForcedAbort(failcount) => {
xous::return_scalar2(
msg.sender,
2,
// failcount is a u64, but on u32-archs, this gets truncated going to
// usize. clip to u32::MAX.
failcount.min(u32::MAX as u64) as usize,
)
.expect("couldn't return scalar");
}
PasswordState::Incorrect(failcount) => {
xous::return_scalar2(msg.sender, 1, failcount.min(u32::MAX as u64) as usize)
.expect("couldn't return scalar")
}
}
})
}
#[cfg(feature = "gen1")]
Opcode::TryMount => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let llio = llio::Llio::new(&xns);
while !llio.is_ec_ready() {
@ -964,12 +1034,26 @@ fn wrapped_main() -> ! {
let mut mgmt = buffer.to_original::<PddbBasisRequest, _>().unwrap();
match mgmt.code {
PddbRequestCode::Create => {
let request =
BasisRequestPassword { db_name: mgmt.name.to_string(), plaintext_pw: None };
let mut buf = Buffer::into_buf(request).unwrap();
buf.lend_mut(pw_cid, PwManagerOpcode::RequestPassword.to_u32().unwrap()).unwrap();
let ret = buf.to_original::<BasisRequestPassword, _>().unwrap();
if let Some(pw) = ret.plaintext_pw {
#[cfg(feature = "gen1")]
let ret = {
let request =
BasisRequestPassword { db_name: mgmt.name.to_string(), plaintext_pw: None };
let mut buf = Buffer::into_buf(request).unwrap();
buf.lend_mut(pw_cid, PwManagerOpcode::RequestPassword.to_u32().unwrap()).unwrap();
buf.to_original::<BasisRequestPassword, _>().unwrap().plaintext_pw
};
#[cfg(feature = "gen2")]
let ret = match modals
.alert_builder(
format!("{}'{}'", t!("pddb.password_for", locales::LANG), mgmt.name).as_str(),
)
.field(None, None)
.build()
{
Ok(text) => Some(text.content()[0].content.clone()),
_ => panic!("failure retrieving password"),
};
if let Some(pw) = ret {
match basis_cache.basis_create(&mut pddb_os, mgmt.name.as_str(), pw.as_str()) {
Ok(_) => {
log::info!(
@ -1005,12 +1089,30 @@ fn wrapped_main() -> ! {
PddbRequestCode::Open => {
let mut finished = false;
while !finished {
let request =
BasisRequestPassword { db_name: mgmt.name.to_string(), plaintext_pw: None };
let mut buf = Buffer::into_buf(request).unwrap();
buf.lend_mut(pw_cid, PwManagerOpcode::RequestPassword.to_u32().unwrap()).unwrap();
let ret = buf.to_original::<BasisRequestPassword, _>().unwrap();
if let Some(pw) = ret.plaintext_pw {
#[cfg(feature = "gen1")]
let ret = {
let request = BasisRequestPassword {
db_name: mgmt.name.to_string(),
plaintext_pw: None,
};
let mut buf = Buffer::into_buf(request).unwrap();
buf.lend_mut(pw_cid, PwManagerOpcode::RequestPassword.to_u32().unwrap())
.unwrap();
buf.to_original::<BasisRequestPassword, _>().unwrap().plaintext_pw
};
#[cfg(feature = "gen2")]
let ret = match modals
.alert_builder(
format!("{}'{}'", t!("pddb.password_for", locales::LANG), &mgmt.name)
.as_str(),
)
.field(None, None)
.build()
{
Ok(text) => Some(text.content()[0].content.clone()),
_ => panic!("failure retrieving password"),
};
if let Some(pw) = ret {
if let Some(basis) = basis_cache.basis_unlock(
&mut pddb_os,
mgmt.name.as_str(),
@ -2342,6 +2444,7 @@ fn wrapped_main() -> ! {
}
Opcode::Quit => {
log::warn!("quitting the PDDB server");
#[cfg(feature = "gen1")]
send_message(
pw_cid,
Message::new_blocking_scalar(PwManagerOpcode::Quit.to_usize().unwrap(), 0, 0, 0, 0),
@ -2361,6 +2464,7 @@ fn wrapped_main() -> ! {
}
// clean up our program
log::trace!("main loop exit, destroying servers");
#[cfg(feature = "gen1")]
pw_handle.join().expect("password ux manager thread did not join as expected");
xns.unregister_server(pddb_sid).unwrap();
xous::destroy_server(pddb_sid).unwrap();
@ -2368,6 +2472,13 @@ fn wrapped_main() -> ! {
xous::terminate_process(0)
}
#[cfg(feature = "gen2")]
fn ensure_password(_modals: &modals::Modals, pddb_os: &mut PddbOs, _pw_cid: xous::CID) -> PasswordState {
// delegate everything to the hw module
pddb_os.ensure_password()
}
#[cfg(feature = "gen1")]
fn ensure_password(modals: &modals::Modals, pddb_os: &mut PddbOs, _pw_cid: xous::CID) -> PasswordState {
log::info!("Requesting login password");
loop {