diff --git a/Cargo.lock b/Cargo.lock index 945f594e1..fbe6de8b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1433,7 +1433,9 @@ dependencies = [ "blowfish", "cipher", "digest", + "gam", "llio", + "locales", "log", "log-server", "num-derive", diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index fba352d03..1ad1bcb22 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -88,7 +88,7 @@ pub(crate) struct UxContext { /// opcode ID for AudioFrame pub audioframe_id: Option, } -const MAX_UX_CONTEXTS: usize = 7; +const MAX_UX_CONTEXTS: usize = 8; // const BOOT_APP_NAME: &'static str = "shellchat"; // this is the app to display on boot -- we will eventually need this once we have more than one app? pub const ROOTKEY_MODAL_NAME: &'static str = "rootkeys modal"; const BOOT_CONTEXT_TRUSTLEVEL: u8 = 254; @@ -257,7 +257,7 @@ impl ContextManager { // // That being said, if you are to run "generic apps from the internet" you can't // put a proper bound on this number. - log::error!("Ran out of UX contexts: try increasing MAX_UX_CONTEXTS in gam.rs"); + log::error!("Ran out of UX contexts: try increasing MAX_UX_CONTEXTS in gam/main.rs"); None } } diff --git a/services/gam/src/tokens.rs b/services/gam/src/tokens.rs index 0476beb32..66c236964 100644 --- a/services/gam/src/tokens.rs +++ b/services/gam/src/tokens.rs @@ -12,7 +12,7 @@ use xous_ipc::String; */ // if you add more UxContexts, and you want them authorized by the GAM, add their names here. -const TOKEN_SLOTS: usize = 8; +const TOKEN_SLOTS: usize = 9; const EXPECTED_BOOT_CONTEXTS: [&'static str; TOKEN_SLOTS] = [ "shellchat", "main menu", @@ -21,7 +21,8 @@ const EXPECTED_BOOT_CONTEXTS: [&'static str; TOKEN_SLOTS] = [ "rootkeys modal", "rtc modal", "rootkeys menu", - "test modal" + "test modal", + "pddb modal", ]; #[derive(Copy, Clone, Debug)] diff --git a/services/pddb/Cargo.toml b/services/pddb/Cargo.toml index 38eddf25a..042f6dd42 100644 --- a/services/pddb/Cargo.toml +++ b/services/pddb/Cargo.toml @@ -34,6 +34,9 @@ digest = "0.9" # bcrypt blowfish = { version = "0.8", features = ["bcrypt"] } +# UX (for password entry and notifications) +gam = {path="../gam"} +locales = {path = "../../locales"} [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = { path = "../../utralib"} diff --git a/services/pddb/locales/i18n.json b/services/pddb/locales/i18n.json new file mode 100644 index 000000000..3039cd089 --- /dev/null +++ b/services/pddb/locales/i18n.json @@ -0,0 +1,12 @@ +{ + "pddb.basisname": { + "en": "Basis Name:", + "zh": "基础名称", + "en-audio": "Enter name of Basis" + }, + "pddb.password": { + "en": "Basis Password:", + "zh": "基础密码", + "en-audio": "Enter password for Basis" + } +} \ No newline at end of file diff --git a/services/pddb/src/api.rs b/services/pddb/src/api.rs index 5084cab32..6ef304546 100644 --- a/services/pddb/src/api.rs +++ b/services/pddb/src/api.rs @@ -6,6 +6,8 @@ pub(crate) const DICT_NAME_LEN: usize = 127 - 4 - 4 - 4 - 4; // u32: flags, age, #[allow(dead_code)] pub(crate) const KEY_NAME_LEN: usize = 127 - 8 - 8 - 8 - 4 - 4; // u64: vaddr/len/resvd, u32: flags, age = 95 #[allow(dead_code)] +pub(crate) const PASSWORD_LEN: usize = 72; // this is actually set by bcrypt +#[allow(dead_code)] pub(crate) const PDDB_MAGIC: [u8; 4] = [0x50, 0x44, 0x44, 0x42]; #[allow(dead_code)] pub(crate) const PDDB_VERSION: u32 = 0x00_00_00_01; @@ -42,6 +44,8 @@ pub(crate) const PDDB_FAST_SPACE_SYSTEM_BASIS: &'static str = ".FastSpace"; // TODO: add hardware acceleration for BCRYPT so we can hit the OWASP target without excessive UX delay pub(crate) const BCRYPT_COST: u32 = 7; // 10 is the minimum recommended by OWASP; takes 5696 ms to verify @ 10 rounds; 804 ms to verify 7 rounds +#[allow(dead_code)] +pub(crate) const PDDB_MODAL_NAME: &'static str = "pddb modal"; #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] pub(crate) enum Opcode { @@ -61,6 +65,8 @@ pub(crate) enum Opcode { /// Suspend/resume callback SuspendResume, + /// quit the server + Quit, } /// A structure for requesting a token to access a particular key/value pair diff --git a/services/pddb/src/backend/bcrypt.rs b/services/pddb/src/backend/bcrypt.rs index 10c7266b5..614aeb4fd 100644 --- a/services/pddb/src/backend/bcrypt.rs +++ b/services/pddb/src/backend/bcrypt.rs @@ -29,17 +29,17 @@ pub fn bcrypt(cost: u32, salt: &[u8], pw: &str, output: &mut [u8]) { assert!(salt.len() == 16); assert!(output.len() == 24); - let pw_len = if pw.len() > 72 { - log::warn!("password of length {} is truncated to 72 bytes [reason: bcrypt limitation]", pw.len()); - 72 + let pw_len = if pw.len() > crate::api::PASSWORD_LEN { + log::warn!("password of length {} is truncated to {} bytes [reason: bcrypt limitation]", pw.len(), crate::api::PASSWORD_LEN); + crate::api::PASSWORD_LEN } else { pw.len() + 1 }; - let mut plaintext_copy: [u8; 73] = [0; 73]; + let mut plaintext_copy: [u8; crate::api::PASSWORD_LEN + 1] = [0; crate::api::PASSWORD_LEN + 1]; for (src, dst) in pw.bytes().zip(plaintext_copy.iter_mut()) { *dst = src; } - plaintext_copy[72] = 0; // always null terminate + plaintext_copy[crate::api::PASSWORD_LEN] = 0; // always null terminate // this function takes the plaintext key and uses it to prime a ~4k region of stack with an s-box // that's used for the round function. The upstream Rust crypto crate does not wipe the sbox after use. diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index 08d7ad83c..a09f93b02 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -368,6 +368,8 @@ mod api; use api::*; mod backend; use backend::*; +mod ux; +use ux::*; #[cfg(not(any(target_os = "none", target_os = "xous")))] mod tests; @@ -375,11 +377,19 @@ mod tests; use tests::*; use num_traits::*; -use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack}; +use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack, send_message, Message}; +use xous_ipc::Buffer; use core::cell::RefCell; use std::rc::Rc; use std::collections::HashSet; +use std::thread; + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub(crate) struct BasisRequestPassword { + db_name: xous_ipc::String::<{crate::api::BASIS_NAME_LEN}>, + plaintext_pw: Option>, +} #[xous::xous_main] fn xmain() -> ! { @@ -613,6 +623,28 @@ fn xmain() -> ! { 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"); + // our very own password modal. Password modals are precious and privately owned, to avoid + // other processes from crafting them. + let pw_sid = xous::create_server().expect("couldn't create a server for the password UX handler"); + let pw_cid = xous::connect(pw_sid).expect("couldn't connect to the password UX handler"); + let pw_handle = thread::spawn({ + move || { + password_ux_manager( + xous::connect(pddb_sid).unwrap(), + pw_sid + ) + } + }); + + let request = BasisRequestPassword { + db_name: xous_ipc::String::<{crate::api::BASIS_NAME_LEN}>::from_str("test basis"), + 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::().unwrap(); + log::info!("Got password: {:?}", ret.plaintext_pw); + loop { let msg = xous::receive_message(pddb_sid).unwrap(); match FromPrimitive::from_usize(msg.body.id()) { @@ -642,14 +674,23 @@ fn xmain() -> ! { susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); pddb.resume(); */ }), - None => { - log::error!("couldn't convert opcode"); + Some(Opcode::Quit) => { + log::warn!("quitting the PDDB server"); + send_message( + pw_cid, + Message::new_blocking_scalar(PwManagerOpcode::Quit.to_usize().unwrap(), 0, 0, 0, 0) + ).unwrap(); + xous::return_scalar(msg.sender, 0).unwrap(); break } + None => { + log::error!("couldn't convert opcode: {:?}", msg); + } } } // clean up our program log::trace!("main loop exit, destroying servers"); + 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(); log::trace!("quitting"); diff --git a/services/pddb/src/ux.rs b/services/pddb/src/ux.rs new file mode 100644 index 000000000..c95fa0d29 --- /dev/null +++ b/services/pddb/src/ux.rs @@ -0,0 +1,211 @@ +use xous::{SID, CID}; + +use xous::{msg_scalar_unpack, send_message}; +use xous_ipc::Buffer; + +use std::sync::{Arc, Mutex}; +use std::thread; +use core::sync::atomic::{AtomicBool, Ordering}; + +use num_traits::*; + +use gam::modal::*; + +use locales::t; +use std::fmt::Write; + +use crate::BasisRequestPassword; +/* +Conclusions: + +- PDDB will get *just* a password modal handler. That is all + (see UxInitRequestPassword from RootKeys modal; create a thread that handles + this local to PDDB, which takes in a blocking scalar to request the password, + and then spawns yet another thread to handle the actual password request.) +- The generic UX handler will be split into a managed server + +What we really want from the UX helper is a compound, blocking call which encapsulates +complex requests (prompt -> list response) and progress bars, with a simple blocking or +non-blocking call. + +I thnk non-blocking calls are pretty straight forward, but the blocking call is harder, because +the structure of the UX handler is like this: + +The (bouncer) is a single-use server to filter UX server opcodes from the GAM server. + +UX Manager UX Renderer GAM server Keyboard server +Do UX op -> raise -> compute redraw area + redraw manager <-(bouncer)<- redraw trigger + (user input) + key handler <-(bouncer)<- event <- keyboard events + draw updates -> compute redraw area + redraw manager <-(bouncer)<- redraw trigger + (user closes box) + lower -> compute redraw +Continue <- response + + +UX handler thread -> raise message -> +GAM server +GAM Modal Object -> redraw -> gam requests + +*/ +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum PwManagerOpcode { + // blocking call to get a password + RequestPassword, + Quit, +} + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum PwRendererOpcode { + RaisePwModal, + PwReturn, + ModalRedraw, + ModalKeypress, + ModalDrop, + Quit, +} + +pub(crate) fn password_ux_manager( + // the CID of the main loop, as a backchannel for async callbacks. + _main_cid: CID, + // the SID we're to use for our loop handler, for getting requests + ux_sid: SID) { + + let tt = ticktimer_server::Ticktimer::new().unwrap(); + + let renderer_sid = xous::create_server().expect("couldn't create a server for the password UX renderer"); + let renderer_cid = xous::connect(renderer_sid).expect("couldn't connect to the password UX renderer"); + let plaintext_pw = Arc::new(Mutex::new(xous_ipc::String::<{crate::api::PASSWORD_LEN}>::new())); + + let renderer_active = Arc::new(AtomicBool::new(false)); + // create a thread that just handles the redrawing requests + let redraw_handle = thread::spawn({ + let renderer_active = Arc::clone(&renderer_active); + let plaintext_pw = Arc::clone(&plaintext_pw); + move || { + // build the core data structure here + let password_action = TextEntry { + is_password: true, + visibility: TextEntryVisibility::LastChars, + action_conn: renderer_cid, + action_opcode: PwRendererOpcode::PwReturn.to_u32().unwrap(), + action_payload: TextEntryPayload::new(), + validator: None, + }; + + let mut pddb_modal = + Modal::new( + crate::api::PDDB_MODAL_NAME, + ActionType::TextEntry(password_action), + Some(t!("pddb.password", xous::LANG)), + None, + GlyphStyle::Small, + 8 + ); + pddb_modal.spawn_helper(renderer_sid, pddb_modal.sid, + PwRendererOpcode::ModalRedraw.to_u32().unwrap(), + PwRendererOpcode::ModalKeypress.to_u32().unwrap(), + PwRendererOpcode::ModalDrop.to_u32().unwrap(), + ); + + loop { + let msg = xous::receive_message(renderer_sid).unwrap(); + log::debug!("message: {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + Some(PwRendererOpcode::RaisePwModal) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let db_name = buffer.to_original::, _>().unwrap(); + pddb_modal.modify( + Some(ActionType::TextEntry(password_action)), + Some(t!("pddb.password", xous::LANG)), false, + Some(db_name.as_str().unwrap()), false, None + ); + pddb_modal.activate(); + } + Some(PwRendererOpcode::PwReturn) => { + let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let mut pw = buf.to_original::().unwrap(); + + plaintext_pw.lock().unwrap().clear(); + write!(plaintext_pw.lock().unwrap(), "{}", pw.as_str()).expect("couldn't transfer password to local buffer"); + + pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave + buf.volatile_clear(); + + // this resumes the waiting Ux Manager thread + renderer_active.store(false, Ordering::SeqCst); + }, + Some(PwRendererOpcode::ModalRedraw) => { + pddb_modal.redraw(); + }, + Some(PwRendererOpcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { + let keys = [ + if let Some(a) = core::char::from_u32(k1 as u32) {a} else {'\u{0000}'}, + if let Some(a) = core::char::from_u32(k2 as u32) {a} else {'\u{0000}'}, + if let Some(a) = core::char::from_u32(k3 as u32) {a} else {'\u{0000}'}, + if let Some(a) = core::char::from_u32(k4 as u32) {a} else {'\u{0000}'}, + ]; + pddb_modal.key_event(keys); + }), + Some(PwRendererOpcode::ModalDrop) => { // this guy should never quit, it's a core OS service + panic!("Password modal for PDDB quit unexpectedly"); + }, + Some(PwRendererOpcode::Quit) => { + log::warn!("received quit on PDDB password UX renderer loop"); + xous::return_scalar(msg.sender, 0).unwrap(); + break; + }, + None => { + log::error!("Couldn't convert opcode: {:?}", msg); + } + } + } + xous::destroy_server(renderer_sid).unwrap(); + } + }); + + // the main loop merely wraps a blocking wrapper around the renderer thread + loop { + let mut msg = xous::receive_message(ux_sid).unwrap(); + log::debug!("message: {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + Some(PwManagerOpcode::RequestPassword) => { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut request = buffer.to_original::().unwrap(); + let fwd_buf = Buffer::into_buf(request.db_name).unwrap(); + renderer_active.store(true, Ordering::SeqCst); + fwd_buf.lend(renderer_cid, PwRendererOpcode::RaisePwModal.to_u32().unwrap()).expect("couldn't request renderer to raise the password modal"); + // this returns almost immediately, because the Ux Manager thread can't block (it has to manage rendering), but the password hasn't come back yet. + // so...."busy wait" by polling once every 100ms until the Ux is finished with its task. + // I can't seem to figure out a way to do this using a solely asynchronous method. I really want a spsc queue, but these don't exist in xous stdlib yet. + // apparently the thing I'm looking for is a `condvar`, which is coming Real Soon Now. + while renderer_active.load(Ordering::SeqCst) { + tt.sleep_ms(100).unwrap(); + } + // when this unblocks, the password request cycle is done. + let retpw = xous_ipc::String::<{crate::api::PASSWORD_LEN}>::from_str(plaintext_pw.lock().unwrap().as_str().unwrap()); + request.plaintext_pw = Some(retpw); + + // return the password to the caller + buffer.replace(request).unwrap(); + }, + Some(PwManagerOpcode::Quit) => { + log::warn!("PDDB password handler exiting."); + send_message( + renderer_cid, + xous::Message::new_blocking_scalar(PwRendererOpcode::Quit.to_usize().unwrap(), + 0, 0, 0, 0)).unwrap(); + xous::return_scalar(msg.sender, 0).unwrap(); + break + }, + None => { + log::error!("couldn't convert opcode"); + } + } + } + redraw_handle.join().expect("redraw thread didn't quit as expected"); + unsafe{xous::disconnect(renderer_cid).unwrap()}; // can't remember if this is...necessary? it'll throw an error if it's not. + xous::destroy_server(ux_sid).unwrap(); +}