feat(store): encrypt the whole sqlite store with SQLCipher
All checks were successful
ci / test (pull_request) Successful in 3m35s
All checks were successful
ci / test (pull_request) Successful in 3m35s
The db held the ed25519 identity secret, friend pubkeys, locators, profiles and payment rows in the clear; only chat bodies were encrypted. Switch rusqlite to `bundled-sqlcipher-vendored-openssl` and open every store with `PRAGMA key = "x'<64 hex>'"` as the first statement after open, using the existing Argon2id output as a raw key (no second KDF pass). The per-install KDF salt moves out of the db into `store_salt` (0600) — a key cannot be derived from a salt that lives inside the file it opens. The per-message ChaCha20-Poly1305 + row-AAD layer is unchanged: whole-db encryption does not defend against ciphertext swapped between rows, the AAD does. v0.2.1 installs are plaintext. The first open with the right passphrase upgrades in place (WAL checkpoint, ATTACH ... KEY, sqlcipher_export) and only swaps the file after the new one opens, passes integrity_check and unwraps store_meta. A wrong passphrase leaves the plaintext file untouched; a missing `store_salt` next to an encrypted db refuses to open rather than guessing. SQLCipher's internal "hmac check failed" ERROR on a rejected key is suppressed (cipher_log_level = NONE) so a typo'd passphrase is not an error dump. docs/THREAT_MODEL.md: the store is now encrypted at rest; sqlcipher leaves the "Out of v1" list.
This commit is contained in:
parent
e6e2a158a8
commit
e7b37ccb40
5 changed files with 551 additions and 8 deletions
389
src/store.rs
389
src/store.rs
|
|
@ -1,4 +1,5 @@
|
|||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
|
@ -119,7 +120,7 @@ impl Store {
|
|||
mkdir_700(&home.join("arti"))?;
|
||||
mkdir_700(&home.join("cache"))?;
|
||||
let db_path = home.join("onionwire.db");
|
||||
let conn = Connection::open(&db_path)?;
|
||||
let conn = open_store_db(home, &db_path, passphrase)?;
|
||||
let journal: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?;
|
||||
if !journal.eq_ignore_ascii_case("wal") {
|
||||
return Err(Error(format!("journal_mode WAL failed: {journal}")));
|
||||
|
|
@ -815,6 +816,187 @@ fn gen_prekey() -> (Vec<u8>, Vec<u8>) {
|
|||
(sk.to_bytes().to_vec(), pk.to_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// Per-install KDF salt for the whole-database key. Not secret (a salt never
|
||||
/// is); kept in the data dir so the db key never has to live inside the db it
|
||||
/// opens.
|
||||
const SALT_FILE: &str = "store_salt";
|
||||
const SQLITE_HEADER: &[u8] = b"SQLite format 3\0";
|
||||
|
||||
enum DbState {
|
||||
Missing,
|
||||
Empty,
|
||||
Plaintext,
|
||||
Encrypted,
|
||||
}
|
||||
|
||||
fn db_state(path: &Path) -> Result<DbState> {
|
||||
let meta = match fs::metadata(path) {
|
||||
Ok(m) => m,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(DbState::Missing),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if meta.len() == 0 {
|
||||
return Ok(DbState::Empty);
|
||||
}
|
||||
let mut head = [0u8; 16];
|
||||
let mut f = fs::File::open(path)?;
|
||||
match f.read_exact(&mut head) {
|
||||
Ok(()) if head.as_slice() == SQLITE_HEADER => Ok(DbState::Plaintext),
|
||||
Ok(()) => Ok(DbState::Encrypted),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(DbState::Encrypted),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_salt(path: &Path) -> Result<Option<[u8; 16]>> {
|
||||
match fs::read(path) {
|
||||
Ok(b) if b.len() == 16 => Ok(Some(b.try_into().expect("len checked"))),
|
||||
Ok(b) => Err(Error(format!("{SALT_FILE} has {} bytes, want 16", b.len()))),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_salt(path: &Path, salt: &[u8; 16]) -> Result<()> {
|
||||
fs::write(path, salt)?;
|
||||
let mut perms = fs::metadata(path)?.permissions();
|
||||
perms.set_mode(0o600);
|
||||
fs::set_permissions(path, perms)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn random_salt() -> [u8; 16] {
|
||||
let mut salt = [0u8; 16];
|
||||
OsRng.fill_bytes(&mut salt);
|
||||
salt
|
||||
}
|
||||
|
||||
/// Opens the store, creating it encrypted and upgrading a v0.2.1 plaintext
|
||||
/// file in place. Any failure before the swap leaves the old file untouched.
|
||||
fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result<Connection> {
|
||||
let salt_path = home.join(SALT_FILE);
|
||||
let mut salt = read_salt(&salt_path)?;
|
||||
match db_state(db_path)? {
|
||||
DbState::Plaintext => {
|
||||
let conn = Connection::open(db_path)?;
|
||||
let ok = wrapped_key_opens(&conn, passphrase)?;
|
||||
drop(conn);
|
||||
if !ok {
|
||||
return Err(Error("wrong passphrase".into()));
|
||||
}
|
||||
let s = salt.unwrap_or_else(random_salt);
|
||||
let key = crate::backup::kdf(passphrase, &s)?;
|
||||
write_salt(&salt_path, &s)?;
|
||||
migrate_plaintext_to_encrypted(db_path, &key, passphrase)?;
|
||||
salt = Some(s);
|
||||
}
|
||||
DbState::Missing | DbState::Empty => {
|
||||
if salt.is_none() {
|
||||
let s = random_salt();
|
||||
write_salt(&salt_path, &s)?;
|
||||
salt = Some(s);
|
||||
}
|
||||
}
|
||||
DbState::Encrypted => {}
|
||||
}
|
||||
let Some(salt) = salt else {
|
||||
return Err(Error(format!(
|
||||
"{SALT_FILE} is missing next to an encrypted onionwire.db; restore it from \
|
||||
your backup, or restore the db from backup and re-import"
|
||||
)));
|
||||
};
|
||||
let key = crate::backup::kdf(passphrase, &salt)?;
|
||||
open_keyed(db_path, &key)
|
||||
}
|
||||
|
||||
/// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is
|
||||
/// the key, with no second KDF pass over it.
|
||||
fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result<Connection> {
|
||||
let conn = Connection::open(db_path)?;
|
||||
conn.execute_batch(&pragma_key(key))?;
|
||||
// A rejected key otherwise logs SQLCipher's internal "hmac check failed"
|
||||
// at ERROR to stderr. A wrong passphrase is a normal user error here.
|
||||
let _ = conn.execute_batch("PRAGMA cipher_log_level = NONE");
|
||||
// Force a read so a wrong key fails here, not on the first later query.
|
||||
conn.query_row("SELECT count(*) FROM sqlite_master", [], |r| {
|
||||
r.get::<_, i64>(0)
|
||||
})
|
||||
.map_err(|_| Error("wrong passphrase or corrupt store".into()))?;
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
fn pragma_key(key: &[u8; 32]) -> String {
|
||||
format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key))
|
||||
}
|
||||
|
||||
/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh
|
||||
/// store) accepts any passphrase, matching the v0.2.1 behaviour.
|
||||
fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result<bool> {
|
||||
let row: Option<(Vec<u8>, Vec<u8>)> = conn
|
||||
.query_row(
|
||||
"SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1",
|
||||
[],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((salt, wrapped)) = row else {
|
||||
return Ok(true);
|
||||
};
|
||||
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
||||
Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok())
|
||||
}
|
||||
|
||||
/// Rewrites a plaintext sqlite store as an encrypted one and swaps it in.
|
||||
/// The source file is only replaced after the new file opens, passes
|
||||
/// `integrity_check` and unlocks with this passphrase.
|
||||
fn migrate_plaintext_to_encrypted(db_path: &Path, key: &[u8; 32], passphrase: &str) -> Result<()> {
|
||||
let mut tmp_name = db_path.as_os_str().to_owned();
|
||||
tmp_name.push(".migrating");
|
||||
let tmp = PathBuf::from(tmp_name);
|
||||
let _ = fs::remove_file(&tmp);
|
||||
let mode = fs::metadata(db_path)?.permissions().mode() & 0o777;
|
||||
|
||||
{
|
||||
// Fold the WAL in so the export sees every committed row.
|
||||
let conn = Connection::open(db_path)?;
|
||||
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
|
||||
let target = tmp.to_string_lossy().replace('\'', "''");
|
||||
conn.execute_batch(&format!(
|
||||
"ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";",
|
||||
hex = fingerprint(key)
|
||||
))?;
|
||||
conn.execute_batch("SELECT sqlcipher_export('enc');")?;
|
||||
conn.execute_batch("DETACH DATABASE enc;")?;
|
||||
}
|
||||
|
||||
let verified = (|| -> Result<()> {
|
||||
let conn = open_keyed(&tmp, key)?;
|
||||
let check: String = conn.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
|
||||
if check != "ok" {
|
||||
return Err(Error(format!("migration integrity_check: {check}")));
|
||||
}
|
||||
if !wrapped_key_opens(&conn, passphrase)? {
|
||||
return Err(Error("migrated store failed to unlock".into()));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = verified {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
fs::rename(&tmp, db_path)?;
|
||||
let mut perms = fs::metadata(db_path)?.permissions();
|
||||
perms.set_mode(mode);
|
||||
fs::set_permissions(db_path, perms)?;
|
||||
for suffix in ["-wal", "-shm"] {
|
||||
let mut stale = db_path.as_os_str().to_owned();
|
||||
stale.push(suffix);
|
||||
let _ = fs::remove_file(PathBuf::from(stale));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn home_dir() -> Result<PathBuf> {
|
||||
if let Some(p) = std::env::var_os("ONIONWIRE_HOME") {
|
||||
return Ok(PathBuf::from(p));
|
||||
|
|
@ -1027,6 +1209,211 @@ mod at_rest {
|
|||
}
|
||||
}
|
||||
|
||||
/// The exact v0.2.1 on-disk layout, hand-built: a plaintext sqlite file with
|
||||
/// the identity row in the clear, a `store_meta` row holding the
|
||||
/// Argon2id-wrapped message key and ChaCha20-Poly1305 message rows bound to
|
||||
/// their row AAD. Pin it here so the migration test cannot drift with the
|
||||
/// production schema.
|
||||
const LEGACY_SCHEMA: &str = "
|
||||
CREATE TABLE friends (
|
||||
id INTEGER PRIMARY KEY,
|
||||
pubkey BLOB NOT NULL UNIQUE,
|
||||
fingerprint TEXT NOT NULL,
|
||||
petname TEXT,
|
||||
onion TEXT NOT NULL,
|
||||
onion_updated_at INTEGER NOT NULL,
|
||||
added_at INTEGER NOT NULL,
|
||||
last_connect_ok INTEGER NOT NULL DEFAULT 1,
|
||||
prekey BLOB NOT NULL DEFAULT x''
|
||||
);
|
||||
CREATE TABLE messages (
|
||||
id INTEGER PRIMARY KEY,
|
||||
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
||||
dir TEXT NOT NULL CHECK(dir IN ('in','out')),
|
||||
plaintext BLOB NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE self (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
identity_sk BLOB NOT NULL,
|
||||
identity_pk BLOB NOT NULL,
|
||||
onion TEXT NOT NULL,
|
||||
onion_rotated_at INTEGER NOT NULL,
|
||||
prekey_sk BLOB NOT NULL,
|
||||
prekey_pk BLOB NOT NULL,
|
||||
hs_nickname TEXT NOT NULL DEFAULT 'ow0'
|
||||
);
|
||||
CREATE TABLE self_profile (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
display_name TEXT NOT NULL DEFAULT '',
|
||||
bio TEXT NOT NULL DEFAULT '',
|
||||
xmr_addr TEXT NOT NULL DEFAULT '',
|
||||
updated_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE friend_profiles (
|
||||
pubkey BLOB PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
bio TEXT NOT NULL,
|
||||
xmr_addr TEXT NOT NULL DEFAULT '',
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE store_meta (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
kdf_salt BLOB NOT NULL,
|
||||
wrapped_key BLOB NOT NULL
|
||||
);
|
||||
CREATE TABLE payments (
|
||||
id INTEGER PRIMARY KEY,
|
||||
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
||||
dir TEXT NOT NULL CHECK(dir IN ('in','out')),
|
||||
kind TEXT NOT NULL CHECK(kind IN ('invoice','receipt')),
|
||||
amount_atomic TEXT NOT NULL,
|
||||
address TEXT NOT NULL,
|
||||
memo TEXT NOT NULL DEFAULT '',
|
||||
txid TEXT,
|
||||
verified INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
|
||||
";
|
||||
|
||||
const LEGACY_IDENTITY_SK: [u8; 32] = [0x11; 32];
|
||||
const LEGACY_FRIEND_PK: [u8; 32] = [0x55; 32];
|
||||
|
||||
/// Writes a v0.2.1 store at `db_path` with no encryption at all.
|
||||
fn write_legacy_plaintext_store(db_path: &Path, passphrase: &str) {
|
||||
let conn = Connection::open(db_path).unwrap();
|
||||
conn.execute_batch(LEGACY_SCHEMA).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname)
|
||||
VALUES (1, ?1, ?2, 'legacy.onion', 7, ?3, ?4, 'ow0')",
|
||||
params![
|
||||
LEGACY_IDENTITY_SK.to_vec(),
|
||||
vec![0x22u8; 32],
|
||||
vec![0x33u8; 32],
|
||||
vec![0x44u8; 32]
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO friends (pubkey, fingerprint, petname, onion, onion_updated_at, added_at, last_connect_ok, prekey)
|
||||
VALUES (?1, ?2, 'legacy-friend', 'legacy-friend.onion', 7, 7, 1, x'')",
|
||||
params![LEGACY_FRIEND_PK.as_slice(), fingerprint(&LEGACY_FRIEND_PK)],
|
||||
)
|
||||
.unwrap();
|
||||
let mut salt = [0u8; 16];
|
||||
OsRng.fill_bytes(&mut salt);
|
||||
let mut data_key = [0u8; 32];
|
||||
OsRng.fill_bytes(&mut data_key);
|
||||
let wrap = crate::backup::kdf(passphrase, &salt).unwrap();
|
||||
let wrapped = crate::backup::aead_encrypt(&wrap, &data_key, b"").unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
||||
params![salt.as_slice(), wrapped],
|
||||
)
|
||||
.unwrap();
|
||||
for (dir, body) in [
|
||||
("in", "legacy-body-xyz"),
|
||||
("out", "legacy-reply-xyz"),
|
||||
] {
|
||||
conn.execute(
|
||||
"INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)",
|
||||
params![dir],
|
||||
)
|
||||
.unwrap();
|
||||
let id = conn.last_insert_rowid();
|
||||
let blob = crate::backup::aead_encrypt(
|
||||
&data_key,
|
||||
body.as_bytes(),
|
||||
&message_aad(1, dir, id),
|
||||
)
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
||||
params![blob, id],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
conn.close().unwrap();
|
||||
}
|
||||
|
||||
fn file_has(path: &Path, needle: &[u8]) -> bool {
|
||||
let Ok(bytes) = std::fs::read(path) else {
|
||||
return false;
|
||||
};
|
||||
bytes.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plaintext_v0_2_1_store_is_encrypted_in_place_and_keeps_history() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db_path = dir.path().join("onionwire.db");
|
||||
write_legacy_plaintext_store(&db_path, "legacy-pass");
|
||||
let raw = std::fs::read(&db_path).unwrap();
|
||||
assert!(
|
||||
raw.starts_with(b"SQLite format 3\0"),
|
||||
"fixture must be a plaintext sqlite file"
|
||||
);
|
||||
|
||||
let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
|
||||
assert_eq!(store.self_identity().unwrap().identity_sk, LEGACY_IDENTITY_SK);
|
||||
let msgs = store.list_messages(&LEGACY_FRIEND_PK).unwrap();
|
||||
assert_eq!(msgs.len(), 2, "history must survive the upgrade");
|
||||
assert_eq!(msgs[0].plaintext, b"legacy-body-xyz");
|
||||
assert_eq!(msgs[1].plaintext, b"legacy-reply-xyz");
|
||||
assert_eq!(
|
||||
store.get_friend(&LEGACY_FRIEND_PK).unwrap().unwrap().onion,
|
||||
"legacy-friend.onion"
|
||||
);
|
||||
drop(store);
|
||||
|
||||
let enc = std::fs::read(&db_path).unwrap();
|
||||
assert!(
|
||||
!enc.starts_with(b"SQLite format 3\0"),
|
||||
"db header must be encrypted after the in-place upgrade"
|
||||
);
|
||||
for (needle, what) in [
|
||||
(b"legacy-body-xyz".to_vec(), "message body"),
|
||||
(fingerprint(&LEGACY_FRIEND_PK).into_bytes(), "friend pubkey hex"),
|
||||
(LEGACY_IDENTITY_SK.to_vec(), "identity secret"),
|
||||
(b"legacy-friend.onion".to_vec(), "locator"),
|
||||
] {
|
||||
assert!(
|
||||
!file_has(&db_path, &needle),
|
||||
"upgraded db still contains the {what}"
|
||||
);
|
||||
}
|
||||
|
||||
let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("reopen");
|
||||
assert_eq!(store.list_messages(&LEGACY_FRIEND_PK).unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_plaintext_store_with_wrong_passphrase_is_left_untouched() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db_path = dir.path().join("onionwire.db");
|
||||
write_legacy_plaintext_store(&db_path, "legacy-pass");
|
||||
let before = std::fs::read(&db_path).unwrap();
|
||||
|
||||
let err = match Store::open_at_with_passphrase(dir.path(), "wrong-pass") {
|
||||
Ok(_) => panic!("wrong passphrase must not open a legacy store"),
|
||||
Err(e) => e,
|
||||
};
|
||||
assert!(
|
||||
err.to_string().to_ascii_lowercase().contains("passphrase"),
|
||||
"got {err}"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(&db_path).unwrap(),
|
||||
before,
|
||||
"a failed legacy upgrade must not modify the plaintext db"
|
||||
);
|
||||
assert!(
|
||||
!dir.path().join("store_salt").exists(),
|
||||
"a failed legacy upgrade must not leave a salt file behind"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_unlock_reencrypts_legacy_plaintext_rows() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
Loading…
Reference in a new issue