Encrypt Yaak Proxy's databases at rest with SQLCipher (#823)

This commit is contained in:
Gregory Schier authored and GitHub committed 2026-11-06 21:07:38 -07:00
1 parent cc382b9226
commit 91696c2d1f
42 files changed
+3366 -286

No files matched your search

+9
View File
@@ -17,7 +17,16 @@ serde_json = { workspace = true }
thiserror = { workspace = true }
ts-rs = { workspace = true }
[features]
# Whole-database encryption: links SQLCipher in place of SQLite, with OpenSSL built in.
sqlcipher = ["rusqlite/bundled-sqlcipher-vendored-openssl", "dep:openssl-sys"]
[dev-dependencies]
tempfile = "3"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# The OpenSSL SQLCipher links, initialized without its exit-time cleanup.
openssl-sys = { version = "0.9", optional = true }
r2d2 = "0.8.10"
r2d2_sqlite = { version = "0.32" }
@@ -0,0 +1,490 @@
//! Whole-database encryption with SQLCipher: the key a connection is opened with, and the
//! one-time conversion of a plain database into an encrypted one.
//!
//! An encrypted file is SQLite inside, so every query, index and full-text table works as on a
//! plain one; pages are encrypted as they are written and decrypted as they are read. Built only
//! with the `sqlcipher` feature, which links SQLCipher in place of SQLite: a build without it
//! cannot open an encrypted file, and one with it opens plain files without a key as before.
use crate::error::{Error, Result};
use rusqlite::Connection;
use std::fmt;
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
/// A database's 256-bit key, given to SQLCipher raw: no passphrase, so no key derivation runs
/// as each connection opens. The file's salt stays in its first 16 bytes, as SQLCipher keeps it.
#[derive(Clone)]
pub struct DatabaseKey([u8; 32]);
impl DatabaseKey {
pub fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
/// The key as `PRAGMA key` and `ATTACH … KEY` take it raw: `"x'…'"`.
fn sql_literal(&self) -> String {
let hex: String = self.0.iter().map(|b| format!("{b:02X}")).collect();
format!("\"x'{hex}'\"")
}
}
/// Never prints the key.
impl fmt::Debug for DatabaseKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("DatabaseKey(..)")
}
}
/// What is at a database's path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileState {
/// Nothing, or an empty file: one opened with a key starts out encrypted.
Missing,
/// A plain SQLite database, which [`encrypt_in_place`] converts.
Plain,
/// Anything else, which only the right key opens.
Encrypted,
}
const PLAIN_HEADER: &[u8; 16] = b"SQLite format 3\0";
/// Whether `path` holds a plain database, an encrypted one, or none. Reads the first 16 bytes:
/// a plain file starts with SQLite's header, an encrypted one with its random salt.
pub fn file_state(path: &Path) -> io::Result<FileState> {
let mut file = match fs::File::open(path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(FileState::Missing),
Err(e) => return Err(e),
};
let mut header = [0u8; 16];
let mut read = 0;
while read < header.len() {
match file.read(&mut header[read..])? {
0 => break,
n => read += n,
}
}
Ok(match read {
0 => FileState::Missing,
_ if &header == PLAIN_HEADER => FileState::Plain,
_ => FileState::Encrypted,
})
}
/// Keys `conn`, which must have just been opened and not yet read: every pool's connection
/// init calls this first. Reads the schema at once, so a wrong key, or a plain file, fails here
/// ("file is not a database") rather than at the first query.
pub fn apply_key(conn: &Connection, key: &DatabaseKey) -> rusqlite::Result<()> {
init_crypto();
conn.execute_batch(&format!("PRAGMA key = {};", key.sql_literal()))?;
conn.query_row("SELECT count(*) FROM sqlite_master", [], |_| Ok(()))
}
/// Initializes OpenSSL without the cleanup it otherwise registers to run at exit, which frees
/// its state while threads still reading or writing an encrypted database use it, so the process
/// crashes as it quits. Must run before the process opens its first SQLite connection: SQLCipher
/// uses OpenSSL as SQLite initializes, and a cleanup registered then cannot be taken back. Every
/// opener here calls it; one that opens a connection itself first calls it too.
pub fn init_crypto() {
openssl_sys::init();
}
/// The bytes a plain database at `path` takes, with its WAL: what [`encrypt_in_place`] has to
/// write, for showing its progress.
pub fn plain_size(path: &Path) -> u64 {
[path.to_path_buf(), sidecar(path, "-wal")]
.iter()
.filter_map(|p| fs::metadata(p).ok())
.map(|m| m.len())
.sum()
}
/// Converts a plain database at `path` into one encrypted with `key`, WAL and all, and returns
/// whether there was one to convert. Exports into a new file beside it, checks the new file
/// opens with `key` and holds every table, swaps it in, then overwrites the plain file, its WAL
/// and shared memory with zeros before deleting them. `progress` hears the bytes written so
/// far, a few times a second.
///
/// Nothing may have the database open meanwhile. A lock beside it serializes callers across
/// processes; the second finds it converted. An interrupted conversion is finished, or undone
/// and redone, by the next call.
pub fn encrypt_in_place(
path: &Path,
key: &DatabaseKey,
progress: &(dyn Fn(u64) + Sync),
) -> Result<bool> {
init_crypto();
let exported = sidecar(path, "-encrypting");
let replaced = sidecar(path, "-plain");
// Nothing to convert and nothing left over, the usual case, takes no lock.
if file_state(path)? != FileState::Plain && !exported.exists() && !replaced.exists() {
return Ok(false);
}
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(sidecar(path, "-encrypt.lock"))?;
lock.lock()?;
recover(path, &exported, &replaced)?;
if file_state(path)? != FileState::Plain {
return Ok(false);
}
let conn = Connection::open(path)?;
conn.busy_timeout(Duration::from_secs(5))?;
keep_wal_on_close(&conn)?;
// Brings in what the WAL holds, so the export is complete however the last run ended.
conn.query_row("PRAGMA wal_checkpoint(FULL)", [], |_| Ok(()))?;
let original = fingerprint(&conn)?;
let user_version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
let exporting = || -> rusqlite::Result<()> {
conn.execute(
&format!("ATTACH DATABASE ?1 AS encrypted KEY {}", key.sql_literal()),
[exported.to_string_lossy()],
)?;
conn.query_row("SELECT sqlcipher_export('encrypted')", [], |_| Ok(()))?;
conn.execute_batch(&format!(
"PRAGMA encrypted.user_version = {user_version}; DETACH DATABASE encrypted;"
))
};
let done = std::sync::atomic::AtomicBool::new(false);
let exported_result = std::thread::scope(|s| {
s.spawn(|| {
while !done.load(std::sync::atomic::Ordering::Relaxed) {
progress(fs::metadata(&exported).map(|m| m.len()).unwrap_or(0));
std::thread::sleep(Duration::from_millis(200));
}
});
let result = exporting();
done.store(true, std::sync::atomic::Ordering::Relaxed);
result
});
if let Err(e) = exported_result {
drop(conn);
let _ = fs::remove_file(&exported);
return Err(e.into());
}
// Closing checkpoints what is left; the WAL stays, to be overwritten below.
drop(conn);
// Writable, as Windows flushes only a handle that can write.
fs::OpenOptions::new().write(true).open(&exported)?.sync_all()?;
progress(fs::metadata(&exported)?.len());
// The copy must open with the key and hold everything, every row under its own rowid,
// before the original goes.
let check = Connection::open(&exported)?;
apply_key(&check, key)?;
let copied = fingerprint(&check)?;
drop(check);
if copied != original {
let _ = fs::remove_file(&exported);
return Err(Error::Database(format!(
"The encrypted copy of {} differs from it, so it is left as it was",
path.display()
)));
}
for suffix in ["-wal", "-shm", "-journal"] {
wipe(&sidecar(path, suffix))?;
}
fs::rename(path, &replaced)?;
fs::rename(&exported, path)?;
sync_dir(path);
wipe(&replaced)?;
// Another caller waiting on the lock holds its own handle, so this only tidies.
let _ = fs::remove_file(sidecar(path, "-encrypt.lock"));
Ok(true)
}
/// Finishes or undoes a conversion that stopped part way: the copy swapped in when the plain
/// file had already moved aside, the plain file put back when there was no copy to swap in,
/// and a half-written copy deleted.
fn recover(path: &Path, exported: &Path, replaced: &Path) -> Result<()> {
if replaced.exists() {
if !path.exists() {
if file_state(exported)? == FileState::Encrypted {
fs::rename(exported, path)?;
} else {
fs::rename(replaced, path)?;
}
}
if replaced.exists() {
wipe(replaced)?;
}
}
if exported.exists() {
fs::remove_file(exported)?;
}
Ok(())
}
/// What a copy must match: every table and index by name, and each table's row count and the
/// total of its rowids, so rows renumbered in the copy show. `sqlcipher_export` keeps rowids by
/// copying each table whole, which SQLite does for an empty table of the same schema.
fn fingerprint(conn: &Connection) -> rusqlite::Result<Vec<(String, i64, f64)>> {
let names: Vec<(String, String)> = conn
.prepare(
"SELECT type, name FROM sqlite_master WHERE type IN ('table', 'index') ORDER BY 1, 2",
)?
.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<rusqlite::Result<_>>()?;
names
.into_iter()
.map(|(kind, name)| {
if kind != "table" {
return Ok((format!("{kind} {name}"), 0, 0.0));
}
let table = format!("\"{}\"", name.replace('"', "\"\""));
let count = |sql: String| conn.query_row(&sql, [], |r| Ok((r.get(0)?, r.get(1)?)));
// A table without rowids, or a virtual one that has none, by its rows alone.
let (rows, rowids) = count(format!("SELECT count(*), total(rowid) FROM {table}"))
.or_else(|_| count(format!("SELECT count(*), 0.0 FROM {table}")))?;
Ok((format!("{kind} {name}"), rows, rowids))
})
.collect()
}
/// Keeps the WAL file when `conn` closes, rather than SQLite deleting it unread, so it can be
/// overwritten before it goes.
fn keep_wal_on_close(conn: &Connection) -> Result<()> {
let mut on: std::ffi::c_int = 1;
// SAFETY: `conn` is open for the call, "main" is a NUL-terminated schema name, and
// SQLITE_FCNTL_PERSIST_WAL takes a pointer to an int it reads and may write.
let rc = unsafe {
rusqlite::ffi::sqlite3_file_control(
conn.handle(),
c"main".as_ptr(),
rusqlite::ffi::SQLITE_FCNTL_PERSIST_WAL,
(&mut on as *mut std::ffi::c_int).cast(),
)
};
if rc != rusqlite::ffi::SQLITE_OK {
return Err(Error::Database(format!("Failed to keep the WAL on close: {rc}")));
}
Ok(())
}
/// Overwrites the file at `path` with zeros, flushed, then deletes it. Nothing there is fine.
fn wipe(path: &Path) -> Result<()> {
let mut file = match fs::OpenOptions::new().write(true).open(path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e.into()),
};
let len = file.metadata()?.len();
let zeros = vec![0u8; 1 << 20];
let mut left = len;
while left > 0 {
let n = left.min(zeros.len() as u64) as usize;
file.write_all(&zeros[..n])?;
left -= n as u64;
}
file.sync_all()?;
drop(file);
fs::remove_file(path)?;
Ok(())
}
/// Flushes the directory holding `path`, so its renames survive a crash. Only Unix can.
fn sync_dir(path: &Path) {
#[cfg(unix)]
if let Some(dir) = path.parent()
&& let Ok(dir) = fs::File::open(dir)
{
let _ = dir.sync_all();
}
#[cfg(not(unix))]
let _ = path;
}
/// `path` with `suffix` added, as SQLite names a database's WAL `<path>-wal`.
fn sidecar(path: &Path, suffix: &str) -> PathBuf {
let mut name = path.as_os_str().to_os_string();
name.push(suffix);
PathBuf::from(name)
}
#[cfg(test)]
mod tests {
use super::*;
fn key(n: u8) -> DatabaseKey {
DatabaseKey::from_bytes([n; 32])
}
fn contains(path: &Path, needle: &[u8]) -> bool {
fs::read(path).map(|b| b.windows(needle.len()).any(|w| w == needle)).unwrap_or(false)
}
#[test]
fn opens_only_with_its_key() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("db.sqlite");
let conn = Connection::open(&path).unwrap();
apply_key(&conn, &key(1)).unwrap();
conn.execute_batch("CREATE TABLE t (v TEXT); INSERT INTO t VALUES ('Bearer secret');")
.unwrap();
drop(conn);
assert_eq!(file_state(&path).unwrap(), FileState::Encrypted);
assert!(!contains(&path, b"Bearer secret"));
let wrong = Connection::open(&path).unwrap();
let err = apply_key(&wrong, &key(2)).unwrap_err();
assert!(err.to_string().contains("file is not a database"), "{err}");
let none = Connection::open(&path).unwrap();
assert!(none.query_row("SELECT count(*) FROM t", [], |r| r.get::<_, i64>(0)).is_err());
let right = Connection::open(&path).unwrap();
apply_key(&right, &key(1)).unwrap();
let v: String = right.query_row("SELECT v FROM t", [], |r| r.get(0)).unwrap();
assert_eq!(v, "Bearer secret");
assert_eq!(format!("{:?}", key(1)), "DatabaseKey(..)");
}
#[test]
fn a_plain_file_does_not_open_with_a_key() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("db.sqlite");
assert_eq!(file_state(&path).unwrap(), FileState::Missing);
Connection::open(&path).unwrap().execute_batch("CREATE TABLE t (v TEXT)").unwrap();
assert_eq!(file_state(&path).unwrap(), FileState::Plain);
assert!(apply_key(&Connection::open(&path).unwrap(), &key(1)).is_err());
}
#[test]
fn converts_a_plain_database_with_its_wal() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("db.sqlite");
let live = dir.path().join("live.sqlite");
let conn = Connection::open(&live).unwrap();
conn.pragma_update(None, "journal_mode", "WAL").unwrap();
conn.execute_batch(
"PRAGMA user_version = 7;
CREATE TABLE t (v TEXT); CREATE INDEX t_v ON t (v);
INSERT INTO t VALUES ('in the main file');",
)
.unwrap();
conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())).unwrap();
// Left in the WAL, as a crash would leave it.
keep_wal_on_close(&conn).unwrap();
conn.execute_batch("PRAGMA wal_autocheckpoint = 0; INSERT INTO t VALUES ('only in wal');")
.unwrap();
// The files as a crash leaves them, nothing checkpointed or closed: copied while the
// connection is open, which then closes, so no handle outlives the test.
fs::copy(&live, &path).unwrap();
fs::copy(sidecar(&live, "-wal"), sidecar(&path, "-wal")).unwrap();
drop(conn);
assert!(contains(&sidecar(&path, "-wal"), b"only in wal"));
assert!(!contains(&path, b"only in wal"));
assert!(plain_size(&path) > 0);
let seen = std::sync::Mutex::new(Vec::new());
assert!(encrypt_in_place(&path, &key(1), &|n| seen.lock().unwrap().push(n)).unwrap());
assert!(seen.lock().unwrap().last().is_some_and(|n| *n > 0));
assert_eq!(file_state(&path).unwrap(), FileState::Encrypted);
for suffix in ["-wal", "-shm", "-plain", "-encrypting"] {
assert!(!sidecar(&path, suffix).exists(), "{suffix} left behind");
}
assert!(!contains(&path, b"only in wal") && !contains(&path, b"in the main file"));
let conn = Connection::open(&path).unwrap();
apply_key(&conn, &key(1)).unwrap();
let rows: Vec<String> = conn
.prepare("SELECT v FROM t ORDER BY v")
.unwrap()
.query_map([], |r| r.get(0))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert_eq!(rows, ["in the main file", "only in wal"]);
let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();
assert_eq!(version, 7);
drop(conn);
// Already encrypted, the second call does nothing.
assert!(!encrypt_in_place(&path, &key(1), &|_| {}).unwrap());
}
/// Rows keep their rowids, gaps from deleted rows and all, as flows' numbers are theirs.
#[test]
fn keeps_rowids() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("db.sqlite");
let conn = Connection::open(&path).unwrap();
conn.execute_batch(
"CREATE TABLE flows (id TEXT NOT NULL PRIMARY KEY, started INTEGER);
CREATE INDEX flows_started ON flows (started, id);
CREATE TABLE marks (id INTEGER PRIMARY KEY, max_rowid INTEGER);",
)
.unwrap();
for i in 0..20 {
conn.execute("INSERT INTO flows VALUES (?1, ?1)", [i]).unwrap();
}
conn.execute_batch(
"DELETE FROM flows WHERE started < 5 OR started IN (9, 12);
INSERT INTO marks VALUES (3, 12);",
)
.unwrap();
let rowids = |conn: &Connection| -> Vec<(i64, String)> {
conn.prepare("SELECT rowid, id FROM flows ORDER BY rowid")
.unwrap()
.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
.unwrap()
.map(|r| r.unwrap())
.collect()
};
let before = rowids(&conn);
drop(conn);
assert!(encrypt_in_place(&path, &key(1), &|_| {}).unwrap());
let conn = Connection::open(&path).unwrap();
apply_key(&conn, &key(1)).unwrap();
assert_eq!(rowids(&conn), before);
let mark: (i64, i64) = conn
.query_row("SELECT id, max_rowid FROM marks", [], |r| Ok((r.get(0)?, r.get(1)?)))
.unwrap();
assert_eq!(mark, (3, 12));
// New rows carry on from the last, not from the count.
conn.execute("INSERT INTO flows VALUES ('new', 99)", []).unwrap();
let last: i64 = conn.query_row("SELECT max(rowid) FROM flows", [], |r| r.get(0)).unwrap();
assert_eq!(last, 21);
}
#[test]
fn finishes_a_swap_that_stopped_halfway() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("db.sqlite");
let plain = sidecar(&path, "-plain");
let exported = sidecar(&path, "-encrypting");
Connection::open(&path).unwrap().execute_batch("CREATE TABLE t (v TEXT)").unwrap();
// Stopped mid-export: the half copy goes and the conversion runs again.
fs::write(&exported, b"half").unwrap();
assert!(encrypt_in_place(&path, &key(1), &|_| {}).unwrap());
assert!(!exported.exists());
// Stopped between the renames: the plain file aside, the copy not yet in place.
fs::rename(&path, &exported).unwrap();
Connection::open(&path).unwrap().execute_batch("CREATE TABLE t (v TEXT)").unwrap();
fs::rename(&path, &plain).unwrap();
assert!(!encrypt_in_place(&path, &key(1), &|_| {}).unwrap());
assert_eq!(file_state(&path).unwrap(), FileState::Encrypted);
assert!(!plain.exists() && !exported.exists());
// Stopped with the plain file aside and no copy: it is put back and converted.
fs::remove_file(&path).unwrap();
Connection::open(&plain).unwrap().execute_batch("CREATE TABLE t (v TEXT)").unwrap();
assert!(encrypt_in_place(&path, &key(1), &|_| {}).unwrap());
assert!(!plain.exists());
let conn = Connection::open(&path).unwrap();
apply_key(&conn, &key(1)).unwrap();
assert_eq!(fingerprint(&conn).unwrap(), [("table t".to_string(), 0, 0.0)]);
}
}
+2
View File
@@ -1,5 +1,7 @@
pub mod connection_or_tx;
pub mod db_context;
#[cfg(all(feature = "sqlcipher", not(target_arch = "wasm32")))]
pub mod encryption;
pub mod error;
pub mod migrate;
pub mod pool;
+11
View File
@@ -13,3 +13,14 @@ log = { workspace = true }
serde = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
yaak-models = { workspace = true }
# The Secret Service backend keyring uses, to tell a missing service from a refusal.
[target.'cfg(target_os = "linux")'.dependencies]
dbus-secret-service = "4.1.0"
[features]
# `MasterKeySource::memory` and `MasterKeySource::refusing`, for other crates' tests.
test-support = []
[dev-dependencies]
tempfile = "3"
+218
View File
@@ -0,0 +1,218 @@
//! A key for an app's own data at rest, outside any workspace. The data key encrypts the data;
//! it is kept beside it wrapped (encrypted) by the app's master key, so only the master key
//! lives in the OS credential store.
use crate::encryption::{decrypt_data, encrypt_data};
use crate::error::Error::{GenericError, IncorrectMasterKey, MissingMasterKey};
use crate::error::Result;
use crate::master_key::{write_secret_file, MasterKey, MasterKeySource};
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use chacha20poly1305::aead::{Generate, Key};
use chacha20poly1305::XChaCha20Poly1305;
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
#[derive(Clone)]
pub struct DataKey {
key: Key<XChaCha20Poly1305>,
}
impl DataKey {
/// Bytes [`DataKey::encrypt`] adds to what it encrypts: a tag and version, the nonce and the
/// authentication tag.
pub const OVERHEAD: usize = 48;
/// A new data key, and it wrapped by the master key in `source`, for storing. Makes the
/// master key when `source` has none.
pub fn create(source: &MasterKeySource) -> Result<(Self, String)> {
let master = MasterKey::get_or_create_in(source.store())?;
let key = Key::<XChaCha20Poly1305>::generate();
let wrapped = BASE64_STANDARD.encode(master.encrypt(key.as_slice())?);
Ok((Self { key }, wrapped))
}
/// The data key in `wrapped`, as [`DataKey::create`] gave it, unwrapped with the master key
/// in `source`. Never makes a master key: one made now could not unwrap it.
pub fn from_wrapped(source: &MasterKeySource, wrapped: &str) -> Result<Self> {
let master = MasterKey::get_in(source.store())?.ok_or(MissingMasterKey)?;
let wrapped = BASE64_STANDARD
.decode(wrapped.trim())
.map_err(|e| GenericError(format!("Failed to decode the wrapped data key: {e}")))?;
let raw = master.decrypt(&wrapped).map_err(|_| IncorrectMasterKey)?;
let key = Key::<XChaCha20Poly1305>::try_from(raw.as_slice())
.map_err(|_| GenericError("The data key is the wrong length".to_string()))?;
Ok(Self { key })
}
/// The data key kept wrapped in the file at `path`, made and written there the first time.
/// Safe to call from several threads and processes at once: a lock beside the file
/// serializes them, so every caller gets the one key that ends up written.
pub fn load_or_create_file(source: &MasterKeySource, path: &Path) -> Result<Self> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path.with_extension("lock"))?;
lock.lock()?;
match fs::read_to_string(path) {
Ok(wrapped) => Self::from_wrapped(source, &wrapped),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
let (key, wrapped) = Self::create(source)?;
// Written beside and renamed over, so a crash never leaves half a key.
let tmp = path.with_extension("tmp");
write_secret_file(&tmp, &wrapped)?;
fs::rename(&tmp, path)?;
Ok(key)
}
Err(e) => Err(e.into()),
}
}
/// The data key kept wrapped in the file at `path`, or None when there is no file. Never
/// makes one, for a reader that must not create keys.
pub fn load_file(source: &MasterKeySource, path: &Path) -> Result<Option<Self>> {
match fs::read_to_string(path) {
Ok(wrapped) => Self::from_wrapped(source, &wrapped).map(Some),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
/// The key's 32 bytes, for a cipher outside this crate, such as SQLCipher's raw key.
pub fn raw_bytes(&self) -> [u8; 32] {
let mut bytes = [0u8; 32];
bytes.copy_from_slice(self.key.as_slice());
bytes
}
pub fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>> {
encrypt_data(data, &self.key)
}
pub fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>> {
decrypt_data(data, &self.key)
}
}
/// Never prints the key.
impl fmt::Debug for DataKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("DataKey(..)")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::Error;
#[test]
fn round_trips_through_its_wrapped_form() -> Result<()> {
let source = MasterKeySource::memory();
let (key, wrapped) = DataKey::create(&source)?;
let sealed = key.encrypt(b"authorization: Bearer abc")?;
assert_eq!(sealed.len(), b"authorization: Bearer abc".len() + DataKey::OVERHEAD);
assert!(!sealed.windows(6).any(|w| w == b"Bearer"));
let unwrapped = DataKey::from_wrapped(&source, &wrapped)?;
assert_eq!(unwrapped.decrypt(&sealed)?, b"authorization: Bearer abc");
assert_eq!(key.decrypt(&unwrapped.encrypt(b"")?)?, b"");
assert_eq!(unwrapped.raw_bytes(), key.raw_bytes());
Ok(())
}
#[test]
fn unwrapping_needs_the_same_master_key() -> Result<()> {
let (_, wrapped) = DataKey::create(&MasterKeySource::memory())?;
// One that has never had a master key does not get one made.
let empty = MasterKeySource::memory();
assert!(matches!(DataKey::from_wrapped(&empty, &wrapped), Err(Error::MissingMasterKey)));
assert!(empty.store().get()?.is_none());
let other = MasterKeySource::memory();
DataKey::create(&other)?;
assert!(matches!(DataKey::from_wrapped(&other, &wrapped), Err(Error::IncorrectMasterKey)));
let refusing = MasterKeySource::refusing("denied");
assert!(DataKey::create(&refusing).is_err());
assert!(DataKey::from_wrapped(&refusing, &wrapped).is_err());
Ok(())
}
#[test]
fn a_wrong_key_does_not_decrypt() -> Result<()> {
let source = MasterKeySource::memory();
let (a, _) = DataKey::create(&source)?;
let (b, _) = DataKey::create(&source)?;
let sealed = a.encrypt(b"secret")?;
assert!(matches!(b.decrypt(&sealed), Err(Error::DecryptionError)));
assert_eq!(format!("{a:?}"), "DataKey(..)");
Ok(())
}
#[test]
fn the_key_file_is_made_once_and_read_back() -> Result<()> {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("data.key");
let source = MasterKeySource::memory();
let made = DataKey::load_or_create_file(&source, &path)?;
let stored = fs::read_to_string(&path)?;
assert!(!stored.is_empty());
assert!(!dir.path().join("data.tmp").exists());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(fs::metadata(&path)?.permissions().mode() & 0o777, 0o600);
}
let read = DataKey::load_or_create_file(&source, &path)?;
assert_eq!(read.raw_bytes(), made.raw_bytes());
let loaded = DataKey::load_file(&source, &path)?.unwrap();
assert_eq!(loaded.raw_bytes(), made.raw_bytes());
assert!(DataKey::load_file(&source, &dir.path().join("none.key"))?.is_none());
assert!(!dir.path().join("none.key").exists());
assert_eq!(fs::read_to_string(&path)?, stored, "not rewritten");
// Another master key cannot read it, and does not replace it.
let other = MasterKeySource::memory();
assert!(matches!(
DataKey::load_or_create_file(&other, &path),
Err(Error::MissingMasterKey)
));
assert!(DataKey::load_or_create_file(&MasterKeySource::refusing("denied"), &path).is_err());
assert_eq!(fs::read_to_string(&path)?, stored);
Ok(())
}
/// Everyone asking at once, the first time, gets the same key: one master key, one data key.
#[test]
fn concurrent_first_loads_agree() -> Result<()> {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("data.key");
let source = MasterKeySource::memory();
let barrier = std::sync::Barrier::new(8);
let keys: Vec<[u8; 32]> = std::thread::scope(|s| {
let handles: Vec<_> = (0..8)
.map(|_| {
s.spawn(|| {
barrier.wait();
DataKey::load_or_create_file(&source, &path).unwrap().raw_bytes()
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
assert!(keys.windows(2).all(|w| w[0] == w[1]));
assert_eq!(DataKey::load_or_create_file(&source, &path)?.raw_bytes(), keys[0]);
Ok(())
}
}
+6
View File
@@ -19,6 +19,12 @@ pub enum Error {
#[error("Failed to decrypt workspace key: {0}")]
WorkspaceKeyDecryptionError(String),
#[error("The encryption key is missing from the keychain")]
MissingMasterKey,
#[error("The keychain's encryption key does not match the one this data was encrypted with")]
IncorrectMasterKey,
#[error("Crypto IO error: {0}")]
IoError(#[from] io::Error),
+3
View File
@@ -1,7 +1,10 @@
extern crate core;
pub mod data_key;
pub mod encryption;
pub mod error;
pub mod manager;
mod master_key;
mod workspace_key;
pub use master_key::MasterKeySource;
+330 -23
View File
@@ -5,7 +5,9 @@ use base32::Alphabet;
use chacha20poly1305::aead::{Generate, Key};
use chacha20poly1305::XChaCha20Poly1305;
use keyring::{Entry, Error};
use log::info;
use log::{info, warn};
use std::path::{Path, PathBuf};
use std::sync::Arc;
const HUMAN_PREFIX: &str = "YKM_";
@@ -16,31 +18,38 @@ pub(crate) struct MasterKey {
impl MasterKey {
pub(crate) fn get_or_create(app_id: &str, user: &str) -> Result<Self> {
let id = format!("{app_id}.EncryptionKey");
let entry = Entry::new(&id, user)?;
let key = match entry.get_password() {
Ok(encoded) => {
let without_prefix = encoded.strip_prefix(HUMAN_PREFIX).unwrap_or(&encoded);
let key_bytes = base32::decode(Alphabet::Crockford {}, &without_prefix)
.ok_or(GenericError("Failed to decode master key".to_string()))?;
Key::<XChaCha20Poly1305>::try_from(key_bytes.as_slice())
.map_err(|_| GenericError("Master key is the wrong length".to_string()))?
}
Err(Error::NoEntry) => {
info!("Creating new master key");
let key = Key::<XChaCha20Poly1305>::generate();
let encoded = base32::encode(Alphabet::Crockford {}, key.as_slice());
let with_prefix = format!("{HUMAN_PREFIX}{encoded}");
entry.set_password(&with_prefix)?;
key
}
Err(e) => return Err(GenericError(e.to_string())),
};
Self::get_or_create_in(&KeychainStore::new(app_id, user))
}
/// The master key in `store`, or a new one put there when it has none. Callers in this
/// process take turns, so two asking at once for the first time do not each make one, the
/// second replacing the first and leaving what it wrapped unreadable.
pub(crate) fn get_or_create_in(store: &dyn SecretStore) -> Result<Self> {
static CREATING: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _turn = CREATING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(key) = Self::get_in(store)? {
return Ok(key);
}
info!("Creating new master key");
let key = Key::<XChaCha20Poly1305>::generate();
let encoded = base32::encode(Alphabet::Crockford {}, key.as_slice());
store.set(&format!("{HUMAN_PREFIX}{encoded}"))?;
Ok(Self { key })
}
/// The master key in `store`, or None when it has none.
pub(crate) fn get_in(store: &dyn SecretStore) -> Result<Option<Self>> {
let Some(encoded) = store.get()? else {
return Ok(None);
};
let without_prefix = encoded.strip_prefix(HUMAN_PREFIX).unwrap_or(&encoded);
let key_bytes = base32::decode(Alphabet::Crockford {}, without_prefix)
.ok_or(GenericError("Failed to decode master key".to_string()))?;
let key = Key::<XChaCha20Poly1305>::try_from(key_bytes.as_slice())
.map_err(|_| GenericError("Master key is the wrong length".to_string()))?;
Ok(Some(Self { key }))
}
pub(crate) fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>> {
encrypt_data(data, &self.key)
}
@@ -56,10 +65,223 @@ impl MasterKey {
}
}
/// Where a master key is kept, as the text [`MasterKey`] encodes it to.
pub(crate) trait SecretStore: Send + Sync {
/// The secret, or None when none has been set.
fn get(&self) -> Result<Option<String>>;
fn set(&self, secret: &str) -> Result<()>;
}
/// Where an app's master key is kept: the OS credential store, normally. Cheap to clone.
#[derive(Clone)]
pub struct MasterKeySource {
store: Arc<dyn SecretStore>,
}
impl MasterKeySource {
/// The OS credential store, under `{app_id}.EncryptionKey`, where Yaak keeps its own: the
/// macOS Keychain, the Windows Credential Manager or the Secret Service on Linux.
pub fn keychain(app_id: &str) -> Self {
Self { store: Arc::new(KeychainStore::new(app_id, KEYCHAIN_USER)) }
}
/// [`Self::keychain`], but on Linux without a Secret Service running, the key is kept in
/// `path`, readable by the user alone, with a warning, rather than not at all.
pub fn keychain_or_file(app_id: &str, path: impl Into<PathBuf>) -> Self {
let store = KeychainStore::new(app_id, KEYCHAIN_USER).with_fallback_file(path.into());
Self { store: Arc::new(store) }
}
/// A key held in memory for as long as this source and its clones live.
#[cfg(any(test, feature = "test-support"))]
pub fn memory() -> Self {
Self { store: Arc::new(test_support::MemoryStore::default()) }
}
/// A store that refuses with `reason`, as a keychain does when access is denied.
#[cfg(any(test, feature = "test-support"))]
pub fn refusing(reason: impl Into<String>) -> Self {
Self { store: Arc::new(test_support::RefusingStore(reason.into())) }
}
pub(crate) fn store(&self) -> &dyn SecretStore {
self.store.as_ref()
}
}
/// The account master keys are kept under, as [`crate::manager::EncryptionManager`] keeps
/// Yaak's.
const KEYCHAIN_USER: &str = "encryption-key";
/// The OS credential store, with a file to fall back to on Linux without a Secret Service.
struct KeychainStore {
service: String,
user: String,
fallback_file: Option<PathBuf>,
}
impl KeychainStore {
fn new(app_id: &str, user: &str) -> Self {
Self { service: format!("{app_id}.EncryptionKey"), user: user.into(), fallback_file: None }
}
fn with_fallback_file(self, path: PathBuf) -> Self {
Self { fallback_file: Some(path), ..self }
}
/// The fallback file, when `e` says there is no credential store to use and there is one.
/// Denied access is not that: it stays an error.
fn fallback_for(&self, e: &Error) -> Option<&Path> {
let path = self.fallback_file.as_deref()?;
is_missing_secret_service(e).then_some(path)
}
/// A key kept in the fallback file while there was no credential store. Read before
/// creating one, so a Secret Service that turns up later does not replace it.
fn fallback_secret(&self) -> Result<Option<String>> {
match &self.fallback_file {
Some(path) => read_secret_file(path),
None => Ok(None),
}
}
}
impl SecretStore for KeychainStore {
fn get(&self) -> Result<Option<String>> {
let entry = Entry::new(&self.service, &self.user)?;
match entry.get_password() {
Ok(secret) => Ok(Some(secret)),
Err(Error::NoEntry) => self.fallback_secret(),
Err(e) => match self.fallback_for(&e) {
Some(path) => read_secret_file(path),
None => Err(GenericError(e.to_string())),
},
}
}
fn set(&self, secret: &str) -> Result<()> {
let entry = Entry::new(&self.service, &self.user)?;
match entry.set_password(secret) {
Ok(()) => Ok(()),
Err(e) => match self.fallback_for(&e) {
Some(path) => {
warn!(
"No Secret Service is running ({e}), so the encryption key for {} is kept \
in {}, readable only by you, instead of the keyring",
self.service,
path.display()
);
write_secret_file(path, secret)
}
None => Err(e.into()),
},
}
}
}
/// D-Bus errors that mean there is no session bus, or no Secret Service on it.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const MISSING_SERVICE_ERRORS: [&str; 7] = [
"org.freedesktop.DBus.Error.ServiceUnknown",
"org.freedesktop.DBus.Error.NameHasNoOwner",
"org.freedesktop.DBus.Error.NoServer",
"org.freedesktop.DBus.Error.FileNotFound",
"org.freedesktop.DBus.Error.BadAddress",
// Autolaunching a session bus without X11
"org.freedesktop.DBus.Error.NotSupported",
"org.freedesktop.DBus.Error.Spawn.ExecFailed",
];
/// `e` says there is no Secret Service to keep a key in: no session bus, or nothing on it
/// providing `org.freedesktop.secrets`. Every other failure, access denied, a locked
/// collection or a dismissed prompt among them, is not, so it stays an error rather than
/// putting the key in a file.
#[cfg(target_os = "linux")]
fn is_missing_secret_service(e: &Error) -> bool {
let Error::PlatformFailure(inner) = e else {
return false;
};
match inner.downcast_ref::<dbus_secret_service::Error>() {
Some(dbus_secret_service::Error::Unavailable) => true,
Some(dbus_secret_service::Error::Dbus(e)) => {
e.name().is_some_and(|name| MISSING_SERVICE_ERRORS.contains(&name))
}
_ => false,
}
}
/// Only Linux keeps keys in a service that may not be running.
#[cfg(not(target_os = "linux"))]
fn is_missing_secret_service(_e: &Error) -> bool {
false
}
fn read_secret_file(path: &Path) -> Result<Option<String>> {
match std::fs::read_to_string(path) {
Ok(secret) => Ok(Some(secret.trim().to_string())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
/// Writes `secret` to `path`, readable and writable by the user alone where the platform has
/// such modes.
pub(crate) fn write_secret_file(path: &Path, secret: &str) -> Result<()> {
use std::io::Write;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let mut file = options.open(path)?;
// A file that already existed keeps its mode through `open`.
#[cfg(unix)]
file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(0o600))?;
file.write_all(secret.as_bytes())?;
file.sync_all()?;
Ok(())
}
#[cfg(any(test, feature = "test-support"))]
mod test_support {
use super::SecretStore;
use crate::error::Error::GenericError;
use crate::error::Result;
use std::sync::Mutex;
#[derive(Default)]
pub(super) struct MemoryStore(Mutex<Option<String>>);
impl SecretStore for MemoryStore {
fn get(&self) -> Result<Option<String>> {
Ok(self.0.lock().unwrap().clone())
}
fn set(&self, secret: &str) -> Result<()> {
*self.0.lock().unwrap() = Some(secret.to_string());
Ok(())
}
}
pub(super) struct RefusingStore(pub(super) String);
impl SecretStore for RefusingStore {
fn get(&self) -> Result<Option<String>> {
Err(GenericError(self.0.clone()))
}
fn set(&self, _secret: &str) -> Result<()> {
Err(GenericError(self.0.clone()))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::Result;
use crate::master_key::MasterKey;
#[test]
fn test_master_key() -> Result<()> {
@@ -75,4 +297,89 @@ mod tests {
Ok(())
}
#[test]
fn creates_a_master_key_once() -> Result<()> {
let source = MasterKeySource::memory();
assert!(MasterKey::get_in(source.store())?.is_none());
let created = MasterKey::get_or_create_in(source.store())?;
let stored = source.store().get()?.unwrap();
assert!(stored.starts_with(HUMAN_PREFIX), "{stored}");
let again = MasterKey::get_or_create_in(source.store())?;
assert_eq!(again.key, created.key);
assert_eq!(source.store().get()?.unwrap(), stored);
Ok(())
}
/// Several asking at once for the first time all get the one key that is stored.
#[test]
fn concurrent_first_creates_agree() {
let source = MasterKeySource::memory();
let barrier = std::sync::Barrier::new(8);
let keys: Vec<_> = std::thread::scope(|s| {
let handles: Vec<_> = (0..8)
.map(|_| {
s.spawn(|| {
barrier.wait();
MasterKey::get_or_create_in(source.store()).unwrap().key
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
let stored = MasterKey::get_in(source.store()).unwrap().unwrap().key;
assert!(keys.iter().all(|k| *k == stored));
}
#[test]
fn a_refusing_store_gives_no_key() {
let source = MasterKeySource::refusing("User canceled the operation");
let err = MasterKey::get_or_create_in(source.store()).unwrap_err();
assert_eq!(err.to_string(), "Encryption error: User canceled the operation");
}
#[test]
fn the_fallback_file_is_private_and_read_back() -> Result<()> {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("keys").join("master.key");
assert_eq!(read_secret_file(&path)?, None);
write_secret_file(&path, "YKM_ABC")?;
assert_eq!(read_secret_file(&path)?.as_deref(), Some("YKM_ABC"));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&path)?.permissions().mode();
assert_eq!(mode & 0o777, 0o600);
}
// Rewritten, it stays private and holds only the new key.
write_secret_file(&path, "YKM_D")?;
assert_eq!(read_secret_file(&path)?.as_deref(), Some("YKM_D"));
Ok(())
}
#[test]
fn falls_back_only_without_a_store() {
let store = KeychainStore::new("app.yaak.test", "u").with_fallback_file("k".into());
// Failures that do not say the Secret Service is missing, such as a denied D-Bus call,
// which the backend also reports as a platform failure.
let other = Error::PlatformFailure("org.freedesktop.DBus.Error.AccessDenied".into());
let denied = Error::NoStorageAccess("prompt dismissed".into());
assert!(store.fallback_for(&other).is_none());
assert!(store.fallback_for(&denied).is_none());
assert!(store.fallback_for(&Error::NoEntry).is_none());
}
#[cfg(target_os = "linux")]
#[test]
fn falls_back_on_linux_without_a_secret_service() {
let store = KeychainStore::new("app.yaak.test", "u").with_fallback_file("k".into());
let missing = Error::PlatformFailure(Box::new(dbus_secret_service::Error::Unavailable));
assert!(store.fallback_for(&missing).is_some());
assert!(KeychainStore::new("app.yaak.test", "u").fallback_for(&missing).is_none());
let locked = Error::PlatformFailure(Box::new(dbus_secret_service::Error::Locked));
assert!(store.fallback_for(&locked).is_none());
}
}
+4
View File
@@ -24,6 +24,10 @@ ts-rs = { workspace = true, features = ["chrono-impl", "serde-json-impl"] }
yaak-core = { workspace = true }
yaak-templates = { path = "../yaak-templates", default-features = false }
[features]
# Opening databases encrypted with SQLCipher; see `yaak_database::encryption`.
sqlcipher = ["yaak-database/sqlcipher"]
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
r2d2 = "0.8.10"
r2d2_sqlite = { version = "0.32" }
+25
View File
@@ -223,6 +223,16 @@ impl BodyChunkWriter {
Ok(self.total_bytes)
}
/// [`Self::finish`] without inserting the partial last chunk: it is returned for the caller
/// to insert, in a transaction it shares with other writes.
pub fn finish_deferred(mut self) -> Option<BodyChunk> {
if self.buf.is_empty() {
return None;
}
let data = std::mem::take(&mut self.buf);
Some(BodyChunk::new(&self.body_id, self.chunk_index, data))
}
fn insert(&mut self, data: Vec<u8>) -> Result<()> {
let chunk = BodyChunk::new(&self.body_id, self.chunk_index, data);
self.blob_manager.with_tx(|b| b.insert_chunk(&chunk))?;
@@ -318,6 +328,21 @@ mod tests {
.unwrap();
}
/// The last chunk is handed back unwritten, after the full chunks written as they filled.
#[test]
fn finish_deferred_returns_the_last_chunk_unwritten() {
let manager = create_test_manager();
let mut writer = BodyChunkWriter::new(manager.clone(), "fl_1.response");
writer.write(&vec![b'a'; BODY_CHUNK_SIZE + 3]).unwrap();
let last = writer.finish_deferred().unwrap();
assert_eq!((last.body_id.as_str(), last.chunk_index), ("fl_1.response", 1));
assert_eq!(last.data, b"aaa");
assert_eq!(manager.connect().get_chunks("fl_1.response").unwrap().len(), 1);
let empty = BodyChunkWriter::new(manager.clone(), "fl_2.response");
assert!(empty.finish_deferred().is_none());
}
#[test]
fn test_insert_and_get_chunks() {
let manager = create_test_manager();
+41
View File
@@ -58,6 +58,31 @@ mod open {
std::fs::create_dir_all(parent)?;
}
let manager = SqliteConnectionManager::file(path).with_init(|c| init_file_connection(c));
build(manager, max_size, min_idle)
}
/// [`file_pool`] over a database encrypted with `key`, keying each connection first.
#[cfg(feature = "sqlcipher")]
pub fn encrypted_file_pool(
path: impl Into<PathBuf>,
max_size: u32,
min_idle: u32,
key: &yaak_database::encryption::DatabaseKey,
) -> Result<SqlitePool> {
let path: PathBuf = path.into();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
yaak_database::encryption::init_crypto();
let key = key.clone();
let manager = SqliteConnectionManager::file(path).with_init(move |c| {
yaak_database::encryption::apply_key(c, &key)?;
init_file_connection(c)
});
build(manager, max_size, min_idle)
}
fn build(manager: SqliteConnectionManager, max_size: u32, min_idle: u32) -> Result<SqlitePool> {
Pool::builder()
.max_size(max_size)
.min_idle(Some(min_idle))
@@ -160,6 +185,22 @@ pub fn init_blob_store(blob_path: impl AsRef<Path>) -> Result<BlobManager> {
Ok(BlobManager::new(blob_readers, blob_writer))
}
/// [`init_blob_store`] for a blobs database encrypted with `key`, as
/// [`yaak_database::encryption`] makes one. A plain one is converted first with
/// [`yaak_database::encryption::encrypt_in_place`].
#[cfg(all(feature = "sqlcipher", not(target_arch = "wasm32")))]
pub fn init_encrypted_blob_store(
blob_path: impl AsRef<Path>,
key: &yaak_database::encryption::DatabaseKey,
) -> Result<BlobManager> {
let blob_path = blob_path.as_ref();
info!("Initializing encrypted blobs database {blob_path:?}");
let readers = open::encrypted_file_pool(blob_path, 10, 1, key)?;
let writer = open::encrypted_file_pool(blob_path, 1, 1, key)?;
migrate_blob_db(&writer)?;
Ok(BlobManager::new(readers, writer))
}
/// Initialize the database managers with in-memory SQLite databases.
/// Useful for testing and CI environments.
///
+149 -15
View File
@@ -28,10 +28,28 @@ pub struct CaStore {
leaf_configs: Mutex<HashMap<(String, bool), Arc<ServerConfig>>>,
}
/// Encrypts the CA's private key at rest, for [`CaStore::load_or_create_encrypted`].
pub trait KeyCipher: Send + Sync {
fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, String>;
fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, String>;
}
impl CaStore {
/// Loads the CA from `dir`, or creates one there (key mode 0600) if either file is missing.
/// Safe to call from several processes at once: `ca.lock` serializes them.
pub fn load_or_create(dir: &Path) -> io::Result<Self> {
Self::open(dir, None)
}
/// [`Self::load_or_create`], keeping `ca.key` encrypted with `cipher`. A plaintext `ca.key`,
/// as builds before encryption wrote, is encrypted in place. One `cipher` cannot decrypt,
/// encrypted with a key since lost, is replaced along with the certificate: unusable, it
/// could only leave the proxy unable to start, and the new one has to be trusted again.
pub fn load_or_create_encrypted(dir: &Path, cipher: &dyn KeyCipher) -> io::Result<Self> {
Self::open(dir, Some(cipher))
}
fn open(dir: &Path, cipher: Option<&dyn KeyCipher>) -> io::Result<Self> {
let cert_path = dir.join("ca.pem");
let key_path = dir.join("ca.key");
@@ -43,22 +61,26 @@ impl CaStore {
.open(dir.join("ca.lock"))?;
lock.lock()?;
let (pem, key) = if cert_path.exists() && key_path.exists() {
let key =
KeyPair::from_pem(&fs::read_to_string(&key_path)?).map_err(io::Error::other)?;
(fs::read_to_string(&cert_path)?, key)
let stored = if cert_path.exists() && key_path.exists() {
load_key(&key_path, cipher)?
} else {
log::info!("Creating proxy CA in {}", dir.display());
let key = KeyPair::generate().map_err(io::Error::other)?;
let now = OffsetDateTime::now_utc();
let mut params = ca_params();
params.not_before = now - Duration::days(1);
params.not_after = now + Duration::days(CA_VALIDITY_DAYS);
let pem = params.self_signed(&key).map_err(io::Error::other)?.pem();
remove_if_exists(&cert_path)?;
write_atomic(&key_path, key.serialize_pem().as_bytes(), true)?;
write_atomic(&cert_path, pem.as_bytes(), false)?;
(pem, key)
None
};
let (pem, key) = match stored {
Some(key) => (fs::read_to_string(&cert_path)?, key),
None => {
log::info!("Creating proxy CA in {}", dir.display());
let key = KeyPair::generate().map_err(io::Error::other)?;
let now = OffsetDateTime::now_utc();
let mut params = ca_params();
params.not_before = now - Duration::days(1);
params.not_after = now + Duration::days(CA_VALIDITY_DAYS);
let pem = params.self_signed(&key).map_err(io::Error::other)?.pem();
remove_if_exists(&cert_path)?;
write_key(&key_path, &key, cipher)?;
write_atomic(&cert_path, pem.as_bytes(), false)?;
(pem, key)
}
};
drop(lock);
@@ -179,6 +201,48 @@ fn ca_params() -> CertificateParams {
params
}
/// The key in `ca.key`: PEM as written without a cipher, or encrypted with one. A plaintext key
/// is encrypted in place when there is a cipher. None when the cipher cannot decrypt it.
fn load_key(path: &Path, cipher: Option<&dyn KeyCipher>) -> io::Result<Option<KeyPair>> {
let stored = fs::read(path)?;
if stored.starts_with(b"-----BEGIN") {
let pem = String::from_utf8(stored).map_err(io::Error::other)?;
let key = KeyPair::from_pem(&pem).map_err(io::Error::other)?;
if cipher.is_some() {
write_key(path, &key, cipher)?;
log::info!("Encrypted the proxy CA's private key in {}", path.display());
}
return Ok(Some(key));
}
let Some(cipher) = cipher else {
return Err(io::Error::other(format!(
"{} is encrypted, with no key to read it",
path.display()
)));
};
let pem = match cipher.decrypt(&stored) {
Ok(pem) => String::from_utf8(pem).map_err(io::Error::other)?,
Err(e) => {
log::warn!(
"Failed to decrypt {} ({e}), so the proxy CA is replaced with a new one",
path.display()
);
return Ok(None);
}
};
KeyPair::from_pem(&pem).map(Some).map_err(io::Error::other)
}
/// Writes `ca.key`, mode 0600, encrypted when there is a cipher.
fn write_key(path: &Path, key: &KeyPair, cipher: Option<&dyn KeyCipher>) -> io::Result<()> {
let pem = key.serialize_pem();
let contents = match cipher {
Some(cipher) => cipher.encrypt(pem.as_bytes()).map_err(io::Error::other)?,
None => pem.into_bytes(),
};
write_atomic(path, &contents, true)
}
fn remove_if_exists(path: &Path) -> io::Result<()> {
match fs::remove_file(path) {
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
@@ -216,6 +280,76 @@ mod tests {
use super::*;
use std::sync::mpsc;
/// Flips every bit behind a marker that names the key, so a wrong key fails to decrypt.
struct TestCipher(u8);
impl KeyCipher for TestCipher {
fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, String> {
Ok([b'k', self.0].into_iter().chain(data.iter().map(|b| !b)).collect())
}
fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, String> {
let rest = data.strip_prefix(&[b'k', self.0][..]).ok_or("wrong key")?;
Ok(rest.iter().map(|b| !b).collect())
}
}
fn private(path: &Path) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(fs::metadata(path).unwrap().permissions().mode() & 0o777, 0o600);
}
#[cfg(not(unix))]
let _ = path;
}
#[test]
fn keeps_the_key_encrypted() {
let dir = tempfile::tempdir().unwrap();
let created = CaStore::load_or_create_encrypted(dir.path(), &TestCipher(1)).unwrap();
let stored = fs::read(created.key_path()).unwrap();
assert!(!stored.windows(11).any(|w| w == b"PRIVATE KEY"), "ca.key is plaintext");
private(created.key_path());
// The certificate is public, and stays as it was.
assert!(fs::read_to_string(created.cert_path()).unwrap().starts_with("-----BEGIN"));
let loaded = CaStore::load_or_create_encrypted(dir.path(), &TestCipher(1)).unwrap();
assert_eq!(loaded.pem(), created.pem());
assert_eq!(fs::read(loaded.key_path()).unwrap(), stored, "rewritten");
loaded.server_config("example.test", true).unwrap();
let err = CaStore::load_or_create(dir.path()).err().unwrap();
assert!(err.to_string().ends_with("ca.key is encrypted, with no key to read it"), "{err}");
}
#[test]
fn encrypts_a_plaintext_key_in_place() {
let dir = tempfile::tempdir().unwrap();
let plain = CaStore::load_or_create(dir.path()).unwrap();
let pem_key = fs::read_to_string(plain.key_path()).unwrap();
let encrypted = CaStore::load_or_create_encrypted(dir.path(), &TestCipher(1)).unwrap();
assert_eq!(encrypted.pem(), plain.pem(), "the same CA, still trusted");
let stored = fs::read(encrypted.key_path()).unwrap();
assert_eq!(TestCipher(1).decrypt(&stored).unwrap(), pem_key.as_bytes());
private(encrypted.key_path());
assert!(!dir.path().join("ca.key.tmp").exists());
}
#[test]
fn replaces_a_ca_whose_key_cannot_be_decrypted() {
let dir = tempfile::tempdir().unwrap();
let lost = CaStore::load_or_create_encrypted(dir.path(), &TestCipher(1)).unwrap();
let replaced = CaStore::load_or_create_encrypted(dir.path(), &TestCipher(2)).unwrap();
assert_ne!(replaced.pem(), lost.pem());
let stored = fs::read(replaced.key_path()).unwrap();
assert!(TestCipher(2).decrypt(&stored).is_ok());
let again = CaStore::load_or_create_encrypted(dir.path(), &TestCipher(2)).unwrap();
assert_eq!(again.pem(), replaced.pem());
}
/// A host whose leaf is still being signed holds up no lookup of another host's.
#[test]
fn signing_one_host_does_not_block_another() {
+1 -1
View File
@@ -30,7 +30,7 @@ use rustls::ClientConfig;
use rustls::pki_types::CertificateDer;
use tokio::net::TcpListener;
pub use cert::CaStore;
pub use cert::{CaStore, KeyCipher};
use connection::handle_connection;
pub use grpc::{detect as detect_grpc, service_and_method};
pub use messages::{MessageDirection, MessageKind, RAW_LIMIT, StreamKind, StreamMessage};