diff --git a/apps-baosec/vault2/Cargo.toml b/apps-baosec/vault2/Cargo.toml index 277cf954d..dde095ffc 100644 --- a/apps-baosec/vault2/Cargo.toml +++ b/apps-baosec/vault2/Cargo.toml @@ -48,6 +48,7 @@ chrono = { version = "0.4.33", default-features = false, features = ["std"] } # password generation passwords = "3.1.9" +random-pick = { version = "1.2.15" } # totp sha1 = "0.10.6" @@ -59,8 +60,6 @@ sntpc = { version = "0.3.1" } # net = { path = "../../services/net" } # com_rs = { git = "https://github.com/betrusted-io/com_rs", rev = "891bdd3ca8e41f81510d112483e178aea3e3a921" } -# testing -random-pick = { version = "1.2.15", optional = true } [dev-dependencies] enum-iterator = "0.6.0" @@ -88,7 +87,7 @@ fuzz = [] debug_ctap = [] autotest = [] multireset = [] # allows credential reset more than once per boot -vault-testing = ["random-pick"] +vault-testing = [] 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 = [ diff --git a/apps-baosec/vault2/locales/i18n.json b/apps-baosec/vault2/locales/i18n.json index 74a0547a4..e4a43d170 100644 --- a/apps-baosec/vault2/locales/i18n.json +++ b/apps-baosec/vault2/locales/i18n.json @@ -1,4 +1,11 @@ { + "vault.add_new": { + "en": "", + "en-tts": "", + "fr": "", + "ja": "<新規追加…>", + "zh": "<新增…>" + }, "vault.autotyping": { "en": "Autotyping...", "en-tts": "Autotyping...", @@ -69,6 +76,13 @@ "ja": "パスワードフィールドはBIP39としてエンコードできません。", "zh": "密码字段不可编码为 BIP39。" }, + "vault.cancel": { + "en": "Cancel", + "en-tts": "Cancel", + "fr": "Annuler", + "ja": "キャンセル", + "zh": "取消" + }, "vault.completed": { "en": "Operation completed.", "en-tts": "Operation completed.", @@ -76,12 +90,26 @@ "ja": "操作が完了しました.", "zh": "操作完成." }, + "vault.configure": { + "en": "Configure", + "en-tts": "Configure", + "fr": "Configurer", + "ja": "設定する", + "zh": "配置" + }, "vault.delete.confirm": { - "en": "Confirm entry deletion: ", - "en-tts": "Confirm entry deletion: ", - "fr": "Confirmer la suppression des entrée: ", - "ja": "エントリの削除を確認する: ", - "zh": "确认条目删除: " + "en": "Delete?", + "en-tts": "Delete?", + "fr": "Supprimer?", + "ja": "削除しますか?", + "zh": "删除?" + }, + "vault.edit": { + "en": "Edit", + "en-tts": "Edit", + "fr": "Modifier", + "ja": "編集", + "zh": "编辑" }, "vault.edit_dialog": { "en": "Make your changes and press enter.\nUse the d-pad to navigate entries.", @@ -223,6 +251,13 @@ "ja": "FIDOホストがPINを作成しています。\n任意のキーを押して受け入れます。", "zh": "FIDO 主机正在创建 PIN。\n按任意键接受。" }, + "vault.generated": { + "en": "Generated", + "en-tts": "Generated", + "fr": "Généré", + "ja": "生成済み", + "zh": "已生成" + }, "vault.hotp.count": { "en": "Please enter the initial HOTP count:", "en-tts": "Please enter the initial HOTP count:", @@ -258,6 +293,13 @@ "ja": "共有秘密は無効ですBase32", "zh": "共享密钥无效 Base32" }, + "vault.length": { + "en": "Length", + "en-tts": "Length", + "fr": "Longueur", + "ja": "長さ", + "zh": "长度" + }, "vault.menu_addnew": { "en": "Add new item", "en-tts": "Add new item", @@ -392,9 +434,9 @@ "zh": "这是哪种类型的 OTP 记录(如果您不知道,可能是 TOTP)?" }, "vault.newitem.lowercase": { - "en": "Lowercase letters", - "en-tts": "Lowercase letters", - "fr": "Lettres minuscules", + "en": "Lowercase", + "en-tts": "Lowercase", + "fr": "Minuscules", "ja": "小文字", "zh": "小写字母" }, @@ -426,6 +468,13 @@ "ja": "シンボル", "zh": "符号" }, + "vault.newitem.symbols_customize": { + "en": "Edit symbols", + "en-tts": "Edit symbols", + "fr": "Modifier symboles", + "ja": "記号を編集", + "zh": "编辑符号" + }, "vault.newitem.totp": { "en": "TOTP", "en-tts": "TOTP", @@ -441,9 +490,9 @@ "zh": "在 Base32 中输入 OTP 共享密钥:" }, "vault.newitem.uppercase": { - "en": "Uppercase letters", - "en-tts": "Uppercase letters", - "fr": "Lettres majuscules", + "en": "Uppercase", + "en-tts": "Uppercase", + "fr": "Majuscules", "ja": "大文字", "zh": "大写字母" }, @@ -475,6 +524,13 @@ "ja": "ノート", "zh": "笔录" }, + "vault.pw.approval": { + "en": "Use", + "en-tts": "Use", + "fr": "Utiliser", + "ja": "使用", + "zh": "使用" + }, "vault.readout_active": { "en": "🔓Readout mode active.🔓\n\nHost is permitted to read and write unlocked records.\n\nPlease run your host scripts, then press any key to restore security.", "en-tts": "Readout mode active.\n\nHost is permitted to read and write unlocked records.\n\nPlease run your host scripts, then press any key to restore security.", @@ -503,6 +559,20 @@ "ja": "フォントを選択する", "zh": "选择字体" }, + "vault.use": { + "en": "Use", + "en-tts": "Use", + "fr": "Utiliser", + "ja": "使用", + "zh": "使用" + }, + "vault.username": { + "en": "Username", + "en-tts": "Username", + "fr": "Nom d’utilisateur", + "ja": "ユーザー名", + "zh": "用户名" + }, "vault.u2f.appinfo.authcount": { "en": "Uses: ", "en-tts": "Uses: ", diff --git a/apps-baosec/vault2/src/actions.rs b/apps-baosec/vault2/src/actions.rs index 41317f46d..13fc9a535 100644 --- a/apps-baosec/vault2/src/actions.rs +++ b/apps-baosec/vault2/src/actions.rs @@ -2,11 +2,12 @@ use core::convert::TryFrom; use std::cell::RefCell; use std::io::ErrorKind; use std::io::Write; +use std::path::Path; use std::sync::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, }; -use std::time::SystemTime; +use std::{fs::File, io, io::BufRead}; #[cfg(feature = "hosted-baosec")] use bao1x_emu::trng::Trng; @@ -20,12 +21,12 @@ use num_traits::*; use passwords::PasswordGenerator; use pddb::BasisRetentionPolicy; use ux_api::widgets::TextEntryPayload; -use vault2::{ - AppInfo, VAULT_ALLOC_HINT, VAULT_PASSWORD_DICT, VAULT_TOTP_DICT, atime_to_str, basis_change, - deserialize_app_info, serialize_app_info, utc_now, -}; +use vault2::{VAULT_PASSWORD_DICT, VAULT_TOTP_DICT, atime_to_str, utc_now}; use xous::{Message, send_message}; +use crate::VAULT_CONFIG_GENERATOR; +use crate::VAULT_CONFIG_USERNAMES; +use crate::generator::*; use crate::storage::{self, PasswordRecord, StorageContent}; use crate::totp::TotpAlgorithm; use crate::{ItemLists, SelectedEntry, VaultMode}; @@ -79,6 +80,8 @@ pub struct ActionManager { gfx: ux_api::service::gfx::Gfx, // used to set time when QR codes are scanned rtc_conn: xous::CID, + // used to type passwords + usb_dev: usb_bao1x::UsbHid, } impl ActionManager { pub fn new( @@ -111,6 +114,7 @@ impl ActionManager { keystore: Keystore::new(&xns), gfx: ux_api::service::gfx::Gfx::new(&xns).unwrap(), rtc_conn, + usb_dev: usb_bao1x::UsbHid::new(), } } @@ -136,6 +140,225 @@ impl ActionManager { .ok(); } + /// This will create a password for `url`, associating it with a `username`. Returns an Option<&str> + /// if the user selects to immediately use the password. + pub(crate) fn add_password(&mut self, url: &str) -> Result { + // 1. Pick or enter a username from the username list. The list always has an entry for , + // which prompts a user to enter a new one, and save it to the list. + // 2. Present a default password using standard parameters. Options are "Use", "Edit", "Configure", + // "Cancel" + // 3. Configure will present options of: length -> use [numbers, uppercase, lowercase, specials] -> if + // specials + // is selected, a checkbox list of which specials, with the "safe set" selected. These options are + // remembered and applied next time the password generator is run. + // 4. "Use" will save the password, and then type it + // 5. "Edit" will go to the standard text editing method + // 6. "Cancel" just returns None, and makes no changes to anything. + + let mut usernames: Vec = if let Ok(file) = File::open(VAULT_CONFIG_USERNAMES) { + let reader = std::io::BufReader::new(file); + reader.lines().collect::>>().map_err(|_| "Can't read usernames")? + } else { + // Create new file and write default content + std::fs::create_dir_all(Path::new(VAULT_CONFIG_USERNAMES).parent().unwrap()).unwrap(); + let mut file = File::create(VAULT_CONFIG_USERNAMES).unwrap(); + file.write_all("".as_bytes()).unwrap(); + Vec::new() + }; + + let username = { + let mut usernames_refs: Vec<&str> = usernames.iter().map(AsRef::as_ref).collect(); + usernames_refs.push(t!("vault.add_new", locales::LANG)); + self.modals.add_list(usernames_refs).unwrap(); + match self.modals.get_radiobutton(t!("vault.username", locales::LANG)) { + Ok(response) => { + if response == t!("vault.add_new", locales::LANG) { + let new_username = &self + .modals + .alert_builder("") + .field(None, None) + .build() + .map_err(|e| format!("Error entering username: {:?}", e))? + .content()[0] + .content; + usernames.push(new_username.to_owned()); + let mut file = File::create(VAULT_CONFIG_USERNAMES) + .map_err(|e| format!("Couldn't open usernames file for writing: {:?}", e))?; + for username in usernames { + writeln!(file, "{}", username) + .map_err(|e| format!("Couldn't write username: {:?}", e))?; + } + new_username.to_owned() + } else { + response + } + } + Err(e) => return Err(format!("Error selecting user: {:?}", e)), + } + }; + + let mut generator_modified = false; + let mut generator_config: GeneratorConfig = if let Ok(file) = File::open(VAULT_CONFIG_GENERATOR) { + GeneratorConfig::deserialize(file).unwrap_or(GeneratorConfig::default()) + } else { + generator_modified = true; + GeneratorConfig::default() + }; + let mut pw: Option = None; + loop { + let pools = generator_config.to_pools(); + if pw.is_none() { + pw = Some(generate(&pools, generator_config.length, true)); + } + let password_options = vec![ + t!("vault.pw.approval", locales::LANG), + t!("vault.edit", locales::LANG), + t!("vault.configure", locales::LANG), + t!("vault.cancel", locales::LANG), + ]; + self.modals.add_list(password_options).unwrap(); + match self.modals.get_radiobutton(&format!( + "{}:\n{}", + t!("vault.generated", locales::LANG), + &pw.as_ref().unwrap() + )) { + Ok(response) => { + if response == t!("vault.pw.approval", locales::LANG) { + break; + } else if response == t!("vault.edit", locales::LANG) { + let new_pw = &self + .modals + .alert_builder("") + .field(pw, Some(password_validator)) + .build() + .map_err(|e| format!("Error editing password: {:?}", e))? + .content()[0] + .content; + pw = Some(if new_pw.len() > 0 { + new_pw.clone() + } else { + // empty password is shortcut to regenerate from scratch + generate(&pools, generator_config.length, true) + }); + } else if response == t!("vault.configure", locales::LANG) { + pw.take(); + generator_modified = true; + let mut modified_config = generator_config.clone(); + // get length + generator_config.length = usize::from_str_radix( + self.modals + .alert_builder(t!("vault.length", locales::LANG)) + .field(Some(generator_config.length.to_string()), Some(length_validator)) + .build() + .map_err(|e| format!("Error getting length: {:?}", e))? + .content()[0] + .as_str(), + 10, + ) + .unwrap_or(crate::generator::DEFAULT_LENGTH); + // configure character sets + let config_options = vec![ + (modified_config.lower, t!("vault.newitem.lowercase", locales::LANG)), + (modified_config.upper, t!("vault.newitem.uppercase", locales::LANG)), + (modified_config.numbers, t!("vault.newitem.numbers", locales::LANG)), + (modified_config.use_symbols, t!("vault.newitem.symbols", locales::LANG)), + (false, t!("vault.newitem.symbols_customize", locales::LANG)), + ]; + self.modals.add_stateful_list(config_options).unwrap(); + match self.modals.get_checkbox(&format!("{}:", t!("vault.use", locales::LANG))) { + Ok(options) => { + let mut modify_symbols = false; + for option in options { + if option == t!("vault.newitem.lowercase", locales::LANG) { + modified_config.lower = true; + } else if option == t!("vault.newitem.uppercase", locales::LANG) { + modified_config.upper = true; + } else if option == t!("vault.newitem.numbers", locales::LANG) { + modified_config.numbers = true; + } else if option == t!("vault.newitem.symbols", locales::LANG) { + modified_config.use_symbols = true; + } else if option == t!("vault.newitem.symbols_customize", locales::LANG) { + modify_symbols = true; + } + } + if modify_symbols { + let mut symbol_states = Vec::<(bool, &str)>::new(); + let symbols_str: Vec = + SYMBOLS_ALL.iter().map(|c| c.to_string()).collect(); + log::info!("config: {:?}", modified_config); + for (&state, sym) in + modified_config.symbols.iter().zip(symbols_str.iter()) + { + symbol_states.push((state, sym)) + } + log::info!("states: {:?}", symbol_states); + self.modals.add_stateful_list(symbol_states).unwrap(); + let new_states = self + .modals + .get_checkbox(&format!("{}:", t!("vault.use", locales::LANG))) + .map_err(|e| format!("Can't get symbol list: {:?}", e))?; + log::info!("new states: {:?}", new_states); + for (new_state, sym) in + modified_config.symbols.iter_mut().zip(symbols_str.iter()) + { + *new_state = new_states.contains(sym); + } + log::info!("updated list: {:?}", modified_config); + } + if !modified_config.lower + && !modified_config.upper + && !modified_config.numbers + && !modified_config.use_symbols + { + log::warn!( + "Invalid generator config - nothing selected. Going back to previous config." + ); + generator_modified = false; + } else { + generator_config = modified_config; + } + } + Err(e) => return Err(format!("Couldn't get options: {:?}", e)), + } + log::info!("leaving config with modified: {:?}", generator_modified); + } else { + return Err("Operation canceled by user".to_string()); + } + } + Err(e) => return Err(format!("Couldn't get password approval: {:?}", e)), + } + } + // create password from url/username/pw tuple + let now = crate::utc_now().timestamp() as u64; + let mut record = storage::PasswordRecord { + version: VAULT_PASSWORD_REC_VERSION, + description: url.to_string(), + username, + password: pw.as_ref().unwrap().to_owned(), + notes: t!("vault.notes", locales::LANG).to_string(), + ctime: now, + atime: now, + count: 1, + }; + // store & update UI + self.storage + .borrow_mut() + .new_record(&mut record, None, true) + .map_err(|e| format!("Couldn't write record: {:?}", e))?; // update the ux cache + let li = make_pw_item_from_record(&storage::hex(record.hash()), record); + self.item_lists.lock().unwrap().insert_unique(self.mode_cache, li); + // update generator if modified + if generator_modified { + // Create new file and write configuration content + let file = File::create(VAULT_CONFIG_GENERATOR).unwrap(); + log::info!("serializing generator: {:?}", generator_config); + generator_config + .serialize(file) + .map_err(|e| format!("Error saving generator config: {:?}", e))?; + } + Ok(pw.unwrap()) + } + /// This routine is now required to update the itemlist data as well as the PDDB to save on /// a full retrieve of the db. pub(crate) fn menu_addnew(&mut self) { @@ -905,7 +1128,7 @@ impl ActionManager { if prev_entry.atime != pw_rec.atime || prev_entry.count != pw_rec.count { - write!(extra, "[{}]", pw_rec.count).ok(); + write!(extra, "{}", pw_rec.username).ok(); prev_entry.extra.clear(); prev_entry.extra.push_str(&extra); } @@ -918,8 +1141,10 @@ impl ActionManager { prev_entry.guid.clear(); prev_entry.guid.push_str(&key.name); } + prev_entry.atime = pw_rec.atime; + prev_entry.count = pw_rec.count; } else { - write!(extra, "[{}]", pw_rec.count).ok(); + write!(extra, "{}", pw_rec.username).ok(); let li = ListItem::new( desc.to_string(), /* these allocs will be slow, but we do it * only once on boot */ @@ -1096,7 +1321,98 @@ impl ActionManager { // now try to lookup the password; if it does not exist, offer // to create a password - // TODO: left off here + // Password lookup has to search all the entries in sequence + // for a match. + // + // Then, we need to disambiguate records that may have more + // than one username + // associated with them. + let mut matches = self + .item_lists + .lock() + .unwrap() + .find_by_name(VaultMode::Password, url); + if matches.len() == 0 { + // try removing "www." as manually entered passwords tend + // to lack this + let base_matches = + self.item_lists.lock().unwrap().find_by_name( + VaultMode::Password, + url.strip_prefix("www.").unwrap_or(url), + ); + matches.extend_from_slice(&base_matches); + } + if matches.len() == 0 { + match self.add_password(url) { + Ok(pw) => { + self.usb_dev.send_str(&pw).ok(); + } + Err(e) => { + log::error!( + "add_password failed with error {:?}", + e + ); + } + } + } else if matches.len() == 1 { + // directly ask if it should be typed + let mut pw: storage::PasswordRecord = self + .storage + .borrow() + .get_record( + &storage::ContentKind::Password, + &matches[0].guid, + ) + .expect( + "entry should exist if it is in the item list", + ); + if self.yes_no_approval(&format!( + "{} {}?", + t!("vault.pw.approval", locales::LANG), + url + )) { + self.usb_dev.send_str(&pw.password).ok(); + self.increment_pw_usage(&matches[0].guid, &mut pw); + } + } else { + // disambiguate which item to type + let mut names: Vec<&str> = + matches.iter().map(|item| item.name()).collect(); + // add a cancel option, in case none of the options look + // correct + names.push(t!("vault.cancel", locales::LANG)); + self.modals.add_list(names).unwrap(); + match self + .modals + .get_radiobutton(t!("vault.username", locales::LANG)) + { + Ok(response) => { + if response != t!("vault.cancel", locales::LANG) { + if let Some(entry) = matches + .iter() + .find(|&item| item.extra() == &response) + { + let mut pw: storage::PasswordRecord = self + .storage + .borrow() + .get_record( + &storage::ContentKind::Password, + &entry.guid, + ) + .expect( + "entry should exist if it is in the item list", + ); + self.usb_dev.send_str(&pw.password).ok(); + self.increment_pw_usage( + &entry.guid, + &mut pw, + ); + } + } + } + _ => (), + } + } } } "new" => { @@ -1133,6 +1449,12 @@ impl ActionManager { } } + pub fn increment_pw_usage(&self, guid: &str, pw: &mut storage::PasswordRecord) { + pw.count += 1; + pw.atime = crate::utc_now().timestamp() as u64; + self.storage.borrow_mut().update(&storage::ContentKind::Password, guid, pw).unwrap(); + } + pub(crate) fn set_time(&self, time_str: &str) { match DateTime::parse_from_rfc3339(time_str) { Ok(datetime) => { @@ -1512,11 +1834,11 @@ pub(crate) fn heap_usage() -> usize { } } -fn make_pw_name(description: &str, username: &str, dest: &mut String) { +fn make_pw_name(description: &str, _username: &str, dest: &mut String) { dest.clear(); dest.push_str(description); - dest.push_str("/"); - dest.push_str(username); + // dest.push_str("/"); + // dest.push_str(username); } fn make_totp_item_from_record(guid: &str, totp: TotpRecord) -> ListItem { diff --git a/apps-baosec/vault2/src/generator.rs b/apps-baosec/vault2/src/generator.rs new file mode 100644 index 000000000..5f75f6caf --- /dev/null +++ b/apps-baosec/vault2/src/generator.rs @@ -0,0 +1,177 @@ +// Based on code from `passwords` 3.1.16 crate (MIT License, Ron Li ) +// +// Reason for vendoring: needed to modify the algorithm to select *which* special characters are +// allowed. The reference implementation picks from a static const array of special characters. + +use std::fs::File; +use std::io::{self, BufRead, BufReader, Write}; + +pub const DEFAULT_LENGTH: usize = 18; + +static NUMBERS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; + +static LOWERCASE_LETTERS: [char; 26] = [ + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', + 'v', 'w', 'x', 'y', 'z', +]; + +static UPPERCASE_LETTERS: [char; 26] = [ + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', + 'V', 'W', 'X', 'Y', 'Z', +]; + +// All symbols we could allow. Ordered from most likely to least likely to be allowed by banks. +// Ironically, it's the banks that have the most restrictions on special charactters +pub static SYMBOLS_ALL: [char; 32] = [ + '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '?', ',', '.', ':', ';', '[', ']', + '{', '|', '}', '/', '\'', '"', '\\', '<', '>', '`', '~', +]; + +#[rustfmt::skip] +// First 8 symbols are the most likely to be allowed, so mark them by default as the set to be included. +const SYMBOLS_DEFAULT_ALLOW: [bool; 32] = [ + true, true, true, true, true, true, true, true, + false, false, false, false, false, false, false, false, + false, false, false, false, false, false, false, false, + false, false, false, false, false, false, false, false, +]; + +#[derive(Copy, Clone, Debug)] +pub struct GeneratorConfig { + pub length: usize, + pub numbers: bool, + pub upper: bool, + pub lower: bool, + pub use_symbols: bool, + pub symbols: [bool; 32], +} +impl GeneratorConfig { + pub fn default() -> Self { + GeneratorConfig { + length: DEFAULT_LENGTH, + numbers: true, + upper: true, + lower: true, + use_symbols: true, + symbols: SYMBOLS_DEFAULT_ALLOW, + } + } + + /// Serialize into a storage string + /// **Format example**: + /// + /// true + /// false + /// true + /// 10101000000000000000000000000000 + pub fn serialize(&self, mut file: File) -> io::Result<()> { + writeln!(file, "{}", self.length)?; + writeln!(file, "{}", self.numbers)?; + writeln!(file, "{}", self.upper)?; + writeln!(file, "{}", self.lower)?; + writeln!(file, "{}", self.use_symbols)?; + log::info!("{:?}", self.symbols); + for &sym in &self.symbols { + write!(file, "{}", if sym { '1' } else { '0' })?; + } + writeln!(file)?; + + Ok(()) + } + + /// Deserialize from a storage string + pub fn deserialize(file: File) -> io::Result { + let reader = BufReader::new(file); + let mut lines = reader.lines(); + + let length = lines.next().and_then(|r| r.ok()).and_then(|s| s.parse().ok()).unwrap_or(18usize); + let numbers = lines.next().and_then(|r| r.ok()).and_then(|s| s.parse().ok()).unwrap_or(true); + let upper = lines.next().and_then(|r| r.ok()).and_then(|s| s.parse().ok()).unwrap_or(true); + let lower = lines.next().and_then(|r| r.ok()).and_then(|s| s.parse().ok()).unwrap_or(true); + let use_symbols = lines.next().and_then(|r| r.ok()).and_then(|s| s.parse().ok()).unwrap_or(true); + + let mut symbols = [false; 32]; + if let Some(Ok(sym_line)) = lines.next() { + for (i, c) in sym_line.chars().enumerate() { + if i >= 32 { + break; + } + symbols[i] = c == '1'; + } + } + + Ok(Self { length, numbers, upper, lower, use_symbols, symbols }) + } + + pub fn to_pools(&self) -> Vec> { + let mut pools = Vec::new(); + if self.lower { + pools.push(LOWERCASE_LETTERS.into()); + } + if self.upper { + pools.push(UPPERCASE_LETTERS.into()); + } + if self.numbers { + pools.push(NUMBERS.into()); + } + if self.use_symbols { + let mut specials = Vec::::new(); + for (i, &allow) in self.symbols.iter().enumerate() { + if allow { + specials.push(SYMBOLS_ALL[i]) + } + } + if specials.len() > 0 { + pools.push(specials); + } + } + pools + } +} + +/// Generate random passwords. `strict` means that at least one item must be included from each of the pools. +pub fn generate(pools: &Vec>, length: usize, strict: bool) -> String { + let pool: Vec = pools.iter().flat_map(|v| v.iter().copied()).collect(); + let weights = vec![1; length]; + let random = random_pick::pick_multiple_from_slice(&pool, &weights, length); + + if strict { + let mut password = String::with_capacity(length); + + let handle = |random: &[&char], password: &mut String, pools: &Vec>| { + let mut mask = 0; + let target_mask = (1 << pools.len()) - 1; + let mut m = false; + + for &c in random[..].iter() { + password.push(*c); + + if !m { + for (i, pool) in pools.iter().enumerate() { + if pool.contains(c) { + mask |= 1 << i; + } + } + m = mask == target_mask; + } + } + + m + }; + + if !handle(&random, &mut password, pools) { + loop { + let random = random_pick::pick_multiple_from_slice(&pool, &weights, length); + + password.clear(); + if handle(&random, &mut password, pools) { + break; + } + } + } + + password + } else { + random.iter().map(|c| **c).collect() + } +} diff --git a/apps-baosec/vault2/src/itemcache.rs b/apps-baosec/vault2/src/itemcache.rs index 5c2c641f2..a455c1458 100644 --- a/apps-baosec/vault2/src/itemcache.rs +++ b/apps-baosec/vault2/src/itemcache.rs @@ -59,8 +59,11 @@ impl PartialEq for ListKey { /// "extra" is more information about the item, which should not be part of the sort. #[derive(Debug, Clone)] pub struct ListItem { + // for passwords, this is the URL of the password name: String, + /// This is the name, but made all lowercase so that the sort goes strictly alphabetical sortable_name: String, + // for passwords, this is the username associated with the URL pub extra: String, /// this is the name of the key used to refer to the item pub guid: String, @@ -113,7 +116,9 @@ impl ListItem { pub fn key(&self) -> String { Self::key_from_parts(&self.name, &self.guid) } - pub fn name(&self) -> &String { &self.name } + pub fn name(&self) -> &str { &self.name } + + pub fn extra(&self) -> &str { &self.extra } pub fn name_clear(&mut self) { self.name.clear(); @@ -147,6 +152,10 @@ impl FilteredListView { } } + pub fn find_by_name(&self, name: &str) -> Vec { + self.list.iter().filter(|item| item.name() == name).cloned().collect() + } + pub fn is_db_empty(&self) -> bool { self.list.len() == 0 } pub fn expand(&mut self, capacity: usize) { self.list.reserve(capacity.saturating_sub(self.list.len())) } @@ -283,6 +292,14 @@ impl ItemLists { pub fn is_db_empty(&self, list_type: VaultMode) -> bool { self.li(list_type).is_db_empty() } + pub fn find_by_name(&self, mode: VaultMode, name: &str) -> Vec { + let view = match mode { + VaultMode::Password => &self.pw, + VaultMode::Totp => &self.totp, + }; + view.find_by_name(name) + } + fn li_mut(&mut self, list_type: VaultMode) -> &mut FilteredListView { match list_type { VaultMode::Totp => &mut self.totp, diff --git a/apps-baosec/vault2/src/main.rs b/apps-baosec/vault2/src/main.rs index 6c74cc0c6..bbf278467 100644 --- a/apps-baosec/vault2/src/main.rs +++ b/apps-baosec/vault2/src/main.rs @@ -10,6 +10,7 @@ mod totp; pub mod vault_api; use ux_api::service::gfx::Gfx; pub use vault_api::*; +mod generator; mod vendor_commands; use core::sync::atomic::{AtomicBool, Ordering}; @@ -465,9 +466,7 @@ fn main() -> ! { ), ) .ok(); - if *mode.lock().unwrap() == VaultMode::Totp { - vault_ui.refresh_draw_list(); - } + vault_ui.refresh_draw_list(); vault_ui.redraw(); } _ => { @@ -505,6 +504,24 @@ fn main() -> ! { } allow_totp_rendering.store(true, Ordering::SeqCst); } + Some(VaultOp::MenuDeleteStage1) => { + allow_totp_rendering.store(false, Ordering::SeqCst); + if let Some(entry) = vault_ui.selected_entry() { + let buf = Buffer::into_buf(entry).expect("IPC error"); + buf.lend(actions_conn, ActionOp::MenuDeleteStage2.to_u32().unwrap()) + .expect("messaging error"); + } else { + modals.show_notification(t!("vault.error.nothing_selected", locales::LANG), None).ok(); + } + xous::send_message( + actions_conn, + xous::Message::new_blocking_scalar(ActionOp::ReloadDb.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); + allow_totp_rendering.store(true, Ordering::SeqCst); + vault_ui.refresh_draw_list(); + vault_ui.redraw(); + } Some(VaultOp::BasisChange) => { vault_ui.basis_change(); xous::send_message( diff --git a/apps-baosec/vault2/src/storage.rs b/apps-baosec/vault2/src/storage.rs index 11c9b97ab..28d7e01dd 100644 --- a/apps-baosec/vault2/src/storage.rs +++ b/apps-baosec/vault2/src/storage.rs @@ -645,9 +645,12 @@ pub enum PasswordSerializationError { #[derive(Default)] pub struct PasswordRecord { pub version: u32, + // This contains the URL pub description: String, + // Username associated with the URL pub username: String, pub password: String, + // Initially contains just "Notes", but will contain the old password when updated pub notes: String, pub ctime: u64, pub atime: u64, diff --git a/apps-baosec/vault2/src/ux.rs b/apps-baosec/vault2/src/ux.rs index ae18e7eb1..fdf5fcef0 100644 --- a/apps-baosec/vault2/src/ux.rs +++ b/apps-baosec/vault2/src/ux.rs @@ -9,7 +9,7 @@ use ux_api::service::gfx::Gfx; use ux_api::widgets::ScrollableList; use xous::CID; -use crate::storage::{ContentKind, Manager}; +use crate::storage::Manager; use crate::*; const FAST_SCROLL_DELAY_MS: u64 = 1300; @@ -384,7 +384,7 @@ impl VaultUi { box_text.style = self.style; box_text.invert = true; // line 1 - write!(box_text, "{} {}", &entry.name(), &entry.extra).ok(); + write!(box_text, "{}/{} [{}]", &entry.name(), &entry.extra, entry.count).ok(); self.gfx.draw_textview(&mut box_text).unwrap(); insert_at += box_text.bounds_computed.unwrap().height() as isize; } else { diff --git a/apps-baosec/vault2/src/vault_api.rs b/apps-baosec/vault2/src/vault_api.rs index 0c7d0583f..f6299805b 100644 --- a/apps-baosec/vault2/src/vault_api.rs +++ b/apps-baosec/vault2/src/vault_api.rs @@ -13,6 +13,11 @@ pub const COMMAND_RESET_SESSION: u8 = 0x74; pub const VAULT_PASSWORD_DICT: &'static str = "vault.passwords"; pub const VAULT_TOTP_DICT: &'static str = "vault.totp"; +/// contains the list of usernames +pub const VAULT_CONFIG_USERNAMES: &'static str = "vault.config/usernames"; +/// contains the generator configuration record +pub const VAULT_CONFIG_GENERATOR: &'static str = "vault.config/generator"; + /// bytes to reserve for a key entry. Making this slightly larger saves on some churn as stuff gets updated pub const VAULT_ALLOC_HINT: usize = 256;