forge
Explore
Log in

Don't you dare go Hollow

SSID-scoped PMK rainbow tables + fast wordlist line counting

Browse files at this commit

d906dc4ee736dbad1881493eaae6a39d2ee15ab2Ahmet Kaan GümüşParent: 7971998
  • feat
    • SSID-scoped PMK rainbow tables + fast wordlist line counting
Show full message
🌈 feat(rainbow): SSID-scoped PMK rainbow tables + fast wordlist line counting
src/rainbow.rsadded+346 -0
@@ -0,0 +1,346 @@
1+//! SSID-scoped precomputed PMK tables — the "rainbow" attack for WPA-PSK.
2+//!
3+//! PBKDF2-HMAC-SHA1(pass, essid, 4096) is the entire per-candidate cost of
4+//! cracking; its output depends only on the passphrase and the SSID, not on
5+//! the captured handshake. Caching pass→PMK pairs for one SSID therefore
6+//! turns every later run against that SSID into a raw compare (millions of
7+//! candidates per second), at disk cost of ~64 B per entry.
8+//!
9+//! Text format, one entry per line:
10+//! ```text
11+//! # wifilab-pmk v1 ssid=Parafin
12+//! <64 lowercase hex chars of PMK> <passphrase bytes to end of line>
13+//! ```
14+//! The passphrase runs to the end of the line (spaces allowed); only the
15+//! first space separates it from the hex PMK. Lines that are empty, start
16+//! with `#`, or fail to parse are skipped.
17+
18+use std::fs::File;
19+use std::io::{BufRead, BufReader, BufWriter, Write};
20+use std::path::Path;
21+
22+use anyhow::{Context, Result, bail};
23+
24+const MAGIC: &str = "# wifilab-pmk v1";
25+
26+struct PmkIter {
27+ lines: std::io::Lines<BufReader<File>>,
28+ /// First line, kept when it turned out to be an entry, not the header.
29+ pending: Option<String>,
30+}
31+
32+impl Iterator for PmkIter {
33+ type Item = ([u8; 32], Vec<u8>);
34+
35+ fn next(&mut self) -> Option<Self::Item> {
36+ if let Some(first) = self.pending.take() {
37+ return parse_entry(first.as_bytes());
38+ }
39+ for line in self.lines.by_ref() {
40+ let Ok(line) = line else { continue }; // unreadable line: skip, keep streaming
41+ let Some(entry) = parse_entry(line.as_bytes()) else {
42+ continue;
43+ };
44+ return Some(entry);
45+ }
46+ None
47+ }
48+}
49+
50+/// `<64 hex> <pass>` → `(pmk, pass)`, or None when malformed.
51+fn parse_entry(line: &[u8]) -> Option<([u8; 32], Vec<u8>)> {
52+ if line.len() < 66 || line[64] != b' ' {
53+ return None;
54+ }
55+ let pmk = hex32(&line[..64])?;
56+ let pass = line[65..].to_vec();
57+ // Writer only emits WPA-legal passphrases; hold the same invariant when
58+ // reading foreign tables so the cracker never wastes a compare.
59+ if !(8..=63).contains(&pass.len()) {
60+ return None;
61+ }
62+ Some((pmk, pass))
63+}
64+
65+/// Strict lowercase-or-uppercase 64-char hex → 32 bytes.
66+fn hex32(s: &[u8]) -> Option<[u8; 32]> {
67+ if s.len() != 64 {
68+ return None;
69+ }
70+ let nibble = |b: u8| -> Option<u8> {
71+ match b {
72+ b'0'..=b'9' => Some(b - b'0'),
73+ b'a'..=b'f' => Some(b - b'a' + 10),
74+ b'A'..=b'F' => Some(b - b'A' + 10),
75+ _ => None,
76+ }
77+ };
78+ let mut out = [0u8; 32];
79+ for (i, pair) in s.chunks_exact(2).enumerate() {
80+ out[i] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
81+ }
82+ Some(out)
83+}
84+
85+/// Open a table for cracking. Returns the SSID recorded in the header
86+/// (`None` when the file has no header) plus a streaming iterator of
87+/// `(pmk, passphrase)` entries. The caller MUST verify the header SSID
88+/// matches the target — PMKs are salt-bound to the SSID and compare-fail
89+/// silently otherwise.
90+pub fn open(path: &Path) -> Result<(Option<String>, Box<dyn Iterator<Item = ([u8; 32], Vec<u8>)> + Send>)> {
91+ let f = File::open(path)
92+ .with_context(|| format!("opening PMK table {}", path.display()))?;
93+ let mut reader = BufReader::with_capacity(1 << 20, f);
94+ // Peek the first line for the header.
95+ let mut first = String::new();
96+ let n = reader
97+ .read_line(&mut first)
98+ .with_context(|| format!("reading PMK table {}", path.display()))?;
99+ let (ssid, pending) = if n > 0 {
100+ let trimmed = first.trim_end_matches(['\r', '\n']);
101+ match parse_header(trimmed) {
102+ Some(s) => (Some(s), None),
103+ // Not a header: the first line is an entry — don't drop it.
104+ None => (None, Some(first)),
105+ }
106+ } else {
107+ (None, None)
108+ };
109+ Ok((
110+ ssid,
111+ Box::new(PmkIter {
112+ lines: reader.lines(),
113+ pending,
114+ }),
115+ ))
116+}
117+
118+/// `# wifilab-pmk v1 ssid=<essid>` → Some(essid); anything else → None.
119+fn parse_header(line: &str) -> Option<String> {
120+ let rest = line.strip_prefix(MAGIC)?;
121+ rest.strip_prefix(" ssid=").map(str::to_string)
122+}
123+
124+/// Streaming table writer: [`create`], [`TableWriter::push`], done.
125+pub struct TableWriter {
126+ w: BufWriter<File>,
127+ entries: u64,
128+}
129+
130+impl TableWriter {
131+ /// Append one entry. `pass` must be 8..=63 bytes (WPA passphrase range).
132+ pub fn push(&mut self, pmk: &[u8; 32], pass: &[u8]) -> std::io::Result<()> {
133+ debug_assert!((8..=63).contains(&pass.len()));
134+ const HEX: &[u8; 16] = b"0123456789abcdef";
135+ let mut hex = [0u8; 64];
136+ for (i, b) in pmk.iter().enumerate() {
137+ hex[i * 2] = HEX[(b >> 4) as usize];
138+ hex[i * 2 + 1] = HEX[(b & 0xf) as usize];
139+ }
140+ self.w.write_all(&hex)?;
141+ self.w.write_all(b" ")?;
142+ self.w.write_all(pass)?;
143+ self.w.write_all(b"\n")?;
144+ self.entries += 1;
145+ Ok(())
146+ }
147+
148+ /// Entries written so far. Flushes the buffer.
149+ pub fn finish(mut self) -> std::io::Result<u64> {
150+ self.w.flush()?;
151+ Ok(self.entries)
152+ }
153+}
154+
155+/// Create a table file with the header for `ssid`. Existing file is
156+/// truncated. Parent directories are created.
157+pub fn create(path: &Path, ssid: &str) -> Result<TableWriter> {
158+ if let Some(parent) = path.parent() {
159+ std::fs::create_dir_all(parent)
160+ .with_context(|| format!("creating PMK table directory {}", parent.display()))?;
161+ }
162+ let f = File::create(path)
163+ .with_context(|| format!("creating PMK table {}", path.display()))?;
164+ let mut w = BufWriter::with_capacity(1 << 20, f);
165+ writeln!(w, "{MAGIC} ssid={ssid}")
166+ .with_context(|| format!("writing PMK table header {}", path.display()))?;
167+ Ok(TableWriter { w, entries: 0 })
168+}
169+
170+/// Open `path` for APPENDING as the table for `ssid` (per-SSID PMK cache
171+/// writer): a missing or zero-length file is created with a fresh header
172+/// (`create` semantics); an existing non-empty file MUST carry a header
173+/// whose SSID passes [`check_ssid`] against `ssid` — anything else is an
174+/// error (refusing to corrupt a table belonging to another SSID). The
175+/// file is opened append-mode, so existing entries are never touched.
176+pub fn append_open(path: &Path, ssid: &str) -> Result<TableWriter> {
177+ let needs_header = match std::fs::metadata(path) {
178+ Ok(m) => m.len() == 0,
179+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
180+ Err(e) => {
181+ return Err(e).with_context(|| format!("stat'ing PMK table {}", path.display()));
182+ }
183+ };
184+ if needs_header {
185+ return create(path, ssid);
186+ }
187+ // Existing table: verify the recorded SSID before appending (PMKs are
188+ // salt-bound to the SSID; mixing tables would poison the cache).
189+ let first = {
190+ let f = File::open(path)
191+ .with_context(|| format!("opening PMK table {}", path.display()))?;
192+ let mut reader = BufReader::new(f);
193+ let mut line = String::new();
194+ reader
195+ .read_line(&mut line)
196+ .with_context(|| format!("reading PMK table header {}", path.display()))?;
197+ line
198+ };
199+ let header = parse_header(first.trim_end_matches(['\r', '\n']));
200+ check_ssid(header.as_deref(), ssid)
201+ .with_context(|| format!("cannot append to PMK table {}", path.display()))?;
202+ let f = std::fs::OpenOptions::new()
203+ .append(true)
204+ .open(path)
205+ .with_context(|| format!("appending to PMK table {}", path.display()))?;
206+ let w = BufWriter::with_capacity(1 << 20, f);
207+ Ok(TableWriter { w, entries: 0 })
208+}
209+
210+/// Guard used before starting a rainbow run: the table's SSID must equal
211+/// the target's. Returns a human reason on mismatch.
212+pub fn check_ssid(table_ssid: Option<&str>, target_ssid: &str) -> Result<()> {
213+ match table_ssid {
214+ None => bail!("PMK table has no ssid header — cannot verify it matches the target"),
215+ Some(s) if s != target_ssid => bail!(
216+ "PMK table is for ssid \"{s}\" but the target's essid is \"{target_ssid}\" (PMKs are salt-bound to the ssid)"
217+ ),
218+ _ => Ok(()),
219+ }
220+}
221+
222+#[cfg(test)]
223+mod tests {
224+ use super::*;
225+
226+ #[test]
227+ fn header_parse() {
228+ assert_eq!(
229+ parse_header("# wifilab-pmk v1 ssid=Parafin"),
230+ Some("Parafin".to_string())
231+ );
232+ assert_eq!(
233+ parse_header("# wifilab-pmk v1 ssid=with space"),
234+ Some("with space".to_string())
235+ );
236+ assert_eq!(parse_header("# wifilab-pmk v1"), None);
237+ assert_eq!(parse_header("garbage"), None);
238+ }
239+
240+ #[test]
241+ fn entry_parse_strict() {
242+ let pmk = [0xabu8; 32];
243+ let hex = "ab".repeat(32);
244+ let line = format!("{hex} pass word1");
245+ let (got_pmk, got_pass) = parse_entry(line.as_bytes()).expect("parses");
246+ assert_eq!(got_pmk, pmk);
247+ assert_eq!(got_pass, b"pass word1");
248+ // No space separator, short hex, bad char, short pass → rejected.
249+ assert!(parse_entry(format!("{hex}pass word1").as_bytes()).is_none());
250+ assert!(parse_entry(b"ab short").is_none());
251+ assert!(parse_entry(format!("{}zz p", &hex[..62]).as_bytes()).is_none());
252+ assert!(parse_entry(format!("{hex} short").as_bytes()).is_none());
253+ }
254+
255+ #[test]
256+ fn roundtrip_write_read() {
257+ let path = std::env::temp_dir().join(format!("wifilab-rainbow-test-{}", std::process::id()));
258+ let entries: Vec<([u8; 32], Vec<u8>)> = vec![
259+ ([0x11; 32], b"password1".to_vec()),
260+ ([0x22; 32], b"two words here".to_vec()),
261+ ([0x33; 32], b"a".repeat(63)),
262+ ];
263+ {
264+ let mut w = create(&path, "Parafin").unwrap();
265+ for (pmk, pass) in &entries {
266+ w.push(pmk, pass).unwrap();
267+ }
268+ assert_eq!(w.finish().unwrap(), 3);
269+ }
270+ let (ssid, it) = open(&path).unwrap();
271+ assert_eq!(ssid.as_deref(), Some("Parafin"));
272+ let got: Vec<_> = it.collect();
273+ assert_eq!(got, entries);
274+ let _ = std::fs::remove_file(&path);
275+ }
276+
277+ #[test]
278+ fn headerless_table_reads_with_none_ssid() {
279+ let path = std::env::temp_dir().join(format!("wifilab-rainbow-hdr-{}", std::process::id()));
280+ std::fs::write(&path, format!("{} passw0rd\n", "cd".repeat(32))).unwrap();
281+ let (ssid, it) = open(&path).unwrap();
282+ assert_eq!(ssid, None);
283+ assert_eq!(it.count(), 1);
284+ let _ = std::fs::remove_file(&path);
285+ }
286+
287+ #[test]
288+ fn append_open_create_vs_append() {
289+ let path =
290+ std::env::temp_dir().join(format!("wifilab-append-pmk-{}", std::process::id()));
291+ let _ = std::fs::remove_file(&path);
292+ // Missing file → created WITH a header, writable.
293+ {
294+ let mut w = append_open(&path, "net1").unwrap();
295+ w.push(&[0x11; 32], b"password1").unwrap();
296+ w.finish().unwrap();
297+ }
298+ // Same SSID → appends, existing entries kept intact.
299+ {
300+ let mut w = append_open(&path, "net1").unwrap();
301+ w.push(&[0x22; 32], b"password2").unwrap();
302+ w.finish().unwrap();
303+ }
304+ let (ssid, it) = open(&path).unwrap();
305+ assert_eq!(ssid.as_deref(), Some("net1"));
306+ assert_eq!(it.count(), 2);
307+ // Truncated to zero bytes → treated like missing (fresh header).
308+ std::fs::write(&path, b"").unwrap();
309+ {
310+ let mut w = append_open(&path, "changed").unwrap();
311+ w.push(&[0x33; 32], b"password3").unwrap();
312+ w.finish().unwrap();
313+ }
314+ let (ssid, it) = open(&path).unwrap();
315+ assert_eq!(ssid.as_deref(), Some("changed"));
316+ assert_eq!(it.count(), 1);
317+ let _ = std::fs::remove_file(&path);
318+ }
319+
320+ #[test]
321+ fn append_open_refuses_ssid_mismatch() {
322+ let path =
323+ std::env::temp_dir().join(format!("wifilab-append-mix-{}", std::process::id()));
324+ {
325+ let mut w = create(&path, "net1").unwrap();
326+ w.push(&[0x11; 32], b"password1").unwrap();
327+ w.finish().unwrap();
328+ }
329+ // A table for another SSID must NOT receive appends (poisoning).
330+ let e = append_open(&path, "othernet").err().expect("refused");
331+ assert!(format!("{e:#}").contains("othernet"), "{e:#}");
332+ // Headerless existing file: unverifiable → also refused.
333+ let raw = std::env::temp_dir().join(format!("wifilab-append-raw-{}", std::process::id()));
334+ std::fs::write(&raw, format!("{} passw0rd\n", "cd".repeat(32))).unwrap();
335+ assert!(append_open(&raw, "net1").is_err());
336+ let _ = std::fs::remove_file(&path);
337+ let _ = std::fs::remove_file(&raw);
338+ }
339+
340+ #[test]
341+ fn ssid_guard() {
342+ assert!(check_ssid(Some("Parafin"), "Parafin").is_ok());
343+ assert!(check_ssid(Some("other"), "Parafin").is_err());
344+ assert!(check_ssid(None, "Parafin").is_err());
345+ }
346+}
src/wordlist.rsmodified+47 -0
@@ -29,6 +29,35 @@ impl Iterator for WordIter {
29 }29 }
30 }30 }
31 31
32+/// Count lines without parsing: byte-scan for `\n` in 8 MiB chunks
33+/// (fast even on multi-GB lists — the cracker's worst-case candidate
34+/// total). A final line without trailing newline counts too.
35+pub fn line_count(path: &Path) -> Result<u64> {
36+ use std::io::Read;
37+
38+ let mut f = File::open(path)
39+ .with_context(|| format!("counting lines of {}", path.display()))?;
40+ let mut buf = vec![0u8; 1 << 23];
41+ let mut count = 0u64;
42+ let mut any = false;
43+ let mut ended_with_nl = true;
44+ loop {
45+ let n = f
46+ .read(&mut buf)
47+ .with_context(|| format!("counting lines of {}", path.display()))?;
48+ if n == 0 {
49+ break;
50+ }
51+ any = true;
52+ ended_with_nl = buf[n - 1] == b'\n';
53+ count += buf[..n].iter().filter(|&&b| b == b'\n').count() as u64;
54+ }
55+ if any && !ended_with_nl {
56+ count += 1;
57+ }
58+ Ok(count)
59+}
60+
32 /// Open a wordlist file as a streaming iterator of passphrase candidates.61 /// Open a wordlist file as a streaming iterator of passphrase candidates.
33 ///62 ///
34 /// Lines are trimmed of `\r\n` only (no whitespace trimming), and only63 /// Lines are trimmed of `\r\n` only (no whitespace trimming), and only
@@ -85,4 +114,22 @@ mod tests {
85 fn missing_file_errors() {114 fn missing_file_errors() {
86 assert!(open(Path::new("/definitely/not/here.lst")).is_err());115 assert!(open(Path::new("/definitely/not/here.lst")).is_err());
87 }116 }
117+
118+ #[test]
119+ fn line_count_edges() {
120+ let dir = std::env::temp_dir();
121+ for (name, bytes, want) in [
122+ ("empty", &b""[..], 0u64),
123+ ("one-no-nl", b"abc", 1),
124+ ("one-nl", b"abc\n", 1),
125+ ("two", b"abc\ndef\n", 2),
126+ ("trailing-nl-only", b"\n", 1),
127+ ("crlf", b"a\r\nb\r\n", 2),
128+ ] {
129+ let path = dir.join(format!("wifilab-lc-{name}-{}", std::process::id()));
130+ std::fs::write(&path, bytes).unwrap();
131+ assert_eq!(line_count(&path).unwrap(), want, "{name}");
132+ let _ = std::fs::remove_file(&path);
133+ }
134+ }
88 }135 }