diff --git a/apps/vault/src/ctap/key_material.rs b/apps/vault/src/ctap/key_material.rs index a49a2109e..9534e58fe 100644 --- a/apps/vault/src/ctap/key_material.rs +++ b/apps/vault/src/ctap/key_material.rs @@ -19,7 +19,6 @@ pub const AAGUID_LENGTH: usize = 16; // certification, and, we're not going to do that. This just returns // a bogus value. pub const AAGUID: &[u8; AAGUID_LENGTH] = - [ + &[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ]; diff --git a/apps/vault/src/ctap/mod.rs b/apps/vault/src/ctap/mod.rs index f55bf946e..f002715b2 100644 --- a/apps/vault/src/ctap/mod.rs +++ b/apps/vault/src/ctap/mod.rs @@ -67,7 +67,6 @@ use ctap_crypto::sha256::Sha256; use ctap_crypto::Hash256; #[cfg(feature = "debug_ctap")] use libtock_drivers::console::Console; -use libtock_drivers::crp; use crate::shims::{ClockValue, Duration}; // This flag enables or disables basic attestation for FIDO2. U2F is unaffected by @@ -233,7 +232,7 @@ where application: &[u8; 32], ) -> Result, Ctap2StatusCode> { let master_keys = self.persistent_store.master_keys()?; - let aes_enc_key = ctap_crypto::aes256::EncryptionKey::new(&master_keys.encryption); + let aes_enc_key = &master_keys.encryption; let mut sk_bytes = [0; 32]; private_key.to_bytes(&mut sk_bytes); let mut iv = [0; 16]; @@ -276,8 +275,8 @@ where ) { return Ok(None); } - let aes_enc_key = ctap_crypto::aes256::EncryptionKey::new(&master_keys.encryption); - let aes_dec_key = ctap_crypto::aes256::DecryptionKey::new(&aes_enc_key); + let aes_enc_key = &master_keys.encryption; + let aes_dec_key = aes_enc_key; let mut iv = [0; 16]; iv.copy_from_slice(&credential_id[..16]); let mut blocks = [[0u8; 16]; 4]; diff --git a/apps/vault/src/ctap/pin_protocol_v1.rs b/apps/vault/src/ctap/pin_protocol_v1.rs index 689db8dce..418d03006 100644 --- a/apps/vault/src/ctap/pin_protocol_v1.rs +++ b/apps/vault/src/ctap/pin_protocol_v1.rs @@ -61,8 +61,8 @@ fn encrypt_hmac_secret_output( if salt_enc.len() != 32 && salt_enc.len() != 64 { return Err(Ctap2StatusCode::CTAP2_ERR_UNSUPPORTED_EXTENSION); } - let aes_enc_key = ctap_crypto::aes256::EncryptionKey::new(shared_secret); - let aes_dec_key = ctap_crypto::aes256::DecryptionKey::new(&aes_enc_key); + let aes_enc_key = shared_secret; + let aes_dec_key = aes_enc_key; // The specification specifically asks for a zero IV. let iv = [0u8; 16]; @@ -102,7 +102,7 @@ fn encrypt_hmac_secret_output( /// Decrypts the new_pin_enc and outputs the found PIN. fn decrypt_pin( - aes_dec_key: &ctap_crypto::aes256::DecryptionKey, + aes_dec_key: &[u8; 32], new_pin_enc: Vec, ) -> Option> { if new_pin_enc.len() != PIN_PADDED_LENGTH { @@ -135,7 +135,7 @@ fn decrypt_pin( /// is hashed, truncated to 16 bytes and persistently stored. fn check_and_store_new_pin( persistent_store: &mut PersistentStore, - aes_dec_key: &ctap_crypto::aes256::DecryptionKey, + aes_dec_key: &[u8; 32], new_pin_enc: Vec, ) -> Result<(), Ctap2StatusCode> { let pin = decrypt_pin(aes_dec_key, new_pin_enc) @@ -201,7 +201,7 @@ impl PinProtocolV1 { &mut self, rng: &mut impl Rng256, persistent_store: &mut PersistentStore, - aes_dec_key: &ctap_crypto::aes256::DecryptionKey, + aes_dec_key: &[u8; 32], pin_hash_enc: Vec, ) -> Result<(), Ctap2StatusCode> { match persistent_store.pin_hash()? { @@ -246,7 +246,7 @@ impl PinProtocolV1 { key_agreement: CoseKey, pin_auth: &[u8], authenticated_message: &[u8], - ) -> Result { + ) -> Result<[u8; 32], Ctap2StatusCode> { let pk: ctap_crypto::ecdh::PubKey = CoseKey::try_into(key_agreement)?; let shared_secret = self.key_agreement_key.exchange_x_sha256(&pk); @@ -254,9 +254,9 @@ impl PinProtocolV1 { return Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID); } - let aes_enc_key = ctap_crypto::aes256::EncryptionKey::new(&shared_secret); - let aes_dec_key = ctap_crypto::aes256::DecryptionKey::new(&aes_enc_key); - Ok(aes_dec_key) + let aes_enc_key = &shared_secret; + let aes_dec_key = aes_enc_key; + Ok(*aes_dec_key) } fn process_get_pin_retries( @@ -332,8 +332,8 @@ impl PinProtocolV1 { let pk: ctap_crypto::ecdh::PubKey = CoseKey::try_into(key_agreement)?; let shared_secret = self.key_agreement_key.exchange_x_sha256(&pk); - let token_encryption_key = ctap_crypto::aes256::EncryptionKey::new(&shared_secret); - let pin_decryption_key = ctap_crypto::aes256::DecryptionKey::new(&token_encryption_key); + let token_encryption_key = &shared_secret; + let pin_decryption_key = token_encryption_key; self.verify_pin_hash_enc(rng, persistent_store, &pin_decryption_key, pin_hash_enc)?; // Assuming PIN_TOKEN_LENGTH % block_size == 0 here. diff --git a/apps/vault/src/ctap/storage.rs b/apps/vault/src/ctap/storage.rs index 72427ee27..91dd038dd 100644 --- a/apps/vault/src/ctap/storage.rs +++ b/apps/vault/src/ctap/storage.rs @@ -31,6 +31,7 @@ use arrayref::array_ref; use cbor::cbor_array_vec; use core::convert::TryInto; use ctap_crypto::rng256::Rng256; +use pddb::Pddb; // Those constants may be modified before compilation to tune the behavior of the key. // @@ -75,7 +76,7 @@ pub struct MasterKeys { /// CTAP persistent storage. pub struct PersistentStore { - store: persistent_store::Store, + pddb: Pddb, } impl PersistentStore { @@ -84,17 +85,16 @@ impl PersistentStore { /// # Safety /// /// This should be at most one instance of persistent store per program lifetime. - pub fn new(rng: &mut impl Rng256) -> PersistentStore { - let storage = new_storage(NUM_PAGES); + pub fn new(_rng: &mut impl Rng256) -> PersistentStore { let mut store = PersistentStore { - store: persistent_store::Store::new(storage).ok().unwrap(), + pddb: Pddb::new() }; - store.init(rng).unwrap(); + store.init().unwrap(); store } /// Initializes the store by creating missing objects. - fn init(&mut self, rng: &mut impl Rng256) -> Result<(), Ctap2StatusCode> { + fn init(&mut self) -> Result<(), Ctap2StatusCode> { // Generate and store the master keys if they are missing. if self.store.find_handle(key::MASTER_KEYS)?.is_none() { let master_encryption_key = rng.gen_uniform_u8x32(); diff --git a/apps/vault/src/ctap/storage/key.rs b/apps/vault/src/ctap/storage/key.rs index 5c5b20e65..f32db9e53 100644 --- a/apps/vault/src/ctap/storage/key.rs +++ b/apps/vault/src/ctap/storage/key.rs @@ -12,54 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::stringify; + /// Number of keys that persist the CTAP reset command. pub const NUM_PERSISTENT_KEYS: usize = 20; -/// Defines a key given its name and value or range of values. -macro_rules! make_key { - ($(#[$doc: meta])* $name: ident = $key: literal..$end: literal) => { - $(#[$doc])* pub const $name: core::ops::Range = $key..$end; - }; - ($(#[$doc: meta])* $name: ident = $key: literal) => { - $(#[$doc])* pub const $name: usize = $key; - }; -} - -/// Returns the range of values of a key given its value description. -#[cfg(test)] -macro_rules! make_range { - ($key: literal..$end: literal) => { - $key..$end - }; - ($key: literal) => { - $key..$key + 1 - }; -} - /// Helper to define keys as a partial partition of a range. -macro_rules! make_partition { - ($range: expr, - $( - $(#[$doc: meta])* - $name: ident = $key: literal $(.. $end: literal)?; - )*) => { - $( - make_key!($(#[$doc])* $name = $key $(.. $end)?); - )* - #[cfg(test)] - const KEY_RANGE: core::ops::Range = $range; - #[cfg(test)] - const ALL_KEYS: &[core::ops::Range] = &[$(make_range!($key $(.. $end)?)),*]; - }; - } - -make_partition! { - // We reserve 0 and 2048+ for possible migration purposes. We add persistent entries starting - // from 1 and going up. We add non-persistent entries starting from 2047 and going down. This - // way, we don't commit to a fixed number of persistent keys. - 1..2048, +macro_rules! define_names { + ($( + $(#[$doc: meta])* + $name: ident = $key: literal $(.. $end: literal)?; + )*) => { + $( + pub const $name: &'static str = stringify!($name); + )* + }; +} +define_names! { // WARNING: Keys should not be deleted but prefixed with `_` to avoid accidentally reusing them. + // the range information is not used by Xous' PDDB, but it is kept around for easy comparison against + // the original OpenSK reference code. /// The attestation private key. ATTESTATION_PRIVATE_KEY = 1; @@ -121,26 +94,3 @@ make_partition! { /// If the entry is absent, the counter is 0. GLOBAL_SIGNATURE_COUNTER = 2047; } - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn enough_credentials() { - use super::super::MAX_SUPPORTED_RESIDENTIAL_KEYS; - assert!(MAX_SUPPORTED_RESIDENTIAL_KEYS <= CREDENTIALS.end - CREDENTIALS.start); - } - - #[test] - fn keys_are_disjoint() { - // Check that keys are in the range. - for keys in ALL_KEYS { - assert!(KEY_RANGE.start <= keys.start && keys.end <= KEY_RANGE.end); - } - // Check that keys are assigned at most once, essentially partitioning the range. - for key in KEY_RANGE { - assert!(ALL_KEYS.iter().filter(|keys| keys.contains(&key)).count() <= 1); - } - } -} diff --git a/apps/vault/src/ctap/timed_permission.rs b/apps/vault/src/ctap/timed_permission.rs index fcc0ada58..af507407e 100644 --- a/apps/vault/src/ctap/timed_permission.rs +++ b/apps/vault/src/ctap/timed_permission.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use libtock_drivers::timer::{ClockValue, Duration}; +use crate::shims::{ClockValue, Duration}; #[derive(Clone, Copy, Debug)] pub enum TimedPermission { diff --git a/apps/vault/src/main.rs b/apps/vault/src/main.rs index 5422d85d4..0f640d017 100644 --- a/apps/vault/src/main.rs +++ b/apps/vault/src/main.rs @@ -14,6 +14,7 @@ use ctap::status_code::Ctap2StatusCode; use ctap::CtapState; mod shims; use shims::*; +use ctap_crypto::rng256::XousRng256; /* UI concept: @@ -94,7 +95,7 @@ fn xmain() -> ! { } }); - let rng = ctap_ctap_crypto::rng256::XousRng256::new(&xns); + let rng = ctap_crypto::rng256::XousRng256::new(&xns); let mut ctap_state = CtapState::new(&mut rng, check_user_presence, boot_time); //let mut ctap_hid = CtapHid::new(); @@ -156,67 +157,92 @@ fn xmain() -> ! { } /* +const KEEPALIVE_DELAY_MS: isize = 100; +const KEEPALIVE_DELAY: Duration = Duration::from_ms(KEEPALIVE_DELAY_MS); +const SEND_TIMEOUT: Duration = Duration::from_ms(1000); -mod api; -use api::*; -mod ctap; -use ctap::hid::{ChannelID, CtapHid, KeepaliveStatus, ProcessedPacket}; -use ctap::status_code::Ctap2StatusCode; -use ctap::CtapState; - -use num_traits::*; -use std::thread; -use usbd_human_interface_device::device::fido::*; - -#[xous::xous_main] -fn xmain() -> ! { - log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Trace); - log::info!("my PID is {}", xous::process::id()); - - let xns = xous_names::XousNames::new().unwrap(); - // TODO: figure out what, if any, should be the limit of connections to the U2F server? - let u2f_sid = xns.register_name(api::SERVER_NAME_U2F, None).expect("can't register server"); - log::trace!("registered with NS -- {:?}", u2f_sid); - - let _ = thread::spawn({ - move || { - let usb = usb_device_xous::UsbHid::new(); - loop { - match usb.u2f_wait_incoming() { - Ok(msg) => { - log::info!("FIDO listener got message: {:?}", msg); +// Returns whether the keepalive was sent, or false if cancelled. +fn send_keepalive_up_needed( + cid: ChannelID, + timeout: Duration, +) -> Result<(), Ctap2StatusCode> { + let keepalive_msg = CtapHid::keepalive(cid, KeepaliveStatus::UpNeeded); + for mut pkt in keepalive_msg { + let status = usb_ctap_hid::send_or_recv_with_timeout(&mut pkt, timeout); + match status { + None => { + #[cfg(feature = "debug_ctap")] + writeln!(Console::new(), "Sending a KEEPALIVE packet timed out").unwrap(); + // TODO: abort user presence test? + } + Some(usb_ctap_hid::SendOrRecvStatus::Error) => panic!("Error sending KEEPALIVE packet"), + Some(usb_ctap_hid::SendOrRecvStatus::Sent) => { + #[cfg(feature = "debug_ctap")] + writeln!(Console::new(), "Sent KEEPALIVE packet").unwrap(); + } + Some(usb_ctap_hid::SendOrRecvStatus::Received) => { + // We only parse one packet, because we only care about CANCEL. + let (received_cid, processed_packet) = CtapHid::process_single_packet(&pkt); + if received_cid != &cid { + #[cfg(feature = "debug_ctap")] + writeln!( + Console::new(), + "Received a packet on channel ID {:?} while sending a KEEPALIVE packet", + received_cid, + ) + .unwrap(); + return Ok(()); + } + match processed_packet { + ProcessedPacket::InitPacket { cmd, .. } => { + if cmd == CtapHid::COMMAND_CANCEL { + // We ignore the payload, we can't answer with an error code anyway. + #[cfg(feature = "debug_ctap")] + writeln!(Console::new(), "User presence check cancelled").unwrap(); + return Err(Ctap2StatusCode::CTAP2_ERR_KEEPALIVE_CANCEL); + } else { + #[cfg(feature = "debug_ctap")] + writeln!( + Console::new(), + "Discarded packet with command {} received while sending a KEEPALIVE packet", + cmd, + ) + .unwrap(); + } } - Err(e) => { - log::warn!("FIDO listener got an error: {:?}", e); + ProcessedPacket::ContinuationPacket { .. } => { + #[cfg(feature = "debug_ctap")] + writeln!( + Console::new(), + "Discarded continuation packet received while sending a KEEPALIVE packet", + ) + .unwrap(); } } } } - }); - - let mut ctap_state = CtapState::new(&mut rng, check_user_presence, boot_time); - let mut ctap_hid = CtapHid::new(); - - loop { - let msg = xous::receive_message(u2f_sid).unwrap(); - match FromPrimitive::from_usize(msg.body.id()) { - Some(Opcode::Quit) => { - log::warn!("Quit received, goodbye world!"); - break; - }, - None => { - log::error!("couldn't convert opcode: {:?}", msg); - } - } } - // clean up our program - log::trace!("main loop exit, destroying servers"); - xns.unregister_server(u2f_sid).unwrap(); - xous::destroy_server(u2f_sid).unwrap(); - log::trace!("quitting"); - xous::terminate_process(0) + Ok(()) } +fn check_user_presence(cid: ChannelID) -> Result<(), Ctap2StatusCode> { + // The timeout is N times the keepalive delay. + const TIMEOUT_ITERATIONS: usize = ctap::TOUCH_TIMEOUT_MS as usize / KEEPALIVE_DELAY_MS as usize; + + /* + This should do the following: + - call send_keepalive_up_needed(cid, KEEPALIVE_DELAY) once every KEEPALIVE_DELAY interval + - pop up a dialog box for TOUCH_TIMEOUT_MS asking to approve "something" + - if TOUCH_TIMEOUT_MS has elapsed and no user approval is received: + - return Err(Ctap2StatusCode::CTAP2_ERR_USER_ACTION_TIMEOUT) + - else return Ok(()) + */ + send_keepalive_up_needed(cid, KEEPALIVE_DELAY)?; + if false { + Ok(()) + } else { + Err(Ctap2StatusCode::CTAP2_ERR_USER_ACTION_TIMEOUT) + } +} */ \ No newline at end of file diff --git a/apps/vault/src/shims.rs b/apps/vault/src/shims.rs index c2d13ce43..a7b586d2f 100644 --- a/apps/vault/src/shims.rs +++ b/apps/vault/src/shims.rs @@ -1,5 +1,16 @@ // 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, PartialEq)] +pub struct ClockFrequency { + hz: usize, +} + +impl ClockFrequency { + pub fn hz(&self) -> usize { + self.hz + } +} #[derive(Copy, Clone, Debug)] pub struct ClockValue {