From fe687537794c31282df40e25170e122a6511a169 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 12 Nov 2025 15:25:30 +0800 Subject: [PATCH] layer in new items that can be activated now that more APIs are implemented, more of the "real meat" of the vault app can be turned on --- apps-baosec/vault2/Cargo.toml | 28 +- apps-baosec/vault2/src/actions.rs | 426 +++------------------ apps-baosec/vault2/src/ctap/hid/mod.rs | 2 +- apps-baosec/vault2/src/env/xous/mod.rs | 6 +- apps-baosec/vault2/src/env/xous/storage.rs | 4 +- apps-baosec/vault2/src/lib.rs | 117 ++++++ apps-baosec/vault2/src/main.rs | 118 ++++-- apps-baosec/vault2/src/storage.rs | 8 +- apps-baosec/vault2/src/submenu.rs | 31 +- apps-baosec/vault2/src/ux.rs | 109 +++++- apps-baosec/vault2/src/vault_api.rs | 8 - 11 files changed, 392 insertions(+), 465 deletions(-) create mode 100644 apps-baosec/vault2/src/lib.rs diff --git a/apps-baosec/vault2/Cargo.toml b/apps-baosec/vault2/Cargo.toml index 4a9f20a21..01ae7c96a 100644 --- a/apps-baosec/vault2/Cargo.toml +++ b/apps-baosec/vault2/Cargo.toml @@ -27,17 +27,20 @@ ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.65" } userprefs = { path = "../../libs/userprefs" } ux-api = { path = "../../libs/ux-api" } bao1x-api = { path = "../../libs/bao1x-api" } +bao1x-hal = { path = "../../libs/bao1x-hal" } bao1x-hal-service = { path = "../../services/bao1x-hal-service", optional = true } bao1x-emu = { path = "../../services/bao1x-emu", optional = true } blitstr2 = { path = "../../libs/blitstr2" } usb-bao1x = { path = "../../services/usb-bao1x" } +xous-usb-hid = { git = "https://github.com/betrusted-io/xous-usb-hid.git", branch = "main" } +keystore = { path = "../../services/keystore" } # opensk -# ctap-crypto = { path = "libraries/crypto" } -# cbor = { path = "libraries/cbor" } -# persistent_store = { path = "libraries/persistent_store" } -# ed25519-compact = { version = "1", default-features = false, optional = true } -# rand = { version = "0.8.5", optional = true } +ctap-crypto = { path = "../../apps/vault/libraries/crypto" } +cbor = { path = "../../apps/vault/libraries/cbor" } +persistent_store = { path = "../../apps/vault/libraries/persistent_store" } +ed25519-compact = { version = "1", default-features = false, optional = true } +rand = { version = "0.8.5", optional = true } # ux formatting hex = { version = "0.4.3", default-features = false, features = ["alloc"] } @@ -71,19 +74,22 @@ board-baosec = [ ] hosted-baosec = ["bao1x-emu", "ux-api/hosted-baosec", "usb-bao1x/hosted-baosec"] -# with_ctap1 = ["ctap-crypto/with_ctap1"] +with_ctap1 = ["ctap-crypto/with_ctap1"] vendor_hid = [] std = [] fuzz = [] debug_ctap = [] autotest = [] -multireset = [] # allows credential reset more than once per boot +multireset = [] # allows credential reset more than once per boot vault-testing = ["random-pick"] -# introduce a slight delay after UX boxes swap, in case of race conditions. Shouldn't be necessary anymore, but kept around in case there's a new edge case we missed. -ux-swap-delay = [] osk-upgrade = [ ] # placeholder to select out OpenSK's "vendor upgrade" over HID, which we don't use because we have our own upgrade path. xous = [ ] # marks xous-specific code segments deep inside the CTAP crate. Mostly to help evaluate if a patch is even feasible in the future. -# ed25519 = ["ed25519-compact"] -default = [] # testing removed for release tag +ed25519 = ["ed25519-compact"] +default = [ + "with_ctap1", + "ed25519", + "xous", + "vault-testing", # testing removed for release tag +] diff --git a/apps-baosec/vault2/src/actions.rs b/apps-baosec/vault2/src/actions.rs index b4b55329c..f49d2f45b 100644 --- a/apps-baosec/vault2/src/actions.rs +++ b/apps-baosec/vault2/src/actions.rs @@ -7,13 +7,19 @@ use std::sync::{ atomic::{AtomicBool, Ordering}, }; +#[cfg(feature = "hosted-baosec")] +use bao1x_emu::trng::Trng; +#[cfg(feature = "board-baosec")] +use bao1x_hal_service::trng::Trng; +use keystore::Keystore; use locales::t; use num_traits::*; use passwords::PasswordGenerator; use pddb::BasisRetentionPolicy; use persistent_store::store::OPENSK2_DICT; -use vault::env::xous::U2F_APP_DICT; -use vault::{ +use ux_api::widgets::TextEntryPayload; +use vault2::env::xous::U2F_APP_DICT; +use vault2::{ AppInfo, VAULT_ALLOC_HINT, VAULT_PASSWORD_DICT, VAULT_TOTP_DICT, atime_to_str, basis_change, ctap::data_formats::PublicKeyCredentialSource, deserialize_app_info, serialize_app_info, utc_now, }; @@ -27,8 +33,18 @@ use crate::{ListItem, ListKey, storage::TotpRecord}; const VAULT_PASSWORD_REC_VERSION: u32 = 1; const VAULT_TOTP_REC_VERSION: u32 = 1; +const DENIABLE_BASIS_NAME: &'static str = "deniable"; + #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub enum ActionOp { + /// Menu items + MenuAddnew, + MenuEditStage2, + MenuDeleteStage2, + MenuUnlockBasis, + MenuManageBasis, + MenuClose, + /// Internal ops UpdateMode, UpdateOneItem, @@ -39,12 +55,12 @@ pub enum ActionOp { GenerateTests, } -pub struct ActionManager<'a> { +pub struct ActionManager { modals: modals::Modals, storage: RefCell, #[cfg(feature = "vault-testing")] - trng: RefCell, + trng: RefCell, mode: Arc>, pub item_lists: Arc>, @@ -54,15 +70,16 @@ pub struct ActionManager<'a> { opensk_mutex: Arc>, mode_cache: VaultMode, main_conn: xous::CID, + keystore: Keystore, } -impl<'a> ActionManager<'a> { +impl ActionManager { pub fn new( main_conn: xous::CID, mode: Arc>, item_lists: Arc>, action_active: Arc, opensk_mutex: Arc>, - ) -> ActionManager<'a> { + ) -> ActionManager { let xns = xous_names::XousNames::new().unwrap(); let storage_manager = storage::Manager::new(&xns); @@ -72,7 +89,7 @@ impl<'a> ActionManager<'a> { storage: RefCell::new(storage_manager), #[cfg(feature = "vault-testing")] - trng: RefCell::new(trng::Trng::new(&xns).unwrap()), + trng: RefCell::new(Trng::new(&xns).unwrap()), mode_cache: mc, mode, @@ -82,6 +99,7 @@ impl<'a> ActionManager<'a> { action_active, opensk_mutex, main_conn, + keystore: Keystore::new(&xns), } } @@ -96,15 +114,13 @@ impl<'a> ActionManager<'a> { (*self.mode.lock().unwrap()).clone() }; self.action_active.store(true, Ordering::SeqCst); - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); // allow calling menu to close } pub(crate) fn deactivate(&self) { self.action_active.store(false, Ordering::SeqCst); send_message( self.main_conn, - Message::new_scalar(crate::VaultOp::FullRedraw.to_usize().unwrap(), 0, 0, 0, 0), + Message::new_scalar(crate::VaultOp::Redraw.to_usize().unwrap(), 0, 0, 0, 0), ) .ok(); } @@ -127,8 +143,6 @@ impl<'a> ActionManager<'a> { return; } }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); let username = match self .modals .alert_builder(t!("vault.newitem.username", locales::LANG)) @@ -142,8 +156,6 @@ impl<'a> ActionManager<'a> { return; } }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); let mut approved = false; let mut bip39 = false; // Security note about PasswordGenerator. This is a 3rd party crate. It relies on `rand`'s @@ -209,8 +221,6 @@ impl<'a> ActionManager<'a> { return; } }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); password = if maybe_password.len() == 0 { let length = match self .modals @@ -225,8 +235,6 @@ impl<'a> ActionManager<'a> { return; } }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); let mut upper = false; let mut number = false; let mut symbol = false; @@ -275,8 +283,6 @@ impl<'a> ActionManager<'a> { .ok(); } } - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); let pg2 = PasswordGenerator { length: *length as usize, numbers: number, @@ -327,10 +333,6 @@ impl<'a> ActionManager<'a> { let li = make_pw_item_from_record(&storage::hex(record.hash()), record); self.item_lists.lock().unwrap().insert_unique(self.mode_cache, li); } - VaultMode::Fido => { - self.report_err(t!("vault.error.add_fido2", locales::LANG), None::); - // no DB entry update because it's an error to even get here - } VaultMode::Totp => { let description = match self .modals @@ -346,8 +348,6 @@ impl<'a> ActionManager<'a> { } }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); self.modals .add_list(vec![ t!("vault.newitem.totp", locales::LANG), @@ -370,8 +370,6 @@ impl<'a> ActionManager<'a> { } } - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); let secret = match self .modals .alert_builder(t!("vault.newitem.totp_ss", locales::LANG)) @@ -385,8 +383,7 @@ impl<'a> ActionManager<'a> { return; } }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); + let ss = secret.to_uppercase(); let ss_vec = if let Some(ss) = base32::decode(base32::Alphabet::RFC4648 { padding: false }, &ss) @@ -408,8 +405,6 @@ impl<'a> ActionManager<'a> { let timestep = if !is_totp { // get the initial count if it's an HOTP record - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); match self .modals .alert_builder(t!("vault.hotp.count", locales::LANG)) @@ -536,7 +531,6 @@ impl<'a> ActionManager<'a> { let choice = match entry.mode { VaultMode::Password => Some(storage::ContentKind::Password), VaultMode::Totp => Some(storage::ContentKind::TOTP), - VaultMode::Fido => None, }; if choice.is_none() { @@ -819,8 +813,6 @@ impl<'a> ActionManager<'a> { return; } }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); password = if maybe_password.len() == 0 { let length = match self .modals @@ -835,8 +827,6 @@ impl<'a> ActionManager<'a> { return; } }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); let mut upper = false; let mut number = false; let mut symbol = false; @@ -885,8 +875,6 @@ impl<'a> ActionManager<'a> { .ok(); } } - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); let pg2 = PasswordGenerator { length: length as usize, numbers: number, @@ -946,14 +934,6 @@ impl<'a> ActionManager<'a> { } } - #[cfg(feature = "vaultperf")] - #[inline] - /// create performance logger entries - pub fn perfentry(&self, pm: &PerfMgr, meta: u32, index: u32, line: u32) { - let event = perf_entry!(self.pid, FILE_ID_APPS_VAULT_SRC_ACTIONS, meta, index, line); - pm.log_event_unchecked(event); - } - pub(crate) fn is_db_empty(&mut self) -> bool { self.mode_cache = { // Wrap this in a block so the lock Drops. This comment keeps rustfmt from shortening the block @@ -970,13 +950,6 @@ impl<'a> ActionManager<'a> { /// - `format!()` is very slow, so we use `push_str()` where possible /// - allocations are slow, so we try to avoid them at all costs pub(crate) fn retrieve_db(&mut self) { - #[cfg(feature = "vaultperf")] - self.pm.stop_and_reset(); - #[cfg(feature = "vaultperf")] - self.pm.start(); - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_STARTBLOCK, 0, std::line!()); - self.mode_cache = { // Wrap this in a block so the lock Drops. This comment keeps rustfmt from shortening the block // and then clippy from complaining about unused braces. @@ -989,13 +962,9 @@ impl<'a> ActionManager<'a> { .dynamic_notification(Some(t!("vault.reloading_database", locales::LANG)), None) .ok(); let start = self.tt.elapsed_ms(); - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_STARTBLOCK, 1, std::line!()); let mut klen = 0; match self.pddb.borrow().read_dict(VAULT_PASSWORD_DICT, None, Some(256 * 1024)) { Ok(keys) => { - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_NONE, 1, std::line!()); let mut oom_keys = 0; // allocate a re-usable temporary buffers, to avoid triggering allocs let mut pw_rec = PasswordRecord::alloc(); @@ -1006,14 +975,10 @@ impl<'a> ActionManager<'a> { // pre-reserve the space at the top, to avoid lots of allocs il.expand(self.mode_cache, keys.len()); for key in keys { - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_STARTBLOCK, 2, std::line!()); if let Some(data) = key.data { if pw_rec.from_vec(data).is_ok() { // reset the re-usable structures extra.clear(); - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_NONE, 2, std::line!()); // build the description string make_pw_name(&pw_rec.description, &pw_rec.username, &mut desc); @@ -1021,14 +986,8 @@ impl<'a> ActionManager<'a> { // build the storage key in the list array lookup_key.reset_from_parts(&desc, &key.name); - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_NONE, 2, std::line!()); if let Some(prev_entry) = il.get(self.mode_cache, &lookup_key) { - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_STARTBLOCK, 3, std::line!()); prev_entry.dirty = true; - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_NONE, 3, std::line!()); if prev_entry.atime != pw_rec.atime || prev_entry.count != pw_rec.count { @@ -1042,25 +1001,16 @@ impl<'a> ActionManager<'a> { prev_entry.extra.clear(); prev_entry.extra.push_str(&extra); } - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_NONE, 3, std::line!()); if prev_entry.name() != &desc { // this check should be redundant, but, leave it in to be safe prev_entry.name_clear(); prev_entry.name_push_str(&desc); } - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_NONE, 3, std::line!()); if prev_entry.guid != key.name { prev_entry.guid.clear(); prev_entry.guid.push_str(&key.name); } - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_ENDBLOCK, 3, std::line!()); } else { - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_STARTBLOCK, 4, std::line!()); - let human_time = atime_to_str(pw_rec.atime); extra.push_str(&human_time); @@ -1078,8 +1028,6 @@ impl<'a> ActionManager<'a> { pw_rec.count, ); il.push(self.mode_cache, li); - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_ENDBLOCK, 4, std::line!()); } klen += 1; @@ -1102,8 +1050,6 @@ impl<'a> ActionManager<'a> { */ oom_keys += 1; } - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_ENDBLOCK, 2, std::line!()); } log::debug!("before fixup_filter: {}", self.tt.elapsed_ms() - start); il.filter_reset(self.mode_cache); @@ -1133,132 +1079,9 @@ impl<'a> ActionManager<'a> { } } } - #[cfg(feature = "vaultperf")] - self.perfentry(&self.pm, PERFMETA_ENDBLOCK, 1, std::line!()); log::info!("readout took {} ms for {} elements", self.tt.elapsed_ms() - start, klen); self.modals.dynamic_notification_close().ok(); } - VaultMode::Fido => { - // first assemble U2F records - log::debug!("listing in {}", U2F_APP_DICT); - // regen from scratch every time, It's slow, but we're counting on <20 FIDO entries on average - self.item_lists.lock().unwrap().clear(self.mode_cache); - match self.pddb.borrow().read_dict(U2F_APP_DICT, None, Some(256 * 1024)) { - Ok(keys) => { - let mut oom_keys = 0; - for key in keys { - if let Some(data) = key.data { - if let Some(ai) = deserialize_app_info(data) { - let li = make_u2f_item_from_record(&key.name, ai); - self.item_lists.lock().unwrap().insert_unique(self.mode_cache, li); - } else { - let err = format!( - "{}:{}:{}: ({})[moved data]...", - key.basis, U2F_APP_DICT, key.name, key.len - ); - self.report_err("Couldn't deserialize U2F key:", Some(err)); - } - } else { - oom_keys += 1; - } - } - if oom_keys != 0 { - log::warn!( - "Ran out of cache space handling U2F tokens. {} tokens are not loaded.", - oom_keys - ); - self.report_err( - &format!( - "Ran out of cache space handling U2F entries. {} tokens not loaded", - oom_keys - ), - None::, - ); - } - } - Err(e) => { - match e.kind() { - ErrorKind::NotFound => { - // this is fine, it just means no entries have been entered yet - } - _ => { - log::error!("Error opening U2F dictionary"); - self.report_err("Error opening U2F dictionary", Some(e)) - } - } - } - } - - { - // this brace creates a block that defines the lifetime of `mutex`; it is released on drop - // as it goes out of scope access to OPENSK2_DICT has to be - // mutex-guarded, otherwise we get errors as the OpenSK thread mutates - // the dictionary while we query it - let mutex = self.opensk_mutex.lock().unwrap(); - log::debug!("listing in {}", OPENSK2_DICT); - match self.pddb.borrow().read_dict(OPENSK2_DICT, None, Some(256 * 1024)) { - Ok(keys) => { - let mut oom_keys = 0; - for key in keys { - let key_number = key.name.parse::().unwrap_or(0); - if vault::ctap::storage::key::CREDENTIALS.contains(&key_number) { - if let Some(data) = key.data { - match vault::ctap::storage::deserialize_credential(&data) { - Some(result) => { - let li = make_fido_item_from_record(&key.name, result); - self.item_lists - .lock() - .unwrap() - .insert_unique(self.mode_cache, li); - } - None => { - // Probably more indicative of a mismatch in OpenSK key range - // mapping, rather than a hard error. - let err = format!( - "{}:{}:{}: ({}){:x?}...", - key.basis, - OPENSK2_DICT, - key.name, - key.len, - &data[..16] - ); - log::info!("Couldn't deserialize FIDO2 key {}", err); - } - } - } else { - oom_keys += 1; - } - } - } - if oom_keys != 0 { - log::warn!( - "Ran out of cache space handling FIDO2 tokens. {} tokens are not loaded.", - oom_keys - ); - self.report_err( - &format!( - "Ran out of cache space handling FIDO2 entries. {} tokens not loaded", - oom_keys - ), - None::, - ); - } - } - Err(e) => { - match e.kind() { - ErrorKind::NotFound => { - // this is fine, it just means no entries have been entered yet - } - _ => { - log::error!("Error opening FIDO2 dictionary"); - self.report_err("Error opening FIDO2 dictionary", Some(e)) - } - } - } - } - drop(mutex); - } - } VaultMode::Totp => { self.item_lists.lock().unwrap().clear(self.mode_cache); match self.pddb.borrow().read_dict(VAULT_TOTP_DICT, None, Some(256 * 1024)) { @@ -1310,54 +1133,24 @@ impl<'a> ActionManager<'a> { } self.item_lists.lock().unwrap().filter_reset(self.mode_cache); log::debug!("heap usage B: {}", heap_usage()); - #[cfg(feature = "vaultperf")] - { - self.perfentry(&self.pm, PERFMETA_ENDBLOCK, 0, std::line!()); - self.pm.flush().ok(); - match self.pm.stop_and_flush() { - Ok(entries) => { - log::info!("entries: {}", entries); - } - _ => { - log::info!("Perfcounter OOM'd during run"); - } - } - log::info!("Buf vmem loc: {:x}", self.perfbuf.as_ptr() as u32); - log::info!( - "Buf pmem loc: {:x}", - xous::syscall::virt_to_phys(self.perfbuf.as_ptr() as usize).unwrap_or(0) - ); - log::info!("PerfLogEntry size: {}", core::mem::size_of::()); - log::info!("Now printing the page table mapping for the performance buffer:"); - for page in (0..BUFLEN).step_by(4096) { - log::info!( - "V|P {:x} {:x}", - self.perfbuf.as_ptr() as usize + page, - xous::syscall::virt_to_phys(self.perfbuf.as_ptr() as usize + page).unwrap_or(0), - ); - } - } + } + + /// This is just a placeholder function - needs to be upgraded to consider prompting the user for + /// a PIN value, etc. + pub(crate) fn get_pin_key(&self) -> [u8; 32] { + let mut key = [0u8; 32]; + key[..16].copy_from_slice(&self.keystore.get_volatile_secret().expect("PIN not set")); + key } pub(crate) fn unlock_basis(&mut self) { - let name = match self - .modals - .alert_builder(t!("vault.basis.name", locales::LANG)) - .field(None, Some(name_validator)) - .build() - { - Ok(text) => &text.content()[0].content, - _ => { - log::error!("Name entry failed"); - self.action_active.store(false, Ordering::SeqCst); - return; - } - }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); - match self.pddb.borrow().unlock_basis(&name, Some(BasisRetentionPolicy::Persist)) { + match self.pddb.borrow().unlock_basis( + DENIABLE_BASIS_NAME, + &self.get_pin_key(), + Some(BasisRetentionPolicy::Persist), + ) { Ok(_) => { - log::debug!("Basis {} unlocked", name); + log::debug!("Basis {} unlocked", DENIABLE_BASIS_NAME); // clear local caches self.item_lists.lock().unwrap().clear_all(); } @@ -1406,13 +1199,14 @@ impl<'a> ActionManager<'a> { return; } }; - #[cfg(feature = "ux-swap-delay")] - self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); - match self.pddb.borrow().create_basis(&name) { + match self.pddb.borrow().create_basis(&name, &self.get_pin_key()) { Ok(_) => { if self.yes_no_approval(t!("vault.basis.created_mount", locales::LANG)) { - match self.pddb.borrow().unlock_basis(&name, Some(BasisRetentionPolicy::Persist)) - { + match self.pddb.borrow().unlock_basis( + &name, + &self.get_pin_key(), + Some(BasisRetentionPolicy::Persist), + ) { Ok(_) => { log::debug!("Basis {} unlocked", name); // clear local caches @@ -1539,106 +1333,7 @@ impl<'a> ActionManager<'a> { }; } } - // --- U2F + FIDO --- - let fido = self.pddb.borrow().list_keys(OPENSK2_DICT, None).unwrap_or(Vec::new()); - let u2f = self.pddb.borrow().list_keys(U2F_APP_DICT, None).unwrap_or(Vec::new()); - let total = fido.len() + u2f.len(); - if total < TARGET_ENTRIES { - let extra_u2f = (TARGET_ENTRIES - total) / 2; - let extra_fido = TARGET_ENTRIES - extra_u2f; - for index in 0..extra_u2f { - let n = random_pick::pick_multiple_from_slice(&words, &weights, 2); - let name = format!("{} {}", n[0], n[1]); - let notes = random_pick::pick_from_slice(&words, &weights).unwrap().to_string(); - let mut id = [0u8; 32]; - self.trng.borrow_mut().fill_bytes_via_next(&mut id); - let record = vault::AppInfo { - name, - id, - notes, - ctime: 1, // zero ctime is disallowed - atime: 1, - count: 0, - }; - let ser = serialize_app_info(&record); - let app_id_str = hex::encode(id); - match self.pddb.borrow().get( - U2F_APP_DICT, - &app_id_str, - None, - true, - true, - Some(256), - Some(basis_change), - ) { - Ok(mut app_data) => match app_data.write(&ser) { - Ok(len) => { - log::debug!("u2f wrote {} bytes", len); - self.modals - .dynamic_notification_update( - Some(&format!("u2f entry {}, {} bytes", index, len)), - None, - ) - .ok(); - } - Err(e) => log::error!("U2F Error: {:?}", e), - }, - _ => log::error!("U2F Error creating record"), - } - } - let xns = xous_names::XousNames::new().unwrap(); - let mut rng = ctap_crypto::rng256::XousRng256::new(&xns); - for index in 0..extra_fido { - use ctap_crypto::rng256::Rng256; - use vault::ctap::data_formats::*; - let _c_id = random_pick::pick_multiple_from_slice(&words, &weights, 2); - let cred_id = format!("{}", index + 1800); // 1800 is extracted from ctap/storage/keys.rs; 1700 is the start of the credential region, this sticks it...somewhere "above" that - let r_id = random_pick::pick_multiple_from_slice(&words, &weights, 2); - let rp_id = format!("{} {}", r_id[0], r_id[1]); - let handle = random_pick::pick_from_slice(&words, &weights).unwrap().to_string(); - let new_credential = PublicKeyCredentialSource { - key_type: PublicKeyCredentialType::PublicKey, - credential_id: rng.gen_uniform_u8x32().to_vec(), - private_key: vault::ctap::crypto_wrapper::PrivateKey::Ecdsa(rng.gen_uniform_u8x32()), - rp_id, - user_handle: handle.as_bytes().to_vec(), - user_display_name: None, - cred_protect_policy: None, - creation_order: 0, - user_name: None, - user_icon: None, - cred_blob: None, - large_blob_key: None, - }; - let shortid = &cred_id; - match self.pddb.borrow().get( - OPENSK2_DICT, - shortid, - None, - true, - true, - Some(128), - Some(basis_change), - ) { - Ok(mut cred) => { - let value = vault::ctap::storage::serialize_credential(new_credential).unwrap(); - match cred.write(&value) { - Ok(len) => { - log::debug!("fido2 wrote {} bytes", len); - self.modals - .dynamic_notification_update( - Some(&format!("fido2 entry {}, {} bytes", index, len)), - None, - ) - .ok(); - } - Err(e) => log::error!("FIDO2 Error: {:?}", e), - } - } - _ => log::error!("couldn't create FIDO2 credential"), - } - } - } + // TOTP let totp = self.pddb.borrow().list_keys(VAULT_TOTP_DICT, None).unwrap_or(Vec::new()); if totp.len() < TARGET_ENTRIES { @@ -1763,31 +1458,6 @@ fn count_validator(input: &TextEntryPayload) -> Option { } } -#[cfg(feature = "vaultperf")] -fn build_perf_mgr<'a>(bufptr: *mut u8) -> PerfMgr<'a> { - use utralib::generated::*; - let perf_csr = xous::syscall::map_memory( - xous::MemoryAddress::new(utra::perfcounter::HW_PERFCOUNTER_BASE), - None, - 4096, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("couldn't map perfcounter CSR range: check that no other performance managers are active"); - // this is the range used by the shellchat performance manager - let event1_csr = xous::syscall::map_memory( - xous::MemoryAddress::new(utra::event_source1::HW_EVENT_SOURCE1_BASE), - None, - 4096, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("couldn't map event1 CSR range"); - PerfMgr::new( - bufptr, - AtomicCsr::new(perf_csr.as_mut_ptr() as *mut u32), - AtomicCsr::new(event1_csr.as_mut_ptr() as *mut u32), // event_source1 - ) -} - pub(crate) fn heap_usage() -> usize { match xous::rsyscall(xous::SysCall::IncreaseHeap(0, xous::MemoryFlags::R)) .expect("couldn't get heap size") diff --git a/apps-baosec/vault2/src/ctap/hid/mod.rs b/apps-baosec/vault2/src/ctap/hid/mod.rs index 585f5536b..82a2ad29e 100644 --- a/apps-baosec/vault2/src/ctap/hid/mod.rs +++ b/apps-baosec/vault2/src/ctap/hid/mod.rs @@ -360,7 +360,7 @@ impl CtapHid { } /// Helper function to parse a raw packet. - pub fn process_single_packet(packet: &HidPacket) -> (ChannelID, ProcessedPacket) { + pub fn process_single_packet(packet: &HidPacket) -> (ChannelID, ProcessedPacket<'_>) { let (&cid, rest) = array_refs![packet, 4, 60]; if rest[0] & CtapHid::PACKET_TYPE_MASK != 0 { let cmd = rest[0] & !CtapHid::PACKET_TYPE_MASK; diff --git a/apps-baosec/vault2/src/env/xous/mod.rs b/apps-baosec/vault2/src/env/xous/mod.rs index ebf92a0a3..3a979691d 100644 --- a/apps-baosec/vault2/src/env/xous/mod.rs +++ b/apps-baosec/vault2/src/env/xous/mod.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::time::{Duration, Instant}; +use bao1x_hal::board::{BOOKEND_END, BOOKEND_START}; use ctap_crypto::rng256::XousRng256; use locales::t; use modals::Modals; use num_traits::*; use persistent_store::Store; -use precursor_hal::board::{BOOKEND_END, BOOKEND_START}; use xous::try_send_message; use xous_names::XousNames; use xous_usb_hid::device::fido::*; @@ -32,7 +32,7 @@ const KEEPALIVE_DELAY: Duration = Duration::from_millis(KEEPALIVE_DELAY_MS); mod storage; pub struct XousHidConnection { - pub endpoint: usb_device_xous::UsbHid, + pub endpoint: usb_bao1x::UsbHid, } impl XousHidConnection { pub fn recv_with_timeout(&mut self, buf: &mut [u8; 64], timeout_delay: Duration) -> SendOrRecvStatus { @@ -613,7 +613,7 @@ impl XousEnv { XousEnv { rng: XousRng256::new(&xns), store, - main_connection: XousHidConnection { endpoint: usb_device_xous::UsbHid::new() }, + main_connection: XousHidConnection { endpoint: usb_bao1x::UsbHid::new() }, #[cfg(feature = "vendor_hid")] vendor_connection: XousHidConnection { endpoint: UsbEndpoint::VendorHid }, modals: modals::Modals::new(&xns).unwrap(), diff --git a/apps-baosec/vault2/src/env/xous/storage.rs b/apps-baosec/vault2/src/env/xous/storage.rs index 4c45316bd..60f68e510 100644 --- a/apps-baosec/vault2/src/env/xous/storage.rs +++ b/apps-baosec/vault2/src/env/xous/storage.rs @@ -37,7 +37,7 @@ impl Storage for XousStorage { } fn num_pages(&self) -> usize { - precursor_hal::board::PDDB_LEN as usize / 4096 + bao1x_hal::board::PDDB_LEN as usize / 4096 } fn max_word_writes(&self) -> usize { @@ -48,7 +48,7 @@ impl Storage for XousStorage { 100_000 } - fn read_slice(&self, _index: StorageIndex, _length: usize) -> StorageResult> { + fn read_slice(&self, _index: StorageIndex, _length: usize) -> StorageResult> { unimplemented!() } diff --git a/apps-baosec/vault2/src/lib.rs b/apps-baosec/vault2/src/lib.rs new file mode 100644 index 000000000..13cc3bb13 --- /dev/null +++ b/apps-baosec/vault2/src/lib.rs @@ -0,0 +1,117 @@ +#![cfg_attr(rustfmt, rustfmt_skip)] +// Copyright2019-2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// #![cfg_attr(not(feature = "std"), no_std)] + +#[macro_use] +extern crate arrayref; + +use crate::ctap::hid::HidPacket; +use crate::ctap::main_hid::MainHid; +#[cfg(feature = "vendor_hid")] +use crate::ctap::vendor_hid::VendorHid; +use crate::ctap::CtapState; +pub use crate::ctap::Transport; +use crate::env::Env; +use std::time::{Instant, Duration}; +#[cfg(feature="xous")] +use ctap::main_hid::HidIterType; + +// Those macros should eventually be split into trace, debug, info, warn, and error macros when +// adding either the defmt or log feature and crate dependency. +#[cfg(feature = "debug_ctap")] +macro_rules! debug_ctap { + ($env: expr, $($rest:tt)*) => {{ + use core::fmt::Write; + writeln!($env.write(), $($rest)*).unwrap(); + }}; +} + +pub mod api; +// TODO(kaczmarczyck): Refactor this so that ctap module isn't public. +pub mod ctap; +pub mod env; + +pub const KEEPALIVE_DELAY_MS: u64 = 100; +pub const KEEPALIVE_DELAY: Duration = Duration::from_millis(KEEPALIVE_DELAY_MS); + +/// CTAP implementation parameterized by its environment. +pub struct Ctap { + env: E, + state: CtapState, + hid: MainHid, + #[cfg(feature = "vendor_hid")] + vendor_hid: VendorHid, +} + +impl Ctap { + /// Instantiates a CTAP implementation given its environment. + // This should only take the environment, but it temporarily takes the boot time until the + // clock is part of the environment. + pub fn new(mut env: E, now: Instant) -> Self { + let state = CtapState::new(&mut env, now); + let hid = MainHid::new(); + #[cfg(feature = "vendor_hid")] + let vendor_hid = VendorHid::new(); + Ctap { + env, + state, + hid, + #[cfg(feature = "vendor_hid")] + vendor_hid, + } + } + + pub fn state(&mut self) -> &mut CtapState { + &mut self.state + } + + pub fn hid(&mut self) -> &mut MainHid { + &mut self.hid + } + + pub fn env(&mut self) -> &mut E { + &mut self.env + } + + pub fn process_hid_packet( + &mut self, + packet: &HidPacket, + transport: Transport, + now: Instant, + ) -> HidIterType { + match transport { + Transport::MainHid => { + self.hid + .process_hid_packet(&mut self.env, packet, now, &mut self.state) + } + #[cfg(feature = "vendor_hid")] + Transport::VendorHid => { + self.vendor_hid + .process_hid_packet(&mut self.env, packet, now, &mut self.state) + } + } + } + + pub fn update_timeouts(&mut self, now: Instant) { + self.state.update_timeouts(now); + self.hid.update_wink_timeout(now); + } +} + +#[cfg(feature="xous")] +pub mod vault_api; +#[cfg(feature="xous")] +pub use vault_api::*; diff --git a/apps-baosec/vault2/src/main.rs b/apps-baosec/vault2/src/main.rs index 8cb5fdcad..353b5748b 100644 --- a/apps-baosec/vault2/src/main.rs +++ b/apps-baosec/vault2/src/main.rs @@ -1,16 +1,25 @@ use core::sync::atomic::{AtomicBool, Ordering}; +use std::cell::RefCell; use std::sync::{Arc, Mutex}; +use std::thread; use num_traits::*; +use pddb::Pddb; use totp::PumpOp; +use xous::msg_blocking_scalar_unpack; +use xous_ipc::Buffer; + mod ux; use ux::*; mod itemcache; use itemcache::*; -// mod actions; -// use actions::ActionOp; -// mod storage; +mod actions; +use actions::ActionOp; +mod storage; +mod submenu; mod totp; +pub(crate) mod vault_api; +use locales::t; /* Dev status & notes -- @@ -38,9 +47,11 @@ two. I am inclined to harmonize the two, which means reworking the TOTP flow to have the search entry at the bottom. -[x] TOTP interaction prototyped -[ ] password interaction prototyped --[ ] implement "home" button press menu mode +-[x] implement "home" button press menu mode -[ ] implement search by text entry - activated via both menu pop-up, and by selecting >search prefix< on the bottom line of UI +-[ ] implement PIN management UI - entering a pin unlocks the deniable basis automatically + -[ ] remove basis management calls when replacing with PIN calls There are three action loops that need to be implemented. These are not necessarily listed in order of implementation: @@ -48,16 +59,16 @@ necessarily listed in order of implementation: -[ ] implement HID loop -[ ] implement "action" loop --[ ] implement keystore +-[x] implement keystore -[ ] Consider the side channel resistance of the AES implementation in the keystore. We may want to use an AES API that explicitly wraps the SCE's masked AES implementation to reduce side channels, versus the Vex CPU core's AES implementation - -[ ] PDDB should have a base 256-bit key to protect all entries, stored in key store + -[x] PDDB should have a base 256-bit key to protect all entries, stored in key store This is equivalent to the "Backup key" in precursor - -[ ] Base 256-bit key is derived from hash of 64kbits raw data scattered + -[x] Base 256-bit key is derived from hash of 64kbits raw data scattered across the RRAM array. Locations are chosen to be diverse, with the goal of reducing voltage contrast due to parasitic leakage masking bits - -[ ] 64kbit array is split into four 16kbit chunks, which are XOR'd together to create + -[x] 64kbit array is split into four 16kbit chunks, which are XOR'd together to create a 16kbit number. The four 16kbit chunks are read out 256-bits at a time, with an order determined by a random number on boot. The random ordering frustrates side channel attacks on read-out of the array. Thus the format is: @@ -114,6 +125,16 @@ pub(crate) enum VaultOp { /// Redraw the screen Redraw = 0, KeyPress, + + /// Partial menu + MenuChangeFont, + MenuDeleteStage1, + MenuEditStage1, + MenuAutotype, + MenuReadoutMode, + MenuAutotypeRate, + MenuLeftyMode, + MenuDone, } #[derive(Copy, Clone, PartialEq, Eq, Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] @@ -131,7 +152,7 @@ pub struct SelectedEntry { fn main() -> ! { log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Info); + log::set_max_level(log::LevelFilter::Debug); log::info!("Vault2 PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); @@ -163,7 +184,7 @@ fn main() -> ! { // has to be in its own thread because it uses blocking modal calls that would cause // redraws of the background list to block/fail. let actions_sid = xous::create_server().unwrap(); - /* + let _ = thread::spawn({ let main_conn = conn.clone(); let sid = actions_sid.clone(); @@ -256,44 +277,81 @@ fn main() -> ! { xous::destroy_server(sid).ok(); } }); - */ + let actions_conn = xous::connect(actions_sid).unwrap(); + + let menu_sid = xous::create_server().unwrap(); + let menu_mgr = submenu::create_submenu(conn, actions_conn, menu_sid); + let modals = modals::Modals::new(&xns).unwrap(); + vault_ui.apply_glyph_style(); + // kickstart the pumper xous::send_message(pump_conn, xous::Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0)) .expect("couldn't start the pumper"); + let mut menu_active = false; loop { let msg = xous::receive_message(sid).unwrap(); - log::debug!("Got message: {:?}", msg); - + log::debug!("Got message: {:?}", msg.body.id()); match FromPrimitive::from_usize(msg.body.id()) { Some(VaultOp::Redraw) => { log::debug!("Got redraw"); vault_ui.redraw(); } + Some(VaultOp::MenuDone) => { + menu_active = false; + allow_totp_rendering.store(true, Ordering::SeqCst); + vault_ui.redraw(); + } Some(VaultOp::KeyPress) => xous::msg_scalar_unpack!(msg, k1, _k2, _k3, _k4, { let k = char::from_u32(k1 as u32).unwrap_or('\u{0000}'); log::info!("key {}", k); - match k { - '↓' => { - vault_ui.nav(NavDir::Down); - } - '↑' => { - vault_ui.nav(NavDir::Up); - } - '←' => { - vault_ui.nav(NavDir::PageUp); - } - '→' => { - vault_ui.nav(NavDir::PageDown); - } - _ => { - log::info!("unhandled key {}", k); + if menu_active { + menu_mgr.key_press(k); + } else { + match k { + '∴' => { + allow_totp_rendering.store(false, Ordering::SeqCst); + menu_mgr.redraw(); + menu_active = true; + } + '↓' => { + vault_ui.nav(NavDir::Down); + vault_ui.redraw(); + } + '↑' => { + vault_ui.nav(NavDir::Up); + vault_ui.redraw(); + } + '←' => { + vault_ui.nav(NavDir::PageUp); + vault_ui.redraw(); + } + '→' => { + vault_ui.nav(NavDir::PageDown); + vault_ui.redraw(); + } + _ => { + log::info!("unhandled key {}", k); + } } } - vault_ui.redraw(); }), + Some(VaultOp::MenuChangeFont) => { + for item in FONT_LIST { + modals.add_list_item(item).expect("couldn't build radio item list"); + } + allow_totp_rendering.store(false, Ordering::SeqCst); + match modals.get_radiobutton(t!("vault.select_font", locales::LANG)) { + Ok(style) => { + vault_ui.store_glyph_style(name_to_style(&style).unwrap_or(DEFAULT_FONT)); + vault_ui.apply_glyph_style(); + } + _ => log::error!("get_radiobutton failed"), + } + allow_totp_rendering.store(true, Ordering::SeqCst); + } _ => { - log::error!("Got unknown message"); + log::error!("Got unknown message: {:?}", msg); } } } diff --git a/apps-baosec/vault2/src/storage.rs b/apps-baosec/vault2/src/storage.rs index f0e2f57e4..0d6ac8a4d 100644 --- a/apps-baosec/vault2/src/storage.rs +++ b/apps-baosec/vault2/src/storage.rs @@ -84,7 +84,7 @@ impl Manager { pub fn new(_xns: &xous_names::XousNames) -> Manager { Manager { pddb: pddb::Pddb::new() } } fn pddb_exists(&self, dict: &str, key_name: &str, basis: Option) -> bool { - match self.pddb.get(dict, &key_name, basis.as_deref(), false, false, None, Some(vault::basis_change)) + match self.pddb.get(dict, &key_name, basis.as_deref(), false, false, None, Some(vault2::basis_change)) { Ok(_) => return true, Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, @@ -117,7 +117,7 @@ impl Manager { // exist true, alloc_hint, - Some(vault::basis_change), + Some(vault2::basis_change), ) { Ok(mut data) => match data.write(payload) { Ok(_) => match sync { @@ -131,7 +131,7 @@ impl Manager { } fn pddb_get(&self, dict: &str, key_name: &str) -> Result, Error> { - match self.pddb.get(dict, key_name, None, false, false, None, Some(vault::basis_change)) { + match self.pddb.get(dict, key_name, None, false, false, None, Some(vault2::basis_change)) { Ok(mut record) => { let mut data = Vec::::new(); record.read_to_end(&mut data)?; @@ -142,7 +142,7 @@ impl Manager { } fn basis_for_key(&self, dict: &str, key_name: &str) -> Result { - match self.pddb.get(dict, key_name, None, false, false, None, Some(vault::basis_change)) { + match self.pddb.get(dict, key_name, None, false, false, None, Some(vault2::basis_change)) { Ok(record) => Ok(record.attributes().expect("couldn't get key attributes").basis), Err(e) => return Err(Error::IoError(e)), } diff --git a/apps-baosec/vault2/src/submenu.rs b/apps-baosec/vault2/src/submenu.rs index 792caa57f..e38b47ee4 100644 --- a/apps-baosec/vault2/src/submenu.rs +++ b/apps-baosec/vault2/src/submenu.rs @@ -1,9 +1,10 @@ -use gam::*; use locales::t; use num_traits::*; -use vault::VaultOp; +use ux_api::menu::*; -use crate::actions::ActionOp; +// use crate::actions::ActionOp; // this is the final home of ActionOp +use crate::ActionOp; +use crate::VaultOp; pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr: xous::SID) -> MenuMatic { let mut menu_items = Vec::::new(); @@ -22,20 +23,6 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr: action_payload: MenuPayload::Scalar([0, 0, 0, 0]), close_on_select: true, }); - menu_items.push(MenuItem { - name: String::from(t!("vault.menu_unlock_basis", locales::LANG)), - action_conn: Some(actions_conn), - action_opcode: ActionOp::MenuUnlockBasis.to_u32().unwrap(), - action_payload: MenuPayload::Scalar([0, 0, 0, 0]), - close_on_select: true, - }); - menu_items.push(MenuItem { - name: String::from(t!("vault.menu_manage_basis", locales::LANG)), - action_conn: Some(actions_conn), - action_opcode: ActionOp::MenuManageBasis.to_u32().unwrap(), - action_payload: MenuPayload::Scalar([0, 0, 0, 0]), - close_on_select: true, - }); menu_items.push(MenuItem { name: String::from(t!("vault.menu_change_font", locales::LANG)), action_conn: Some(vault_conn), @@ -65,13 +52,6 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr: action_payload: MenuPayload::Scalar([0, 0, 0, 0]), close_on_select: true, }); - menu_items.push(MenuItem { - name: String::from(t!("vault.menu_set_lefty_mode", locales::LANG)), - action_conn: Some(vault_conn), - action_opcode: VaultOp::MenuLeftyMode.to_u32().unwrap(), - action_payload: MenuPayload::Scalar([0, 0, 0, 0]), - close_on_select: true, - }); menu_items.push(MenuItem { name: String::from(t!("vault.menu_close", locales::LANG)), action_conn: Some(actions_conn), @@ -80,5 +60,6 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr: close_on_select: true, }); - menu_matic(menu_items, gam::APP_MENU_0_VAULT, Some(menu_mgr)).expect("couldn't create MenuMatic manager") + menu_matic(menu_items, "Vault Menu", Some(menu_mgr), vault_conn, VaultOp::MenuDone.to_usize().unwrap()) + .expect("couldn't create MenuMatic manager") } diff --git a/apps-baosec/vault2/src/ux.rs b/apps-baosec/vault2/src/ux.rs index 086de57da..2cd7a23bc 100644 --- a/apps-baosec/vault2/src/ux.rs +++ b/apps-baosec/vault2/src/ux.rs @@ -1,4 +1,5 @@ -use core::fmt::Write; +use core::fmt::Write as TextViewWrite; +use std::io::{Read, Write}; use std::sync::{Arc, Mutex}; use blitstr2::GlyphStyle; @@ -10,6 +11,35 @@ use xous::CID; use crate::*; +pub const DEFAULT_FONT: GlyphStyle = GlyphStyle::Bold; +pub const FONT_LIST: [&'static str; 6] = ["regular", "tall", "mono", "bold", "large", "small"]; +pub fn name_to_style(name: &str) -> Option { + match name { + "regular" => Some(GlyphStyle::Regular), + "tall" => Some(GlyphStyle::Tall), + "mono" => Some(GlyphStyle::Monospace), + "cjk" => Some(GlyphStyle::Cjk), + "bold" => Some(GlyphStyle::Bold), + "large" => Some(GlyphStyle::Large), + "small" => Some(GlyphStyle::Small), + _ => None, + } +} +fn style_to_name(style: &GlyphStyle) -> String { + match style { + GlyphStyle::Regular => "regular".to_string(), + GlyphStyle::Monospace => "mono".to_string(), + GlyphStyle::Cjk => "cjk".to_string(), + GlyphStyle::Bold => "bold".to_string(), + GlyphStyle::Large => "large".to_string(), + GlyphStyle::Small => "small".to_string(), + GlyphStyle::Tall => "tall".to_string(), + _ => "regular".to_string(), + } +} +const VAULT_CONFIG_DICT: &'static str = "vault.config"; +const VAULT_CONFIG_KEY_FONT: &'static str = "fontstyle"; + pub enum NavDir { Up, Down, @@ -49,6 +79,9 @@ pub struct VaultUi { /// totp redraw state totp_code: Option, last_epoch: u64, + + pddb: RefCell, + item_height: isize, } impl VaultUi { @@ -58,24 +91,94 @@ impl VaultUi { item_lists: Arc>, mode: Arc>, ) -> Self { - let mut totp_list = ScrollableList::default() + let pddb = pddb::Pddb::new(); + let mut totp_list = ScrollableList::default(); + totp_list .set_margin(TotpLayout::totp_margin()) .pane_size(TotpLayout::list_box()) .style(TotpLayout::list_font()); for i in 0..6 { totp_list.add_item(0, &format!("example {}", i)); } + let gfx = Gfx::new(&xns).unwrap(); + let style = DEFAULT_FONT; + let glyph_height = gfx.glyph_height_hint(style).unwrap() as isize; + let height = gfx.screen_size().unwrap().y; Self { main_cid: cid, - gfx: Gfx::new(&xns).unwrap(), + gfx, totp_list, item_lists, mode, totp_code: None, last_epoch: crate::totp::get_current_unix_time().expect("couldn't get current time") / 30, + pddb: RefCell::new(pddb), + item_height: height / glyph_height, } } + pub(crate) fn store_glyph_style(&mut self, style: GlyphStyle) { + self.pddb + .borrow() + .delete_key(VAULT_CONFIG_DICT, VAULT_CONFIG_KEY_FONT, Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS)) + .expect("couldn't delete previous setting"); + + match self.pddb.borrow().get( + VAULT_CONFIG_DICT, + VAULT_CONFIG_KEY_FONT, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), + true, + true, + Some(32), + Some(vault2::basis_change), + ) { + Ok(mut style_key) => { + style_key.write(style_to_name(&style).as_bytes()).ok(); + } + _ => panic!("PDDB access erorr"), + }; + self.pddb.borrow().sync().ok(); + } + + pub(crate) fn apply_glyph_style(&mut self) { + let style = match self.pddb.borrow().get( + VAULT_CONFIG_DICT, + VAULT_CONFIG_KEY_FONT, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), + true, + true, + Some(32), + Some(vault2::basis_change), + ) { + Ok(mut style_key) => { + let mut name_bytes = Vec::::new(); + match style_key.read_to_end(&mut name_bytes) { + Ok(_len) => { + log::debug!( + "name_bytes: {:?} {:?}", + name_bytes, + String::from_utf8(name_bytes.to_vec()) + ); + name_to_style(&String::from_utf8(name_bytes).unwrap_or("bold".to_string())) + .unwrap_or(GlyphStyle::Bold) + } + Err(_) => GlyphStyle::Bold, + } + } + _ => { + log::warn!("PDDB access error reading default glyph size"); + GlyphStyle::Bold + } + }; + self.totp_list.style(style); + let glyph_height = self.gfx.glyph_height_hint(style).unwrap(); + self.item_height = glyph_height as isize + 2; // +2 because of the border width + self.item_lists + .lock() + .unwrap() + .set_items_per_screen(self.gfx.screen_size().unwrap().y / self.item_height); + } + /// Clear the entire screen. pub fn clear_area(&self) { self.gfx.clear().ok(); } diff --git a/apps-baosec/vault2/src/vault_api.rs b/apps-baosec/vault2/src/vault_api.rs index 1a1b5b191..caa00f4b7 100644 --- a/apps-baosec/vault2/src/vault_api.rs +++ b/apps-baosec/vault2/src/vault_api.rs @@ -166,14 +166,6 @@ pub fn deserialize_app_info(descriptor: Vec) -> Option { log::trace!("invalid line skipped: {:?}", line); } } - #[cfg(any(feature = "precursor", feature = "renode"))] - if appinfo.name.len() > 0 && appinfo.id != [0u8; 32] && appinfo.ctime != 0 { - // atime can be 0 - indicates never used - Some(appinfo) - } else { - None - } - #[cfg(not(target_os = "xous"))] if appinfo.name.len() > 0 && appinfo.id != [0u8; 32] { // atime can be 0 - indicates never used. In hosted mode, ctime is 0. Some(appinfo)