1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! This is the documentation for the no-std compatible `bruteforce` crate

#![crate_name = "bruteforce"]
#![feature(
    const_fn,
    test,
    generators,
    generator_trait,
    const_if_match,
    const_panic,
    proc_macro_hygiene
)]
#![cfg_attr(not(feature = "std"), no_std)]

extern crate test;

#[cfg(not(feature = "std"))]
extern crate no_std_compat as std;

#[cfg(feature = "bruteforce-macros")]
extern crate bruteforce_macros;

pub mod charset;

#[cfg(feature = "generators")]
use std::ops::{Generator, GeneratorState};
#[cfg(feature = "generators")]
use std::pin::Pin;
use std::prelude::v1::*;

use charset::Charset;

#[cfg(test)]
mod tests {
    #[macro_use]
    use super::*;
    use test::Bencher;

    const BENCH_CHARS: Charset = Charset::new(&[
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
        'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
        'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
        '2', '3', '4', '5', '6', '7', '8', '9', '!', '\"', '\'', '?', '\\', '#', '$', '§', '%',
        '&', '/', '(', ')', '=', '[', ']', '{', '}', '´', '`', '<', '>', '€', ',', '.', '-', '_',
    ]);

    #[bench]
    fn bench_raw_next(b: &mut Bencher) {
        let mut brute_forcer = BruteForce::new(BENCH_CHARS);
        b.iter(|| {
            brute_forcer.raw_next();
        });
    }

    #[bench]
    fn bench_next(b: &mut Bencher) {
        let mut brute_forcer = BruteForce::new(BENCH_CHARS);
        b.iter(|| brute_forcer.next());
    }

    #[bench]
    fn bench_new(b: &mut Bencher) {
        b.iter(|| BruteForce::new(BENCH_CHARS));
    }

    #[bench]
    fn bench_charset_new(b: &mut Bencher) {
        b.iter(|| {
            Charset::new(&[
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '\"',
                '\'', '?', '\\', '#', '$', '§', '%', '&', '/', '(', ')', '=', '[', ']', '{', '}',
                '´', '`', '<', '>', '€', ',', '.', '-', '_',
            ])
        });
    }

    #[bench]
    fn bench_charset_new_by_str(b: &mut Bencher) {
        b.iter(|| Charset::new_by_str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"\'?\\$§%&/()=[]{}´`<>€,.-_"));
    }

    #[bench]
    fn bench_charset_concat(b: &mut Bencher) {
        let c1 = Charset::new_by_str("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        let c2 = Charset::new_by_str("abcdefghijklmnopqrstuvwxyz0123456789");

        b.iter(|| c1.concat(&c2));
    }

    #[bench]
    fn bench_charset_by_range(b: &mut Bencher) {
        b.iter(|| Charset::by_char_range('a'..='z'));
    }

    #[bench]
    fn bench_charset_to_string(b: &mut Bencher) {
        b.iter(|| BENCH_CHARS.to_string());
    }
}

/// Represents a brute-forcing instance
#[derive(Debug, Clone)]
pub struct BruteForce<'a> {
    /// Represents the charset of the brute-forcer
    pub chars: Charset<'a>,

    /// This is the current string
    pub current: String,

    /// Reversed representation of current where each element is an index of charset
    raw_current: Vec<usize>,
}

impl<'a> BruteForce<'a> {
    /// Returns a brute forcer with default settings
    ///
    /// # Arguments
    ///
    /// * `charset` - A char array that contains all chars to be tried
    ///
    /// # Example
    ///
    /// ```rust
    /// use bruteforce::BruteForce;
    /// use bruteforce::charset::Charset;
    /// const CHARSET: Charset = Charset::new(&['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']);
    /// let mut brute_forcer = BruteForce::new(CHARSET);
    ///
    /// const password: &'static str = "PASS";
    /// for s in brute_forcer {
    /// if s == password.to_string() {
    ///        println!("Password cracked");
    ///        break;
    ///    }
    /// }
    /// ```
    pub fn new(charset: Charset) -> BruteForce {
        BruteForce {
            chars: charset,
            current: String::default(),
            // Maybe the answer is an empty string?
            raw_current: vec![],
        }
    }

