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, 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)]
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    /// Deliberately weak parameters — **only** for fast unit tests.
66    #[doc(hidden)]
67    pub fn fast() -> Self {
68        Self {
69            m_cost: 512,
70            t_cost: 1,
71            p_cost: 1,
72        }
73    }
74}
75
76impl Default for KdfParams {
77    fn default() -> Self {
78        Self::secure()
79    }
80}
81
82/// Derive the key-encryption-key (KEK) from a passphrase using Argon2id.
83pub fn derive_kek(
84    passphrase: &[u8],
85    salt: &[u8],
86    params: KdfParams,
87) -> Result<Zeroizing<[u8; KEY_LEN]>> {
88    let p = Params::new(params.m_cost, params.t_cost, params.p_cost, Some(KEY_LEN))
89        .map_err(|e| MnemoError::Kdf(e.to_string()))?;
90    let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, p);
91    let mut key = Zeroizing::new([0u8; KEY_LEN]);
92    argon
93        .hash_password_into(passphrase, salt, &mut key[..])
94        .map_err(|e| MnemoError::Kdf(e.to_string()))?;
95    Ok(key)
96}
97
98fn cipher(key: &[u8; KEY_LEN]) -> Aes256Gcm {
99    Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key))
100}
101
102/// AES-256-GCM encrypt with **Associated Authenticated Data**. The AAD is not
103/// part of the ciphertext but is bound into the authentication tag; decryption
104/// fails unless the caller supplies the same AAD. Output is
105/// `ciphertext || 16-byte tag`.
106///
107/// Pass `&[]` to encrypt without AAD — this matches the format before v6, used
108/// for wrapping the DEK and for v4/v5 page encryption. From v6 onwards, page
109/// encryption passes `page_no.to_le_bytes()` as AAD so an attacker can't
110/// transplant a valid encrypted page to a different page slot — the
111/// authentication tag binds the page image to its home page number.
112pub fn aead_encrypt(
113    key: &[u8; KEY_LEN],
114    nonce: &[u8; NONCE_LEN],
115    plaintext: &[u8],
116    aad: &[u8],
117) -> Result<Vec<u8>> {
118    cipher(key)
119        .encrypt(
120            Nonce::from_slice(nonce),
121            Payload {
122                msg: plaintext,
123                aad,
124            },
125        )
126        .map_err(|e| MnemoError::Crypto(e.to_string()))
127}
128
129/// AES-256-GCM decrypt with AAD. Input must be `ciphertext || 16-byte tag`.
130/// Returns an error if authentication fails — including when the supplied
131/// AAD doesn't match what was used during encryption.
132pub fn aead_decrypt(
133    key: &[u8; KEY_LEN],
134    nonce: &[u8; NONCE_LEN],
135    ciphertext: &[u8],
136    aad: &[u8],
137) -> Result<Vec<u8>> {
138    cipher(key)
139        .decrypt(
140            Nonce::from_slice(nonce),
141            Payload {
142                msg: ciphertext,
143                aad,
144            },
145        )
146        .map_err(|_| MnemoError::Crypto("authentication failed".into()))
147}
148
149/// Generate a fresh random 256-bit data-encryption-key.
150pub fn random_dek() -> Zeroizing<[u8; KEY_LEN]> {
151    use rand::RngCore;
152    let mut dek = Zeroizing::new([0u8; KEY_LEN]);
153    rand::thread_rng().fill_bytes(&mut dek[..]);
154    dek
155}
156
157/// Generate a random Argon2 salt.
158pub fn random_salt() -> [u8; SALT_LEN] {
159    use rand::RngCore;
160    let mut salt = [0u8; SALT_LEN];
161    rand::thread_rng().fill_bytes(&mut salt);
162    salt
163}
164
165/// Generate a random nonce (used for wrapping the DEK).
166pub fn random_nonce() -> [u8; NONCE_LEN] {
167    use rand::RngCore;
168    let mut n = [0u8; NONCE_LEN];
169    rand::thread_rng().fill_bytes(&mut n);
170    n
171}
172
173/// Generate a random `u64`, used by the pager to pick a per-session
174/// nonce prefix. See [`session_page_nonce`] for the full construction.
175pub fn random_u64() -> u64 {
176    use rand::RngCore;
177    rand::thread_rng().next_u64()
178}
179
180/// Build a per-session page nonce (PR SEC-1, v0.5.2).
181///
182/// Structure, following NIST SP 800-38D §8.2.1 (fixed field + invocation
183/// field) for AES-GCM:
184///
185/// - **Bytes 0..8** — `session_random`: a 64-bit random value drawn
186///   fresh on every writable [`crate::Mnemo::open`] / [`crate::Mnemo::create`]
187///   (and regenerated on counter wrap). This is the "fixed field".
188/// - **Bytes 8..12** — `session_counter`: a 32-bit per-session monotonic
189///   counter that advances once per encrypted page write. This is the
190///   "invocation field".
191///
192/// `page_no` is **not** encoded in the nonce. Pages were bound to their
193/// home slot through AAD since v6 (`page_no.to_le_bytes()`), so an
194/// attacker who swapped a valid page to a different slot already failed
195/// authentication — the AAD binding stays in place and does the job the
196/// `page_no` component of the pre-SEC-1 nonce was helping with.
197///
198/// # Why not deterministic any more
199///
200/// Before v0.5.2 the nonce was `page_no as u32 || write_counter as u64`,
201/// which was unique **within a file** but not **across copies of a file**.
202/// If you copied a `.mnemo` file to another host and both the original and
203/// the copy got written to (two laptops syncing a Dropbox file; a
204/// restored older backup resuming operation), each copy's writer produced
205/// pages whose nonces collided with the other's at the same `(page_no,
206/// write_counter)` coordinates, under the same DEK (`random_dek()` only
207/// at create; `rekey` keeps it). That breaks AES-GCM's confidentiality
208/// and tamper-evidence guarantee: whoever holds both ciphertexts can
209/// recover the XOR of the plaintexts and forge pages with a valid tag.
210///
211/// A fresh random 64-bit `session_random` per writable open closes that:
212/// cross-copy collision now requires two sessions to independently draw
213/// the same 64-bit value (birthday bound ~2^32 sessions, i.e.
214/// astronomically unlikely for a human-scale user). The 32-bit
215/// `session_counter` guarantees uniqueness *within* a session; the pager
216/// regenerates `session_random` and resets the counter if it would wrap.
217///
218/// # Decrypt is unaffected
219///
220/// Each page already stores its own nonce in bytes `[0..12]` of the
221/// on-disk image (see `mnemo/src/pager.rs::read_page`). Decrypt reads the
222/// stored nonce; it never recomputes one. **No format bump — a v0.5.1
223/// file opens fine on v0.5.2 and vice versa.**
224pub fn session_page_nonce(session_random: u64, session_counter: u32) -> [u8; NONCE_LEN] {
225    let mut n = [0u8; NONCE_LEN];
226    n[0..8].copy_from_slice(&session_random.to_le_bytes());
227    n[8..12].copy_from_slice(&session_counter.to_le_bytes());
228    n
229}
230
231/// Wrap (encrypt) the DEK with the KEK. The wrap uses **empty AAD** in every
232/// version, so v5 wrapped-DEK bytes on disk round-trip unchanged through a v6
233/// build — only page encryption changed in v6.
234pub fn wrap_dek(
235    kek: &[u8; KEY_LEN],
236    nonce: &[u8; NONCE_LEN],
237    dek: &[u8; KEY_LEN],
238) -> Result<Vec<u8>> {
239    aead_encrypt(kek, nonce, dek, &[])
240}
241
242/// Unwrap (decrypt) the DEK with the KEK. A wrong KEK (wrong passphrase)
243/// fails authentication and is reported as [`MnemoError::WrongPassphrase`].
244pub fn unwrap_dek(
245    kek: &[u8; KEY_LEN],
246    nonce: &[u8; NONCE_LEN],
247    wrapped: &[u8],
248) -> Result<Zeroizing<[u8; KEY_LEN]>> {
249    let plain = cipher(kek)
250        .decrypt(
251            Nonce::from_slice(nonce),
252            Payload {
253                msg: wrapped,
254                aad: &[],
255            },
256        )
257        .map_err(|_| MnemoError::WrongPassphrase)?;
258    if plain.len() != KEY_LEN {
259        return Err(MnemoError::WrongPassphrase);
260    }
261    let mut dek = Zeroizing::new([0u8; KEY_LEN]);
262    dek.copy_from_slice(&plain);
263    Ok(dek)
264}