1use crate::random::ChaCha20;
48use argon2::{Algorithm, Argon2, ParamsBuilder};
49use blake2::{
50 Blake2bMac,
51 digest::{FixedOutput, KeyInit, Update, consts::U32},
52};
53
54pub const VERSION: u32 = 1;
56
57pub const LEVEL_DEFAULT: u32 = 2;
59
60pub const LEVEL_MAX: u32 = 3;
62
63pub const SEED_MAX: usize = 64;
65
66const 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct Cost {
86 pub memory: u32,
88 pub passes: u32,
90}
91
92impl Cost {
93 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#[derive(thiserror::Error, Debug, Clone, PartialEq)]
109pub enum Error {
110 #[error("unknown version {0} of master passphrase mode, only version 1 exists")]
112 Version(u32),
113 #[error("unknown level {0}, it has to be from 1 to {LEVEL_MAX}")]
115 Level(u32),
116 #[error("seed is too long, it can have at most {SEED_MAX} bytes")]
118 SeedTooLong,
119 #[error("cost is not valid")]
121 Cost,
122 #[error("not enough memory to derive the master key")]
124 OutOfMemory,
125}
126
127#[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 f.debug_struct("Master").finish_non_exhaustive()
138 }
139}
140
141impl Master {
142 const SALT: &[u8] = b"passgen/master/1";
145
146 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 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 error => panic!("cannot derive the master key: {error}"),
188 })?;
189
190 Ok(Self { key })
191 }
192
193 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 pub fn hash_hex(&self) -> String {
204 self.hash()
205 .iter()
206 .map(|byte| format!("{byte:02x}"))
207 .collect()
208 }
209
210 pub fn random(&self, domain: &str, user: &str) -> ChaCha20 {
214 let mut hash = self.keyed();
215 hash.update(b"passgen/site");
216 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 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 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 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 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 ("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}