Skip to content

ui: Don't resend a PIN that was already tried - #261

Open
kpanuragh wants to merge 3 commits into
linux-credentials:mainfrom
kpanuragh:dedupe-pins
Open

kpanuragh wants to merge 3 commits into
linux-credentials:mainfrom
kpanuragh:dedupe-pins

Conversation

@kpanuragh

@kpanuragh kpanuragh commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Closes #209. The core dump hardening is now in #263.

When the user enters a PIN that was already sent to the connected device during this request, the UI shows "You already tried this PIN. Enter a different PIN.", with the remaining attempts if known, and does not send it.

How tried PINs are kept

  • Nothing is stored in plaintext. Each PIN is hashed with Argon2::new_with_secret(pepper, Argon2id, ...). The pepper and salt are random and created per request.
  • The pepper, salt and up to 16 hashes live in one anonymous mmap page. The page is mlocked, marked MADV_DONTDUMP and zeroed before munmap. Argon2's working memory gets the same treatment, through hash_password_into_with_memory.
  • Argon2 uses m=512 KiB, t=3, which stays well under the default 8 MiB RLIMIT_MEMLOCK. If locked memory can't be set up, the UI logs a warning and sends PINs as before.
  • The history is cleared on UsbConnected/NfcConnected, because the UI can't tell devices apart (Send device name to backend #257) and a different key can have a different PIN.
  • PINs longer than 63 bytes are never sent, so they are not recorded.
  • argon2 0.5.3 is the only new crate, plus password-hash. It reuses the blake2 0.10.6 already in the lockfile. Both crates build at opt-level 3 in dev; without that, debug builds take about 0.5 s per hash.

Known limitations

  • The blake2 crate doesn't zeroize its state. A copy of the PIN, salt and pepper can stay on the hashing thread's stack until something overwrites it. GTK already holds the PIN in ordinary memory while it is typed.
  • "Already tried" means "sent before", not "rejected by the device".

Open question

Should we keep the hashing? As @kalvdans pointed out, a 4–6 digit PIN is easy to brute-force once the salt is known. The hashing only guards against accidentally logging the PIN. If you'd rather drop it, storing the tried PINs in the same locked, MADV_DONTDUMP page removes argon2 and roughly half of pin_history.rs. I'm happy to make that change.

Testing

  • cargo test -p credentialsd-ui: 11 pass. They cover PinHistory (a repeat is always refused, every tried PIN is remembered, clearing, eviction, the scratch slot is wiped) and the view-model event loop over its real channels: a repeated PIN is never sent, a new connection forgets earlier PINs, over-long PINs are not recorded.
  • cargo clippy --all-targets and cargo fmt --check: clean.
  • Not tested: the GTK prompt with a real key. I have no PIN-capable authenticator.

@kalvdans

Copy link
Copy Markdown

hashing won't add much security as the pin is 4-6 digits and is easily bruteforced if the salt is known. So security-wise it is just as secure as storing the tried pins in cleartext in a MADV_DONTDUMP page?

@iinuwa

iinuwa commented Nov 11, 2026

Copy link
Copy Markdown
Member

Thanks for this submission! Can you split this in two PRs? The memory protection is useful independent of the remember PIN feature.

Is the "enter it again to send anyway" override what you want, or should a repeated PIN be refused outright?

There's no point in sending a the PIN again, just tell the user they already tried it.

Would you rather have PR_SET_DUMPABLE set after GTK's first portal call? xdg-desktop-portal caches caller info per connection, so that works today, but it is fragile. Or is RLIMIT_CORE enough?

No, I think that would just make the code less clear. Once xdg-desktop-portal supports systemd-appd for identifying processes, then we could drop ptrace.

However, we don't currently support dark mode right now, I think. Maybe this doesn't matter and we should do it anyway? I'll have to think about that some more. For now, this is probably fine.

hashing won't add much security as the pin is 4-6 digits and is easily bruteforced if the salt is known. So security-wise it is just as secure as storing the tried pins in cleartext in a MADV_DONTDUMP page?

Yeah, hashing is just a provision against accidentally logging the cleartext value, assuming that the secret pepper is handled with more care than the hashes. But if we can keep the secret from leaking, then we can keep the hashes from leaking, and the memory protection from other processes is definitely more important. I might be fine with dropping this. I'll think about it some more.

@kpanuragh kpanuragh changed the title ui: Warn before resending a PIN that was already tried ui: Don't resend a PIN that was already tried Nov 12, 2026
@kpanuragh

Copy link
Copy Markdown
Contributor Author

Thanks for the review!

  • Split: the core dump change is now ui: Disable core dumps for the UI process #263, and this PR has only the PIN feature, rebased on main.
  • A repeated PIN is now always refused, with no "enter it again" override. The prompt says "You already tried this PIN. Enter a different PIN.", plus the remaining attempts if known.
  • RLIMIT_CORE: kept as is in ui: Disable core dumps for the UI process #263. I'll leave ptrace to Yama until xdg-desktop-portal can identify callers without /proc/<pid>/root.
  • Hashing: I've left it in for now. If you decide to drop it, I'll switch to storing the tried PINs in the locked, MADV_DONTDUMP page, which also removes the argon2 dependency.

@kpanuragh

Copy link
Copy Markdown
Contributor Author

One question about the split. #263 only disables core dumps. The locked-memory helper (an mmaped region that is mlocked, marked MADV_DONTDUMP and zeroed on drop) is still in this PR, because only the PIN history uses it at the moment.

Should I move that helper into #263 as well, so other secrets in the UI can use it independently of this feature? The new-PIN entry in the set-PIN flow is one example. Or is it fine to keep it here with its only user?

@iinuwa iinuwa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The memory handling looks good, but we need to make the PIN history lifetime shorter, see the comments

