S067: passwords page asks for the computer password without a master password (PAM login service, faillock-aware throttle, D-052); same check guards reveal, copy, edit, export, master password

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-18 07:15:13 -06:00
commit 4365908d4c
13 changed files with 549 additions and 38 deletions

View file

@ -64,7 +64,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
| `nice cargo build --release -j 2` | compile check, produces `target/release/nacre` | now |
| `nice cargo test --release -j 2` | unit tests (44, ~16 s test-profile build then <1 s run; shares the S001 build) (util, settings, history, bookmarks, permissions, vault, dns, bridge loopback, download, adblock, keys, scripts, updates, inject, hub, theme, ui::widgets input, ui::paint, ui::pages::newtab) | first successful build; not alongside a build |
| `src/selftest.rs` | in-app self test: `NACRE_SCRIPT=<file>` runs script commands (listed at its top) | now |
| `tools/smoke.sh <script> [outdir]` | smoke run in a hidden nested Wayland session (`tools/nested-session.sh start\|stop <dir> [WxH]`: Xvfb → nested niri, software GL, own runtime dir and bus; `SMOKE_SIZE` = nested output size, window at 0,0) with a throwaway home; selftest `click`/`rclick`/`pagescroll`/`pagetype` are real compositor input there (`tools/wl-input`, own crate, built on first use; `wtype`), `resize` goes through the nested niri; outdir (default `target/smoke/<name>-<time>`, use a fresh one: `home/` persists) gets `nacre.log`, `selftest.log`, `<shot>.png`, `<status>.json`, `home/`, `session/`; exits non-zero on crash, panic, no `status done` or a failed `assert <js>`. Scripts in `tests/smoke/` (`launch.txt` offline, `https.txt` needs internet, `restore.txt` with `SMOKE_HOME=<launch outdir>/home`, `chrome.txt` chrome and every flyout dark and light, offline; `colours.txt` colours after welcome and site colour vs internal pages, hidden `SMOKE_SIZE=1280x1100`; `input.txt` real clicks, typing, right click, wheel on a web page, offline; `basics.txt` tabs, navigation, find, zoom, full screen, pop-ups, offline; `heavy-web.txt` DuckDuckGo, Wikipedia, YouTube, needs internet, `SMOKE_TIMEOUT=900`; `keys.txt` every shortcut action, offline; `privacy-net.txt` DNT/GPC/Save-Data headers and third-party cookies on a loopback server, offline, start `python3 tests/smoke/net/server.py &` first; `site-doctor.txt` Google sign-in, captchas, Reddit, GitHub, needs internet; `cache.txt` HTTP cache, offline, start `python3 tests/smoke/cache/server.py &` first; selftest `launch <args>` checks single instance; `cookies.txt` → `cookies-restart.txt` → `cookies-cleared.txt` encrypted cookies across restarts with `SMOKE_KEYRING=1` (own throwaway GNOME Keyring + bus) and `SMOKE_HOME`, `cookies-nokeyring.txt` without, server.py first; `zap.txt` ad removal animation (cookie shield mid-animation, slots closed, players kept, Motion off), dark and light, offline, `SMOKE_SIZE=1280x900`; `stuck.txt` tab lifecycle (leave-page question, Reload, nacre:// pages free their view, Back with history, chatty page closes without CRITICAL, shortcut recording ends), offline, `SMOKE_SIZE=1280x900`; `nacre-lock.txt` web pages can't reach nacre:// and the passwords page asks on every open (D-049), server.py first, `SMOKE_SIZE=1280x900`; `crash-adblock.txt` R5-01 regression, ~1300 blocked loads with reloads/navigations mid-load plus 3200 timers under GC pressure, offline, server.py first; `hang.txt` page isn't responding bar (Wait, Reload page, caught on switch-to) and crash pages for the active, a hidden and a PiP tab, hidden only, offline, `SMOKE_SIZE=1280x900`; `previews.txt` hover-preview probe, no pass/fail, see its header); header documents env vars and commands. `SMOKE_VISIBLE=1` shows the run on the user's screen (real GPU; page input synthesized in the page, no `rclick`/`resize`); it refuses to start unless the user's niri config has the `dev.nacre.Nacre` window rule from the smoke.sh header (DP-1, no focus), so it never moves the user's focus or workspace (D-044). WebKit state (S050): launch, basics, input, keys, chrome, dialogs, pip, auth, stores-*, integ-spell, net-*, privacy-net, privacy-mode, cache*, crash-adblock green hidden (loopback skips the bridge, no `NACRE_NO_BRIDGE` needed); other scripts not yet. Read the PNGs | now (S003, S046) |
| `tools/smoke.sh <script> [outdir]` | smoke run in a hidden nested Wayland session (`tools/nested-session.sh start\|stop <dir> [WxH]`: Xvfb → nested niri, software GL, own runtime dir and bus; `SMOKE_SIZE` = nested output size, window at 0,0) with a throwaway home; selftest `click`/`rclick`/`pagescroll`/`pagetype` are real compositor input there (`tools/wl-input`, own crate, built on first use; `wtype`), `resize` goes through the nested niri; outdir (default `target/smoke/<name>-<time>`, use a fresh one: `home/` persists) gets `nacre.log`, `selftest.log`, `<shot>.png`, `<status>.json`, `home/`, `session/`; exits non-zero on crash, panic, no `status done` or a failed `assert <js>`. Scripts in `tests/smoke/` (`launch.txt` offline, `https.txt` needs internet, `restore.txt` with `SMOKE_HOME=<launch outdir>/home`, `chrome.txt` chrome and every flyout dark and light, offline; `colours.txt` colours after welcome and site colour vs internal pages, hidden `SMOKE_SIZE=1280x1100`; `input.txt` real clicks, typing, right click, wheel on a web page, offline; `basics.txt` tabs, navigation, find, zoom, full screen, pop-ups, offline; `heavy-web.txt` DuckDuckGo, Wikipedia, YouTube, needs internet, `SMOKE_TIMEOUT=900`; `keys.txt` every shortcut action, offline; `privacy-net.txt` DNT/GPC/Save-Data headers and third-party cookies on a loopback server, offline, start `python3 tests/smoke/net/server.py &` first; `site-doctor.txt` Google sign-in, captchas, Reddit, GitHub, needs internet; `cache.txt` HTTP cache, offline, start `python3 tests/smoke/cache/server.py &` first; selftest `launch <args>` checks single instance; `cookies.txt` → `cookies-restart.txt` → `cookies-cleared.txt` encrypted cookies across restarts with `SMOKE_KEYRING=1` (own throwaway GNOME Keyring + bus) and `SMOKE_HOME`, `cookies-nokeyring.txt` without, server.py first; `zap.txt` ad removal animation (cookie shield mid-animation, slots closed, players kept, Motion off), dark and light, offline, `SMOKE_SIZE=1280x900`; `stuck.txt` tab lifecycle (leave-page question, Reload, nacre:// pages free their view, Back with history, chatty page closes without CRITICAL, shortcut recording ends), offline, `SMOKE_SIZE=1280x900`; `nacre-lock.txt` web pages can't reach nacre:// and the passwords page asks on every open (D-049, D-052: computer password via `NACRE_TEST_ACCOUNT_PASSWORD=smoke-account`), server.py first, `SMOKE_SIZE=1280x900`; `crash-adblock.txt` R5-01 regression, ~1300 blocked loads with reloads/navigations mid-load plus 3200 timers under GC pressure, offline, server.py first; `hang.txt` page isn't responding bar (Wait, Reload page, caught on switch-to) and crash pages for the active, a hidden and a PiP tab, hidden only, offline, `SMOKE_SIZE=1280x900`; `previews.txt` hover-preview probe, no pass/fail, see its header); header documents env vars and commands. `SMOKE_VISIBLE=1` shows the run on the user's screen (real GPU; page input synthesized in the page, no `rclick`/`resize`); it refuses to start unless the user's niri config has the `dev.nacre.Nacre` window rule from the smoke.sh header (DP-1, no focus), so it never moves the user's focus or workspace (D-044). WebKit state (S050): launch, basics, input, keys, chrome, dialogs, pip, auth, stores-*, integ-spell, net-*, privacy-net, privacy-mode, cache*, crash-adblock green hidden (loopback skips the bridge, no `NACRE_NO_BRIDGE` needed); other scripts not yet. Read the PNGs | now (S003, S046) |
| `nacre://gallery` + `SMOKE_SIZE=1400x2800 tools/smoke.sh tests/smoke/gallery.txt` | every design token and widget, dark and light (+ new tab and settings shots); read the PNGs | now (S015) |
| `SMOKE_SIZE=1400x1200 tools/smoke.sh tests/smoke/newtab.txt` | new tab page dark/light, nothing playing and a video playing, weather failed state, tall/narrow/phone widths (offline); `tests/smoke/newtab-weather.txt` shoots the real weather card (needs internet); read the PNGs | now (S017) |
| `SMOKE_SIZE=1400x900 tools/smoke.sh tests/smoke/backgrounds.txt` | every new tab background with the pointer, Customize panel dark/light, image + blur, GIF frames; `perf-*-a/b.json` `frames` (median/max draw ms, `drawn` count) per background at Lots/Fast, hidden tab, still, Motion off. Selftest `pointer x y`, `customize`; `@PAGESDIR@` = path of tests/smoke/pages | now (S018) |

View file

@ -11,11 +11,11 @@ D-052. User report (2026-11-18): without a master password, `nacre://passwords`
- `/etc/pam.d/system-auth`, `/etc/pam.d/login`, `/etc/security/faillock.conf` (this PC: Arch, pam_faillock deny 3)
## Steps
- [ ] Pick the check, write it in D-052: PAM conversation in-process for the current user (`getuid` user, never a typed user name) through an existing service (prefer one that includes `system-auth`, like `login` or the screen lockers use; no root, no new /etc file; works from an AppImage) — or the running polkit agent if PAM can't work unprivileged. Note faillock: 3 wrong tries lock the account login for 10 min, so Nacre allows at most 2 tries per minute and says so.
- [ ] `src/auth.rs`: `verify_account_password(&str) -> Result<(), AuthError>` off the main thread (PAM can take ~2 s on failure); password buffer zeroed after use; unit test for the pure parts (try throttling, error texts). Missing PAM → the gate says why and offers setting a master password, never opens.
- [ ] Gate UI in device mode: "Enter your computer password (the one you use to log in) to see your passwords", password field, Unlock, error line, busy state; replaces the click button. The same check guards Reveal/Copy/Edit/Export and removing or changing the master password.
- [ ] Selftest: `NACRE_TEST_ACCOUNT_PASSWORD=<pw>` swaps the PAM call for a compare (debug/selftest only, never in normal runs) so `nacre-lock.txt` covers wrong → right; extend `nacre-lock.txt`.
- [ ] PROGRESS entry, DECISIONS D-052, DESIGN note, INDEX line, tracker, commit `S067: …`, push.
- [x] Pick the check, write it in D-052: PAM conversation in-process for the current user (`getuid` user, never a typed user name) through an existing service (prefer one that includes `system-auth`, like `login` or the screen lockers use; no root, no new /etc file; works from an AppImage) — or the running polkit agent if PAM can't work unprivileged. Note faillock: 3 wrong tries lock the account login for 10 min, so Nacre allows at most 2 tries per minute and says so.
- [x] `src/auth.rs`: `verify_account_password(&str) -> Result<(), AuthError>` off the main thread (PAM can take ~2 s on failure); password buffer zeroed after use; unit test for the pure parts (try throttling, error texts). Missing PAM → the gate says why and offers setting a master password, never opens.
- [x] Gate UI in device mode: "Enter your computer password (the one you use to log in) to see your passwords", password field, Unlock, error line, busy state; replaces the click button. The same check guards Reveal/Copy/Edit/Export and removing or changing the master password.
- [x] Selftest: `NACRE_TEST_ACCOUNT_PASSWORD=<pw>` swaps the PAM call for a compare (debug/selftest only, never in normal runs) so `nacre-lock.txt` covers wrong → right; extend `nacre-lock.txt`.
- [x] PROGRESS entry, DECISIONS D-052, DESIGN note, INDEX line, tracker, commit `S067: …`, push.
- [ ] 🧑 (orchestrator asks the user) type the real account password once on screen: wrong once, then right; note the answer.
## End criteria

View file

@ -55,4 +55,4 @@
- D-049 — 2026-11-18 — Internal pages: web content never opens, redirects to, frames or pops up a `nacre://` URL; only the user's own actions open them. `nacre://passwords` asks for the vault unlock on every open, relocks when its tab is hidden, switched, navigated or closed, and is never saved in the session. — Pages could open nacre://passwords with a link. — S063
- D-050 — 2026-11-18 — Amends D-022: a custom download manager is a user-given name + loopback port (several allowed), listed with the built-in managers; the endpoint is `http://127.0.0.1:<port>/` with D-022's body, ping and fallback. S036 superseded by S065. — User's choice. — S065
- D-051 — 2026-11-18 — Pop-ups and frames: a site not asked about gets pop-ups only from a click or key press (Chromium's rule); Allow/Block per site as before. Nacre's menu shows only when the page didn't cancel `contextmenu` (the bridge script's answer decides, not WebKit's signal). A script navigation not proven to be a frame's is never rewritten into a load in the tab; the browser reloads it only once the tab itself starts loading it. — WebKit asks for menus on cancelled right clicks after its first menu; ad frames took tabs over through Nacre's rewrites. — S061 — later pop-up, menu or navigation-policy work
- D-052 — 2026-11-18 — Saved passwords without a master password are guarded by the Linux account password of the user running Nacre (checked by the system, so a changed login password works at once), never by a click; with a master password, the master password guards them. Mechanism (PAM service or polkit agent) chosen and recorded by S067. — User: "it should ask for a password from the user like other browsers". — S067
- D-052 — 2026-11-18 — Saved passwords without a master password are guarded by the Linux account password of the user running Nacre (checked by the system, so a changed login password works at once), never by a click; with a master password, the master password guards them. Mechanism (S067): PAM's `login` service in-process for the `getuid` user (as swaylock does: unprivileged, pam_unix's setuid helper, no root, no new /etc file), libpam loaded at run time (`src/auth.rs`), off the main thread; no polkit. pam_faillock counts these tries with every login (deny 3 in 15 min → 10 min lock), so Nacre allows at most 2 wrong tries per faillock window (read from faillock.conf, at least a minute) and says how long to wait. Without libpam the gate says why and offers a master password. Tests use `NACRE_TEST_ACCOUNT_PASSWORD` (only with `NACRE_SCRIPT`). — User: "it should ask for a password from the user like other browsers". — S067

View file

@ -135,10 +135,18 @@ extensions replaced by user scripts and styles, the context menu, the download m
"Open anyway", taken only from the tab showing that warning.
- The user opens them: address bar, menus, buttons, shortcuts, bookmarks, command line (`Command::Open` /
`Navigate` / `ShowPage`).
- `nacre://passwords` asks first every time it is shown (master password, or a "Show passwords" click without one),
even while the vault is unlocked for autofill. When a frame draws without it (another tab, page, the tab closed)
- `nacre://passwords` asks first every time it is shown (master password, or without one the computer password,
D-052), even while the vault is unlocked for autofill. When a frame draws without it (another tab, page, the tab closed)
`PageState::close_passwords` forgets the answer and every field it showed or took. It is saved and restored as a
new tab (`session::kept_url`).
- Computer password (`src/auth.rs`, D-052): PAM `login` service in-process for the `getuid` user, libpam dlopen'd
(`libpam.so.0`), the conversation answers only the hidden prompt and keeps PAM's messages to show. It runs on its
own thread (`auth::check` → `Check::poll` in `passwords::poll_account_check`, repaint when done); the typed text is
wiped (`auth::wipe`) and never kept in `PageState`. `Throttle` allows at most 2 wrong tries per pam_faillock window
(`/etc/security/faillock.conf`, ≥ 60 s), a running try counts as wrong. A right answer sets `vault.last_auth`, so
Reveal, Copy, Edit, Export and the master password card use the same "ask again" window (`needs_reauth`, both
modes, at least 10 s so "0 min" still works). No libpam: the gate shows why and the master password card.
Tests: `NACRE_TEST_ACCOUNT_PASSWORD` (honoured only with `NACRE_SCRIPT`) replaces PAM with a compare.
## Media

View file

@ -549,6 +549,16 @@ Later: S010 list: user checks the Discord icon with their own client (the Discor
- Not done: a real SIGSEGV / memory-limit kill (selftest uses `terminate_web_process`); bar buttons pressed by `cmd`, not a tap; no unit test (state in `App`); no visible run; the user's deadlock not reproduced here.
- Later: muted videos in a session without an audio server hang WebKit in the PipeWire ALSA plugin (test sessions only so far).
## S067 — Passwords ask for your computer password (2026-11-18)
- Done (D-052): without a master password `nacre://passwords` asks for the Linux account password ("Enter your computer password (the one you use to log in)…", field, Unlock / Checking…, error line); the "Show passwords" click is gone. The same check (or the master password) guards Reveal, Copy, Edit of a saved login, Export and the master password card (`authorized` / `may_reveal`, `needs_reauth` now in both modes).
- `src/auth.rs`: PAM `login` service in-process (as swaylock), `getuid` user, libpam dlopen'd, off the main thread, password wiped; no polkit, no root, no /etc file. Faillock: at most 2 wrong tries per faillock window (default 15 min, read from faillock.conf), then "Wait N minutes…"; PAM's own messages (locked account) are shown. No libpam → reason + master password card.
- Env override `NACRE_TEST_ACCOUNT_PASSWORD` (only with `NACRE_SCRIPT`). Selftest `uitext <text>` (new) types into the focused egui field. `nacre-lock.txt` covers wrong → right, ask again after a tab switch.
- Settings label: "Ask for your password again before showing passwords"; "0 min" now trusts the answer 10 s (was: never revealable).
- Verified: `nacre-lock.txt` exit 0 (`target/smoke/s067-lock-3`, shots ask/wrong/open read); grep: no "Show passwords" path; `cargo test` 98 + webext 1 (4 new auth tests).
- Not done: real PAM only by the user's 🧑 check; the throttled "Wait" text and the no-libpam path are unit-tested, not shot; Reveal/Copy/Edit/Export guards not driven in a smoke.
- Later: on "ask again" after a tab switch the field isn't focused (the address bar keeps the keyboard).
- Note: without libpam, setting a master password from the gate is offered as the plan says; whoever sits at the machine can do that (no PAM = nothing to check against).
## Later
- A link followed inside a frame still goes through the tab's navigation policy (WebKit's GTK API has no frame info; S050).
- file:// media outside the XDG user folders doesn't play (WebKit sandbox, D-043).

385
src/auth.rs Normal file
View file

@ -0,0 +1,385 @@
//! The computer (Linux account) password of the user running Nacre, which guards saved passwords without a master
//! password (D-052). PAM's `login` service, in-process and unprivileged as screen lockers do it: pam_unix checks the
//! password through its setuid helper, so a changed login password works at once. libpam is loaded at run time, so
//! a system without it gets a reason instead of a crash.
//!
//! pam_faillock counts these tries with every other login: three wrong ones in 15 minutes lock the account for 10.
//! Nacre never lets a third wrong try happen inside that window (`Throttle`).
//!
//! `NACRE_TEST_ACCOUNT_PASSWORD` (only together with `NACRE_SCRIPT`, the selftest) swaps PAM for a compare, so tests
//! never send a wrong password to the real PAM.
use std::ffi::{CStr, CString, c_char, c_int, c_void};
use std::sync::{Mutex, OnceLock, mpsc};
use crate::util;
#[derive(Clone, Debug, PartialEq)]
pub enum AuthError {
/// The password is not right; PAM's own message, if it gave one (for example a locked account).
Wrong(Option<String>),
/// Another try now could lock the login; seconds to wait.
Wait(u64),
/// The password can't be checked on this system.
Unavailable(String),
}
impl std::fmt::Display for AuthError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AuthError::Wrong(Some(message)) => write!(f, "That password is not right. The system says: {message}"),
AuthError::Wrong(None) => write!(f, "That password is not right. Try again."),
AuthError::Wait(seconds) => write!(f, "Wait {} before trying again: one more wrong password now would lock your computer login for {}.", minutes(*seconds), minutes(faillock().unlock_time)),
AuthError::Unavailable(why) => write!(f, "Nacre can't check your computer password here ({why}). Set a master password to protect your passwords."),
}
}
}
fn minutes(seconds: u64) -> String {
match seconds.div_ceil(60) {
1 => "1 minute".into(),
n => format!("{n} minutes"),
}
}
/// pam_faillock's settings (`/etc/security/faillock.conf`, its defaults when a line is missing).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Faillock {
pub deny: u32,
pub fail_interval: u64,
pub unlock_time: u64,
}
impl Faillock {
pub fn parse(text: &str) -> Faillock {
let mut config = Faillock { deny: 3, fail_interval: 900, unlock_time: 600 };
for line in text.lines() {
let line = line.split('#').next().unwrap_or("");
let Some((key, value)) = line.split_once('=') else { continue };
let Ok(value) = value.trim().parse::<u64>() else { continue };
match key.trim() {
"deny" => config.deny = value as u32,
"fail_interval" => config.fail_interval = value,
"unlock_time" => config.unlock_time = value,
_ => {},
}
}
config
}
}
fn faillock() -> Faillock {
static CONFIG: OnceLock<Faillock> = OnceLock::new();
*CONFIG.get_or_init(|| Faillock::parse(&std::fs::read_to_string("/etc/security/faillock.conf").unwrap_or_default()))
}
/// Wrong tries in the last window. At most two per window (one when faillock denies sooner), and the window is at
/// least a minute, so Nacre alone never locks the login with its default settings. A try counts as wrong until its answer says otherwise.
#[derive(Debug)]
pub struct Throttle {
failures: Vec<u64>,
limit: usize,
window: u64,
}
impl Throttle {
pub fn new(config: Faillock) -> Throttle {
let limit = if config.deny == 0 { 3 } else { config.deny.clamp(2, 3) as usize };
Throttle { failures: Vec::new(), limit, window: config.fail_interval.max(60) }
}
/// Seconds until another try is safe, or None when it is now.
pub fn wait(&mut self, now: u64) -> Option<u64> {
let window = self.window;
self.failures.retain(|t| t + window > now);
(self.failures.len() + 1 >= self.limit).then(|| self.failures.iter().min().map_or(0, |t| t + window - now))
}
pub fn begin(&mut self, now: u64) {
self.failures.push(now);
}
/// The answer of the try begun at `started`: right clears the count (faillock does too), wrong keeps it, a check
/// that couldn't run doesn't count.
pub fn finish(&mut self, started: u64, result: &Result<(), AuthError>) {
match result {
Ok(()) => self.failures.clear(),
Err(AuthError::Wrong(_)) => {},
Err(_) => {
if let Some(i) = self.failures.iter().position(|t| *t == started) {
self.failures.remove(i);
}
},
}
}
}
fn throttle() -> &'static Mutex<Throttle> {
static THROTTLE: OnceLock<Mutex<Throttle>> = OnceLock::new();
THROTTLE.get_or_init(|| Mutex::new(Throttle::new(faillock())))
}
/// A check running on its own thread.
pub struct Check(mpsc::Receiver<Result<(), AuthError>>);
impl Check {
/// The answer, once it is there.
pub fn poll(&self) -> Option<Result<(), AuthError>> {
match self.0.try_recv() {
Ok(result) => Some(result),
Err(mpsc::TryRecvError::Empty) => None,
Err(mpsc::TryRecvError::Disconnected) => Some(Err(AuthError::Unavailable("the check stopped".into()))),
}
}
}
/// Whether the password can be checked at all.
pub fn available() -> Result<(), String> {
if test_password().is_some() {
return Ok(());
}
pam().map(|_| ())
}
/// Check the computer password off the main thread (PAM takes ~2 s on a wrong one); `done` runs when the answer is
/// there (to repaint). The password is wiped from memory after use.
pub fn check(mut password: String, done: impl FnOnce() + Send + 'static) -> Result<Check, AuthError> {
let now = util::now();
{
let mut throttle = throttle().lock().unwrap_or_else(|e| e.into_inner());
if let Some(seconds) = throttle.wait(now) {
wipe(&mut password);
return Err(AuthError::Wait(seconds));
}
throttle.begin(now);
}
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let result = verify_account_password(&password);
wipe(&mut password);
throttle().lock().unwrap_or_else(|e| e.into_inner()).finish(now, &result);
if result.is_err() {
log::info!("auth: computer password check: {}", match &result {
Err(AuthError::Wrong(_)) => "wrong",
_ => "not available",
});
}
let _ = tx.send(result);
done();
});
Ok(Check(rx))
}
/// Overwrite a secret before it is freed.
pub fn wipe(secret: &mut String) {
// SAFETY: only zero bytes are written, which keeps the String valid UTF-8.
for b in unsafe { secret.as_mut_vec() }.iter_mut() {
unsafe { std::ptr::write_volatile(b, 0) };
}
secret.clear();
}
fn test_password() -> Option<String> {
std::env::var_os("NACRE_SCRIPT")?;
std::env::var("NACRE_TEST_ACCOUNT_PASSWORD").ok()
}
/// Check `password` for the user running Nacre (never a typed user name). Blocks: call it off the main thread.
pub fn verify_account_password(password: &str) -> Result<(), AuthError> {
if let Some(expected) = test_password() {
return if expected == password { Ok(()) } else { Err(AuthError::Wrong(None)) };
}
let pam = pam().map_err(AuthError::Unavailable)?;
let user = current_user().ok_or_else(|| AuthError::Unavailable("no user name for this account".into()))?;
let secret = CString::new(password).map_err(|_| AuthError::Wrong(None))?;
let mut talk = Talk { password: secret, messages: Vec::new() };
let conv = PamConv { conv: converse, appdata: &mut talk as *mut Talk as *mut c_void };
let service = c"login";
let mut handle: *mut c_void = std::ptr::null_mut();
// SAFETY: the symbols have libpam's signatures; `talk` and `conv` outlive the handle (ended below).
let result = unsafe {
let started = (pam.start)(service.as_ptr(), user.as_ptr(), &conv, &mut handle);
if started != PAM_SUCCESS {
return Err(AuthError::Unavailable(format!("PAM didn't start: {started}")));
}
let code = (pam.authenticate)(handle, 0);
(pam.end)(handle, code);
code
};
// Overwrite our copy of the password.
let mut bytes = std::mem::replace(&mut talk.password, CString::default()).into_bytes();
for b in bytes.iter_mut() {
unsafe { std::ptr::write_volatile(b, 0) };
}
let message = (!talk.messages.is_empty()).then(|| talk.messages.join(" "));
match result {
PAM_SUCCESS => Ok(()),
PAM_AUTH_ERR | PAM_PERM_DENIED | PAM_MAXTRIES | PAM_CRED_INSUFFICIENT => Err(AuthError::Wrong(message)),
code => Err(AuthError::Unavailable(message.unwrap_or_else(|| format!("PAM error {code}")))),
}
}
fn current_user() -> Option<CString> {
let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
let mut buf = vec![0 as c_char; 4096];
let mut found: *mut libc::passwd = std::ptr::null_mut();
// SAFETY: getpwuid_r writes into `pwd` and `buf`, which live through the copy below.
let code = unsafe { libc::getpwuid_r(libc::getuid(), &mut pwd, buf.as_mut_ptr(), buf.len(), &mut found) };
if code != 0 || found.is_null() {
return None;
}
Some(unsafe { CStr::from_ptr(pwd.pw_name) }.to_owned())
}
// libpam's interface (security/_pam_types.h).
const PAM_SUCCESS: c_int = 0;
const PAM_BUF_ERR: c_int = 5;
const PAM_PERM_DENIED: c_int = 6;
const PAM_AUTH_ERR: c_int = 7;
const PAM_CRED_INSUFFICIENT: c_int = 8;
const PAM_MAXTRIES: c_int = 11;
const PAM_CONV_ERR: c_int = 19;
const PAM_PROMPT_ECHO_OFF: c_int = 1;
const PAM_ERROR_MSG: c_int = 3;
const PAM_TEXT_INFO: c_int = 4;
#[repr(C)]
struct PamMessage {
style: c_int,
text: *const c_char,
}
#[repr(C)]
struct PamResponse {
resp: *mut c_char,
retcode: c_int,
}
type Converse = unsafe extern "C" fn(c_int, *mut *const PamMessage, *mut *mut PamResponse, *mut c_void) -> c_int;
#[repr(C)]
struct PamConv {
conv: Converse,
appdata: *mut c_void,
}
struct Pam {
start: unsafe extern "C" fn(*const c_char, *const c_char, *const PamConv, *mut *mut c_void) -> c_int,
authenticate: unsafe extern "C" fn(*mut c_void, c_int) -> c_int,
end: unsafe extern "C" fn(*mut c_void, c_int) -> c_int,
}
fn pam() -> Result<&'static Pam, String> {
static PAM: OnceLock<Result<(libloading::Library, Pam), String>> = OnceLock::new();
PAM.get_or_init(|| {
// SAFETY: libpam has no load-time side effects; the symbols are read with their C signatures.
unsafe {
let lib = libloading::Library::new("libpam.so.0").map_err(|_| "PAM isn't installed".to_owned())?;
let start = *lib.get(b"pam_start\0").map_err(|e| e.to_string())?;
let authenticate = *lib.get(b"pam_authenticate\0").map_err(|e| e.to_string())?;
let end = *lib.get(b"pam_end\0").map_err(|e| e.to_string())?;
Ok((lib, Pam { start, authenticate, end }))
}
})
.as_ref()
.map(|(_, pam)| pam)
.map_err(Clone::clone)
}
struct Talk {
password: CString,
messages: Vec<String>,
}
/// PAM's conversation: the password for the hidden prompt, other messages kept to show; nothing else is answered.
unsafe extern "C" fn converse(count: c_int, messages: *mut *const PamMessage, responses: *mut *mut PamResponse, appdata: *mut c_void) -> c_int {
if count <= 0 || messages.is_null() || responses.is_null() || appdata.is_null() {
return PAM_CONV_ERR;
}
// SAFETY: PAM passes `count` messages and our `Talk`; the replies are malloc'd because PAM frees them.
unsafe {
let talk = &mut *(appdata as *mut Talk);
let replies = libc::calloc(count as usize, std::mem::size_of::<PamResponse>()) as *mut PamResponse;
if replies.is_null() {
return PAM_BUF_ERR;
}
for i in 0..count as usize {
let message = &**messages.add(i);
match message.style {
PAM_PROMPT_ECHO_OFF => (*replies.add(i)).resp = libc::strdup(talk.password.as_ptr()),
PAM_ERROR_MSG | PAM_TEXT_INFO if !message.text.is_null() => talk.messages.push(CStr::from_ptr(message.text).to_string_lossy().trim().to_owned()),
PAM_ERROR_MSG | PAM_TEXT_INFO => {},
_ => {
for j in 0..i {
let resp = (*replies.add(j)).resp;
if !resp.is_null() {
for k in 0..libc::strlen(resp) {
std::ptr::write_volatile(resp.add(k), 0);
}
libc::free(resp as *mut c_void);
}
}
libc::free(replies as *mut c_void);
return PAM_CONV_ERR;
},
}
}
*responses = replies;
}
PAM_SUCCESS
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn faillock_config() {
assert_eq!(Faillock::parse(""), Faillock { deny: 3, fail_interval: 900, unlock_time: 600 });
let text = "# deny = 9\ndeny = 5\n fail_interval=120 # two minutes\nunlock_time = 0\nsilent\n";
assert_eq!(Faillock::parse(text), Faillock { deny: 5, fail_interval: 120, unlock_time: 0 });
}
#[test]
fn throttle_never_reaches_the_lock() {
let mut t = Throttle::new(Faillock::parse(""));
assert_eq!(t.wait(1000), None);
t.begin(1000);
t.finish(1000, &Err(AuthError::Wrong(None)));
assert_eq!(t.wait(1010), None);
t.begin(1010);
// A try still running counts as wrong.
assert_eq!(t.wait(1020), Some(880));
t.finish(1010, &Err(AuthError::Wrong(None)));
assert_eq!(t.wait(1899), Some(1));
// The oldest try leaves the window.
assert_eq!(t.wait(1900), None);
// Right clears the count; a check that couldn't run doesn't count.
t.begin(1900);
t.finish(1900, &Ok(()));
t.begin(1901);
t.finish(1901, &Err(AuthError::Unavailable("x".into())));
assert_eq!(t.wait(1902), None);
// A strict faillock (deny 1) still allows one try a minute; deny 0 (off) two.
let mut strict = Throttle::new(Faillock { deny: 1, fail_interval: 10, unlock_time: 60 });
assert_eq!(strict.wait(0), None);
strict.begin(0);
assert_eq!(strict.wait(5), Some(55));
let mut off = Throttle::new(Faillock { deny: 0, fail_interval: 900, unlock_time: 600 });
assert_eq!(off.wait(0), None);
}
#[test]
fn error_texts() {
assert_eq!(AuthError::Wrong(None).to_string(), "That password is not right. Try again.");
assert!(AuthError::Wait(61).to_string().starts_with("Wait 2 minutes before trying again"));
assert!(AuthError::Unavailable("PAM isn't installed".into()).to_string().contains("Set a master password"));
}
#[test]
fn wipe_clears() {
let mut s = String::from("hunter2");
wipe(&mut s);
assert!(s.is_empty());
}
}

