|
| 1 | +//! The sealed envelope — password-locked, self-describing, zero-knowledge. |
| 2 | +//! |
| 3 | +//! [`seal`] runs client-side (browser wasm or native): it derives a key |
| 4 | +//! from the password with Argon2id, draws a fresh salt + XChaCha20 |
| 5 | +//! nonce from the CSPRNG, and returns one opaque blob. A server that |
| 6 | +//! stores the blob learns **nothing** — the password never leaves the |
| 7 | +//! client, and the blob authenticates its own header, so any tampering |
| 8 | +//! (including with the cost parameters) makes [`open`] fail. |
| 9 | +//! |
| 10 | +//! ## Byte layout (fixed, little-endian, parsed by hand — no serde) |
| 11 | +//! |
| 12 | +//! ```text |
| 13 | +//! offset len field |
| 14 | +//! 0 4 magic = b"ADAC" |
| 15 | +//! 4 1 version = 1 |
| 16 | +//! 5 4 m_cost_kib (u32 LE) Argon2id memory cost |
| 17 | +//! 9 4 t_cost (u32 LE) Argon2id passes |
| 18 | +//! 13 4 p_cost (u32 LE) Argon2id lanes |
| 19 | +//! 17 16 salt fresh CSPRNG bytes per seal |
| 20 | +//! 33 24 nonce fresh CSPRNG bytes per seal |
| 21 | +//! 57 … ciphertext ‖ 16-byte Poly1305 tag |
| 22 | +//! ``` |
| 23 | +//! |
| 24 | +//! The first 57 bytes (the header) are the AEAD's associated data, so |
| 25 | +//! they are integrity-bound to the ciphertext: an attacker cannot, for |
| 26 | +//! example, lower `m_cost_kib` to cheapen an offline guess and still |
| 27 | +//! have the blob open. |
| 28 | +
|
| 29 | +use crate::aead::{self, NONCE_LEN}; |
| 30 | +pub use crate::kdf::KdfParams; |
| 31 | +use crate::kdf::{self, KdfError}; |
| 32 | + |
| 33 | +/// Envelope magic: "ADAC" (Ada crypto). |
| 34 | +pub const MAGIC: [u8; 4] = *b"ADAC"; |
| 35 | +/// Current envelope layout version. |
| 36 | +pub const VERSION: u8 = 1; |
| 37 | +/// Salt length stored in the header. |
| 38 | +pub const SALT_LEN: usize = 16; |
| 39 | +/// Total header length preceding the ciphertext. |
| 40 | +pub const HEADER_LEN: usize = 4 + 1 + 4 + 4 + 4 + SALT_LEN + NONCE_LEN; // 57 |
| 41 | + |
| 42 | +/// Why an envelope could not be sealed or opened. Field-free — an |
| 43 | +/// `open` failure never says *which* part was wrong. |
| 44 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 45 | +pub enum EnvelopeError { |
| 46 | + /// The platform CSPRNG was unavailable (seal only). |
| 47 | + Rng, |
| 48 | + /// The Argon2id parameters were rejected. |
| 49 | + Kdf(KdfError), |
| 50 | + /// The blob is not an envelope (bad magic, short buffer). |
| 51 | + Malformed, |
| 52 | + /// The blob's layout version is newer than this code understands. |
| 53 | + UnsupportedVersion, |
| 54 | + /// Wrong password, or the blob was tampered with. Indistinguishable |
| 55 | + /// by design. |
| 56 | + Decrypt, |
| 57 | + /// Encryption failed (should not happen with valid inputs). |
| 58 | + Encrypt, |
| 59 | +} |
| 60 | + |
| 61 | +impl core::fmt::Display for EnvelopeError { |
| 62 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 63 | + match self { |
| 64 | + EnvelopeError::Rng => f.write_str("platform CSPRNG unavailable"), |
| 65 | + EnvelopeError::Kdf(e) => write!(f, "key derivation failed: {e}"), |
| 66 | + EnvelopeError::Malformed => f.write_str("not a sealed envelope"), |
| 67 | + EnvelopeError::UnsupportedVersion => f.write_str("unsupported envelope version"), |
| 68 | + EnvelopeError::Decrypt => f.write_str("wrong password or tampered envelope"), |
| 69 | + EnvelopeError::Encrypt => f.write_str("encryption failed"), |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +impl std::error::Error for EnvelopeError {} |
| 75 | + |
| 76 | +/// Seal `plaintext` under `password`. Draws salt + nonce from the |
| 77 | +/// CSPRNG, so sealing the same input twice yields different blobs. |
| 78 | +pub fn seal(password: &[u8], plaintext: &[u8], params: &KdfParams) -> Result<Vec<u8>, EnvelopeError> { |
| 79 | + let mut salt = [0u8; SALT_LEN]; |
| 80 | + crate::fill_random(&mut salt).map_err(|_| EnvelopeError::Rng)?; |
| 81 | + let mut nonce = [0u8; NONCE_LEN]; |
| 82 | + crate::fill_random(&mut nonce).map_err(|_| EnvelopeError::Rng)?; |
| 83 | + |
| 84 | + let header = encode_header(params, &salt, &nonce); |
| 85 | + let key = kdf::derive_key(password, &salt, params).map_err(EnvelopeError::Kdf)?; |
| 86 | + let ciphertext = |
| 87 | + aead::seal_with_key(key.as_bytes(), &nonce, &header, plaintext).map_err(|_| EnvelopeError::Encrypt)?; |
| 88 | + |
| 89 | + let mut blob = Vec::with_capacity(HEADER_LEN + ciphertext.len()); |
| 90 | + blob.extend_from_slice(&header); |
| 91 | + blob.extend_from_slice(&ciphertext); |
| 92 | + Ok(blob) |
| 93 | +} |
| 94 | + |
| 95 | +/// Open a sealed envelope with `password`. The KDF parameters are read |
| 96 | +/// from the (authenticated) header, so cost bumps never orphan old blobs. |
| 97 | +pub fn open(password: &[u8], blob: &[u8]) -> Result<Vec<u8>, EnvelopeError> { |
| 98 | + let (params, salt, nonce) = decode_header(blob)?; |
| 99 | + let header = &blob[..HEADER_LEN]; |
| 100 | + let ciphertext = &blob[HEADER_LEN..]; |
| 101 | + |
| 102 | + let key = kdf::derive_key(password, &salt, ¶ms).map_err(EnvelopeError::Kdf)?; |
| 103 | + aead::open_with_key(key.as_bytes(), &nonce, header, ciphertext).map_err(|_| EnvelopeError::Decrypt) |
| 104 | +} |
| 105 | + |
| 106 | +fn encode_header(params: &KdfParams, salt: &[u8; SALT_LEN], nonce: &[u8; NONCE_LEN]) -> [u8; HEADER_LEN] { |
| 107 | + let mut h = [0u8; HEADER_LEN]; |
| 108 | + h[0..4].copy_from_slice(&MAGIC); |
| 109 | + h[4] = VERSION; |
| 110 | + h[5..9].copy_from_slice(¶ms.m_cost_kib.to_le_bytes()); |
| 111 | + h[9..13].copy_from_slice(¶ms.t_cost.to_le_bytes()); |
| 112 | + h[13..17].copy_from_slice(¶ms.p_cost.to_le_bytes()); |
| 113 | + h[17..17 + SALT_LEN].copy_from_slice(salt); |
| 114 | + h[33..33 + NONCE_LEN].copy_from_slice(nonce); |
| 115 | + h |
| 116 | +} |
| 117 | + |
| 118 | +fn decode_header(blob: &[u8]) -> Result<(KdfParams, [u8; SALT_LEN], [u8; NONCE_LEN]), EnvelopeError> { |
| 119 | + if blob.len() < HEADER_LEN || blob[0..4] != MAGIC { |
| 120 | + return Err(EnvelopeError::Malformed); |
| 121 | + } |
| 122 | + if blob[4] != VERSION { |
| 123 | + return Err(EnvelopeError::UnsupportedVersion); |
| 124 | + } |
| 125 | + let le_u32 = |at: usize| u32::from_le_bytes([blob[at], blob[at + 1], blob[at + 2], blob[at + 3]]); |
| 126 | + let params = KdfParams { |
| 127 | + m_cost_kib: le_u32(5), |
| 128 | + t_cost: le_u32(9), |
| 129 | + p_cost: le_u32(13), |
| 130 | + }; |
| 131 | + let mut salt = [0u8; SALT_LEN]; |
| 132 | + salt.copy_from_slice(&blob[17..17 + SALT_LEN]); |
| 133 | + let mut nonce = [0u8; NONCE_LEN]; |
| 134 | + nonce.copy_from_slice(&blob[33..33 + NONCE_LEN]); |
| 135 | + Ok((params, salt, nonce)) |
| 136 | +} |
| 137 | + |
| 138 | +#[cfg(test)] |
| 139 | +mod tests { |
| 140 | + use super::*; |
| 141 | + |
| 142 | + const FAST: KdfParams = KdfParams { |
| 143 | + m_cost_kib: 32, |
| 144 | + t_cost: 1, |
| 145 | + p_cost: 1, |
| 146 | + }; |
| 147 | + |
| 148 | + #[test] |
| 149 | + fn round_trip() { |
| 150 | + let blob = seal(b"hunter2", b"the secret", &FAST).unwrap(); |
| 151 | + assert_eq!(open(b"hunter2", &blob).unwrap(), b"the secret"); |
| 152 | + } |
| 153 | + |
| 154 | + #[test] |
| 155 | + fn wrong_password_fails_opaquely() { |
| 156 | + let blob = seal(b"right", b"s", &FAST).unwrap(); |
| 157 | + assert_eq!(open(b"wrong", &blob).unwrap_err(), EnvelopeError::Decrypt); |
| 158 | + } |
| 159 | + |
| 160 | + #[test] |
| 161 | + fn same_input_two_seals_differ() { |
| 162 | + let a = seal(b"pw", b"s", &FAST).unwrap(); |
| 163 | + let b = seal(b"pw", b"s", &FAST).unwrap(); |
| 164 | + assert_ne!(a, b, "salt+nonce must be fresh per seal"); |
| 165 | + } |
| 166 | + |
| 167 | + #[test] |
| 168 | + fn header_tamper_fails() { |
| 169 | + let mut blob = seal(b"pw", b"s", &FAST).unwrap(); |
| 170 | + // Attacker tries to cheapen the KDF cost in the header. |
| 171 | + blob[5] = 1; // m_cost_kib low byte |
| 172 | + assert!(open(b"pw", &blob).is_err()); |
| 173 | + } |
| 174 | + |
| 175 | + #[test] |
| 176 | + fn ciphertext_tamper_fails() { |
| 177 | + let mut blob = seal(b"pw", b"s", &FAST).unwrap(); |
| 178 | + let last = blob.len() - 1; |
| 179 | + blob[last] ^= 0x80; |
| 180 | + assert_eq!(open(b"pw", &blob).unwrap_err(), EnvelopeError::Decrypt); |
| 181 | + } |
| 182 | + |
| 183 | + #[test] |
| 184 | + fn malformed_inputs_rejected() { |
| 185 | + assert_eq!(open(b"pw", b"").unwrap_err(), EnvelopeError::Malformed); |
| 186 | + assert_eq!(open(b"pw", &[0u8; HEADER_LEN]).unwrap_err(), EnvelopeError::Malformed); |
| 187 | + let mut blob = seal(b"pw", b"s", &FAST).unwrap(); |
| 188 | + blob[4] = 99; |
| 189 | + assert_eq!(open(b"pw", &blob).unwrap_err(), EnvelopeError::UnsupportedVersion); |
| 190 | + } |
| 191 | + |
| 192 | + #[test] |
| 193 | + fn empty_plaintext_round_trips() { |
| 194 | + let blob = seal(b"pw", b"", &FAST).unwrap(); |
| 195 | + assert_eq!(blob.len(), HEADER_LEN + crate::aead::TAG_LEN); |
| 196 | + assert_eq!(open(b"pw", &blob).unwrap(), b""); |
| 197 | + } |
| 198 | +} |
0 commit comments