forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

wordlist.rs206 lines, 7.6 KiBHistoryRawDownload
1//! Streaming wordlist reader: line-oriented, bytes-accurate, filters to the
2//! WPA passphrase length range 8..=63 bytes.
3
4use std::fs::File;
5use std::io::{BufRead, BufReader};
6use std::path::Path;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use anyhow::{Context, Result};
10
11/// Process-wide count of lines skipped by [`open`] iterators: unreadable
12/// lines and lines outside the WPA passphrase range (8..=63 bytes).
13/// Lines with invalid UTF-8 are NOT skipped — passphrases are raw bytes
14/// (rockyou-family lists carry high-bit bytes) and are yielded as read.
15static SKIPPED_LINES: AtomicU64 = AtomicU64::new(0);
16
17/// Cumulative number of wordlist lines skipped since process start. Read
18/// before and after exhausting an iterator; the delta is that file's
19/// skipped-line total (undecodable/unreadable + overlong/undersized).
20pub fn skipped_lines() -> u64 {
21 SKIPPED_LINES.load(Ordering::Relaxed)
22}
23
24struct WordIter {
25 reader: BufReader<File>,
26}
27
28impl Iterator for WordIter {
29 type Item = Vec<u8>;
30
31 fn next(&mut self) -> Option<Vec<u8>> {
32 let mut buf = Vec::new();
33 loop {
34 buf.clear();
35 match self.reader.read_until(b'\n', &mut buf) {
36 Ok(0) => return None,
37 Ok(_) => {
38 // Trim the line terminator only: `\n`, then one `\r` of a
39 // CRLF pair (no whitespace trimming — trailing spaces are
40 // passphrase material).
41 if buf.last() == Some(&b'\n') {
42 buf.pop();
43 if buf.last() == Some(&b'\r') {
44 buf.pop();
45 }
46 }
47 if (8..=63).contains(&buf.len()) {
48 return Some(std::mem::take(&mut buf));
49 }
50 SKIPPED_LINES.fetch_add(1, Ordering::Relaxed);
51 }
52 // Unreadable line: count it and stop. A read error on a
53 // plain file almost always persists; retrying would spin.
54 Err(_) => {
55 SKIPPED_LINES.fetch_add(1, Ordering::Relaxed);
56 return None;
57 }
58 }
59 }
60 }
61}
62
63/// Count lines without parsing: byte-scan for `\n` in 8 MiB chunks
64/// (fast even on multi-GB lists — the cracker's worst-case candidate
65/// total). A final line without trailing newline counts too.
66pub fn line_count(path: &Path) -> Result<u64> {
67 use std::io::Read;
68
69 let mut f =
70 File::open(path).with_context(|| format!("counting lines of {}", path.display()))?;
71 let mut buf = vec![0u8; 1 << 23];
72 let mut count = 0u64;
73 let mut any = false;
74 let mut ended_with_nl = true;
75 loop {
76 let n = f
77 .read(&mut buf)
78 .with_context(|| format!("counting lines of {}", path.display()))?;
79 if n == 0 {
80 break;
81 }
82 any = true;
83 ended_with_nl = buf[n - 1] == b'\n';
84 count += buf[..n].iter().filter(|&&b| b == b'\n').count() as u64;
85 }
86 if any && !ended_with_nl {
87 count += 1;
88 }
89 Ok(count)
90}
91
92/// Open a wordlist file as a streaming iterator of passphrase candidates.
93///
94/// Byte-safe: lines are split at `\n` and trimmed of a trailing `\r` (no
95/// UTF-8 decoding, so high-bit bytes survive — WPA passphrases are raw
96/// bytes); only candidates of 8..=63 *bytes* are yielded. Skipped lines are
97/// tallied in [`skipped_lines`]. The iterator is `Send` and does not load
98/// the file into memory.
99pub fn open(path: &Path) -> Result<Box<dyn Iterator<Item = Vec<u8>> + Send>> {
100 let f = File::open(path).with_context(|| format!("opening wordlist {}", path.display()))?;
101 let reader = BufReader::with_capacity(1 << 20, f);
102 Ok(Box::new(WordIter { reader }))
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108 use std::io::Write;
109
110 /// Serializes tests that assert on the process-wide skip counter.
111 /// (parking_lot isn't a direct dependency; recover from poisoning
112 /// instead of unwrapping.)
113 static SKIP_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
114
115 /// Lock `SKIP_LOCK`, recovering the guard if a panicked test poisoned it.
116 fn skip_lock() -> std::sync::MutexGuard<'static, ()> {
117 SKIP_LOCK.lock().unwrap_or_else(|e| e.into_inner())
118 }
119
120 #[test]
121 fn filters_and_trims() {
122 let _g = skip_lock();
123 let dir = std::env::temp_dir();
124 let path = dir.join(format!("wifi_lab-wordlist-test-{}", std::process::id()));
125 {
126 let mut f = File::create(&path).unwrap();
127 // too short, ok, crlf ok, trailing space kept (too short when
128 // counted), exactly 8, exactly 63, 64 too long, empty line.
129 writeln!(f, "short").unwrap();
130 writeln!(f, "sup3r-secret").unwrap();
131 f.write_all(b"crlf-pass\r\n").unwrap();
132 writeln!(f, "eight88 ").unwrap();
133 writeln!(f, "eight888").unwrap();
134 writeln!(f, "{}", "a".repeat(63)).unwrap();
135 writeln!(f, "{}", "b".repeat(64)).unwrap();
136 f.write_all(b"\n").unwrap();
137 }
138 let before = skipped_lines();
139 let mut it = open(&path).unwrap();
140 let got: Vec<Vec<u8>> = std::iter::from_fn(|| it.next()).collect();
141 // "eight88 " keeps its trailing space: only \r\n is trimmed.
142 assert_eq!(
143 got,
144 vec![
145 b"sup3r-secret".to_vec(),
146 b"crlf-pass".to_vec(),
147 b"eight88 ".to_vec(),
148 b"eight888".to_vec(),
149 "a".repeat(63).into_bytes(),
150 ]
151 );
152 // "short", the 64-byte line and the empty line were skipped.
153 assert_eq!(skipped_lines() - before, 3);
154 let _ = std::fs::remove_file(&path);
155 }
156
157 #[test]
158 fn non_utf8_bytes_are_candidates_not_dropped() {
159 let _g = skip_lock();
160 let dir = std::env::temp_dir();
161 let path = dir.join(format!("wifi_lab-wordlist-utf8-{}", std::process::id()));
162 {
163 let mut f = File::create(&path).unwrap();
164 // rockyou-style high-bit bytes: invalid UTF-8, VALID passphrase.
165 f.write_all(b"p\xe4ssw\xf6rd\n").unwrap();
166 f.write_all(b"\xff\xfepass\x80\x81\n").unwrap();
167 // plus noise that must be counted as skipped:
168 f.write_all(b"tiny\n").unwrap();
169 f.write_all(&[b'x'; 64]).unwrap();
170 f.write_all(b"\n").unwrap();
171 }
172 let before = skipped_lines();
173 let mut it = open(&path).unwrap();
174 let got: Vec<Vec<u8>> = std::iter::from_fn(|| it.next()).collect();
175 assert_eq!(
176 got,
177 vec![b"p\xe4ssw\xf6rd".to_vec(), b"\xff\xfepass\x80\x81".to_vec()]
178 );
179 // "tiny" and the 64-byte line skipped; the binary lines yielded.
180 assert_eq!(skipped_lines() - before, 2);
181 let _ = std::fs::remove_file(&path);
182 }
183
184 #[test]
185 fn missing_file_errors() {
186 assert!(open(Path::new("/definitely/not/here.lst")).is_err());
187 }
188
189 #[test]
190 fn line_count_edges() {
191 let dir = std::env::temp_dir();
192 for (name, bytes, want) in [
193 ("empty", &b""[..], 0u64),
194 ("one-no-nl", b"abc", 1),
195 ("one-nl", b"abc\n", 1),
196 ("two", b"abc\ndef\n", 2),
197 ("trailing-nl-only", b"\n", 1),
198 ("crlf", b"a\r\nb\r\n", 2),
199 ] {
200 let path = dir.join(format!("wifi_lab-lc-{name}-{}", std::process::id()));
201 std::fs::write(&path, bytes).unwrap();
202 assert_eq!(line_count(&path).unwrap(), want, "{name}");
203 let _ = std::fs::remove_file(&path);
204 }
205 }
206}