//! SSID-scoped precomputed PMK tables — the "rainbow" attack for WPA-PSK. //! //! PBKDF2-HMAC-SHA1(pass, essid, 4096) is the entire per-candidate cost of //! cracking; its output depends only on the passphrase and the SSID, not on //! the captured handshake. Caching pass→PMK pairs for one SSID therefore //! turns every later run against that SSID into a raw compare (millions of //! candidates per second), at disk cost of ~64 B per entry. //! //! Current text format (v2), one entry per line, all binary data hex-coded //! so no passphrase byte (newline, `=`, high-bit) can corrupt the frame: //! ```text //! # wifi_lab-pmk v2 ssid= //! <64 lowercase hex chars of PMK> //! # wifi_lab-pmk v2 end count= sha1=<40 lowercase hex> //! ``` //! The footer carries the entry count and a SHA-1 over the raw bytes of //! every entry line (without its newline); [`open`] validates both eagerly //! and REFUSES a truncated or mutated table instead of silently dropping //! entries. Legacy v1 files (`# wifi_lab-pmk v1 ssid=`, raw //! passphrase to end of line) are still read — with a `tracing::warn!` — but //! every write produces v2. use std::collections::HashSet; use std::fs::File; use std::io::{BufRead, BufReader, BufWriter, Seek, SeekFrom, Write}; use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; use anyhow::{Context, Result, bail}; use sha1::{Digest, Sha1}; const MAGIC_V1: &str = "# wifi_lab-pmk v1"; const MAGIC_V2: &str = "# wifi_lab-pmk v2"; const FOOTER: &str = "# wifi_lab-pmk v2 end"; /// Process-wide count of table lines skipped by [`open`] iterators while /// streaming v1/headerless files (malformed lines; v2 files are validated /// eagerly and never reach the iterator with bad lines). static SKIPPED_LINES: AtomicU64 = AtomicU64::new(0); /// Cumulative number of PMK-table lines skipped since process start (see /// [`SKIPPED_LINES`]). Read before/after exhausting an iterator; the delta /// is that file's skipped total. pub fn skipped_lines() -> u64 { SKIPPED_LINES.load(Ordering::Relaxed) } struct PmkIter { reader: BufReader<File>, /// v2 body (hex-coded passphrases, footer-terminated) vs legacy v1 /// (raw passphrase to end of line). v2: bool, /// First line, kept (trimmed) when it turned out to be an entry, not /// the header. pending: Option<Vec<u8>>, } /// Strip the line terminator: `\n`, then one `\r` of a CRLF pair. fn trim_eol(mut line: Vec<u8>) -> Vec<u8> { if line.last() == Some(&b'\n') { line.pop(); if line.last() == Some(&b'\r') { line.pop(); } } line } impl Iterator for PmkIter { type Item = ([u8; 32], Vec<u8>); fn next(&mut self) -> Option<Self::Item> { let mut buf = Vec::new(); loop { let line = if let Some(first) = self.pending.take() { first } else { buf.clear(); match self.reader.read_until(b'\n', &mut buf) { Ok(0) => return None, Ok(_) => trim_eol(std::mem::take(&mut buf)), // Unreadable line: count it and stop — a persistent read // error would otherwise spin forever. Err(_) => { SKIPPED_LINES.fetch_add(1, Ordering::Relaxed); return None; } } }; if self.v2 { if line.starts_with(FOOTER.as_bytes()) { return None; // end of entries } match parse_entry_v2(&line) { Some(entry) => return Some(entry), None => { SKIPPED_LINES.fetch_add(1, Ordering::Relaxed); continue; } } } // v1 / headerless: comments and empty lines are by design, not // counted as skipped. if line.is_empty() || line.starts_with(b"#") { continue; } match parse_entry(&line) { Some(entry) => return Some(entry), None => { SKIPPED_LINES.fetch_add(1, Ordering::Relaxed); continue; } } } } } /// `<64 hex> <pass>` → `(pmk, pass)`, or None when malformed (v1). fn parse_entry(line: &[u8]) -> Option<([u8; 32], Vec<u8>)> { if line.len() < 66 || line[64] != b' ' { return None; } let pmk = hex32(&line[..64])?; let pass = line[65..].to_vec(); // Writer only emits WPA-legal passphrases; hold the same invariant when // reading foreign tables so the cracker never wastes a compare. if !(8..=63).contains(&pass.len()) { return None; } Some((pmk, pass)) } /// `<64 hex> <hex-pass>` → `(pmk, pass)`, or None when malformed (v2). fn parse_entry_v2(line: &[u8]) -> Option<([u8; 32], Vec<u8>)> { if line.len() < 65 || line[64] != b' ' { return None; } let pmk = hex32(&line[..64])?; let pass = unhex(&line[65..])?; if !(8..=63).contains(&pass.len()) { return None; } Some((pmk, pass)) } /// Strict lowercase-or-uppercase 64-char hex → 32 bytes. fn hex32(s: &[u8]) -> Option<[u8; 32]> { if s.len() != 64 { return None; } let mut out = [0u8; 32]; for (i, pair) in s.as_chunks::<2>().0.iter().enumerate() { out[i] = (nibble(pair[0])? << 4) | nibble(pair[1])?; } Some(out) } /// Even-length lowercase-or-uppercase hex → bytes. fn unhex(s: &[u8]) -> Option<Vec<u8>> { if !s.len().is_multiple_of(2) { return None; } let mut out = Vec::with_capacity(s.len() / 2); for pair in s.as_chunks::<2>().0 { out.push((nibble(pair[0])? << 4) | nibble(pair[1])?); } Some(out) } fn nibble(b: u8) -> Option<u8> { match b { b'0'..=b'9' => Some(b - b'0'), b'a'..=b'f' => Some(b - b'a' + 10), b'A'..=b'F' => Some(b - b'A' + 10), _ => None, } } fn hex_push(out: &mut String, bytes: &[u8]) { const HEX: &[u8; 16] = b"0123456789abcdef"; for b in bytes { out.push(HEX[(b >> 4) as usize] as char); out.push(HEX[(b & 0xf) as usize] as char); } } /// Streaming `(pmk, passphrase)` entries of an opened table. pub type EntryIter = Box<dyn Iterator<Item = ([u8; 32], Vec<u8>)> + Send>; /// Open a table for cracking. Returns the SSID recorded in the header /// (`None` when the file has no header) plus a streaming iterator of /// `(pmk, passphrase)` entries. The caller MUST verify the header SSID /// matches the target — PMKs are salt-bound to the SSID and compare-fail /// silently otherwise. /// /// v2 tables are validated EAGERLY (one extra read pass): every entry line /// must parse, the footer must be present and last, its entry count and /// SHA-1 (over the raw entry-line bytes) must match — any violation is an /// error here, not silently dropped entries mid-crack. v1 tables load with /// a `tracing::warn!` (legacy, unauthenticated format). pub fn open(path: &Path) -> Result<(Option<String>, EntryIter)> { let f = File::open(path).with_context(|| format!("opening PMK table {}", path.display()))?; let mut reader = BufReader::with_capacity(1 << 20, f); // Peek the first line (byte-based: entry passphrases need not be UTF-8). let mut first = Vec::new(); let n = reader .read_until(b'\n', &mut first) .with_context(|| format!("reading PMK table {}", path.display()))?; let first = trim_eol(first); if n > 0 && first.starts_with(MAGIC_V2.as_bytes()) { let ssid = parse_header_v2(&first) .with_context(|| format!("malformed v2 header in PMK table {}", path.display()))?; validate_v2_body(&mut reader, path)?; // Validated: rewind past the header and stream the entries. let mut f = reader.into_inner(); f.seek(SeekFrom::Start(0)) .with_context(|| format!("rewinding PMK table {}", path.display()))?; let mut reader = BufReader::with_capacity(1 << 20, f); let mut header = Vec::new(); reader .read_until(b'\n', &mut header) .with_context(|| format!("reading PMK table {}", path.display()))?; return Ok(( Some(ssid), Box::new(PmkIter { reader, v2: true, pending: None, }), )); } let (ssid, pending) = if n > 0 { match std::str::from_utf8(&first).ok().and_then(parse_header_v1) { Some(s) => { tracing::warn!( "PMK table {} uses the legacy v1 format (no integrity check) — rebuild it to upgrade to v2", path.display() ); (Some(s), None) } // Not a header: the first line is an entry — keep it (TRIMMED: // the bytes yielded must not carry the line terminator). None => (None, Some(first)), } } else { (None, None) }; Ok(( ssid, Box::new(PmkIter { reader, v2: false, pending, }), )) } /// Eager integrity pass over the v2 body (header already consumed): every /// line until the footer must be a well-formed entry; the footer must be /// the last line and its `count`/`sha1` must match the body. fn validate_v2_body(reader: &mut BufReader<File>, path: &Path) -> Result<()> { let mut hash = Sha1::new(); let mut count = 0u64; let mut footer: Option<(u64, [u8; 20])> = None; let mut buf = Vec::new(); loop { buf.clear(); let n = reader .read_until(b'\n', &mut buf) .with_context(|| format!("reading PMK table {}", path.display()))?; if n == 0 { break; } let line = trim_eol(std::mem::take(&mut buf)); if let Some(f) = parse_footer(&line) { footer = Some(f); // The footer must terminate the file. let mut tail = Vec::new(); let m = reader .read_until(b'\n', &mut tail) .with_context(|| format!("reading PMK table {}", path.display()))?; if m != 0 { bail!( "PMK table {}: mutated — entries after the footer", path.display() ); } break; } if parse_entry_v2(&line).is_none() { bail!( "PMK table {}: mutated — malformed or unexpected line in v2 table", path.display() ); } hash.update(&line); count += 1; } let Some((want_count, want_digest)) = footer else { bail!( "PMK table {}: truncated — v2 footer missing (partial write?)", path.display() ); }; if want_count != count { bail!( "PMK table {}: corrupted — footer says {want_count} entries, body has {count}", path.display() ); } let digest: [u8; 20] = hash.finalize().into(); if digest != want_digest { bail!( "PMK table {}: corrupted — entry checksum mismatch", path.display() ); } Ok(()) } /// `# wifi_lab-pmk v1 ssid=<essid>` → Some(essid); anything else → None. fn parse_header_v1(line: &str) -> Option<String> { let rest = line.strip_prefix(MAGIC_V1)?; rest.strip_prefix(" ssid=").map(str::to_string) } /// `# wifi_lab-pmk v2 ssid=<hex essid>` → Some(essid); anything else → None. fn parse_header_v2(line: &[u8]) -> Option<String> { let rest = line.strip_prefix(MAGIC_V2.as_bytes())?; let rest = rest.strip_prefix(b" ssid=")?; String::from_utf8(unhex(rest)?).ok() } /// `# wifi_lab-pmk v2 end count=<n> sha1=<40 hex>` → Some((n, digest)). fn parse_footer(line: &[u8]) -> Option<(u64, [u8; 20])> { let s = std::str::from_utf8(line).ok()?; let rest = s.strip_prefix(FOOTER)?.strip_prefix(" count=")?; let (count_s, digest_s) = rest.split_once(" sha1=")?; let count: u64 = count_s.parse().ok()?; let digest: [u8; 20] = unhex(digest_s.as_bytes())?.try_into().ok()?; Some((count, digest)) } /// Streaming table writer: [`create`], [`TableWriter::push`], /// [`TableWriter::finish`] (writing the integrity footer). The file is only /// valid v2 once `finish` ran — a crash mid-build leaves a footer-less file /// that [`open`] reports as truncated instead of trusting. pub struct TableWriter { w: BufWriter<File>, /// Total entries in the file (preloaded + pushed this session). entries: u64, /// Entries pushed by THIS session's [`TableWriter::push`] calls (what /// [`TableWriter::finish`] reports back to the caller). session_new: u64, /// Passphrases already in the file (dedupe), preloaded on append. seen: HashSet<Vec<u8>>, /// Running SHA-1 over the raw entry-line bytes (footer checksum). hash: Sha1, } impl TableWriter { /// Append one entry. `pass` must be 8..=63 bytes (WPA passphrase range). /// A passphrase already in the table is skipped silently (dedupe); the /// file keeps exactly one entry per passphrase. pub fn push(&mut self, pmk: &[u8; 32], pass: &[u8]) -> std::io::Result<()> { self.push_inner(pmk, pass, true) } fn push_inner( &mut self, pmk: &[u8; 32], pass: &[u8], count_as_new: bool, ) -> std::io::Result<()> { debug_assert!((8..=63).contains(&pass.len())); if !self.seen.insert(pass.to_vec()) { return Ok(()); // duplicate passphrase — deduped } let mut line = String::with_capacity(64 + 1 + pass.len() * 2); hex_push(&mut line, pmk); line.push(' '); hex_push(&mut line, pass); self.hash.update(line.as_bytes()); line.push('\n'); self.w.write_all(line.as_bytes())?; self.entries += 1; if count_as_new { self.session_new += 1; } Ok(()) } /// Write the integrity footer and flush. Returns the number of entries /// appended by THIS session (preloaded/kept entries don't count). pub fn finish(mut self) -> std::io::Result<u64> { let digest = std::mem::take(&mut self.hash).finalize(); let mut footer = String::with_capacity(80); footer.push_str(FOOTER); footer.push_str(" count="); footer.push_str(&self.entries.to_string()); footer.push_str(" sha1="); hex_push(&mut footer, &digest); footer.push('\n'); self.w.write_all(footer.as_bytes())?; self.w.flush()?; Ok(self.session_new) } } /// Create a v2 table file with the header for `ssid`. Existing file is /// truncated. Parent directories are created. pub fn create(path: &Path, ssid: &str) -> Result<TableWriter> { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent) .with_context(|| format!("creating PMK table directory {}", parent.display()))?; } let f = File::create(path).with_context(|| format!("creating PMK table {}", path.display()))?; let mut w = BufWriter::with_capacity(1 << 20, f); let mut header = String::with_capacity(MAGIC_V2.len() + 8 + ssid.len() * 2); header.push_str(MAGIC_V2); header.push_str(" ssid="); hex_push(&mut header, ssid.as_bytes()); header.push('\n'); w.write_all(header.as_bytes()) .with_context(|| format!("writing PMK table header {}", path.display()))?; Ok(TableWriter { w, entries: 0, session_new: 0, seen: HashSet::new(), hash: Sha1::new(), }) } /// Open `path` as the table for `ssid` (per-SSID PMK cache writer): a /// missing or zero-length file is created fresh (`create` semantics); an /// existing non-empty file MUST carry a header whose SSID passes /// [`check_ssid`] against `ssid` — anything else is an error (refusing to /// corrupt a table belonging to another SSID). /// /// v2 tables can't grow by blind appending (the footer carries a checksum /// and entry count), so the existing entries are read — v2 integrity /// validated, so a truncated/mutated table errors here — and REWRITTEN /// together with the new ones; [`TableWriter::push`] dedupes against the /// existing passphrases. The file on disk never mixes formats: what leaves /// this function is always a valid v2 stream. pub fn append_open(path: &Path, ssid: &str) -> Result<TableWriter> { let needs_header = match std::fs::metadata(path) { Ok(m) => m.len() == 0, Err(e) if e.kind() == std::io::ErrorKind::NotFound => true, Err(e) => { return Err(e).with_context(|| format!("stat'ing PMK table {}", path.display())); } }; if needs_header { return create(path, ssid); } // Existing table: verify the recorded SSID and load its entries BEFORE // truncating (v2 validation happens inside open). let existing: Vec<([u8; 32], Vec<u8>)> = { let (table_ssid, entries) = open(path).with_context(|| format!("reading existing PMK table {}", path.display()))?; check_ssid(table_ssid.as_deref(), ssid) .with_context(|| format!("cannot append to PMK table {}", path.display()))?; entries.collect() }; let mut w = create(path, ssid)?; for (pmk, pass) in &existing { w.push_inner(pmk, pass, false) .with_context(|| format!("rewriting PMK table {}", path.display()))?; } Ok(w) } /// Guard used before starting a rainbow run: the table's SSID must equal /// the target's. Returns a human reason on mismatch. pub fn check_ssid(table_ssid: Option<&str>, target_ssid: &str) -> Result<()> { match table_ssid { None => bail!("PMK table has no ssid header — cannot verify it matches the target"), Some(s) if s != target_ssid => bail!( "PMK table is for ssid \"{s}\" but the target's essid is \"{target_ssid}\" (PMKs are salt-bound to the ssid)" ), _ => Ok(()), } } #[cfg(test)] mod tests { use super::*; use std::io::Write; /// Serializes tests that assert on the process-wide skip counter /// (parking_lot isn't a direct dependency; recover from poisoning /// instead of unwrapping). static SKIP_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); fn skip_lock() -> std::sync::MutexGuard<'static, ()> { SKIP_LOCK.lock().unwrap_or_else(|e| e.into_inner()) } fn tmp(name: &str) -> std::path::PathBuf { std::env::temp_dir().join(format!("wifi_lab-{name}-{}", std::process::id())) } #[test] fn header_parse() { assert_eq!( parse_header_v1("# wifi_lab-pmk v1 ssid=Testnet"), Some("Testnet".to_string()) ); assert_eq!( parse_header_v1("# wifi_lab-pmk v1 ssid=with space"), Some("with space".to_string()) ); assert_eq!(parse_header_v1("# wifi_lab-pmk v1"), None); assert_eq!(parse_header_v1("garbage"), None); // v2: hex-ssid roundtrip, incl. spaces/UTF-8. let mut h = String::from("# wifi_lab-pmk v2 ssid="); hex_push(&mut h, "mit Leerzeichen".as_bytes()); assert_eq!( parse_header_v2(h.as_bytes()), Some("mit Leerzeichen".into()) ); assert_eq!(parse_header_v2(b"# wifi_lab-pmk v2 ssid=zz"), None); assert_eq!(parse_header_v2(b"# wifi_lab-pmk v2"), None); } #[test] fn entry_parse_strict() { let pmk = [0xabu8; 32]; let hex = "ab".repeat(32); let line = format!("{hex} pass word1"); let (got_pmk, got_pass) = parse_entry(line.as_bytes()).expect("parses"); assert_eq!(got_pmk, pmk); assert_eq!(got_pass, b"pass word1"); // No space separator, short hex, bad char, short pass → rejected. assert!(parse_entry(format!("{hex}pass word1").as_bytes()).is_none()); assert!(parse_entry(b"ab short").is_none()); assert!(parse_entry(format!("{}zz p", &hex[..62]).as_bytes()).is_none()); assert!(parse_entry(format!("{hex} short").as_bytes()).is_none()); // v2: hex passphrase, odd length/bad nibble rejected. let v2 = format!("{hex} {}", "70".repeat(9)); let (p2, w2) = parse_entry_v2(v2.as_bytes()).expect("v2 parses"); assert_eq!(p2, pmk); assert_eq!(w2, b"ppppppppp"); assert!(parse_entry_v2(format!("{hex} abc").as_bytes()).is_none()); assert!(parse_entry_v2(format!("{hex} 7z").as_bytes()).is_none()); } #[test] fn roundtrip_write_read() { let path = tmp("rainbow-test"); let entries: Vec<([u8; 32], Vec<u8>)> = vec![ ([0x11; 32], b"password1".to_vec()), ([0x22; 32], b"two words here".to_vec()), ([0x33; 32], b"a".repeat(63)), ]; { let mut w = create(&path, "Testnet").unwrap(); for (pmk, pass) in &entries { w.push(pmk, pass).unwrap(); } assert_eq!(w.finish().unwrap(), 3); } let (ssid, it) = open(&path).unwrap(); assert_eq!(ssid.as_deref(), Some("Testnet")); let got: Vec<_> = it.collect(); assert_eq!(got, entries); let _ = std::fs::remove_file(&path); } #[test] fn v2_roundtrips_binary_passphrases() { // Passphrase bytes that would corrupt a line-based v1 table: // newline, carriage return, '=', leading/trailing spaces, high-bit. let path = tmp("rainbow-bin"); let nasty: Vec<u8> = { let mut v = b"give".to_vec(); v.extend_from_slice(b"me\nliberty=or giveme death \xf0\x9f\x94\x91"); v.truncate(40); v }; assert!(nasty.len() <= 63); let entries: Vec<([u8; 32], Vec<u8>)> = vec![ ([0x01; 32], b"with\nnewline".to_vec()), ([0x02; 32], b"trail=eq==".to_vec()), ([0x03; 32], nasty.clone()), ([0x04; 32], b"\xff\xfepass\x80\x81".to_vec()), ]; { let mut w = create(&path, "bin net").unwrap(); for (pmk, pass) in &entries { w.push(pmk, pass).unwrap(); } assert_eq!(w.finish().unwrap(), 4); } // On disk: no raw newline/"=" from passphrases — just hex. let raw = std::fs::read_to_string(&path).unwrap(); assert_eq!(raw.lines().count(), 2 + 4); // header + 4 entries + footer let (ssid, it) = open(&path).unwrap(); assert_eq!(ssid.as_deref(), Some("bin net")); let got: Vec<_> = it.collect(); assert_eq!(got, entries); let _ = std::fs::remove_file(&path); } #[test] fn headerless_table_first_entry_has_exact_bytes() { // Regression: the peeked first line kept its trailing \r\n, so entry // #1's passphrase gained a newline and first-line hits were wrong. let path = tmp("rainbow-hdr"); std::fs::write( &path, format!( "{} firstp4ss\r\n{} secondp4ss\n", "cd".repeat(32), "ef".repeat(32) ), ) .unwrap(); let (ssid, it) = open(&path).unwrap(); assert_eq!(ssid, None); let got: Vec<_> = it.collect(); assert_eq!( got, vec![ ([0xcd; 32], b"firstp4ss".to_vec()), ([0xef; 32], b"secondp4ss".to_vec()), ] ); let _ = std::fs::remove_file(&path); } #[test] fn v1_table_reads_with_legacy_entries() { let _g = skip_lock(); let path = tmp("rainbow-v1"); { let mut f = File::create(&path).unwrap(); writeln!(f, "# wifi_lab-pmk v1 ssid=Legacy").unwrap(); writeln!(f, "{} pass word1", "ab".repeat(32)).unwrap(); // Raw high-bit bytes in a v1 passphrase: still readable. f.write_all("cd".repeat(32).as_bytes()).unwrap(); f.write_all(b" p\xe4ssw\xF6rd\n").unwrap(); // Malformed line: skipped (and counted), not fatal. writeln!(f, "this is not an entry").unwrap(); } let before = skipped_lines(); let (ssid, it) = open(&path).unwrap(); assert_eq!(ssid.as_deref(), Some("Legacy")); let got: Vec<_> = it.collect(); assert_eq!( got, vec![ ([0xab; 32], b"pass word1".to_vec()), ([0xcd; 32], b"p\xe4ssw\xF6rd".to_vec()), ] ); assert_eq!(skipped_lines() - before, 1); let _ = std::fs::remove_file(&path); } #[test] fn v2_corruption_and_truncation_detected() { let path = tmp("rainbow-corrupt"); { let mut w = create(&path, "Testnet").unwrap(); w.push(&[0x11; 32], b"password1").unwrap(); w.push(&[0x22; 32], b"password2").unwrap(); w.finish().unwrap(); } let good = std::fs::read(&path).unwrap(); // Truncated (footer missing / partial build) → error, not partial read. let footer_at = good .windows(FOOTER.len()) .rposition(|w| w == FOOTER.as_bytes()) .unwrap(); std::fs::write(&path, &good[..footer_at]).unwrap(); let e = open(&path).err().expect("truncated table refused"); assert!(format!("{e:#}").contains("truncated"), "{e:#}"); // Mutated entry (flip one hex char of a passphrase) → checksum error. let mut mutated = good.clone(); // First entry line starts right after the header line. let off = good.iter().position(|&b| b == b'\n').unwrap() + 1 + 70; mutated[off] = if mutated[off] == b'0' { b'1' } else { b'0' }; std::fs::write(&path, &mutated).unwrap(); let e = open(&path).err().expect("mutated table refused"); assert!(format!("{e:#}").contains("checksum"), "{e:#}"); // Entry inserted after the footer → error. let mut appended = good.clone(); appended.extend_from_slice(format!("{} passw0rd3\n", "ab".repeat(32)).as_bytes()); std::fs::write(&path, &appended).unwrap(); assert!(open(&path).is_err()); // Untouched file still opens. std::fs::write(&path, &good).unwrap(); let (_, it) = open(&path).unwrap(); assert_eq!(it.count(), 2); let _ = std::fs::remove_file(&path); } #[test] fn append_open_create_vs_append() { let path = tmp("append-pmk"); let _ = std::fs::remove_file(&path); // Missing file → created WITH a header, writable. { let mut w = append_open(&path, "net1").unwrap(); w.push(&[0x11; 32], b"password1").unwrap(); w.finish().unwrap(); } // Same SSID → appends, existing entries kept intact. { let mut w = append_open(&path, "net1").unwrap(); w.push(&[0x22; 32], b"password2").unwrap(); w.finish().unwrap(); } let (ssid, it) = open(&path).unwrap(); assert_eq!(ssid.as_deref(), Some("net1")); assert_eq!(it.count(), 2); // Truncated to zero bytes → treated like missing (fresh header). std::fs::write(&path, b"").unwrap(); { let mut w = append_open(&path, "changed").unwrap(); w.push(&[0x33; 32], b"password3").unwrap(); w.finish().unwrap(); } let (ssid, it) = open(&path).unwrap(); assert_eq!(ssid.as_deref(), Some("changed")); assert_eq!(it.count(), 1); let _ = std::fs::remove_file(&path); } #[test] fn append_open_dedupes_existing_entries() { let path = tmp("append-dedupe"); { let mut w = create(&path, "net1").unwrap(); w.push(&[0x11; 32], b"password1").unwrap(); w.push(&[0x22; 32], b"password2").unwrap(); assert_eq!(w.finish().unwrap(), 2); } // Duplicates inside one session are dropped too. { let mut w = create(&path, "net1").unwrap(); w.push(&[0xaa; 32], b"password1").unwrap(); w.push(&[0xbb; 32], b"password1").unwrap(); w.push(&[0x22; 32], b"password2").unwrap(); assert_eq!(w.finish().unwrap(), 2); } { let mut w = append_open(&path, "net1").unwrap(); // password2 already in the table → deduped, not counted as new. w.push(&[0x33; 32], b"password2").unwrap(); w.push(&[0x44; 32], b"password3").unwrap(); assert_eq!(w.finish().unwrap(), 1); } let (ssid, it) = open(&path).unwrap(); assert_eq!(ssid.as_deref(), Some("net1")); let got: Vec<_> = it.collect(); assert_eq!( got, vec![ ([0xaa; 32], b"password1".to_vec()), ([0x22; 32], b"password2".to_vec()), ([0x44; 32], b"password3".to_vec()), ] ); let _ = std::fs::remove_file(&path); } #[test] fn append_open_refuses_ssid_mismatch() { let path = tmp("append-mix"); { let mut w = create(&path, "net1").unwrap(); w.push(&[0x11; 32], b"password1").unwrap(); w.finish().unwrap(); } // A table for another SSID must NOT receive appends (poisoning). let e = append_open(&path, "othernet").err().expect("refused"); assert!(format!("{e:#}").contains("othernet"), "{e:#}"); // Headerless existing file: unverifiable → also refused. let raw = tmp("append-raw"); std::fs::write(&raw, format!("{} passw0rd\n", "cd".repeat(32))).unwrap(); assert!(append_open(&raw, "net1").is_err()); // Corrupt v2 table: integrity error surfaces instead of silent loss. let mut bytes = std::fs::read(&path).unwrap(); let off = bytes.iter().position(|&b| b == b'\n').unwrap() + 1 + 70; bytes[off] = if bytes[off] == b'0' { b'1' } else { b'0' }; std::fs::write(&path, &bytes).unwrap(); assert!(append_open(&path, "net1").is_err()); let _ = std::fs::remove_file(&path); let _ = std::fs::remove_file(&raw); } #[test] fn ssid_guard() { assert!(check_ssid(Some("Testnet"), "Testnet").is_ok()); assert!(check_ssid(Some("other"), "Testnet").is_err()); assert!(check_ssid(None, "Testnet").is_err()); } }