S025: cookies encrypted at rest with a key in the OS keyring (R1-19)

servo-net hands its public cookie jar to Nacre instead of writing plain
cookie_jar.json; store::cookies seals it in cookies.bin (XChaCha20-Poly1305)
with a keyring-held key, saves on change and at exit, migrates the old plain
jar. No keyring: cookies for the run only, Settings says so (D-019).
Smokes with a throwaway GNOME Keyring (SMOKE_KEYRING=1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-12 19:30:09 -06:00
commit a5982a7c1b
6 changed files with 1109 additions and 46 deletions

View file

@ -383,6 +383,8 @@ impl App {
prefs.shell_background_color_rgba = if dark { [0.1, 0.1, 0.1, 1.0] } else { [1.0, 1.0, 1.0, 1.0] };
let opts = Opts { config_dir: Some(self.shared.paths.engine()), temporary_storage: self.shared.incognito, multiprocess: false, ..Opts::default() };
let _ = std::fs::create_dir_all(self.shared.paths.engine());
// Cookies are kept encrypted by Nacre, not in Servo's plain cookie_jar.json (R1-19).
crate::store::cookies::start(&self.shared.paths.data, &self.shared.paths.engine(), self.shared.incognito);
let servo = ServoBuilder::default().opts(opts).preferences(prefs).event_loop_waker(Box::new(Waker(self.proxy.clone()))).build();
servo.set_delegate(self.hub.clone());
servo.setup_logging();

View file

@ -767,6 +767,7 @@ impl App {
serde_json::json!({
"windows": self.windows.len(),
"tab_count": tabs.len(),
"cookies": crate::store::cookies::keeping().map(|k| format!("{k:?}")),
"active_index": self.windows.get(&window).map(|w| w.active),
"fullscreen": self.windows.get(&window).map(|w| w.fullscreen),
"frames": frames,

271
src/store/cookies.rs Normal file
View file

@ -0,0 +1,271 @@
//! Cookies encrypted at rest (R1-19).
//!
//! Servo 0.7 keeps its cookie jar as plain JSON (`engine/cookie_jar.json`), which an infostealer copying the profile
//! can replay to take over signed-in sessions. The vendored servo-net hands the jar to Nacre instead
//! (`net::nacre::set_cookie_persistence`); Nacre keeps it in `cookies.bin`, sealed like the vault
//! (XChaCha20-Poly1305) with a 256-bit key held in the OS keyring: Secret Service (GNOME Keyring, KWallet) on Linux,
//! Credential Manager on Windows. The file alone is useless without the user's unlocked keyring.
//!
//! - Loaded before Servo starts; saved every few seconds when the jar changed, and when Servo exits.
//! - A plain cookie_jar.json from older builds is read once and deleted after the first encrypted save reads back.
//! - No keyring: cookies stay in memory for this run only (nothing plain is written); Settings says so.
//! - A file that doesn't decrypt (key gone, keyring reset) is moved to `cookies-unreadable-<time>.bin`, never
//! deleted; it opens again if the old key comes back into the keyring.
//! - Incognito: nothing is read or written.
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as B64;
use crate::store::vault::{seal, unseal};
use crate::util;
pub const FILE: &str = "cookies.bin";
/// The plain jar Servo writes into its config dir.
pub const PLAIN_FILE: &str = "cookie_jar.json";
const MAGIC: &[u8] = b"NACRECK1";
const AAD: &[u8] = b"nacre-cookies-v1";
const KEYRING_SERVICE: &str = "Nacre";
const SAVE_EVERY: Duration = Duration::from_secs(5);
static KEEPING: OnceLock<Keeping> = OnceLock::new();
/// How this run keeps cookies between restarts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Keeping {
Encrypted,
NoKeyring,
Incognito,
}
impl Keeping {
pub fn describe(self) -> &'static str {
match self {
Keeping::Encrypted => "Encrypted on disk with a key in your system keyring",
Keeping::NoKeyring => "No system keyring found: cookies are kept until Nacre closes, never written unencrypted",
Keeping::Incognito => "Incognito: cookies are never written to disk",
}
}
}
/// How cookies are kept in this run (`None` before the engine started).
pub fn keeping() -> Option<Keeping> {
KEEPING.get().copied()
}
pub fn encrypt(key: &[u8; 32], json: &[u8]) -> Vec<u8> {
let mut out = MAGIC.to_vec();
out.extend(seal(key, AAD, json));
out
}
pub fn decrypt(key: &[u8; 32], bytes: &[u8]) -> Option<Vec<u8>> {
unseal(key, AAD, bytes.strip_prefix(MAGIC)?)
}
fn digest(json: &[u8]) -> u64 {
let mut hasher = DefaultHasher::new();
json.hash(&mut hasher);
hasher.finish()
}
#[derive(Default)]
struct SaveState {
/// Digest of the jar last written, to skip unchanged saves.
last: Option<u64>,
/// A plain jar still waiting to be deleted once the encrypted copy is safe.
plain: Option<PathBuf>,
/// Servo has exited and the final jar is written: later saves would be older.
closed: bool,
}
pub struct CookieStore {
path: PathBuf,
key: [u8; 32],
state: Mutex<SaveState>,
}
impl CookieStore {
/// Opens `dir/cookies.bin` and returns the jar to start with: the decrypted file, or else the plain jar at
/// `plain` (migration). A file that doesn't decrypt is moved aside.
pub fn open(dir: &Path, plain: &Path, key: [u8; 32]) -> (CookieStore, Option<Vec<u8>>) {
let path = dir.join(FILE);
let mut initial = None;
match std::fs::read(&path) {
Ok(bytes) => match decrypt(&key, &bytes) {
Some(json) => initial = Some(json),
None => {
let aside = dir.join(format!("cookies-unreadable-{}.bin", util::now()));
log::warn!("cookies: {} doesn't decrypt with the keyring key; moved to {}", path.display(), aside.display());
if let Err(e) = std::fs::rename(&path, &aside) {
log::warn!("cookies: could not move it aside: {e}");
}
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => log::warn!("cookies: can't read {}: {e}", path.display()),
}
let plain = plain.exists().then(|| plain.to_path_buf());
if let (None, Some(plain)) = (&initial, &plain) {
log::info!("cookies: moving the plain cookie jar into the encrypted store");
initial = std::fs::read(plain).ok();
}
let state = SaveState { plain, ..SaveState::default() };
(CookieStore { path, key, state: Mutex::new(state) }, initial)
}
/// Writes the jar if it changed. True when written.
pub fn save(&self, json: &[u8]) -> bool {
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
let digest = digest(json);
if state.closed || state.last == Some(digest) {
return false;
}
if let Err(e) = util::write_atomic(&self.path, &encrypt(&self.key, json), true) {
log::warn!("cookies: not saved: {e}");
return false;
}
state.last = Some(digest);
if let Some(plain) = state.plain.take() {
let reads_back = std::fs::read(&self.path).ok().and_then(|b| decrypt(&self.key, &b)).is_some_and(|b| b == json);
if reads_back && std::fs::remove_file(&plain).is_ok() {
log::info!("cookies: plain cookie jar deleted");
} else {
state.plain = Some(plain);
}
}
true
}
/// The last save (Servo's exit): nothing after it may overwrite the file.
pub fn close(&self) {
self.state.lock().unwrap_or_else(|e| e.into_inner()).closed = true;
}
fn closed(&self) -> bool {
self.state.lock().unwrap_or_else(|e| e.into_inner()).closed
}
}
/// The cookie key from the OS keyring, made on first use. `None` when there is no usable keyring.
fn keyring_key(account: &str) -> Option<[u8; 32]> {
let entry = keyring::Entry::new(KEYRING_SERVICE, account).map_err(|e| log::warn!("cookies: no keyring: {e}")).ok()?;
let text = match entry.get_password() {
Ok(text) => text,
Err(keyring::Error::NoEntry) => {
let mut key = [0u8; 32];
util::random_bytes(&mut key);
let text = B64.encode(key);
if let Err(e) = entry.set_password(&text) {
log::warn!("cookies: keyring refused the key: {e}");
return None;
}
log::info!("cookies: new key stored in the keyring");
// Read it back: a keyring that drops what it is given would lose every cookie at the next start.
entry.get_password().ok().filter(|t| *t == text)?
}
Err(e) => {
log::warn!("cookies: keyring unavailable: {e}");
return None;
}
};
B64.decode(text.trim()).ok()?.try_into().ok()
}
/// Wires Servo's cookie jar to Nacre before Servo starts (see the module docs). `data` is the profile's data folder,
/// `engine` Servo's config dir (where the plain jar may be).
pub fn start(data: &Path, engine: &Path, incognito: bool) -> Keeping {
let keeping = if incognito {
net::nacre::set_cookie_persistence(None, Box::new(|_| {}));
Keeping::Incognito
} else if let Some(key) = keyring_key(&format!("cookies {}", data.display())) {
let (store, initial) = CookieStore::open(data, &engine.join(PLAIN_FILE), key);
let store = Arc::new(store);
let at_exit = store.clone();
net::nacre::set_cookie_persistence(
initial,
Box::new(move |json| {
at_exit.save(json);
at_exit.close();
}),
);
let _ = std::thread::Builder::new().name("cookie-saver".into()).spawn(move || {
while !store.closed() {
std::thread::sleep(SAVE_EVERY);
if let Some(json) = net::nacre::cookie_jar_snapshot() {
store.save(&json);
}
}
});
Keeping::Encrypted
} else {
// Use the old plain jar for this run, but write nothing.
net::nacre::set_cookie_persistence(std::fs::read(engine.join(PLAIN_FILE)).ok(), Box::new(|_| {}));
Keeping::NoKeyring
};
let _ = KEEPING.set(keeping);
log::info!("cookies: {keeping:?}");
keeping
}
#[cfg(test)]
mod tests {
use super::*;
const JAR: &[u8] = br#"{"version":1,"cookies_map":{"example.com":[]},"max_per_host":150}"#;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("nacre-cookies-{name}-{}", util::random_hex(6)));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn round_trip() {
let dir = temp_dir("round");
let key = [7u8; 32];
let (store, initial) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), key);
assert!(initial.is_none());
assert!(store.save(JAR));
assert!(!store.save(JAR), "unchanged jar is not written again");
let bytes = std::fs::read(dir.join(FILE)).unwrap();
assert!(!bytes.windows(11).any(|w| w == b"example.com"), "no plain text on disk");
assert!(decrypt(&[8u8; 32], &bytes).is_none(), "unreadable without the key");
let (_, initial) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), key);
assert_eq!(initial.as_deref(), Some(JAR));
store.close();
assert!(!store.save(b"{}"), "nothing after the exit save");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn migrates_plain_jar() {
let dir = temp_dir("migrate");
let plain = dir.join(PLAIN_FILE);
std::fs::write(&plain, JAR).unwrap();
let (store, initial) = CookieStore::open(&dir, &plain, [1u8; 32]);
assert_eq!(initial.as_deref(), Some(JAR));
assert!(plain.exists(), "plain jar kept until the encrypted copy is saved");
assert!(store.save(JAR));
assert!(!plain.exists());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn wrong_key_moves_file_aside() {
let dir = temp_dir("aside");
let (store, _) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), [1u8; 32]);
store.save(JAR);
let (_, initial) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), [2u8; 32]);
assert!(initial.is_none());
assert!(!dir.join(FILE).exists());
let aside: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.file_name().to_string_lossy().starts_with("cookies-unreadable-")).collect();
assert_eq!(aside.len(), 1, "the unreadable file is kept");
let _ = std::fs::remove_dir_all(dir);
}
}

