Skip to main content

passgen/
random.rs

1//! # Sources of randomness
2//!
3//! A [RandomSource] gives streams of random bytes, one for every passphrase that is
4//! generated. There are two kinds:
5//!
6//! * *Non-deterministic*: the random number generator of the system ([System]). This is the
7//!   default, for new passphrases that are stored somewhere.
8//! * *Deterministic*: a pseudorandom generator with a secret ([ChaCha20], which is what the
9//!   [master passphrase mode](crate::master) uses). The same secret always gives the same passphrases, so
10//!   they do not have to be stored.
11//!
12//! [Zero] and [Xorshift] are deterministic and not secure. They are there for testing.
13//!
14//! A source is usually made from a [RandomDesc], which is a description of one that can be
15//! parsed from a string.
16//!
17//! ## Streams
18//!
19//! Every passphrase is generated from a stream of its own, so that passphrases can be
20//! generated from several threads, and what one of them uses does not change the others.
21//! For the deterministic sources, the stream with an index always gives the same bytes,
22//! which are the same as in the C implementation of Passgen.
23//!
24//! ## Sampling
25//!
26//! A source of randomness only has to produce bytes, as a [RandomStream]. How these bytes are
27//! turned into choices is defined by that trait, and is the same as in the C implementation of
28//! Passgen. It must never change: for the deterministic sources, the same bytes have to result
29//! in the same passphrase, in every version and on every platform.
30//!
31//! ## Examples
32//!
33//! Streams of a deterministic source, which always give the same numbers.
34//!
35//! ```
36//! use passgen::random::*;
37//!
38//! // using the xorshift deterministic pseudorandom number generator
39//! let random = Xorshift::new(1234).unwrap();
40//!
41//! // stream zero
42//! let mut stream = random.stream(0);
43//! assert_eq!(stream.below(100), 91);
44//! assert_eq!(stream.below(100), 3);
45//!
46//! // stream one (independent from zero)
47//! let mut stream = random.stream(1);
48//! assert_eq!(stream.below(100), 47);
49//! assert_eq!(stream.below(100), 88);
50//! ```
51
52use crate::master::{self, Master};
53use chacha20::{
54    ChaCha20Legacy,
55    cipher::{KeyIvInit, StreamCipher},
56};
57use serde::Deserialize;
58use std::{num::NonZeroU64, str::FromStr};
59
60/// Stream of random bytes, and the way that Passgen makes choices with them.
61///
62/// Implementations only provide [read](RandomStream::read). What is read must be a plain
63/// stream of bytes: reading two bytes has to give the same as reading one byte twice.
64pub trait RandomStream {
65    /// Fills the buffer with random bytes.
66    fn read(&mut self, dest: &mut [u8]);
67
68    /// Returns a random 64 bit number, read as eight bytes in little-endian order.
69    fn u64(&mut self) -> u64 {
70        let mut data = [0; 8];
71        self.read(&mut data);
72        u64::from_le_bytes(data)
73    }
74
75    /// Returns a random boolean. Reads one byte, and is true if its highest bit is not set.
76    fn bool(&mut self) -> bool {
77        let mut data = [0; 1];
78        self.read(&mut data);
79        data[0] & 128 == 0
80    }
81
82    /// Returns a random number that is less than `max`, with every number being as likely as
83    /// any other.
84    ///
85    /// Reads 64 bit numbers and masks them with the smallest mask of the form *2ⁿ - 1* that
86    /// covers `max - 1`, until one of them is less than `max`. This also reads a number when
87    /// `max` is one. Where there is only one option, generating does not ask for a number.
88    ///
89    /// # Panics
90    ///
91    /// Panics if `max` is zero, because there is no number to return.
92    fn below(&mut self, max: u64) -> u64 {
93        assert!(max > 0, "cannot choose from nothing");
94        // a mask of zero (when there is only one choice) still reads a number.
95        let mask = match max - 1 {
96            0 => 0,
97            largest => u64::MAX >> largest.leading_zeros(),
98        };
99        loop {
100            let number = self.u64() & mask;
101            if number < max {
102                return number;
103            }
104        }
105    }
106}
107
108impl<T: RandomStream + ?Sized> RandomStream for &mut T {
109    fn read(&mut self, dest: &mut [u8]) {
110        (**self).read(dest)
111    }
112}
113
114impl<T: RandomStream + ?Sized> RandomStream for Box<T> {
115    fn read(&mut self, dest: &mut [u8]) {
116        (**self).read(dest)
117    }
118}
119
120/// Turns something that produces blocks of `N` bytes into a stream of bytes.
121#[derive(Debug, Clone)]
122struct Blocks<const N: usize> {
123    block: [u8; N],
124    /// How much of the block was read already.
125    position: usize,
126}
127
128impl<const N: usize> Blocks<N> {
129    fn new() -> Self {
130        Self {
131            block: [0; N],
132            position: N,
133        }
134    }
135
136    fn read(&mut self, mut dest: &mut [u8], mut next: impl FnMut(&mut [u8; N])) {
137        while !dest.is_empty() {
138            if self.position == N {
139                next(&mut self.block);
140                self.position = 0;
141            }
142            let length = dest.len().min(N - self.position);
143            let (head, tail) = dest.split_at_mut(length);
144            head.copy_from_slice(&self.block[self.position..self.position + length]);
145            self.position += length;
146            dest = tail;
147        }
148    }
149}
150
151/// Any of the sources of randomness.
152///
153/// This is usually created from a [RandomDesc]. It defaults to the [System] randomness
154/// generator, which is not deterministic.
155#[derive(Debug, Clone, PartialEq)]
156pub enum Random {
157    /// The random number generator of the system.
158    System(System),
159    /// Only zeroes.
160    Zero(Zero),
161    /// The xorshift generator with a seed.
162    Xorshift(Xorshift),
163    /// The ChaCha20 stream cipher with a key, also for the master passphrase mode.
164    ChaCha20(ChaCha20),
165}
166
167impl Default for Random {
168    fn default() -> Self {
169        Self::System(System)
170    }
171}
172
173impl Random {
174    /// Whether the stream with an index always gives the same bytes. This is so for every
175    /// source but that of the system.
176    pub fn is_deterministic(&self) -> bool {
177        !matches!(self, Self::System(_))
178    }
179}
180
181/// Description of a source of randomness.
182///
183/// This is only data: it says which source to use, and with what. It is what a user chooses
184/// the source of randomness with, and is [opened](RandomDesc::open) to get the [Random]
185/// source. It defaults to the [System] randomness generator.
186///
187/// ## Syntax
188///
189/// A description can be parsed from a string, in the syntax of the C implementation:
190///
191/// - `system`
192/// - `zero`
193/// - `xorshift:SEED`
194/// - `chacha20:KEY[:IV]`, where the key is 64 hex digits and the IV is 16 hex digits
195/// - `master:VERSION:LEVEL:PASSPHRASE:SEED:DOMAIN:USER`, which is the
196///   [master passphrase mode](crate::master). All six parts have to be there. The seed (in hex),
197///   the domain and the user can be empty. In the passphrase, the domain and the user, a colon
198///   is written as `\:` and a backslash as `\\`.
199///
200/// ```
201/// use passgen::random::*;
202///
203/// let desc: RandomDesc = "xorshift:1234".parse().unwrap();
204/// let random = desc.open().unwrap();
205/// assert_eq!(random.stream(0).below(100), 91);
206/// ```
207///
208/// It can also be deserialized, for use in configuration files. This uses a structured form
209/// (and not the syntax above): `"system"`, or `{"xorshift": {"seed": 1234}}`.
210#[derive(Clone, PartialEq, Default, Deserialize)]
211pub enum RandomDesc {
212    /// See [System].
213    #[default]
214    #[serde(rename = "system")]
215    System,
216    /// See [Zero].
217    #[serde(rename = "zero")]
218    Zero,
219    /// See [Xorshift].
220    #[serde(rename = "xorshift")]
221    Xorshift {
222        /// Seed of the generator.
223        seed: NonZeroU64,
224    },
225    /// See [ChaCha20].
226    #[serde(rename = "chacha20")]
227    ChaCha20 {
228        /// Key of the cipher.
229        key: [u8; 32],
230        /// IV of the cipher, which is [DEFAULT_IV](ChaCha20::DEFAULT_IV) without one.
231        #[serde(default = "default_iv")]
232        iv: [u8; 8],
233    },
234    /// Master passphrase mode, see [Master].
235    #[serde(rename = "master")]
236    Master {
237        /// How keys are derived.
238        version: u32,
239        /// How much effort deriving the master key takes.
240        level: u32,
241        /// The master passphrase.
242        passphrase: String,
243        /// The seed, which is empty when there is none.
244        #[serde(default)]
245        seed: Vec<u8>,
246        /// What the passphrases are for, such as the name of a website. Can be empty.
247        #[serde(default)]
248        domain: String,
249        /// Who the passphrases are for, such as the name of an account. Can be empty.
250        #[serde(default)]
251        user: String,
252    },
253}
254
255fn default_iv() -> [u8; 8] {
256    ChaCha20::DEFAULT_IV
257}
258
259impl std::fmt::Debug for RandomDesc {
260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        // keys and passphrases are secrets.
262        match self {
263            Self::System => f.write_str("System"),
264            Self::Zero => f.write_str("Zero"),
265            Self::Xorshift { seed } => f.debug_struct("Xorshift").field("seed", seed).finish(),
266            Self::ChaCha20 { .. } => f.debug_struct("ChaCha20").finish_non_exhaustive(),
267            Self::Master {
268                version,
269                level,
270                domain,
271                user,
272                ..
273            } => f
274                .debug_struct("Master")
275                .field("version", version)
276                .field("level", level)
277                .field("domain", domain)
278                .field("user", user)
279                .finish_non_exhaustive(),
280        }
281    }
282}
283
284impl RandomDesc {
285    /// Whether a description has a secret in it (a key or a master passphrase), going by how
286    /// it starts. This also works for one that cannot be parsed, so that an error about it
287    /// does not have to show it.
288    pub fn is_secret(input: &str) -> bool {
289        input.starts_with("chacha20:") || input.starts_with("master:")
290    }
291
292    /// Creates the source of randomness that this describes.
293    ///
294    /// For the master passphrase mode, this is what derives the key, which takes a while.
295    pub fn open(&self) -> Result<Random, master::Error> {
296        Ok(match self {
297            Self::System => Random::System(System),
298            Self::Zero => Random::Zero(Zero),
299            Self::Xorshift { seed } => Random::Xorshift(Xorshift(seed.get())),
300            Self::ChaCha20 { key, iv } => Random::ChaCha20(ChaCha20::new(*key, *iv)),
301            Self::Master {
302                version,
303                level,
304                passphrase,
305                seed,
306                domain,
307                user,
308            } => {
309                let master = Master::derive(*version, *level, passphrase, seed)?;
310                Random::ChaCha20(master.random(domain, user))
311            }
312        })
313    }
314}
315
316/// Error parsing a [RandomDesc] value from a string.
317#[derive(thiserror::Error, Debug, Clone, PartialEq)]
318pub enum ParseError {
319    /// Not one of the kinds of sources, or one without what it needs.
320    #[error("unknown randomness source '{0:}'")]
321    Unknown(String),
322    /// The seed of `xorshift:` is not a number that can be one.
323    #[error("invalid seed '{0:}', must be a number between 1 and 18446744073709551615")]
324    Seed(String),
325    /// The key of `chacha20:` is not 64 hex digits.
326    #[error("key must be 64 hex digits")]
327    Key,
328    /// The IV of `chacha20:` is not 16 hex digits.
329    #[error("IV must be 16 hex digits")]
330    Iv,
331    /// What follows `master:` is not six parts, or one of them is not valid. This does not
332    /// say more, so that it cannot show the master passphrase.
333    #[error(
334        "expected master:VERSION:LEVEL:PASSPHRASE:SEED:DOMAIN:USER, with a seed in hex, and \\: \
335         for colons"
336    )]
337    Master,
338    /// The version or the level of `master:` does not exist.
339    #[error(transparent)]
340    MasterLevel(#[from] master::Error),
341    /// A part of `master:` is longer than the C implementation allows.
342    #[error("master passphrase, domain and user can have at most {DESCRIPTION_MAX} bytes each")]
343    TooLong,
344}
345
346/// Decodes exactly `N` bytes from hex, see [hex_bytes].
347fn hex<const N: usize>(input: &str) -> Option<[u8; N]> {
348    hex_bytes(input)?.try_into().ok()
349}
350
351/// How long the master passphrase, the domain and the user can be in a description of a
352/// source of randomness. This is a limit of the C implementation.
353const DESCRIPTION_MAX: usize = 128;
354
355/// Splits what follows `master:` into its parts, at the colons. In a part, `\:` is a colon
356/// and `\\` is a backslash. A backslash before anything else is not valid.
357fn master_fields(input: &str) -> Option<Vec<String>> {
358    let mut fields = vec![String::new()];
359    let mut chars = input.chars();
360    while let Some(character) = chars.next() {
361        match character {
362            ':' => fields.push(String::new()),
363            '\\' => match chars.next()? {
364                escaped @ (':' | '\\') => fields.last_mut()?.push(escaped),
365                _ => return None,
366            },
367            character => fields.last_mut()?.push(character),
368        }
369    }
370    Some(fields)
371}
372
373/// Parses a version or a level: one to three digits, without leading zeroes.
374fn master_number(input: &str) -> Option<u32> {
375    let valid = (1..=3).contains(&input.len())
376        && input.bytes().all(|byte| byte.is_ascii_digit())
377        && (input.len() == 1 || !input.starts_with('0'));
378    valid.then(|| input.parse().ok()).flatten()
379}
380
381/// Decodes bytes from hex, with two digits for each of them, in upper or lower case.
382fn hex_bytes(input: &str) -> Option<Vec<u8>> {
383    if !input.len().is_multiple_of(2) {
384        return None;
385    }
386    input
387        .as_bytes()
388        .chunks(2)
389        .map(|pair| {
390            let high = (pair[0] as char).to_digit(16)?;
391            let low = (pair[1] as char).to_digit(16)?;
392            Some((high << 4 | low) as u8)
393        })
394        .collect()
395}
396
397/// Parses what follows `master:`.
398fn master_desc(params: &str) -> Result<RandomDesc, ParseError> {
399    let fields: [String; 6] = master_fields(params)
400        .and_then(|fields| fields.try_into().ok())
401        .ok_or(ParseError::Master)?;
402    let [version, level, passphrase, seed, domain, user] = fields;
403
404    // the version and the level have to be known.
405    let version = master_number(&version).ok_or(ParseError::Master)?;
406    let level = master_number(&level).ok_or(ParseError::Master)?;
407    master::Cost::level(version, level)?;
408
409    if [&passphrase, &domain, &user]
410        .iter()
411        .any(|part| part.len() > DESCRIPTION_MAX)
412    {
413        return Err(ParseError::TooLong);
414    }
415
416    let seed = hex_bytes(&seed).ok_or(ParseError::Master)?;
417    if seed.len() > master::SEED_MAX {
418        return Err(master::Error::SeedTooLong.into());
419    }
420
421    Ok(RandomDesc::Master {
422        version,
423        level,
424        passphrase,
425        seed,
426        domain,
427        user,
428    })
429}
430
431impl FromStr for RandomDesc {
432    type Err = ParseError;
433
434    fn from_str(input: &str) -> Result<Self, Self::Err> {
435        let (name, params) = match input.split_once(':') {
436            Some((name, params)) => (name, Some(params)),
437            None => (input, None),
438        };
439
440        match (name, params) {
441            ("system", None) => Ok(Self::System),
442            ("zero", None) => Ok(Self::Zero),
443            ("xorshift", Some(seed)) => seed
444                .parse()
445                .ok()
446                // only digits (parsing would accept a sign as well).
447                .filter(|_| seed.bytes().all(|byte| byte.is_ascii_digit()))
448                .map(|seed| Self::Xorshift { seed })
449                .ok_or_else(|| ParseError::Seed(seed.to_string())),
450            ("chacha20", Some(params)) => {
451                // the key and the IV are in hex, with exactly as many digits as they need.
452                // one that is too long is not cut off silently.
453                let (key, iv) = match params.split_once(':') {
454                    Some((key, iv)) => (key, Some(iv)),
455                    None => (params, None),
456                };
457
458                Ok(Self::ChaCha20 {
459                    key: hex(key).ok_or(ParseError::Key)?,
460                    iv: match iv {
461                        None => ChaCha20::DEFAULT_IV,
462                        Some(iv) => hex(iv).ok_or(ParseError::Iv)?,
463                    },
464                })
465            }
466            ("master", Some(params)) => master_desc(params),
467            _ => Err(ParseError::Unknown(input.to_string())),
468        }
469    }
470}
471
472/// Source of randomness, which gives a stream of random bytes for every passphrase.
473///
474/// For a source that is not deterministic, the streams can all be the same. For a
475/// deterministic one, they are independent of each other, and the stream with an index
476/// always gives the same bytes.
477pub trait RandomSource {
478    /// Underlying type of the streams of this randomness source.
479    type Stream: RandomStream + 'static;
480
481    /// The stream with an index.
482    fn stream(&self, index: u64) -> Self::Stream;
483
484    /// The stream with an index, as a trait object.
485    fn stream_boxed(&self, index: u64) -> Box<dyn RandomStream> {
486        Box::new(self.stream(index))
487    }
488}
489
490impl RandomSource for Random {
491    type Stream = Box<dyn RandomStream>;
492
493    fn stream(&self, index: u64) -> Box<dyn RandomStream> {
494        match self {
495            Self::System(random) => random.stream_boxed(index),
496            Self::Zero(random) => random.stream_boxed(index),
497            Self::Xorshift(random) => random.stream_boxed(index),
498            Self::ChaCha20(random) => random.stream_boxed(index),
499        }
500    }
501
502    fn stream_boxed(&self, index: u64) -> Box<dyn RandomStream> {
503        self.stream(index)
504    }
505}
506
507/// System randomness generator for secure, non-deterministic passphrase generation.
508#[derive(Debug, Clone, Copy, PartialEq, Default)]
509pub struct System;
510
511/// Stream of the [System] randomness generator.
512#[derive(Debug, Clone)]
513pub struct SystemStream(Blocks<1024>);
514
515impl RandomSource for System {
516    type Stream = SystemStream;
517
518    fn stream(&self, _index: u64) -> Self::Stream {
519        SystemStream(Blocks::new())
520    }
521}
522
523impl RandomStream for SystemStream {
524    /// # Panics
525    ///
526    /// Panics if the system cannot provide randomness.
527    fn read(&mut self, dest: &mut [u8]) {
528        self.0.read(dest, |block| {
529            getrandom::fill(block).expect("system randomness is not available")
530        })
531    }
532}
533
534/// Source of randomness that always returns zeroes.
535#[derive(Debug, Clone, Copy, PartialEq, Default)]
536pub struct Zero;
537
538impl RandomSource for Zero {
539    type Stream = Zero;
540
541    fn stream(&self, _index: u64) -> Self::Stream {
542        Zero
543    }
544}
545
546impl RandomStream for Zero {
547    fn read(&mut self, dest: &mut [u8]) {
548        dest.fill(0);
549    }
550}
551
552/// Pseudorandom generator based on xorshift64. Not secure, this exists for testing.
553#[derive(Debug, Clone, Copy, PartialEq)]
554pub struct Xorshift(u64);
555
556impl Xorshift {
557    /// Creates the generator from a seed, which can be any number but zero.
558    pub fn new(seed: u64) -> Option<Self> {
559        (seed != 0).then_some(Xorshift(seed))
560    }
561}
562
563/// Stream of the [Xorshift] generator: its outputs, as 64 bit numbers in little-endian order.
564#[derive(Debug, Clone)]
565pub struct XorshiftStream {
566    state: u64,
567    blocks: Blocks<8>,
568}
569
570impl RandomSource for Xorshift {
571    type Stream = XorshiftStream;
572
573    fn stream(&self, index: u64) -> Self::Stream {
574        // stream zero is the generator with the seed itself, as in the C implementation. this
575        // generator cannot jump ahead, so the other streams start from a state that mixes the
576        // index into the seed (with the finalizer of splitmix64).
577        let mut mix = index.wrapping_mul(0x9e3779b97f4a7c15);
578        mix = (mix ^ (mix >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
579        mix = (mix ^ (mix >> 27)).wrapping_mul(0x94d049bb133111eb);
580        mix ^= mix >> 31;
581
582        // the state must never be zero.
583        let state = match self.0 ^ mix {
584            0 => u64::MAX,
585            state => state,
586        };
587
588        XorshiftStream {
589            state,
590            blocks: Blocks::new(),
591        }
592    }
593}
594
595impl RandomStream for XorshiftStream {
596    fn read(&mut self, dest: &mut [u8]) {
597        let state = &mut self.state;
598        self.blocks.read(dest, |block| {
599            *state ^= *state << 13;
600            *state ^= *state >> 7;
601            *state ^= *state << 17;
602            *block = state.to_le_bytes();
603        })
604    }
605}
606
607/// Pseudorandom generator based on the ChaCha20 stream cipher: its keystream, in the original
608/// variant of the cipher (with a nonce of 64 bits).
609///
610/// This is what the [master passphrase mode](crate::master) uses.
611#[derive(Clone, Copy, PartialEq)]
612pub struct ChaCha20 {
613    key: [u8; 32],
614    iv: [u8; 8],
615}
616
617impl std::fmt::Debug for ChaCha20 {
618    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
619        // the key is a secret.
620        f.debug_struct("ChaCha20").finish_non_exhaustive()
621    }
622}
623
624impl ChaCha20 {
625    /// IV that is used unless another one is given.
626    pub const DEFAULT_IV: [u8; 8] = *b"passgen\0";
627
628    /// Creates the generator from a key and an IV.
629    pub fn new(key: [u8; 32], iv: [u8; 8]) -> Self {
630        Self { key, iv }
631    }
632}
633
634/// Stream of the [ChaCha20] generator.
635pub struct ChaCha20Stream(ChaCha20Legacy);
636
637impl RandomSource for ChaCha20 {
638    type Stream = ChaCha20Stream;
639
640    fn stream(&self, index: u64) -> Self::Stream {
641        // stream zero is the keystream for the IV itself. the other streams are the
642        // keystreams for other IVs: the IV as a number, XOR the index. this is the same as
643        // in the C implementation.
644        let iv = u64::from_le_bytes(self.iv) ^ index;
645        ChaCha20Stream(ChaCha20Legacy::new(
646            &self.key.into(),
647            &iv.to_le_bytes().into(),
648        ))
649    }
650}
651
652impl RandomStream for ChaCha20Stream {
653    fn read(&mut self, dest: &mut [u8]) {
654        // the keystream is what the cipher turns zeroes into.
655        dest.fill(0);
656        self.0.apply_keystream(dest);
657    }
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663    use test_strategy::*;
664
665    /// Stream that returns the given bytes, and counts how many were read.
666    struct Bytes<'a>(&'a [u8], usize);
667
668    impl RandomStream for Bytes<'_> {
669        fn read(&mut self, dest: &mut [u8]) {
670            dest.copy_from_slice(&self.0[self.1..self.1 + dest.len()]);
671            self.1 += dest.len();
672        }
673    }
674
675    #[test]
676    fn stream_u64_little_endian() {
677        let mut stream = Bytes(&[1, 2, 3, 4, 5, 6, 7, 8], 0);
678        assert_eq!(stream.u64(), 0x0807060504030201);
679    }
680
681    #[test]
682    fn stream_bool_highest_bit() {
683        let mut stream = Bytes(&[0, 127, 128, 255], 0);
684        assert_eq!(
685            [stream.bool(), stream.bool(), stream.bool(), stream.bool()],
686            [true, true, false, false]
687        );
688        assert_eq!(stream.1, 4);
689    }
690
691    #[test]
692    fn stream_below_masks_and_rejects() {
693        let numbers: Vec<u8> = [0xffu64, 0x106, 0x105, 0x1234]
694            .into_iter()
695            .flat_map(u64::to_le_bytes)
696            .collect();
697
698        // the mask for 6 is 7. 0xff & 7 is 7 and 0x106 & 7 is 6, which are rejected.
699        let mut stream = Bytes(&numbers, 0);
700        assert_eq!(stream.below(6), 5);
701        assert_eq!(stream.1, 24);
702
703        // a power of two never rejects.
704        let mut stream = Bytes(&numbers, 0);
705        assert_eq!(stream.below(8), 7);
706        assert_eq!(stream.below(256), 6);
707        assert_eq!(stream.1, 16);
708
709        // when there is only one choice, a number is read regardless.
710        let mut stream = Bytes(&numbers, 0);
711        assert_eq!(stream.below(1), 0);
712        assert_eq!(stream.1, 8);
713
714        // the largest number is rejected when everything but it can be chosen.
715        let numbers: Vec<u8> = [u64::MAX, u64::MAX - 1]
716            .into_iter()
717            .flat_map(u64::to_le_bytes)
718            .collect();
719        let mut stream = Bytes(&numbers, 0);
720        assert_eq!(stream.below(u64::MAX), u64::MAX - 1);
721        assert_eq!(stream.1, 16);
722    }
723
724    #[test]
725    #[should_panic]
726    fn stream_below_zero() {
727        Zero.below(0);
728    }
729
730    #[proptest]
731    fn stream_below_in_range(#[strategy(1u64..)] seed: u64, #[strategy(1u64..)] max: u64) {
732        let mut stream = Xorshift::new(seed).unwrap().stream(0);
733        for _ in 0..16 {
734            assert!(stream.below(max) < max);
735        }
736    }
737
738    /// However the bytes are asked for, they are the same.
739    #[proptest]
740    fn streams_are_bytes(index: u64, #[strategy(1u64..)] seed: u64, sizes: Vec<u8>) {
741        let sources = [
742            Random::Xorshift(Xorshift::new(seed).unwrap()),
743            Random::ChaCha20(ChaCha20::new([seed as u8; 32], seed.to_le_bytes())),
744        ];
745        for source in sources {
746            let total = sizes.iter().map(|size| *size as usize).sum();
747            let mut whole = vec![0; total];
748            source.stream(index).read(&mut whole);
749
750            let mut stream = source.stream(index);
751            let mut parts = vec![0; total];
752            let mut rest = &mut parts[..];
753            for size in &sizes {
754                let (part, tail) = rest.split_at_mut(*size as usize);
755                stream.read(part);
756                rest = tail;
757            }
758
759            assert_eq!(whole, parts);
760        }
761    }
762
763    #[test]
764    fn xorshift_stream() {
765        // the first outputs of xorshift64 with a seed of one.
766        let mut stream = Xorshift::new(1).unwrap().stream(0);
767        assert_eq!(stream.u64(), 0x40822041);
768        assert_eq!(stream.u64(), 0x100041060c011441);
769        assert_eq!(Xorshift::new(0), None);
770    }
771
772    #[test]
773    fn parse_random() {
774        let parse = |input: &str| input.parse::<RandomDesc>();
775        assert_eq!(parse("system"), Ok(RandomDesc::System));
776        assert_eq!(parse("zero"), Ok(RandomDesc::Zero));
777        assert_eq!(
778            parse("xorshift:18446744073709551615"),
779            Ok(RandomDesc::Xorshift {
780                seed: NonZeroU64::MAX
781            })
782        );
783        for seed in ["", "0", "+1", "-1", "abc", "1 ", "18446744073709551616"] {
784            assert_eq!(
785                parse(&format!("xorshift:{seed}")),
786                Err(ParseError::Seed(seed.into()))
787            );
788        }
789        for random in ["", "null", "xorshift", "zero:1", "xoshiro:1", "chacha20"] {
790            assert_eq!(parse(random), Err(ParseError::Unknown(random.into())));
791        }
792    }
793
794    #[test]
795    fn open_random() {
796        let open = |input: &str| input.parse::<RandomDesc>().unwrap().open().unwrap();
797        assert_eq!(RandomDesc::default().open(), Ok(Random::default()));
798        assert_eq!(open("system"), Random::System(System));
799        assert_eq!(open("zero"), Random::Zero(Zero));
800        assert_eq!(open("xorshift:5"), Random::Xorshift(Xorshift(5)));
801        assert_eq!(
802            open(&format!("chacha20:{}:{}", "6b".repeat(32), "69".repeat(8))),
803            Random::ChaCha20(ChaCha20::new([b'k'; 32], [b'i'; 8]))
804        );
805        assert_eq!(
806            open("master:1:1:a:00:b:c"),
807            Random::ChaCha20(Master::derive(1, 1, "a", &[0]).unwrap().random("b", "c"))
808        );
809    }
810
811    #[test]
812    fn debug_hides_secrets() {
813        // the key is `secret` four times, and then eight more bytes.
814        let key = format!("{}{}", "736563726574".repeat(4), "00".repeat(8));
815        for random in [
816            format!("chacha20:{key}"),
817            "master:1:1:secret:736563726574:domain:user".to_string(),
818        ] {
819            let desc: RandomDesc = random.parse().unwrap();
820            for debug in [format!("{desc:?}"), format!("{:?}", desc.open().unwrap())] {
821                assert!(!debug.contains("secret"));
822                assert!(!debug.contains("736563"));
823                // bytes of the key as numbers
824                assert!(!debug.contains("115, 101, 99"));
825            }
826        }
827    }
828
829    #[test]
830    fn deserialize_random() {
831        let parse = |input: &str| serde_json::from_str::<RandomDesc>(input).unwrap();
832        assert_eq!(parse(r#""system""#), RandomDesc::System);
833        assert_eq!(parse(r#""zero""#), RandomDesc::Zero);
834        assert_eq!(
835            parse(r#"{"xorshift": {"seed": 1234}}"#),
836            "xorshift:1234".parse().unwrap()
837        );
838        assert_eq!(
839            parse(r#"{"master": {"version": 1, "level": 2, "passphrase": "a", "domain": "b"}}"#),
840            "master:1:2:a::b:".parse().unwrap()
841        );
842        assert_eq!(
843            parse(&format!(r#"{{"chacha20": {{"key": {:?}}}}}"#, [97; 32])),
844            format!("chacha20:{}", "61".repeat(32)).parse().unwrap()
845        );
846        // the seed cannot be zero.
847        assert!(serde_json::from_str::<RandomDesc>(r#"{"xorshift": {"seed": 0}}"#).is_err());
848    }
849
850    #[test]
851    fn chacha20_stream() {
852        // test vector for the original ChaCha20: a key and an IV of zeroes.
853        let mut stream = ChaCha20::new([0; 32], [0; 8]).stream(0);
854        let mut data = [0; 16];
855        stream.read(&mut data);
856        assert_eq!(
857            data,
858            [
859                0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86,
860                0xbd, 0x28
861            ]
862        );
863    }
864
865    #[test]
866    fn chacha20_streams_differ() {
867        let random = ChaCha20::new([1; 32], ChaCha20::DEFAULT_IV);
868        let numbers = |index| {
869            let mut stream = random.stream(index);
870            [stream.u64(), stream.u64()]
871        };
872        assert_eq!(numbers(0), numbers(0));
873        assert_ne!(numbers(0), numbers(1));
874        assert_ne!(numbers(1), numbers(2));
875    }
876
877    #[test]
878    fn parse_chacha20() {
879        let parse = |input: &str| match input.parse::<RandomDesc>() {
880            Ok(RandomDesc::ChaCha20 { key, iv }) => Ok((key, iv)),
881            Ok(other) => panic!("not chacha20: {other:?}"),
882            Err(error) => Err(error),
883        };
884
885        let mut key = [0; 32];
886        key[..3].copy_from_slice(b"key");
887        let hex_key = format!("6b6579{}", "0".repeat(58));
888        assert_eq!(
889            parse(&format!("chacha20:{hex_key}")),
890            Ok((key, *b"passgen\0"))
891        );
892        assert_eq!(
893            parse(&format!("chacha20:{hex_key}:6976000000000000")),
894            Ok((key, *b"iv\0\0\0\0\0\0"))
895        );
896
897        // upper and lower case.
898        assert_eq!(
899            parse(&format!("chacha20:{}:{}", "fF".repeat(32), "Ab".repeat(8))),
900            Ok(([0xff; 32], [0xab; 8]))
901        );
902
903        // exactly as many digits as are needed, and nothing else.
904        for key in [
905            "",
906            "key",
907            &hex_key[1..],
908            &format!("{hex_key}00"),
909            &hex_key.replace('6', "g"),
910        ] {
911            assert_eq!(
912                parse(&format!("chacha20:{key}")),
913                Err(ParseError::Key),
914                "{key}"
915            );
916        }
917        for iv in [
918            "",
919            "iv",
920            "69760000000000",
921            "697600000000000000",
922            "+976000000000000",
923        ] {
924            assert_eq!(
925                parse(&format!("chacha20:{hex_key}:{iv}")),
926                Err(ParseError::Iv),
927                "{iv}"
928            );
929        }
930        assert_eq!(
931            parse(&format!("chacha20:{hex_key}:6976000000000000:")),
932            Err(ParseError::Iv)
933        );
934    }
935
936    #[test]
937    fn parse_master() {
938        let parse = |input: &str| input.parse::<RandomDesc>();
939        let master = |passphrase: &str, seed: &[u8], domain: &str, user: &str| {
940            Ok(RandomDesc::Master {
941                version: 1,
942                level: 1,
943                passphrase: passphrase.into(),
944                seed: seed.into(),
945                domain: domain.into(),
946                user: user.into(),
947            })
948        };
949        assert_eq!(parse("master:1:1:master:::"), master("master", &[], "", ""));
950        assert_eq!(parse("master:1:1:a::b:c"), master("a", &[], "b", "c"));
951        assert_eq!(parse("master:1:1:a:::c"), master("a", &[], "", "c"));
952        assert_eq!(parse("master:1:1::::"), master("", &[], "", ""));
953        assert_eq!(
954            parse("master:1:1:a:00fFa1:b:c"),
955            master("a", &[0, 255, 161], "b", "c")
956        );
957        assert!(matches!(
958            parse("master:1:3:a::b:c"),
959            Ok(RandomDesc::Master { level: 3, .. })
960        ));
961
962        // colons and backslashes are escaped.
963        assert_eq!(
964            parse(r"master:1:1:pass\:word\\::example.com\:8443:us\\er"),
965            master(r"pass:word\", &[], "example.com:8443", r"us\er")
966        );
967
968        // all six parts have to be there, and no more.
969        for random in [
970            "master:",
971            "master:1:1:a",
972            "master:1:1:a::b",
973            "master:1:1:a::b:c:",
974            "master:1:1:a::b:c:d",
975            // any other backslash is not valid, also at the end.
976            r"master:1:1:pa\ss::b:c",
977            r"master:1:1:a::b:c\",
978            // the version and the level are numbers without anything else.
979            "master::1:a::b:c",
980            "master:1::a::b:c",
981            "master:01:1:a::b:c",
982            "master:1:+1:a::b:c",
983            "master:1:1000:a::b:c",
984            "master:x:1:a::b:c",
985            // the seed is bytes in hex.
986            "master:1:1:a:0:b:c",
987            "master:1:1:a:0g:b:c",
988            "master:1:1:a:seed:b:c",
989        ] {
990            assert_eq!(parse(random), Err(ParseError::Master), "{random}");
991        }
992
993        // versions and levels that do not exist.
994        assert_eq!(
995            parse("master:2:1:a::b:c"),
996            Err(ParseError::MasterLevel(master::Error::Version(2)))
997        );
998        assert_eq!(
999            parse("master:1:4:a::b:c"),
1000            Err(ParseError::MasterLevel(master::Error::Level(4)))
1001        );
1002        assert_eq!(
1003            parse("master:1:0:a::b:c"),
1004            Err(ParseError::MasterLevel(master::Error::Level(0)))
1005        );
1006    }
1007
1008    #[test]
1009    fn parse_master_limits() {
1010        let parse = |input: &str| input.parse::<RandomDesc>();
1011        let fits = "a".repeat(DESCRIPTION_MAX);
1012        assert!(parse(&format!("master:1:1:{fits}::{fits}:{fits}")).is_ok());
1013
1014        let long = format!("{fits}a");
1015        for random in [
1016            format!("master:1:1:{long}::b:c"),
1017            format!("master:1:1:a::{long}:c"),
1018            format!("master:1:1:a::b:{long}"),
1019        ] {
1020            assert_eq!(parse(&random), Err(ParseError::TooLong));
1021        }
1022
1023        let seed = "00".repeat(master::SEED_MAX);
1024        assert!(parse(&format!("master:1:1:a:{seed}:b:c")).is_ok());
1025        assert_eq!(
1026            parse(&format!("master:1:1:a:{seed}00:b:c")),
1027            Err(ParseError::MasterLevel(master::Error::SeedTooLong))
1028        );
1029    }
1030
1031    #[test]
1032    fn secret_descriptions() {
1033        for random in ["system", "zero", "xorshift:1", "chacha20", "unknown:x"] {
1034            assert!(!RandomDesc::is_secret(random), "{random}");
1035        }
1036        for random in ["chacha20:", "chacha20:key", "master:", "master:1:1:a"] {
1037            assert!(RandomDesc::is_secret(random), "{random}");
1038        }
1039    }
1040}