    /// Returns a brute forcer skipping some letters
    ///
    /// # Arguments
    ///
    /// * `charset` - A char array that contains all chars to be tried
    /// * `start` - E.g. the known password length
    ///
    /// # Example
    ///
    /// ```rust
    /// // This example will take less time, because we know the password length
    /// use bruteforce::BruteForce;
    /// use bruteforce::charset::Charset;
    /// const CHARSET: Charset = Charset::new(&['A', 'B', 'C', 'P', 'S']); // all possible characters
    /// let mut brute_forcer = BruteForce::new_at(CHARSET, 4);
    ///
    /// const password: &'static str = "PASS";
    /// for s in brute_forcer {
    /// if s == password.to_string() {
    ///        println!("Password cracked");
    ///        break;
    ///    }
    /// }
    /// ```
    pub fn new_at(charset: Charset, start: usize) -> BruteForce {
        BruteForce {
            chars: charset,
            current: String::default(),
            raw_current: (0..start).map(|_| 0).collect::<Vec<usize>>(),
        }
    }

    /// Returns a brute forcer skipping some text
    ///
    /// # Arguments
    ///
    /// * `charset` - A char array that contains all chars to be tried
    /// * `start_string` - A string
    ///
    /// # Example
    ///
    /// ```rust
    /// // This could be useful if we want to save our brute force progress and resume it later
    /// use bruteforce::BruteForce;
    /// use bruteforce::charset::Charset;
    /// const CHARSET: Charset = Charset::new(&['A', 'B', 'C', 'P', 'S']); // all possible characters
    /// let mut brute_forcer = BruteForce::new_by_start_string(CHARSET, "CCCC".to_string());
    ///
    /// const password: &'static str = "PASS";
    /// for s in brute_forcer {
    /// if s == password.to_string() {
    ///        println!("Password cracked");
    ///        break;
    ///    }
    /// }
    /// ```
    pub fn new_by_start_string(charset: Charset, start_string: String) -> BruteForce {
        BruteForce {
            current: String::default(),
            raw_current: start_string
                .chars()
                .rev()
                .map(|c1| charset.iter().position(|&c2| c1 == c2))
                .collect::<Option<Vec<usize>>>()
                .expect("characters in start_string must exist in charset"),
            // assigning charset to chars must happen after it is used by .map()
            chars: charset,
        }
    }

    /// This returns the next element without unnecessary boxing in a Option
    pub fn raw_next(&mut self) -> &str {
        // Generate self.current from self.raw_current
        // This doesn't allocate because it has no content.
        let mut temp = String::default();
        // Borrow splitting workaround. https://doc.rust-lang.org/nomicon/borrow-splitting.html
        std::mem::swap(&mut self.current, &mut temp);
        temp.clear();
        temp.extend(self.raw_current.iter().rev().map(|&i| {
            assert!(i < self.chars.len(), "Bug: Invalid character index");
            self.chars[i]
        }));
        self.current = temp;

        // "Add" 1 to self.raw_current
        let mut carryover = true;
        for i in self.raw_current.iter_mut() {
            *i += 1;
            if *i == self.chars.len() {
                *i = 0;
            } else {
                carryover = false;
                break;
            }
        }
        if carryover {
            self.raw_current.push(0);
        }

        &self.current
    }
}

impl<'a> Iterator for BruteForce<'a> {
    type Item = String;

    fn next(&mut self) -> Option<String> {
        Some(self.raw_next().to_string())
    }
}

#[cfg(feature = "generators")]
impl Generator for Pin<&mut BruteForce<'_>> {
    type Yield = String;
    type Return = ();

    fn resume(self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
        GeneratorState::Yielded(self.get_mut().raw_next().to_string())
    }
}