From 6aadbf3caea2171655c237d43f7c12a436327c8d Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 25 Jun 2022 23:02:01 +0800 Subject: [PATCH 1/7] fix error message on edit of FIDO2 entry --- apps/vault/src/actions.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/vault/src/actions.rs b/apps/vault/src/actions.rs index bd8f94a3e..600ba58e8 100644 --- a/apps/vault/src/actions.rs +++ b/apps/vault/src/actions.rs @@ -548,7 +548,7 @@ impl ActionManager { } Err(e) => { match e.kind() { - std::io::ErrorKind::NotFound => self.report_err(t!("vault.error.not_found", xous::LANG), None::), + std::io::ErrorKind::NotFound => self.report_err(t!("vault.error.fido2", xous::LANG), None::), _ => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), } None From 819b84954a3e944712af5929e61a48fa3b3a1f9d Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 25 Jun 2022 23:02:12 +0800 Subject: [PATCH 2/7] add autotype to TOTP. why not? --- apps/vault/src/ux/framework.rs | 148 ++++++++++++++++++--------------- 1 file changed, 82 insertions(+), 66 deletions(-) diff --git a/apps/vault/src/ux/framework.rs b/apps/vault/src/ux/framework.rs index d76c9b697..b5e3ac4e5 100644 --- a/apps/vault/src/ux/framework.rs +++ b/apps/vault/src/ux/framework.rs @@ -190,7 +190,7 @@ impl VaultUx { /* Entry Users ------------------------------------- - - autotype pw + - autotype pw totp - add new pw totp - edit pw totp fido - delete pw totp fido @@ -203,19 +203,7 @@ impl VaultUx { self.menu_mgr.delete_item(t!("vault.menu_addnew", xous::LANG)); match *self.mode.lock().unwrap() { VaultMode::Fido => (), - VaultMode::Totp => { - self.menu_mgr.insert_item( - MenuItem { - name: xous_ipc::String::from_str(t!("vault.menu_addnew", xous::LANG)), - action_conn: Some(self.actions_conn), - action_opcode: ActionOp::MenuAddnew.to_u32().unwrap(), - action_payload: MenuPayload::Scalar([0, 0, 0, 0]), - close_on_select: true, - }, - 0 - ); - }, - VaultMode::Password => { + VaultMode::Password | VaultMode::Totp => { self.menu_mgr.insert_item( MenuItem { name: xous_ipc::String::from_str(t!("vault.menu_addnew", xous::LANG)), @@ -647,74 +635,102 @@ impl VaultUx { if self.selection_index >= self.filtered_list.len() { return Err(xous::Error::InvalidPID); } - let entry = &self.filtered_list[self.selection_index].guid; - // we re-fetch the entry for autotype, because the PDDB could have unmounted a basis. - let updated_pw = match self.pddb.borrow().get( - crate::actions::VAULT_PASSWORD_DICT, - entry, - None, - false, false, None, - Some(crate::basis_change) - ) { - Ok(mut record) => { - let mut data = Vec::::new(); - match record.read_to_end(&mut data) { - Ok(_len) => { - if let Some(mut pw) = crate::actions::deserialize_password(data) { - match self.usb_dev.send_str(&pw.password) { - Ok(_) => { - pw.count += 1; - pw.atime = utc_now().timestamp() as u64; - pw - }, - Err(e) => { - log::error!("couldn't autotype password: {:?}", e); - return Err(xous::Error::UseBeforeInit); + let mode_cache = (*self.mode.lock().unwrap()).clone(); + match mode_cache { + VaultMode::Password => { + let entry = &self.filtered_list[self.selection_index].guid; + // we re-fetch the entry for autotype, because the PDDB could have unmounted a basis. + let updated_pw = match self.pddb.borrow().get( + crate::actions::VAULT_PASSWORD_DICT, + entry, + None, + false, false, None, + Some(crate::basis_change) + ) { + Ok(mut record) => { + let mut data = Vec::::new(); + match record.read_to_end(&mut data) { + Ok(_len) => { + if let Some(mut pw) = crate::actions::deserialize_password(data) { + match self.usb_dev.send_str(&pw.password) { + Ok(_) => { + pw.count += 1; + pw.atime = utc_now().timestamp() as u64; + pw + }, + Err(e) => { + log::error!("couldn't autotype password: {:?}", e); + return Err(xous::Error::UseBeforeInit); + } + } + } else { + log::error!("couldn't deserialize {}", entry); + return Err(xous::Error::InvalidString); } } - } else { - log::error!("couldn't deserialize {}", entry); - return Err(xous::Error::InvalidString); + Err(e) => { + log::error!("couldn't access key {}: {:?}", entry, e); + return Err(xous::Error::ProcessNotFound); + }, } } Err(e) => { log::error!("couldn't access key {}: {:?}", entry, e); return Err(xous::Error::ProcessNotFound); - }, - } - } - Err(e) => { - log::error!("couldn't access key {}: {:?}", entry, e); - return Err(xous::Error::ProcessNotFound); - } - }; - match self.pddb.borrow().delete_key(crate::actions::VAULT_PASSWORD_DICT, entry, None) { - Ok(_) => {} - Err(_e) => { - return Err(xous::Error::InternalError); - } - } - match self.pddb.borrow().get( - crate::actions::VAULT_PASSWORD_DICT, entry, None, - false, true, Some(crate::actions::VAULT_ALLOC_HINT), - Some(crate::basis_change) - ) { - Ok(mut record) => { - let ser = crate::actions::serialize_password(&updated_pw); - match record.write(&ser) { + } + }; + match self.pddb.borrow().delete_key(crate::actions::VAULT_PASSWORD_DICT, entry, None) { Ok(_) => {} + Err(_e) => { + return Err(xous::Error::InternalError); + } + } + match self.pddb.borrow().get( + crate::actions::VAULT_PASSWORD_DICT, entry, None, + false, true, Some(crate::actions::VAULT_ALLOC_HINT), + Some(crate::basis_change) + ) { + Ok(mut record) => { + let ser = crate::actions::serialize_password(&updated_pw); + match record.write(&ser) { + Ok(_) => {} + Err(e) => { + log::error!("couldn't update key {}: {:?}", entry, e); + return Err(xous::Error::OutOfMemory); + } + } + } Err(e) => { log::error!("couldn't update key {}: {:?}", entry, e); return Err(xous::Error::OutOfMemory); } } + self.pddb.borrow().sync().ok(); } - Err(e) => { - log::error!("couldn't update key {}: {:?}", entry, e); - return Err(xous::Error::OutOfMemory); + VaultMode::Totp => { + let fields = self.filtered_list[self.selection_index].extra.split(':').collect::>(); + if fields.len() == 4 { + let shared_secret = base32::decode( + base32::Alphabet::RFC4648 { padding: false }, fields[0]) + .unwrap_or(vec![]); + let digit_count = u8::from_str_radix(fields[1], 10).unwrap_or(6); + let step_seconds = u16::from_str_radix(fields[2], 10).unwrap_or(30); + let algorithm = TotpAlgorithm::try_from(fields[2]).unwrap_or(TotpAlgorithm::HmacSha1); + let totp = totp::TotpEntry { + step_seconds, + shared_secret, + digit_count, + algorithm + }; + let code = generate_totp_code( + totp::get_current_unix_time().unwrap_or(0), + &totp + ).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string()); + self.usb_dev.send_str(&code).ok(); + } } + _ => log::error!("Illegal state! we shouldn't be having an autotype on {:?}", mode_cache), } - self.pddb.borrow().sync().ok(); Ok(()) } pub(crate) fn selected_entry(&self) -> Option { From 475fadb25567ad9cca9dd1b127255bef8be7a48e Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 26 Jun 2022 02:10:50 +0800 Subject: [PATCH 3/7] make search strings persist between modes and menus --- apps/vault/src/ux/framework.rs | 9 ++++++++- services/ime-frontend/src/main.rs | 24 ------------------------ 2 files changed, 8 insertions(+), 25 deletions(-) diff --git a/apps/vault/src/ux/framework.rs b/apps/vault/src/ux/framework.rs index b5e3ac4e5..d780fb412 100644 --- a/apps/vault/src/ux/framework.rs +++ b/apps/vault/src/ux/framework.rs @@ -73,6 +73,8 @@ pub(crate) struct VaultUx { filtered_list: Vec::, /// the index into the item_list that is selected selection_index: usize, + /// last filter query, so we can re-use it when mode is changed + last_query: String, /// pddb handle pddb: RefCell::, @@ -176,6 +178,7 @@ impl VaultUx { usb_dev: usb_device_xous::UsbHid::new(), last_epoch: current_time / 30, current_time, + last_query: String::new(), } } @@ -183,7 +186,8 @@ impl VaultUx { self.title_dirty = true; self.filtered_list.clear(); self.selection_index = 0; - self.filter(""); + let query = self.last_query.to_string(); + self.filter(&query); self.swap_submenu(); } @@ -195,6 +199,8 @@ impl VaultUx { - edit pw totp fido - delete pw totp fido - change font pw totp fido + - unlock basis pw totp fido + - list/lock basis pw totp fido - close pw totp fido */ pub fn swap_submenu(&mut self) { @@ -346,6 +352,7 @@ impl VaultUx { pub(crate) fn input(&mut self, line: &str) -> Result<(), xous::Error> { self.title_dirty = true; self.filter(line); + self.last_query = line.to_string(); Ok(()) } fn get_page(&self) -> i16 { diff --git a/services/ime-frontend/src/main.rs b/services/ime-frontend/src/main.rs index 9d7e6ac92..894374c6f 100644 --- a/services/ime-frontend/src/main.rs +++ b/services/ime-frontend/src/main.rs @@ -326,12 +326,6 @@ impl InputTracker { self.insert_prediction(0); do_redraw = true; } else { - self.pred_phrase.clear(); - self.line.clear(); - self.can_unpick = false; - self.last_trigger_char = Some(0); - self.characters = 0; - self.insertion = 0; retstring = Some(xous_ipc::String::<4000>::from_str("\u{0011}")); do_redraw = true; } @@ -341,12 +335,6 @@ impl InputTracker { self.insert_prediction(1); do_redraw = true; } else { - self.pred_phrase.clear(); - self.line.clear(); - self.can_unpick = false; - self.last_trigger_char = Some(0); - self.characters = 0; - self.insertion = 0; retstring = Some(xous_ipc::String::<4000>::from_str("\u{0012}")); do_redraw = true; } @@ -356,12 +344,6 @@ impl InputTracker { self.insert_prediction(2); do_redraw = true; } else { - self.pred_phrase.clear(); - self.line.clear(); - self.can_unpick = false; - self.last_trigger_char = Some(0); - self.characters = 0; - self.insertion = 0; retstring = Some(xous_ipc::String::<4000>::from_str("\u{0013}")); do_redraw = true; } @@ -371,12 +353,6 @@ impl InputTracker { self.insert_prediction(3); do_redraw = true; } else { - self.pred_phrase.clear(); - self.line.clear(); - self.can_unpick = false; - self.last_trigger_char = Some(0); - self.characters = 0; - self.insertion = 0; retstring = Some(xous_ipc::String::<4000>::from_str("\u{0014}")); do_redraw = true; } From e62c9bf3d3113a63e0d21fcf6eeb66ce22ad6257 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 26 Jun 2022 02:11:13 +0800 Subject: [PATCH 4/7] add basis management functions and debug some basis issues there's some problems with the automatic basis unionization feature. now debugging... --- apps/vault/locales/i18n.json | 48 +++++++ apps/vault/src/actions.rs | 96 +++++++++++++- apps/vault/src/submenu.rs | 14 +++ services/pddb/src/backend/basis.rs | 9 ++ services/pddb/src/main.rs | 193 ++++++++++++++++------------- 5 files changed, 270 insertions(+), 90 deletions(-) diff --git a/apps/vault/locales/i18n.json b/apps/vault/locales/i18n.json index cd8804176..aa9da3371 100644 --- a/apps/vault/locales/i18n.json +++ b/apps/vault/locales/i18n.json @@ -1,4 +1,34 @@ { + "vault.basis.name": { + "en": "Enter name of Basis to unlock:", + "ja": "ロックを解除する基準の名前を入力してください:", + "zh": "输入要解锁的基础名称:", + "en-tts": "Enter name of Basis to unlock:" + }, + "vault.basis.create": { + "en": "Enter name of Basis to create:", + "ja": "作成する基準の名前を入力します:", + "zh": "输入要创建的基础名称:", + "en-tts": "Enter name of Basis to create:" + }, + "vault.basis.created_mount": { + "en": "Basis created. Mount it now?", + "ja": "ベーシスが作成されました。 今それをマウントしますか?", + "zh": "创建的基础。 现在装吗?", + "en-tts": "Basis created. Mount it now?" + }, + "vault.basis.none": { + "en": "No active secret Bases. Would you like to create one?", + "ja": "アクティブな秘密の根拠はありません。 作成しますか?", + "zh": "没有有效的秘密基础。 你想创建一个吗?", + "en-tts": "No active secret Bases. Would you like to create one?" + }, + "vault.basis.unmount": { + "en": "Select the Bases to unmount:", + "ja": "アンマウントするベースを選択します:", + "zh": "选择要卸载的基础:", + "en-tts": "Select the Bases to unmount:" + }, "vault.edit_dialog": { "en": "Make your changes and press enter.\nUse the d-pad to navigate entries.", "ja": "変更を加えてEnterキーを押します。 D-PADを使用してエントリをナビゲートします。", @@ -17,6 +47,12 @@ "zh": "现在自动输入...", "en-tts": "Autotyping..." }, + "vault.error.basis_unlock_error": { + "en": "Basis does not exist. Or maybe wrong password?", + "ja": "根拠は存在しません。 または多分間違ったパスワード?", + "zh": "基础不存在。 或者密码错误?", + "en-tts": "Basis does not exist. Or maybe wrong password?" + }, "vault.error.mount_pddb": { "en": "PDDB not mounted. Please init root keys and then init PDDB.", "ja": "PDDBがマウントされていません。 ルートキーを初期化してから、PDDBを初期化してください。", @@ -359,6 +395,18 @@ "zh": "更改字体", "en-tts": "🔇" }, + "vault.menu_unlock_basis": { + "en": "Unlock secret Basis", + "ja": "シークレットベースのロックを解除", + "zh": "解锁秘密基础", + "en-tts": "Unlock secret basis" + }, + "vault.menu_manage_basis": { + "en": "Manage Bases", + "ja": "管理基盤", + "zh": "管理基础", + "en-tts": "Manage Bases" + }, "vault.menu_close": { "en": "Close submenu", "ja": "メニューを閉じる", diff --git a/apps/vault/src/actions.rs b/apps/vault/src/actions.rs index 600ba58e8..5cecdfaeb 100644 --- a/apps/vault/src/actions.rs +++ b/apps/vault/src/actions.rs @@ -1,6 +1,7 @@ use core::convert::TryFrom; -use std::thread; +use std::{thread, io::ErrorKind}; use gam::TextEntryPayload; +use pddb::BasisRetentionPolicy; use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; use num_traits::*; use xous::{SID, msg_blocking_scalar_unpack, Message, send_message}; @@ -58,6 +59,8 @@ pub(crate) enum ActionOp { MenuEditStage2, MenuDeleteStage2, MenuClose, + MenuUnlockBasis, + MenuManageBasis, /// Internal ops UpdateMode, Quit, @@ -103,6 +106,16 @@ pub(crate) fn start_actions_thread( manager.retrieve_db(); manager.deactivate(); }, + Some(ActionOp::MenuUnlockBasis) => { + manager.activate(); + manager.unlock_basis(); + manager.deactivate(); + }, + Some(ActionOp::MenuManageBasis) => { + manager.activate(); + manager.manage_basis(); + manager.deactivate(); + } Some(ActionOp::MenuClose) => { // dummy activate/de-activate cycle because we have to trigger a redraw of the underlying UX manager.activate(); @@ -876,6 +889,87 @@ impl ActionManager { } il.sort(); } + + pub(crate) fn unlock_basis(&mut self) { + let name = match self.modals + .alert_builder(t!("vault.basis.name", xous::LANG)) + .field(None, Some(name_validator)) + .build() + { + Ok(text) => { + text.content()[0].content.as_str().unwrap_or("UTF-8 error").to_string() + }, + _ => {log::error!("Name entry failed"); self.action_active.store(false, Ordering::SeqCst); return} + }; + self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); + match self.pddb.borrow().unlock_basis(&name, Some(BasisRetentionPolicy::Persist)) { + Ok(_) => log::debug!("Basis {} unlocked", name), + Err(e) => match e.kind() { + ErrorKind::PermissionDenied => { + self.report_err(t!("vault.error.basis_unlock_error", xous::LANG), None::) + }, + _ => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + } + } + } + + pub(crate) fn manage_basis(&mut self) { + let mut bases = self.pddb.borrow().list_basis(); + bases.retain(|name| name != pddb::PDDB_DEFAULT_SYSTEM_BASIS); + let b: Vec<&str> = bases.iter().map(AsRef::as_ref).collect(); + if bases.len() > 0 { + self.modals + .add_list( + b + ).expect("couldn't create unmount modal"); + match self.modals.get_checkbox(t!("vault.basis.unmount", xous::LANG)) { + Ok(unmount) => { + for b in unmount { + match self.pddb.borrow().lock_basis(&b) { + Ok(_) => log::debug!("basis {} locked", b), + Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + } + } + } + Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + } + } else { + if self.yes_no_approval(t!("vault.basis.none", xous::LANG)) { + let name = match self.modals + .alert_builder(t!("vault.basis.create", xous::LANG)) + .field(None, Some(name_validator)) + .build() + { + Ok(text) => { + text.content()[0].content.as_str().unwrap_or("UTF-8 error").to_string() + }, + Err(e) => {self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)); return} + }; + self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); + match self.pddb.borrow().create_basis(&name) { + Ok(_) => { + if self.yes_no_approval(t!("vault.basis.created_mount", xous::LANG)) { + match self.pddb.borrow().unlock_basis(&name, Some(BasisRetentionPolicy::Persist)) { + Ok(_) => log::debug!("Basis {} unlocked", name), + Err(e) => match e.kind() { + ErrorKind::PermissionDenied => { + self.report_err(t!("vault.error.basis_unlock_error", xous::LANG), None::) + }, + _ => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + } + } + } else { + // do nothing + } + } + Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + } + } else { + // do nothing + } + } + } + #[cfg(feature="testing")] pub(crate) fn populate_tests(&mut self) { use crate::ux::serialize_app_info; diff --git a/apps/vault/src/submenu.rs b/apps/vault/src/submenu.rs index 3d418c18e..03f805327 100644 --- a/apps/vault/src/submenu.rs +++ b/apps/vault/src/submenu.rs @@ -22,6 +22,20 @@ 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: xous_ipc::String::from_str(t!("vault.menu_unlock_basis", xous::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: xous_ipc::String::from_str(t!("vault.menu_manage_basis", xous::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: xous_ipc::String::from_str(t!("vault.menu_change_font", xous::LANG)), action_conn: Some(vault_conn), diff --git a/services/pddb/src/backend/basis.rs b/services/pddb/src/backend/basis.rs index 72b986fa8..854e9f8e3 100644 --- a/services/pddb/src/backend/basis.rs +++ b/services/pddb/src/backend/basis.rs @@ -256,6 +256,14 @@ impl BasisCache { tt: ticktimer_server::Ticktimer::new().unwrap(), } } + /// Returns a Vec which is a list of Bases to visit, in order of visitation, to create the union view. + pub(crate) fn access_list(&self) -> Vec:: { + let mut al = Vec::::new(); + for entry in self.cache.iter().rev() { + al.push(entry.name.to_string()); + } + al + } fn select_basis(&mut self, basis_name: Option<&str>) -> Option { if self.cache.len() == 0 { log::error!("Can't select basis: PDDB is not mounted"); @@ -941,6 +949,7 @@ impl BasisCache { } } else { for basis in self.cache.iter_mut() { + log::info!("syncing {}", basis.name); basis.sync(hw)?; } } diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index e259d8354..98fac8e2e 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -779,74 +779,76 @@ fn main() -> ! { buffer.replace(mgmt).unwrap(); } Some(Opcode::KeyRequest) => { - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; - let mut req: PddbKeyRequest = buffer.to_original::().unwrap(); - let bname = if req.basis_specified { - Some(req.basis.as_str().unwrap()) - } else { - None - }; - let dict = req.dict.as_str().expect("dict utf-8 decode error"); - let key = req.key.as_str().expect("key utf-8 decode error"); - if basis_cache.dict_attributes(&mut pddb_os, dict, bname).is_err() { - if req.create_dict { - match basis_cache.dict_add(&mut pddb_os, dict, bname) { - Ok(_) => (), - Err(e) => { - match e.kind() { - std::io::ErrorKind::OutOfMemory => {req.result = PddbRequestCode::NoFreeSpace; buffer.replace(req).unwrap(); continue} - std::io::ErrorKind::NotFound => {req.result = PddbRequestCode::NotMounted; buffer.replace(req).unwrap(); continue} - _ => {req.result = PddbRequestCode::InternalError; buffer.replace(req).unwrap(); continue} + for basis in basis_cache.access_list().iter() { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut req: PddbKeyRequest = buffer.to_original::().unwrap(); + let bname = if req.basis_specified { + Some(req.basis.as_str().unwrap()) + } else { + Some(basis.as_str()) + }; + let dict = req.dict.as_str().expect("dict utf-8 decode error"); + let key = req.key.as_str().expect("key utf-8 decode error"); + if basis_cache.dict_attributes(&mut pddb_os, dict, bname).is_err() { + if req.create_dict { + match basis_cache.dict_add(&mut pddb_os, dict, bname) { + Ok(_) => (), + Err(e) => { + match e.kind() { + std::io::ErrorKind::OutOfMemory => {req.result = PddbRequestCode::NoFreeSpace; buffer.replace(req).unwrap(); continue} + std::io::ErrorKind::NotFound => {req.result = PddbRequestCode::NotMounted; buffer.replace(req).unwrap(); continue} + _ => {req.result = PddbRequestCode::InternalError; buffer.replace(req).unwrap(); continue} + } + } + } + } else { + req.result = PddbRequestCode::NotFound; + buffer.replace(req).unwrap(); continue + } + } + let alloc_hint = if let Some(hint) = req.alloc_hint {Some(hint as usize)} else {None}; + if basis_cache.key_attributes(&mut pddb_os, dict, key, bname).is_err() { + if !req.create_key { + req.result = PddbRequestCode::NotFound; + buffer.replace(req).unwrap(); continue + } else { + // create an empty key placeholder + let empty: [u8; 0] = []; + match basis_cache.key_update(&mut pddb_os, + dict, key, &empty, None, alloc_hint, bname, true + ) { + Ok(_) => {}, + Err(e) => { + log::error!("Couldn't allocate key: {:?}", e); + match e.kind() { + std::io::ErrorKind::NotFound => req.result = PddbRequestCode::NotMounted, + std::io::ErrorKind::OutOfMemory => req.result = PddbRequestCode::NoFreeSpace, + _ => req.result = PddbRequestCode::InternalError, + } + buffer.replace(req).unwrap(); continue } } } - } else { - req.result = PddbRequestCode::NotFound; - buffer.replace(req).unwrap(); continue } - } - let alloc_hint = if let Some(hint) = req.alloc_hint {Some(hint as usize)} else {None}; - if basis_cache.key_attributes(&mut pddb_os, dict, key, bname).is_err() { - if !req.create_key { - req.result = PddbRequestCode::NotFound; - buffer.replace(req).unwrap(); continue + // at this point, we have established a basis/dict/key tuple. + let token: ApiToken = [pddb_os.trng_u32(), pddb_os.trng_u32(), pddb_os.trng_u32()]; + let cid = if let Some(cb_sid) = req.cb_sid { + Some(xous::connect(xous::SID::from_array(cb_sid)).expect("couldn't connect for callback")) } else { - // create an empty key placeholder - let empty: [u8; 0] = []; - match basis_cache.key_update(&mut pddb_os, - dict, key, &empty, None, alloc_hint, bname, true - ) { - Ok(_) => {}, - Err(e) => { - log::error!("Couldn't allocate key: {:?}", e); - match e.kind() { - std::io::ErrorKind::NotFound => req.result = PddbRequestCode::NotMounted, - std::io::ErrorKind::OutOfMemory => req.result = PddbRequestCode::NoFreeSpace, - _ => req.result = PddbRequestCode::InternalError, - } - buffer.replace(req).unwrap(); continue - } - } - } + None + }; + let token_record = TokenRecord { + dict: String::from(dict), + key: String::from(key), + basis: if let Some(name) = bname {Some(String::from(name))} else {None}, + conn: cid, + alloc_hint, + }; + token_dict.insert(token, token_record); + req.token = Some(token); + req.result = PddbRequestCode::NoErr; + buffer.replace(req).unwrap(); } - // at this point, we have established a basis/dict/key tuple. - let token: ApiToken = [pddb_os.trng_u32(), pddb_os.trng_u32(), pddb_os.trng_u32()]; - let cid = if let Some(cb_sid) = req.cb_sid { - Some(xous::connect(xous::SID::from_array(cb_sid)).expect("couldn't connect for callback")) - } else { - None - }; - let token_record = TokenRecord { - dict: String::from(dict), - key: String::from(key), - basis: if let Some(name) = bname {Some(String::from(name))} else {None}, - conn: cid, - alloc_hint, - }; - token_dict.insert(token, token_record); - req.token = Some(token); - req.result = PddbRequestCode::NoErr; - buffer.replace(req).unwrap(); } Some(Opcode::KeyDrop) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, _, { let token: ApiToken = [t0 as u32, t1 as u32, t2 as u32]; @@ -1124,19 +1126,28 @@ fn main() -> ! { let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance let token = pbuf.token; if let Some(rec) = token_dict.get(&token) { - match basis_cache.key_read(&mut pddb_os, - &rec.dict, &rec.key, - &mut pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), - if let Some (name) = &rec.basis {Some(&name)} else {None}) { - Ok(readlen) => { - pbuf.len = readlen as u16; - pbuf.retcode = PddbRetcode::Ok; - } - Err(e) => match e.kind() { - std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost, - std::io::ErrorKind::UnexpectedEof => pbuf.retcode = PddbRetcode::UnexpectedEof, - std::io::ErrorKind::OutOfMemory => pbuf.retcode = PddbRetcode::DiskFull, - _ => pbuf.retcode = PddbRetcode::InternalError, + for basis in basis_cache.access_list().iter() { + let temp = if let Some (name) = &rec.basis {Some(name)} else {Some(basis)}; + log::info!("accessing {:?}", temp); + match basis_cache.key_read(&mut pddb_os, + &rec.dict, &rec.key, + &mut pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), + // this is a bit inefficient because if a specific basis is specified *and* the key does not exist, + // it'll retry the same basis for a number of times equal to the number of bases open. + // However, usually, there's only 1-2 bases open, and usually, if you specify a basis, + // the key will be a hit, so, we let it stand. + if let Some (name) = &rec.basis {Some(&name)} else {Some(basis)}) { + Ok(readlen) => { + pbuf.len = readlen as u16; + pbuf.retcode = PddbRetcode::Ok; + break; + } + Err(e) => match e.kind() { + std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost, + std::io::ErrorKind::UnexpectedEof => pbuf.retcode = PddbRetcode::UnexpectedEof, + std::io::ErrorKind::OutOfMemory => pbuf.retcode = PddbRetcode::DiskFull, + _ => pbuf.retcode = PddbRetcode::InternalError, + } } } } else { @@ -1149,20 +1160,23 @@ fn main() -> ! { let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance let token = pbuf.token; if let Some(rec) = token_dict.get(&token) { - match basis_cache.key_update(&mut pddb_os, - &rec.dict, &rec.key, - &pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), - rec.alloc_hint, if let Some (name) = &rec.basis {Some(&name)} else {None}, - false - ) { - Ok(_) => { - pbuf.retcode = PddbRetcode::Ok; - } - Err(e) => match e.kind() { - std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost, - std::io::ErrorKind::UnexpectedEof => pbuf.retcode = PddbRetcode::UnexpectedEof, - std::io::ErrorKind::OutOfMemory => pbuf.retcode = PddbRetcode::DiskFull, - _ => pbuf.retcode = PddbRetcode::InternalError, + for basis in basis_cache.access_list().iter() { + match basis_cache.key_update(&mut pddb_os, + &rec.dict, &rec.key, + &pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), + rec.alloc_hint, if let Some (name) = &rec.basis {Some(&name)} else {Some(basis)}, + false + ) { + Ok(_) => { + pbuf.retcode = PddbRetcode::Ok; + break; + } + Err(e) => match e.kind() { + std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost, + std::io::ErrorKind::UnexpectedEof => pbuf.retcode = PddbRetcode::UnexpectedEof, + std::io::ErrorKind::OutOfMemory => pbuf.retcode = PddbRetcode::DiskFull, + _ => pbuf.retcode = PddbRetcode::InternalError, + } } } } else { @@ -1188,6 +1202,7 @@ fn main() -> ! { let mut note = String::from(t!("pddb.menu.listbasis_response", xous::LANG)); for basis in bases.iter() { note.push_str(basis); + note.push_str("\n"); } modals.show_notification(¬e, None).expect("couldn't show basis list"); }, From 9f409fda2d0dfe56b4219a3b87d63d9e9f475e7b Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 26 Jun 2022 03:52:27 +0800 Subject: [PATCH 5/7] fix basis search order issues at least, it passes some simple tests. much more testing is needed. --- apps/vault/src/actions.rs | 48 ++++++++++++++++++++++++++-------- apps/vault/src/main.rs | 1 + apps/vault/src/ux/framework.rs | 6 ++--- services/pddb/src/main.rs | 6 ++++- services/status/src/time.rs | 6 ++--- 5 files changed, 49 insertions(+), 18 deletions(-) diff --git a/apps/vault/src/actions.rs b/apps/vault/src/actions.rs index 5cecdfaeb..45a3851cf 100644 --- a/apps/vault/src/actions.rs +++ b/apps/vault/src/actions.rs @@ -109,11 +109,13 @@ pub(crate) fn start_actions_thread( Some(ActionOp::MenuUnlockBasis) => { manager.activate(); manager.unlock_basis(); + manager.retrieve_db(); manager.deactivate(); }, Some(ActionOp::MenuManageBasis) => { manager.activate(); manager.manage_basis(); + manager.retrieve_db(); manager.deactivate(); } Some(ActionOp::MenuClose) => { @@ -346,10 +348,12 @@ impl ActionManager { Ok(mut data) => { match data.write(&ser) { Ok(len) => log::debug!("wrote {} bytes", len), - Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + Err(e) => {log::error!("internal error"); + self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e))}, } } - Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + Err(e) => { log::error!("internal error"); + self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e))}, } log::debug!("syncing..."); self.pddb.borrow().sync().ok(); @@ -498,23 +502,31 @@ impl ActionManager { pw.notes = edit_data.content()[3].content.as_str().unwrap().to_string(); pw.atime = utc_now().timestamp() as u64; Some(pw) - } else { self.report_err(t!("vault.error.record_error", xous::LANG), None::); None } + } else { log::error!("record error"); + self.report_err(t!("vault.error.record_error", xous::LANG), None::); None } } - Err(e) => { self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)); None } + Err(e) => { log::error!("internal error"); self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)); None } }; maybe_update } Err(e) => { match e.kind() { - std::io::ErrorKind::NotFound => self.report_err(t!("vault.error.not_found", xous::LANG), None::), - _ => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + std::io::ErrorKind::NotFound => { + log::error!("not found"); + self.report_err(t!("vault.error.not_found", xous::LANG), None::) + }, + _ => { + log::error!("internal error"); + self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)) + }, } None } }; if let Some(update) = maybe_update { self.pddb.borrow().delete_key(dict, entry.key_name.as_str().unwrap(), None) - .unwrap_or_else(|e| self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e))); + .unwrap_or_else(|e| {log::error!("internal error"); + self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e))}); match self.pddb.borrow().get( dict, entry.key_name.as_str().unwrap(), None, false, true, Some(VAULT_ALLOC_HINT), @@ -524,9 +536,13 @@ impl ActionManager { let ser = serialize_password(&update); record.write(&ser) .unwrap_or_else(|e| { + log::error!("internal error"); self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)); 0}); } - Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + Err(e) => { + log::error!("internal error"); + self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)) + }, } } self.pddb.borrow().sync().ok(); @@ -695,7 +711,10 @@ impl ActionManager { std::io::ErrorKind::NotFound => { log::debug!("Password dictionary not yet created"); } - _ => self.report_err("Dictionary error accessing password database", Some(e)), + _ => { + log::error!("Dictionary error accessing password database"); + self.report_err("Dictionary error accessing password database", Some(e)) + }, } Vec::new() } @@ -727,13 +746,20 @@ impl ActionManager { }; il.push(li); } else { + log::error!("Couldn't deserialize password"); self.report_err("Couldn't deserialize password:", Some(key)); } } - Err(e) => self.report_err("Couldn't access password key", Some(e)), + Err(e) => { + log::error!("Couldn't access password key"); + self.report_err("Couldn't access password key", Some(e)) + }, } } - Err(e) => self.report_err("Couldn't access password key", Some(e)), + Err(e) => { + log::error!("Couldn't access password key"); + self.report_err("Couldn't access password key", Some(e)) + }, } } } diff --git a/apps/vault/src/main.rs b/apps/vault/src/main.rs index aba11fea1..cc3b656ce 100644 --- a/apps/vault/src/main.rs +++ b/apps/vault/src/main.rs @@ -471,6 +471,7 @@ fn check_user_presence(_cid: ChannelID) -> Result<(), Ctap2StatusCode> { } pub(crate) fn basis_change() { + log::info!("got basis change"); xous::send_message(SELF_CONN.load(Ordering::SeqCst), Message::new_scalar(VaultOp::BasisChange.to_usize().unwrap(), 0, 0, 0, 0) ).unwrap(); diff --git a/apps/vault/src/ux/framework.rs b/apps/vault/src/ux/framework.rs index d780fb412..257592d4a 100644 --- a/apps/vault/src/ux/framework.rs +++ b/apps/vault/src/ux/framework.rs @@ -238,7 +238,7 @@ impl VaultUx { let style = match self.pddb.borrow().get( VAULT_CONFIG_DICT, VAULT_CONFIG_KEY_FONT, - None, true, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), true, true, Some(32), Some(crate::basis_change) ) { Ok(mut style_key) => { @@ -269,13 +269,13 @@ impl VaultUx { self.items_per_screen = available_height / self.item_height; } pub(crate) fn set_glyph_style(&mut self, style: GlyphStyle) { - self.pddb.borrow().delete_key(VAULT_CONFIG_DICT, VAULT_CONFIG_KEY_FONT, None) + 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, - None, true, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), true, true, Some(32), Some(crate::basis_change) ) { Ok(mut style_key) => { diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index 98fac8e2e..8f0978af5 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -789,6 +789,7 @@ fn main() -> ! { }; let dict = req.dict.as_str().expect("dict utf-8 decode error"); let key = req.key.as_str().expect("key utf-8 decode error"); + log::info!("get: {:?} {}", bname, key); if basis_cache.dict_attributes(&mut pddb_os, dict, bname).is_err() { if req.create_dict { match basis_cache.dict_add(&mut pddb_os, dict, bname) { @@ -848,6 +849,7 @@ fn main() -> ! { req.token = Some(token); req.result = PddbRequestCode::NoErr; buffer.replace(req).unwrap(); + break; // if we got here, entry was found, stop searching } } Some(Opcode::KeyDrop) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, _, { @@ -1128,7 +1130,7 @@ fn main() -> ! { if let Some(rec) = token_dict.get(&token) { for basis in basis_cache.access_list().iter() { let temp = if let Some (name) = &rec.basis {Some(name)} else {Some(basis)}; - log::info!("accessing {:?}", temp); + log::info!("read (spec: {:?}){:?} {}", rec.basis, temp, rec.key); match basis_cache.key_read(&mut pddb_os, &rec.dict, &rec.key, &mut pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), @@ -1161,6 +1163,8 @@ fn main() -> ! { let token = pbuf.token; if let Some(rec) = token_dict.get(&token) { for basis in basis_cache.access_list().iter() { + let temp = if let Some (name) = &rec.basis {Some(name)} else {Some(basis)}; + log::info!("write (spec: {:?}){:?} {}", rec.basis, temp, rec.key); match basis_cache.key_update(&mut pddb_os, &rec.dict, &rec.key, &pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), diff --git a/services/status/src/time.rs b/services/status/src/time.rs index c1afbd9fe..ffc850950 100644 --- a/services/status/src/time.rs +++ b/services/status/src/time.rs @@ -245,7 +245,7 @@ pub fn start_time_server() { let mut offset_key = offset_handle.get( TIME_SERVER_DICT, TIME_SERVER_UTC_OFFSET, - None, true, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), true, true, Some(8), None:: ).expect("couldn't open UTC offset key"); @@ -253,7 +253,7 @@ pub fn start_time_server() { let mut tz_key = tz_handle.get( TIME_SERVER_DICT, TIME_SERVER_TZ_OFFSET, - None, true, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), true, true, Some(8), None:: ).expect("couldn't open TZ offset key"); @@ -532,7 +532,7 @@ pub fn start_time_ux(sid: xous::SID) { let maybe_tz_set_key = tz_set_handle.get( TIME_SERVER_DICT, TIME_SERVER_TZ_OFFSET, - None, false, false, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, false, None, None:: ).ok(); From 88ea0145daf02a2f80421f933b93546952023c8d Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 26 Jun 2022 03:55:26 +0800 Subject: [PATCH 6/7] clean up some debug spew --- services/pddb/src/main.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index 8f0978af5..107c6e123 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -789,7 +789,7 @@ fn main() -> ! { }; let dict = req.dict.as_str().expect("dict utf-8 decode error"); let key = req.key.as_str().expect("key utf-8 decode error"); - log::info!("get: {:?} {}", bname, key); + log::debug!("get: {:?} {}", bname, key); if basis_cache.dict_attributes(&mut pddb_os, dict, bname).is_err() { if req.create_dict { match basis_cache.dict_add(&mut pddb_os, dict, bname) { @@ -1130,7 +1130,7 @@ fn main() -> ! { if let Some(rec) = token_dict.get(&token) { for basis in basis_cache.access_list().iter() { let temp = if let Some (name) = &rec.basis {Some(name)} else {Some(basis)}; - log::info!("read (spec: {:?}){:?} {}", rec.basis, temp, rec.key); + log::debug!("read (spec: {:?}){:?} {}", rec.basis, temp, rec.key); match basis_cache.key_read(&mut pddb_os, &rec.dict, &rec.key, &mut pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), @@ -1164,7 +1164,7 @@ fn main() -> ! { if let Some(rec) = token_dict.get(&token) { for basis in basis_cache.access_list().iter() { let temp = if let Some (name) = &rec.basis {Some(name)} else {Some(basis)}; - log::info!("write (spec: {:?}){:?} {}", rec.basis, temp, rec.key); + log::debug!("write (spec: {:?}){:?} {}", rec.basis, temp, rec.key); match basis_cache.key_update(&mut pddb_os, &rec.dict, &rec.key, &pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), From 42b84ad890191a3dfdb0071efd904eda7fbdc708 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 26 Jun 2022 14:25:54 +0800 Subject: [PATCH 7/7] adjust some of the default basis references in OpenSK storage implementation These adjustments ideally make the system less confusing to use in the face of secret Bases, but the spec calls for some information that could be a leakage channel (see below). - items that are assumed to be consistent regardless of the basis are now forced into the System basis. This reduces potentially confusing behavior if the system has han unlocked secret basis and things like PIN hashes are set which appear to be global. - There is a "global signature counter" which could leak some information about how many credentials are in the device. However, the FIDO2 spec enforces some plausible deniability by requiring that the counter increments by a random value instead of by 1. In the OpenSK implementation, this increments by a random integer from 1-8. So, if you store dozens of credentials in secret bases, it may become less deniable due to this global signature counter. The global signature counter seems optional, so maybe that is a feature to be stripped out... --- apps/vault/src/ctap/storage.rs | 82 ++++++++++++++++++---------------- apps/vault/src/main.rs | 4 ++ 2 files changed, 47 insertions(+), 39 deletions(-) diff --git a/apps/vault/src/ctap/storage.rs b/apps/vault/src/ctap/storage.rs index b340990f5..0bc97a524 100644 --- a/apps/vault/src/ctap/storage.rs +++ b/apps/vault/src/ctap/storage.rs @@ -129,7 +129,7 @@ impl PersistentStore { match self.pddb.borrow().get( FIDO_DICT, key::MASTER_KEYS, - None, true, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), true, true, Some(64), Some(crate::basis_change) ) { Ok(mut master_keys) => { @@ -152,7 +152,7 @@ impl PersistentStore { match self.pddb.borrow().get( FIDO_DICT, key::CRED_RANDOM_SECRET, - None, true, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), true, true, Some(64), Some(crate::basis_change) ) { Ok(mut cred_random) => { @@ -174,7 +174,7 @@ impl PersistentStore { match self.pddb.borrow().get( FIDO_PERSISTENT_DICT, key::AAGUID, - None, true, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), true, true, Some(16), Some(crate::basis_change) ) { Ok(mut aaguid) => { @@ -220,7 +220,7 @@ impl PersistentStore { match self.pddb.borrow().get( FIDO_PERSISTENT_DICT, key::ATTESTATION_PRIVATE_KEY, - None, true, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), true, true, Some(32), Some(crate::basis_change) ) { Ok(mut aapriv) => { @@ -244,7 +244,7 @@ impl PersistentStore { match self.pddb.borrow().get( FIDO_PERSISTENT_DICT, key::ATTESTATION_CERTIFICATE, - None, true, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), true, true, Some(512), Some(crate::basis_change) ) { Ok(mut cert) => { @@ -516,7 +516,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::GLOBAL_SIGNATURE_COUNTER, - None, false, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, true, Some(4), Some(crate::basis_change) ) { Ok(mut gsc) => { @@ -546,7 +546,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::GLOBAL_SIGNATURE_COUNTER, - None, false, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, true, Some(4), Some(crate::basis_change) ) { Ok(mut gsc) => { @@ -565,7 +565,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::MASTER_KEYS, - None, false, false, None, Some(crate::basis_change) + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, false, None, Some(crate::basis_change) ) { Ok(mut mk) => { let mut master_keys = [0u8; 64]; @@ -588,7 +588,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::CRED_RANDOM_SECRET, - None, false, false, None, Some(crate::basis_change) + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, false, None, Some(crate::basis_change) ) { Ok(mut crs) => { let mut cred_random_secret = [0u8; 64]; @@ -609,7 +609,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::PIN_HASH, - None, false, false, None, Some(crate::basis_change) + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, false, None, Some(crate::basis_change) ) { Ok(mut ph) => { let mut pin_hash = [0u8; PIN_AUTH_LENGTH]; @@ -648,7 +648,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::PIN_HASH, - None, false, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, true, Some(PIN_AUTH_LENGTH), Some(crate::basis_change) ) { Ok(mut ph) => { @@ -677,7 +677,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::PIN_RETRIES, - None, false, false, None, Some(crate::basis_change) + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, false, None, Some(crate::basis_change) ) { Ok(mut pr) => { let mut value = [0u8; 1]; @@ -701,7 +701,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::PIN_RETRIES, - None, false, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, true, Some(1), Some(crate::basis_change) ) { Ok(mut pr) => { @@ -721,7 +721,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().delete_key( FIDO_DICT, PIN_RETRIES, - None + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS) ) { Ok(_) => Ok(()), Err(e) => match e.kind() { @@ -737,7 +737,8 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::MIN_PIN_LENGTH, - None, false, false, None, Some(crate::basis_change) + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), + false, false, None, Some(crate::basis_change) ) { Ok(mut pr) => { let mut value = [0u8; 1]; @@ -759,7 +760,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::MIN_PIN_LENGTH, - None, false, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, true, Some(1), Some(crate::basis_change) ) { Ok(mut pl) => { @@ -779,7 +780,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem if let Some(mut mplri) = self.pddb.borrow().get( FIDO_DICT, key::_MIN_PIN_LENGTH_RP_IDS, - None, false, false, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, false, None, Some(crate::basis_change) ).ok() { let mut data = Vec::::new(); @@ -812,7 +813,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_DICT, key::_MIN_PIN_LENGTH_RP_IDS, - None, false, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, true, Some(_MAX_RP_IDS_LENGTH), Some(crate::basis_change) ) { Ok(mut mrpli) => { @@ -831,7 +832,8 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_PERSISTENT_DICT, key::ATTESTATION_PRIVATE_KEY, - None, false, false, None, Some(crate::basis_change) + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, false, + None, Some(crate::basis_change) ) { Ok(mut apk) => { let mut key = [0u8; key_material::ATTESTATION_PRIVATE_KEY_LENGTH]; @@ -863,7 +865,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_PERSISTENT_DICT, key::ATTESTATION_PRIVATE_KEY, - None, false, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, true, Some(key_material::ATTESTATION_PRIVATE_KEY_LENGTH), Some(crate::basis_change) ) { Ok(mut apk) => { @@ -882,7 +884,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem if let Some(mut acert) = self.pddb.borrow().get( FIDO_PERSISTENT_DICT, key::ATTESTATION_CERTIFICATE, - None, false, false, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, false, None, Some(crate::basis_change) ).ok() { let mut data = Vec::::new(); @@ -907,7 +909,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_PERSISTENT_DICT, key::ATTESTATION_CERTIFICATE, - None, false, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, true, Some(1024), Some(crate::basis_change) ) { Ok(mut acert) => { @@ -926,7 +928,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem if let Some(mut guid) = self.pddb.borrow().get( FIDO_PERSISTENT_DICT, key::AAGUID, - None, false, false, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, false, None, Some(crate::basis_change) ).ok() { let mut data = [0u8; key_material::AAGUID_LENGTH]; @@ -952,7 +954,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_PERSISTENT_DICT, key::AAGUID, - None, false, true, + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), false, true, Some(key_material::AAGUID_LENGTH), Some(crate::basis_change) ) { Ok(mut guid) => { @@ -970,27 +972,29 @@ openssl asn1parse -in opensk_cert.pem -inform pem /// /// In particular persistent entries are not reset. pub fn reset(&mut self, _rng: &mut impl Rng256) -> Result<(), Ctap2StatusCode> { - match self.pddb.borrow().delete_dict(FIDO_DICT, None) { - Err(e) => match e.kind() { - std::io::ErrorKind::NotFound => Ok(()), - _ => Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR), // PDDB internal error - } - Ok(_) => Ok(()), - }?; - match self.pddb.borrow().delete_dict(FIDO_CRED_DICT, None) { - Err(e) => match e.kind() { - std::io::ErrorKind::NotFound => Ok(()), - _ => Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR), // PDDB internal error - } - Ok(_) => Ok(()), - }?; - match self.pddb.borrow().delete_dict(crate::fido::U2F_APP_DICT, None) { + match self.pddb.borrow().delete_dict(FIDO_DICT, Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS)) { Err(e) => match e.kind() { std::io::ErrorKind::NotFound => Ok(()), _ => Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR), // PDDB internal error } Ok(_) => Ok(()), }?; + for basis in self.pddb.borrow().list_basis().iter () { + match self.pddb.borrow().delete_dict(FIDO_CRED_DICT, Some(basis)) { + Err(e) => match e.kind() { + std::io::ErrorKind::NotFound => Ok(()), + _ => Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR), // PDDB internal error + } + Ok(_) => Ok(()), + }?; + match self.pddb.borrow().delete_dict(crate::fido::U2F_APP_DICT, Some(basis)) { + Err(e) => match e.kind() { + std::io::ErrorKind::NotFound => Ok(()), + _ => Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR), // PDDB internal error + } + Ok(_) => Ok(()), + }?; + } // don't delete the persistent dictionary... self.init()?; Ok(()) diff --git a/apps/vault/src/main.rs b/apps/vault/src/main.rs index cc3b656ce..eec47bff9 100644 --- a/apps/vault/src/main.rs +++ b/apps/vault/src/main.rs @@ -107,6 +107,10 @@ To clear test entries: pddb dictdelete vault.totp pddb dictdelete fido.cred pddb dictdelete fido.u2fapps + +Issue: editing an entry in a non-secret basis while a secret basis is open won't work because +the delete key function doesn't work in that case. Need to modify the `get` routine to return +the basis so we can specify which basis to edit... */ #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]