headless: refuse shared passphrase files; wipe secret buffers (L5)

This commit is contained in:
raucao committed 2026-11-30 10:31:00 +04:00
1 parent e67963d86b
commit f4487f4425
5 files changed
+116 -15

No files matched your search

+7 -3
View File
@@ -739,7 +739,9 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
- **Unlocking for an unattended run**: `--passphrase-file <path>` (a small
regular file, mode 0400/0600 — never argv or the environment), or a systemd
credential at `$CREDENTIALS_DIRECTORY/regent-passphrase`, which wins when
present. It is read once, wrapped in `Zeroizing`, and never logged. Without it
present. It is opened **once** (`read_passphrase_file`, so no metadata/read
TOCTOU), **refused** if group/other can read it (not merely warned about), read
via `take(4097)` into a `Zeroizing` buffer, and never logged. Without it
a locked vault simply denies the sensitive methods. `--pair` needs no identity
secret and works while locked.
- **In-app pairing** (Apps page → "Connect an app…" or the primary menu): paste the
@@ -883,8 +885,10 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
clipboard again after 60 s **if it still holds that value**.
- **Never log, print or put the passphrase in argv/env.** The passphrase is
`Zeroizing` where it crosses the vault and the headless path, and is dropped as
soon as the unlock lands; the GTK dialog fields hand it over as a plain
`String`, so this is hygiene, not a blanket guarantee. Verified: on drop,
soon as the unlock lands. The GTK dialogs now **clear their entry rows** on
every response and wrap the extracted passphrase / pasted `nsec` in
`Zeroizing` before the async call (L5) — still hygiene, not a blanket
guarantee. Verified: on drop,
`nostr::SecretKey` calls secp256k1's `non_secure_erase()`, a volatile overwrite
— *not* a guarantee (copies can survive in registers or on the stack, and there
is no `ZeroizeOnDrop` contract). Treat in-memory exposure as a real risk.
+79 -10
View File
@@ -283,11 +283,25 @@ fn read_passphrase(file: Option<&str>) -> Result<Option<Zeroizing<String>>, Stri
Some(path) if path.exists() => Some(path),
_ => file.map(PathBuf::from),
};
let Some(path) = path else {
return Ok(None);
};
match path {
Some(path) => Ok(Some(read_passphrase_file(&path)?)),
None => Ok(None),
}
}
let metadata = std::fs::metadata(&path)
/// Read a passphrase from `path`, refusing anything but a small, private
/// (mode 0400/0600) regular file.
///
/// The file is opened **once** and every check is made on that descriptor: a
/// `metadata(path)` followed by `read_to_string(path)` is a TOCTOU window. The
/// buffer is zeroized.
fn read_passphrase_file(path: &std::path::Path) -> Result<Zeroizing<String>, String> {
use std::io::Read;
let file = std::fs::File::open(path)
.map_err(|error| format!("--passphrase-file {}: {error}", path.display()))?;
let metadata = file
.metadata()
.map_err(|error| format!("--passphrase-file {}: {error}", path.display()))?;
if !metadata.is_file() {
return Err(format!(
@@ -305,23 +319,27 @@ fn read_passphrase(file: Option<&str>) -> Result<Option<Zeroizing<String>>, Stri
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
eprintln!(
"regent: warning: {} is readable by other users",
return Err(format!(
"--passphrase-file {}: readable by other users (needs mode 0400 or 0600)",
path.display()
);
));
}
}
let text = std::fs::read_to_string(&path)
let mut bytes = Zeroizing::new(Vec::new());
file.take(4097)
.read_to_end(&mut bytes)
.map_err(|error| format!("--passphrase-file {}: {error}", path.display()))?;
let passphrase = text.trim_end_matches(['\n', '\r']).to_string();
let text = std::str::from_utf8(&bytes)
.map_err(|_| format!("--passphrase-file {}: not valid UTF-8", path.display()))?;
let passphrase = Zeroizing::new(text.trim_end_matches(['\n', '\r']).to_string());
if passphrase.is_empty() {
return Err(format!(
"--passphrase-file {}: the passphrase is empty",
path.display()
));
}
Ok(Some(Zeroizing::new(passphrase)))
Ok(passphrase)
}
async fn wait_for_shutdown() {
@@ -339,3 +357,54 @@ async fn wait_for_shutdown() {
_ = terminate.recv() => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch_path() -> PathBuf {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
std::env::temp_dir().join(format!(
"regent-passphrase-{}-{}",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
))
}
#[cfg(unix)]
fn write_with_mode(path: &std::path::Path, contents: &[u8], mode: u32) {
use std::os::unix::fs::PermissionsExt;
std::fs::write(path, contents).unwrap();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
}
/// A passphrase file that other users can read is refused, not warned about.
#[cfg(unix)]
#[test]
fn a_world_readable_passphrase_file_is_refused() {
let path = scratch_path();
write_with_mode(&path, b"hunter2", 0o644);
let error = read_passphrase_file(&path).expect_err("must refuse");
assert!(error.contains("readable by other users"), "got: {error}");
let _ = std::fs::remove_file(&path);
}
#[cfg(unix)]
#[test]
fn a_private_passphrase_file_is_read_and_trimmed() {
let path = scratch_path();
write_with_mode(&path, b"hunter2\n", 0o600);
assert_eq!(read_passphrase_file(&path).unwrap().as_str(), "hunter2");
let _ = std::fs::remove_file(&path);
}
#[cfg(unix)]
#[test]
fn an_oversized_passphrase_file_is_refused() {
let path = scratch_path();
write_with_mode(&path, &vec![b'a'; 4097], 0o600);
let error = read_passphrase_file(&path).expect_err("must refuse");
assert!(error.contains("too large"), "got: {error}");
let _ = std::fs::remove_file(&path);
}
}
+2 -1
View File
@@ -53,7 +53,8 @@ Options:
--background start with no window, running in the background (used for
autostart); the tray or a second launch brings the window up
--passphrase-file <path>
read the key-vault passphrase from this file (mode 0400/0600)
read the key-vault passphrase from this file (a small regular
file, mode 0400/0600; refused if group/other can read it)
so an unattended run can sign; a systemd credential named
regent-passphrase is used instead when present
--version, -V print the version and exit
+23 -1
View File
@@ -20,6 +20,7 @@ use nostr::prelude::{Keys, PublicKey};
use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use zeroize::Zeroizing;
use crate::runtime;
use crate::state::AppState;
@@ -406,6 +407,15 @@ impl PassphraseFields {
let confirm = self.confirm.as_ref().map(|row| row.text().to_string());
validate_passphrase(&self.passphrase.text(), confirm.as_deref())
}
/// Wipe the typed secrets from the fields; a dialog's fields must not keep a
/// passphrase after it closes.
fn clear(&self) {
self.passphrase.set_text("");
if let Some(confirm) = &self.confirm {
confirm.set_text("");
}
}
}
/// Validate a passphrase/confirmation pair. Pure so it is testable without
@@ -469,6 +479,8 @@ fn present_create(handles: Handles, state: Rc<AppState>) {
Ok(passphrase) => passphrase,
Err(error) => return report_error(&handles, &error),
};
fields.clear();
let passphrase = Zeroizing::new(passphrase);
let name = name.text().trim().to_string();
let after = Rc::clone(&state);
let handles = handles.clone();
@@ -556,7 +568,15 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
Err(error) => return report_error(&handles, &error),
};
let text = entry.text().to_string();
let import_password = import_password.text().to_string();
let import_password_text = import_password.text().to_string();
// Wipe what was read from the widgets: a pasted `nsec` and the
// passphrases must not linger.
fields.clear();
entry.set_text("");
import_password.set_text("");
let text = Zeroizing::new(text);
let import_password = Zeroizing::new(import_password_text);
let passphrase = Zeroizing::new(passphrase);
// Empty means "no label": the discovered profile name is what the app
// shows, and a label is only for keys with no profile.
let label = name.text().trim().to_string();
@@ -684,6 +704,8 @@ fn present_export_dialog(handles: Handles, state: Rc<AppState>, public_key: Publ
Ok(password) => password,
Err(error) => return report_error(&handles, &error),
};
fields.clear();
let password = Zeroizing::new(password);
let store = state.store();
let (password, handles, window) =
(password, handles.clone(), window.clone());
+5
View File
@@ -23,6 +23,7 @@ use crate::runner::{SignerRunner, Status};
use crate::runtime;
use crate::state::AppState;
use crate::ui::plain;
use zeroize::Zeroizing;
/// The auto-lock choices: the timeout in seconds, and what to call it. `0` means
/// never lock, which is the user's call to make — but not the default.
@@ -523,6 +524,10 @@ impl Preferences {
if confirm.text().to_string() != passphrase {
return preferences.error("The two passphrases do not match.");
}
// Wipe the fields; the new passphrase must not linger in a widget.
new.set_text("");
confirm.set_text("");
let passphrase = Zeroizing::new(passphrase);
let store = preferences.state.store();
let preferences = Rc::clone(&preferences);
runtime::spawn(