kdf: version Argon2id profiles and raise the default to 64 MiB / t=3
All checks were successful
ci / test (pull_request) Successful in 29m38s
ci / sdk (pull_request) Successful in 2m7s

The store and identity backup shared one hard-coded Argon2id profile
(m=19456 KiB, t=2, p=1) with nothing recorded on disk, so changing it
would have bricked every existing store and backup.

Record the profile with the data and raise the default:
- KdfProfile { Legacy = 0, Current = 1 }; Current is m=65536 KiB,
  t=3, p=1, out=32.
- Backups: seal() writes a profile byte after owbak1. Legacy blobs
  (exactly SEALED_BODY_LEN after MAGIC) still open; an unknown id is
  an error, never a fallback.
- Stores: store_meta gains kdf_profile (additive, default 0). The
  SQLCipher file key has no place to record a profile before the db
  opens, so a legacy file is detected by trial-opening with the
  legacy profile, then rekeyed to Current in one SQLCipher
  transaction; store_meta is re-wrapped (salt + ciphertext + profile)
  in a single transaction on the first successful unlock. Both are
  one-shot: the next start takes the current path.
- docs/THREAT_MODEL.md states the new params and the versioning.

Measured in release on this host: kdf legacy 0.018s / current 0.095s;
Store reopen current 0.354s, legacy upgrade path 0.528s.
This commit is contained in:
rust-dev 2026-10-22 22:29:28 -04:00
commit 8f959e937f
No known key found for this signature in database
3 changed files with 460 additions and 32 deletions

View file

