Skip to main content

passgen/
generate.rs

1use super::pattern::*;
2use crate::{entropy::Entropy, random::RandomStream};
3use std::fmt::Write;
4
5type Pattern = super::pattern::Pattern<Prepared>;
6type Group = super::pattern::Group<Prepared>;
7type Set = super::pattern::Set<Prepared>;
8type Segment = super::pattern::Segment<Prepared>;
9type Item = super::pattern::Item<Prepared>;
10type Special = super::pattern::Special<Prepared>;
11type Literal = super::pattern::Literal<Prepared>;
12
13/// Error generating a passphrase.
14#[derive(thiserror::Error, Debug)]
15pub enum Error {
16    /// What the passphrase is written to did not accept it.
17    #[error("cannot write the passphrase to the output")]
18    Write(#[from] std::fmt::Error),
19    /// Generating takes more steps than the limit allows.
20    #[error("takes too many steps")]
21    StepLimit,
22}
23
24/// How many steps generating a passphrase may take, unless another limit is given.
25///
26/// Without a limit, a short pattern can take practically forever and need any amount of
27/// memory: `a{999999999}` repeats that many times, and repetitions that are nested multiply.
28/// This matters when patterns come from someone else.
29///
30/// Every time a part of a pattern is generated is a step: a character of a set, a run of
31/// literal characters, a word or a group, and each of its repetitions counts. So `[a-z]{20}`
32/// takes 20 steps. Steps are counted for the pattern as it is after optimizing, where
33/// `(ab){3}` is a single run of characters.
34pub const STEP_LIMIT: usize = 1_000_000;
35
36pub trait Generate {
37    /// Writes what is generated to the output, and returns the entropy of the choices that
38    /// were made. Takes steps from those that are left, and fails when there are none.
39    fn generate(
40        &self,
41        rand: &mut dyn RandomStream,
42        output: &mut dyn Write,
43        steps: &mut usize,
44    ) -> Result<Entropy, Error>;
45}
46
47impl Pattern {
48    /// Generates a passphrase.
49    pub fn generate(&self, rng: &mut dyn RandomStream) -> Result<String, Error> {
50        let (output, _entropy) = self.generate_with_entropy(rng)?;
51        Ok(output)
52    }
53
54    /// Generates a passphrase, and measures the [entropy](crate::entropy) of the choices that
55    /// were made for it.
56    pub fn generate_with_entropy(
57        &self,
58        rng: &mut dyn RandomStream,
59    ) -> Result<(String, Entropy), Error> {
60        let mut output = String::new();
61        let entropy = self.generate_into(rng, &mut output)?;
62        Ok((output, entropy))
63    }
64
65    /// Generates a passphrase and writes it to the output. Returns the
66    /// [entropy](crate::entropy) of the choices that were made for it.
67    pub fn generate_into(
68        &self,
69        rng: &mut dyn RandomStream,
70        output: &mut dyn Write,
71    ) -> Result<Entropy, Error> {
72        self.generate_limited(rng, output, STEP_LIMIT)
73    }
74
75    /// Generates a passphrase and writes it to the output, in no more than a number of
76    /// steps (see [STEP_LIMIT], which is what the other methods use). Returns the
77    /// [entropy](crate::entropy) of the choices that were made for it.
78    ///
79    /// When it would take more steps, this fails. What was generated up to then has been
80    /// written to the output.
81    pub fn generate_limited(
82        &self,
83        rng: &mut dyn RandomStream,
84        output: &mut dyn Write,
85        mut steps: usize,
86    ) -> Result<Entropy, Error> {
87        Generate::generate(self, rng, output, &mut steps)
88    }
89}
90
91impl Generate for Pattern {
92    fn generate(
93        &self,
94        rand: &mut dyn RandomStream,
95        output: &mut dyn Write,
96        steps: &mut usize,
97    ) -> Result<Entropy, Error> {
98        match self {
99            Pattern::Group(group) => group.generate(rand, output, steps),
100            Pattern::Set(set) => set.generate(rand, output, steps),
101            Pattern::Literal(literal) => literal.generate(rand, output, steps),
102            Pattern::Special(special) => special.generate(rand, output, steps),
103        }
104    }
105}
106
107impl Generate for Group {
108    fn generate(
109        &self,
110        rand: &mut dyn RandomStream,
111        output: &mut dyn Write,
112        steps: &mut usize,
113    ) -> Result<Entropy, Error> {
114        // segments are chosen according to their weights.
115        let total: usize = self.segments.iter().map(|segment| segment.weight).sum();
116        if total == 0 {
117            return Ok(Entropy::ZERO);
118        }
119
120        // one of the segments is chosen. if there is only one, there is nothing to choose,
121        // which takes no randomness. this makes `(abc)` the same as `abc`.
122        let mut index = match self.segments.len() {
123            1 => 0,
124            _ => rand.below(total as u64) as usize,
125        };
126        for segment in &self.segments {
127            if index < segment.weight {
128                let choice = Entropy::weighted(segment.weight as u64, total as u64);
129                return Ok(choice + segment.generate(rand, output, steps)?);
130            }
131            index -= segment.weight;
132        }
133
134        unreachable!()
135    }
136}
137
138impl Generate for Segment {
139    fn generate(
140        &self,
141        rand: &mut dyn RandomStream,
142        output: &mut dyn Write,
143        steps: &mut usize,
144    ) -> Result<Entropy, Error> {
145        let mut entropy = Entropy::ZERO;
146        for item in &self.items {
147            entropy += item.generate(rand, output, steps)?;
148        }
149
150        Ok(entropy)
151    }
152}
153
154impl Generate for Item {
155    fn generate(
156        &self,
157        rand: &mut dyn RandomStream,
158        output: &mut dyn Write,
159        steps: &mut usize,
160    ) -> Result<Entropy, Error> {
161        // leaving it out or not is a choice between two.
162        let mut entropy = Entropy::ZERO;
163        if self.optional {
164            entropy += Entropy::choices(2);
165            if !rand.bool() {
166                return Ok(entropy);
167            }
168        }
169
170        // randomness is only used when there is something to choose.
171        let (min, max) = (*self.repeat.start(), *self.repeat.end());
172        let mut amount = min;
173        if min < max {
174            // the number of choices only overflows for a range of everything.
175            amount += match ((max - min) as u64).checked_add(1) {
176                Some(choices) => {
177                    entropy += Entropy::choices(choices);
178                    rand.below(choices) as usize
179                }
180                None => {
181                    entropy += Entropy::from_bits(64.0);
182                    rand.u64() as usize
183                }
184            };
185        }
186        for _ in 0..amount {
187            // every time something is generated is a step, which bounds how long this takes.
188            *steps = steps.checked_sub(1).ok_or(Error::StepLimit)?;
189            entropy += Generate::generate(&self.pattern, rand, output, steps)?;
190        }
191
192        Ok(entropy)
193    }
194}
195
196impl Generate for Literal {
197    fn generate(
198        &self,
199        _rand: &mut dyn RandomStream,
200        output: &mut dyn Write,
201        _steps: &mut usize,
202    ) -> Result<Entropy, Error> {
203        output.write_str(&self.value)?;
204        Ok(Entropy::ZERO)
205    }
206}
207
208impl Generate for Special {
209    fn generate(
210        &self,
211        rand: &mut dyn RandomStream,
212        output: &mut dyn Write,
213        _steps: &mut usize,
214    ) -> Result<Entropy, Error> {
215        match self {
216            Self::Wordlist(list) => {
217                // with a single word, there is nothing to choose, which takes no randomness.
218                let index = match list.len() {
219                    1 => 0,
220                    length => rand.below(length as u64) as usize,
221                };
222                let word = list.get(index).expect("a prepared wordlist is not empty");
223                output.write_str(word)?;
224                Ok(Entropy::choices(list.len() as u64))
225            }
226            Self::Markov(markov) => {
227                // the end of the word is a choice as well, which the iterator does not have.
228                let mut window = markov.window();
229                let mut total = Entropy::ZERO;
230                loop {
231                    let (character, entropy) = markov.generate(rand, &mut window);
232                    total += entropy;
233                    match character {
234                        Some(character) => output.write_char(character)?,
235                        None => break Ok(total),
236                    }
237                }
238            }
239            Self::Preset(never) => match *never {},
240        }
241    }
242}
243
244impl Generate for Set {
245    fn generate(
246        &self,
247        rand: &mut dyn RandomStream,
248        output: &mut dyn Write,
249        _steps: &mut usize,
250    ) -> Result<Entropy, Error> {
251        // a set of a single character (however many times it is listed) has nothing to
252        // choose, which takes no randomness.
253        let index = match self.single() {
254            true => 0,
255            false => rand.below(self.total() as u64) as usize,
256        };
257        let (character, weight) = self.get(index);
258        output.write_char(character)?;
259        Ok(Entropy::weighted(weight as u64, self.total() as u64))
260    }
261}