diff --git a/Cargo.lock b/Cargo.lock index c0ccca743..df1f5df84 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -154,6 +154,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" +[[package]] +name = "base32" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa" + [[package]] name = "base64" version = "0.13.0" @@ -3095,6 +3101,19 @@ dependencies = [ "syn", ] +[[package]] +name = "sha-1" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6" +dependencies = [ + "block-buffer 0.9.0", + "cfg-if 1.0.0", + "cpufeatures", + "digest 0.9.0", + "opaque-debug", +] + [[package]] name = "sha2" version = "0.9.8" @@ -3890,15 +3909,19 @@ name = "vault" version = "0.1.0" dependencies = [ "arrayref", + "base32", "byteorder", "cbor", "chrono", "content-plugin-api", + "crypto-mac", "ctap-crypto", + "digest 0.9.0", "enum-iterator", "gam", "graphics-server", "hex 0.4.3", + "hmac 0.11.0", "ime-plugin-api", "locales", "log", @@ -3909,7 +3932,10 @@ dependencies = [ "passwords", "pddb", "rand_core 0.6.3", + "random-pick", "rkyv", + "sha-1", + "sha2", "subtle", "ticktimer-server", "trng", diff --git a/RELEASE-v0.9.md b/RELEASE-v0.9.md index 354e110fd..386e3476e 100644 --- a/RELEASE-v0.9.md +++ b/RELEASE-v0.9.md @@ -171,7 +171,7 @@ perform the Xous firmware upgrade. This requires running manual update commands, - Autobacklight feature: selectable feature to automatically raise the backlight when keys are pressed. Thanks to gsora for the feature! - More importantly, this adds `crossbeam` into the kernel. This is a somewhat heavyweight item and is not recommended for use in core services, but by including it to drive the auto-backlight feature, we get regular code coverage of the condvar pathway. - +- TOTP integration thanks to blakesmith's PoC TOTP code! ## Roadmap to 1.0 diff --git a/apps/vault/Cargo.toml b/apps/vault/Cargo.toml index 7a1319500..c876db5bd 100644 --- a/apps/vault/Cargo.toml +++ b/apps/vault/Cargo.toml @@ -39,6 +39,16 @@ chrono = {version = "0.4.19", default-features = false, features = ["std"]} # password generation passwords = "3.1.9" +# totp +crypto-mac = "0.11.1" +sha-1 = "0.9.8" +hmac = "0.11.0" +digest = "0.9.0" +base32 = "0.4.0" +sha2 = {path="../../services/engine-sha512"} + +# testing +random-pick = {version = "1.2.15", optional = true} [dev-dependencies] enum-iterator = "0.6.0" @@ -48,4 +58,5 @@ with_ctap1 = ["ctap-crypto/with_ctap1"] with_ctap2_1 = [] autotest = [] multireset = [] # allows credential reset more than once per boot -default = ["with_ctap1", "with_ctap2_1"] +default = ["with_ctap1", "with_ctap2_1", "testing"] +testing = ["random-pick"] \ No newline at end of file diff --git a/apps/vault/locales/i18n.json b/apps/vault/locales/i18n.json index 7630e4e42..828f62ee0 100644 --- a/apps/vault/locales/i18n.json +++ b/apps/vault/locales/i18n.json @@ -47,6 +47,12 @@ "zh": "无法编辑 FIDO2 令牌。", "en-tts": "Can't edit FIDO2 tokens." }, + "vault.error.add_fido2": { + "en": "FIDO tokens are added through the web.", + "ja": "FIDOトークンはWebを使用して追加されます.", + "zh": "FIDO 令牌是使用网络添加的.", + "en-tts": "FIDO tokens are added through the web." + }, "vault.error.internal_error": { "en": "Internal error.", "ja": "内部エラー.", @@ -83,6 +89,12 @@ "zh": "取消", "en-tts": "No" }, + "vault.newitem.totp_ss": { + "en": "Enter the TOTP shared secret in Base32:", + "ja": "Base32にTOTP共有シークレットを入力します。", + "zh": "在 Base32 中输入 TOTP 共享密钥:", + "en-tts": "Enter the TOTP shared secret in Base32:" + }, "vault.newitem.name": { "en": "Please name the credential:", "ja": "クレデンシャルに名前を付ける:", @@ -149,6 +161,12 @@ "zh": "请输入 1-128 之间的数字", "en-tts": "Please enter a number from 1-128" }, + "vault.illegal_totp": { + "en": "Shared secret is not valid Base32", + "ja": "共有秘密は無効ですBase32", + "zh": "共享密钥无效 Base32", + "en-tts": "Shared secret is not valid Base32" + }, "vault.no_items": { "en": "No items found", "ja": "項目は見つかりませんでした", diff --git a/apps/vault/src/actions.rs b/apps/vault/src/actions.rs index 2555d98c3..93c130998 100644 --- a/apps/vault/src/actions.rs +++ b/apps/vault/src/actions.rs @@ -1,3 +1,4 @@ +use core::convert::TryFrom; use std::thread; use gam::TextEntryPayload; use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; @@ -11,13 +12,19 @@ use chrono::{Utc, DateTime, NaiveDateTime}; use std::time::{SystemTime, UNIX_EPOCH}; use std::cell::RefCell; -use crate::ux::ListItem; +use crate::{ux::{ListItem, deserialize_app_info}, ctap::FIDO_CRED_DICT}; use crate::{VaultMode, SelectedEntry}; +use crate::fido::U2F_APP_DICT; +use crate::totp::TotpAlgorithm; + pub(crate) const VAULT_PASSWORD_DICT: &'static str = "vault.passwords"; +pub(crate) const VAULT_TOTP_DICT: &'static str = "vault.totp"; /// bytes to reserve for a key entry. Making this slightly larger saves on some churn as stuff gets updated pub(crate) const VAULT_ALLOC_HINT: usize = 256; +pub(crate) const VAULT_TOTP_ALLOC_HINT: usize = 128; const VAULT_PASSWORD_REC_VERSION: u32 = 1; +const VAULT_TOTP_REC_VERSION: u32 = 1; /// time allowed between dialog box swaps for background operations to redraw const SWAP_DELAY_MS: usize = 300; @@ -32,6 +39,18 @@ pub(crate) struct PasswordRecord { pub count: u64, } +pub(crate) struct TotpRecord { + pub version: u32, + // as base32, RFC4648 no padding + pub secret: String, + pub name: String, + pub algorithm: TotpAlgorithm, + pub notes: String, + pub digits: u32, + pub timestep: u64, + pub ctime: u64, +} + #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub(crate) enum ActionOp { /// Menu items @@ -42,6 +61,9 @@ pub(crate) enum ActionOp { /// Internal ops UpdateMode, Quit, + #[cfg(feature="testing")] + /// Testing + GenerateTests, } pub(crate) fn start_actions_thread( @@ -96,6 +118,11 @@ pub(crate) fn start_actions_thread( None => { log::error!("msg could not be decoded {:?}", msg); } + #[cfg(feature="testing")] + Some(ActionOp::GenerateTests) => { + manager.populate_tests(); + manager.retrieve_db(); + } } } xous::destroy_server(sid).ok(); @@ -296,7 +323,7 @@ impl ActionManager { }; let ser = serialize_password(&record); let guid = self.gen_guid(); - log::info!("storing into guid: {}", guid); + log::debug!("storing into guid: {}", guid); match self.pddb.borrow().get( VAULT_PASSWORD_DICT, &guid, @@ -306,23 +333,87 @@ impl ActionManager { Ok(mut data) => { match data.write(&ser) { Ok(len) => log::debug!("wrote {} bytes", len), - Err(e) => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), e - ), None).ok(); - } + Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), } } - Err(e) => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), e - ), None).ok(); - } + Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), } - log::info!("syncing..."); + log::debug!("syncing..."); + self.pddb.borrow().sync().ok(); + } + VaultMode::Fido => { + self.report_err(t!("vault.error.add_fido2", xous::LANG), None::); + } + VaultMode::Totp => { + let description = match self.modals + .alert_builder(t!("vault.newitem.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(); + let secret = match self.modals + .alert_builder(t!("vault.newitem.totp_ss", xous::LANG)) + .field(None, Some(totp_ss_validator)) + .build() + { + Ok(text) => { + text.content()[0].content.as_str().unwrap_or("UTF-8 error").to_string() + }, + _ => {log::error!("TOTP ss entry failed"); self.action_active.store(false, Ordering::SeqCst); return} + }; + self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); + let ss = secret.to_uppercase(); + let ss_vec = if let Some(ss) = base32::decode(base32::Alphabet::RFC4648 { padding: false }, &ss) { + ss + } else { + if let Some(ss) = base32::decode(base32::Alphabet::RFC4648 { padding: true }, &ss) { + ss + } else { + if let Some(ss) = base32::decode(base32::Alphabet::Crockford, &ss) { + ss + } else { + log::error!("Shouldn't have happened: validated shared secret didn't decode!"); + Vec::new() + } + } + }; + let validated_secret = base32::encode(base32::Alphabet::RFC4648 { padding: false }, &ss_vec); + // time, hash, etc. are all the "expected defaults" -- if you want to change them, edit the record after entering it. + let totp = TotpRecord { + version: VAULT_TOTP_REC_VERSION, + name: description, + secret: validated_secret, + algorithm: TotpAlgorithm::HmacSha1, + digits: 6, + timestep: 30, + ctime: utc_now().timestamp() as u64, + notes: t!("vault.notes", xous::LANG).to_string(), + }; + let ser = serialize_totp(&totp); + let guid = self.gen_guid(); + log::debug!("storing into guid: {}", guid); + match self.pddb.borrow().get( + VAULT_TOTP_DICT, + &guid, + None, true, true, + Some(VAULT_TOTP_ALLOC_HINT), Some(crate::basis_change) + ) { + 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) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), + } + log::debug!("syncing..."); self.pddb.borrow().sync().ok(); } - _ => {} // not valid for these other modes } } @@ -331,7 +422,7 @@ impl ActionManager { let dict = match entry.mode { VaultMode::Password => VAULT_PASSWORD_DICT, VaultMode::Fido => crate::fido::U2F_APP_DICT, - VaultMode::Totp => unimplemented!(), + VaultMode::Totp => VAULT_TOTP_DICT, }; match self.pddb.borrow().delete_key(dict, entry.key_name.as_str().unwrap_or("UTF8-error"), None) { Ok(_) => { @@ -355,14 +446,9 @@ impl ActionManager { _ => {} } } - self.modals.show_notification(t!("vault.error.not_found", xous::LANG), None).ok(); - } - _ => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), - e - ), None).ok(); + self.report_err(t!("vault.error.not_found", xous::LANG), None::); } + _ => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)), } } } @@ -399,49 +485,23 @@ impl ActionManager { pw.notes = edit_data.content()[3].content.as_str().unwrap().to_string(); pw.atime = utc_now().timestamp() as u64; Some(pw) - } else { - log::error!("couldn't deserialize {}", entry.key_name); - self.modals.show_notification(t!("vault.error.record_error", xous::LANG), None).ok(); - None - } - } - Err(e) => { - log::error!("couldn't access key {}: {:?}", entry.key_name, e); - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), e), - None - ).ok(); - None + } else { 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 } }; maybe_update } Err(e) => { match e.kind() { - std::io::ErrorKind::NotFound => { - self.modals.show_notification(t!("vault.error.not_found", xous::LANG), None).ok(); - } - _ => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), - e - ), None).ok(); - } + 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)), } None } }; if let Some(update) = maybe_update { - match self.pddb.borrow().delete_key(dict, entry.key_name.as_str().unwrap(), None) { - Ok(_) => {} - Err(e) => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), - e - ), None).ok(); - return; - } - } + 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))); match self.pddb.borrow().get( dict, entry.key_name.as_str().unwrap(), None, false, true, Some(VAULT_ALLOC_HINT), @@ -449,21 +509,11 @@ impl ActionManager { ) { Ok(mut record) => { let ser = serialize_password(&update); - match record.write(&ser) { - Ok(_) => {} - Err(e) => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), e - ), None).ok(); - } - } - } - Err(e) => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), e - ), None).ok(); - return; + record.write(&ser) + .unwrap_or_else(|e| { + 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)), } } self.pddb.borrow().sync().ok(); @@ -490,51 +540,23 @@ impl ActionManager { ai.notes = edit_data.content()[1].content.as_str().unwrap().to_string(); ai.atime = utc_now().timestamp() as u64; Some(ai) - } else { - log::error!("couldn't deserialize {}", entry.key_name); - self.modals.show_notification(t!("vault.error.record_error", xous::LANG), None).ok(); - None - } - } - Err(e) => { - log::error!("couldn't access key {}: {:?}", entry.key_name, e); - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), e), - None - ).ok(); - None + } else { 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 } }; maybe_update } Err(e) => { match e.kind() { - std::io::ErrorKind::NotFound => { - // most likely this is due to this being a FIDO2 token, which we can't edit - // there are no editable fields -- if we change them, it can break the authentication protocol. - self.modals.show_notification(t!("vault.error.fido2", xous::LANG), None).ok(); - } - _ => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), - e - ), None).ok(); - } + 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)), } None } }; if let Some(update) = maybe_update { - match self.pddb.borrow().delete_key(dict, entry.key_name.as_str().unwrap(), None) { - Ok(_) => {} - Err(e) => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), - e - ), None).ok(); - return; - } - } + 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))); match self.pddb.borrow().get( dict, entry.key_name.as_str().unwrap(), None, false, true, Some(VAULT_ALLOC_HINT), @@ -542,27 +564,78 @@ impl ActionManager { ) { Ok(mut record) => { let ser = crate::fido::serialize_app_info(&update); - match record.write(&ser) { - Ok(_) => {} - Err(e) => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), e - ), None).ok(); - } - } - } - Err(e) => { - self.modals.show_notification(&format!("{}\n{:?}", - t!("vault.error.internal_error", xous::LANG), e - ), None).ok(); - return; + record.write(&ser).unwrap_or_else(|e| { + 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)), } } self.pddb.borrow().sync().ok(); } VaultMode::Totp => { - unimplemented!() + let maybe_update = match self.pddb.borrow().get( + dict, entry.key_name.as_str().unwrap(), None, + false, false, None, Some(crate::basis_change) + ) { + Ok(mut record) => { + let mut data = Vec::::new(); + let maybe_update = match record.read_to_end(&mut data) { + Ok(_len) => { + if let Some(mut pw) = deserialize_totp(data) { + let alg: String = pw.algorithm.into(); + let edit_data = self.modals + .alert_builder(t!("vault.edit_dialog", xous::LANG)) + .field(Some(pw.name), Some(name_validator)) + .field(Some(pw.secret), Some(name_validator)) + .field(Some(pw.notes), Some(name_validator)) + .field(Some(pw.timestep.to_string()), Some(name_validator)) + .field(Some(alg), Some(name_validator)) + .field(Some(pw.digits.to_string()), Some(name_validator)) + .build().expect("modals error in edit"); + pw.name = edit_data.content()[0].content.as_str().unwrap().to_string(); + pw.secret = edit_data.content()[1].content.as_str().unwrap().to_string(); + pw.notes = edit_data.content()[2].content.as_str().unwrap().to_string(); + if let Ok(t) = u64::from_str_radix(edit_data.content()[3].content.as_str().unwrap(), 10) { + pw.timestep = t; + } + if let Ok(alg) = TotpAlgorithm::try_from(edit_data.content()[4].content.as_str().unwrap()) { + pw.algorithm = alg; + } + if let Ok(d) = u32::from_str_radix(edit_data.content()[5].content.as_str().unwrap(), 10) { + pw.digits = d; + } + Some(pw) + } else { 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 } + }; + 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)), + } + 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))); + match self.pddb.borrow().get( + dict, entry.key_name.as_str().unwrap(), None, + false, true, Some(VAULT_ALLOC_HINT), + Some(crate::basis_change) + ) { + Ok(mut record) => { + let ser = serialize_totp(&update); + record.write(&ser).unwrap_or_else(|e| { + 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)), + } + } + self.pddb.borrow().sync().ok(); } } } @@ -605,7 +678,12 @@ impl ActionManager { let keylist = match self.pddb.borrow().list_keys(VAULT_PASSWORD_DICT, None) { Ok(keylist) => keylist, Err(e) => { - log::error!("error accessing password database: {:?}", e); + match e.kind() { + std::io::ErrorKind::NotFound => { + log::debug!("Password dictionary not yet created"); + } + _ => self.report_err("Dictionary error accessing password database", Some(e)), + } Vec::new() } }; @@ -627,7 +705,7 @@ impl ActionManager { t!("vault.u2f.appinfo.authcount", xous::LANG), pw.count, ); - let desc = format!("{} @ {}", pw.username, pw.description); + let desc = format!("{}/{}", pw.description, pw.username); let li = ListItem { name: desc, extra, @@ -636,50 +714,427 @@ impl ActionManager { }; il.push(li); } else { - log::error!("couldn't deserialize {}", key); + self.report_err("Couldn't deserialize password:", Some(key)); } } - Err(e) => log::error!("couldn't access key {}: {:?}", key, e), + Err(e) => self.report_err("Couldn't access password key", Some(e)), } } - Err(e) => log::error!("couldn't access key {}: {:?}", key, e), + Err(e) => self.report_err("Couldn't access password key", Some(e)), } } } VaultMode::Fido => { - il.push(ListItem { name: "test.com".to_string(), extra: "Used 5 mins ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "google.com".to_string(), extra: "Never used".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "my app".to_string(), extra: "Used 2 hours ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "💎🙌".to_string(), extra: "Used 2 days ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "百度".to_string(), extra: "Used 1 month ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "duplicate.com".to_string(), extra: "Used 1 week ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "duplicate.com".to_string(), extra: "Used 8 mins ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "amawhat.com".to_string(), extra: "Used 6 days ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "amazon.com".to_string(), extra: "Used 3 days ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "amazingcode.org".to_string(), extra: "Never used".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "ziggyziggyziggylongdomain.com".to_string(), extra: "Never used".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "another long domain name.com".to_string(), extra: "Used 2 months ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "bunniestudios.com".to_string(), extra: "Used 30 mins ago".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "github.com".to_string(), extra: "Used 6 hours ago".to_string(), dirty: true, guid: self.gen_guid() }); + // first assemble U2F records + let keylist = match self.pddb.borrow().list_keys(U2F_APP_DICT, None) { + Ok(keylist) => keylist, + Err(e) => { + match e.kind() { + std::io::ErrorKind::NotFound => { + log::debug!("U2F dictionary not yet created"); + } + _ => self.report_err("Dictionary error accessing U2F database", Some(e)), + } + Vec::new() + } + }; + for key in keylist { + match self.pddb.borrow().get( + U2F_APP_DICT, + &key, + 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(ai) = deserialize_app_info(data) { + let extra = format!("{}; {}{}", + crate::ux::atime_to_str(ai.atime), + t!("vault.u2f.appinfo.authcount", xous::LANG), + ai.count, + ); + let desc = format!("{}", ai.name); + let li = ListItem { + name: desc, + extra, + dirty: true, + guid: key, + }; + il.push(li); + } else { + self.report_err("Couldn't deserialize U2F:", Some(key)); + } + } + Err(e) => self.report_err("Couldn't access U2F key", Some(e)), + } + } + Err(e) => self.report_err("Couldn't access U2F key", Some(e)), + } + } + let keylist = match self.pddb.borrow().list_keys(FIDO_CRED_DICT, None) { + Ok(keylist) => keylist, + Err(e) => { + match e.kind() { + std::io::ErrorKind::NotFound => { + log::debug!("FIDO2 dictionary not yet created"); + } + _ => self.report_err("Dictionary error accessing FIDO2 database", Some(e)), + } + Vec::new() + } + }; + // now merge in the FIDO2 records + for key in keylist { + match self.pddb.borrow().get( + FIDO_CRED_DICT, + &key, + 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) => { + match crate::ctap::storage::deserialize_credential(&data) { + Some(result) => { + let name = if let Some(display_name) = result.user_display_name { + display_name + } else { + String::from_utf8(result.user_handle).unwrap_or("".to_string()) + }; + let desc = format!("{} / {}", result.rp_id, String::from_utf8(result.credential_id).unwrap_or("---".to_string())); + let extra = format!("FIDO2 {}", name); + let li = ListItem { + name: desc, + extra, + dirty: true, + guid: key, + }; + il.push(li); + } + None => self.report_err("Couldn't deserialize FIDO2:", Some(key)), + } + } + Err(e) => self.report_err("Couldn't access FIDO2 key", Some(e)), + } + } + Err(e) => self.report_err("Couldn't access FIDO2 key", Some(e)), + } + } } VaultMode::Totp => { - il.push(ListItem { name: "gmail.com".to_string(), extra: "162 321".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "google.com".to_string(), extra: "445 768".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "my 图片 app".to_string(), extra: "982 111".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "🍕🍔🍟🌭".to_string(), extra: "056 182".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "百度".to_string(), extra: "111 111".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "duplicate.com".to_string(), extra: "462 124".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "duplicate.com".to_string(), extra: "462 124".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "amazon.com".to_string(), extra: "842 012".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "ziggyziggyziggylongdomain.com".to_string(), extra: "462 212".to_string(), dirty: true, guid: self.gen_guid() }); - il.push(ListItem { name: "github.com".to_string(), extra: "Used 6 hours ago".to_string(), dirty: true, guid: self.gen_guid() }); + let keylist = match self.pddb.borrow().list_keys(VAULT_TOTP_DICT, None) { + Ok(keylist) => keylist, + Err(e) => { + match e.kind() { + std::io::ErrorKind::NotFound => { + log::debug!("TOTP dictionary not yet created"); + } + _ => self.report_err("Dictionary error accessing TOTP database", Some(e)), + } + Vec::new() + } + }; + for key in keylist { + match self.pddb.borrow().get( + VAULT_TOTP_DICT, + &key, + 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(totp) = deserialize_totp(data) { + let alg: String = totp.algorithm.into(); + let extra = format!("{}:{}:{}:{}", totp.secret, totp.digits, totp.timestep, alg); + let desc = format!("{}", totp.name); + let li = ListItem { + name: desc, + extra, + dirty: true, + guid: key, + }; + il.push(li); + } else { + self.report_err("Couldn't deserialize TOTP:", Some(key)); + } + } + Err(e) => self.report_err("Couldn't access TOTP key", Some(e)), + } + } + Err(e) => self.report_err("Couldn't access TOTP key", Some(e)), + } + } } } il.sort(); } + #[cfg(feature="testing")] + pub(crate) fn populate_tests(&mut self) { + use crate::ux::serialize_app_info; + + let words = [ + "bunnie", "foo", "turtle.net", "Fox.ng", "Bear", "dog food", "Cat.com", "FUzzy", "1off", "www_test_site_com/long_name/stupid/foo.htm", + "._weird~yy%\":'test", "//WHYwhyWHY", "Xyz|zy", "foo:bar", "f🍕🍔🍟🌭d", "💎🙌", "some ノート", "笔录4u", "@u", "sane text", "Käsesoßenrührlöffel"]; + let weights = [1; 21]; + const TARGET_ENTRIES: usize = 35; + const TARGET_ENTRIES_PW: usize = 300; + // for each database, populate up to TARGET_ENTRIES + // as this is testing code, it's written a bit more fragile in terms of error handling (fail-panic, rather than fail-dialog) + // --- passwords --- + let pws = self.pddb.borrow().list_keys(VAULT_PASSWORD_DICT, None).unwrap_or(Vec::new()); + if pws.len() < TARGET_ENTRIES_PW { + let extra_count = TARGET_ENTRIES - pws.len(); + for _ in 0..extra_count { + let desc = random_pick::pick_multiple_from_slice(&words, &weights, 3); + let description = format!("{} {} {}", desc[0], desc[1], desc[2]); + let username = random_pick::pick_from_slice(&words, &weights).unwrap().to_string(); + let notes = random_pick::pick_from_slice(&words, &weights).unwrap().to_string(); + let pg = PasswordGenerator { + length: 20, + numbers: true, + lowercase_letters: true, + uppercase_letters: true, + symbols: true, + spaces: false, + exclude_similar_characters: true, + strict: true, + }; + let password = pg.generate_one().unwrap(); + let record = PasswordRecord { + version: VAULT_PASSWORD_REC_VERSION, + description, + username, + password, + notes, + ctime: utc_now().timestamp() as u64, + atime: 0, + count: 0, + }; + let ser = serialize_password(&record); + let guid = self.gen_guid(); + match self.pddb.borrow().get( + VAULT_PASSWORD_DICT, + &guid, + None, true, true, + Some(VAULT_ALLOC_HINT), Some(crate::basis_change) + ) { + Ok(mut data) => { + match data.write(&ser) { + Ok(len) => log::debug!("wrote {} bytes", len), + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + } + } + } + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + } + } + } + } + // --- U2F + FIDO --- + let fido = self.pddb.borrow().list_keys(FIDO_CRED_DICT, None).unwrap_or(Vec::new()); + let u2f = self.pddb.borrow().list_keys(U2F_APP_DICT, None).unwrap_or(Vec::new()); + let total = fido.len() + u2f.len(); + if total < TARGET_ENTRIES { + let extra_u2f = (TARGET_ENTRIES - total) / 2; + let extra_fido = TARGET_ENTRIES - extra_u2f; + for _ in 0..extra_u2f { + let n = random_pick::pick_multiple_from_slice(&words, &weights, 2); + let name = format!("{} {}", n[0], n[1]); + let notes = random_pick::pick_from_slice(&words, &weights).unwrap().to_string(); + let mut id = [0u8; 32]; + self.trng.borrow_mut().fill_bytes(&mut id); + let record = crate::AppInfo { + name, + id, + notes, + ctime: utc_now().timestamp() as u64, + atime: 0, + count: 0, + }; + let ser = serialize_app_info(&record); + let app_id_str = hex::encode(id); + match self.pddb.borrow().get( + U2F_APP_DICT, + &app_id_str, + None, true, true, + Some(256), Some(crate::basis_change) + ) { + Ok(mut app_data) => { + app_data.write(&ser).expect("couldn't create"); + } + _ => log::error!("Error creating record"), + } + } + let xns = xous_names::XousNames::new().unwrap(); + let mut rng = ctap_crypto::rng256::XousRng256::new(&xns); + for _ in 0..extra_fido { + use crate::ctap::data_formats::*; + let c_id = random_pick::pick_multiple_from_slice(&words, &weights, 2); + let cred_id = format!("{} {}", c_id[0], c_id[1]); + let r_id = random_pick::pick_multiple_from_slice(&words, &weights, 2); + let rp_id = format!("{} {}", r_id[0], r_id[1]); + let handle = random_pick::pick_from_slice(&words, &weights).unwrap().to_string(); + let new_credential = PublicKeyCredentialSource { + key_type: PublicKeyCredentialType::PublicKey, + credential_id: cred_id.as_bytes().to_vec(), + private_key: ctap_crypto::ecdsa::SecKey::gensk(&mut rng), + rp_id, + user_handle: handle.as_bytes().to_vec(), + user_display_name: None, + cred_protect_policy: None, + creation_order: 0, + user_name: None, + user_icon: None, + }; + let shortid = &cred_id; + match self.pddb.borrow().get( + FIDO_CRED_DICT, + shortid, + None, true, true, + Some(crate::ctap::storage::CRED_INITAL_SIZE), Some(crate::basis_change) + ) { + Ok(mut cred) => { + let value = crate::ctap::storage::serialize_credential(new_credential).unwrap(); + cred.write(&value).unwrap(); + } + _ => log::error!("couldn't create FIDO2 credential") + } + } + } + // TOTP + let totp = self.pddb.borrow().list_keys(VAULT_TOTP_DICT, None).unwrap_or(Vec::new()); + if totp.len() < TARGET_ENTRIES { + let extra = TARGET_ENTRIES - totp.len(); + for _ in 0..extra { + let names = random_pick::pick_multiple_from_slice(&words, &weights, 3); + let name = format!("{} {} {}", names[0], names[1], names[2]); + let notes = random_pick::pick_from_slice(&words, &weights).unwrap().to_string(); + let mut secret_bytes = [0u8; 10]; + self.trng.borrow_mut().fill_bytes(&mut secret_bytes); + let record = TotpRecord { + version: VAULT_TOTP_REC_VERSION, + secret: base32::encode(base32::Alphabet::RFC4648 { padding: false }, &secret_bytes), + name, + algorithm: TotpAlgorithm::HmacSha1, + notes, + digits: 6, + timestep: 30, + ctime: utc_now().timestamp() as u64, + }; + let ser = serialize_totp(&record); + let guid = self.gen_guid(); + match self.pddb.borrow().get( + VAULT_TOTP_DICT, + &guid, + None, true, true, + Some(VAULT_TOTP_ALLOC_HINT), Some(crate::basis_change) + ) { + Ok(mut data) => { + match data.write(&ser) { + Ok(len) => log::debug!("wrote {} bytes", len), + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + } + } + } + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + } + } + } + // specific TOTP entry with a known shared secret for testing + let record = TotpRecord { + version: VAULT_TOTP_REC_VERSION, + secret: "I65VU7K5ZQL7WB4E".to_string(), + name: "totp@authenticationtest.com".to_string(), + algorithm: TotpAlgorithm::HmacSha1, + notes: "Predefined test".to_string(), + digits: 6, + timestep: 30, + ctime: utc_now().timestamp() as u64, + }; + let ser = serialize_totp(&record); + let guid = self.gen_guid(); + match self.pddb.borrow().get( + VAULT_TOTP_DICT, + &guid, + None, true, true, + Some(VAULT_TOTP_ALLOC_HINT), Some(crate::basis_change) + ) { + Ok(mut data) => { + match data.write(&ser) { + Ok(len) => log::debug!("wrote {} bytes", len), + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + } + } + } + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + } + } + } + self.pddb.borrow().sync().ok(); + } + + fn report_err(&self, note: &str, e: Option) { + log::error!("{}: {:?}", note, e); + if let Some(e) = e { + self.modals.show_notification(&format!("{}\n{:?}", note, e), None).ok(); + } else { + self.modals.show_notification(&format!("{}", note), None).ok(); + } + } } +pub(crate) fn totp_ss_validator(input: TextEntryPayload) -> Option> { + let proposed_ss = input.as_str().to_uppercase(); + if let Some(ss) = base32::decode(base32::Alphabet::RFC4648 { padding: false }, &proposed_ss) { + if ss.len() > 0 { + return None; + } else { + return Some(xous_ipc::String::<256>::from_str(t!("vault.illegal_totp", xous::LANG))); + } + } + if let Some(ss) = base32::decode(base32::Alphabet::RFC4648 { padding: true }, &proposed_ss) { + if ss.len() > 0 { + return None; + } else { + return Some(xous_ipc::String::<256>::from_str(t!("vault.illegal_totp", xous::LANG))); + } + } + if let Some(ss) = base32::decode(base32::Alphabet::Crockford, &proposed_ss) { + if ss.len() > 0 { + return None; + } else { + return Some(xous_ipc::String::<256>::from_str(t!("vault.illegal_totp", xous::LANG))); + } + } + Some(xous_ipc::String::<256>::from_str(t!("vault.illegal_totp", xous::LANG))) +} pub(crate) fn name_validator(input: TextEntryPayload) -> Option> { let proposed_name = input.as_str(); if proposed_name.contains('\n') { // the '\n' is reserved as the delimiter to end the name field @@ -766,12 +1221,94 @@ pub(crate) fn deserialize_password(data: Vec::) -> Option { } } _ => { - log::warn!("unexpected tag {} encountered parsing app info, aborting", tag); - return None; + log::warn!("unexpected tag {} encountered parsing password info, ignoring", tag); } } } else { - log::debug!("invalid line skipped: {:?}", line); + log::trace!("invalid line skipped: {:?}", line); + } + } + Some(pr) + } else { + None + } +} + +pub(crate) fn serialize_totp<'a>(record: &TotpRecord) -> Vec:: { + let ta: String = record.algorithm.into(); + format!("{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n", + "version", record.version, + "secret", record.secret, + "name", record.name, + "algorithm", ta, + "notes", record.notes, + "digits", record.digits, + "timestep", record.timestep, + "ctime", record.ctime, + ).into_bytes() +} + +pub(crate) fn deserialize_totp(data: Vec::) -> Option { + if let Ok(desc_str) = String::from_utf8(data) { + let mut pr = TotpRecord { + version: 0, + secret: String::new(), + name: String::new(), + algorithm: TotpAlgorithm::HmacSha1, + notes: String::new(), + digits: 0, + ctime: 0, + timestep: 0, + }; + let lines = desc_str.split('\n'); + for line in lines { + if let Some((tag, data)) = line.split_once(':') { + match tag { + "version" => { + if let Ok(ver) = u32::from_str_radix(data, 10) { + pr.version = ver + } else { + log::warn!("ver error"); + return None; + } + } + "secret" => pr.secret.push_str(data), + "name" => pr.name.push_str(data), + "algorithm" => pr.algorithm = match TotpAlgorithm::try_from(data) { + Ok(a) => a, + Err(_) => return None + }, + "notes" => pr.notes.push_str(data), + "digits" => { + if let Ok(digits) = u32::from_str_radix(data, 10) { + pr.digits = digits; + } else { + log::warn!("digits error"); + return None; + } + } + "ctime" => { + if let Ok(ctime) = u64::from_str_radix(data, 10) { + pr.ctime = ctime; + } else { + log::warn!("ctime error"); + return None; + } + } + "timestep" => { + if let Ok(timestep) = u64::from_str_radix(data, 10) { + pr.timestep = timestep; + } else { + log::warn!("timestep error"); + return None; + } + } + _ => { + log::warn!("unexpected tag {} encountered parsing TOTP info, ignoring", tag); + } + } + } else { + log::trace!("invalid line skipped: {:?}", line); } } Some(pr) diff --git a/apps/vault/src/ctap/mod.rs b/apps/vault/src/ctap/mod.rs index 9fe0d9f60..a6454614f 100644 --- a/apps/vault/src/ctap/mod.rs +++ b/apps/vault/src/ctap/mod.rs @@ -22,7 +22,7 @@ mod key_material; mod pin_protocol_v1; pub mod response; pub mod status_code; -mod storage; +pub mod storage; mod timed_permission; #[cfg(feature = "with_ctap2_1")] diff --git a/apps/vault/src/ctap/storage.rs b/apps/vault/src/ctap/storage.rs index 2dceb54da..b8e2e260c 100644 --- a/apps/vault/src/ctap/storage.rs +++ b/apps/vault/src/ctap/storage.rs @@ -43,7 +43,7 @@ use super::CREDENTIAL_ID_SIZE; /// credentials, but what happens in this case is just a re-allocation in the PDDB. /// Whereas if this number is "too big" you end up with wasted space. I think a /// typical record will be around 300-400 bytes, so, this is a good compromise. -const CRED_INITAL_SIZE: usize = 512; +pub(crate) const CRED_INITAL_SIZE: usize = 512; // Those constants may be modified before compilation to tune the behavior of the key. // @@ -149,10 +149,8 @@ impl PersistentStore { } // Generate and store the CredRandom secrets if they are missing. - // note this goes into the FIDO_CRED_DICT, in order to force its creation. - // It does mean we have a special case key in the dictionary. match self.pddb.borrow().get( - FIDO_CRED_DICT, + FIDO_DICT, key::CRED_RANDOM_SECRET, None, true, true, Some(64), Some(crate::basis_change) @@ -415,7 +413,10 @@ openssl asn1parse -in opensk_cert.pem -inform pem } Err(e) => match e.kind() { std::io::ErrorKind::NotFound => Ok(None), - _ => Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR), // PDDB internal error + _ => { + log::error!("PDDB internal error in find_credential: {:?}", e); + Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR) + }, // PDDB internal error } } } @@ -431,7 +432,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem match self.pddb.borrow().get( FIDO_CRED_DICT, &shortid, - None, false, true, + None, true, true, Some(CRED_INITAL_SIZE), Some(crate::basis_change) ) { Ok(mut cred) => { @@ -455,9 +456,8 @@ openssl asn1parse -in opensk_cert.pem -inform pem check_cred_protect: bool, ) -> Result, Ctap2StatusCode> { let mut result = Vec::::new(); - let mut cred_list = self.pddb.borrow().list_keys( - FIDO_CRED_DICT, None).or(Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR))?; - cred_list.retain(|name| name != key::CRED_RANDOM_SECRET); // don't try to investigate this one key + let cred_list = self.pddb.borrow().list_keys( + FIDO_CRED_DICT, None).unwrap_or(Vec::new()); for cred_name in cred_list.iter() { if let Some(mut cred_entry) = self.pddb.borrow().get( FIDO_CRED_DICT, @@ -482,17 +482,15 @@ openssl asn1parse -in opensk_cert.pem -inform pem #[cfg(test)] pub fn count_credentials(&self) -> Result { let mut cred_list = self.pddb.borrow().list_keys( - FIDO_CRED_DICT, None).or(Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR))?; - cred_list.retain(|name| name != key::CRED_RANDOM_SECRET); // don't count this special case key + FIDO_CRED_DICT, None).unwrap_or(Vec::new()); Ok(cred_list.len()) } /// Returns the next creation order. pub fn new_creation_order(&self) -> Result { let mut max = 0; - let mut cred_list = self.pddb.borrow().list_keys( - FIDO_CRED_DICT, None).or(Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR))?; - cred_list.retain(|name| name != key::CRED_RANDOM_SECRET); // don't try to investigate this one key + let cred_list = self.pddb.borrow().list_keys( + FIDO_CRED_DICT, None).unwrap_or(Vec::new()); if cred_list.len() == 0 { return Ok(0) } @@ -588,7 +586,7 @@ openssl asn1parse -in opensk_cert.pem -inform pem /// Returns the CredRandom secret. pub fn cred_random_secret(&self, has_uv: bool) -> Result<[u8; 32], Ctap2StatusCode> { match self.pddb.borrow().get( - FIDO_CRED_DICT, + FIDO_DICT, key::CRED_RANDOM_SECRET, None, false, false, None, Some(crate::basis_change) ) { @@ -1000,13 +998,13 @@ openssl asn1parse -in opensk_cert.pem -inform pem } /// Deserializes a credential from storage representation. -fn deserialize_credential(data: &[u8]) -> Option { +pub(crate) fn deserialize_credential(data: &[u8]) -> Option { let cbor = cbor::read(data).ok()?; cbor.try_into().ok() } /// Serializes a credential to storage representation. -fn serialize_credential(credential: PublicKeyCredentialSource) -> Result, Ctap2StatusCode> { +pub(crate) fn serialize_credential(credential: PublicKeyCredentialSource) -> Result, Ctap2StatusCode> { let mut data = Vec::new(); if cbor::write(credential.into(), &mut data) { Ok(data) diff --git a/apps/vault/src/main.rs b/apps/vault/src/main.rs index 8560d135b..f0ee82ed8 100644 --- a/apps/vault/src/main.rs +++ b/apps/vault/src/main.rs @@ -19,6 +19,7 @@ mod shims; use shims::*; mod submenu; mod actions; +mod totp; use locales::t; @@ -80,6 +81,25 @@ UI concept: - Icontray thread: a simple server that serves as a shim between the IME structure and this to create an icontray function */ + // TOTP test I65VU7K5ZQL7WB4E https://authenticationtest.com/totpChallenge/ + // otpauth-migration://offline?data=Ci8KCke7Wn1dzBf7B4QSG3RvdHBAYXV0aGVudGljYXRpb250ZXN0LmNvbSABKAEwAhABGAEgACjh8Yv%2B%2BP%2F%2F%2F%2F8B +/* +otp_parameters { + secret: "G\273Z}]\314\027\373\007\204" + name: "totp@authenticationtest.com" + algorithm: SHA1 + digits: SIX + type: TOTP +} +version: 1 +batch_size: 1 +batch_index: 0 +batch_id: -1883047711 + +>>> b32decode("I65VU7K5ZQL7WB4E").hex() +'47bb5a7d5dcc17fb0784' +*/ + #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub(crate) enum VaultOp { /// a line of text has arrived @@ -203,6 +223,10 @@ fn main() -> ! { icontray_server(conn); } }); + // spawn the TOTP pumper + let pump_sid = xous::create_server().unwrap(); + crate::totp::pumper(mode.clone(), pump_sid, conn); + let pump_conn = xous::connect(pump_sid).unwrap(); let menu_sid = xous::create_server().unwrap(); let menu_mgr = submenu::create_submenu(conn, actions_conn, menu_sid); @@ -268,6 +292,10 @@ fn main() -> ! { Message::new_blocking_scalar(ActionOp::UpdateMode.to_usize().unwrap(), 0, 0, 0, 0) ).ok(); vaultux.update_mode(); + // this will start a periodic pump to keep the UX updating + send_message(pump_conn, + Message::new_scalar(totp::PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0) + ).ok(); } "\u{0013}" => { *mode.lock().unwrap() = VaultMode::Password; diff --git a/apps/vault/src/submenu.rs b/apps/vault/src/submenu.rs index 6d6821587..3d418c18e 100644 --- a/apps/vault/src/submenu.rs +++ b/apps/vault/src/submenu.rs @@ -29,6 +29,14 @@ 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, }); + #[cfg(feature="testing")] + menu_items.push(MenuItem { + name: xous_ipc::String::from_str("Generate test vectors"), + action_conn: Some(actions_conn), + action_opcode: ActionOp::GenerateTests.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_close", xous::LANG)), action_conn: Some(actions_conn), diff --git a/apps/vault/src/totp.rs b/apps/vault/src/totp.rs new file mode 100644 index 000000000..82708ead6 --- /dev/null +++ b/apps/vault/src/totp.rs @@ -0,0 +1,177 @@ +use crypto_mac::InvalidKeyLength; +use sha1::Sha1; +use hmac::{Hmac, Mac, NewMac}; +use std::{ + convert::TryFrom, + time::{SystemTime, SystemTimeError}, +}; +use std::sync::{Arc, Mutex}; +use xous::{Message, send_message}; +use std::thread; +use crate::VaultMode; +use num_traits::*; + +// Derived from https://github.com/blakesmith/xous-core/blob/xtotp-time/apps/xtotp/src/main.rs +#[derive(Clone, Copy)] +pub(crate) enum TotpAlgorithm { + HmacSha1, + HmacSha256, + HmacSha512, +} +impl std::fmt::Debug for TotpAlgorithm { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + TotpAlgorithm::HmacSha1 => write!(f, "SHA1"), + TotpAlgorithm::HmacSha256 => write!(f, "SHA256"), + TotpAlgorithm::HmacSha512 => write!(f, "SHA512"), + } + } +} + +impl TryFrom<&str> for TotpAlgorithm { + type Error = xous::Error; + fn try_from(s: &str) -> Result { + match s { + "SHA1" => Ok(TotpAlgorithm::HmacSha1), + "SHA256" => Ok(TotpAlgorithm::HmacSha256), + "SHA512" => Ok(TotpAlgorithm::HmacSha512), + _ => Err(xous::Error::InvalidString) + } + } +} +impl Into for TotpAlgorithm { + fn into(self) -> String { + match self { + TotpAlgorithm::HmacSha1 => "SHA1".to_string(), + TotpAlgorithm::HmacSha256 => "SHA256".to_string(), + TotpAlgorithm::HmacSha512 => "SHA512".to_string(), + } + } +} + +#[derive(Debug)] +pub(crate) struct TotpEntry { + pub step_seconds: u16, + pub shared_secret: Vec, + pub digit_count: u8, + pub algorithm: TotpAlgorithm, +} + +#[derive(Debug)] +pub(crate) enum Error { + Io(std::io::Error), + DigestLength(InvalidKeyLength), +} + +impl From for Error { + fn from(err: std::io::Error) -> Self { + Error::Io(err) + } +} + +impl From for Error { + fn from(err: InvalidKeyLength) -> Self { + Error::DigestLength(err) + } +} + +pub(crate) fn get_current_unix_time() -> Result { + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map(|duration| duration.as_secs()) +} + +fn unpack_u64(v: u64) -> [u8; 8] { + let mask = 0x00000000000000ff; + let mut bytes: [u8; 8] = [0; 8]; + (0..8).for_each(|i| bytes[7 - i] = (mask & (v >> (i * 8))) as u8); + bytes +} + +fn generate_hmac_bytes(unix_timestamp: u64, totp_entry: &TotpEntry) -> Result, Error> { + let mut computed_hmac = Vec::new(); + match totp_entry.algorithm { + // The OpenTitan HMAC core does not support hmac-sha1. Fall back to + // a software implementation. + TotpAlgorithm::HmacSha1 => { + let mut mac: Hmac = Hmac::new_from_slice(&totp_entry.shared_secret)?; + mac.update(&unpack_u64(unix_timestamp / totp_entry.step_seconds as u64)); + let hash: &[u8] = &mac.finalize().into_bytes(); + computed_hmac.extend_from_slice(hash); + } + // note: sha256/sha512 implementations not yet tested, as we have yet to find a site that uses this to test against. + TotpAlgorithm::HmacSha256 => { + let mut mac: Hmac = Hmac::new_from_slice(&totp_entry.shared_secret)?; + mac.update(&unpack_u64(unix_timestamp / totp_entry.step_seconds as u64)); + let hash: &[u8] = &mac.finalize().into_bytes(); + computed_hmac.extend_from_slice(hash); + } + TotpAlgorithm::HmacSha512 => { + let mut mac: Hmac = Hmac::new_from_slice(&totp_entry.shared_secret)?; + mac.update(&unpack_u64(unix_timestamp / totp_entry.step_seconds as u64)); + let hash: &[u8] = &mac.finalize().into_bytes(); + computed_hmac.extend_from_slice(hash); + } + } + + Ok(computed_hmac) +} + +pub(crate) fn generate_totp_code(unix_timestamp: u64, totp_entry: &TotpEntry) -> Result { + let hash = generate_hmac_bytes(unix_timestamp, totp_entry)?; + let offset: usize = (hash.last().unwrap_or(&0) & 0xf) as usize; + let binary: u64 = (((hash[offset] & 0x7f) as u64) << 24) + | ((hash[offset + 1] as u64) << 16) + | ((hash[offset + 2] as u64) << 8) + | (hash[offset + 3] as u64); + + let truncated_code = format!( + "{:01$}", + binary % (10_u64.pow(totp_entry.digit_count as u32)), + totp_entry.digit_count as usize + ); + + Ok(truncated_code) +} + +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub(crate) enum PumpOp { + Pump, + Quit, +} + +pub(crate) fn pumper(mode: Arc>, sid: xous::SID, main_conn: xous::CID) { + let _ = thread::spawn({ + move || { + let tt = ticktimer_server::Ticktimer::new().unwrap(); + let self_conn = xous::connect(sid).unwrap(); + loop { + let msg = xous::receive_message(sid).unwrap(); + let opcode: Option = FromPrimitive::from_usize(msg.body.id()); + log::trace!("{:?}", opcode); + match opcode { + Some(PumpOp::Pump) => { + send_message(main_conn, + Message::new_scalar(crate::VaultOp::Redraw.to_usize().unwrap(), + 0, 0, 0, 0) + ).expect("couldn't pump redraw"); + let mode_cache = {(*mode.lock().unwrap()).clone()}; + { // we really want mode.lock() to be in a different scope so... + if mode_cache == VaultMode::Totp { + tt.sleep_ms(2000).unwrap(); + send_message(self_conn, + Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), + 0, 0, 0, 0) + ).expect("couldn't restart pump"); + } + } + // if not in Totp mode, the restart message doesn't go through, and the redraws automatically stop. + }, + Some(PumpOp::Quit) => {break;} + _ => log::warn!("couldn't parse message: {:?}", msg), + } + } + xous::destroy_server(sid).ok(); + } + }); +} \ No newline at end of file diff --git a/apps/vault/src/ux/fido.rs b/apps/vault/src/ux/fido.rs index 3a3bc582d..a78fb5b8e 100644 --- a/apps/vault/src/ux/fido.rs +++ b/apps/vault/src/ux/fido.rs @@ -554,7 +554,7 @@ pub(crate) fn deserialize_app_info(descriptor: Vec::) -> Option:: { } } } else { - log::debug!("invalid line skipped: {:?}", line); + log::trace!("invalid line skipped: {:?}", line); } } if appinfo.name.len() > 0 diff --git a/apps/vault/src/ux/framework.rs b/apps/vault/src/ux/framework.rs index 1e68008d5..8a79d9407 100644 --- a/apps/vault/src/ux/framework.rs +++ b/apps/vault/src/ux/framework.rs @@ -1,4 +1,5 @@ use crate::*; +use crate::totp::{TotpAlgorithm, generate_totp_code}; use gam::{UxRegistration, GlyphStyle, MenuMatic, MenuItem, MenuPayload}; use graphics_server::{Gid, Point, Rectangle, DrawStyle, PixelColor, TextView}; use std::fmt::Write; @@ -8,6 +9,7 @@ use std::cmp::Ordering; use std::io::{Read, Write as FsWrite}; use actions::ActionOp; use std::sync::atomic::Ordering as AtomicOrdering; +use std::convert::TryFrom; /// Display list for items. "name" is the key by which the list is sorted. /// "extra" is more information about the item, which should not be part of the sort. @@ -87,6 +89,10 @@ pub(crate) struct VaultUx { /// usb interface usb_dev: usb_device_xous::UsbHid, + + /// totp redraw state + last_epoch: u64, + current_time: u64, } pub(crate) const DEFAULT_FONT: GlyphStyle = GlyphStyle::Regular; @@ -153,6 +159,7 @@ impl VaultUx { let pddb = pddb::Pddb::new(); // TODO: put some informative message asking to mount the PDDB if it's not mounted, right now you just get a blank screen. + // TODO: also add routines to detect if time is not set up, and block initialization until that happens. pddb.is_mounted_blocking(); // temporary style setting, this will get over-ridden after init let style = GlyphStyle::Regular; @@ -161,6 +168,8 @@ impl VaultUx { let item_height = (glyph_height * 2) as i16 + margin.y * 2 + 2; // +2 because of the border width let items_per_screen = available_height / item_height; + let current_time = totp::get_current_unix_time().unwrap_or(0); + VaultUx { content, gam, @@ -181,6 +190,8 @@ impl VaultUx { actions_conn, action_active, usb_dev: usb_device_xous::UsbHid::new(), + last_epoch: current_time / 30, + current_time, } } @@ -456,7 +467,27 @@ impl VaultUx { } pub(crate) fn redraw(&mut self) -> Result<(), xous::Error> { + // to reduce locking thrash, we cache a copy of the current mode at the top of redraw. + // this could lead to some race conditions that lead to awkward problems, we'll see, but it + // is probably worth the performance improvement. + let mode_at_entry = (*self.mode.lock().unwrap()).clone(); + + if mode_at_entry == VaultMode::Totp { // always redraw the title in TOTP mode + self.title_dirty = true; + // always grab the current time, regardless of the mode? saves an extra call to get time... + self.current_time = totp::get_current_unix_time().unwrap_or(0); + // duration bar is hard-coded to once every 30 seconds, even if the keys may not change that often. + let epoch = self.current_time / 30; + if self.last_epoch != epoch { + self.last_epoch = epoch; + // force a redraw of all the items if the epoch has changed + for item in self.filtered_list.iter_mut() { + item.dirty = true; + } + } + } self.clear_area(); + // ---- draw title area ---- if self.title_dirty || self.action_active.load(AtomicOrdering::SeqCst) { let mut title_text = TextView::new(self.content, @@ -470,12 +501,28 @@ impl VaultUx { title_text.draw_border = false; title_text.clear_area = true; title_text.style = GlyphStyle::Large; - match *self.mode.lock().unwrap() { + match mode_at_entry { VaultMode::Fido => write!(title_text, "FIDO").ok(), VaultMode::Totp => write!(title_text, "⏳1234").ok(), VaultMode::Password => write!(title_text, "🔐****").ok(), }; self.gam.post_textview(&mut title_text).expect("couldn't post title"); + if mode_at_entry == VaultMode::Totp { + const BAR_HEIGHT: i16 = 5; + const BAR_GAP: i16 = -10; + // draw the duration bar + let delta = (self.current_time - (self.last_epoch * 30)) as i32; + let width = (self.screensize.x - (self.margin.x * 2)) as i32; + let delta_width = (delta * width * 100) / (30 * 100); + self.gam.draw_rectangle( + self.content, + Rectangle { + tl: Point::new(self.margin.x, TITLE_HEIGHT - (BAR_HEIGHT + BAR_GAP)), + br: Point::new(self.screensize.x - self.margin.x - delta_width as i16, TITLE_HEIGHT - BAR_GAP), + style: DrawStyle { fill_color: Some(PixelColor::Dark), stroke_color: None, stroke_width: 0 } + } + ).ok(); + } self.title_dirty = false; } if self.action_active.load(AtomicOrdering::SeqCst) { @@ -532,7 +579,35 @@ impl VaultUx { if index == selected as usize { box_text.border_width = 4; } - write!(box_text, "{}\n{}", item.name, item.extra).ok(); + match mode_at_entry { + VaultMode::Fido | VaultMode::Password => {write!(box_text, "{}\n{}", item.name, item.extra).ok();}, + VaultMode::Totp => { + let fields = item.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()); + // why code on top? because the item.name can be very long, and it can wrap which would cause + // the code to become hidden. + write!(box_text, "{}\n{}", code, item.name).ok(); + } else { + write!(box_text, "{}", t!("vault.error.record_error", xous::LANG)).ok(); + } + }, + } self.gam.post_textview(&mut box_text).expect("couldn't post list item"); item.dirty = false; }