diff --git a/apps/vault/locales/i18n.json b/apps/vault/locales/i18n.json index 05fe35198..33b54bc7c 100644 --- a/apps/vault/locales/i18n.json +++ b/apps/vault/locales/i18n.json @@ -138,10 +138,28 @@ "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:" + "en": "Enter the OTP shared secret in Base32:", + "ja": "Base32にOTP共有シークレットを入力します。", + "zh": "在 Base32 中输入 OTP 共享密钥:", + "en-tts": "Enter the OTP shared secret in Base32:" + }, + "vault.newitem.is_t_or_h_otp": { + "en": "Which type of OTP record is this (if you don't know, it's probably TOTP)?", + "ja": "これはどのタイプの OTP レコードですか (わからない場合は、おそらく TOTP です)。", + "zh": "这是哪种类型的 OTP 记录(如果您不知道,可能是 TOTP)?", + "en-tts": "Which type of OTP record is this (if you don't know, it's probably TOTP)?" + }, + "vault.newitem.totp": { + "en": "TOTP", + "ja": "TOTP", + "zh": "TOTP", + "en-tts": "TOTP" + }, + "vault.newitem.hotp": { + "en": "HOTP", + "ja": "HOTP", + "zh": "HOTP", + "en-tts": "HOTP" }, "vault.newitem.name": { "en": "Please name the credential:", diff --git a/apps/vault/src/actions.rs b/apps/vault/src/actions.rs index ef291a47a..e65b7422c 100644 --- a/apps/vault/src/actions.rs +++ b/apps/vault/src/actions.rs @@ -343,6 +343,25 @@ impl ActionManager { }, _ => {log::error!("Name entry failed"); self.action_active.store(false, Ordering::SeqCst); return} }; + + self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); + self.modals + .add_list(vec![ + t!("vault.newitem.totp", xous::LANG), + t!("vault.newitem.hotp", xous::LANG), + ]).expect("couldn't create configuration modal"); + let is_totp: bool; + match self.modals.get_radiobutton(t!("vault.newitem.is_t_or_h_otp", xous::LANG)) { + Ok(response) => { + if &response == t!("vault.newitem.totp", xous::LANG) { + is_totp = true; + } else { + is_totp = false; + } + } + _ => {log::error!("Modal selection error"); 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)) @@ -371,6 +390,7 @@ impl ActionManager { } }; 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 mut totp = storage::TotpRecord { version: VAULT_TOTP_REC_VERSION, @@ -378,8 +398,9 @@ impl ActionManager { secret: validated_secret, algorithm: TotpAlgorithm::HmacSha1, digits: 6, - timestep: 30, - ctime: 0, + timestep: if is_totp {30} else {0}, + ctime: 0, + is_hotp: !is_totp, notes: t!("vault.notes", xous::LANG).to_string(), }; @@ -443,7 +464,7 @@ impl ActionManager { }; if choice.is_none() { - let dict = VAULT_TOTP_DICT; + let dict = U2F_APP_DICT; // at the moment only U2F records are supported for editing. The FIDO2 stuff is done with a different record // storage format that's a bit funkier to edit. let maybe_update = match self.pddb.borrow().get( @@ -524,10 +545,12 @@ impl ActionManager { .field(Some(pw.timestep.to_string()), Some(password_validator)) .field(Some(alg), Some(password_validator)) .field(Some(pw.digits.to_string()), Some(password_validator)) + .field(Some(if pw.is_hotp {"HOTP".to_string()} else {"TOTP".to_string()}), Some(password_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(); + pw.is_hotp = if edit_data.content()[6].content.as_str().unwrap().to_string().to_uppercase() == "HOTP" {true} else {false}; if let Ok(t) = u64::from_str_radix(edit_data.content()[3].content.as_str().unwrap(), 10) { pw.timestep = t; } @@ -808,7 +831,13 @@ impl ActionManager { Ok(_len) => { if let Some(totp) = storage::TotpRecord::try_from(data).ok() { let alg: String = totp.algorithm.into(); - let extra = format!("{}:{}:{}:{}", totp.secret, totp.digits, totp.timestep, alg); + let extra = format!("{}:{}:{}:{}:{}", + totp.secret, + totp.digits, + totp.timestep, + alg, + if totp.is_hotp {"HOTP"} else {"TOTP"} + ); let desc = format!("{}", totp.name); let li = ListItem { name: desc, @@ -947,7 +976,7 @@ impl ActionManager { strict: true, }; let password = pg.generate_one().unwrap(); - let record = storage::PasswordRecord { + let mut record = storage::PasswordRecord { version: VAULT_PASSWORD_REC_VERSION, description, username, @@ -958,7 +987,7 @@ impl ActionManager { count: 0, }; - match self.storage.borrow_mut().new_record(record, None) { + match self.storage.borrow_mut().new_record(&mut record, None, true) { Ok(_) => {}, Err(e) => log::error!("PW Error: {:?}", e), }; @@ -1058,7 +1087,7 @@ impl ActionManager { 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 = storage::TotpRecord { + let mut record = storage::TotpRecord { version: VAULT_TOTP_REC_VERSION, secret: base32::encode(base32::Alphabet::RFC4648 { padding: false }, &secret_bytes), name, @@ -1067,15 +1096,16 @@ impl ActionManager { digits: 6, timestep: 30, ctime: 0, + is_hotp: false, }; - match self.storage.borrow_mut().new_record(record, None) { + match self.storage.borrow_mut().new_record(&mut record, None, true) { Ok(_) => {}, Err(e) => log::error!("PW Error: {:?}", e), }; } // specific TOTP entry with a known shared secret for testing - let record = storage::TotpRecord { + let mut record = storage::TotpRecord { version: VAULT_TOTP_REC_VERSION, secret: "I65VU7K5ZQL7WB4E".to_string(), name: "totp@authenticationtest.com".to_string(), @@ -1084,9 +1114,10 @@ impl ActionManager { digits: 6, timestep: 30, ctime: 0, + is_hotp: false, }; - match self.storage.borrow_mut().new_record(record, None) { + match self.storage.borrow_mut().new_record(&mut record, None, true) { Ok(_) => {}, Err(e) => log::error!("PW Error: {:?}", e), }; diff --git a/apps/vault/src/storage.rs b/apps/vault/src/storage.rs index 2191f0485..2f7decde7 100644 --- a/apps/vault/src/storage.rs +++ b/apps/vault/src/storage.rs @@ -12,7 +12,7 @@ const VAULT_PASSWORD_DICT: &'static str = "vault.passwords"; const VAULT_TOTP_DICT: &'static str = "vault.totp"; const VAULT_TOTP_ALLOC_HINT: usize = 128; const VAULT_PASSWORD_REC_VERSION: u32 = 1; -const VAULT_TOTP_REC_VERSION: u32 = 1; +const VAULT_TOTP_REC_VERSION: u32 = 2; #[derive(Debug)] pub enum Error { @@ -315,6 +315,7 @@ pub struct TotpRecord { pub digits: u32, pub timestep: u64, pub ctime: u64, + pub is_hotp: bool, } #[derive(Debug)] @@ -324,6 +325,7 @@ pub enum TOTPSerializationError { BadDigitsAmount, BadCtime, BadTimestep, + BadHotp, MalformedInput, } @@ -389,6 +391,18 @@ impl StorageContent for TotpRecord { return Err(TOTPSerializationError::BadTimestep)?; } } + "hotp" => { + if let Ok(setting) = u8::from_str_radix(data, 10) { + if setting != 0 { + pr.is_hotp = true; + } else { + pr.is_hotp = false; + } + } else { + log::warn!("hotp variant error"); + return Err(TOTPSerializationError::BadHotp)?; + } + } _ => { log::warn!( "unexpected tag {} encountered parsing TOTP info, ignoring", @@ -408,7 +422,7 @@ impl StorageContent for TotpRecord { fn to_vec(&self) -> Vec { let ta: String = self.algorithm.into(); format!( - "{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n", + "{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n", "version", self.version, "secret", @@ -423,6 +437,8 @@ impl StorageContent for TotpRecord { self.digits, "timestep", self.timestep, + "hotp", + if self.is_hotp {1} else {0}, "ctime", self.ctime, ) @@ -451,6 +467,7 @@ impl TryFrom> for TotpRecord { digits: 0, ctime: 0, timestep: 0, + is_hotp: false, }; let lines = desc_str.split('\n'); for line in lines { @@ -497,6 +514,18 @@ impl TryFrom> for TotpRecord { return Err(TOTPSerializationError::BadTimestep); } } + "hotp" => { + if let Ok(setting) = u8::from_str_radix(data, 10) { + if setting != 0 { + pr.is_hotp = true; + } else { + pr.is_hotp = false; + } + } else { + log::warn!("hotp error"); + return Err(TOTPSerializationError::BadHotp); + } + } _ => { log::warn!( "unexpected tag {} encountered parsing TOTP info, ignoring", @@ -517,7 +546,7 @@ impl From for Vec { fn from(tr: TotpRecord) -> Self { let ta: String = tr.algorithm.into(); format!( - "{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n", + "{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n", "version", tr.version, "secret", @@ -532,6 +561,8 @@ impl From for Vec { tr.digits, "timestep", tr.timestep, + "hotp", + if tr.is_hotp {1} else {0}, "ctime", tr.ctime, ) diff --git a/apps/vault/src/ux/framework.rs b/apps/vault/src/ux/framework.rs index c43eeb932..892194ab8 100644 --- a/apps/vault/src/ux/framework.rs +++ b/apps/vault/src/ux/framework.rs @@ -291,7 +291,9 @@ impl VaultUx { } fn mark_as_dirty(&mut self, index: usize) { let list_len = self.filtered_list.len(); - self.filtered_list[index.min(list_len - 1)].dirty = true; + if list_len > 0 { + self.filtered_list[index.min(list_len - 1)].dirty = true; + } } fn mark_screen_as_dirty(&mut self, index: usize) { let page = index as i16 / self.items_per_screen; @@ -303,6 +305,17 @@ impl VaultUx { item.dirty = true; } } + fn backpropagate_item(&mut self, updated_item: ListItem) -> bool { + for item in self.item_list.lock().unwrap().iter_mut() { + if item.guid == updated_item.guid { + item.name = updated_item.name.to_string(); + item.extra = updated_item.extra.to_string(); + item.dirty = true; + return true; + } + } + false + } pub(crate) fn nav(&mut self, dir: NavDir) { match dir { NavDir::Up => { @@ -576,26 +589,37 @@ impl VaultUx { 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 { + if fields.len() == 5 { 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 step_seconds = u64::from_str_radix(fields[2], 10).unwrap_or(30); + let algorithm = TotpAlgorithm::try_from(fields[3]).unwrap_or(TotpAlgorithm::HmacSha1); + let is_hotp = fields[4].to_uppercase() == "HOTP"; let totp = totp::TotpEntry { - step_seconds, + step_seconds: if !is_hotp {step_seconds as u16} else {1}, // step_seconds is re-used by hotp as the code. 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(); + if !is_hotp { + 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 { + let code = generate_totp_code( + step_seconds, + &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, "HOTP {}\n{}", code, item.name).ok(); + } } else { write!(box_text, "{}", t!("vault.error.record_error", xous::LANG)).ok(); } @@ -734,27 +758,120 @@ impl VaultUx { } } self.pddb.borrow().sync().ok(); + // force a redraw of the record as the access count updated + self.filtered_list[self.selection_index].dirty = true; + self.backpropagate_item(self.filtered_list[self.selection_index].clone()); } VaultMode::Totp => { let fields = self.filtered_list[self.selection_index].extra.split(':').collect::>(); - if fields.len() == 4 { + if fields.len() == 5 { 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 step_seconds = u64::from_str_radix(fields[2], 10).unwrap_or(30); + let algorithm = TotpAlgorithm::try_from(fields[3]).unwrap_or(TotpAlgorithm::HmacSha1); + let is_hotp = fields[4] == "HOTP"; let totp = totp::TotpEntry { - step_seconds, + step_seconds: if !is_hotp {step_seconds as u16} else {1}, // step_seconds is re-used by hotp as the code. 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(); + let code = if !is_hotp { + generate_totp_code( + totp::get_current_unix_time().unwrap_or(0), + &totp + ).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string()) + } else { + generate_totp_code( + step_seconds, + &totp + ).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string()) + }; + match self.usb_dev.send_str(&code) { + Ok(_) => { + if is_hotp { + // update the count once the HOTP has been typed successfully + let entry = self.filtered_list[self.selection_index].guid.to_string(); + + // this get determines which basis the key is in + let (basis, hotp_rec) = match self.pddb.borrow().get( + crate::actions::VAULT_TOTP_DICT, + &entry, + None, true, true, + Some(256), Some(crate::basis_change) + ) { + Ok(mut app_data) => { + let attr = app_data.attributes().expect("couldn't get attributes"); + let len = app_data.attributes().unwrap().len; + let mut data = Vec::::with_capacity(len); + data.resize(len, 0); + match app_data.read_exact(&mut data) { + Ok(_len) => { + if let Some(mut totp_rec) = storage::TotpRecord::try_from(data).ok() { + totp_rec.timestep += 1; + (attr.basis, totp_rec) + } else { + log::error!("Couldn't deserialize HOTP: {:?}", entry); + return Err(xous::Error::InternalError); + } + } + Err(e) => { + log::error!("Couldn't access HOTP key: {:?}", e); + return Err(xous::Error::InternalError); + }, + } + } + Err(e) => { + log::error!("error updating HOTP count: {:?}", e); + return Err(xous::Error::InternalError); + } + }; + // remove the old entry, specifically only in the most recently open basis. + match self.pddb.borrow().delete_key(crate::actions::VAULT_TOTP_DICT, &entry, Some(&basis)) { + Ok(_) => {} + Err(_e) => { + return Err(xous::Error::InternalError); + } + } + // update the "extra" field, because the timestep field has been altered + let alg: String = hotp_rec.algorithm.into(); + self.filtered_list[self.selection_index].extra = format!("{}:{}:{}:{}:{}", + hotp_rec.secret, + hotp_rec.digits, + hotp_rec.timestep, + alg, + if hotp_rec.is_hotp {"HOTP"} else {"TOTP"} + ); + self.filtered_list[self.selection_index].dirty = true; + self.backpropagate_item(self.filtered_list[self.selection_index].clone()); + // now write to disk + match self.pddb.borrow().get( + crate::actions::VAULT_TOTP_DICT, &entry, Some(&basis), + false, true, Some(crate::actions::VAULT_ALLOC_HINT), + Some(crate::basis_change) + ) { + Ok(mut record) => { + let ser: Vec = storage::TotpRecord::into(hotp_rec); + 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(); + } + }, + _ => () + }; } } _ => log::error!("Illegal state! we shouldn't be having an autotype on {:?}", mode_cache), diff --git a/apps/vault/src/vendor_commands.rs b/apps/vault/src/vendor_commands.rs index 488c538a2..75e0564dc 100644 --- a/apps/vault/src/vendor_commands.rs +++ b/apps/vault/src/vendor_commands.rs @@ -274,6 +274,7 @@ fn handle_restore(data: Vec, xns: &xous_names::XousNames) -> Result, timestep: elem.step_seconds, ctime: 0, // Will be filled in later by storage::new_totp_record(); notes: t!("vault.notes", xous::LANG).to_string(), + is_hotp: false, }; entries.push(Box::new(totp)); }