Comment thread credentialsd-ui/src/pin_history.rs Outdated
Comment on lines +164 to +180
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(())
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we use the rand crate since credentialsd already depends on it?

Comment thread credentialsd-ui/src/pin_history.rs Outdated
//! 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is misleading: we do store PINs, just as hashes.

Suggested change
//! PINs are never stored. Each PIN is hashed with Argon2id, keyed with a
//! Each PIN is hashed with Argon2id, keyed with a

Comment thread credentialsd-ui/src/pin_history.rs Outdated

/// Checks `pin` against the PINs already tried and records it if it is
/// new.
pub(crate) fn check(&mut self, pin: &[u8]) -> Result<PinCheck, PinHistoryError> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

based on the comment in the event loop, this could take the salt as a public parameter and doesn't need to be persisted in the buffer.

Comment thread credentialsd-ui/src/pin_history.rs Outdated
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think clearing history and setting a new salt need to be separate functions: we want to clear as quickly as possible, but we only need to generate a new salt when we connect to a new device that needs a PIN.

Comment on lines +144 to +154
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;
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I think we could avoid copying by using a ring buffer instead, e.g. change
len to an attempt_count that always increments. Then the offset to write to would be ENTRIES_OFFSET + (attempt_count & (MAX_ENTRIES - 1)) * HASH_LEN. wrapping the counter should never happen, but should be safe to do.


Event::Background(BackgroundEvent::UsbConnected) => {
info!("Found USB device");
self.reset_pin_history();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should reset as soon as the PIN is accepted, and only generate a salt when the PIN is needed.

I think this means we need a different API for PinHistory. It may be easier to expose the salt as a public parameter, and then we can store an Option<[u8; 32]> for the salt that is filled that should make different devices and requests have distinct histories, and we only keep it in memory as long as we need it.

Then we can change this function to be called on every tick of the event loop, and to:

if NeedsPin
  if not salt exists, create salt
else
  if salt exists, clear history and salt

This could be refined to ignore events that may be sent concurrently during the PIN collection (like if hybrid flakes and sends a transport error).

Comment thread credentialsd-ui/src/pin_history.rs Outdated
Comment on lines +12 to +15
//! 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for this note

@iinuwa

iinuwa commented Nov 13, 2026

Copy link
Copy Markdown
Member

On second thought, we've decided to just drop argon2 for now; the memory page protection should be sufficient. Can you change to just use SHA2 to make the PIN entries a constant size?

We still should make sure to zeroize as soon as we don't need the request any more (when a background event is not NeedsPin)

Should I move that helper into #263 as well, so other secrets in the UI can use it independently of this feature? The new-PIN entry in the set-PIN flow is one example. Or is it fine to keep it here with its only user?

No, that's fine to stay here.

kpanuragh added a commit to kpanuragh/credentialsd that referenced this pull request Nov 13, 2026
Address review on linux-credentials#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.
@kpanuragh

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Addressed in e8c4d4a (kept as a separate commit to make it easier to review; happy to squash):

  • Lifetime: the view model now holds an Option<PinSalt>. On every event, track_pin_prompt creates a salt on NeedsPin if there is none. Any event that ends the prompt clears the history and drops the salt: PIN accepted (NeedsUserPresence, SelectingCredential, …), device connected or restarting, or a terminal error. Hybrid events are ignored, and so are ErrorAuthenticator/ErrorInternal since they don't say which transport failed. USB swallows those mid-flow and follows up with UsbRestarting, which ends the prompt. The match is exhaustive, so a new BackgroundEvent variant forces a decision.
  • API: check(&salt, pin) takes the salt; clear() only wipes the hashes, and salt generation is separate (PinSalt::generate()). The pepper stays in the locked page for the lifetime of the request.
  • Ring buffer: attempt_count with & (MAX_ENTRIES - 1), plus a const assert that MAX_ENTRIES is a power of two.
  • rand: rand::rngs::SysRng, same =0.10.2 as the daemon.
  • Docs: applied your suggestion.

One assumption to flag: every USB and NFC event ends the prompt. That's fine while NFC discovery is disabled in the daemon. If both transports ever run at once, the other one's events should be ignored like hybrid's; there's a comment saying so.

There's also one pre-existing edge case I left alone: the PIN is recorded before it's sent. If enter_client_pin fails, that PIN would be refused for the rest of the prompt even though the device never saw it. I can add a forget_newest() for that path if you'd like.

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 linux-credentials#209.
Address review on linux-credentials#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.
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.
@kpanuragh

Copy link
Copy Markdown
Contributor Author

Done, and rebased on main to fix the conflict:

  • SHA-256: Argon2 is gone. Each tried PIN is stored as SHA-256 over the per-request pepper, the per-prompt salt and the PIN, so entries are a constant 32 bytes. They still live in the locked, MADV_DONTDUMP page. This also drops the argon2 dependency and the dev-profile overrides it needed.

  • Wiping: the history and salt are zeroized as soon as an event other than NeedsPin arrives, now including ErrorAuthenticator and ErrorInternal. Before, these two kept the history.

    The one exception is the Hybrid* events. The daemon runs hybrid discovery alongside USB, so HybridStarted/HybridRestarting can arrive while the user is typing a USB PIN. Wiping on those would quietly turn the check off. They never come from the device being asked for the PIN, so ignoring them doesn't keep the history past the end of the prompt. Happy to make it strict if you'd rather.

Tested end to end with a virtual FIDO2 key (PIN set):

  • entered a wrong PIN, which the key rejected;
  • entered the same PIN again: the dialog showed "You already tried this PIN. Enter a different PIN. 7 attempts remaining." and the key's log shows that PIN arrived only once;
  • entered the correct PIN, which created the credential.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Deduplicate client PIN entries

3 participants