View file

@ -2,6 +2,7 @@
pub mod apps;
pub mod bookmarks;
pub mod cookies;
pub mod downloads;
pub mod history;
pub mod permissions;

View file

@ -123,22 +123,24 @@ impl std::fmt::Display for VaultError {
}
}
fn seal(key: &[u8; 32], plain: &[u8]) -> Vec<u8> {
/// XChaCha20-Poly1305 with a fresh random nonce: nonce || ciphertext. `aad` names what is sealed. Also used by the
/// cookie store.
pub(crate) fn seal(key: &[u8; 32], aad: &[u8], plain: &[u8]) -> Vec<u8> {
let cipher = XChaCha20Poly1305::new(chacha20poly1305::Key::from_slice(key));
let mut nonce = [0u8; 24];
util::random_bytes(&mut nonce);
let sealed = cipher.encrypt(XNonce::from_slice(&nonce), Payload { msg: plain, aad: AAD }).expect("encryption with a valid key cannot fail");
let sealed = cipher.encrypt(XNonce::from_slice(&nonce), Payload { msg: plain, aad }).expect("encryption with a valid key cannot fail");
let mut out = nonce.to_vec();
out.extend(sealed);
out
}
fn unseal(key: &[u8; 32], blob: &[u8]) -> Option<Vec<u8>> {
pub(crate) fn unseal(key: &[u8; 32], aad: &[u8], blob: &[u8]) -> Option<Vec<u8>> {
if blob.len() < 24 + 16 {
return None;
}
let cipher = XChaCha20Poly1305::new(chacha20poly1305::Key::from_slice(key));
cipher.decrypt(XNonce::from_slice(&blob[..24]), Payload { msg: &blob[24..], aad: AAD }).ok()
cipher.decrypt(XNonce::from_slice(&blob[..24]), Payload { msg: &blob[24..], aad }).ok()
}
fn password_key(password: &str, salt: &[u8]) -> [u8; 32] {
@ -211,7 +213,7 @@ impl Vault {
self.contents = Contents::default();
} else {
let blob = B64.decode(&self.meta.data).map_err(|e| VaultError::Damaged(e.to_string()))?;
let plain = unseal(&key, &blob).ok_or(VaultError::WrongPassword)?;
let plain = unseal(&key, AAD, &blob).ok_or(VaultError::WrongPassword)?;
self.contents = serde_json::from_slice(&plain).map_err(|e| VaultError::Damaged(e.to_string()))?;
}
self.key = Some(key);
@ -235,7 +237,7 @@ impl Vault {
let salt = B64.decode(&self.meta.salt).map_err(|e| VaultError::Damaged(e.to_string()))?;
let wrapped = B64.decode(&self.meta.wrapped).map_err(|e| VaultError::Damaged(e.to_string()))?;
let kek = password_key(password, &salt);
let key_bytes = unseal(&kek, &wrapped).ok_or(VaultError::WrongPassword)?;
let key_bytes = unseal(&kek, AAD, &wrapped).ok_or(VaultError::WrongPassword)?;
let key = <[u8; 32]>::try_from(key_bytes.as_slice()).map_err(|_| VaultError::Damaged("bad key".into()))?;
self.unlock_with(key)?;
self.last_auth = util::now();
@ -249,7 +251,7 @@ impl Vault {
}
let Ok(salt) = B64.decode(&self.meta.salt) else { return false };
let Ok(wrapped) = B64.decode(&self.meta.wrapped) else { return false };
let ok = unseal(&password_key(password, &salt), &wrapped).is_some();
let ok = unseal(&password_key(password, &salt), AAD, &wrapped).is_some();
if ok {
self.last_auth = util::now();
}
@ -286,7 +288,7 @@ impl Vault {
return Ok(());
}
let plain = serde_json::to_vec(&self.contents).map_err(|e| VaultError::Io(e.to_string()))?;
self.meta.data = B64.encode(seal(&key, &plain));
self.meta.data = B64.encode(seal(&key, AAD, &plain));
util::save_json_private(&self.path, &self.meta).map_err(|e| VaultError::Io(e.to_string()))
}
@ -297,7 +299,7 @@ impl Vault {
util::random_bytes(&mut salt);
let kek = password_key(password, &salt);
self.meta.salt = B64.encode(salt);
self.meta.wrapped = B64.encode(seal(&kek, &key));
self.meta.wrapped = B64.encode(seal(&kek, AAD, &key));
self.meta.mode = Mode::Master;
self.save()?;
if !self.read_only {

View file

@ -775,6 +775,9 @@ fn privacy(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
if icon_row(ui, icons::DELETE, "Delete browsing data", "History, cookies, cache and more", |ui| button(ui, ButtonKind::Tonal, None, "Delete…").clicked()) {
f.send(Command::ShowPage(Page::ClearData));
}
if let Some(keeping) = crate::store::cookies::keeping() {
icon_row(ui, icons::COOKIE, "Cookies on disk", keeping.describe(), |_| {});
}
wide_row(ui, "Delete when Nacre closes", "", |ui| {
toggle_chips(ui, &mut s.privacy.clear_on_exit, &[("history", "History"), ("cookies", "Cookies"), ("cache", "Cache"), ("downloads", "Downloads list")]);
});