Skip to main content

passgen/
master.rs

1//! # Master passphrase mode
2//!
3//! In master passphrase mode, passphrases are not random, but derived from a master
4//! passphrase. The same master passphrase, domain, user and pattern always give the same
5//! passphrase, so there is no need to store it.
6//!
7//! This happens in two steps:
8//!
9//! 1. A [Master] key is [derived](Master::derive) from the master passphrase. This takes a lot
10//!    of memory and time on purpose (how much is set by the level), so that guessing the master
11//!    passphrase is expensive. It only has to be done once.
12//! 2. From the master key, the source of randomness for a domain and a user is
13//!    [derived](Master::random). This is fast.
14//!
15//! The master key also has a [hash](Master::hash). Storing the start of it is a way to notice
16//! a master passphrase that was mistyped.
17//!
18//! ## Version 1
19//!
20//! This is the same as in the C implementation of Passgen, and must never change: other
21//! parameters need a new version.
22//!
23//! - The master key is 32 bytes from Argon2id, with the memory of the level (see [Cost]),
24//!   3 passes and 1 lane. The master passphrase is the password, the salt is
25//!   `passgen/master/1`, and the seed is the secret key.
26//! - The key for a domain and a user is 32 bytes of BLAKE2b, keyed with the master key, of
27//!   `passgen/site`, the length of the domain in bytes (64 bits, little-endian), the domain,
28//!   the length of the user and the user. It is used for [ChaCha20] with the
29//!   [default IV](ChaCha20::DEFAULT_IV).
30//! - The hash is 32 bytes of BLAKE2b, keyed with the master key, of `passgen/hash`.
31//!
32//! ## Example
33//!
34//! ```
35//! use passgen::{master::{Cost, Master}, pattern::Pattern, random::RandomSource};
36//!
37//! // a real master key is derived with `Master::derive`, which needs a lot more memory.
38//! let cost = Cost { memory: 64, passes: 1 };
39//! let master = Master::derive_with_cost(1, cost, "correct horse battery staple", &[]).unwrap();
40//! let random = master.random("example.com", "alice");
41//!
42//! let pattern = Pattern::parse("[a-z]{8}").unwrap().optimize().0;
43//! let pattern = pattern.prepare(&()).unwrap();
44//! assert_eq!(pattern.generate(&mut random.stream(0)).unwrap(), "xmipkamt");
45//! ```
46
47use crate::random::ChaCha20;
48use argon2::{Algorithm, Argon2, ParamsBuilder};
49use blake2::{
50    Blake2bMac,
51    digest::{FixedOutput, KeyInit, Update, consts::U32},
52};
53
54/// The version that new master passphrases are set up with.
55pub const VERSION: u32 = 1;
56
57/// The level that is recommended, when there is no reason for another one.
58pub const LEVEL_DEFAULT: u32 = 2;
59
60/// The highest level there is. The lowest is one.
61pub const LEVEL_MAX: u32 = 3;
62
63/// How many bytes a seed can have.
64pub const SEED_MAX: usize = 64;
65
66/// Costs of the levels of version 1. These must never change, as that would change every
67/// passphrase derived from a master passphrase.
68const COSTS_V1: [Cost; LEVEL_MAX as usize] = [
69    Cost {
70        memory: 64 * 1024,
71        passes: 3,
72    },
73    Cost {
74        memory: 256 * 1024,
75        passes: 3,
76    },
77    Cost {
78        memory: 1024 * 1024,
79        passes: 3,
80    },
81];
82
83/// How much effort deriving a master key takes.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct Cost {
86    /// Memory that is needed, in kibibytes.
87    pub memory: u32,
88    /// How many times the memory is passed over.
89    pub passes: u32,
90}
91
92impl Cost {
93    /// The cost of a level in a version: 64 MiB, 256 MiB and 1 GiB of memory for the levels
94    /// 1, 2 and 3 of version 1.
95    pub fn level(version: u32, level: u32) -> Result<Self, Error> {
96        if version != 1 {
97            return Err(Error::Version(version));
98        }
99        level
100            .checked_sub(1)
101            .and_then(|index| COSTS_V1.get(index as usize))
102            .copied()
103            .ok_or(Error::Level(level))
104    }
105}
106
107/// Error deriving a master key.
108#[derive(thiserror::Error, Debug, Clone, PartialEq)]
109pub enum Error {
110    /// There is no such version.
111    #[error("unknown version {0} of master passphrase mode, only version 1 exists")]
112    Version(u32),
113    /// There is no such level.
114    #[error("unknown level {0}, it has to be from 1 to {LEVEL_MAX}")]
115    Level(u32),
116    /// The seed has more than [SEED_MAX] bytes.
117    #[error("seed is too long, it can have at most {SEED_MAX} bytes")]
118    SeedTooLong,
119    /// The cost is not one that a key can be derived with.
120    #[error("cost is not valid")]
121    Cost,
122    /// There is not enough memory to derive the key.
123    #[error("not enough memory to derive the master key")]
124    OutOfMemory,
125}
126
127/// Key derived from a master passphrase, which the passphrases for all domains and users are
128/// derived from.
129#[derive(Clone, PartialEq)]
130pub struct Master {
131    key: [u8; 32],
132}
133
134impl std::fmt::Debug for Master {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        // the key is a secret.
137        f.debug_struct("Master").finish_non_exhaustive()
138    }
139}
140
141impl Master {
142    /// Salt for deriving the key. It is fixed, so that nothing has to be stored. The seed is
143    /// what can be.
144    const SALT: &[u8] = b"passgen/master/1";
145
146    /// Derives the key from a master passphrase, with the cost of a level. With a seed (which
147    /// can be empty for none), the master passphrase alone is not enough to derive anything.
148    ///
149    /// This takes a while, and as much memory as the level says.
150    pub fn derive(version: u32, level: u32, passphrase: &str, seed: &[u8]) -> Result<Self, Error> {
151        let cost = Cost::level(version, level)?;
152        Self::derive_with_cost(version, cost, passphrase, seed)
153    }
154
155    /// Derives the key from a master passphrase with a cost that is not that of a level.
156    ///
157    /// Nothing else derives the same from the master passphrase. This is for tests, which
158    /// can use a cost that is small.
159    pub fn derive_with_cost(
160        version: u32,
161        cost: Cost,
162        passphrase: &str,
163        seed: &[u8],
164    ) -> Result<Self, Error> {
165        if version != 1 {
166            return Err(Error::Version(version));
167        }
168        if seed.len() > SEED_MAX {
169            return Err(Error::SeedTooLong);
170        }
171
172        let params = ParamsBuilder::new()
173            .m_cost(cost.memory)
174            .t_cost(cost.passes)
175            .p_cost(1)
176            .build()
177            .map_err(|_| Error::Cost)?;
178
179        let mut key = [0; 32];
180        Argon2::new_with_secret(seed, Algorithm::Argon2id, argon2::Version::V0x13, params)
181            .and_then(|argon2| {
182                argon2.hash_password_into(passphrase.as_bytes(), Self::SALT, &mut key)
183            })
184            .map_err(|error| match error {
185                argon2::Error::OutOfMemory => Error::OutOfMemory,
186                // what is left to fail are inputs of more than four gigabytes.
187                error => panic!("cannot derive the master key: {error}"),
188            })?;
189
190        Ok(Self { key })
191    }
192
193    /// Hash of the key, which tells whether a master passphrase is the right one without
194    /// storing it. Only the start of it should be stored: the more of it there is, the more
195    /// it helps someone who is guessing the master passphrase.
196    pub fn hash(&self) -> [u8; 32] {
197        let mut hash = self.keyed();
198        hash.update(b"passgen/hash");
199        hash.finalize_fixed().into()
200    }
201
202    /// The [hash](Master::hash) in hex, in lower case.
203    pub fn hash_hex(&self) -> String {
204        self.hash()
205            .iter()
206            .map(|byte| format!("{byte:02x}"))
207            .collect()
208    }
209
210    /// The source of randomness for a domain (such as `example.com`) and a user (such as the
211    /// name of an account), both of which can be empty. They are used as they are, so
212    /// `example.com` and `Example.com` are different domains.
213    pub fn random(&self, domain: &str, user: &str) -> ChaCha20 {
214        let mut hash = self.keyed();
215        hash.update(b"passgen/site");
216        // the lengths come first, so that where the domain ends is part of what is hashed.
217        for string in [domain, user] {
218            hash.update(&(string.len() as u64).to_le_bytes());
219            hash.update(string.as_bytes());
220        }
221
222        ChaCha20::new(hash.finalize_fixed().into(), ChaCha20::DEFAULT_IV)
223    }
224
225    /// BLAKE2b with the key, which gives 32 bytes.
226    fn keyed(&self) -> Blake2bMac<U32> {
227        Blake2bMac::new_from_slice(&self.key).expect("key has a valid length")
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    /// A cost that is small, so that tests are fast.
236    const COST: Cost = Cost {
237        memory: 64,
238        passes: 1,
239    };
240
241    fn master(passphrase: &str, seed: &[u8]) -> Master {
242        Master::derive_with_cost(1, COST, passphrase, seed).unwrap()
243    }
244
245    #[test]
246    fn levels() {
247        assert_eq!(Cost::level(1, 1).unwrap().memory, 64 * 1024);
248        assert_eq!(Cost::level(1, 2).unwrap().memory, 256 * 1024);
249        assert_eq!(Cost::level(1, 3).unwrap().memory, 1024 * 1024);
250        assert_eq!(Cost::level(1, 0), Err(Error::Level(0)));
251        assert_eq!(Cost::level(1, 4), Err(Error::Level(4)));
252        assert_eq!(Cost::level(0, 1), Err(Error::Version(0)));
253        assert_eq!(Cost::level(2, 1), Err(Error::Version(2)));
254    }
255
256    #[test]
257    fn derive_checks_inputs() {
258        assert_eq!(Master::derive(2, 1, "master", &[]), Err(Error::Version(2)));
259        assert_eq!(Master::derive(1, 9, "master", &[]), Err(Error::Level(9)));
260        assert_eq!(
261            Master::derive_with_cost(1, COST, "master", &[0; SEED_MAX + 1]),
262            Err(Error::SeedTooLong)
263        );
264        assert!(Master::derive_with_cost(1, COST, "master", &[0; SEED_MAX]).is_ok());
265
266        // argon2 needs at least eight blocks of memory, and one pass.
267        let cost = Cost {
268            memory: 7,
269            passes: 1,
270        };
271        assert_eq!(
272            Master::derive_with_cost(1, cost, "master", &[]),
273            Err(Error::Cost)
274        );
275        let cost = Cost {
276            memory: 64,
277            passes: 0,
278        };
279        assert_eq!(
280            Master::derive_with_cost(1, cost, "master", &[]),
281            Err(Error::Cost)
282        );
283    }
284
285    #[test]
286    fn inputs_matter() {
287        let masters = [
288            master("master", &[]),
289            master("other", &[]),
290            master("master", &[0]),
291            master("master", b"seed"),
292        ];
293        for (index, master) in masters.iter().enumerate() {
294            assert!(!masters[index + 1..].contains(master));
295        }
296        assert_eq!(master("master", &[]), masters[0]);
297
298        // the cost changes the key as well.
299        let cost = Cost {
300            memory: 128,
301            passes: 1,
302        };
303        let other = Master::derive_with_cost(1, cost, "master", &[]).unwrap();
304        assert_ne!(other, masters[0]);
305
306        let sites = [
307            ("", ""),
308            ("example.com", ""),
309            ("example.com", "user"),
310            ("example.com", "admin"),
311            ("example.org", "user"),
312            ("", "user"),
313            ("user", ""),
314            // where the domain ends matters.
315            ("ab", "c"),
316            ("a", "bc"),
317        ];
318        let sources: Vec<_> = sites
319            .iter()
320            .map(|(domain, user)| masters[0].random(domain, user))
321            .collect();
322        for (index, source) in sources.iter().enumerate() {
323            assert!(!sources[index + 1..].contains(source));
324        }
325        assert_eq!(masters[0].random("example.com", "user"), sources[2]);
326        assert_ne!(masters[1].random("example.com", "user"), sources[2]);
327    }
328
329    #[test]
330    fn hash() {
331        let first = master("master", &[]);
332        assert_eq!(first.hash(), master("master", &[]).hash());
333        assert_ne!(first.hash(), master("other", &[]).hash());
334        assert_ne!(first.hash(), master("master", b"seed").hash());
335
336        let hex = first.hash_hex();
337        assert_eq!(hex.len(), 64);
338        assert!(hex.bytes().all(|byte| b"0123456789abcdef".contains(&byte)));
339        assert_eq!(u8::from_str_radix(&hex[..2], 16), Ok(first.hash()[0]));
340    }
341
342    #[test]
343    fn debug_hides_key() {
344        assert_eq!(format!("{:?}", master("master", &[])), "Master { .. }");
345    }
346}