forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

rainbow.rs808 lines, 30.1 KiBHistoryRawDownload
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//! Current text format (v2), one entry per line, all binary data hex-coded
10//! so no passphrase byte (newline, `=`, high-bit) can corrupt the frame:
11//! ```text
12//! # wifi_lab-pmk v2 ssid=<hex of SSID>
13//! <64 lowercase hex chars of PMK> <lowercase hex of passphrase>
14//! # wifi_lab-pmk v2 end count=<entries> sha1=<40 lowercase hex>
15//! ```
16//! The footer carries the entry count and a SHA-1 over the raw bytes of
17//! every entry line (without its newline); [`open`] validates both eagerly
18//! and REFUSES a truncated or mutated table instead of silently dropping
19//! entries. Legacy v1 files (`# wifi_lab-pmk v1 ssid=<plaintext>`, raw
20//! passphrase to end of line) are still read — with a `tracing::warn!` — but
21//! every write produces v2.
22
23use std::collections::HashSet;
24use std::fs::File;
25use std::io::{BufRead, BufReader, BufWriter, Seek, SeekFrom, Write};
26use std::path::Path;
27use std::sync::atomic::{AtomicU64, Ordering};
28
29use anyhow::{Context, Result, bail};
30use sha1::{Digest, Sha1};
31
32const MAGIC_V1: &str = "# wifi_lab-pmk v1";
33const MAGIC_V2: &str = "# wifi_lab-pmk v2";
34const FOOTER: &str = "# wifi_lab-pmk v2 end";
35
36/// Process-wide count of table lines skipped by [`open`] iterators while
37/// streaming v1/headerless files (malformed lines; v2 files are validated
38/// eagerly and never reach the iterator with bad lines).
39static SKIPPED_LINES: AtomicU64 = AtomicU64::new(0);
40
41/// Cumulative number of PMK-table lines skipped since process start (see
42/// [`SKIPPED_LINES`]). Read before/after exhausting an iterator; the delta
43/// is that file's skipped total.
44pub fn skipped_lines() -> u64 {
45 SKIPPED_LINES.load(Ordering::Relaxed)
46}
47
48struct PmkIter {
49 reader: BufReader<File>,
50 /// v2 body (hex-coded passphrases, footer-terminated) vs legacy v1
51 /// (raw passphrase to end of line).
52 v2: bool,
53 /// First line, kept (trimmed) when it turned out to be an entry, not
54 /// the header.
55 pending: Option<Vec<u8>>,
56}
57
58/// Strip the line terminator: `\n`, then one `\r` of a CRLF pair.
59fn trim_eol(mut line: Vec<u8>) -> Vec<u8> {
60 if line.last() == Some(&b'\n') {
61 line.pop();
62 if line.last() == Some(&b'\r') {
63 line.pop();
64 }
65 }
66 line
67}
68
69impl Iterator for PmkIter {
70 type Item = ([u8; 32], Vec<u8>);
71
72 fn next(&mut self) -> Option<Self::Item> {
73 let mut buf = Vec::new();
74 loop {
75 let line = if let Some(first) = self.pending.take() {
76 first
77 } else {
78 buf.clear();
79 match self.reader.read_until(b'\n', &mut buf) {
80 Ok(0) => return None,
81 Ok(_) => trim_eol(std::mem::take(&mut buf)),
82 // Unreadable line: count it and stop — a persistent read
83 // error would otherwise spin forever.
84 Err(_) => {
85 SKIPPED_LINES.fetch_add(1, Ordering::Relaxed);
86 return None;
87 }
88 }
89 };
90 if self.v2 {
91 if line.starts_with(FOOTER.as_bytes()) {
92 return None; // end of entries
93 }
94 match parse_entry_v2(&line) {
95 Some(entry) => return Some(entry),
96 None => {
97 SKIPPED_LINES.fetch_add(1, Ordering::Relaxed);
98 continue;
99 }
100 }
101 }
102 // v1 / headerless: comments and empty lines are by design, not
103 // counted as skipped.
104 if line.is_empty() || line.starts_with(b"#") {
105 continue;
106 }
107 match parse_entry(&line) {
108 Some(entry) => return Some(entry),
109 None => {
110 SKIPPED_LINES.fetch_add(1, Ordering::Relaxed);
111 continue;
112 }
113 }
114 }
115 }
116}
117
118/// `<64 hex> <pass>` → `(pmk, pass)`, or None when malformed (v1).
119fn parse_entry(line: &[u8]) -> Option<([u8; 32], Vec<u8>)> {
120 if line.len() < 66 || line[64] != b' ' {
121 return None;
122 }
123 let pmk = hex32(&line[..64])?;
124 let pass = line[65..].to_vec();
125 // Writer only emits WPA-legal passphrases; hold the same invariant when
126 // reading foreign tables so the cracker never wastes a compare.
127 if !(8..=63).contains(&pass.len()) {
128 return None;
129 }
130 Some((pmk, pass))
131}
132
133/// `<64 hex> <hex-pass>` → `(pmk, pass)`, or None when malformed (v2).
134fn parse_entry_v2(line: &[u8]) -> Option<([u8; 32], Vec<u8>)> {
135 if line.len() < 65 || line[64] != b' ' {
136 return None;
137 }
138 let pmk = hex32(&line[..64])?;
139 let pass = unhex(&line[65..])?;
140 if !(8..=63).contains(&pass.len()) {
141 return None;
142 }
143 Some((pmk, pass))
144}
145
146/// Strict lowercase-or-uppercase 64-char hex → 32 bytes.
147fn hex32(s: &[u8]) -> Option<[u8; 32]> {
148 if s.len() != 64 {
149 return None;
150 }
151 let mut out = [0u8; 32];
152 for (i, pair) in s.as_chunks::<2>().0.iter().enumerate() {
153 out[i] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
154 }
155 Some(out)
156}
157
158/// Even-length lowercase-or-uppercase hex → bytes.
159fn unhex(s: &[u8]) -> Option<Vec<u8>> {
160 if !s.len().is_multiple_of(2) {
161 return None;
162 }
163 let mut out = Vec::with_capacity(s.len() / 2);
164 for pair in s.as_chunks::<2>().0 {
165 out.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
166 }
167 Some(out)
168}
169
170fn nibble(b: u8) -> Option<u8> {
171 match b {
172 b'0'..=b'9' => Some(b - b'0'),
173 b'a'..=b'f' => Some(b - b'a' + 10),
174 b'A'..=b'F' => Some(b - b'A' + 10),
175 _ => None,
176 }
177}
178
179fn hex_push(out: &mut String, bytes: &[u8]) {
180 const HEX: &[u8; 16] = b"0123456789abcdef";
181 for b in bytes {
182 out.push(HEX[(b >> 4) as usize] as char);
183 out.push(HEX[(b & 0xf) as usize] as char);
184 }
185}
186
187/// Streaming `(pmk, passphrase)` entries of an opened table.
188pub type EntryIter = Box<dyn Iterator<Item = ([u8; 32], Vec<u8>)> + Send>;
189
190/// Open a table for cracking. Returns the SSID recorded in the header
191/// (`None` when the file has no header) plus a streaming iterator of
192/// `(pmk, passphrase)` entries. The caller MUST verify the header SSID
193/// matches the target — PMKs are salt-bound to the SSID and compare-fail
194/// silently otherwise.
195///
196/// v2 tables are validated EAGERLY (one extra read pass): every entry line
197/// must parse, the footer must be present and last, its entry count and
198/// SHA-1 (over the raw entry-line bytes) must match — any violation is an
199/// error here, not silently dropped entries mid-crack. v1 tables load with
200/// a `tracing::warn!` (legacy, unauthenticated format).
201pub fn open(path: &Path) -> Result<(Option<String>, EntryIter)> {
202 let f = File::open(path).with_context(|| format!("opening PMK table {}", path.display()))?;
203 let mut reader = BufReader::with_capacity(1 << 20, f);
204 // Peek the first line (byte-based: entry passphrases need not be UTF-8).
205 let mut first = Vec::new();
206 let n = reader
207 .read_until(b'\n', &mut first)
208 .with_context(|| format!("reading PMK table {}", path.display()))?;
209 let first = trim_eol(first);
210
211 if n > 0 && first.starts_with(MAGIC_V2.as_bytes()) {
212 let ssid = parse_header_v2(&first)
213 .with_context(|| format!("malformed v2 header in PMK table {}", path.display()))?;
214 validate_v2_body(&mut reader, path)?;
215 // Validated: rewind past the header and stream the entries.
216 let mut f = reader.into_inner();
217 f.seek(SeekFrom::Start(0))
218 .with_context(|| format!("rewinding PMK table {}", path.display()))?;
219 let mut reader = BufReader::with_capacity(1 << 20, f);
220 let mut header = Vec::new();
221 reader
222 .read_until(b'\n', &mut header)
223 .with_context(|| format!("reading PMK table {}", path.display()))?;
224 return Ok((
225 Some(ssid),
226 Box::new(PmkIter {
227 reader,
228 v2: true,
229 pending: None,
230 }),
231 ));
232 }
233
234 let (ssid, pending) = if n > 0 {
235 match std::str::from_utf8(&first).ok().and_then(parse_header_v1) {
236 Some(s) => {
237 tracing::warn!(
238 "PMK table {} uses the legacy v1 format (no integrity check) — rebuild it to upgrade to v2",
239 path.display()
240 );
241 (Some(s), None)
242 }
243 // Not a header: the first line is an entry — keep it (TRIMMED:
244 // the bytes yielded must not carry the line terminator).
245 None => (None, Some(first)),
246 }
247 } else {
248 (None, None)
249 };
250 Ok((
251 ssid,
252 Box::new(PmkIter {
253 reader,
254 v2: false,
255 pending,
256 }),
257 ))
258}
259
260/// Eager integrity pass over the v2 body (header already consumed): every
261/// line until the footer must be a well-formed entry; the footer must be
262/// the last line and its `count`/`sha1` must match the body.
263fn validate_v2_body(reader: &mut BufReader<File>, path: &Path) -> Result<()> {
264 let mut hash = Sha1::new();
265 let mut count = 0u64;
266 let mut footer: Option<(u64, [u8; 20])> = None;
267 let mut buf = Vec::new();
268 loop {
269 buf.clear();
270 let n = reader
271 .read_until(b'\n', &mut buf)
272 .with_context(|| format!("reading PMK table {}", path.display()))?;
273 if n == 0 {
274 break;
275 }
276 let line = trim_eol(std::mem::take(&mut buf));
277 if let Some(f) = parse_footer(&line) {
278 footer = Some(f);
279 // The footer must terminate the file.
280 let mut tail = Vec::new();
281 let m = reader
282 .read_until(b'\n', &mut tail)
283 .with_context(|| format!("reading PMK table {}", path.display()))?;
284 if m != 0 {
285 bail!(
286 "PMK table {}: mutated — entries after the footer",
287 path.display()
288 );
289 }
290 break;
291 }
292 if parse_entry_v2(&line).is_none() {
293 bail!(
294 "PMK table {}: mutated — malformed or unexpected line in v2 table",
295 path.display()
296 );
297 }
298 hash.update(&line);
299 count += 1;
300 }
301 let Some((want_count, want_digest)) = footer else {
302 bail!(
303 "PMK table {}: truncated — v2 footer missing (partial write?)",
304 path.display()
305 );
306 };
307 if want_count != count {
308 bail!(
309 "PMK table {}: corrupted — footer says {want_count} entries, body has {count}",
310 path.display()
311 );
312 }
313 let digest: [u8; 20] = hash.finalize().into();
314 if digest != want_digest {
315 bail!(
316 "PMK table {}: corrupted — entry checksum mismatch",
317 path.display()
318 );
319 }
320 Ok(())
321}
322
323/// `# wifi_lab-pmk v1 ssid=<essid>` → Some(essid); anything else → None.
324fn parse_header_v1(line: &str) -> Option<String> {
325 let rest = line.strip_prefix(MAGIC_V1)?;
326 rest.strip_prefix(" ssid=").map(str::to_string)
327}
328
329/// `# wifi_lab-pmk v2 ssid=<hex essid>` → Some(essid); anything else → None.
330fn parse_header_v2(line: &[u8]) -> Option<String> {
331 let rest = line.strip_prefix(MAGIC_V2.as_bytes())?;
332 let rest = rest.strip_prefix(b" ssid=")?;
333 String::from_utf8(unhex(rest)?).ok()
334}
335
336/// `# wifi_lab-pmk v2 end count=<n> sha1=<40 hex>` → Some((n, digest)).
337fn parse_footer(line: &[u8]) -> Option<(u64, [u8; 20])> {
338 let s = std::str::from_utf8(line).ok()?;
339 let rest = s.strip_prefix(FOOTER)?.strip_prefix(" count=")?;
340 let (count_s, digest_s) = rest.split_once(" sha1=")?;
341 let count: u64 = count_s.parse().ok()?;
342 let digest: [u8; 20] = unhex(digest_s.as_bytes())?.try_into().ok()?;
343 Some((count, digest))
344}
345
346/// Streaming table writer: [`create`], [`TableWriter::push`],
347/// [`TableWriter::finish`] (writing the integrity footer). The file is only
348/// valid v2 once `finish` ran — a crash mid-build leaves a footer-less file
349/// that [`open`] reports as truncated instead of trusting.
350pub struct TableWriter {
351 w: BufWriter<File>,
352 /// Total entries in the file (preloaded + pushed this session).
353 entries: u64,
354 /// Entries pushed by THIS session's [`TableWriter::push`] calls (what
355 /// [`TableWriter::finish`] reports back to the caller).
356 session_new: u64,
357 /// Passphrases already in the file (dedupe), preloaded on append.
358 seen: HashSet<Vec<u8>>,
359 /// Running SHA-1 over the raw entry-line bytes (footer checksum).
360 hash: Sha1,
361}
362
363impl TableWriter {
364 /// Append one entry. `pass` must be 8..=63 bytes (WPA passphrase range).
365 /// A passphrase already in the table is skipped silently (dedupe); the
366 /// file keeps exactly one entry per passphrase.
367 pub fn push(&mut self, pmk: &[u8; 32], pass: &[u8]) -> std::io::Result<()> {
368 self.push_inner(pmk, pass, true)
369 }
370
371 fn push_inner(
372 &mut self,
373 pmk: &[u8; 32],
374 pass: &[u8],
375 count_as_new: bool,
376 ) -> std::io::Result<()> {
377 debug_assert!((8..=63).contains(&pass.len()));
378 if !self.seen.insert(pass.to_vec()) {
379 return Ok(()); // duplicate passphrase — deduped
380 }
381 let mut line = String::with_capacity(64 + 1 + pass.len() * 2);
382 hex_push(&mut line, pmk);
383 line.push(' ');
384 hex_push(&mut line, pass);
385 self.hash.update(line.as_bytes());
386 line.push('\n');
387 self.w.write_all(line.as_bytes())?;
388 self.entries += 1;
389 if count_as_new {
390 self.session_new += 1;
391 }
392 Ok(())
393 }
394
395 /// Write the integrity footer and flush. Returns the number of entries
396 /// appended by THIS session (preloaded/kept entries don't count).
397 pub fn finish(mut self) -> std::io::Result<u64> {
398 let digest = std::mem::take(&mut self.hash).finalize();
399 let mut footer = String::with_capacity(80);
400 footer.push_str(FOOTER);
401 footer.push_str(" count=");
402 footer.push_str(&self.entries.to_string());
403 footer.push_str(" sha1=");
404 hex_push(&mut footer, &digest);
405 footer.push('\n');
406 self.w.write_all(footer.as_bytes())?;
407 self.w.flush()?;
408 Ok(self.session_new)
409 }
410}
411
412/// Create a v2 table file with the header for `ssid`. Existing file is
413/// truncated. Parent directories are created.
414pub fn create(path: &Path, ssid: &str) -> Result<TableWriter> {
415 if let Some(parent) = path.parent() {
416 std::fs::create_dir_all(parent)
417 .with_context(|| format!("creating PMK table directory {}", parent.display()))?;
418 }
419 let f = File::create(path).with_context(|| format!("creating PMK table {}", path.display()))?;
420 let mut w = BufWriter::with_capacity(1 << 20, f);
421 let mut header = String::with_capacity(MAGIC_V2.len() + 8 + ssid.len() * 2);
422 header.push_str(MAGIC_V2);
423 header.push_str(" ssid=");
424 hex_push(&mut header, ssid.as_bytes());
425 header.push('\n');
426 w.write_all(header.as_bytes())
427 .with_context(|| format!("writing PMK table header {}", path.display()))?;
428 Ok(TableWriter {
429 w,
430 entries: 0,
431 session_new: 0,
432 seen: HashSet::new(),
433 hash: Sha1::new(),
434 })
435}
436
437/// Open `path` as the table for `ssid` (per-SSID PMK cache writer): a
438/// missing or zero-length file is created fresh (`create` semantics); an
439/// existing non-empty file MUST carry a header whose SSID passes
440/// [`check_ssid`] against `ssid` — anything else is an error (refusing to
441/// corrupt a table belonging to another SSID).
442///
443/// v2 tables can't grow by blind appending (the footer carries a checksum
444/// and entry count), so the existing entries are read — v2 integrity
445/// validated, so a truncated/mutated table errors here — and REWRITTEN
446/// together with the new ones; [`TableWriter::push`] dedupes against the
447/// existing passphrases. The file on disk never mixes formats: what leaves
448/// this function is always a valid v2 stream.
449pub fn append_open(path: &Path, ssid: &str) -> Result<TableWriter> {
450 let needs_header = match std::fs::metadata(path) {
451 Ok(m) => m.len() == 0,
452 Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
453 Err(e) => {
454 return Err(e).with_context(|| format!("stat'ing PMK table {}", path.display()));
455 }
456 };
457 if needs_header {
458 return create(path, ssid);
459 }
460 // Existing table: verify the recorded SSID and load its entries BEFORE
461 // truncating (v2 validation happens inside open).
462 let existing: Vec<([u8; 32], Vec<u8>)> = {
463 let (table_ssid, entries) =
464 open(path).with_context(|| format!("reading existing PMK table {}", path.display()))?;
465 check_ssid(table_ssid.as_deref(), ssid)
466 .with_context(|| format!("cannot append to PMK table {}", path.display()))?;
467 entries.collect()
468 };
469 let mut w = create(path, ssid)?;
470 for (pmk, pass) in &existing {
471 w.push_inner(pmk, pass, false)
472 .with_context(|| format!("rewriting PMK table {}", path.display()))?;
473 }
474 Ok(w)
475}
476
477/// Guard used before starting a rainbow run: the table's SSID must equal
478/// the target's. Returns a human reason on mismatch.
479pub fn check_ssid(table_ssid: Option<&str>, target_ssid: &str) -> Result<()> {
480 match table_ssid {
481 None => bail!("PMK table has no ssid header — cannot verify it matches the target"),
482 Some(s) if s != target_ssid => bail!(
483 "PMK table is for ssid \"{s}\" but the target's essid is \"{target_ssid}\" (PMKs are salt-bound to the ssid)"
484 ),
485 _ => Ok(()),
486 }
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492 use std::io::Write;
493
494 /// Serializes tests that assert on the process-wide skip counter
495 /// (parking_lot isn't a direct dependency; recover from poisoning
496 /// instead of unwrapping).
497 static SKIP_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
498
499 fn skip_lock() -> std::sync::MutexGuard<'static, ()> {
500 SKIP_LOCK.lock().unwrap_or_else(|e| e.into_inner())
501 }
502
503 fn tmp(name: &str) -> std::path::PathBuf {
504 std::env::temp_dir().join(format!("wifi_lab-{name}-{}", std::process::id()))
505 }
506
507 #[test]
508 fn header_parse() {
509 assert_eq!(
510 parse_header_v1("# wifi_lab-pmk v1 ssid=Testnet"),
511 Some("Testnet".to_string())
512 );
513 assert_eq!(
514 parse_header_v1("# wifi_lab-pmk v1 ssid=with space"),
515 Some("with space".to_string())
516 );
517 assert_eq!(parse_header_v1("# wifi_lab-pmk v1"), None);
518 assert_eq!(parse_header_v1("garbage"), None);
519 // v2: hex-ssid roundtrip, incl. spaces/UTF-8.
520 let mut h = String::from("# wifi_lab-pmk v2 ssid=");
521 hex_push(&mut h, "mit Leerzeichen".as_bytes());
522 assert_eq!(
523 parse_header_v2(h.as_bytes()),
524 Some("mit Leerzeichen".into())
525 );
526 assert_eq!(parse_header_v2(b"# wifi_lab-pmk v2 ssid=zz"), None);
527 assert_eq!(parse_header_v2(b"# wifi_lab-pmk v2"), None);
528 }
529
530 #[test]
531 fn entry_parse_strict() {
532 let pmk = [0xabu8; 32];
533 let hex = "ab".repeat(32);
534 let line = format!("{hex} pass word1");
535 let (got_pmk, got_pass) = parse_entry(line.as_bytes()).expect("parses");
536 assert_eq!(got_pmk, pmk);
537 assert_eq!(got_pass, b"pass word1");
538 // No space separator, short hex, bad char, short pass → rejected.
539 assert!(parse_entry(format!("{hex}pass word1").as_bytes()).is_none());
540 assert!(parse_entry(b"ab short").is_none());
541 assert!(parse_entry(format!("{}zz p", &hex[..62]).as_bytes()).is_none());
542 assert!(parse_entry(format!("{hex} short").as_bytes()).is_none());
543 // v2: hex passphrase, odd length/bad nibble rejected.
544 let v2 = format!("{hex} {}", "70".repeat(9));
545 let (p2, w2) = parse_entry_v2(v2.as_bytes()).expect("v2 parses");
546 assert_eq!(p2, pmk);
547 assert_eq!(w2, b"ppppppppp");
548 assert!(parse_entry_v2(format!("{hex} abc").as_bytes()).is_none());
549 assert!(parse_entry_v2(format!("{hex} 7z").as_bytes()).is_none());
550 }
551
552 #[test]
553 fn roundtrip_write_read() {
554 let path = tmp("rainbow-test");
555 let entries: Vec<([u8; 32], Vec<u8>)> = vec![
556 ([0x11; 32], b"password1".to_vec()),
557 ([0x22; 32], b"two words here".to_vec()),
558 ([0x33; 32], b"a".repeat(63)),
559 ];
560 {
561 let mut w = create(&path, "Testnet").unwrap();
562 for (pmk, pass) in &entries {
563 w.push(pmk, pass).unwrap();
564 }
565 assert_eq!(w.finish().unwrap(), 3);
566 }
567 let (ssid, it) = open(&path).unwrap();
568 assert_eq!(ssid.as_deref(), Some("Testnet"));
569 let got: Vec<_> = it.collect();
570 assert_eq!(got, entries);
571 let _ = std::fs::remove_file(&path);
572 }
573
574 #[test]
575 fn v2_roundtrips_binary_passphrases() {
576 // Passphrase bytes that would corrupt a line-based v1 table:
577 // newline, carriage return, '=', leading/trailing spaces, high-bit.
578 let path = tmp("rainbow-bin");
579 let nasty: Vec<u8> = {
580 let mut v = b"give".to_vec();
581 v.extend_from_slice(b"me\nliberty=or giveme death \xf0\x9f\x94\x91");
582 v.truncate(40);
583 v
584 };
585 assert!(nasty.len() <= 63);
586 let entries: Vec<([u8; 32], Vec<u8>)> = vec![
587 ([0x01; 32], b"with\nnewline".to_vec()),
588 ([0x02; 32], b"trail=eq==".to_vec()),
589 ([0x03; 32], nasty.clone()),
590 ([0x04; 32], b"\xff\xfepass\x80\x81".to_vec()),
591 ];
592 {
593 let mut w = create(&path, "bin net").unwrap();
594 for (pmk, pass) in &entries {
595 w.push(pmk, pass).unwrap();
596 }
597 assert_eq!(w.finish().unwrap(), 4);
598 }
599 // On disk: no raw newline/"=" from passphrases — just hex.
600 let raw = std::fs::read_to_string(&path).unwrap();
601 assert_eq!(raw.lines().count(), 2 + 4); // header + 4 entries + footer
602 let (ssid, it) = open(&path).unwrap();
603 assert_eq!(ssid.as_deref(), Some("bin net"));
604 let got: Vec<_> = it.collect();
605 assert_eq!(got, entries);
606 let _ = std::fs::remove_file(&path);
607 }
608
609 #[test]
610 fn headerless_table_first_entry_has_exact_bytes() {
611 // Regression: the peeked first line kept its trailing \r\n, so entry
612 // #1's passphrase gained a newline and first-line hits were wrong.
613 let path = tmp("rainbow-hdr");
614 std::fs::write(
615 &path,
616 format!(
617 "{} firstp4ss\r\n{} secondp4ss\n",
618 "cd".repeat(32),
619 "ef".repeat(32)
620 ),
621 )
622 .unwrap();
623 let (ssid, it) = open(&path).unwrap();
624 assert_eq!(ssid, None);
625 let got: Vec<_> = it.collect();
626 assert_eq!(
627 got,
628 vec![
629 ([0xcd; 32], b"firstp4ss".to_vec()),
630 ([0xef; 32], b"secondp4ss".to_vec()),
631 ]
632 );
633 let _ = std::fs::remove_file(&path);
634 }
635
636 #[test]
637 fn v1_table_reads_with_legacy_entries() {
638 let _g = skip_lock();
639 let path = tmp("rainbow-v1");
640 {
641 let mut f = File::create(&path).unwrap();
642 writeln!(f, "# wifi_lab-pmk v1 ssid=Legacy").unwrap();
643 writeln!(f, "{} pass word1", "ab".repeat(32)).unwrap();
644 // Raw high-bit bytes in a v1 passphrase: still readable.
645 f.write_all("cd".repeat(32).as_bytes()).unwrap();
646 f.write_all(b" p\xe4ssw\xF6rd\n").unwrap();
647 // Malformed line: skipped (and counted), not fatal.
648 writeln!(f, "this is not an entry").unwrap();
649 }
650 let before = skipped_lines();
651 let (ssid, it) = open(&path).unwrap();
652 assert_eq!(ssid.as_deref(), Some("Legacy"));
653 let got: Vec<_> = it.collect();
654 assert_eq!(
655 got,
656 vec![
657 ([0xab; 32], b"pass word1".to_vec()),
658 ([0xcd; 32], b"p\xe4ssw\xF6rd".to_vec()),
659 ]
660 );
661 assert_eq!(skipped_lines() - before, 1);
662 let _ = std::fs::remove_file(&path);
663 }
664
665 #[test]
666 fn v2_corruption_and_truncation_detected() {
667 let path = tmp("rainbow-corrupt");
668 {
669 let mut w = create(&path, "Testnet").unwrap();
670 w.push(&[0x11; 32], b"password1").unwrap();
671 w.push(&[0x22; 32], b"password2").unwrap();
672 w.finish().unwrap();
673 }
674 let good = std::fs::read(&path).unwrap();
675
676 // Truncated (footer missing / partial build) → error, not partial read.
677 let footer_at = good
678 .windows(FOOTER.len())
679 .rposition(|w| w == FOOTER.as_bytes())
680 .unwrap();
681 std::fs::write(&path, &good[..footer_at]).unwrap();
682 let e = open(&path).err().expect("truncated table refused");
683 assert!(format!("{e:#}").contains("truncated"), "{e:#}");
684
685 // Mutated entry (flip one hex char of a passphrase) → checksum error.
686 let mut mutated = good.clone();
687 // First entry line starts right after the header line.
688 let off = good.iter().position(|&b| b == b'\n').unwrap() + 1 + 70;
689 mutated[off] = if mutated[off] == b'0' { b'1' } else { b'0' };
690 std::fs::write(&path, &mutated).unwrap();
691 let e = open(&path).err().expect("mutated table refused");
692 assert!(format!("{e:#}").contains("checksum"), "{e:#}");
693
694 // Entry inserted after the footer → error.
695 let mut appended = good.clone();
696 appended.extend_from_slice(format!("{} passw0rd3\n", "ab".repeat(32)).as_bytes());
697 std::fs::write(&path, &appended).unwrap();
698 assert!(open(&path).is_err());
699
700 // Untouched file still opens.
701 std::fs::write(&path, &good).unwrap();
702 let (_, it) = open(&path).unwrap();
703 assert_eq!(it.count(), 2);
704 let _ = std::fs::remove_file(&path);
705 }
706
707 #[test]
708 fn append_open_create_vs_append() {
709 let path = tmp("append-pmk");
710 let _ = std::fs::remove_file(&path);
711 // Missing file → created WITH a header, writable.
712 {
713 let mut w = append_open(&path, "net1").unwrap();
714 w.push(&[0x11; 32], b"password1").unwrap();
715 w.finish().unwrap();
716 }
717 // Same SSID → appends, existing entries kept intact.
718 {
719 let mut w = append_open(&path, "net1").unwrap();
720 w.push(&[0x22; 32], b"password2").unwrap();
721 w.finish().unwrap();
722 }
723 let (ssid, it) = open(&path).unwrap();
724 assert_eq!(ssid.as_deref(), Some("net1"));
725 assert_eq!(it.count(), 2);
726 // Truncated to zero bytes → treated like missing (fresh header).
727 std::fs::write(&path, b"").unwrap();
728 {
729 let mut w = append_open(&path, "changed").unwrap();
730 w.push(&[0x33; 32], b"password3").unwrap();
731 w.finish().unwrap();
732 }
733 let (ssid, it) = open(&path).unwrap();
734 assert_eq!(ssid.as_deref(), Some("changed"));
735 assert_eq!(it.count(), 1);
736 let _ = std::fs::remove_file(&path);
737 }
738
739 #[test]
740 fn append_open_dedupes_existing_entries() {
741 let path = tmp("append-dedupe");
742 {
743 let mut w = create(&path, "net1").unwrap();
744 w.push(&[0x11; 32], b"password1").unwrap();
745 w.push(&[0x22; 32], b"password2").unwrap();
746 assert_eq!(w.finish().unwrap(), 2);
747 }
748 // Duplicates inside one session are dropped too.
749 {
750 let mut w = create(&path, "net1").unwrap();
751 w.push(&[0xaa; 32], b"password1").unwrap();
752 w.push(&[0xbb; 32], b"password1").unwrap();
753 w.push(&[0x22; 32], b"password2").unwrap();
754 assert_eq!(w.finish().unwrap(), 2);
755 }
756 {
757 let mut w = append_open(&path, "net1").unwrap();
758 // password2 already in the table → deduped, not counted as new.
759 w.push(&[0x33; 32], b"password2").unwrap();
760 w.push(&[0x44; 32], b"password3").unwrap();
761 assert_eq!(w.finish().unwrap(), 1);
762 }
763 let (ssid, it) = open(&path).unwrap();
764 assert_eq!(ssid.as_deref(), Some("net1"));
765 let got: Vec<_> = it.collect();
766 assert_eq!(
767 got,
768 vec![
769 ([0xaa; 32], b"password1".to_vec()),
770 ([0x22; 32], b"password2".to_vec()),
771 ([0x44; 32], b"password3".to_vec()),
772 ]
773 );
774 let _ = std::fs::remove_file(&path);
775 }
776
777 #[test]
778 fn append_open_refuses_ssid_mismatch() {
779 let path = tmp("append-mix");
780 {
781 let mut w = create(&path, "net1").unwrap();
782 w.push(&[0x11; 32], b"password1").unwrap();
783 w.finish().unwrap();
784 }
785 // A table for another SSID must NOT receive appends (poisoning).
786 let e = append_open(&path, "othernet").err().expect("refused");
787 assert!(format!("{e:#}").contains("othernet"), "{e:#}");
788 // Headerless existing file: unverifiable → also refused.
789 let raw = tmp("append-raw");
790 std::fs::write(&raw, format!("{} passw0rd\n", "cd".repeat(32))).unwrap();
791 assert!(append_open(&raw, "net1").is_err());
792 // Corrupt v2 table: integrity error surfaces instead of silent loss.
793 let mut bytes = std::fs::read(&path).unwrap();
794 let off = bytes.iter().position(|&b| b == b'\n').unwrap() + 1 + 70;
795 bytes[off] = if bytes[off] == b'0' { b'1' } else { b'0' };
796 std::fs::write(&path, &bytes).unwrap();
797 assert!(append_open(&path, "net1").is_err());
798 let _ = std::fs::remove_file(&path);
799 let _ = std::fs::remove_file(&raw);
800 }
801
802 #[test]
803 fn ssid_guard() {
804 assert!(check_ssid(Some("Testnet"), "Testnet").is_ok());
805 assert!(check_ssid(Some("other"), "Testnet").is_err());
806 assert!(check_ssid(None, "Testnet").is_err());
807 }
808}