kdf: version Argon2id profiles and raise the default to 64 MiB / t=3
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:
parent
36969a7e95
commit
8f959e937f
3 changed files with 460 additions and 32 deletions
|
|
@ -59,9 +59,18 @@ What this does **not** buy:
|
||||||
## Your store is encrypted
|
## Your store is encrypted
|
||||||
|
|
||||||
The sqlite store is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`).
|
The sqlite store is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`).
|
||||||
A 32-byte key is derived from the store passphrase with Argon2id (same params as
|
A 32-byte key is derived from the store passphrase with Argon2id — m =
|
||||||
identity backup) over a per-install 16-byte salt in `store_salt`, and handed to
|
65_536 KiB (64 MiB), t = 3, p = 1, out = 32 — over a per-install 16-byte salt
|
||||||
SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) — no second KDF pass over it.
|
in `store_salt`, and handed to SQLCipher as a **raw** key (`PRAGMA key =
|
||||||
|
"x'…'"`) — no second KDF pass over it. The identity backup and the
|
||||||
|
message-key wrap in `store_meta` use the same profile. Parameters are
|
||||||
|
versioned with the data: a backup blob names its profile in the header and
|
||||||
|
`store_meta.kdf_profile` names the store's, and an unknown profile id is a
|
||||||
|
clear error, never a silent fallback. Data written with the earlier
|
||||||
|
19_456 KiB / t=2 / p=1 profile still opens: a legacy store is rekeyed and its
|
||||||
|
message key re-wrapped with the current profile on the first successful
|
||||||
|
unlock, and a legacy backup file opens as-is (re-exporting it writes the
|
||||||
|
current profile).
|
||||||
The key is the first statement after open, so the file header, schema, identity
|
The key is the first statement after open, so the file header, schema, identity
|
||||||
secret key, friend public keys, locators, profiles, payment rows and the
|
secret key, friend public keys, locators, profiles, payment rows and the
|
||||||
per-friend ratchet session blobs (`ratchet_sessions`) are all ciphertext on
|
per-friend ratchet session blobs (`ratchet_sessions`) are all ciphertext on
|
||||||
|
|
|
||||||
165
src/backup.rs
165
src/backup.rs
|
|
@ -1,4 +1,9 @@
|
||||||
//! Encrypted identity backup. Onion (locator) is not included.
|
//! Encrypted identity backup. Onion (locator) is not included.
|
||||||
|
//!
|
||||||
|
//! `seal()` writes `owbak1 || profile(1) || salt(16) || nonce(12) || ct`.
|
||||||
|
//! The pre-profile `owbak1 || salt(16) || nonce(12) || ct` layout is still
|
||||||
|
//! accepted as [`KdfProfile::Legacy`]; the two are unambiguous because the
|
||||||
|
//! plaintext is a fixed [`PLAIN_LEN`], so only two total lengths are legal.
|
||||||
|
|
||||||
use argon2::{Algorithm, Argon2, Params, Version};
|
use argon2::{Algorithm, Argon2, Params, Version};
|
||||||
use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload};
|
use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload};
|
||||||
|
|
@ -11,6 +16,52 @@ const SALT_LEN: usize = 16;
|
||||||
const NONCE_LEN: usize = 12;
|
const NONCE_LEN: usize = 12;
|
||||||
const KEY_LEN: usize = 32;
|
const KEY_LEN: usize = 32;
|
||||||
const PLAIN_LEN: usize = KEY_LEN * 4;
|
const PLAIN_LEN: usize = KEY_LEN * 4;
|
||||||
|
/// Salt + nonce + ciphertext + Poly1305 tag, i.e. everything after `MAGIC`.
|
||||||
|
const SEALED_BODY_LEN: usize = SALT_LEN + NONCE_LEN + PLAIN_LEN + 16;
|
||||||
|
|
||||||
|
/// Which Argon2id parameters a stored blob was written with.
|
||||||
|
///
|
||||||
|
/// The id is recorded with the data (a byte in the backup header, a
|
||||||
|
/// `store_meta.kdf_profile` column in the store). `Legacy` is id `0` and also
|
||||||
|
/// covers every blob written before profiles existed — those have no recorded
|
||||||
|
/// id at all. Never change an existing profile's parameters: a new cost means
|
||||||
|
/// a new id.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum KdfProfile {
|
||||||
|
/// m = 19_456 KiB, t = 2, p = 1.
|
||||||
|
Legacy,
|
||||||
|
/// m = 65_536 KiB (64 MiB), t = 3, p = 1.
|
||||||
|
Current,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KdfProfile {
|
||||||
|
pub(crate) const LEGACY_ID: u8 = 0;
|
||||||
|
pub(crate) const CURRENT_ID: u8 = 1;
|
||||||
|
|
||||||
|
pub(crate) fn id(self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Self::Legacy => Self::LEGACY_ID,
|
||||||
|
Self::Current => Self::CURRENT_ID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strict: an id this build does not know is an error, never a fallback.
|
||||||
|
pub(crate) fn from_id(id: u8) -> Result<Self, String> {
|
||||||
|
match id {
|
||||||
|
Self::LEGACY_ID => Ok(Self::Legacy),
|
||||||
|
Self::CURRENT_ID => Ok(Self::Current),
|
||||||
|
other => Err(format!("unknown kdf profile {other}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn params(self) -> Result<Params, String> {
|
||||||
|
let (m_cost, t_cost, p_cost) = match self {
|
||||||
|
Self::Legacy => (19_456, 2, 1),
|
||||||
|
Self::Current => (65_536, 3, 1),
|
||||||
|
};
|
||||||
|
Params::new(m_cost, t_cost, p_cost, Some(KEY_LEN)).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The identity bundle. Secret halves wipe on drop; `Debug` never prints them.
|
/// The identity bundle. Secret halves wipe on drop; `Debug` never prints them.
|
||||||
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
|
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
|
||||||
|
|
@ -58,14 +109,21 @@ impl BackupKeys {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<Zeroizing<[u8; 32]>, String> {
|
pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<Zeroizing<[u8; 32]>, String> {
|
||||||
|
kdf_with(KdfProfile::Current, passphrase, salt)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn kdf_with(
|
||||||
|
profile: KdfProfile,
|
||||||
|
passphrase: &str,
|
||||||
|
salt: &[u8],
|
||||||
|
) -> Result<Zeroizing<[u8; 32]>, String> {
|
||||||
if passphrase.is_empty() {
|
if passphrase.is_empty() {
|
||||||
return Err("empty passphrase".into());
|
return Err("empty passphrase".into());
|
||||||
}
|
}
|
||||||
if salt.len() != SALT_LEN {
|
if salt.len() != SALT_LEN {
|
||||||
return Err("salt length".into());
|
return Err("salt length".into());
|
||||||
}
|
}
|
||||||
let params = Params::new(19_456, 2, 1, Some(32)).map_err(|e| e.to_string())?;
|
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, profile.params()?);
|
||||||
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
|
||||||
let mut key = Zeroizing::new([0u8; 32]);
|
let mut key = Zeroizing::new([0u8; 32]);
|
||||||
argon
|
argon
|
||||||
.hash_password_into(passphrase.as_bytes(), salt, &mut key[..])
|
.hash_password_into(passphrase.as_bytes(), salt, &mut key[..])
|
||||||
|
|
@ -85,8 +143,9 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result<Vec<u8>, String> {
|
||||||
let ct = cipher
|
let ct = cipher
|
||||||
.encrypt(&nonce, &keys.to_bytes()[..])
|
.encrypt(&nonce, &keys.to_bytes()[..])
|
||||||
.map_err(|_| "encrypt failed".to_string())?;
|
.map_err(|_| "encrypt failed".to_string())?;
|
||||||
let mut out = Vec::with_capacity(MAGIC.len() + SALT_LEN + NONCE_LEN + ct.len());
|
let mut out = Vec::with_capacity(MAGIC.len() + 1 + SEALED_BODY_LEN);
|
||||||
out.extend_from_slice(MAGIC);
|
out.extend_from_slice(MAGIC);
|
||||||
|
out.push(KdfProfile::Current.id());
|
||||||
out.extend_from_slice(&salt);
|
out.extend_from_slice(&salt);
|
||||||
out.extend_from_slice(&nonce);
|
out.extend_from_slice(&nonce);
|
||||||
out.extend_from_slice(&ct);
|
out.extend_from_slice(&ct);
|
||||||
|
|
@ -94,15 +153,25 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result<Vec<u8>, String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn open(passphrase: &str, blob: &[u8]) -> Result<BackupKeys, String> {
|
pub fn open(passphrase: &str, blob: &[u8]) -> Result<BackupKeys, String> {
|
||||||
let min = MAGIC.len() + SALT_LEN + NONCE_LEN + 16;
|
if !blob.starts_with(MAGIC) {
|
||||||
if blob.len() < min || !blob.starts_with(MAGIC) {
|
|
||||||
return Err("not an onionwire backup".into());
|
return Err("not an onionwire backup".into());
|
||||||
}
|
}
|
||||||
let salt = &blob[MAGIC.len()..MAGIC.len() + SALT_LEN];
|
let rest = &blob[MAGIC.len()..];
|
||||||
let nonce_off = MAGIC.len() + SALT_LEN;
|
// The sealed plaintext is a fixed size, so a legacy blob is exactly
|
||||||
let nonce = Nonce::from_slice(&blob[nonce_off..nonce_off + NONCE_LEN]);
|
// SEALED_BODY_LEN bytes after MAGIC and a versioned one is one byte longer.
|
||||||
let ct = &blob[nonce_off + NONCE_LEN..];
|
let (profile, body) = match rest.len() {
|
||||||
let key = kdf(passphrase, salt)?;
|
SEALED_BODY_LEN => (KdfProfile::Legacy, rest),
|
||||||
|
n if n == SEALED_BODY_LEN + 1 => {
|
||||||
|
let profile = KdfProfile::from_id(rest[0])?;
|
||||||
|
(profile, &rest[1..])
|
||||||
|
}
|
||||||
|
_ => return Err("not an onionwire backup".into()),
|
||||||
|
};
|
||||||
|
let salt = &body[..SALT_LEN];
|
||||||
|
let nonce_off = SALT_LEN;
|
||||||
|
let nonce = Nonce::from_slice(&body[nonce_off..nonce_off + NONCE_LEN]);
|
||||||
|
let ct = &body[nonce_off + NONCE_LEN..];
|
||||||
|
let key = kdf_with(profile, passphrase, salt)?;
|
||||||
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
|
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
|
||||||
let pt = Zeroizing::new(
|
let pt = Zeroizing::new(
|
||||||
cipher
|
cipher
|
||||||
|
|
@ -191,4 +260,80 @@ mod tests {
|
||||||
assert!(dbg.contains("<redacted>"), "{dbg}");
|
assert!(dbg.contains("<redacted>"), "{dbg}");
|
||||||
assert!(dbg.contains("174"), "public half should stay: {dbg}");
|
assert!(dbg.contains("174"), "public half should stay: {dbg}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The pre-profile layout: `MAGIC || salt || nonce || ct`, no id byte.
|
||||||
|
fn legacy_blob(passphrase: &str, keys: &BackupKeys) -> Vec<u8> {
|
||||||
|
let salt = [0x5Au8; SALT_LEN];
|
||||||
|
let key = kdf_with(KdfProfile::Legacy, passphrase, &salt).expect("legacy kdf");
|
||||||
|
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
|
||||||
|
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
|
||||||
|
let ct = cipher.encrypt(&nonce, &keys.to_bytes()[..]).expect("seal");
|
||||||
|
let mut out = Vec::new();
|
||||||
|
out.extend_from_slice(MAGIC);
|
||||||
|
out.extend_from_slice(&salt);
|
||||||
|
out.extend_from_slice(&nonce);
|
||||||
|
out.extend_from_slice(&ct);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sealed_blob_records_the_current_profile_and_roundtrips() {
|
||||||
|
let k = keys(9);
|
||||||
|
let blob = seal("correct horse", &k).expect("seal");
|
||||||
|
assert_eq!(blob.len(), MAGIC.len() + 1 + SEALED_BODY_LEN);
|
||||||
|
assert_eq!(
|
||||||
|
blob[MAGIC.len()],
|
||||||
|
KdfProfile::Current.id(),
|
||||||
|
"new blobs must name their KDF profile"
|
||||||
|
);
|
||||||
|
assert_eq!(open("correct horse", &blob).expect("open"), k);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_profile_blob_still_opens() {
|
||||||
|
let k = keys(4);
|
||||||
|
let blob = legacy_blob("correct horse", &k);
|
||||||
|
assert_eq!(blob.len(), MAGIC.len() + SEALED_BODY_LEN);
|
||||||
|
assert_eq!(open("correct horse", &blob).expect("legacy open"), k);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_passphrase_on_a_current_profile_blob_is_the_existing_error() {
|
||||||
|
let blob = seal("right", &keys(1)).expect("seal");
|
||||||
|
let err = open("wrong", &blob).expect_err("wrong passphrase must fail");
|
||||||
|
assert_eq!(err, "wrong passphrase or corrupt backup");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_profile_id_is_a_clear_error_not_a_fallback() {
|
||||||
|
let mut blob = seal("pw", &keys(2)).expect("seal");
|
||||||
|
blob[MAGIC.len()] = 9;
|
||||||
|
let err = open("pw", &blob).expect_err("unknown profile must fail");
|
||||||
|
assert_eq!(err, "unknown kdf profile 9");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trailing_garbage_is_not_an_onionwire_backup() {
|
||||||
|
let mut blob = seal("pw", &keys(3)).expect("seal");
|
||||||
|
blob.push(0xff);
|
||||||
|
assert_eq!(
|
||||||
|
open("pw", &blob).expect_err("must reject"),
|
||||||
|
"not an onionwire backup"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "manual KDF timing measurement; run with --release --ignored"]
|
||||||
|
fn kdf_profile_timings() {
|
||||||
|
use std::time::Instant;
|
||||||
|
let salt = [0x11u8; SALT_LEN];
|
||||||
|
for (label, profile) in [
|
||||||
|
("legacy m=19456 t=2 p=1", KdfProfile::Legacy),
|
||||||
|
("current m=65536 t=3 p=1", KdfProfile::Current),
|
||||||
|
] {
|
||||||
|
let started = Instant::now();
|
||||||
|
let _ = kdf_with(profile, "correct horse battery staple", &salt).expect("kdf");
|
||||||
|
eprintln!("{label}: {:.3}s", started.elapsed().as_secs_f64());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
312
src/store.rs
312
src/store.rs
|
|
@ -293,7 +293,8 @@ impl Store {
|
||||||
CREATE TABLE IF NOT EXISTS store_meta (
|
CREATE TABLE IF NOT EXISTS store_meta (
|
||||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
kdf_salt BLOB NOT NULL,
|
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,
|
-- The wallet child's RPC creds + chain-source snapshot. One row,
|
||||||
-- sealed with the store data key (see `save_wallet_child`): the
|
-- sealed with the store data key (see `save_wallet_child`): the
|
||||||
|
|
@ -692,6 +693,13 @@ impl Store {
|
||||||
"payload",
|
"payload",
|
||||||
"ALTER TABLE outbox ADD COLUMN payload BLOB",
|
"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
|
// `insert_payment` has accepted `kind = "tip"` since the tip path
|
||||||
// landed, but the table's CHECK only allowed invoice/receipt, so every
|
// landed, but the table's CHECK only allowed invoice/receipt, so every
|
||||||
// tip insert (inbound *and* outbound) failed the constraint and the
|
// tip insert (inbound *and* outbound) failed the constraint and the
|
||||||
|
|
@ -741,17 +749,18 @@ impl Store {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unlock_messages(&mut self, passphrase: &str) -> Result<()> {
|
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
|
.conn
|
||||||
.query_row(
|
.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()?;
|
.optional()?;
|
||||||
match row {
|
match row {
|
||||||
Some((salt, wrapped)) => {
|
Some((salt, wrapped, profile_id)) => {
|
||||||
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)?;
|
||||||
// The unwrapped data key lands in a Zeroizing buffer immediately.
|
// The unwrapped data key lands in a Zeroizing buffer immediately.
|
||||||
let raw = Zeroizing::new(
|
let raw = Zeroizing::new(
|
||||||
crate::backup::aead_decrypt(&wrap_key, &wrapped, b"")
|
crate::backup::aead_decrypt(&wrap_key, &wrapped, b"")
|
||||||
|
|
@ -761,6 +770,11 @@ impl Store {
|
||||||
return Err(Error("wrapped message key length".into()));
|
return Err(Error("wrapped message key length".into()));
|
||||||
}
|
}
|
||||||
self.msg_key.copy_from_slice(&raw);
|
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()?;
|
self.rewrap_empty_aad_messages()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -772,8 +786,13 @@ impl Store {
|
||||||
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
||||||
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?;
|
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?;
|
||||||
self.conn.execute(
|
self.conn.execute(
|
||||||
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
"INSERT INTO store_meta (id, kdf_salt, wrapped_key, kdf_profile)
|
||||||
params![salt.as_slice(), wrapped],
|
VALUES (1, ?1, ?2, ?3)",
|
||||||
|
params![
|
||||||
|
salt.as_slice(),
|
||||||
|
wrapped,
|
||||||
|
i64::from(crate::backup::KdfProfile::CURRENT_ID)
|
||||||
|
],
|
||||||
)?;
|
)?;
|
||||||
self.msg_key = data_key;
|
self.msg_key = data_key;
|
||||||
self.reencrypt_legacy_messages()?;
|
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<()> {
|
fn reencrypt_legacy_messages(&self) -> Result<()> {
|
||||||
let mut stmt = self
|
let mut stmt = self
|
||||||
.conn
|
.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"
|
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)?;
|
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
|
/// 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
|
/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh
|
||||||
/// store) accepts any passphrase, matching the v0.2.1 behaviour.
|
/// store) accepts any passphrase, matching the v0.2.1 behaviour.
|
||||||
fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result<bool> {
|
fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result<bool> {
|
||||||
let row: Option<(Vec<u8>, Vec<u8>)> = conn
|
let Some((salt, wrapped, profile_id)) = read_store_meta(conn)? else {
|
||||||
.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);
|
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())
|
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.
|
/// 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
|
/// The source file is only replaced after the new file opens, passes
|
||||||
/// `integrity_check` and unlocks with this passphrase.
|
/// `integrity_check` and unlocks with this passphrase.
|
||||||
|
|
@ -2271,7 +2374,8 @@ mod at_rest {
|
||||||
OsRng.fill_bytes(&mut salt);
|
OsRng.fill_bytes(&mut salt);
|
||||||
let mut data_key = Zeroizing::new([0u8; 32]);
|
let mut data_key = Zeroizing::new([0u8; 32]);
|
||||||
OsRng.fill_bytes(&mut data_key[..]);
|
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();
|
let wrapped = crate::backup::aead_encrypt(&wrap, &data_key[..], b"").unwrap();
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
"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.list_wallets().unwrap().len(), 1);
|
||||||
assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row);
|
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"), ¤t).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}"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue