feat(store): encrypt chat bodies at rest; Ctrl-Q CLEAR/QUIT
All checks were successful
ci / test (pull_request) Successful in 3m13s

Wrap a random 32-byte message key with Argon2id+ChaCha20-Poly1305.
sqlite messages.plaintext is nonce||ciphertext; identity keys stay
plaintext. Empty/wrong passphrase fails closed. Ctrl-Q types CLEAR or
QUIT then Enter (Esc cancels).
This commit is contained in:
Sirius DevOps 2026-09-10 17:19:50 -04:00
commit 6323619d80
No known key found for this signature in database
16 changed files with 461 additions and 35 deletions

View file

@ -4,6 +4,7 @@ use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use ed25519_dalek::SigningKey;
use rand::RngCore;
use rand::rngs::OsRng;
use rusqlite::{Connection, OptionalExtension, params};
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
@ -33,8 +34,15 @@ impl From<std::io::Error> for Error {
}
}
impl From<String> for Error {
fn from(e: String) -> Self {
Self(e)
}
}
pub struct Store {
conn: Connection,
msg_key: [u8; 32],
}
pub struct SelfIdentity {
@ -100,6 +108,13 @@ impl Store {
}
pub fn open_at(home: &Path) -> Result<Self> {
Self::open_at_with_passphrase(home, &passphrase_from_env()?)
}
pub fn open_at_with_passphrase(home: &Path, passphrase: &str) -> Result<Self> {
if passphrase.is_empty() {
return Err(Error("empty passphrase".into()));
}
mkdir_700(home)?;
mkdir_700(&home.join("arti"))?;
let db_path = home.join("onionwire.db");
@ -153,6 +168,11 @@ impl Store {
xmr_addr TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS store_meta (
id INTEGER PRIMARY KEY CHECK (id = 1),
kdf_salt BLOB NOT NULL,
wrapped_key BLOB NOT NULL
);
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
@ -172,9 +192,13 @@ impl Store {
if check != "ok" {
return Err(Error(format!("integrity_check: {check}")));
}
let store = Self { conn };
let mut store = Self {
conn,
msg_key: [0u8; 32],
};
store.migrate()?;
store.ensure_self()?;
store.unlock_messages(passphrase)?;
Ok(store)
}
@ -234,6 +258,66 @@ impl Store {
Ok(())
}
fn unlock_messages(&mut self, passphrase: &str) -> Result<()> {
let row: Option<(Vec<u8>, Vec<u8>)> = self
.conn
.query_row(
"SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
match row {
Some((salt, wrapped)) => {
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
let raw = crate::backup::aead_decrypt(&wrap_key, &wrapped)
.map_err(|_| Error("wrong passphrase".into()))?;
if raw.len() != 32 {
return Err(Error("wrapped message key length".into()));
}
self.msg_key.copy_from_slice(&raw);
Ok(())
}
None => {
let mut data_key = [0u8; 32];
OsRng.fill_bytes(&mut data_key);
let mut salt = [0u8; 16];
OsRng.fill_bytes(&mut salt);
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key)?;
self.conn.execute(
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
params![salt.as_slice(), wrapped],
)?;
self.msg_key = data_key;
self.reencrypt_legacy_messages()?;
Ok(())
}
}
}
fn reencrypt_legacy_messages(&self) -> Result<()> {
let mut stmt = self.conn.prepare("SELECT id, plaintext FROM messages")?;
let rows: Vec<(i64, Vec<u8>)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
.collect::<std::result::Result<_, _>>()?;
drop(stmt);
if rows.is_empty() {
return Ok(());
}
let tx = self.conn.unchecked_transaction()?;
for (id, plain) in rows {
let blob = crate::backup::aead_encrypt(&self.msg_key, &plain)?;
tx.execute(
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
params![blob, id],
)?;
}
tx.commit()?;
let _ = self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
Ok(())
}
fn add_column_if_missing(&self, table: &str, column: &str, ddl: &str) -> Result<()> {
let sql =
format!("SELECT COUNT(*) FROM pragma_table_info('{table}') WHERE name = '{column}'");
@ -562,9 +646,10 @@ impl Store {
|row| row.get(0),
)
.map_err(|_| Error("friend not found".into()))?;
let blob = crate::backup::aead_encrypt(&self.msg_key, plaintext)?;
self.conn.execute(
"INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (?1, ?2, ?3, ?4)",
params![friend_id, dir, plaintext, unix_now()],
params![friend_id, dir, blob, unix_now()],
)?;
Ok(())
}
@ -577,14 +662,14 @@ impl Store {
ORDER BY m.id",
)?;
let rows = stmt.query_map(params![friend_pk], |row| {
Ok(Message {
dir: row.get(0)?,
plaintext: row.get(1)?,
})
Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?))
})?;
let mut out = Vec::new();
for row in rows {
out.push(row?);
let (dir, blob) = row?;
let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob)
.map_err(|_| Error("message decrypt failed".into()))?;
out.push(Message { dir, plaintext });
}
Ok(out)
}
@ -657,6 +742,14 @@ fn home_dir() -> Result<PathBuf> {
Ok(PathBuf::from(home).join(".local/share/onionwire"))
}
fn passphrase_from_env() -> Result<String> {
match std::env::var("ONIONWIRE_STORE_PASSPHRASE") {
Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())),
Ok(p) => Ok(p),
Err(_) => Err(Error("ONIONWIRE_STORE_PASSPHRASE required".into())),
}
}
fn mkdir_700(path: &Path) -> Result<()> {
fs::create_dir_all(path)?;
let mut perms = fs::metadata(path)?.permissions();
@ -675,3 +768,45 @@ fn unix_now() -> i64 {
fn fingerprint(pubkey: &[u8]) -> String {
pubkey.iter().map(|b| format!("{b:02x}")).collect()
}
#[cfg(test)]
mod at_rest {
use super::*;
#[test]
fn first_unlock_reencrypts_legacy_plaintext_rows() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "migrate-pass").unwrap();
let pk = [1u8; 32];
store.upsert_friend(&pk, "a.onion", None).unwrap();
store
.append_message(&pk, "out", b"legacy-plain-xyz")
.unwrap();
store.conn.execute("DELETE FROM store_meta", []).unwrap();
store
.conn
.execute(
"UPDATE messages SET plaintext = ?1",
params![b"legacy-plain-xyz".as_slice()],
)
.unwrap();
let _ = store.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
drop(store);
let store = Store::open_at_with_passphrase(dir.path(), "migrate-pass").unwrap();
let msgs = store.list_messages(&pk).unwrap();
assert_eq!(msgs[0].plaintext, b"legacy-plain-xyz");
drop(store);
let needle = b"legacy-plain-xyz";
for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] {
let path = dir.path().join(name);
let Ok(bytes) = std::fs::read(&path) else {
continue;
};
assert!(
!bytes.windows(needle.len()).any(|w| w == needle),
"{name} still contains legacy plaintext"
);
}
}
}