diff --git a/apps/vault/libraries/backup/src/lib.rs b/apps/vault/libraries/backup/src/lib.rs index b08e82d1b..47b387292 100644 --- a/apps/vault/libraries/backup/src/lib.rs +++ b/apps/vault/libraries/backup/src/lib.rs @@ -134,7 +134,9 @@ impl TryFrom for TotpEntry { let digit_count = extract_unsigned(digit_count.unwrap())? as u32; let algorithm: HashAlgorithms = algorithm.unwrap().try_into()?; let name = extract_string(name.unwrap())?; - let hotp = extract_bool(hotp.unwrap())?; + let hotp = extract_bool(hotp.unwrap_or( + cbor::Value::Simple(cbor::SimpleValue::FalseValue) + )).unwrap_or(false); Ok(TotpEntry { step_seconds, diff --git a/apps/vault/src/actions.rs b/apps/vault/src/actions.rs index d9c75e056..583740cff 100644 --- a/apps/vault/src/actions.rs +++ b/apps/vault/src/actions.rs @@ -1070,6 +1070,7 @@ impl<'a> ActionManager<'a> { } }, } + drop(mutex); } } VaultMode::Totp => { @@ -1264,8 +1265,6 @@ impl<'a> ActionManager<'a> { #[cfg(feature="vault-testing")] pub(crate) fn populate_tests(&mut self) { - use serialize_app_info; - self.modals.dynamic_notification(Some("Creating test entries..."), None).ok(); let words = [ "bunnie", "foo", "turtle.net", "Fox.ng", "Bear", "dog food", "Cat.com", "FUzzy", "1off", "www_test_site_com/long_name/stupid/foo.htm", diff --git a/apps/vault/src/ctap/hid/mod.rs b/apps/vault/src/ctap/hid/mod.rs index 4f969b21e..a720def8f 100644 --- a/apps/vault/src/ctap/hid/mod.rs +++ b/apps/vault/src/ctap/hid/mod.rs @@ -31,6 +31,10 @@ use std::time::Duration; #[cfg(test)] use enum_iterator::IntoEnumIterator; +use crate::vault_api::{ + COMMAND_BACKUP_TOTP_CODES, COMMAND_RESTORE_TOTP_CODES, COMMAND_RESET_SESSION +}; + pub type HidPacket = [u8; 64]; pub type ChannelID = [u8; 4]; @@ -51,6 +55,9 @@ pub enum CtapHidCommand { Keepalive = 0x3B, Error = 0x3F, // The vendor range starts here, going from 0x40 to 0x7F. + RestoreTotpCodes = COMMAND_RESTORE_TOTP_CODES as _, + BackupTotpCodes = COMMAND_BACKUP_TOTP_CODES as _, + ResetSession = COMMAND_RESET_SESSION as _, } impl From for CtapHidCommand { @@ -64,6 +71,9 @@ impl From for CtapHidCommand { x if x == CtapHidCommand::Cbor as u8 => CtapHidCommand::Cbor, x if x == CtapHidCommand::Cancel as u8 => CtapHidCommand::Cancel, x if x == CtapHidCommand::Keepalive as u8 => CtapHidCommand::Keepalive, + x if x == CtapHidCommand::RestoreTotpCodes as u8 => CtapHidCommand::RestoreTotpCodes, + x if x == CtapHidCommand::BackupTotpCodes as u8 => CtapHidCommand::BackupTotpCodes, + x if x == CtapHidCommand::ResetSession as u8 => CtapHidCommand::ResetSession, // This includes the actual error code 0x3F. Error is not used for incoming packets in // the specification, so we can safely reuse it for unknown bytes. _ => CtapHidCommand::Error, @@ -237,7 +247,7 @@ impl CtapHid { ) -> Option { match self.assembler.parse_packet(env, packet, clock_value) { Ok(Some(message)) => { - log::debug!("Received message: {:02x?}", message); + log::trace!("Received message: {:02x?}", message); self.preprocess_message(message) } Ok(None) => { @@ -315,6 +325,11 @@ impl CtapHid { None } CtapHidCommand::Wink => Some(message), + CtapHidCommand::BackupTotpCodes | + CtapHidCommand::RestoreTotpCodes | + CtapHidCommand::ResetSession => { + Some(message) + } _ => { // Unknown or unsupported command. Some(CtapHid::error_message(cid, CtapHidError::InvalidCmd)) diff --git a/apps/vault/src/ctap/main_hid.rs b/apps/vault/src/ctap/main_hid.rs index 74244f9ed..6afed98ea 100644 --- a/apps/vault/src/ctap/main_hid.rs +++ b/apps/vault/src/ctap/main_hid.rs @@ -30,6 +30,11 @@ pub struct MainHid { wink_permission: TimedPermission, } +pub enum HidIterType { + Ctap(HidPacketIterator), + Vendor(Message), +} + impl MainHid { const WINK_TIMEOUT_DURATION: Duration = Duration::from_millis(5000); @@ -56,13 +61,22 @@ impl MainHid { packet: &HidPacket, now: Instant, ctap_state: &mut CtapState, - ) -> HidPacketIterator { + ) -> HidIterType { if let Some(message) = self.hid.parse_packet(env, packet, now) { let processed_message = self.process_message(env, message, now, ctap_state); - log::debug!("Sending message: {:02x?}", processed_message); - CtapHid::split_message(processed_message) + match processed_message.cmd { + CtapHidCommand::RestoreTotpCodes | + CtapHidCommand::BackupTotpCodes | + CtapHidCommand::ResetSession => { + HidIterType::Vendor(processed_message) + } + _ => { + log::trace!("Sending message: {:02x?}", processed_message); + HidIterType::Ctap(CtapHid::split_message(processed_message)) + } + } } else { - HidPacketIterator::none() + HidIterType::Ctap(HidPacketIterator::none()) } } diff --git a/apps/vault/src/ctap/timed_permission.rs b/apps/vault/src/ctap/timed_permission.rs index e17ec3210..f0e833047 100644 --- a/apps/vault/src/ctap/timed_permission.rs +++ b/apps/vault/src/ctap/timed_permission.rs @@ -57,6 +57,7 @@ impl TimedPermission { #[cfg(feature = "with_ctap1")] #[derive(Debug)] +#[allow(dead_code)] pub struct U2fUserPresenceState { // If user presence was recently requested, its timeout is saved here. needs_up: TimedPermission, @@ -128,6 +129,7 @@ impl U2fUserPresenceState { self.has_up = self.has_up.check_expiration(now); } #[cfg(feature="xous")] + #[allow(dead_code)] pub fn check_expiration(&mut self, _now: Instant) { } } diff --git a/apps/vault/src/env/xous/mod.rs b/apps/vault/src/env/xous/mod.rs index 964d04fc2..40e2ccf90 100644 --- a/apps/vault/src/env/xous/mod.rs +++ b/apps/vault/src/env/xous/mod.rs @@ -15,7 +15,6 @@ use ctap_crypto::rng256::XousRng256; use xous_names::XousNames; use crate::env::xous::storage::XousUpgradeStorage; use usbd_human_interface_device::device::fido::*; -use pddb::Pddb; use modals::Modals; use locales::t; use std::io::{Read, Write}; @@ -92,8 +91,6 @@ pub struct XousEnv { #[cfg(feature = "vendor_hid")] vendor_connection: XousHidConnection, modals: Modals, - pddb: Pddb, - main_cid: xous::CID, last_user_presence_request: Option::, ctap1_cid: xous::CID, } @@ -212,7 +209,7 @@ impl XousEnv { } // determine the application info string let app_id_str = hex::encode(request.app_id); - if let Some(mut info) = { + if let Some(info) = { // fetch the application info, if it exists log::debug!("querying U2F record {}", app_id_str); // add code to query the PDDB here to look for the k/v mapping of this app ID @@ -413,8 +410,6 @@ impl XousEnv { endpoint: UsbEndpoint::VendorHid, }, modals: modals::Modals::new(&xns).unwrap(), - pddb: pddb::Pddb::new(), - main_cid: conn, last_user_presence_request: None, ctap1_cid, } diff --git a/apps/vault/src/lib.rs b/apps/vault/src/lib.rs index 710340319..1351bf5b5 100644 --- a/apps/vault/src/lib.rs +++ b/apps/vault/src/lib.rs @@ -17,7 +17,7 @@ #[macro_use] extern crate arrayref; -use crate::ctap::hid::{HidPacket, HidPacketIterator}; +use crate::ctap::hid::HidPacket; use crate::ctap::main_hid::MainHid; #[cfg(feature = "vendor_hid")] use crate::ctap::vendor_hid::VendorHid; @@ -25,6 +25,8 @@ use crate::ctap::CtapState; pub use crate::ctap::Transport; use crate::env::Env; use std::time::{Instant, Duration}; +#[cfg(feature="xous")] +use ctap::main_hid::HidIterType; // Those macros should eventually be split into trace, debug, info, warn, and error macros when // adding either the defmt or log feature and crate dependency. @@ -90,7 +92,7 @@ impl Ctap { packet: &HidPacket, transport: Transport, now: Instant, - ) -> HidPacketIterator { + ) -> HidIterType { match transport { Transport::MainHid => { self.hid diff --git a/apps/vault/src/main.rs b/apps/vault/src/main.rs index 08e83cea4..84264404a 100644 --- a/apps/vault/src/main.rs +++ b/apps/vault/src/main.rs @@ -2,8 +2,6 @@ #![cfg_attr(target_os = "none", no_main)] mod ux; -mod shims; -use shims::*; mod submenu; mod actions; mod totp; @@ -14,10 +12,8 @@ mod migration_v1; use locales::t; -use vault::ctap::status_code::Ctap2StatusCode; -use vault::ctap::hid::HidPacketIterator; +use vault::ctap::main_hid::HidIterType; use vault::env::xous::XousEnv; -use vault::api::connection::{HidConnection, SendOrRecvStatus}; use vault::env::Env; use vault::{ SELF_CONN, Transport, VaultOp @@ -31,14 +27,13 @@ use crate::vendor_commands::VendorSession; use ux::framework::{VaultUx, DEFAULT_FONT, FONT_LIST, name_to_style}; use xous_ipc::Buffer; use xous::{send_message, Message}; -use pddb::Pddb; use usbd_human_interface_device::device::fido::*; use num_traits::*; use std::thread; use core::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; -use std::time::{Instant, Duration}; +use std::time::Instant; use std::collections::BTreeMap; @@ -148,50 +143,6 @@ impl ItemLists { } const ERR_TIMEOUT_MS: usize = 5000; -const SEND_TIMEOUT: Duration = Duration::from_millis(1000); -const KEEPALIVE_DELAY: Duration = Duration::from_millis(100); -// The reply/replies that are queued for each endpoint. -struct EndpointReply { - reply: HidPacketIterator, -} - -impl EndpointReply { - pub fn new() -> Self { - EndpointReply { - reply: HidPacketIterator::none(), - } - } -} -const NUM_ENDPOINTS: usize = 1; -// A single packet to send. -struct SendPacket { - packet: [u8; 64], -} - -struct EndpointReplies { - replies: [EndpointReply; NUM_ENDPOINTS], -} - -impl EndpointReplies { - pub fn new() -> Self { - EndpointReplies { - replies: [ - EndpointReply::new(), - ], - } - } - - pub fn next_packet(&mut self) -> Option { - for ep in self.replies.iter_mut() { - if let Some(packet) = ep.reply.next() { - return Some(SendPacket { - packet, - }); - } - } - None - } -} fn main() -> ! { log_server::init_wait().unwrap(); @@ -235,8 +186,6 @@ fn main() -> ! { let conn = conn.clone(); move || { let xns = xous_names::XousNames::new().unwrap(); - let tt = ticktimer_server::Ticktimer::new().unwrap(); - let mut vendor_session = VendorSession::default(); // block until the PDDB is mounted let pddb = pddb::Pddb::new(); @@ -253,35 +202,94 @@ fn main() -> ! { } }; - let mut env = XousEnv::new(conn); - let mut replies = EndpointReplies::new(); + let env = XousEnv::new(conn); // only run the main loop if the SoC is compatible if env.is_soc_compatible() { let mut ctap = vault::Ctap::new(env, Instant::now()); - let mut pkt_request: Option::<[u8; 64]> = None; loop { - /////////// - // TODO: vendor command for gsora backup protocol has disappeared. - /////////// match ctap.env().main_hid_connection().u2f_wait_incoming() { Ok(msg) => { let mutex = opensk_mutex.lock().unwrap(); - log::debug!("Received U2F packet"); - let reply = ctap.process_hid_packet(&msg.packet, Transport::MainHid, Instant::now()); - for pkt_reply in reply { - let mut reply = RawFidoMsg::default(); - reply.packet.copy_from_slice(&pkt_reply); - let status = ctap.env().main_hid_connection().u2f_send(reply); - match status { - Ok(()) => { - log::debug!("Sent U2F packet"); + log::trace!("Received U2F packet"); + let typed_reply = ctap.process_hid_packet(&msg.packet, Transport::MainHid, Instant::now()); + match typed_reply { + HidIterType::Ctap(reply) => { + for pkt_reply in reply { + let mut reply = RawFidoMsg::default(); + reply.packet.copy_from_slice(&pkt_reply); + let status = ctap.env().main_hid_connection().u2f_send(reply); + match status { + Ok(()) => { + log::trace!("Sent U2F packet"); + } + Err(e) => { + log::error!("Error sending U2F packet: {:?}", e); + } + } } - Err(e) => { - log::error!("Error sending U2F packet: {:?}", e); + } + HidIterType::Vendor(msg) => { + let reply = + match vendor_commands::handle_vendor_data( + msg.cmd as u8, + msg.cid, + msg.payload, + &mut vendor_session + ) { + Ok(return_payload) => { + // if None, this means we've finished parsing all that + // was needed, and we handle/respond with real data + + match return_payload { + Some(data) => data, + None => { + log::debug!("starting processing of vendor data..."); + let resp = vendor_commands::handle_vendor_command( + &mut vendor_session, + allow_host.load(Ordering::SeqCst) + ); + log::debug!("finished processing of vendor data!"); + + match vendor_session.is_backup() { + true => { + if vendor_session.has_backup_data() { + resp + } else { + vendor_session = VendorSession::default(); + resp + } + }, + false => { + vendor_session = VendorSession::default(); + resp + } + } + } + } + } + Err(session_error) => { + // reset the session + vendor_session = VendorSession::default(); + + session_error.ctaphid_error(msg.cid) + } + }; + for pkt_reply in reply { + let mut reply = RawFidoMsg::default(); + reply.packet.copy_from_slice(&pkt_reply); + let status = ctap.env().main_hid_connection().u2f_send(reply); + match status { + Ok(()) => { + log::trace!("Sent U2F packet"); + } + Err(e) => { + log::error!("Error sending U2F packet: {:?}", e); + } + } } } } - // mutex goes out of scope here, and is released + drop(mutex); } Err(e) => { match e { diff --git a/apps/vault/src/migration_v1.rs b/apps/vault/src/migration_v1.rs index b0a816e94..22f89b42b 100644 --- a/apps/vault/src/migration_v1.rs +++ b/apps/vault/src/migration_v1.rs @@ -39,6 +39,9 @@ fn decode_hex(s: &str) -> Result, ParseIntError> { /// `./configure.py --private-key=crypto_data/opensk.key --certificate=crypto_data/opensk_cert.pem` pub fn migrate(pddb: &Pddb) -> Result<(), xous::Error> { if !pddb.list_dict(None).unwrap().contains(&persistent_store::store::OPENSK2_DICT.to_string()) { + let xns = xous_names::XousNames::new().unwrap(); + let modals = modals::Modals::new(&xns).unwrap(); + modals.dynamic_notification(Some("Migrating FIDO Database"), Some("Please wait...")).ok(); // build the attestation keys let pk = decode_hex("b8c3abd05cbe17b2faf87659c6f73e8467832112a0e609807cb68996c9a0c6a8").unwrap(); pddb.get( @@ -72,17 +75,16 @@ pub fn migrate(pddb: &Pddb) -> Result<(), xous::Error> { migrate_one(pddb, FIDO_PERSISTENT_DICT, "AAGUID", key::AAGUID)?; // port master keys migrate_one(pddb, FIDO_DICT, "MASTER_KEYS", key::_RESERVED_KEY_STORE)?; + migrate_one(pddb, FIDO_DICT, "GLOBAL_SIGNATURE_COUNTER", key::GLOBAL_SIGNATURE_COUNTER)?; // port other settings // Turns out that porting over the PIN is a mistake. Just clear it. - - // migrate_one(pddb, FIDO_DICT, "MIN_PIN_LENGTH", key::MIN_PIN_LENGTH)?; - // migrate_one(pddb, FIDO_DICT, "PIN_RETRIES", key::PIN_RETRIES)?; - migrate_one(pddb, FIDO_DICT, "GLOBAL_SIGNATURE_COUNTER", key::GLOBAL_SIGNATURE_COUNTER)?; + migrate_one(pddb, FIDO_DICT, "MIN_PIN_LENGTH", key::MIN_PIN_LENGTH)?; + migrate_one(pddb, FIDO_DICT, "PIN_RETRIES", key::PIN_RETRIES)?; // PIN_HASH requires appending a length to the end. This is an `advisory` field, so we...just make up a value of 8. // This may not actually be the length used, but it's likely to be long enough to avoid forcing a re-PIN event because // the PIN hash is too short. - // migrate_pin(pddb)?; + migrate_pin(pddb)?; // migrate credentials let creds = match pddb.list_keys(FIDO_CRED_DICT, None) { @@ -122,6 +124,7 @@ pub fn migrate(pddb: &Pddb) -> Result<(), xous::Error> { } } pddb.sync().ok(); + modals.dynamic_notification_close().ok(); if successful_migrations == expected_creds { Ok(()) } else { @@ -173,6 +176,12 @@ fn migrate_one ( fn migrate_pin ( pddb: &Pddb, ) -> Result<(), xous::Error> { + // create the key for a forced PIN change + // pddb.get( + // persistent_store::store::OPENSK2_DICT, + // &key::FORCE_PIN_CHANGE.to_string(), + // None, true, true, None, None:: + // ).ok(); let legacy_dict = FIDO_DICT; let legacy_key = "PIN_HASH"; let new_key = key::PIN_PROPERTIES; @@ -183,8 +192,8 @@ fn migrate_pin ( ) { Ok(mut key) => { let mut data = Vec::::new(); + data.push(8); // add a bogus "length" advisory field of 8 let len = key.read_to_end(&mut data).map_err(|_| xous::Error::AccessDenied)? + 1; - data.push(5); // add a bogus "length" advisory field of 8 let mut new_key = pddb.get( persistent_store::store::OPENSK2_DICT, &new_key.to_string(), diff --git a/apps/vault/src/shims.rs b/apps/vault/src/shims.rs deleted file mode 100644 index 0c6b4a87b..000000000 --- a/apps/vault/src/shims.rs +++ /dev/null @@ -1,138 +0,0 @@ -#![allow(dead_code)] // a fair bit of dead code here because we have adapters from Tock functions we don't use -// shims for Tock calls, to avoid having to recode some fairly pervasive patterns in OpenSK -use std::ops::{Sub, Add, AddAssign}; - - -#[derive(Copy, Clone, Debug)] -pub struct ClockValue { - num_ticks: i64, -} - -impl ClockValue { - pub const fn new(num_ticks: i64, _clock_hz: usize) -> ClockValue { - ClockValue { - num_ticks, - } - } - - pub fn num_ticks(&self) -> i64 { - self.num_ticks - } - - pub fn ms(&self) -> i64 { - self.num_ticks - } - - pub fn ms_f64(&self) -> f64 { - self.num_ticks as f64 - } - - pub fn wrapping_add(self, duration: Duration) -> ClockValue { - ClockValue { - num_ticks: self.num_ticks.wrapping_add(duration.ms), - } - } - - pub fn wrapping_sub(self, other: ClockValue) -> Option> { - Some(Duration::from_ms(self.num_ticks - other.num_ticks)) - } -} - - -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct Duration { - ms: T, -} - -impl Duration { - pub const fn from_ms(ms: T) -> Duration { - Duration { ms } - } -} - -impl Duration -where - T: Copy, -{ - pub fn ms(&self) -> T { - self.ms - } -} - -impl Sub for Duration -where - T: Sub, -{ - type Output = Duration; - - fn sub(self, other: Duration) -> Duration { - Duration { - ms: self.ms - other.ms, - } - } -} - -#[derive(Copy, Clone, Debug)] -pub struct Timestamp { - ms: T, -} - -impl Timestamp { - pub const fn from_ms(ms: T) -> Timestamp { - Timestamp { ms } - } -} - -impl Timestamp -where - T: Copy, -{ - pub fn ms(&self) -> T { - self.ms - } -} - -impl Timestamp { - pub fn from_clock_value(value: ClockValue) -> Timestamp { - Timestamp { ms: value.ms() } - } -} - -impl Timestamp { - pub fn from_clock_value(value: ClockValue) -> Timestamp { - Timestamp { ms: value.ms_f64() } - } -} - -impl Sub for Timestamp -where - T: Sub, -{ - type Output = Duration; - - fn sub(self, other: Timestamp) -> Duration { - Duration::from_ms(self.ms - other.ms) - } -} - -impl Add> for Timestamp -where - T: Copy + Add, -{ - type Output = Timestamp; - - fn add(self, duration: Duration) -> Timestamp { - Timestamp { - ms: self.ms + duration.ms(), - } - } -} - -impl AddAssign> for Timestamp -where - T: Copy + AddAssign, -{ - fn add_assign(&mut self, duration: Duration) { - self.ms += duration.ms(); - } -} diff --git a/apps/vault/src/vault_api.rs b/apps/vault/src/vault_api.rs index d7f9851ae..9f1962bf3 100644 --- a/apps/vault/src/vault_api.rs +++ b/apps/vault/src/vault_api.rs @@ -7,6 +7,10 @@ use chrono::{Utc, DateTime, NaiveDateTime}; // This file contains items that are used simultaneously within OpenSK and the `vault` app itself. // These items need to be pulled in via both `lib` and `main` scopes. +// Vault-specific command to upload TOTP codes +pub const COMMAND_RESTORE_TOTP_CODES: u8 = 0x71; +pub const COMMAND_BACKUP_TOTP_CODES: u8 = 0x72; +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"; diff --git a/apps/vault/src/vendor_commands.rs b/apps/vault/src/vendor_commands.rs index 564302aab..d030d1710 100644 --- a/apps/vault/src/vendor_commands.rs +++ b/apps/vault/src/vendor_commands.rs @@ -8,11 +8,9 @@ use vault::{ use crate::totp::TotpAlgorithm; use crate::storage::{Error, PasswordRecord, TotpRecord}; -// Vault-specific command to upload TOTP codes -pub const COMMAND_RESTORE_TOTP_CODES: u8 = 0x71; -pub const COMMAND_BACKUP_TOTP_CODES: u8 = 0x72; -pub const COMMAND_RESET_SESSION: u8 = 0x74; - +use vault::vault_api::{ + COMMAND_BACKUP_TOTP_CODES, COMMAND_RESTORE_TOTP_CODES, COMMAND_RESET_SESSION +}; // TODO(gsora): add something that checks whether or not a command works. pub enum SessionError {