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

+214 -24
View File
@@ -1,15 +1,30 @@
//! The one place the proxy's databases are opened. `proxy.db` and `blobs.sqlite` are encrypted
//! whole with SQLCipher, keyed from the data key [`Stores::open`] is given: every connection is
//! keyed as it opens, and a plain database left by a build from before is converted before
//! anything writes to it. Only reading, an unconverted one is read as it is.
use include_dir::{Dir, include_dir};
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::functions::FunctionFlags;
use rusqlite::{OpenFlags, Transaction, TransactionBehavior};
use std::path::Path;
use std::path::{Path, PathBuf};
use std::time::Duration;
use yaak_crypto::MasterKeySource;
use yaak_crypto::data_key::DataKey;
use yaak_database::encryption::{self, DatabaseKey, FileState};
use yaak_database::{ConnectionOrTx, DbContext, Error, Result, SqlitePool, run_migrations};
use yaak_models::blob_manager::BlobManager;
static MIGRATIONS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/migrations");
/// Flows, their headers and messages.
pub const PROXY_DB: &str = "proxy.db";
/// Request and response bodies, and message payloads.
pub const BLOBS_DB: &str = "blobs.sqlite";
/// The key both are encrypted with, wrapped by the app's master key in the keychain.
pub const DATA_KEY: &str = "data.key";
/// Reads come from a pool; writes go through one connection, as in yaak-models'
/// `QueryManager`. WAL lets the CLI read `proxy.db` while the app writes it.
#[derive(Clone)]
@@ -19,19 +34,23 @@ pub struct ProxyQueryManager {
}
impl ProxyQueryManager {
pub fn new(db_path: &Path) -> Result<Self> {
/// Opens `proxy.db` encrypted with `key`, made so when it is new and converted when a build
/// from before left it plain, and brings its schema up to date.
pub fn new(db_path: &Path, key: &DatabaseKey) -> Result<Self> {
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent)?;
}
let writer = file_pool(db_path, 1)?;
encryption::encrypt_in_place(db_path, key, &|_| {})?;
let writer = file_pool(db_path, 1, key)?;
run_migrations(&writer, &MIGRATIONS)?;
Ok(Self { readers: file_pool(db_path, 5)?, writer })
Ok(Self { readers: file_pool(db_path, 5, key)?, writer })
}
/// `proxy.db` for reading while another process may be writing it, or none is. Writes
/// fail. No migrations run, so an older database reads as it is.
pub fn open_read_only(db_path: &Path) -> Result<Self> {
let readers = read_only_pool(db_path)?;
/// fail. No migrations run, so an older database reads as it is. An encrypted one needs
/// `key`; a plain one, not yet converted, is read without it.
pub fn open_read_only(db_path: &Path, key: Option<&DatabaseKey>) -> Result<Self> {
let readers = read_only_pool(db_path, key)?;
Ok(Self { writer: readers.clone(), readers })
}
@@ -71,12 +90,150 @@ impl ProxyQueryManager {
}
}
/// `blobs.sqlite` encrypted with `key`, converted first when it is plain, migrated.
pub fn open_blobs(path: &Path, key: &DatabaseKey) -> Result<BlobManager> {
encryption::encrypt_in_place(path, key, &|_| {})?;
yaak_models::init_encrypted_blob_store(path, key).map_err(|e| Error::Database(e.to_string()))
}
/// `blobs.sqlite` for reading, alongside [`ProxyQueryManager::open_read_only`].
pub fn open_blobs_read_only(path: &Path) -> Result<BlobManager> {
let readers = read_only_pool(path)?;
pub fn open_blobs_read_only(path: &Path, key: Option<&DatabaseKey>) -> Result<BlobManager> {
let readers = read_only_pool(path, key)?;
Ok(BlobManager::new(readers.clone(), readers))
}
/// The SQLCipher key for the databases, from the data key.
pub fn database_key(data_key: &DataKey) -> DatabaseKey {
DatabaseKey::from_bytes(data_key.raw_bytes())
}
/// Where the data key is kept in `data_dir`.
pub fn data_key_path(data_dir: &Path) -> PathBuf {
data_dir.join(DATA_KEY)
}
/// The data key for the databases in `data_dir`, unwrapped with the master key in `keys`, and
/// made the first time. Not made again once a database is encrypted, should its file go: a new
/// one could not open it, and would replace the CA.
pub fn load_or_create_data_key(
keys: &MasterKeySource,
data_dir: &Path,
) -> std::result::Result<DataKey, String> {
let path = data_key_path(data_dir);
if any_encrypted(data_dir) {
DataKey::load_file(keys, &path)
.map_err(|e| key_unavailable(&e.to_string()))?
.ok_or_else(|| missing_data_key(data_dir))
} else {
DataKey::load_or_create_file(keys, &path).map_err(|e| key_unavailable(&e.to_string()))
}
}
fn any_encrypted(data_dir: &Path) -> bool {
[PROXY_DB, BLOBS_DB]
.iter()
.any(|name| encryption::file_state(&data_dir.join(name)).ok() == Some(FileState::Encrypted))
}
fn missing_data_key(data_dir: &Path) -> String {
format!(
"The proxy's captured traffic is encrypted, but its key is missing from {}",
data_dir.display()
)
}
/// Both databases, opened together.
#[derive(Clone)]
pub struct Stores {
pub db: ProxyQueryManager,
pub blobs: BlobManager,
}
impl Stores {
/// The databases in `data_dir`, encrypted with `key`. Ones a build from before left plain
/// are converted first, without progress; [`encrypt_existing`] shows it.
pub fn open(data_dir: &Path, key: &DatabaseKey) -> std::result::Result<Self, String> {
let db = ProxyQueryManager::new(&data_dir.join(PROXY_DB), key)
.map_err(|e| format!("Failed to open proxy database: {e}"))?;
let blobs = open_blobs(&data_dir.join(BLOBS_DB), key)
.map_err(|e| format!("Failed to open proxy blob store: {e}"))?;
Ok(Self { db, blobs })
}
/// The databases in `data_dir` for reading, with the data key the master key in `keys`
/// unwraps. Asks the keychain only when one is encrypted, and never makes a key.
pub fn open_read_only(
data_dir: &Path,
keys: &MasterKeySource,
) -> std::result::Result<Self, String> {
let db_path = data_dir.join(PROXY_DB);
let blobs_path = data_dir.join(BLOBS_DB);
let key = if any_encrypted(data_dir) {
let data_key = DataKey::load_file(keys, &data_key_path(data_dir))
.map_err(|e| key_unavailable(&e.to_string()))?
.ok_or_else(|| missing_data_key(data_dir))?;
Some(database_key(&data_key))
} else {
None
};
let db = ProxyQueryManager::open_read_only(&db_path, key.as_ref())
.map_err(|e| format!("Failed to open {}: {e}", db_path.display()))?;
let blobs = open_blobs_read_only(&blobs_path, key.as_ref())
.map_err(|e| format!("Failed to open the proxy's blob store: {e}"))?;
Ok(Self { db, blobs })
}
}
/// Either database in `data_dir` is plain, left by a build from before encryption.
pub fn needs_encrypting(data_dir: &Path) -> bool {
[PROXY_DB, BLOBS_DB]
.iter()
.any(|name| encryption::file_state(&data_dir.join(name)).ok() == Some(FileState::Plain))
}
/// Converts the plain databases in `data_dir` to ones encrypted with `key`, telling `progress`
/// how far it has got, from 0 to 1. Returns whether there were any. Nothing may have them
/// open meanwhile.
pub fn encrypt_existing(
data_dir: &Path,
key: &DatabaseKey,
progress: &(dyn Fn(f64) + Sync),
) -> std::result::Result<bool, String> {
let paths: Vec<PathBuf> = [PROXY_DB, BLOBS_DB]
.iter()
.map(|name| data_dir.join(name))
.filter(|p| encryption::file_state(p).ok() == Some(FileState::Plain))
.collect();
let total = paths.iter().map(|p| encryption::plain_size(p)).sum::<u64>().max(1) as f64;
let mut before = 0u64;
let mut converted = false;
for path in &paths {
let size = encryption::plain_size(path);
let done = before;
let file_progress = move |written: u64| {
progress(((done + written.min(size)) as f64 / total).min(1.0));
};
converted |= encryption::encrypt_in_place(path, key, &file_progress)
.map_err(|e| format!("Failed to encrypt {}: {e}", path.display()))?;
before += size;
}
progress(1.0);
Ok(converted)
}
const KEY_UNAVAILABLE: &str =
"Yaak Proxy stores traffic encrypted and couldn't read its key from the keychain";
/// Why the databases cannot be opened, or the CA made, without the data key.
pub fn key_unavailable(reason: &str) -> String {
format!("{KEY_UNAVAILABLE}: {reason}. Allow it access, then retry.")
}
/// `reason` is [`key_unavailable`]'s: the keychain would not give up the key.
pub fn is_key_unavailable(reason: &str) -> bool {
reason.starts_with(KEY_UNAVAILABLE)
}
/// The functions filters use: `sidebar_path(url)`, the app sidebar's place for a URL, and
/// `under_site(url, site)`, for filtering by its nodes; `folder_name(dir)`, for naming a program
/// by its folder; and `is_system(bundle_id, path)`, for macOS's own daemons.
@@ -99,10 +256,24 @@ fn add_functions(conn: &mut rusqlite::Connection) -> rusqlite::Result<()> {
})
}
fn read_only_pool(path: &Path) -> Result<SqlitePool> {
fn read_only_pool(path: &Path, key: Option<&DatabaseKey>) -> Result<SqlitePool> {
encryption::init_crypto();
let key = match (encryption::file_state(path)?, key) {
(FileState::Plain, _) => None,
(_, Some(key)) => Some(key.clone()),
(_, None) => {
return Err(Error::Database(format!(
"{} is encrypted, with no key to read it",
path.display()
)));
}
};
let manager = SqliteConnectionManager::file(path)
.with_flags(OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX)
.with_init(|conn| {
.with_init(move |conn| {
if let Some(key) = &key {
encryption::apply_key(conn, key)?;
}
conn.busy_timeout(Duration::from_millis(5000))?;
add_functions(conn)
});
@@ -113,8 +284,11 @@ fn read_only_pool(path: &Path) -> Result<SqlitePool> {
.map_err(|e| Error::Database(e.to_string()))
}
fn file_pool(path: &Path, max_size: u32) -> Result<SqlitePool> {
let manager = SqliteConnectionManager::file(path).with_init(|conn| {
fn file_pool(path: &Path, max_size: u32, key: &DatabaseKey) -> Result<SqlitePool> {
encryption::init_crypto();
let key = key.clone();
let manager = SqliteConnectionManager::file(path).with_init(move |conn| {
encryption::apply_key(conn, &key)?;
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.busy_timeout(Duration::from_millis(5000))?;
@@ -127,6 +301,21 @@ fn file_pool(path: &Path, max_size: u32) -> Result<SqlitePool> {
.map_err(|e| Error::Database(e.to_string()))
}
/// The key unit tests encrypt their databases with.
#[cfg(test)]
pub(crate) fn test_key() -> DatabaseKey {
DatabaseKey::from_bytes([7; 32])
}
/// A connection to a database encrypted with [`test_key`], for altering it as another build
/// would have.
#[cfg(test)]
pub(crate) fn test_conn(path: &Path) -> rusqlite::Connection {
let conn = rusqlite::Connection::open(path).unwrap();
encryption::apply_key(&conn, &test_key()).unwrap();
conn
}
#[cfg(test)]
mod tests {
use super::*;
@@ -142,10 +331,10 @@ mod tests {
use crate::models::Flow;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("proxy.db");
drop(ProxyQueryManager::new(&path).unwrap());
drop(ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap());
// As a build from before the saved request and client columns left it.
let conn = Connection::open(&path).unwrap();
let conn = test_conn(&path);
conn.execute_batch(
"ALTER TABLE flows DROP COLUMN saved_request_id;
ALTER TABLE flows DROP COLUMN client_pid;
@@ -164,7 +353,7 @@ mod tests {
.unwrap();
drop(conn);
let db = ProxyQueryManager::open_read_only(&path).unwrap();
let db = ProxyQueryManager::open_read_only(&path, Some(&test_key())).unwrap();
let flows = db.with_conn(|c| c.find_all::<Flow>()).unwrap();
assert_eq!(flows.len(), 1);
assert_eq!((flows[0].id.as_str(), flows[0].saved_request_id.as_deref()), ("fl_old", None));
@@ -178,7 +367,7 @@ mod tests {
// Filters by app work without the folder column, and count without the clear mark.
drop(db);
let conn = Connection::open(&path).unwrap();
let conn = test_conn(&path);
conn.execute_batch(
"ALTER TABLE flows ADD COLUMN client_name TEXT;
ALTER TABLE flows ADD COLUMN client_bundle_id TEXT;
@@ -189,7 +378,7 @@ mod tests {
)
.unwrap();
drop(conn);
let db = ProxyQueryManager::open_read_only(&path).unwrap();
let db = ProxyQueryManager::open_read_only(&path, Some(&test_key())).unwrap();
let filter =
crate::flows::FlowFilter { app: Some(vec!["curl".into()]), ..Default::default() };
let (page, total, matching) = crate::flows::page(&db, &filter).unwrap();
@@ -219,10 +408,10 @@ mod tests {
.unwrap();
drop(conn);
let db = ProxyQueryManager::new(&path).unwrap();
let db = ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap();
drop(db);
let conn = Connection::open(&path).unwrap();
let conn = test_conn(&path);
let tables: Vec<String> = conn
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
.unwrap()
@@ -312,9 +501,9 @@ mod tests {
.unwrap();
drop(conn);
drop(ProxyQueryManager::new(&path).unwrap());
drop(ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap());
let conn = Connection::open(&path).unwrap();
let conn = test_conn(&path);
assert!(columns(&conn, "flows").contains(&"client_cwd".to_string()));
let applied: Vec<String> = conn
.prepare("SELECT version FROM _sqlx_migrations ORDER BY version")
@@ -329,8 +518,9 @@ mod tests {
drop(conn);
// The stream and its messages come through, and clearing then deleting takes both.
let db = ProxyQueryManager::new(&path).unwrap();
let blobs = yaak_models::init_blob_store(dir.path().join("blobs.sqlite")).unwrap();
let db = ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap();
let blobs = crate::db::open_blobs(&dir.path().join("blobs.sqlite"), &crate::db::test_key())
.unwrap();
let listed = crate::flows::list(&db, &Default::default()).unwrap();
assert_eq!(listed.len(), 1);
assert_eq!((listed[0].id.as_str(), listed[0].message_count), ("fl_ws", 2));