@ -293,7 +293,8 @@ impl Store {
CREATE TABLE IF NOT EXISTS store_meta (
id INTEGER PRIMARY KEY CHECK (id = 1),
kdf_salt BLOB NOT NULL,
wrapped_key BLOB NOT NULL
wrapped_key BLOB NOT NULL,
kdf_profile INTEGER NOT NULL DEFAULT 0
);
-- The wallet child's RPC creds + chain-source snapshot. One row,
-- sealed with the store data key (see `save_wallet_child`): the
@ -692,6 +693,13 @@ impl Store {
"payload",
"ALTER TABLE outbox ADD COLUMN payload BLOB",
)?;
// Which Argon2id profile wraps `store_meta.wrapped_key`. Rows written
// before the column existed are the legacy profile (id 0).
self.add_column_if_missing(
"store_meta",
"kdf_profile",
"ALTER TABLE store_meta ADD COLUMN kdf_profile INTEGER NOT NULL DEFAULT 0",
)?;
// `insert_payment` has accepted `kind = "tip"` since the tip path
// landed, but the table's CHECK only allowed invoice/receipt, so every
// tip insert (inbound *and* outbound) failed the constraint and the
@ -741,17 +749,18 @@ impl Store {
}
fn unlock_messages(&mut self, passphrase: &str) -> Result<()> {
let row: Option<(Vec<u8>, Vec<u8>)> = self
let row: Option<(Vec<u8>, Vec<u8>, i64)> = self
.conn
.query_row(
"SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1",
"SELECT kdf_salt, wrapped_key, kdf_profile FROM store_meta WHERE id = 1",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?;
match row {
Some((salt, wrapped)) => {
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
Some((salt, wrapped, profile_id)) => {
let profile = kdf_profile_from_id(profile_id)?;
let wrap_key = crate::backup::kdf_with(profile, passphrase, &salt)?;
// The unwrapped data key lands in a Zeroizing buffer immediately.
let raw = Zeroizing::new(
crate::backup::aead_decrypt(&wrap_key, &wrapped, b"")
@ -761,6 +770,11 @@ impl Store {
return Err(Error("wrapped message key length".into()));
}
self.msg_key.copy_from_slice(&raw);
// The passphrase proved itself: a legacy wrap is re-wrapped
// with the current profile once, in one transaction.
if profile != crate::backup::KdfProfile::Current {
self.rewrap_store_meta(passphrase)?;
}
self.rewrap_empty_aad_messages()?;
Ok(())
}
@ -772,8 +786,13 @@ impl Store {
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?;
self.conn.execute(
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
params![salt.as_slice(), wrapped],
"INSERT INTO store_meta (id, kdf_salt, wrapped_key, kdf_profile)
VALUES (1, ?1, ?2, ?3)",
params![
salt.as_slice(),
wrapped,
i64::from(crate::backup::KdfProfile::CURRENT_ID)
],
)?;
self.msg_key = data_key;
self.reencrypt_legacy_messages()?;
@ -782,6 +801,27 @@ impl Store {
}
}
/// One-shot upgrade of a legacy-profile wrap to the current KDF profile.
/// Salt, ciphertext and profile id move together in a single transaction.
fn rewrap_store_meta(&mut self, passphrase: &str) -> Result<()> {
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, &self.msg_key[..], b"")?;
let tx = self.conn.unchecked_transaction()?;
tx.execute(
"UPDATE store_meta SET kdf_salt = ?1, wrapped_key = ?2, kdf_profile = ?3
WHERE id = 1",
params![
salt.as_slice(),
wrapped,
i64::from(crate::backup::KdfProfile::CURRENT_ID)
],
)?;
tx.commit()?;
Ok(())
}
fn reencrypt_legacy_messages(&self) -> Result<()> {
let mut stmt = self
.conn
@ -1748,8 +1788,41 @@ fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result<Connec
your backup, or restore the db from backup and re-import"
)));
};
// The SQLCipher file key is KDF(passphrase, store_salt) with no recorded
// profile: the file itself says which one opened it. A legacy store is
// opened with the legacy profile and immediately rekeyed to the current
// one, so the next start takes the fast path.
let key = crate::backup::kdf(passphrase, &salt)?;
open_keyed(db_path, &key)
match open_keyed(db_path, &key) {
Ok(conn) => Ok(conn),
Err(_) => {
let legacy_key =
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, passphrase, &salt)?;
let conn = open_keyed(db_path, &legacy_key)
.map_err(|_| Error("wrong passphrase or corrupt store".into()))?;
rekey_store(&conn, &key)?;
Ok(conn)
}
}
}
/// Rewrite every page of an open store under `new_key` in one transaction.
/// SQLCipher rolls the rekey back if any page write fails.
fn rekey_store(conn: &Connection, new_key: &[u8; 32]) -> Result<()> {
// Old-keyed WAL frames must be folded in before the rewrite, or they would
// replay under a key that no longer opens them.
conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
let pragma = Zeroizing::new(format!(
"PRAGMA rekey = \"x'{hex}'\"",
hex = fingerprint(new_key)
));
conn.execute_batch(pragma.as_str())
.map_err(|e| Error(format!("store rekey: {e}")))?;
conn.query_row("SELECT count(*) FROM sqlite_master", [], |r| {
r.get::<_, i64>(0)
})
.map_err(|_| Error("store rekey failed".into()))?;
Ok(())
}
/// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is
@ -1777,20 +1850,50 @@ fn pragma_key(key: &[u8; 32]) -> Zeroizing<String> {
/// 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 {
let Some((salt, wrapped, profile_id)) = read_store_meta(conn)? else {
return Ok(true);
};
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
let profile = kdf_profile_from_id(profile_id)?;
let wrap_key = crate::backup::kdf_with(profile, passphrase, &salt)?;
Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok())
}
/// `(kdf_salt, wrapped_key, kdf_profile)`.
type StoreMetaRow = (Vec<u8>, Vec<u8>, i64);
/// Read the `store_meta` row, tolerating a table that predates `kdf_profile`
/// (a v0.2.1 plaintext store), where the profile is the legacy one.
fn read_store_meta(conn: &Connection) -> Result<Option<StoreMetaRow>> {
let has_profile: i64 = conn.query_row(
"SELECT COUNT(*) FROM pragma_table_info('store_meta') WHERE name = 'kdf_profile'",
[],
|r| r.get(0),
)?;
let Some((salt, wrapped, profile)) = (if has_profile > 0 {
conn.query_row(
"SELECT kdf_salt, wrapped_key, kdf_profile FROM store_meta WHERE id = 1",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?
} else {
conn.query_row(
"SELECT kdf_salt, wrapped_key, 0 FROM store_meta WHERE id = 1",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?
}) else {
return Ok(None);
};
Ok(Some((salt, wrapped, profile)))
}
fn kdf_profile_from_id(id: i64) -> Result<crate::backup::KdfProfile> {
let id = u8::try_from(id).map_err(|_| Error(format!("unknown kdf profile {id}")))?;
crate::backup::KdfProfile::from_id(id).map_err(Error)
}
/// 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.
@ -2271,7 +2374,8 @@ mod at_rest {
OsRng.fill_bytes(&mut salt);
let mut data_key = Zeroizing::new([0u8; 32]);
OsRng.fill_bytes(&mut data_key[..]);
let wrap = crate::backup::kdf(passphrase, &salt).unwrap();
let wrap =
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, 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)",
@ -2661,4 +2765,174 @@ mod at_rest {
assert_eq!(store.list_wallets().unwrap().len(), 1);
assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row);
}
/// Turn a freshly created store into the exact pre-profile shape: the
/// SQLCipher file keyed with the legacy Argon2id params, and the message
/// key wrapped under the legacy profile with no meaningful profile id.
/// Returns the (salt, wrapped) pair that must be replaced by the upgrade.
fn downgrade_to_legacy_profile(dir: &Path, pass: &str) -> (Vec<u8>, Vec<u8>) {
let store = Store::open_at_with_passphrase(dir, pass).unwrap();
let data_key = *store.msg_key;
let salt: [u8; 16] = fs::read(dir.join(SALT_FILE)).unwrap().try_into().unwrap();
let legacy_db_key =
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &salt).unwrap();
let wrap_salt = [0x33u8; 16];
let legacy_wrap =
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &wrap_salt).unwrap();
let wrapped = crate::backup::aead_encrypt(&legacy_wrap, &data_key[..], b"").unwrap();
store
.conn
.execute(
"UPDATE store_meta SET kdf_salt = ?1, wrapped_key = ?2, kdf_profile = 0
WHERE id = 1",
params![wrap_salt.as_slice(), wrapped.clone()],
)
.unwrap();
store
.conn
.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")
.unwrap();
store
.conn
.execute_batch(&format!(
"PRAGMA rekey = \"x'{hex}'\"",
hex = fingerprint(&legacy_db_key[..])
))
.unwrap();
drop(store);
(wrap_salt.to_vec(), wrapped)
}
fn store_meta_parts(dir: &Path, pass: &str) -> (Vec<u8>, Vec<u8>, i64) {
let salt: [u8; 16] = fs::read(dir.join(SALT_FILE)).unwrap().try_into().unwrap();
let key = crate::backup::kdf(pass, &salt).unwrap();
let db = dir.join("onionwire.db");
let conn = open_keyed(&db, &key)
.or_else(|_| {
let legacy =
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &salt)?;
open_keyed(&db, &legacy)
})
.unwrap();
conn.query_row(
"SELECT kdf_salt, wrapped_key, kdf_profile FROM store_meta WHERE id = 1",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.unwrap()
}
#[test]
fn a_legacy_store_opens_and_upgrades_its_kdf_profile_exactly_once() {
let dir = tempfile::tempdir().unwrap();
let pass = "legacy-upgrade-pass";
let pk = [7u8; 32];
{
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
store.upsert_friend(&pk, "b.onion", None).unwrap();
store.append_message(&pk, "in", b"survives rekey").unwrap();
}
let (old_salt, old_wrapped) = downgrade_to_legacy_profile(dir.path(), pass);
assert_eq!(
store_meta_parts(dir.path(), pass).2,
0,
"fixture must start on the legacy profile"
);
let store = Store::open_at_with_passphrase(dir.path(), pass).expect("legacy upgrade");
assert_eq!(
store.list_messages(&pk).unwrap()[0].plaintext,
b"survives rekey",
"the rekey must not lose data"
);
let (salt, wrapped, profile) = store_meta_parts(dir.path(), pass);
assert_eq!(profile, i64::from(crate::backup::KdfProfile::CURRENT_ID));
assert_ne!(salt, old_salt, "upgrade must mint a fresh wrap salt");
assert_ne!(wrapped, old_wrapped, "upgrade must re-wrap the message key");
drop(store);
// The SQLCipher file itself moved to the current profile.
let file_salt: [u8; 16] = fs::read(dir.path().join(SALT_FILE))
.unwrap()
.try_into()
.unwrap();
let current = crate::backup::kdf(pass, &file_salt).unwrap();
assert!(
open_keyed(&dir.path().join("onionwire.db"), &current).is_ok(),
"store must be rekeyed to the current profile"
);
let legacy =
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &file_salt).unwrap();
assert!(
open_keyed(&dir.path().join("onionwire.db"), &legacy).is_err(),
"the legacy file key must no longer open the store"
);
// Second unlock is a no-op: the profile flip is one-shot.
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
let (salt2, wrapped2, profile2) = store_meta_parts(dir.path(), pass);
assert_eq!(profile2, i64::from(crate::backup::KdfProfile::CURRENT_ID));
assert_eq!((salt2, wrapped2), (salt, wrapped), "re-wrapped twice");
assert_eq!(store.list_messages(&pk).unwrap().len(), 1);
}
#[test]
#[ignore = "manual unlock timing measurement; run with --release --ignored"]
fn store_unlock_timing() {
use std::time::Instant;
let dir = tempfile::tempdir().unwrap();
let pass = "unlock-timing-pass";
let started = Instant::now();
drop(Store::open_at_with_passphrase(dir.path(), pass).unwrap());
eprintln!(
"first open (create): {:.3}s",
started.elapsed().as_secs_f64()
);
let started = Instant::now();
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
eprintln!(
"reopen, current profile: {:.3}s",
started.elapsed().as_secs_f64()
);
drop(store);
downgrade_to_legacy_profile(dir.path(), pass);
let started = Instant::now();
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
eprintln!(
"reopen, legacy store (open + rekey + rewrap): {:.3}s",
started.elapsed().as_secs_f64()
);
drop(store);
let started = Instant::now();
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
eprintln!(
"reopen after upgrade: {:.3}s",
started.elapsed().as_secs_f64()
);
drop(store);
}
#[test]
fn an_unknown_store_kdf_profile_is_a_clean_error() {
let dir = tempfile::tempdir().unwrap();
let pass = "unknown-profile-pass";
{
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
store
.conn
.execute("UPDATE store_meta SET kdf_profile = 9 WHERE id = 1", [])
.unwrap();
}
let err = match Store::open_at_with_passphrase(dir.path(), pass) {
Ok(_) => panic!("an unknown kdf profile must not fall back to legacy params"),
Err(e) => e,
};
assert!(
err.to_string().contains("unknown kdf profile 9"),
"got {err}"
);
}
}