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, 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/// AES-256-GCM encrypt with **Associated Authenticated Data**. The AAD is not
180/// part of the ciphertext but is bound into the authentication tag; decryption
181/// fails unless the caller supplies the same AAD. Output is
182/// `ciphertext || 16-byte tag`.
183///
184/// Pass `&[]` to encrypt without AAD — this matches the format before v6, used
185/// for wrapping the DEK and for v4/v5 page encryption. From v6 onwards, page
186/// encryption passes `page_no.to_le_bytes()` as AAD so an attacker can't
187/// transplant a valid encrypted page to a different page slot — the
188/// authentication tag binds the page image to its home page number.
189pub fn aead_encrypt(
190 key: &[u8; KEY_LEN],
191 nonce: &[u8; NONCE_LEN],
192 plaintext: &[u8],
193 aad: &[u8],
194) -> Result<Vec<u8>> {
195 cipher(key)
196 .encrypt(
197 Nonce::from_slice(nonce),
198 Payload {
199 msg: plaintext,
200 aad,
201 },
202 )
203 .map_err(|e| MnemoError::Crypto(e.to_string()))
204}
205
206/// AES-256-GCM decrypt with AAD. Input must be `ciphertext || 16-byte tag`.
207/// Returns an error if authentication fails — including when the supplied
208/// AAD doesn't match what was used during encryption.
209pub fn aead_decrypt(
210 key: &[u8; KEY_LEN],
211 nonce: &[u8; NONCE_LEN],
212 ciphertext: &[u8],
213 aad: &[u8],
214) -> Result<Vec<u8>> {
215 cipher(key)
216 .decrypt(
217 Nonce::from_slice(nonce),
218 Payload {
219 msg: ciphertext,
220 aad,
221 },
222 )
223 .map_err(|_| MnemoError::Crypto("authentication failed".into()))
224}
225
226/// Generate a fresh random 256-bit data-encryption-key.
227pub fn random_dek() -> Zeroizing<[u8; KEY_LEN]> {
228 use rand::RngCore;
229 let mut dek = Zeroizing::new([0u8; KEY_LEN]);
230 rand::thread_rng().fill_bytes(&mut dek[..]);
231 dek
232}
233
234/// Generate a random Argon2 salt.
235pub fn random_salt() -> [u8; SALT_LEN] {
236 use rand::RngCore;
237 let mut salt = [0u8; SALT_LEN];
238 rand::thread_rng().fill_bytes(&mut salt);
239 salt
240}
241
242/// Generate a random nonce (used for wrapping the DEK).
243pub fn random_nonce() -> [u8; NONCE_LEN] {
244 use rand::RngCore;
245 let mut n = [0u8; NONCE_LEN];
246 rand::thread_rng().fill_bytes(&mut n);
247 n
248}
249
250/// Generate a random `u64`, used by the pager to pick a per-session
251/// nonce prefix. See [`session_page_nonce`] for the full construction.
252pub fn random_u64() -> u64 {
253 use rand::RngCore;
254 rand::thread_rng().next_u64()
255}
256
257/// Build a per-session page nonce (PR SEC-1, v0.5.2).
258///
259/// Structure, following NIST SP 800-38D §8.2.1 (fixed field + invocation
260/// field) for AES-GCM:
261///
262/// - **Bytes 0..8** — `session_random`: a 64-bit random value drawn
263/// fresh on every writable [`crate::Mnemo::open`] / [`crate::Mnemo::create`]
264/// (and regenerated on counter wrap). This is the "fixed field".
265/// - **Bytes 8..12** — `session_counter`: a 32-bit per-session monotonic
266/// counter that advances once per encrypted page write. This is the
267/// "invocation field".
268///
269/// `page_no` is **not** encoded in the nonce. Pages were bound to their
270/// home slot through AAD since v6 (`page_no.to_le_bytes()`), so an
271/// attacker who swapped a valid page to a different slot already failed
272/// authentication — the AAD binding stays in place and does the job the
273/// `page_no` component of the pre-SEC-1 nonce was helping with.
274///
275/// # Why not deterministic any more
276///
277/// Before v0.5.2 the nonce was `page_no as u32 || write_counter as u64`,
278/// which was unique **within a file** but not **across copies of a file**.
279/// If you copied a `.mnemo` file to another host and both the original and
280/// the copy got written to (two laptops syncing a Dropbox file; a
281/// restored older backup resuming operation), each copy's writer produced
282/// pages whose nonces collided with the other's at the same `(page_no,
283/// write_counter)` coordinates, under the same DEK (`random_dek()` only
284/// at create; `rekey` keeps it). That breaks AES-GCM's confidentiality
285/// and tamper-evidence guarantee: whoever holds both ciphertexts can
286/// recover the XOR of the plaintexts and forge pages with a valid tag.
287///
288/// A fresh random 64-bit `session_random` per writable open closes that:
289/// cross-copy collision now requires two sessions to independently draw
290/// the same 64-bit value (birthday bound ~2^32 sessions, i.e.
291/// astronomically unlikely for a human-scale user). The 32-bit
292/// `session_counter` guarantees uniqueness *within* a session; the pager
293/// regenerates `session_random` and resets the counter if it would wrap.
294///
295/// # Decrypt is unaffected
296///
297/// Each page already stores its own nonce in bytes `[0..12]` of the
298/// on-disk image (see `mnemo/src/pager.rs::read_page`). Decrypt reads the
299/// stored nonce; it never recomputes one. **No format bump — a v0.5.1
300/// file opens fine on v0.5.2 and vice versa.**
301pub fn session_page_nonce(session_random: u64, session_counter: u32) -> [u8; NONCE_LEN] {
302 let mut n = [0u8; NONCE_LEN];
303 n[0..8].copy_from_slice(&session_random.to_le_bytes());
304 n[8..12].copy_from_slice(&session_counter.to_le_bytes());
305 n
306}
307
308/// Wrap (encrypt) the DEK with the KEK. The wrap uses **empty AAD** in every
309/// version, so v5 wrapped-DEK bytes on disk round-trip unchanged through a v6
310/// build — only page encryption changed in v6.
311pub fn wrap_dek(
312 kek: &[u8; KEY_LEN],
313 nonce: &[u8; NONCE_LEN],
314 dek: &[u8; KEY_LEN],
315) -> Result<Vec<u8>> {
316 aead_encrypt(kek, nonce, dek, &[])
317}
318
319/// Unwrap (decrypt) the DEK with the KEK. A wrong KEK (wrong passphrase)
320/// fails authentication and is reported as [`MnemoError::WrongPassphrase`].
321pub fn unwrap_dek(
322 kek: &[u8; KEY_LEN],
323 nonce: &[u8; NONCE_LEN],
324 wrapped: &[u8],
325) -> Result<Zeroizing<[u8; KEY_LEN]>> {
326 let plain = cipher(kek)
327 .decrypt(
328 Nonce::from_slice(nonce),
329 Payload {
330 msg: wrapped,
331 aad: &[],
332 },
333 )
334 .map_err(|_| MnemoError::WrongPassphrase)?;
335 if plain.len() != KEY_LEN {
336 return Err(MnemoError::WrongPassphrase);
337 }
338 let mut dek = Zeroizing::new([0u8; KEY_LEN]);
339 dek.copy_from_slice(&plain);
340 Ok(dek)
341}