From efbb52e44da5ca73f0885adbb967ab4f1a58d603 Mon Sep 17 00:00:00 2001 From: K Panuragh Date: Wed, 11 Nov 2026 22:25:24 +0530 Subject: [PATCH 1/3] ui: Don't resend a PIN that was already tried Mistyping a PIN and then sending the same wrong PIN again wastes one of the device's few PIN retries. The UI now remembers which PINs were sent to the connected device during a request and, when the user enters one of them again, tells them so instead of sending it. PINs are not stored. Each is hashed with Argon2id keyed with a random pepper and salted with a random salt, both per request. The pepper, salt, hashes and Argon2's working memory live in anonymous mappings that are mlocked, marked MADV_DONTDUMP and zeroed before unmapping. The history is cleared when a device connects, since the UI cannot tell devices apart and a different key may use a different PIN. Closes #209. --- CHANGELOG.md | 1 + Cargo.lock | 26 ++ Cargo.toml | 7 + credentialsd-ui/Cargo.toml | 2 + credentialsd-ui/src/client.rs | 2 +- credentialsd-ui/src/gui/mod.rs | 4 + credentialsd-ui/src/gui/view_model/gtk/mod.rs | 16 + credentialsd-ui/src/gui/view_model/mod.rs | 172 +++++++++- credentialsd-ui/src/main.rs | 1 + credentialsd-ui/src/pin_history.rs | 322 ++++++++++++++++++ 10 files changed, 550 insertions(+), 3 deletions(-) create mode 100644 credentialsd-ui/src/pin_history.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 491d652c..2614df91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - daemon: Build the list of devices offered to the user from libwebauthn's `available_transports()`, the same source discovery uses (#32) - ui: Pass the caller's activation token to the compositor when showing the dialog, so it can take focus when the requesting window is in the background (#152) - ui: Disable core dumps for the UI process, which handles typed PINs. Build with `-Denable_core_dumps=true` to allow them for debugging (#209) +- ui: Tell the user when they enter a PIN that was already tried on the connected device, instead of sending it again. Tried PINs are kept only as peppered Argon2id hashes in locked memory excluded from core dumps (#209) # 0.4.0 [2026-11-05] diff --git a/Cargo.lock b/Cargo.lock index c28837ce..4e7112b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -87,6 +87,19 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.2.17", + "password-hash", + "zeroize", +] + [[package]] name = "asn1-rs" version = "0.7.2" @@ -834,6 +847,7 @@ dependencies = [ name = "credentialsd-ui" version = "0.4.0" dependencies = [ + "argon2", "async-std", "credentialsd-common", "futures-lite", @@ -847,6 +861,7 @@ dependencies = [ "tracing", "tracing-subscriber", "zbus", + "zeroize", ] [[package]] @@ -2801,6 +2816,17 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "pcsc" version = "2.9.0" diff --git a/Cargo.toml b/Cargo.toml index bc9a01c3..2e5f1404 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,13 @@ members = ["credentialsd", "credentialsd-common", "credentialsd-ui"] [profile.release] lto = true +# PIN hashing in credentialsd-ui is noticeably slow without optimisations. +[profile.dev.package.argon2] +opt-level = 3 + +[profile.dev.package.blake2] +opt-level = 3 + [workspace.dependencies] futures-lite = "=2.6.1" libc = "=0.2.189" diff --git a/credentialsd-ui/Cargo.toml b/credentialsd-ui/Cargo.toml index b6d47a3f..484c54f9 100644 --- a/credentialsd-ui/Cargo.toml +++ b/credentialsd-ui/Cargo.toml @@ -12,6 +12,7 @@ wayland = ["gdk-wayland"] [dependencies] credentialsd-common = { path = "../credentialsd-common" } +argon2 = { version = "=0.5.3", default-features = false, features = ["alloc", "zeroize"] } futures-lite.workspace = true libc.workspace = true serde.workspace = true @@ -25,3 +26,4 @@ gio-unix = "=0.22.8" gtk = { version = "=0.11.4", package = "gtk4", features = ["v4_14"] } gdk-wayland = { version = "=0.11.4", package = "gdk4-wayland", optional = true } qrcode = "=0.14.1" +zeroize = "=1.9.0" diff --git a/credentialsd-ui/src/client.rs b/credentialsd-ui/src/client.rs index 29c5979b..d6d299ff 100644 --- a/credentialsd-ui/src/client.rs +++ b/credentialsd-ui/src/client.rs @@ -8,7 +8,7 @@ use credentialsd_common::{ model::{BackgroundEvent, PinNotSetError, UserInteractedEvent}, }; -const CTAP_CLIENT_SECRET_MAX_LEN: usize = 63; +pub(crate) const CTAP_CLIENT_SECRET_MAX_LEN: usize = 63; #[derive(Debug)] pub struct FlowControlClient { diff --git a/credentialsd-ui/src/gui/mod.rs b/credentialsd-ui/src/gui/mod.rs index bc657dc8..f732cf26 100644 --- a/credentialsd-ui/src/gui/mod.rs +++ b/credentialsd-ui/src/gui/mod.rs @@ -84,6 +84,10 @@ pub enum ViewUpdate { NeedsPin { attempts_left: Option, }, + /// The entered PIN was already tried on this device and was not sent. + PinAlreadyTried { + attempts_left: Option, + }, PinNotSet { error: PinNotSetError, }, diff --git a/credentialsd-ui/src/gui/view_model/gtk/mod.rs b/credentialsd-ui/src/gui/view_model/gtk/mod.rs index f2b7d305..2015a50c 100644 --- a/credentialsd-ui/src/gui/view_model/gtk/mod.rs +++ b/credentialsd-ui/src/gui/view_model/gtk/mod.rs @@ -179,6 +179,22 @@ impl ViewModel { view_model.set_prompt(prompt); view_model.set_usb_nfc_pin_entry_visible(true); } + ViewUpdate::PinAlreadyTried { attempts_left } => { + let prompt = if let Some(left) = attempts_left { + let localized = ngettext( + "You already tried this PIN. Enter a different PIN. One attempt remaining.", + "You already tried this PIN. Enter a different PIN. %d attempts remaining.", + left, + ); + localized.replace("%d", &format!("{}", left)) + } else { + gettext( + "You already tried this PIN. Enter a different PIN.", + ) + }; + view_model.set_prompt(prompt); + view_model.set_usb_nfc_pin_entry_visible(true); + } ViewUpdate::NeedsUserVerification { attempts_left } => { let prompt = match attempts_left { Some(left) => { diff --git a/credentialsd-ui/src/gui/view_model/mod.rs b/credentialsd-ui/src/gui/view_model/mod.rs index 6cf331bd..ef4463d7 100644 --- a/credentialsd-ui/src/gui/view_model/mod.rs +++ b/credentialsd-ui/src/gui/view_model/mod.rs @@ -11,11 +11,15 @@ use credentialsd_common::memfd::read_secret; use credentialsd_common::model::{BackgroundEvent, Credential}; use gettextrs::gettext; use serde::{Deserialize, Serialize}; -use tracing::{error, info}; +use tracing::{error, info, warn}; use credentialsd_common::model::{Device, Operation, Transport}; -use crate::{RequestingApplication, ViewRequest, client::FlowControlClient}; +use crate::{ + RequestingApplication, ViewRequest, + client::{CTAP_CLIENT_SECRET_MAX_LEN, FlowControlClient}, + pin_history::{PinCheck, PinHistory}, +}; use super::ViewUpdate; @@ -36,6 +40,12 @@ pub(crate) struct ViewModel { selected_device: Option, hybrid_qr_code_data: Option>, + + /// Hashes of PINs already sent to the connected device, if the locked + /// memory for them could be set up. + pin_history: Option, + /// PIN retries left, as last reported by the device. + pin_attempts_left: Option, } impl ViewModel { @@ -66,6 +76,38 @@ impl ViewModel { devices, selected_device: None, hybrid_qr_code_data: None, + pin_history: PinHistory::new() + .inspect_err(|err| warn!(%err, "Not warning about repeated PIN entries")) + .ok(), + pin_attempts_left: None, + } + } + + /// Returns true if `pin` was already tried on the connected device and the + /// user should be told instead of sending it again. + fn pin_already_tried(&mut self, pin: &str) -> bool { + // Over-long PINs are rejected without being sent, so never record them. + if pin.len() > CTAP_CLIENT_SECRET_MAX_LEN { + return false; + } + let Some(history) = self.pin_history.as_mut() else { + return false; + }; + match history.check(pin.as_bytes()) { + Ok(check) => check == PinCheck::AlreadyTried, + Err(err) => { + warn!(%err, "Failed to check PIN against earlier attempts"); + false + } + } + } + + /// Forgets earlier PIN attempts, since a new connection may be a + /// different device with a different PIN. + fn reset_pin_history(&mut self) { + if let Some(Err(err)) = self.pin_history.as_mut().map(PinHistory::clear) { + warn!(%err, "Failed to reset PIN history"); + self.pin_history = None; } } @@ -150,6 +192,15 @@ impl ViewModel { self.start_discovery().await; } Event::View(ViewEvent::PinEntered(pin)) => { + if self.pin_already_tried(&pin) { + self.tx_update + .send(ViewUpdate::PinAlreadyTried { + attempts_left: self.pin_attempts_left, + }) + .await + .unwrap(); + continue; + } let mut cred_service = self.flow_controller.lock().await; if cred_service.enter_client_pin(pin).await.is_err() { error!("Failed to send pin to device"); @@ -203,6 +254,7 @@ impl ViewModel { Event::Background(BackgroundEvent::UsbConnected) => { info!("Found USB device"); + self.reset_pin_history(); self.tx_update .send(ViewUpdate::WaitingForDevice(Device { id: "TODO: bogus".to_string(), @@ -212,6 +264,7 @@ impl ViewModel { .unwrap(); } Event::Background(BackgroundEvent::NeedsPin { attempts_left }) => { + self.pin_attempts_left = attempts_left; self.tx_update .send(ViewUpdate::NeedsPin { attempts_left }) .await @@ -305,6 +358,7 @@ impl ViewModel { } Event::Background(BackgroundEvent::NfcConnected) => { info!("Found NFC device"); + self.reset_pin_history(); self.tx_update .send(ViewUpdate::WaitingForDevice(Device { id: "TODO: bogus".to_string(), @@ -396,3 +450,117 @@ pub enum Event { Background(BackgroundEvent), View(ViewEvent), } + +#[cfg(test)] +mod tests { + use async_std::channel::{Receiver, Sender, unbounded}; + use credentialsd_common::model::UserInteractedEvent; + + use super::*; + + struct Harness { + view_tx: Sender, + bg_tx: Sender, + updates: Receiver, + sent: Receiver, + } + + fn start() -> Harness { + let (view_tx, view_rx) = unbounded(); + let (bg_tx, bg_rx) = unbounded(); + let (update_tx, updates) = unbounded(); + let (client_tx, sent) = unbounded(); + let client = FlowControlClient { + tx: client_tx, + rx: AsyncMutex::new(Some(bg_rx)), + }; + let request = ViewRequest { + operation: Operation::PublicKeyCreate, + rp_id: "example.com".to_string(), + requesting_app: RequestingApplication::default(), + initial_devices: Vec::new(), + window_handle: None, + }; + let mut vm = ViewModel::new( + request, + Arc::new(AsyncMutex::new(client)), + view_rx, + update_tx, + ); + async_std::task::spawn(async move { vm.start_event_loop().await }); + Harness { + view_tx, + bg_tx, + updates, + sent, + } + } + + impl Harness { + async fn connect_usb(&self) { + self.bg_tx + .send(BackgroundEvent::UsbConnected) + .await + .unwrap(); + let update = self.updates.recv().await.unwrap(); + assert!(matches!(update, ViewUpdate::WaitingForDevice(_))); + } + + /// Enters `pin` and returns true if it was sent to the backend. + async fn enter_pin(&self, pin: &str) -> bool { + self.view_tx + .send(ViewEvent::PinEntered(pin.to_string())) + .await + .unwrap(); + let sent = async { Ok(self.sent.recv().await.unwrap()) }; + let warned = async { Err(self.updates.recv().await.unwrap()) }; + match sent.race(warned).await { + Ok(UserInteractedEvent::ClientPinEntered(_)) => true, + Ok(other) => panic!("unexpected backend event {other:?}"), + Err(ViewUpdate::PinAlreadyTried { .. }) => false, + Err(other) => panic!("unexpected view update {other:?}"), + } + } + } + + #[test] + fn repeated_pin_is_never_sent() { + async_std::task::block_on(async { + let h = start(); + h.connect_usb().await; + assert!(h.enter_pin("1234").await); + assert!(!h.enter_pin("1234").await); + assert!(!h.enter_pin("1234").await); + assert!(h.enter_pin("5678").await); + }); + } + + #[test] + fn over_long_pin_is_not_recorded() { + async_std::task::block_on(async { + let h = start(); + h.connect_usb().await; + let long = "1".repeat(CTAP_CLIENT_SECRET_MAX_LEN + 1); + h.view_tx + .send(ViewEvent::PinEntered(long.clone())) + .await + .unwrap(); + h.view_tx.send(ViewEvent::PinEntered(long)).await.unwrap(); + // Neither entry is sent, and the second one is not reported as + // already tried; the next valid PIN goes straight through. + assert!(h.enter_pin("1234").await); + assert!(h.updates.try_recv().is_err()); + }); + } + + #[test] + fn new_connection_forgets_tried_pins() { + async_std::task::block_on(async { + let h = start(); + h.connect_usb().await; + assert!(h.enter_pin("1234").await); + h.connect_usb().await; + assert!(h.enter_pin("1234").await); + }); + } +} diff --git a/credentialsd-ui/src/main.rs b/credentialsd-ui/src/main.rs index ed1fb4da..37296e20 100644 --- a/credentialsd-ui/src/main.rs +++ b/credentialsd-ui/src/main.rs @@ -4,6 +4,7 @@ mod config; mod dbus; mod gui; mod hardening; +mod pin_history; use std::error::Error; diff --git a/credentialsd-ui/src/pin_history.rs b/credentialsd-ui/src/pin_history.rs new file mode 100644 index 00000000..2de7fbac --- /dev/null +++ b/credentialsd-ui/src/pin_history.rs @@ -0,0 +1,322 @@ +//! Remembers which client PINs were already sent to the authenticator during a +//! request, so the user can be told instead of wasting a PIN attempt on a PIN +//! that already failed. +//! +//! PINs are never stored. Each PIN is hashed with Argon2id, keyed with a +//! random pepper and salted with a random salt, both created per history +//! (that is, per request). The pepper, salt and hashes live in an anonymous +//! mapping that is locked into RAM (`mlock`) and excluded from core dumps +//! (`MADV_DONTDUMP`); so does Argon2's working memory while a PIN is hashed. +//! Both are zeroed before they are unmapped. +//! +//! Limitation: the `blake2` crate used inside Argon2 does not zeroize its +//! state, so a copy of the PIN, salt and pepper can remain on the hashing +//! thread's stack until it is overwritten. The PIN itself is already held in +//! ordinary memory by GTK while the user types it. + +use std::{io, ptr::NonNull}; + +use argon2::{Algorithm, Argon2, Block, Params, Version}; +use zeroize::Zeroize; + +const PEPPER_LEN: usize = 32; +const SALT_LEN: usize = 16; +const HASH_LEN: usize = 32; +/// CTAP authenticators allow at most 8 PIN retries before blocking, so this +/// leaves room for a device being re-plugged within one request. +const MAX_ENTRIES: usize = 16; + +/// Argon2 memory cost in KiB (one block each). Kept far below the usual +/// 8 MiB `RLIMIT_MEMLOCK` so the working memory can be locked. The pepper is +/// secret, so memory-hardness matters little here. +const M_COST_KIB: u32 = 512; +const T_COST: u32 = 3; + +const SALT_OFFSET: usize = PEPPER_LEN; +const SCRATCH_OFFSET: usize = SALT_OFFSET + SALT_LEN; +const ENTRIES_OFFSET: usize = SCRATCH_OFFSET + HASH_LEN; +const REGION_LEN: usize = ENTRIES_OFFSET + MAX_ENTRIES * HASH_LEN; + +/// What to do with a PIN the user just entered. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum PinCheck { + /// Send the PIN to the authenticator. + Send, + /// The PIN was already tried for this device. Tell the user instead of + /// sending it. + AlreadyTried, +} + +#[derive(Debug)] +pub(crate) enum PinHistoryError { + /// Setting up the locked memory page failed. + Memory(io::Error), + /// The kernel random number generator failed. + Random(io::Error), + /// Argon2 rejected its parameters or inputs. + Hash(argon2::Error), +} + +impl std::fmt::Display for PinHistoryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Memory(err) => write!(f, "failed to set up locked memory for PIN history: {err}"), + Self::Random(err) => write!(f, "failed to generate random bytes: {err}"), + Self::Hash(err) => write!(f, "failed to hash PIN: {err}"), + } + } +} + +impl std::error::Error for PinHistoryError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Memory(err) | Self::Random(err) => Some(err), + // argon2::Error only implements std::error::Error with the + // crate's `std` feature; its message is included in Display. + Self::Hash(_) => None, + } + } +} + +/// Hashes of the PINs already tried on the current device. +pub(crate) struct PinHistory { + page: LockedPage, + len: usize, +} + +impl PinHistory { + pub(crate) fn new() -> Result { + let mut page = LockedPage::new(REGION_LEN).map_err(PinHistoryError::Memory)?; + fill_random(&mut page.as_mut_slice()[..SCRATCH_OFFSET]).map_err(PinHistoryError::Random)?; + Ok(Self { page, len: 0 }) + } + + /// Checks `pin` against the PINs already tried and records it if it is + /// new. + pub(crate) fn check(&mut self, pin: &[u8]) -> Result { + self.hash_into_scratch(pin)?; + let result = if self.scratch_is_recorded() { + PinCheck::AlreadyTried + } else { + self.push_scratch(); + PinCheck::Send + }; + self.page.as_mut_slice()[SCRATCH_OFFSET..ENTRIES_OFFSET].zeroize(); + Ok(result) + } + + /// Forgets all tried PINs, e.g. because a different device may now be + /// connected, and picks a new salt. + pub(crate) fn clear(&mut self) -> Result<(), PinHistoryError> { + let bytes = self.page.as_mut_slice(); + bytes[SCRATCH_OFFSET..].zeroize(); + self.len = 0; + fill_random(&mut bytes[SALT_OFFSET..SCRATCH_OFFSET]).map_err(PinHistoryError::Random) + } + + fn hash_into_scratch(&mut self, pin: &[u8]) -> Result<(), PinHistoryError> { + let bytes = self.page.as_mut_slice(); + let (keys, rest) = bytes.split_at_mut(SCRATCH_OFFSET); + let (pepper, salt) = keys.split_at(PEPPER_LEN); + let scratch = &mut rest[..HASH_LEN]; + let params = + Params::new(M_COST_KIB, T_COST, 1, Some(HASH_LEN)).map_err(PinHistoryError::Hash)?; + let argon = Argon2::new_with_secret(pepper, Algorithm::Argon2id, Version::V0x13, params) + .map_err(PinHistoryError::Hash)?; + // Dropped (zeroed and unmapped) at the end of this function. + let mut memory = LockedPage::new(M_COST_KIB as usize * size_of::()) + .map_err(PinHistoryError::Memory)?; + argon + .hash_password_into_with_memory(pin, salt, scratch, memory.as_mut_blocks()) + .map_err(PinHistoryError::Hash) + } + + fn scratch_is_recorded(&self) -> bool { + let bytes = self.page.as_slice(); + let scratch = &bytes[SCRATCH_OFFSET..ENTRIES_OFFSET]; + bytes[ENTRIES_OFFSET..] + .chunks_exact(HASH_LEN) + .take(self.len) + .any(|entry| entry == scratch) + } + + /// Appends the scratch hash, dropping the oldest entry when full. + fn push_scratch(&mut self) { + let bytes = self.page.as_mut_slice(); + if self.len == MAX_ENTRIES { + bytes.copy_within(ENTRIES_OFFSET + HASH_LEN.., ENTRIES_OFFSET); + self.len -= 1; + } + let dst = ENTRIES_OFFSET + self.len * HASH_LEN; + bytes.copy_within(SCRATCH_OFFSET..ENTRIES_OFFSET, dst); + self.len += 1; + } +} + +impl std::fmt::Debug for PinHistory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PinHistory") + .field("len", &self.len) + .finish_non_exhaustive() + } +} + +fn fill_random(buf: &mut [u8]) -> io::Result<()> { + let mut filled = 0; + while filled < buf.len() { + let rest = &mut buf[filled..]; + // SAFETY: `rest` is a valid, writable buffer of `rest.len()` bytes. + let n = unsafe { libc::getrandom(rest.as_mut_ptr().cast(), rest.len(), 0) }; + if n < 0 { + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(err); + } + filled += n as usize; + } + Ok(()) +} + +/// Anonymous private memory, locked into RAM and excluded from core dumps. +struct LockedPage { + ptr: NonNull, + len: usize, +} + +// SAFETY: `LockedPage` exclusively owns its mapping; nothing else holds the +// pointer, so moving it to another thread is sound. +unsafe impl Send for LockedPage {} +// SAFETY: shared references only allow reading the mapping through +// `as_slice`; writes need `&mut self`, so the usual borrow rules apply. +unsafe impl Sync for LockedPage {} + +impl LockedPage { + fn new(len: usize) -> io::Result { + // SAFETY: an anonymous private mapping with no address hint has no + // preconditions; the result is checked against MAP_FAILED. + let addr = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + if addr == libc::MAP_FAILED { + return Err(io::Error::last_os_error()); + } + let ptr = NonNull::new(addr.cast::()).ok_or_else(io::Error::last_os_error)?; + // From here on, `Drop` unmaps the region if a later step fails. + let page = Self { ptr, len }; + // SAFETY: `addr` is a page-aligned mapping of `len` bytes owned by us. + if unsafe { libc::madvise(addr, len, libc::MADV_DONTDUMP) } != 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: as above. + if unsafe { libc::mlock(addr, len) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(page) + } + + fn as_slice(&self) -> &[u8] { + // SAFETY: the mapping is `len` readable bytes, zero-initialised by + // the kernel, and lives as long as `self`. + unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) } + } + + fn as_mut_slice(&mut self) -> &mut [u8] { + // SAFETY: as in `as_slice`; `&mut self` guarantees exclusive access. + unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) } + } + + /// Views the mapping as Argon2 blocks; trailing bytes that do not fill a + /// whole block are left out. + fn as_mut_blocks(&mut self) -> &mut [Block] { + let count = self.len / size_of::(); + // SAFETY: mmap returns page-aligned memory, which satisfies Block's + // 64-byte alignment; `count` blocks fit in `len` bytes; a Block is a + // plain array of u64, for which the all-zero (or any) bit pattern is + // valid; `&mut self` guarantees exclusive access. + unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr().cast::(), count) } + } +} + +impl Drop for LockedPage { + fn drop(&mut self) { + self.as_mut_slice().zeroize(); + let addr = self.ptr.as_ptr().cast(); + // SAFETY: `addr`/`len` describe our own mapping, which is not used + // after this point. munlock on an unlocked range is harmless. + unsafe { + libc::munlock(addr, self.len); + libc::munmap(addr, self.len); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn new_pin_is_sent() { + let mut history = PinHistory::new().unwrap(); + assert_eq!(history.check(b"1234").unwrap(), PinCheck::Send); + } + + #[test] + fn repeated_pin_is_always_refused() { + let mut history = PinHistory::new().unwrap(); + history.check(b"1234").unwrap(); + assert_eq!(history.check(b"1234").unwrap(), PinCheck::AlreadyTried); + assert_eq!(history.check(b"1234").unwrap(), PinCheck::AlreadyTried); + } + + #[test] + fn every_tried_pin_is_remembered() { + let mut history = PinHistory::new().unwrap(); + history.check(b"1111").unwrap(); + history.check(b"2222").unwrap(); + assert_eq!(history.check(b"1111").unwrap(), PinCheck::AlreadyTried); + assert_eq!(history.check(b"2222").unwrap(), PinCheck::AlreadyTried); + assert_eq!(history.check(b"3333").unwrap(), PinCheck::Send); + } + + #[test] + fn clear_forgets_tried_pins() { + let mut history = PinHistory::new().unwrap(); + history.check(b"1234").unwrap(); + history.clear().unwrap(); + assert_eq!(history.check(b"1234").unwrap(), PinCheck::Send); + } + + #[test] + fn oldest_entry_is_dropped_when_full() { + let mut history = PinHistory::new().unwrap(); + for i in 0..=MAX_ENTRIES { + assert_eq!( + history.check(format!("{i:04}").as_bytes()).unwrap(), + PinCheck::Send + ); + } + assert_eq!(history.check(b"0000").unwrap(), PinCheck::Send); + assert_eq!(history.check(b"0002").unwrap(), PinCheck::AlreadyTried); + } + + #[test] + fn scratch_hash_is_wiped_after_check() { + let mut history = PinHistory::new().unwrap(); + history.check(b"98765432").unwrap(); + let bytes = history.page.as_slice(); + assert!( + bytes[SCRATCH_OFFSET..ENTRIES_OFFSET] + .iter() + .all(|b| *b == 0) + ); + } +} From 7d2ff5cd61c17e480db334238d413998f44c1a5b Mon Sep 17 00:00:00 2001 From: K Panuragh Date: Fri, 13 Nov 2026 23:19:22 +0530 Subject: [PATCH 2/3] ui: Keep PIN history only for the current PIN prompt Address review on #261: - Create a salt when the device asks for a PIN and wipe the history and salt as soon as the prompt ends (PIN accepted, device changed, or the request failed), checked on every event. Hybrid events and errors that don't name a transport are ignored, so they can't wipe the history while the user types. - Pass the salt to PinHistory::check() instead of keeping it in the locked page, and make clear() only wipe the hashes. - Store hashes in a ring buffer instead of shifting entries. - Use rand's SysRng instead of calling getrandom through libc. - Fix the module docs, which said PINs are never stored. --- CHANGELOG.md | 2 +- Cargo.lock | 1 + credentialsd-ui/Cargo.toml | 1 + credentialsd-ui/src/gui/view_model/mod.rs | 250 +++++++++++++++++++--- credentialsd-ui/src/pin_history.rs | 234 +++++++++++++------- 5 files changed, 371 insertions(+), 117 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2614df91..62875aa2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ - daemon: Build the list of devices offered to the user from libwebauthn's `available_transports()`, the same source discovery uses (#32) - ui: Pass the caller's activation token to the compositor when showing the dialog, so it can take focus when the requesting window is in the background (#152) - ui: Disable core dumps for the UI process, which handles typed PINs. Build with `-Denable_core_dumps=true` to allow them for debugging (#209) -- ui: Tell the user when they enter a PIN that was already tried on the connected device, instead of sending it again. Tried PINs are kept only as peppered Argon2id hashes in locked memory excluded from core dumps (#209) +- ui: Tell the user when they enter a PIN that was already tried for the current PIN prompt, instead of sending it again. Tried PINs are kept as peppered Argon2id hashes in locked memory excluded from core dumps, and wiped as soon as the prompt ends (#209) # 0.4.0 [2026-11-05] diff --git a/Cargo.lock b/Cargo.lock index 4e7112b0..145db894 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -857,6 +857,7 @@ dependencies = [ "gtk4", "libc", "qrcode", + "rand 0.10.2", "serde", "tracing", "tracing-subscriber", diff --git a/credentialsd-ui/Cargo.toml b/credentialsd-ui/Cargo.toml index 484c54f9..a3a286c2 100644 --- a/credentialsd-ui/Cargo.toml +++ b/credentialsd-ui/Cargo.toml @@ -15,6 +15,7 @@ credentialsd-common = { path = "../credentialsd-common" } argon2 = { version = "=0.5.3", default-features = false, features = ["alloc", "zeroize"] } futures-lite.workspace = true libc.workspace = true +rand = "=0.10.2" serde.workspace = true tracing.workspace = true tracing-subscriber.workspace = true diff --git a/credentialsd-ui/src/gui/view_model/mod.rs b/credentialsd-ui/src/gui/view_model/mod.rs index ef4463d7..0711ab0e 100644 --- a/credentialsd-ui/src/gui/view_model/mod.rs +++ b/credentialsd-ui/src/gui/view_model/mod.rs @@ -18,7 +18,7 @@ use credentialsd_common::model::{Device, Operation, Transport}; use crate::{ RequestingApplication, ViewRequest, client::{CTAP_CLIENT_SECRET_MAX_LEN, FlowControlClient}, - pin_history::{PinCheck, PinHistory}, + pin_history::{PinCheck, PinHistory, PinSalt}, }; use super::ViewUpdate; @@ -41,9 +41,12 @@ pub(crate) struct ViewModel { hybrid_qr_code_data: Option>, - /// Hashes of PINs already sent to the connected device, if the locked - /// memory for them could be set up. + /// Hashes of PINs already sent during the current PIN prompt, if the + /// locked memory for them could be set up. pin_history: Option, + /// Salt for the current PIN prompt. Set while a device is asking for a + /// PIN, and dropped together with the history as soon as it stops. + pin_salt: Option, /// PIN retries left, as last reported by the device. pin_attempts_left: Option, } @@ -79,6 +82,7 @@ impl ViewModel { pin_history: PinHistory::new() .inspect_err(|err| warn!(%err, "Not warning about repeated PIN entries")) .ok(), + pin_salt: None, pin_attempts_left: None, } } @@ -90,10 +94,11 @@ impl ViewModel { if pin.len() > CTAP_CLIENT_SECRET_MAX_LEN { return false; } - let Some(history) = self.pin_history.as_mut() else { + let (Some(history), Some(salt)) = (self.pin_history.as_mut(), self.pin_salt.as_ref()) + else { return false; }; - match history.check(pin.as_bytes()) { + match history.check(salt, pin.as_bytes()) { Ok(check) => check == PinCheck::AlreadyTried, Err(err) => { warn!(%err, "Failed to check PIN against earlier attempts"); @@ -102,12 +107,26 @@ impl ViewModel { } } - /// Forgets earlier PIN attempts, since a new connection may be a - /// different device with a different PIN. - fn reset_pin_history(&mut self) { - if let Some(Err(err)) = self.pin_history.as_mut().map(PinHistory::clear) { - warn!(%err, "Failed to reset PIN history"); - self.pin_history = None; + /// Starts a PIN history when a device asks for a PIN, and wipes it as + /// soon as the prompt is over: the PIN was accepted, the device changed, + /// or the request failed. Called for every event before it is handled. + fn track_pin_prompt(&mut self, event: &Event) { + match pin_prompt_change(event) { + Some(PinPrompt::Open) => { + if self.pin_salt.is_none() { + self.pin_salt = PinSalt::generate() + .inspect_err(|err| warn!(%err, "Not warning about repeated PIN entries")) + .ok(); + } + } + Some(PinPrompt::Closed) => { + if self.pin_salt.take().is_some() + && let Some(history) = self.pin_history.as_mut() + { + history.clear(); + } + } + None => {} } } @@ -185,6 +204,7 @@ impl ViewModel { let mut all_events = view_events.merge(bg_events.map(Event::Background)); while let Some(event) = all_events.next().await { tracing::trace!("View event received: {event:?}"); + self.track_pin_prompt(&event); match event { Event::View(ViewEvent::Initiated) => { self.update_title().await; @@ -254,7 +274,6 @@ impl ViewModel { Event::Background(BackgroundEvent::UsbConnected) => { info!("Found USB device"); - self.reset_pin_history(); self.tx_update .send(ViewUpdate::WaitingForDevice(Device { id: "TODO: bogus".to_string(), @@ -358,7 +377,6 @@ impl ViewModel { } Event::Background(BackgroundEvent::NfcConnected) => { info!("Found NFC device"); - self.reset_pin_history(); self.tx_update .send(ViewUpdate::WaitingForDevice(Device { id: "TODO: bogus".to_string(), @@ -451,6 +469,60 @@ pub enum Event { View(ViewEvent), } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PinPrompt { + Open, + Closed, +} + +/// How `event` affects the PIN prompt, if at all. +/// +/// Events that cannot come from the device being asked for its PIN are +/// ignored, so that e.g. hybrid restarting in the background does not wipe +/// the history while the user is typing. `ErrorAuthenticator` and +/// `ErrorInternal` don't say which transport failed, so they are ignored too; +/// the transport restarting afterwards ends the prompt. +/// +/// Any USB or NFC event ends the prompt. That assumes only one of the two is +/// discovering at a time, which holds while NFC discovery is disabled in the +/// daemon; if both run at once, events from the other transport should be +/// ignored like hybrid ones. +fn pin_prompt_change(event: &Event) -> Option { + let Event::Background(event) = event else { + return None; + }; + match event { + BackgroundEvent::NeedsPin { .. } => Some(PinPrompt::Open), + BackgroundEvent::HybridIdle + | BackgroundEvent::HybridStarted(_) + | BackgroundEvent::HybridConnecting + | BackgroundEvent::HybridConnected + | BackgroundEvent::HybridRestarting + | BackgroundEvent::ErrorAuthenticator + | BackgroundEvent::ErrorInternal => None, + BackgroundEvent::CeremonyCompleted + | BackgroundEvent::PinNotSet { .. } + | BackgroundEvent::NeedsUserVerification { .. } + | BackgroundEvent::NeedsUserPresence + | BackgroundEvent::SelectingCredential { .. } + | BackgroundEvent::NfcIdle + | BackgroundEvent::NfcWaiting + | BackgroundEvent::NfcConnected + | BackgroundEvent::NfcRestarting + | BackgroundEvent::UsbIdle + | BackgroundEvent::UsbWaiting + | BackgroundEvent::UsbSelectingDevice + | BackgroundEvent::UsbConnected + | BackgroundEvent::UsbRestarting + | BackgroundEvent::ErrorTimedOut + | BackgroundEvent::ErrorCancelled + | BackgroundEvent::ErrorNoCredentials + | BackgroundEvent::ErrorPinAttemptsExhausted + | BackgroundEvent::ErrorPinNotSet + | BackgroundEvent::ErrorCredentialExcluded => Some(PinPrompt::Closed), + } +} + #[cfg(test)] mod tests { use async_std::channel::{Receiver, Sender, unbounded}; @@ -465,7 +537,7 @@ mod tests { sent: Receiver, } - fn start() -> Harness { + fn view_model() -> (ViewModel, Harness) { let (view_tx, view_rx) = unbounded(); let (bg_tx, bg_rx) = unbounded(); let (update_tx, updates) = unbounded(); @@ -480,32 +552,51 @@ mod tests { requesting_app: RequestingApplication::default(), initial_devices: Vec::new(), window_handle: None, + activation_token: None, }; - let mut vm = ViewModel::new( + let vm = ViewModel::new( request, Arc::new(AsyncMutex::new(client)), view_rx, update_tx, ); - async_std::task::spawn(async move { vm.start_event_loop().await }); - Harness { + let harness = Harness { view_tx, bg_tx, updates, sent, - } + }; + (vm, harness) + } + + fn start() -> Harness { + let (mut vm, harness) = view_model(); + async_std::task::spawn(async move { vm.start_event_loop().await }); + harness } impl Harness { + /// Sends a background event and returns the first view update it + /// causes. + async fn background(&self, event: BackgroundEvent) -> ViewUpdate { + self.bg_tx.send(event).await.unwrap(); + self.updates.recv().await.unwrap() + } + async fn connect_usb(&self) { - self.bg_tx - .send(BackgroundEvent::UsbConnected) - .await - .unwrap(); - let update = self.updates.recv().await.unwrap(); + let update = self.background(BackgroundEvent::UsbConnected).await; assert!(matches!(update, ViewUpdate::WaitingForDevice(_))); } + async fn needs_pin(&self) { + let update = self + .background(BackgroundEvent::NeedsPin { + attempts_left: Some(8), + }) + .await; + assert!(matches!(update, ViewUpdate::NeedsPin { .. })); + } + /// Enters `pin` and returns true if it was sent to the backend. async fn enter_pin(&self, pin: &str) -> bool { self.view_tx @@ -528,6 +619,7 @@ mod tests { async_std::task::block_on(async { let h = start(); h.connect_usb().await; + h.needs_pin().await; assert!(h.enter_pin("1234").await); assert!(!h.enter_pin("1234").await); assert!(!h.enter_pin("1234").await); @@ -536,20 +628,69 @@ mod tests { } #[test] - fn over_long_pin_is_not_recorded() { + fn wrong_pin_prompt_keeps_history() { async_std::task::block_on(async { let h = start(); h.connect_usb().await; - let long = "1".repeat(CTAP_CLIENT_SECRET_MAX_LEN + 1); - h.view_tx - .send(ViewEvent::PinEntered(long.clone())) - .await - .unwrap(); - h.view_tx.send(ViewEvent::PinEntered(long)).await.unwrap(); - // Neither entry is sent, and the second one is not reported as - // already tried; the next valid PIN goes straight through. + h.needs_pin().await; + assert!(h.enter_pin("1234").await); + // The device rejected the PIN and asks again. + h.needs_pin().await; + assert!(!h.enter_pin("1234").await); + }); + } + + #[test] + fn hybrid_restart_during_pin_prompt_keeps_history() { + async_std::task::block_on(async { + let h = start(); + h.connect_usb().await; + h.needs_pin().await; + assert!(h.enter_pin("1234").await); + let update = h.background(BackgroundEvent::HybridRestarting).await; + assert!(matches!(update, ViewUpdate::TransportRestarting)); + assert!(!h.enter_pin("1234").await); + }); + } + + #[test] + fn ambiguous_error_during_pin_prompt_keeps_history() { + async_std::task::block_on(async { + let h = start(); + h.connect_usb().await; + h.needs_pin().await; + assert!(h.enter_pin("1234").await); + let update = h.background(BackgroundEvent::ErrorAuthenticator).await; + assert!(matches!(update, ViewUpdate::Failed(_))); + assert!(!h.enter_pin("1234").await); + }); + } + + #[test] + fn transport_restart_forgets_tried_pins() { + async_std::task::block_on(async { + let h = start(); + h.connect_usb().await; + h.needs_pin().await; + assert!(h.enter_pin("1234").await); + let update = h.background(BackgroundEvent::UsbRestarting).await; + assert!(matches!(update, ViewUpdate::TransportRestarting)); + h.needs_pin().await; + assert!(h.enter_pin("1234").await); + }); + } + + #[test] + fn accepted_pin_forgets_tried_pins() { + async_std::task::block_on(async { + let h = start(); + h.connect_usb().await; + h.needs_pin().await; + assert!(h.enter_pin("1234").await); + let update = h.background(BackgroundEvent::NeedsUserPresence).await; + assert!(matches!(update, ViewUpdate::NeedsUserPresence)); + h.needs_pin().await; assert!(h.enter_pin("1234").await); - assert!(h.updates.try_recv().is_err()); }); } @@ -558,9 +699,52 @@ mod tests { async_std::task::block_on(async { let h = start(); h.connect_usb().await; + h.needs_pin().await; assert!(h.enter_pin("1234").await); h.connect_usb().await; + h.needs_pin().await; assert!(h.enter_pin("1234").await); }); } + + #[test] + fn end_of_pin_prompt_wipes_history_and_salt() { + let (mut vm, _h) = view_model(); + vm.track_pin_prompt(&Event::Background(BackgroundEvent::NeedsPin { + attempts_left: None, + })); + assert!(vm.pin_salt.is_some()); + assert!(!vm.pin_already_tried("1234")); + assert!(!vm.pin_history.as_ref().unwrap().is_empty()); + + vm.track_pin_prompt(&Event::Background(BackgroundEvent::NeedsUserPresence)); + assert!(vm.pin_salt.is_none()); + assert!(vm.pin_history.as_ref().unwrap().is_empty()); + } + + #[test] + fn pin_entered_without_prompt_is_not_recorded() { + let (mut vm, _h) = view_model(); + assert!(!vm.pin_already_tried("1234")); + assert!(vm.pin_history.as_ref().unwrap().is_empty()); + } + + #[test] + fn over_long_pin_is_not_recorded() { + async_std::task::block_on(async { + let h = start(); + h.connect_usb().await; + h.needs_pin().await; + let long = "1".repeat(CTAP_CLIENT_SECRET_MAX_LEN + 1); + h.view_tx + .send(ViewEvent::PinEntered(long.clone())) + .await + .unwrap(); + h.view_tx.send(ViewEvent::PinEntered(long)).await.unwrap(); + // Neither entry is sent, and the second one is not reported as + // already tried; the next valid PIN goes straight through. + assert!(h.enter_pin("1234").await); + assert!(h.updates.try_recv().is_err()); + }); + } } diff --git a/credentialsd-ui/src/pin_history.rs b/credentialsd-ui/src/pin_history.rs index 2de7fbac..23a41ef6 100644 --- a/credentialsd-ui/src/pin_history.rs +++ b/credentialsd-ui/src/pin_history.rs @@ -2,12 +2,13 @@ //! request, so the user can be told instead of wasting a PIN attempt on a PIN //! that already failed. //! -//! PINs are never stored. Each PIN is hashed with Argon2id, keyed with a -//! random pepper and salted with a random salt, both created per history -//! (that is, per request). The pepper, salt and hashes live in an anonymous -//! mapping that is locked into RAM (`mlock`) and excluded from core dumps -//! (`MADV_DONTDUMP`); so does Argon2's working memory while a PIN is hashed. -//! Both are zeroed before they are unmapped. +//! Each PIN is hashed with Argon2id, keyed with a random pepper created per +//! history (that is, per request) and salted with a [`PinSalt`] that the +//! caller creates each time a device asks for a PIN, so different devices +//! and PIN prompts have distinct histories. The pepper and hashes live in an +//! anonymous mapping that is locked into RAM (`mlock`) and excluded from core +//! dumps (`MADV_DONTDUMP`); so does Argon2's working memory while a PIN is +//! hashed. Both are zeroed before they are unmapped. //! //! Limitation: the `blake2` crate used inside Argon2 does not zeroize its //! state, so a copy of the PIN, salt and pepper can remain on the hashing @@ -17,14 +18,17 @@ use std::{io, ptr::NonNull}; use argon2::{Algorithm, Argon2, Block, Params, Version}; +use rand::{TryRng, rngs::SysRng}; use zeroize::Zeroize; const PEPPER_LEN: usize = 32; const SALT_LEN: usize = 16; const HASH_LEN: usize = 32; -/// CTAP authenticators allow at most 8 PIN retries before blocking, so this -/// leaves room for a device being re-plugged within one request. +/// One PIN prompt allows at most 8 attempts (CTAP's retry limit), so this +/// is enough for a whole prompt. +/// A power of two, so the ring buffer index is a cheap mask. const MAX_ENTRIES: usize = 16; +const _: () = assert!(MAX_ENTRIES.is_power_of_two()); /// Argon2 memory cost in KiB (one block each). Kept far below the usual /// 8 MiB `RLIMIT_MEMLOCK` so the working memory can be locked. The pepper is @@ -32,8 +36,7 @@ const MAX_ENTRIES: usize = 16; const M_COST_KIB: u32 = 512; const T_COST: u32 = 3; -const SALT_OFFSET: usize = PEPPER_LEN; -const SCRATCH_OFFSET: usize = SALT_OFFSET + SALT_LEN; +const SCRATCH_OFFSET: usize = PEPPER_LEN; const ENTRIES_OFFSET: usize = SCRATCH_OFFSET + HASH_LEN; const REGION_LEN: usize = ENTRIES_OFFSET + MAX_ENTRIES * HASH_LEN; @@ -52,7 +55,7 @@ pub(crate) enum PinHistoryError { /// Setting up the locked memory page failed. Memory(io::Error), /// The kernel random number generator failed. - Random(io::Error), + Random(rand::rngs::SysError), /// Argon2 rejected its parameters or inputs. Hash(argon2::Error), } @@ -70,7 +73,8 @@ impl std::fmt::Display for PinHistoryError { impl std::error::Error for PinHistoryError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - Self::Memory(err) | Self::Random(err) => Some(err), + Self::Memory(err) => Some(err), + Self::Random(err) => Some(err), // argon2::Error only implements std::error::Error with the // crate's `std` feature; its message is included in Display. Self::Hash(_) => None, @@ -78,46 +82,79 @@ impl std::error::Error for PinHistoryError { } } -/// Hashes of the PINs already tried on the current device. +/// Salt for one PIN prompt. It is not secret, so it does not need locked +/// memory. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct PinSalt([u8; SALT_LEN]); + +impl PinSalt { + pub(crate) fn generate() -> Result { + let mut salt = [0; SALT_LEN]; + SysRng + .try_fill_bytes(&mut salt) + .map_err(PinHistoryError::Random)?; + Ok(Self(salt)) + } +} + +/// Hashes of the PINs already tried on the current device, kept in a ring +/// buffer of `MAX_ENTRIES`. pub(crate) struct PinHistory { page: LockedPage, - len: usize, + /// Number of PINs recorded since the last `clear`. The next hash is + /// written to slot `attempt_count % MAX_ENTRIES`. + attempt_count: usize, } impl PinHistory { pub(crate) fn new() -> Result { let mut page = LockedPage::new(REGION_LEN).map_err(PinHistoryError::Memory)?; - fill_random(&mut page.as_mut_slice()[..SCRATCH_OFFSET]).map_err(PinHistoryError::Random)?; - Ok(Self { page, len: 0 }) + SysRng + .try_fill_bytes(&mut page.as_mut_slice()[..PEPPER_LEN]) + .map_err(PinHistoryError::Random)?; + Ok(Self { + page, + attempt_count: 0, + }) } - /// Checks `pin` against the PINs already tried and records it if it is - /// new. - pub(crate) fn check(&mut self, pin: &[u8]) -> Result { - self.hash_into_scratch(pin)?; - let result = if self.scratch_is_recorded() { - PinCheck::AlreadyTried - } else { - self.push_scratch(); - PinCheck::Send - }; + /// Checks `pin` against the PINs already tried with `salt` and records it + /// if it is new. + pub(crate) fn check( + &mut self, + salt: &PinSalt, + pin: &[u8], + ) -> Result { + let hashed = self.hash_into_scratch(salt, pin); + let result = hashed.map(|()| { + if self.scratch_is_recorded() { + PinCheck::AlreadyTried + } else { + self.push_scratch(); + PinCheck::Send + } + }); self.page.as_mut_slice()[SCRATCH_OFFSET..ENTRIES_OFFSET].zeroize(); - Ok(result) + result } - /// Forgets all tried PINs, e.g. because a different device may now be - /// connected, and picks a new salt. - pub(crate) fn clear(&mut self) -> Result<(), PinHistoryError> { - let bytes = self.page.as_mut_slice(); - bytes[SCRATCH_OFFSET..].zeroize(); - self.len = 0; - fill_random(&mut bytes[SALT_OFFSET..SCRATCH_OFFSET]).map_err(PinHistoryError::Random) + /// Forgets all tried PINs. The pepper is kept. + pub(crate) fn clear(&mut self) { + self.page.as_mut_slice()[SCRATCH_OFFSET..].zeroize(); + self.attempt_count = 0; } - fn hash_into_scratch(&mut self, pin: &[u8]) -> Result<(), PinHistoryError> { + #[cfg(test)] + pub(crate) fn is_empty(&self) -> bool { + self.attempt_count == 0 + && self.page.as_slice()[ENTRIES_OFFSET..] + .iter() + .all(|b| *b == 0) + } + + fn hash_into_scratch(&mut self, salt: &PinSalt, pin: &[u8]) -> Result<(), PinHistoryError> { let bytes = self.page.as_mut_slice(); - let (keys, rest) = bytes.split_at_mut(SCRATCH_OFFSET); - let (pepper, salt) = keys.split_at(PEPPER_LEN); + let (pepper, rest) = bytes.split_at_mut(SCRATCH_OFFSET); let scratch = &mut rest[..HASH_LEN]; let params = Params::new(M_COST_KIB, T_COST, 1, Some(HASH_LEN)).map_err(PinHistoryError::Hash)?; @@ -127,7 +164,7 @@ impl PinHistory { let mut memory = LockedPage::new(M_COST_KIB as usize * size_of::()) .map_err(PinHistoryError::Memory)?; argon - .hash_password_into_with_memory(pin, salt, scratch, memory.as_mut_blocks()) + .hash_password_into_with_memory(pin, &salt.0, scratch, memory.as_mut_blocks()) .map_err(PinHistoryError::Hash) } @@ -136,49 +173,31 @@ impl PinHistory { let scratch = &bytes[SCRATCH_OFFSET..ENTRIES_OFFSET]; bytes[ENTRIES_OFFSET..] .chunks_exact(HASH_LEN) - .take(self.len) + .take(self.attempt_count.min(MAX_ENTRIES)) .any(|entry| entry == scratch) } - /// Appends the scratch hash, dropping the oldest entry when full. + /// Writes the scratch hash to the next ring buffer slot, overwriting the + /// oldest entry when full. fn push_scratch(&mut self) { - let bytes = self.page.as_mut_slice(); - if self.len == MAX_ENTRIES { - bytes.copy_within(ENTRIES_OFFSET + HASH_LEN.., ENTRIES_OFFSET); - self.len -= 1; - } - let dst = ENTRIES_OFFSET + self.len * HASH_LEN; - bytes.copy_within(SCRATCH_OFFSET..ENTRIES_OFFSET, dst); - self.len += 1; + let dst = ENTRIES_OFFSET + (self.attempt_count & (MAX_ENTRIES - 1)) * HASH_LEN; + self.page + .as_mut_slice() + .copy_within(SCRATCH_OFFSET..ENTRIES_OFFSET, dst); + // Wrapping would take 2^64 PINs; if it did, the history would only + // look shorter until it fills again. + self.attempt_count = self.attempt_count.wrapping_add(1); } } impl std::fmt::Debug for PinHistory { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("PinHistory") - .field("len", &self.len) + .field("attempt_count", &self.attempt_count) .finish_non_exhaustive() } } -fn fill_random(buf: &mut [u8]) -> io::Result<()> { - let mut filled = 0; - while filled < buf.len() { - let rest = &mut buf[filled..]; - // SAFETY: `rest` is a valid, writable buffer of `rest.len()` bytes. - let n = unsafe { libc::getrandom(rest.as_mut_ptr().cast(), rest.len(), 0) }; - if n < 0 { - let err = io::Error::last_os_error(); - if err.kind() == io::ErrorKind::Interrupted { - continue; - } - return Err(err); - } - filled += n as usize; - } - Ok(()) -} - /// Anonymous private memory, locked into RAM and excluded from core dumps. struct LockedPage { ptr: NonNull, @@ -263,55 +282,104 @@ impl Drop for LockedPage { mod tests { use super::*; + fn salt() -> PinSalt { + PinSalt::generate().unwrap() + } + #[test] fn new_pin_is_sent() { let mut history = PinHistory::new().unwrap(); - assert_eq!(history.check(b"1234").unwrap(), PinCheck::Send); + assert_eq!(history.check(&salt(), b"1234").unwrap(), PinCheck::Send); } #[test] fn repeated_pin_is_always_refused() { let mut history = PinHistory::new().unwrap(); - history.check(b"1234").unwrap(); - assert_eq!(history.check(b"1234").unwrap(), PinCheck::AlreadyTried); - assert_eq!(history.check(b"1234").unwrap(), PinCheck::AlreadyTried); + let salt = salt(); + history.check(&salt, b"1234").unwrap(); + assert_eq!( + history.check(&salt, b"1234").unwrap(), + PinCheck::AlreadyTried + ); + assert_eq!( + history.check(&salt, b"1234").unwrap(), + PinCheck::AlreadyTried + ); } #[test] fn every_tried_pin_is_remembered() { let mut history = PinHistory::new().unwrap(); - history.check(b"1111").unwrap(); - history.check(b"2222").unwrap(); - assert_eq!(history.check(b"1111").unwrap(), PinCheck::AlreadyTried); - assert_eq!(history.check(b"2222").unwrap(), PinCheck::AlreadyTried); - assert_eq!(history.check(b"3333").unwrap(), PinCheck::Send); + let salt = salt(); + history.check(&salt, b"1111").unwrap(); + history.check(&salt, b"2222").unwrap(); + assert_eq!( + history.check(&salt, b"1111").unwrap(), + PinCheck::AlreadyTried + ); + assert_eq!( + history.check(&salt, b"2222").unwrap(), + PinCheck::AlreadyTried + ); + assert_eq!(history.check(&salt, b"3333").unwrap(), PinCheck::Send); + } + + #[test] + fn different_salts_keep_separate_histories() { + let mut history = PinHistory::new().unwrap(); + history.check(&salt(), b"1234").unwrap(); + assert_eq!(history.check(&salt(), b"1234").unwrap(), PinCheck::Send); } #[test] fn clear_forgets_tried_pins() { let mut history = PinHistory::new().unwrap(); - history.check(b"1234").unwrap(); - history.clear().unwrap(); - assert_eq!(history.check(b"1234").unwrap(), PinCheck::Send); + let salt = salt(); + history.check(&salt, b"1234").unwrap(); + history.clear(); + assert_eq!(history.check(&salt, b"1234").unwrap(), PinCheck::Send); + } + + #[test] + fn clear_wipes_stored_hashes() { + let mut history = PinHistory::new().unwrap(); + history.check(&salt(), b"1234").unwrap(); + history.clear(); + let bytes = history.page.as_slice(); + assert!(bytes[ENTRIES_OFFSET..].iter().all(|b| *b == 0)); } #[test] fn oldest_entry_is_dropped_when_full() { let mut history = PinHistory::new().unwrap(); + let salt = salt(); for i in 0..=MAX_ENTRIES { assert_eq!( - history.check(format!("{i:04}").as_bytes()).unwrap(), + history.check(&salt, format!("{i:04}").as_bytes()).unwrap(), PinCheck::Send ); } - assert_eq!(history.check(b"0000").unwrap(), PinCheck::Send); - assert_eq!(history.check(b"0002").unwrap(), PinCheck::AlreadyTried); + // 0000 was overwritten by 0016; sending it again overwrites 0001. + assert_eq!(history.check(&salt, b"0000").unwrap(), PinCheck::Send); + assert_eq!(history.check(&salt, b"0001").unwrap(), PinCheck::Send); + assert_eq!( + history.check(&salt, b"0003").unwrap(), + PinCheck::AlreadyTried + ); + assert_eq!( + history.check(&salt, b"0016").unwrap(), + PinCheck::AlreadyTried + ); + assert_eq!( + history.check(&salt, b"0000").unwrap(), + PinCheck::AlreadyTried + ); } #[test] fn scratch_hash_is_wiped_after_check() { let mut history = PinHistory::new().unwrap(); - history.check(b"98765432").unwrap(); + history.check(&salt(), b"98765432").unwrap(); let bytes = history.page.as_slice(); assert!( bytes[SCRATCH_OFFSET..ENTRIES_OFFSET] From 6ef4cb8b3860ccfd5ec04f046203bf2b5cc6e39c Mon Sep 17 00:00:00 2001 From: K Panuragh Date: Sat, 14 Nov 2026 01:53:23 +0530 Subject: [PATCH 3/3] ui: Hash tried PINs with SHA-256 instead of Argon2 The tried PINs already live in a locked page that is excluded from core dumps, so a slow hash adds little. SHA-256 still gives every entry the same size whatever the PIN length, and drops the argon2 dependency and its locked working memory. Also wipe the history on ErrorAuthenticator and ErrorInternal. The UI treats both as final and shows the error page, so the tried PINs are not needed any more. --- CHANGELOG.md | 2 +- Cargo.lock | 26 +--- Cargo.toml | 7 - credentialsd-ui/Cargo.toml | 2 +- credentialsd-ui/src/gui/view_model/mod.rs | 45 +++---- credentialsd-ui/src/pin_history.rs | 151 +++++++--------------- 6 files changed, 74 insertions(+), 159 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62875aa2..bde697f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ - daemon: Build the list of devices offered to the user from libwebauthn's `available_transports()`, the same source discovery uses (#32) - ui: Pass the caller's activation token to the compositor when showing the dialog, so it can take focus when the requesting window is in the background (#152) - ui: Disable core dumps for the UI process, which handles typed PINs. Build with `-Denable_core_dumps=true` to allow them for debugging (#209) -- ui: Tell the user when they enter a PIN that was already tried for the current PIN prompt, instead of sending it again. Tried PINs are kept as peppered Argon2id hashes in locked memory excluded from core dumps, and wiped as soon as the prompt ends (#209) +- ui: Tell the user when they enter a PIN that was already tried for the current PIN prompt, instead of sending it again. Tried PINs are kept as fixed-size SHA-256 hashes in locked memory excluded from core dumps, and wiped as soon as the prompt ends (#209) # 0.4.0 [2026-11-05] diff --git a/Cargo.lock b/Cargo.lock index 145db894..4f1b63f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -87,19 +87,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "argon2" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" -dependencies = [ - "base64ct", - "blake2", - "cpufeatures 0.2.17", - "password-hash", - "zeroize", -] - [[package]] name = "asn1-rs" version = "0.7.2" @@ -847,7 +834,6 @@ dependencies = [ name = "credentialsd-ui" version = "0.4.0" dependencies = [ - "argon2", "async-std", "credentialsd-common", "futures-lite", @@ -859,6 +845,7 @@ dependencies = [ "qrcode", "rand 0.10.2", "serde", + "sha2", "tracing", "tracing-subscriber", "zbus", @@ -2817,17 +2804,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "password-hash" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" -dependencies = [ - "base64ct", - "rand_core 0.6.4", - "subtle", -] - [[package]] name = "pcsc" version = "2.9.0" diff --git a/Cargo.toml b/Cargo.toml index 2e5f1404..bc9a01c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,13 +5,6 @@ members = ["credentialsd", "credentialsd-common", "credentialsd-ui"] [profile.release] lto = true -# PIN hashing in credentialsd-ui is noticeably slow without optimisations. -[profile.dev.package.argon2] -opt-level = 3 - -[profile.dev.package.blake2] -opt-level = 3 - [workspace.dependencies] futures-lite = "=2.6.1" libc = "=0.2.189" diff --git a/credentialsd-ui/Cargo.toml b/credentialsd-ui/Cargo.toml index a3a286c2..c097aac0 100644 --- a/credentialsd-ui/Cargo.toml +++ b/credentialsd-ui/Cargo.toml @@ -12,11 +12,11 @@ wayland = ["gdk-wayland"] [dependencies] credentialsd-common = { path = "../credentialsd-common" } -argon2 = { version = "=0.5.3", default-features = false, features = ["alloc", "zeroize"] } futures-lite.workspace = true libc.workspace = true rand = "=0.10.2" serde.workspace = true +sha2 = "=0.10.9" tracing.workspace = true tracing-subscriber.workspace = true zbus = { workspace = true, default-features = false, features = ["async-io"]} diff --git a/credentialsd-ui/src/gui/view_model/mod.rs b/credentialsd-ui/src/gui/view_model/mod.rs index 0711ab0e..153586d2 100644 --- a/credentialsd-ui/src/gui/view_model/mod.rs +++ b/credentialsd-ui/src/gui/view_model/mod.rs @@ -98,13 +98,7 @@ impl ViewModel { else { return false; }; - match history.check(salt, pin.as_bytes()) { - Ok(check) => check == PinCheck::AlreadyTried, - Err(err) => { - warn!(%err, "Failed to check PIN against earlier attempts"); - false - } - } + history.check(salt, pin.as_bytes()) == PinCheck::AlreadyTried } /// Starts a PIN history when a device asks for a PIN, and wipes it as @@ -479,9 +473,7 @@ enum PinPrompt { /// /// Events that cannot come from the device being asked for its PIN are /// ignored, so that e.g. hybrid restarting in the background does not wipe -/// the history while the user is typing. `ErrorAuthenticator` and -/// `ErrorInternal` don't say which transport failed, so they are ignored too; -/// the transport restarting afterwards ends the prompt. +/// the history while the user is typing. /// /// Any USB or NFC event ends the prompt. That assumes only one of the two is /// discovering at a time, which holds while NFC discovery is disabled in the @@ -497,9 +489,7 @@ fn pin_prompt_change(event: &Event) -> Option { | BackgroundEvent::HybridStarted(_) | BackgroundEvent::HybridConnecting | BackgroundEvent::HybridConnected - | BackgroundEvent::HybridRestarting - | BackgroundEvent::ErrorAuthenticator - | BackgroundEvent::ErrorInternal => None, + | BackgroundEvent::HybridRestarting => None, BackgroundEvent::CeremonyCompleted | BackgroundEvent::PinNotSet { .. } | BackgroundEvent::NeedsUserVerification { .. } @@ -519,7 +509,9 @@ fn pin_prompt_change(event: &Event) -> Option { | BackgroundEvent::ErrorNoCredentials | BackgroundEvent::ErrorPinAttemptsExhausted | BackgroundEvent::ErrorPinNotSet - | BackgroundEvent::ErrorCredentialExcluded => Some(PinPrompt::Closed), + | BackgroundEvent::ErrorCredentialExcluded + | BackgroundEvent::ErrorAuthenticator + | BackgroundEvent::ErrorInternal => Some(PinPrompt::Closed), } } @@ -654,16 +646,21 @@ mod tests { } #[test] - fn ambiguous_error_during_pin_prompt_keeps_history() { - async_std::task::block_on(async { - let h = start(); - h.connect_usb().await; - h.needs_pin().await; - assert!(h.enter_pin("1234").await); - let update = h.background(BackgroundEvent::ErrorAuthenticator).await; - assert!(matches!(update, ViewUpdate::Failed(_))); - assert!(!h.enter_pin("1234").await); - }); + fn error_during_pin_prompt_wipes_history_and_salt() { + for error in [ + BackgroundEvent::ErrorAuthenticator, + BackgroundEvent::ErrorInternal, + ] { + let (mut vm, _h) = view_model(); + vm.track_pin_prompt(&Event::Background(BackgroundEvent::NeedsPin { + attempts_left: None, + })); + assert!(!vm.pin_already_tried("1234")); + + vm.track_pin_prompt(&Event::Background(error)); + assert!(vm.pin_salt.is_none()); + assert!(vm.pin_history.as_ref().unwrap().is_empty()); + } } #[test] diff --git a/credentialsd-ui/src/pin_history.rs b/credentialsd-ui/src/pin_history.rs index 23a41ef6..57bb7ef6 100644 --- a/credentialsd-ui/src/pin_history.rs +++ b/credentialsd-ui/src/pin_history.rs @@ -2,40 +2,38 @@ //! request, so the user can be told instead of wasting a PIN attempt on a PIN //! that already failed. //! -//! Each PIN is hashed with Argon2id, keyed with a random pepper created per -//! history (that is, per request) and salted with a [`PinSalt`] that the -//! caller creates each time a device asks for a PIN, so different devices -//! and PIN prompts have distinct histories. The pepper and hashes live in an +//! Each PIN is stored as a SHA-256 hash, so every entry has the same size +//! whatever the PIN length. The hash covers a random pepper created per +//! history (that is, per request), a [`PinSalt`] that the caller creates each +//! time a device asks for a PIN, and the PIN, so different devices and PIN +//! prompts have distinct histories. The pepper and hashes live in an //! anonymous mapping that is locked into RAM (`mlock`) and excluded from core -//! dumps (`MADV_DONTDUMP`); so does Argon2's working memory while a PIN is -//! hashed. Both are zeroed before they are unmapped. +//! dumps (`MADV_DONTDUMP`), and are zeroed before it is unmapped. //! -//! Limitation: the `blake2` crate used inside Argon2 does not zeroize its -//! state, so a copy of the PIN, salt and pepper can remain on the hashing -//! thread's stack until it is overwritten. The PIN itself is already held in -//! ordinary memory by GTK while the user types it. +//! Limitation: the `sha2` crate does not zeroize its state, so a copy of the +//! PIN, salt and pepper can remain on the hashing thread's stack until it is +//! overwritten. The PIN itself is already held in ordinary memory by GTK +//! while the user types it. use std::{io, ptr::NonNull}; -use argon2::{Algorithm, Argon2, Block, Params, Version}; use rand::{TryRng, rngs::SysRng}; +use sha2::{ + Digest, Sha256, + digest::{OutputSizeUser, typenum::Unsigned}, +}; use zeroize::Zeroize; const PEPPER_LEN: usize = 32; const SALT_LEN: usize = 16; const HASH_LEN: usize = 32; +const _: () = assert!(HASH_LEN == ::OutputSize::USIZE); /// One PIN prompt allows at most 8 attempts (CTAP's retry limit), so this /// is enough for a whole prompt. /// A power of two, so the ring buffer index is a cheap mask. const MAX_ENTRIES: usize = 16; const _: () = assert!(MAX_ENTRIES.is_power_of_two()); -/// Argon2 memory cost in KiB (one block each). Kept far below the usual -/// 8 MiB `RLIMIT_MEMLOCK` so the working memory can be locked. The pepper is -/// secret, so memory-hardness matters little here. -const M_COST_KIB: u32 = 512; -const T_COST: u32 = 3; - const SCRATCH_OFFSET: usize = PEPPER_LEN; const ENTRIES_OFFSET: usize = SCRATCH_OFFSET + HASH_LEN; const REGION_LEN: usize = ENTRIES_OFFSET + MAX_ENTRIES * HASH_LEN; @@ -56,8 +54,6 @@ pub(crate) enum PinHistoryError { Memory(io::Error), /// The kernel random number generator failed. Random(rand::rngs::SysError), - /// Argon2 rejected its parameters or inputs. - Hash(argon2::Error), } impl std::fmt::Display for PinHistoryError { @@ -65,7 +61,6 @@ impl std::fmt::Display for PinHistoryError { match self { Self::Memory(err) => write!(f, "failed to set up locked memory for PIN history: {err}"), Self::Random(err) => write!(f, "failed to generate random bytes: {err}"), - Self::Hash(err) => write!(f, "failed to hash PIN: {err}"), } } } @@ -75,9 +70,6 @@ impl std::error::Error for PinHistoryError { match self { Self::Memory(err) => Some(err), Self::Random(err) => Some(err), - // argon2::Error only implements std::error::Error with the - // crate's `std` feature; its message is included in Display. - Self::Hash(_) => None, } } } @@ -120,20 +112,14 @@ impl PinHistory { /// Checks `pin` against the PINs already tried with `salt` and records it /// if it is new. - pub(crate) fn check( - &mut self, - salt: &PinSalt, - pin: &[u8], - ) -> Result { - let hashed = self.hash_into_scratch(salt, pin); - let result = hashed.map(|()| { - if self.scratch_is_recorded() { - PinCheck::AlreadyTried - } else { - self.push_scratch(); - PinCheck::Send - } - }); + pub(crate) fn check(&mut self, salt: &PinSalt, pin: &[u8]) -> PinCheck { + self.hash_into_scratch(salt, pin); + let result = if self.scratch_is_recorded() { + PinCheck::AlreadyTried + } else { + self.push_scratch(); + PinCheck::Send + }; self.page.as_mut_slice()[SCRATCH_OFFSET..ENTRIES_OFFSET].zeroize(); result } @@ -152,20 +138,15 @@ impl PinHistory { .all(|b| *b == 0) } - fn hash_into_scratch(&mut self, salt: &PinSalt, pin: &[u8]) -> Result<(), PinHistoryError> { + fn hash_into_scratch(&mut self, salt: &PinSalt, pin: &[u8]) { let bytes = self.page.as_mut_slice(); let (pepper, rest) = bytes.split_at_mut(SCRATCH_OFFSET); let scratch = &mut rest[..HASH_LEN]; - let params = - Params::new(M_COST_KIB, T_COST, 1, Some(HASH_LEN)).map_err(PinHistoryError::Hash)?; - let argon = Argon2::new_with_secret(pepper, Algorithm::Argon2id, Version::V0x13, params) - .map_err(PinHistoryError::Hash)?; - // Dropped (zeroed and unmapped) at the end of this function. - let mut memory = LockedPage::new(M_COST_KIB as usize * size_of::()) - .map_err(PinHistoryError::Memory)?; - argon - .hash_password_into_with_memory(pin, &salt.0, scratch, memory.as_mut_blocks()) - .map_err(PinHistoryError::Hash) + let mut hasher = Sha256::new(); + hasher.update(&*pepper); + hasher.update(salt.0); + hasher.update(pin); + hasher.finalize_into(scratch.into()); } fn scratch_is_recorded(&self) -> bool { @@ -252,17 +233,6 @@ impl LockedPage { // SAFETY: as in `as_slice`; `&mut self` guarantees exclusive access. unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) } } - - /// Views the mapping as Argon2 blocks; trailing bytes that do not fill a - /// whole block are left out. - fn as_mut_blocks(&mut self) -> &mut [Block] { - let count = self.len / size_of::(); - // SAFETY: mmap returns page-aligned memory, which satisfies Block's - // 64-byte alignment; `count` blocks fit in `len` bytes; a Block is a - // plain array of u64, for which the all-zero (or any) bit pattern is - // valid; `&mut self` guarantees exclusive access. - unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr().cast::(), count) } - } } impl Drop for LockedPage { @@ -289,61 +259,49 @@ mod tests { #[test] fn new_pin_is_sent() { let mut history = PinHistory::new().unwrap(); - assert_eq!(history.check(&salt(), b"1234").unwrap(), PinCheck::Send); + assert_eq!(history.check(&salt(), b"1234"), PinCheck::Send); } #[test] fn repeated_pin_is_always_refused() { let mut history = PinHistory::new().unwrap(); let salt = salt(); - history.check(&salt, b"1234").unwrap(); - assert_eq!( - history.check(&salt, b"1234").unwrap(), - PinCheck::AlreadyTried - ); - assert_eq!( - history.check(&salt, b"1234").unwrap(), - PinCheck::AlreadyTried - ); + history.check(&salt, b"1234"); + assert_eq!(history.check(&salt, b"1234"), PinCheck::AlreadyTried); + assert_eq!(history.check(&salt, b"1234"), PinCheck::AlreadyTried); } #[test] fn every_tried_pin_is_remembered() { let mut history = PinHistory::new().unwrap(); let salt = salt(); - history.check(&salt, b"1111").unwrap(); - history.check(&salt, b"2222").unwrap(); - assert_eq!( - history.check(&salt, b"1111").unwrap(), - PinCheck::AlreadyTried - ); - assert_eq!( - history.check(&salt, b"2222").unwrap(), - PinCheck::AlreadyTried - ); - assert_eq!(history.check(&salt, b"3333").unwrap(), PinCheck::Send); + history.check(&salt, b"1111"); + history.check(&salt, b"2222"); + assert_eq!(history.check(&salt, b"1111"), PinCheck::AlreadyTried); + assert_eq!(history.check(&salt, b"2222"), PinCheck::AlreadyTried); + assert_eq!(history.check(&salt, b"3333"), PinCheck::Send); } #[test] fn different_salts_keep_separate_histories() { let mut history = PinHistory::new().unwrap(); - history.check(&salt(), b"1234").unwrap(); - assert_eq!(history.check(&salt(), b"1234").unwrap(), PinCheck::Send); + history.check(&salt(), b"1234"); + assert_eq!(history.check(&salt(), b"1234"), PinCheck::Send); } #[test] fn clear_forgets_tried_pins() { let mut history = PinHistory::new().unwrap(); let salt = salt(); - history.check(&salt, b"1234").unwrap(); + history.check(&salt, b"1234"); history.clear(); - assert_eq!(history.check(&salt, b"1234").unwrap(), PinCheck::Send); + assert_eq!(history.check(&salt, b"1234"), PinCheck::Send); } #[test] fn clear_wipes_stored_hashes() { let mut history = PinHistory::new().unwrap(); - history.check(&salt(), b"1234").unwrap(); + history.check(&salt(), b"1234"); history.clear(); let bytes = history.page.as_slice(); assert!(bytes[ENTRIES_OFFSET..].iter().all(|b| *b == 0)); @@ -355,31 +313,22 @@ mod tests { let salt = salt(); for i in 0..=MAX_ENTRIES { assert_eq!( - history.check(&salt, format!("{i:04}").as_bytes()).unwrap(), + history.check(&salt, format!("{i:04}").as_bytes()), PinCheck::Send ); } // 0000 was overwritten by 0016; sending it again overwrites 0001. - assert_eq!(history.check(&salt, b"0000").unwrap(), PinCheck::Send); - assert_eq!(history.check(&salt, b"0001").unwrap(), PinCheck::Send); - assert_eq!( - history.check(&salt, b"0003").unwrap(), - PinCheck::AlreadyTried - ); - assert_eq!( - history.check(&salt, b"0016").unwrap(), - PinCheck::AlreadyTried - ); - assert_eq!( - history.check(&salt, b"0000").unwrap(), - PinCheck::AlreadyTried - ); + assert_eq!(history.check(&salt, b"0000"), PinCheck::Send); + assert_eq!(history.check(&salt, b"0001"), PinCheck::Send); + assert_eq!(history.check(&salt, b"0003"), PinCheck::AlreadyTried); + assert_eq!(history.check(&salt, b"0016"), PinCheck::AlreadyTried); + assert_eq!(history.check(&salt, b"0000"), PinCheck::AlreadyTried); } #[test] fn scratch_hash_is_wiped_after_check() { let mut history = PinHistory::new().unwrap(); - history.check(&salt(), b"98765432").unwrap(); + history.check(&salt(), b"98765432"); let bytes = history.page.as_slice(); assert!( bytes[SCRATCH_OFFSET..ENTRIES_OFFSET]