Skip to main content

vault_core/
rekey.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Changing the master password: a new salt, a new key, the same data.
4//!
5//! The key is Argon2id over the password and `vault.salt`, so changing the password changes both
6//! files: `vault.db` is re-encrypted and `vault.salt` replaced. Two files cannot be swapped
7//! atomically, so the order is chosen so that a crash at any point leaves a vault that opens with
8//! either the old password or the new one, never neither:
9//!
10//! 1. take a write lock on the old database (a second connection, since `ATTACH` cannot run inside
11//!    a transaction), checkpoint it, and copy `vault.db` and
12//!    `vault.salt` to `*.pre-rekey` (the way back);
13//! 2. write the new salt as `vault.salt.new`;
14//! 3. `sqlcipher_export` the data into `vault.db.rekey-new` under the new key;
15//! 4. open that file with the new key and check that it is intact and holds the same rows;
16//! 5. rename it over `vault.db`, then rename `vault.salt.new` over `vault.salt`.
17//!
18//! A crash before step 5's first rename leaves the old pair untouched (the leftovers are removed).
19//! A crash between the two renames leaves a new database beside the old salt and a `vault.salt.new`;
20//! [`recover_interrupted`], which every unlock runs first, sees that the new password opens the
21//! database through `vault.salt.new` and finishes the rename. The `*.pre-rekey` copies stay until
22//! the next successful unlock ([`cleanup_after_unlock`]). Backups made before the change still open
23//! with the old password, which is the point of a backup, and the documentation says so.
24//!
25//! Recovery packages are encrypted to an age recipient, not to the master password, so they are not
26//! affected.
27
28use crate::{derive_key, open_db, platform, restrict_to_owner, VaultKey, SALT_LEN};
29use rusqlite::Connection;
30use std::fs;
31use std::path::{Path, PathBuf};
32
33/// The shortest new master password the command accepts, as in the desktop app.
34pub const MIN_PASSWORD_CHARS: usize = 12;
35
36/// Where a rekey can be stopped, for the tests that prove each stop is survivable.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum Stage {
39    CopiedOld,
40    WroteNewSalt,
41    Exported,
42    Verified,
43    SwappedDatabase,
44}
45
46#[derive(Debug, PartialEq, Eq)]
47pub struct Report {
48    /// Rows copied across all tables.
49    pub rows: u64,
50    /// The copy of the old database, kept until the next successful unlock.
51    pub kept_database: PathBuf,
52    pub kept_salt: PathBuf,
53}
54
55fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
56    let mut s = path.as_os_str().to_owned();
57    s.push(suffix);
58    PathBuf::from(s)
59}
60
61fn sql_literal(path: &Path) -> String {
62    path.to_string_lossy().replace('\'', "''")
63}
64
65/// Every table's row count, so a copy can be compared with its source.
66fn table_counts(conn: &Connection) -> Result<Vec<(String, i64)>, String> {
67    let names: Vec<String> = {
68        let mut st = conn
69            .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
70            .map_err(|e| e.to_string())?;
71        let rows = st.query_map([], |r| r.get(0)).map_err(|e| e.to_string())?;
72        rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
73    };
74    names
75        .into_iter()
76        .map(|n| {
77            let c: i64 = conn
78                .query_row(&format!("SELECT count(*) FROM \"{n}\""), [], |r| r.get(0))
79                .map_err(|e| e.to_string())?;
80            Ok((n, c))
81        })
82        .collect()
83}
84
85fn intact(conn: &Connection) -> Result<(), String> {
86    let ok: String = conn
87        .query_row("PRAGMA integrity_check", [], |r| r.get(0))
88        .map_err(|e| e.to_string())?;
89    if ok != "ok" {
90        return Err(format!("integrity check failed: {ok}"));
91    }
92    let mut st = conn
93        .prepare("PRAGMA cipher_integrity_check")
94        .map_err(|e| e.to_string())?;
95    if st
96        .query_map([], |r| r.get::<_, String>(0))
97        .map_err(|e| e.to_string())?
98        .next()
99        .is_some()
100    {
101        return Err("SQLCipher integrity check failed".into());
102    }
103    Ok(())
104}
105
106/// Re-encrypts the vault under `new_password`. `stop_after` ends the run early with an error, which
107/// is what a crash at that point looks like; production callers pass `None` through [`rekey`].
108pub fn rekey_with(
109    db_path: &Path,
110    salt_path: &Path,
111    old_password: &str,
112    new_password: &str,
113    stop_after: Option<Stage>,
114) -> Result<Report, String> {
115    if new_password.chars().count() < MIN_PASSWORD_CHARS {
116        return Err(format!(
117            "The new master password must be at least {MIN_PASSWORD_CHARS} characters"
118        ));
119    }
120    if new_password == old_password {
121        return Err("The new master password is the same as the old one".into());
122    }
123    recover_interrupted(db_path, salt_path, old_password)?;
124    crate::check_salt_pairing(db_path, salt_path)?;
125    let old_salt: [u8; SALT_LEN] = fs::read(salt_path)
126        .map_err(|e| e.to_string())?
127        .try_into()
128        .map_err(|_| "vault.salt is corrupt (wrong length)".to_string())?;
129    let old_key = derive_key(old_password, &old_salt)?;
130    let conn = open_db(db_path, &old_key)?;
131    let before = table_counts(&conn)?;
132    intact(&conn)?;
133
134    let kept_db = with_suffix(db_path, ".pre-rekey");
135    let kept_salt = with_suffix(salt_path, ".pre-rekey");
136    let new_salt_path = with_suffix(salt_path, ".new");
137    let new_db_path = with_suffix(db_path, ".rekey-new");
138    let _ = fs::remove_file(&new_db_path);
139    let _ = fs::remove_file(&new_salt_path);
140
141    let stop = |stage: Stage| -> Result<(), String> {
142        if stop_after == Some(stage) {
143            Err(format!("interrupted after {stage:?}"))
144        } else {
145            Ok(())
146        }
147    };
148    let cleanup = || {
149        let _ = fs::remove_file(&new_db_path);
150        let _ = fs::remove_file(&new_salt_path);
151    };
152
153    // `ATTACH` is refused inside a transaction, so the write lock is held by a second connection
154    // while this one reads and exports. Readers are not blocked; writers are.
155    let guard = open_db(db_path, &old_key)?;
156    let result = (|| -> Result<u64, String> {
157        // 1. No writer can slip in while the copy is taken and the export runs.
158        guard
159            .execute_batch("BEGIN IMMEDIATE;")
160            .map_err(|e| format!("the vault is in use by another program: {e}"))?;
161        conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
162            .map_err(|e| e.to_string())?;
163        fs::copy(db_path, &kept_db).map_err(|e| format!("cannot keep the old database: {e}"))?;
164        fs::copy(salt_path, &kept_salt).map_err(|e| format!("cannot keep the old salt: {e}"))?;
165        restrict_to_owner(&kept_db)?;
166        restrict_to_owner(&kept_salt)?;
167        stop(Stage::CopiedOld)?;
168
169        // 2. The new salt, durable before anything depends on it.
170        let new_salt: [u8; SALT_LEN] = rand::random();
171        {
172            use std::io::Write;
173            let mut f = fs::File::create(&new_salt_path).map_err(|e| e.to_string())?;
174            f.write_all(&new_salt).map_err(|e| e.to_string())?;
175            f.sync_all().map_err(|e| e.to_string())?;
176        }
177        restrict_to_owner(&new_salt_path)?;
178        let new_key: VaultKey = derive_key(new_password, &new_salt)?;
179        stop(Stage::WroteNewSalt)?;
180
181        // 3. Export under the new key.
182        let version: i64 = conn
183            .query_row("PRAGMA user_version", [], |r| r.get(0))
184            .map_err(|e| e.to_string())?;
185        conn.execute_batch(&format!(
186            "ATTACH DATABASE '{}' AS rekeyed KEY \"x'{}'\"; SELECT sqlcipher_export('rekeyed'); PRAGMA rekeyed.user_version = {version}; DETACH DATABASE rekeyed;",
187            sql_literal(&new_db_path),
188            hex::encode(new_key)
189        ))
190        .map_err(|e| format!("export failed: {e}"))?;
191        restrict_to_owner(&new_db_path)?;
192        stop(Stage::Exported)?;
193
194        // 4. Prove the copy before it replaces anything.
195        let check = open_db(&new_db_path, &new_key).map_err(|e| {
196            format!("the re-encrypted copy does not open with the new password: {e}")
197        })?;
198        intact(&check)?;
199        let after = table_counts(&check)?;
200        if after != before {
201            return Err("the re-encrypted copy does not hold the same rows".into());
202        }
203        let rows = after.iter().map(|(_, c)| *c as u64).sum();
204        check
205            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
206            .map_err(|e| e.to_string())?;
207        drop(check);
208        stop(Stage::Verified)?;
209        Ok(rows)
210    })();
211
212    let rows = match result {
213        Ok(rows) => rows,
214        Err(e) => {
215            let _ = guard.execute_batch("ROLLBACK;");
216            drop(guard);
217            drop(conn);
218            // Before the swap nothing of the old pair has changed; only an interruption that
219            // simulates a crash keeps its leftovers for the recovery test to find.
220            if stop_after.is_none() {
221                cleanup();
222            }
223            return Err(e);
224        }
225    };
226
227    // 5. The swap. The old connection must be closed and its sidecars gone first.
228    let _ = guard.execute_batch("ROLLBACK;");
229    drop(guard);
230    drop(conn);
231    for suffix in ["-wal", "-shm"] {
232        let _ = fs::remove_file(with_suffix(db_path, suffix));
233    }
234    platform::replace_file(&new_db_path, db_path)
235        .map_err(|e| format!("cannot install the new database: {e}"))?;
236    stop(Stage::SwappedDatabase)?;
237    platform::replace_file(&new_salt_path, salt_path)
238        .map_err(|e| format!("cannot install the new salt: {e}"))?;
239    Ok(Report {
240        rows,
241        kept_database: kept_db,
242        kept_salt,
243    })
244}
245
246/// [`rekey_with`] without a stop.
247pub fn rekey(
248    db_path: &Path,
249    salt_path: &Path,
250    old_password: &str,
251    new_password: &str,
252) -> Result<Report, String> {
253    rekey_with(db_path, salt_path, old_password, new_password, None)
254}
255
256/// Finishes or abandons a rekey that a crash interrupted. Cheap when there is nothing to do: one
257/// existence check. Returns whether it changed anything.
258///
259/// If `vault.salt.new` exists, the new password opening the database through it proves the
260/// database was already swapped, so the salt rename is completed; otherwise the rekey never got that
261/// far and its leftovers are removed.
262pub fn recover_interrupted(
263    db_path: &Path,
264    salt_path: &Path,
265    password: &str,
266) -> Result<bool, String> {
267    let new_salt_path = with_suffix(salt_path, ".new");
268    let new_db_path = with_suffix(db_path, ".rekey-new");
269    if !new_salt_path.exists() {
270        // A half-written export without a new salt is just litter.
271        if new_db_path.exists() {
272            let _ = fs::remove_file(&new_db_path);
273            return Ok(true);
274        }
275        return Ok(false);
276    }
277    let new_salt = fs::read(&new_salt_path).map_err(|e| e.to_string())?;
278    let swapped = derive_key(password, &new_salt)
279        .ok()
280        .is_some_and(|key| db_path.exists() && open_db_quietly(db_path, &key));
281    if swapped {
282        platform::replace_file(&new_salt_path, salt_path)
283            .map_err(|e| format!("cannot finish the interrupted password change: {e}"))?;
284    } else {
285        let _ = fs::remove_file(&new_salt_path);
286    }
287    let _ = fs::remove_file(&new_db_path);
288    Ok(true)
289}
290
291/// Whether the database opens under `key`, without creating or modifying anything.
292fn open_db_quietly(db_path: &Path, key: &VaultKey) -> bool {
293    let Ok(conn) = Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
294    else {
295        return false;
296    };
297    conn.execute_batch(&format!("PRAGMA key = \"x'{}'\";", hex::encode(key)))
298        .is_ok()
299        && conn
300            .execute_batch("SELECT count(*) FROM sqlite_master;")
301            .is_ok()
302}
303
304/// Removes the `*.pre-rekey` copies. Called after an unlock has succeeded, which proves the new pair
305/// works; until then they are the way back.
306pub fn cleanup_after_unlock(db_path: &Path, salt_path: &Path) -> bool {
307    let a = fs::remove_file(with_suffix(db_path, ".pre-rekey")).is_ok();
308    let b = fs::remove_file(with_suffix(salt_path, ".pre-rekey")).is_ok();
309    a || b
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    struct Vault {
317        dir: PathBuf,
318        db: PathBuf,
319        salt: PathBuf,
320    }
321
322    fn vault(old: &str) -> Vault {
323        let dir = std::env::temp_dir().join(format!("vc-rekey-{}", crate::new_uuid()));
324        fs::create_dir_all(&dir).unwrap();
325        let (db, salt) = (dir.join("vault.db"), dir.join("vault.salt"));
326        let s = crate::read_or_create_salt(&salt).unwrap();
327        let key = derive_key(old, &s).unwrap();
328        let conn = open_db(&db, &key).unwrap();
329        crate::init_schema(&conn).unwrap();
330        conn.execute_batch(
331            "CREATE TABLE IF NOT EXISTS probe (k TEXT PRIMARY KEY, v TEXT); INSERT INTO probe VALUES ('a', 'one'), ('b', 'two');",
332        )
333        .unwrap();
334        Vault { dir, db, salt }
335    }
336
337    /// Opens the vault the way an unlock does: recover first, then derive from the salt on disk.
338    fn unlock(v: &Vault, password: &str) -> Result<Connection, String> {
339        recover_interrupted(&v.db, &v.salt, password)?;
340        let salt = fs::read(&v.salt).map_err(|e| e.to_string())?;
341        open_db(&v.db, &derive_key(password, &salt)?)
342    }
343
344    fn rows(conn: &Connection) -> i64 {
345        conn.query_row("SELECT count(*) FROM probe", [], |r| r.get(0))
346            .unwrap()
347    }
348
349    // Built at run time: a literal here reads as a hard-coded key to the code scanner.
350    static OLD: std::sync::LazyLock<String> =
351        std::sync::LazyLock::new(|| format!("the old master password {}", 1));
352    static NEW: std::sync::LazyLock<String> =
353        std::sync::LazyLock::new(|| format!("the new master password {}", 2));
354
355    #[test]
356    fn the_new_password_opens_the_same_data_and_the_old_one_no_longer_does() {
357        let v = vault(&OLD);
358        let report = rekey(&v.db, &v.salt, &OLD, &NEW).unwrap();
359        assert!(report.rows >= 2);
360        assert_eq!(rows(&unlock(&v, &NEW).unwrap()), 2);
361        assert_eq!(unlock(&v, &OLD).err().unwrap(), "Wrong master password");
362        assert!(
363            report.kept_database.exists() && report.kept_salt.exists(),
364            "the way back is kept"
365        );
366        // After a successful unlock the copies go.
367        assert!(cleanup_after_unlock(&v.db, &v.salt));
368        assert!(!report.kept_database.exists() && !report.kept_salt.exists());
369        assert!(
370            !cleanup_after_unlock(&v.db, &v.salt),
371            "nothing left to remove"
372        );
373        let _ = fs::remove_dir_all(&v.dir);
374    }
375
376    #[test]
377    fn the_kept_copy_still_opens_with_the_old_password() {
378        let v = vault(&OLD);
379        let report = rekey(&v.db, &v.salt, &OLD, &NEW).unwrap();
380        let salt = fs::read(&report.kept_salt).unwrap();
381        let conn = open_db(&report.kept_database, &derive_key(&OLD, &salt).unwrap()).unwrap();
382        assert_eq!(rows(&conn), 2);
383        drop(conn);
384        let _ = fs::remove_dir_all(&v.dir);
385    }
386
387    #[test]
388    fn a_stop_at_any_step_leaves_a_vault_that_opens_with_the_old_or_the_new_password() {
389        for (stage, new_wins) in [
390            (Stage::CopiedOld, false),
391            (Stage::WroteNewSalt, false),
392            (Stage::Exported, false),
393            (Stage::Verified, false),
394            (Stage::SwappedDatabase, true),
395        ] {
396            let v = vault(&OLD);
397            let err = rekey_with(&v.db, &v.salt, &OLD, &NEW, Some(stage)).unwrap_err();
398            assert!(err.contains("interrupted"), "{stage:?}: {err}");
399            let (winner, loser) = if new_wins {
400                (&**NEW, &**OLD)
401            } else {
402                (&**OLD, &**NEW)
403            };
404            let conn = unlock(&v, winner)
405                .unwrap_or_else(|e| panic!("{stage:?}: the expected password should open: {e}"));
406            assert_eq!(rows(&conn), 2, "{stage:?}");
407            drop(conn);
408            assert!(
409                unlock(&v, loser).is_err(),
410                "{stage:?}: the other password should not open"
411            );
412            assert!(
413                !with_suffix(&v.salt, ".new").exists(),
414                "{stage:?}: no half-finished salt is left"
415            );
416            assert!(
417                !with_suffix(&v.db, ".rekey-new").exists(),
418                "{stage:?}: no half-written copy is left"
419            );
420            let _ = fs::remove_dir_all(&v.dir);
421        }
422    }
423
424    #[test]
425    fn recovery_is_a_no_op_when_nothing_was_interrupted() {
426        let v = vault(&OLD);
427        assert!(!recover_interrupted(&v.db, &v.salt, &OLD).unwrap());
428        // A stray half-written export with no new salt is removed.
429        fs::write(with_suffix(&v.db, ".rekey-new"), b"junk").unwrap();
430        assert!(recover_interrupted(&v.db, &v.salt, &OLD).unwrap());
431        assert!(!with_suffix(&v.db, ".rekey-new").exists());
432        let _ = fs::remove_dir_all(&v.dir);
433    }
434
435    #[test]
436    fn a_wrong_old_password_a_weak_new_one_and_an_unchanged_one_are_refused_before_any_file_changes(
437    ) {
438        let v = vault(&OLD);
439        let before = (fs::read(&v.db).unwrap().len(), fs::read(&v.salt).unwrap());
440        assert_eq!(
441            rekey(&v.db, &v.salt, &format!("{}x", *OLD), &NEW).unwrap_err(),
442            "Wrong master password"
443        );
444        let weak = rekey(&v.db, &v.salt, &OLD, &"x".repeat(5)).unwrap_err();
445        assert!(weak.contains("at least 12"), "{weak}");
446        let same = rekey(&v.db, &v.salt, &OLD, &OLD).unwrap_err();
447        assert!(same.contains("same"), "{same}");
448        assert_eq!(fs::read(&v.salt).unwrap(), before.1);
449        assert!(!with_suffix(&v.db, ".pre-rekey").exists());
450        assert_eq!(rows(&unlock(&v, &OLD).unwrap()), 2);
451        let _ = fs::remove_dir_all(&v.dir);
452    }
453
454    #[test]
455    fn a_missing_salt_is_reported_as_such_and_not_papered_over() {
456        let v = vault(&OLD);
457        fs::remove_file(&v.salt).unwrap();
458        let err = rekey(&v.db, &v.salt, &OLD, &NEW).unwrap_err();
459        assert!(
460            err.contains("vault.salt") && err.contains("missing"),
461            "{err}"
462        );
463        let _ = fs::remove_dir_all(&v.dir);
464    }
465
466    #[test]
467    fn a_vault_another_program_holds_open_for_writing_is_refused_not_corrupted() {
468        let v = vault(&OLD);
469        let salt = fs::read(&v.salt).unwrap();
470        let other = open_db(&v.db, &derive_key(&OLD, &salt).unwrap()).unwrap();
471        other.execute_batch("BEGIN IMMEDIATE;").unwrap();
472        let err = rekey(&v.db, &v.salt, &OLD, &NEW).unwrap_err();
473        assert!(err.contains("in use"), "{err}");
474        other.execute_batch("ROLLBACK;").unwrap();
475        drop(other);
476        assert_eq!(rows(&unlock(&v, &OLD).unwrap()), 2, "still the old vault");
477        assert!(
478            !with_suffix(&v.salt, ".new").exists() && !with_suffix(&v.db, ".rekey-new").exists()
479        );
480        let _ = fs::remove_dir_all(&v.dir);
481    }
482}