View file

@ -4,6 +4,7 @@
mod actions;
mod adblock;
mod app;
mod auth;
mod discord;
mod egui_area;
mod engine;

View file

@ -48,6 +48,7 @@
//! `{enter}` / `{escape}` in the text press Enter / Escape
//! pointer <x> <y> | off move the interface's pointer to x,y in the page area (new tab backgrounds follow it)
//! key <name> press and release a key in the interface: enter, escape, tab, space or a letter
//! uitext <text> type text into the interface's focused field (a Nacre page's field, the address bar)
//! realkey <key>… real key presses through the compositor (wtype names: Down, Return, Escape), wherever
//! the window's keyboard is; hidden runs only
//! tap <x> <y> click the interface (not the web page) at x,y in the window (logical px, as in a
@ -732,6 +733,13 @@ impl App {
}
self.redraw(window);
},
"uitext" => {
// Type text into the interface's focused field (egui text input, no key presses).
if let Some(win) = self.windows.get_mut(&window) {
win.area.push(egui::Event::Text(rest.to_owned()));
}
self.redraw(window);
},
"tap" => {
let mut parts = rest.split_whitespace().filter_map(|p| p.parse::<f32>().ok());
if let (Some(x), Some(y), Some(win)) = (parts.next(), parts.next(), self.windows.get_mut(&window)) {

View file

@ -162,7 +162,7 @@ pub struct Vault {
read_only: bool,
/// Last activity, for auto-lock (seconds).
pub last_used: u64,
/// Master mode: when the password was last entered, for "ask again before revealing".
/// When the master (or computer, D-052) password was last entered, for "ask again before revealing".
pub last_auth: u64,
}
@ -277,9 +277,11 @@ impl Vault {
self.last_used = util::now();
}
/// Whether revealing a password needs the master password again.
/// Whether revealing a password needs the password again: the master password, or without one the computer
/// password (D-052).
pub fn needs_reauth(&self, reauth: bool, minutes: u32) -> bool {
reauth && self.meta.mode == Mode::Master && (minutes == 0 || util::now().saturating_sub(self.last_auth) > minutes as u64 * 60)
// 0 = every time: the answer still counts for a few seconds, so what it was given for can happen.
reauth && util::now().saturating_sub(self.last_auth) > (minutes as u64 * 60).max(10)
}
fn save(&mut self) -> Result<(), VaultError> {

View file

@ -54,10 +54,14 @@ pub struct PageState {
pub reauth_error: String,
pub unlock: String,
pub unlock_error: String,
/// The master password (or, without one, a click) was given since the passwords page was last shown (S063).
/// The master password (or, without one, the computer password, D-052) was given since the passwords page was last shown (S063).
pub passwords_open: bool,
/// The passwords page was drawn this frame.
pub passwords_shown: bool,
/// A computer password check running for the passwords page (D-052).
pub account_check: Option<crate::auth::Check>,
/// Export was pressed without a recent password: the password card shows.
pub reauth_ask: bool,
pub generated: String,
pub gen_passphrase: bool,
pub script_edit: Option<(u64, String)>,
@ -77,6 +81,8 @@ impl PageState {
/// time, and nothing it showed or was typed into it stays in memory (S063).
pub fn close_passwords(&mut self, ctx: &egui::Context) {
self.passwords_open = false;
self.account_check = None;
self.reauth_ask = false;
self.passwords_search.clear();
self.revealed.clear();
self.login_edit = None;

View file

@ -10,7 +10,7 @@ use crate::actions::{Command, Disposition};
use crate::store::vault::{self, Address, Card, Login, Mode};
use crate::theme::{self, Weight};
use crate::ui::icons;
use crate::util;
use crate::{auth, util};
const TABS: &[(usize, &str)] = &[(0, "Passwords"), (1, "Addresses"), (2, "Cards"), (3, "Generator"), (4, "Check"), (5, "Master password")];
@ -19,6 +19,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
let subtitle = if f.incognito() { "Incognito windows have their own empty store that is thrown away when they close." } else { "" };
page_header(ui, "Passwords and autofill", subtitle, |_| {});
f.ui.pages.passwords_shown = true;
poll_account_check(f);
// Every time the page opens it asks first, even when the store is unlocked for filling in (S063).
if f.shared.vault.borrow().locked() || !f.ui.pages.passwords_open {
unlock(ui, f);
@ -60,12 +61,34 @@ fn unlock(ui: &mut Ui, f: &mut Frame) {
super::super::widgets::icon(ui, rect.center(), icons::LOCK, theme::ICON_LARGE, true, p.on_secondary_container);
ui.add_space(theme::GAP_L);
ui.label(RichText::new("Your passwords are locked").font(theme::font(theme::TITLE, Weight::Medium)).color(p.on_surface));
// Without a master password there is nothing to ask: a click shows them (no page can click it, D-049).
// Without a master password the computer password guards them (D-052).
if f.shared.vault.borrow().mode() != Mode::Master {
ui.label(RichText::new("Set a master password to keep others from seeing them.").font(theme::font(theme::BODY, Weight::Regular)).color(p.on_surface_variant));
if let Err(why) = auth::available() {
let text = auth::AuthError::Unavailable(why).to_string();
error_line(ui, f, &text);
ui.add_space(theme::GAP_L);
set_master_fields(ui, f);
return;
}
ui.label(RichText::new("Enter your computer password (the one you use to log in) to see your passwords.").font(theme::font(theme::BODY, Weight::Regular)).color(p.on_surface_variant));
ui.add_space(theme::GAP_L);
if button(ui, ButtonKind::Filled, Some(icons::LOCK_OPEN), "Show passwords").clicked() {
f.ui.pages.passwords_open = true;
let r = password_field(ui, &mut f.ui.pages.unlock, "Computer password", 280.0);
// Ready to type into, unless Enter just left it (that is the submit below).
if !r.lost_focus() && ui.memory(|m| m.focused().is_none()) {
r.request_focus();
}
ui.add_space(theme::GAP_M);
let busy = f.ui.pages.account_check.is_some();
let clicked = ui.add_enabled_ui(!busy, |ui| button(ui, ButtonKind::Filled, Some(icons::LOCK_OPEN), if busy { "Checking…" } else { "Unlock" })).inner.clicked();
if (clicked || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)))) && !busy {
let pw = std::mem::take(&mut f.ui.pages.unlock);
start_account_check(ui, f, pw);
r.request_focus();
}
if !f.ui.pages.unlock_error.is_empty() {
ui.add_space(theme::GAP_S);
let text = f.ui.pages.unlock_error.clone();
error_line(ui, f, &text);
}
return;
}
@ -95,6 +118,38 @@ fn unlock(ui: &mut Ui, f: &mut Frame) {
});
}
/// Check the computer password on its own thread; `poll_account_check` takes the answer.
fn start_account_check(ui: &Ui, f: &mut Frame, mut pw: String) {
if pw.is_empty() {
return;
}
let ctx = ui.ctx().clone();
let error = match auth::check(std::mem::take(&mut pw), move || ctx.request_repaint()) {
Ok(check) => {
f.ui.pages.account_check = Some(check);
String::new()
},
Err(e) => e.to_string(),
};
if f.ui.pages.passwords_open { f.ui.pages.reauth_error = error } else { f.ui.pages.unlock_error = error }
}
/// A finished computer password check opens the page (or trusts it again for revealing, D-052).
fn poll_account_check(f: &mut Frame) {
let Some(result) = f.ui.pages.account_check.as_ref().and_then(|c| c.poll()) else { return };
f.ui.pages.account_check = None;
match result {
Ok(()) => {
f.shared.vault.borrow_mut().last_auth = util::now();
f.ui.pages.passwords_open = true;
f.ui.pages.unlock_error.clear();
f.ui.pages.reauth_error.clear();
},
Err(e) if f.ui.pages.passwords_open => f.ui.pages.reauth_error = e.to_string(),
Err(e) => f.ui.pages.unlock_error = e.to_string(),
}
}
/// Copy a secret and wipe it from the clipboard later if it is still there.
fn copy_secret(f: &Frame, secret: &str) {
let seconds = f.shared.settings.borrow().vault.clipboard_clear;
@ -112,21 +167,29 @@ fn copy_secret(f: &Frame, secret: &str) {
f.shared.toast(if seconds > 0 { format!("Copied; cleared from the clipboard in {seconds} s") } else { "Copied".into() });
}
/// Whether passwords may be shown right now; asks for the master password if needed.
/// The password was given recently enough to reveal without asking.
fn authorized(f: &Frame) -> bool {
let s = f.shared.settings.borrow();
!f.shared.vault.borrow().needs_reauth(s.vault.reauth, s.vault.reauth_min)
}
/// Whether passwords may be shown, copied, edited or exported right now; asks for the password if needed.
fn may_reveal(ui: &mut Ui, f: &mut Frame) -> bool {
let (reauth, minutes) = {
let s = f.shared.settings.borrow();
(s.vault.reauth, s.vault.reauth_min)
};
if !f.shared.vault.borrow().needs_reauth(reauth, minutes) {
if authorized(f) {
return true;
}
let master = f.shared.vault.borrow().mode() == Mode::Master;
card(ui, |ui| {
row(ui, "Enter the master password", "To see or copy passwords.", |ui| {
let r = password_field(ui, &mut f.ui.pages.reauth, "Master password", 200.0);
if button(ui, ButtonKind::Filled, None, "Continue").clicked() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) {
let (title, hint) = if master { ("Enter the master password", "Master password") } else { ("Enter your computer password", "Computer password") };
row(ui, title, "To see, copy, edit or export passwords.", |ui| {
let r = password_field(ui, &mut f.ui.pages.reauth, hint, 200.0);
let busy = f.ui.pages.account_check.is_some();
let clicked = ui.add_enabled_ui(!busy, |ui| button(ui, ButtonKind::Filled, None, if busy { "Checking…" } else { "Continue" })).inner.clicked();
if (clicked || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)))) && !busy {
let pw = std::mem::take(&mut f.ui.pages.reauth);
if f.shared.vault.borrow_mut().check_password(&pw) {
if !master {
start_account_check(ui, f, pw);
} else if f.shared.vault.borrow_mut().check_password(&pw) {
f.ui.pages.reauth_error.clear();
} else {
f.ui.pages.reauth_error = "That master password is not right.".into();
@ -176,10 +239,20 @@ fn logins(ui: &mut Ui, f: &mut Frame) {
f.send(Command::ImportPasswords);
}
if button(ui, ButtonKind::Outlined, Some(icons::DOWNLOAD), "Export CSV").clicked() {
f.send(Command::ExportPasswords);
if authorized(f) {
f.send(Command::ExportPasswords);
} else {
f.ui.pages.reauth_ask = true;
}
}
});
if let Some(mut edit) = f.ui.pages.login_edit.clone() {
// Revealing, copying, editing a saved password or exporting asks for the password first (D-052).
let editing = f.ui.pages.login_edit.as_ref().is_some_and(|l| l.id != 0);
let can_reveal = !(editing || f.ui.pages.reauth_ask || !f.ui.pages.revealed.is_empty()) || may_reveal(ui, f);
if can_reveal {
f.ui.pages.reauth_ask = false;
}
if let Some(mut edit) = f.ui.pages.login_edit.clone().filter(|l| l.id == 0 || can_reveal) {
section(ui, if edit.id == 0 { "New password" } else { "Edit password" });
let mut finished = false;
card(ui, |ui| {
@ -232,7 +305,6 @@ fn logins(ui: &mut Ui, f: &mut Frame) {
empty_state(ui, icons::SEARCH, "Nothing matches", &format!("No saved password matches \"{}\".", query.trim()), None);
}
}
let can_reveal = f.ui.pages.revealed.is_empty() || may_reveal(ui, f);
let mut delete = None;
if !list.is_empty() {
section(ui, &format!("{} saved", list.len()));
@ -257,8 +329,7 @@ fn logins(ui: &mut Ui, f: &mut Frame) {
}
});
if icon_button(ui, icons::CONTENT_COPY, "Copy password").clicked() {
let ok = !f.shared.vault.borrow().needs_reauth(f.shared.settings.borrow().vault.reauth, f.shared.settings.borrow().vault.reauth_min);
if ok {
if authorized(f) {
copy_secret(f, &login.password);
} else {
f.ui.pages.revealed.insert(login.id);
@ -482,6 +553,14 @@ fn check(ui: &mut Ui, f: &mut Frame) {
}
fn master(ui: &mut Ui, f: &mut Frame) {
// Setting, changing or removing the master password asks for the password first (D-052).
if may_reveal(ui, f) {
set_master_fields(ui, f);
}
}
/// The master password card; also on the locked page when the computer password can't be checked.
fn set_master_fields(ui: &mut Ui, f: &mut Frame) {
let p = f.palette();
let mode = f.shared.vault.borrow().mode();
let intro = match mode {

View file

@ -930,7 +930,7 @@ fn passwords(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
section(ui, "Security");
card(ui, |ui| {
row(ui, "Lock after", "With a master password: lock after this many idle minutes (0 = never)", |ui| number(ui, &mut s.vault.autolock_min, 0..=1440, " min"));
switch_row(ui, "Ask for the master password before showing passwords", "", &mut s.vault.reauth);
switch_row(ui, "Ask for your password again before showing passwords", "The master password, or without one your computer password", &mut s.vault.reauth);
row(ui, "Then trust this session for", "", |ui| number(ui, &mut s.vault.reauth_min, 0..=240, " min"));
row(ui, "Clear copied passwords from the clipboard after", "0 = never", |ui| number(ui, &mut s.vault.clipboard_clear, 0..=600, " s"));
});

View file

@ -1,7 +1,8 @@
# nacre:// lockdown (S063, D-049): a web page's link, middle click, target=_blank, window.open, script navigation,
# frame, meta refresh and HTTP redirect to nacre://passwords never show one of Nacre's pages; the user's address bar
# does, and the passwords page asks first every time it is shown (here without a master password: its button).
# Offline. Run: python3 tests/smoke/net/server.py & then SMOKE_SIZE=1280x900 tools/smoke.sh tests/smoke/nacre-lock.txt ;
# does, and the passwords page asks first every time it is shown (here without a master password: the computer
# password, D-052, through the selftest's stand-in, never real PAM). Offline. Run: python3 tests/smoke/net/server.py &
# then NACRE_TEST_ACCOUNT_PASSWORD=smoke-account SMOKE_SIZE=1280x900 tools/smoke.sh tests/smoke/nacre-lock.txt ;
# `grep -c "can't open Nacre's pages" <out>/nacre.log` > 0.
wait 3
resize 1280 900
@ -59,7 +60,14 @@ wait 1
expect /active/page "nacre://passwords"
expect /lifecycle/passwords_open false
shot ask
tap 640 400
# A wrong computer password keeps it shut; the right one opens it.
uitext not-it
key enter
wait 1
expect /lifecycle/passwords_open false
shot wrong
uitext smoke-account
key enter
wait 1
expect /lifecycle/passwords_open true
shot open
@ -72,7 +80,11 @@ wait 1
expect /active/page "nacre://passwords"
expect /lifecycle/passwords_open false
shot ask-again
tap 640 400
# The address bar kept the keyboard: click the field first.
tap 640 382
wait 0.5
uitext smoke-account
key enter
wait 1
expect /lifecycle/passwords_open true
# Away to another page in the same tab and back by the address bar: asks again.