diff --git a/CHANGELOG.md b/CHANGELOG.md index 491d652c..bde697f1 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 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 c28837ce..4f1b63f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -843,10 +843,13 @@ dependencies = [ "gtk4", "libc", "qrcode", + "rand 0.10.2", "serde", + "sha2", "tracing", "tracing-subscriber", "zbus", + "zeroize", ] [[package]] diff --git a/credentialsd-ui/Cargo.toml b/credentialsd-ui/Cargo.toml index b6d47a3f..c097aac0 100644 --- a/credentialsd-ui/Cargo.toml +++ b/credentialsd-ui/Cargo.toml @@ -14,7 +14,9 @@ credentialsd-common = { path = "../credentialsd-common" } 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"]} @@ -25,3 +27,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..153586d2 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, PinSalt}, +}; use super::ViewUpdate; @@ -36,6 +40,15 @@ pub(crate) struct ViewModel { selected_device: Option, hybrid_qr_code_data: Option>, + + /// 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, } impl ViewModel { @@ -66,6 +79,48 @@ 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_salt: None, + 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), Some(salt)) = (self.pin_history.as_mut(), self.pin_salt.as_ref()) + else { + return false; + }; + history.check(salt, pin.as_bytes()) == PinCheck::AlreadyTried + } + + /// 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 => {} } } @@ -143,6 +198,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; @@ -150,6 +206,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"); @@ -212,6 +277,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 @@ -396,3 +462,286 @@ pub enum Event { Background(BackgroundEvent), 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. +/// +/// 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 => 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 + | BackgroundEvent::ErrorAuthenticator + | BackgroundEvent::ErrorInternal => Some(PinPrompt::Closed), + } +} + +#[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 view_model() -> (ViewModel, 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, + activation_token: None, + }; + let vm = ViewModel::new( + request, + Arc::new(AsyncMutex::new(client)), + view_rx, + update_tx, + ); + 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) { + 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 + .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; + h.needs_pin().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 wrong_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); + // 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 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] + 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); + }); + } + + #[test] + fn new_connection_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); + 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/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..57bb7ef6 --- /dev/null +++ b/credentialsd-ui/src/pin_history.rs @@ -0,0 +1,339 @@ +//! 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. +//! +//! 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`), and are zeroed before it is unmapped. +//! +//! 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 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()); + +const SCRATCH_OFFSET: usize = PEPPER_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(rand::rngs::SysError), +} + +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}"), + } + } +} + +impl std::error::Error for PinHistoryError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Memory(err) => Some(err), + Self::Random(err) => Some(err), + } + } +} + +/// 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, + /// 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)?; + 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 with `salt` and records it + /// if it is new. + 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 + } + + /// 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; + } + + #[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]) { + let bytes = self.page.as_mut_slice(); + let (pepper, rest) = bytes.split_at_mut(SCRATCH_OFFSET); + let scratch = &mut rest[..HASH_LEN]; + 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 { + let bytes = self.page.as_slice(); + let scratch = &bytes[SCRATCH_OFFSET..ENTRIES_OFFSET]; + bytes[ENTRIES_OFFSET..] + .chunks_exact(HASH_LEN) + .take(self.attempt_count.min(MAX_ENTRIES)) + .any(|entry| entry == scratch) + } + + /// Writes the scratch hash to the next ring buffer slot, overwriting the + /// oldest entry when full. + fn push_scratch(&mut self) { + 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("attempt_count", &self.attempt_count) + .finish_non_exhaustive() + } +} + +/// 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) } + } +} + +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::*; + + fn salt() -> PinSalt { + PinSalt::generate().unwrap() + } + + #[test] + fn new_pin_is_sent() { + let mut history = PinHistory::new().unwrap(); + 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"); + 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"); + 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"); + 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"); + history.clear(); + 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"); + 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(&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"), 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"); + let bytes = history.page.as_slice(); + assert!( + bytes[SCRATCH_OFFSET..ENTRIES_OFFSET] + .iter() + .all(|b| *b == 0) + ); + } +}