Skip to main content

mnemo_engine/
crypto.rs

1//! Cryptography layer for Mnemo (Phase 4 of the build plan).
2//!
3//! Mnemo uses a **two-tier key hierarchy**:
4//!
5//! ```text
6//!   passphrase ──Argon2id──▶ KEK (key-encryption-key)
7//!                              │  AES-256-GCM
8//!                              ▼
9//!                            DEK (data-encryption-key, random 256-bit)
10//!                              │  AES-256-GCM, per-page
11//!                              ▼
12//!                            encrypted pages on disk
13//! ```
14//!
15//! The DEK encrypts every page. The KEK only ever encrypts ("wraps") the DEK.
16//! This is what makes `rekey` cheap: changing the passphrase re-derives the KEK
17//! and re-wraps the DEK — the pages themselves never need re-encryption.
18//!
19//! Every page gets a 96-bit nonce minted at write time from a per-session
20//! random prefix plus a per-session monotonic counter (SEC-1). The random
21//! prefix is drawn fresh when a `Mnemo` handle opens the file — it never
22//! touches the disk — and the counter resets to zero in the same step.
23//! Together they make an AES-GCM nonce reuse infeasible across the sessions
24//! that could ever share one DEK, including the "two forks of the same file
25//! after a backup" case that an on-disk `write_counter`-based scheme leaks.
26
27use aes_gcm::aead::{Aead, AeadInPlace, KeyInit, Payload};
28use aes_gcm::{Aes256Gcm, Key, Nonce};
29use argon2::{Algorithm, Argon2, Params, Version};
30use zeroize::Zeroizing;
31
32use crate::error::{MnemoError, Result};
33
34/// Length of a symmetric key in bytes (256-bit).
35pub const KEY_LEN: usize = 32;
36/// Length of an AES-GCM nonce in bytes (96-bit).
37pub const NONCE_LEN: usize = 12;
38/// Length of an AES-GCM authentication tag in bytes.
39pub const TAG_LEN: usize = 16;
40/// Length of the Argon2 salt in bytes.
41pub const SALT_LEN: usize = 16;
42
43/// Argon2id cost parameters. Stored (unencrypted) in the file header so the
44/// KEK can be re-derived on open.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub struct KdfParams {
47    /// Memory cost in KiB.
48    pub m_cost: u32,
49    /// Time cost (number of iterations).
50    pub t_cost: u32,
51    /// Parallelism (lanes).
52    pub p_cost: u32,
53}
54
55impl KdfParams {
56    /// Sensible interactive-use defaults (~19 MiB, 2 passes).
57    pub fn secure() -> Self {
58        Self {
59            m_cost: 19_456,
60            t_cost: 2,
61            p_cost: 1,
62        }
63    }
64
65    /// PERF-1 step 7 (R-004.5): the Argon2id floor (8 KiB, one pass), for
66    /// databases unlocked by a raw random 256-bit key
67    /// (`Mnemo::create_with_key`). A uniformly random key has full entropy
68    /// already, so stretching it buys nothing; these are recorded in the
69    /// header so the normal open path runs in microseconds. **Never** use
70    /// them with a human passphrase.
71    pub fn raw_key() -> Self {
72        Self {
73            m_cost: 8,
74            t_cost: 1,
75            p_cost: 1,
76        }
77    }
78
79    /// Deliberately weak parameters — **only** for fast unit tests.
80    #[doc(hidden)]
81    pub fn fast() -> Self {
82        Self {
83            m_cost: 512,
84            t_cost: 1,
85            p_cost: 1,
86        }
87    }
88}
89
90impl Default for KdfParams {
91    fn default() -> Self {
92        Self::secure()
93    }
94}
95
96/// 12.3 (the keys note, section 1): the memory cost below which parameters
97/// are the raw-key kind. [`KdfParams::raw_key`] is below it, and
98/// [`KdfParams::fast`] sits exactly on it, so the tests' parameters stay
99/// allowed with a passphrase.
100const PASSPHRASE_FLOOR_M_COST: u32 = 512;
101
102impl KdfParams {
103    /// 12.3: the parameters a passphrase gets when a file had `self`: for
104    /// each cost, the larger of `self`'s and [`KdfParams::secure`]'s. Every
105    /// surface that rekeys to a passphrase uses it, so a passphrase never
106    /// lands on weaker parameters than a file already had, nor below
107    /// `secure()`.
108    pub fn for_passphrase(self) -> Self {
109        let s = Self::secure();
110        Self {
111            m_cost: self.m_cost.max(s.m_cost),
112            t_cost: self.t_cost.max(s.t_cost),
113            p_cost: self.p_cost.max(s.p_cost),
114        }
115    }
116
117    /// 12.3: whether these are raw-key parameters, too light for a human
118    /// passphrase ([`KdfParams::raw_key`] is; [`KdfParams::fast`] isn't).
119    /// The engine refuses a passphrase with them, and a file a passphrase
120    /// opens with them is reported.
121    pub fn below_passphrase_floor(&self) -> bool {
122        self.m_cost < PASSPHRASE_FLOOR_M_COST
123    }
124
125    /// 12.3: at or above the floor but below [`KdfParams::secure`]'s memory
126    /// cost: test-grade parameters, such as [`KdfParams::fast`].
127    pub fn is_test_grade(&self) -> bool {
128        !self.below_passphrase_floor() && self.m_cost < Self::secure().m_cost
129    }
130}
131
132/// 12.3: a rekey's hook, given the new salt before anything is written.
133pub(crate) type SaltHook<'a> = dyn FnMut(&[u8; SALT_LEN]) -> Result<()> + 'a;
134
135/// 12.3: what kind of secret a caller handed the engine. A passphrase is a
136/// person's; a key is a uniformly random 256-bit value a machine made.
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub enum SecretKind {
139    /// A passphrase a person chose.
140    Passphrase,
141    /// A raw 256-bit key.
142    Key,
143}
144
145/// 12.3 (the keys note, section 1, rule 2): refuse a passphrase with
146/// raw-key parameters. Called where every create and rekey path meets.
147pub(crate) fn check_kdf_for(kind: SecretKind, kdf: KdfParams) -> Result<()> {
148    if kind == SecretKind::Passphrase && kdf.below_passphrase_floor() {
149        return Err(MnemoError::Invalid(format!(
150            "these KDF parameters ({} KiB, {} pass) are for a raw 256-bit key, not a \
151             passphrase; use create_with_key or rekey_with_key for a key, or \
152             KdfParams::secure() for a passphrase",
153            kdf.m_cost, kdf.t_cost
154        )));
155    }
156    Ok(())
157}
158
159/// Derive the key-encryption-key (KEK) from a passphrase using Argon2id.
160pub fn derive_kek(
161    passphrase: &[u8],
162    salt: &[u8],
163    params: KdfParams,
164) -> Result<Zeroizing<[u8; KEY_LEN]>> {
165    let p = Params::new(params.m_cost, params.t_cost, params.p_cost, Some(KEY_LEN))
166        .map_err(|e| MnemoError::Kdf(e.to_string()))?;
167    let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, p);
168    let mut key = Zeroizing::new([0u8; KEY_LEN]);
169    argon
170        .hash_password_into(passphrase, salt, &mut key[..])
171        .map_err(|e| MnemoError::Kdf(e.to_string()))?;
172    Ok(key)
173}
174
175fn cipher(key: &[u8; KEY_LEN]) -> Aes256Gcm {
176    Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key))
177}
178
179/// PERF-2 (v0.19.0): one AES-256-GCM instance for many decrypts (a batch of
180/// pages), so the key schedule runs once, not per page. It's `Sync`, so
181/// scoped threads can share it.
182pub(crate) fn page_cipher(key: &[u8; KEY_LEN]) -> Aes256Gcm {
183    cipher(key)
184}
185
186/// PERF-2 (v0.19.0): decrypt one sealed page where it lies. `buf` holds
187/// the ciphertext and becomes the plaintext; `tag` is the 16 bytes after
188/// it. Nothing is allocated. On failure `buf` is left as it was.
189pub(crate) fn aead_decrypt_in_place(
190    cipher: &Aes256Gcm,
191    nonce: &[u8; NONCE_LEN],
192    aad: &[u8],
193    buf: &mut [u8],
194    tag: &[u8],
195) -> Result<()> {
196    cipher
197        .decrypt_in_place_detached(
198            Nonce::from_slice(nonce),
199            aad,
200            buf,
201            aes_gcm::Tag::from_slice(tag),
202        )
203        .map_err(|_| MnemoError::Crypto("authentication failed".into()))
204}
205
206/// AES-256-GCM encrypt with **Associated Authenticated Data**. The AAD is not
207/// part of the ciphertext but is bound into the authentication tag; decryption
208/// fails unless the caller supplies the same AAD. Output is
209/// `ciphertext || 16-byte tag`.
210///
211/// Pass `&[]` to encrypt without AAD — this matches the format before v6, used
212/// for wrapping the DEK and for v4/v5 page encryption. From v6 onwards, page
213/// encryption passes `page_no.to_le_bytes()` as AAD so an attacker can't
214/// transplant a valid encrypted page to a different page slot — the
215/// authentication tag binds the page image to its home page number.
216pub fn aead_encrypt(
217    key: &[u8; KEY_LEN],
218    nonce: &[u8; NONCE_LEN],
219    plaintext: &[u8],
220    aad: &[u8],
221) -> Result<Vec<u8>> {
222    cipher(key)
223        .encrypt(
224            Nonce::from_slice(nonce),
225            Payload {
226                msg: plaintext,
227                aad,
228            },
229        )
230        .map_err(|e| MnemoError::Crypto(e.to_string()))
231}
232
233/// AES-256-GCM decrypt with AAD. Input must be `ciphertext || 16-byte tag`.
234/// Returns an error if authentication fails — including when the supplied
235/// AAD doesn't match what was used during encryption.
236pub fn aead_decrypt(
237    key: &[u8; KEY_LEN],
238    nonce: &[u8; NONCE_LEN],
239    ciphertext: &[u8],
240    aad: &[u8],
241) -> Result<Vec<u8>> {
242    cipher(key)
243        .decrypt(
244            Nonce::from_slice(nonce),
245            Payload {
246                msg: ciphertext,
247                aad,
248            },
249        )
250        .map_err(|_| MnemoError::Crypto("authentication failed".into()))
251}
252
253/// Generate a fresh random 256-bit data-encryption-key.
254pub fn random_dek() -> Zeroizing<[u8; KEY_LEN]> {
255    use rand::RngCore;
256    let mut dek = Zeroizing::new([0u8; KEY_LEN]);
257    rand::thread_rng().fill_bytes(&mut dek[..]);
258    dek
259}
260
261/// Generate a random Argon2 salt.
262pub fn random_salt() -> [u8; SALT_LEN] {
263    use rand::RngCore;
264    let mut salt = [0u8; SALT_LEN];
265    rand::thread_rng().fill_bytes(&mut salt);
266    salt
267}
268
269/// Generate a random nonce (used for wrapping the DEK).
270pub fn random_nonce() -> [u8; NONCE_LEN] {
271    use rand::RngCore;
272    let mut n = [0u8; NONCE_LEN];
273    rand::thread_rng().fill_bytes(&mut n);
274    n
275}
276
277/// Generate a random `u64`, used by the pager to pick a per-session
278/// nonce prefix. See [`session_page_nonce`] for the full construction.
279pub fn random_u64() -> u64 {
280    use rand::RngCore;
281    rand::thread_rng().next_u64()
282}
283
284/// Build a per-session page nonce (PR SEC-1, v0.5.2).
285///
286/// Structure, following NIST SP 800-38D §8.2.1 (fixed field + invocation
287/// field) for AES-GCM:
288///
289/// - **Bytes 0..8** — `session_random`: a 64-bit random value drawn
290///   fresh on every writable [`crate::Mnemo::open`] / [`crate::Mnemo::create`]
291///   (and regenerated on counter wrap). This is the "fixed field".
292/// - **Bytes 8..12** — `session_counter`: a 32-bit per-session monotonic
293///   counter that advances once per encrypted page write. This is the
294///   "invocation field".
295///
296/// `page_no` is **not** encoded in the nonce. Pages were bound to their
297/// home slot through AAD since v6 (`page_no.to_le_bytes()`), so an
298/// attacker who swapped a valid page to a different slot already failed
299/// authentication — the AAD binding stays in place and does the job the
300/// `page_no` component of the pre-SEC-1 nonce was helping with.
301///
302/// # Why not deterministic any more
303///
304/// Before v0.5.2 the nonce was `page_no as u32 || write_counter as u64`,
305/// which was unique **within a file** but not **across copies of a file**.
306/// If you copied a `.mnemo` file to another host and both the original and
307/// the copy got written to (two laptops syncing a Dropbox file; a
308/// restored older backup resuming operation), each copy's writer produced
309/// pages whose nonces collided with the other's at the same `(page_no,
310/// write_counter)` coordinates, under the same DEK (`random_dek()` only
311/// at create; `rekey` keeps it). That breaks AES-GCM's confidentiality
312/// and tamper-evidence guarantee: whoever holds both ciphertexts can
313/// recover the XOR of the plaintexts and forge pages with a valid tag.
314///
315/// A fresh random 64-bit `session_random` per writable open closes that:
316/// cross-copy collision now requires two sessions to independently draw
317/// the same 64-bit value (birthday bound ~2^32 sessions, i.e.
318/// astronomically unlikely for a human-scale user). The 32-bit
319/// `session_counter` guarantees uniqueness *within* a session; the pager
320/// regenerates `session_random` and resets the counter if it would wrap.
321///
322/// # Decrypt is unaffected
323///
324/// Each page already stores its own nonce in bytes `[0..12]` of the
325/// on-disk image (see `mnemo/src/pager.rs::read_page`). Decrypt reads the
326/// stored nonce; it never recomputes one. **No format bump — a v0.5.1
327/// file opens fine on v0.5.2 and vice versa.**
328pub fn session_page_nonce(session_random: u64, session_counter: u32) -> [u8; NONCE_LEN] {
329    let mut n = [0u8; NONCE_LEN];
330    n[0..8].copy_from_slice(&session_random.to_le_bytes());
331    n[8..12].copy_from_slice(&session_counter.to_le_bytes());
332    n
333}
334
335/// Wrap (encrypt) the DEK with the KEK. The wrap uses **empty AAD** in every
336/// version, so v5 wrapped-DEK bytes on disk round-trip unchanged through a v6
337/// build — only page encryption changed in v6.
338pub fn wrap_dek(
339    kek: &[u8; KEY_LEN],
340    nonce: &[u8; NONCE_LEN],
341    dek: &[u8; KEY_LEN],
342) -> Result<Vec<u8>> {
343    aead_encrypt(kek, nonce, dek, &[])
344}
345
346/// Unwrap (decrypt) the DEK with the KEK. A wrong KEK (wrong passphrase)
347/// fails authentication and is reported as [`MnemoError::WrongPassphrase`].
348pub fn unwrap_dek(
349    kek: &[u8; KEY_LEN],
350    nonce: &[u8; NONCE_LEN],
351    wrapped: &[u8],
352) -> Result<Zeroizing<[u8; KEY_LEN]>> {
353    let plain = cipher(kek)
354        .decrypt(
355            Nonce::from_slice(nonce),
356            Payload {
357                msg: wrapped,
358                aad: &[],
359            },
360        )
361        .map_err(|_| MnemoError::WrongPassphrase)?;
362    if plain.len() != KEY_LEN {
363        return Err(MnemoError::WrongPassphrase);
364    }
365    let mut dek = Zeroizing::new([0u8; KEY_LEN]);
366    dek.copy_from_slice(&plain);
367    Ok(dek)
368}