forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

attack.rs2733 lines, 104.1 KiBHistoryRawDownload
1//! Cracker attack modes and the worker threads driving them.
2//!
3//! Everything here runs in the UI process — the candidates and the GPU
4//! need no privileges and **no radio**: wordlist / brute-force candidates
5//! go through PBKDF2 (GPU when an adapter exists, CPU fallback), a rainbow
6//! table ([`crate::rainbow`]) skips PBKDF2 entirely and checks precomputed
7//! PMKs with one PTK derivation + MIC compare each.
8//!
9//! Worker contract: progress via `CrackProgress` (its `done` is an exact
10//! RAW stream position — the session v2 resume index, see [`RawPosIter`]),
11//! then exactly one terminator — `CrackFound` + `CrackStopped { found:
12//! true }` on success, `CrackStopped { found: false }` on stop,
13//! exhaustion, or setup failure, `CrackError { reason }` on backend
14//! failure (GPU device lost / dispatch timeout / worker panic: NOT
15//! exhaustion; the resume session is left in place). The rainbow *builder*
16//! job reports `RainbowProgress` and always ends with one `RainbowBuilt`
17//! (entries written so far; errors precede it as `Error` events).
18
19use std::collections::HashSet;
20use std::path::{Path, PathBuf};
21use std::rc::Rc;
22use std::sync::Arc;
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::time::{Duration, Instant};
25
26use anyhow::{Context, Result, bail};
27use crossbeam_channel::Sender;
28
29use crate::common::Event;
30use crate::crypto::{self, CrackTarget};
31use crate::gpu::{self, GpuCracker};
32use crate::rainbow;
33use crate::store;
34use crate::wordlist;
35
36/// Attack mode selected on the Cracker page. Serialized into the resume
37/// session file (see [`crate::store::CrackSession`]) exactly as entered.
38#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
39pub enum Attack {
40 /// Dictionary: stream a wordlist through PBKDF2.
41 Wordlist(PathBuf),
42 /// Dictionary × mutation rules (hashcat-subset ops, see [`parse_rules`]).
43 Rules { wordlist: PathBuf, rules: PathBuf },
44 /// Dictionary × append-charset sweep: `word + charset^k` for k in `min..=max`.
45 Hybrid {
46 wordlist: PathBuf,
47 charset: Vec<u8>,
48 min: usize,
49 max: usize,
50 },
51 /// Exhaustive `charset^len` sweep for len in `min..=max` through PBKDF2.
52 /// `freq_order` permutes the charset most-common-first (a bijection —
53 /// space size and seek indices are unchanged).
54 Bruteforce {
55 charset: Vec<u8>,
56 min: usize,
57 max: usize,
58 #[serde(default)]
59 freq_order: bool,
60 },
61 /// Precomputed PMK table for the target SSID — no PBKDF2 at run time.
62 Rainbow(PathBuf),
63}
64
65impl Attack {
66 /// One line for logs/status.
67 pub fn describe(&self) -> String {
68 match self {
69 Attack::Wordlist(p) => format!("wordlist {}", p.display()),
70 Attack::Rules { wordlist, rules } => {
71 format!("rules {} × {}", wordlist.display(), rules.display())
72 }
73 Attack::Hybrid {
74 wordlist,
75 charset,
76 min,
77 max,
78 } => format!(
79 "hybrid {} + charset({} bytes) suffix len {min}..={max}",
80 wordlist.display(),
81 charset.len()
82 ),
83 Attack::Bruteforce {
84 charset,
85 min,
86 max,
87 freq_order,
88 } => format!(
89 "bruteforce charset({} bytes, {:?}…{}) len {min}..={max}",
90 charset.len(),
91 String::from_utf8_lossy(&charset[..charset.len().min(16)]),
92 if *freq_order { ", freq-order" } else { "" },
93 ),
94 Attack::Rainbow(p) => format!("rainbow {}", p.display()),
95 }
96 }
97
98 /// Fail-fast validation the UI runs BEFORE marking a run active, so a
99 /// refused start never leaves stale running flags or a zombie thread.
100 pub fn validate(&self) -> Result<()> {
101 match self {
102 Attack::Wordlist(p) => {
103 std::fs::File::open(p)
104 .with_context(|| format!("cannot open wordlist {}", p.display()))?;
105 }
106 Attack::Rules { wordlist, rules } => {
107 std::fs::File::open(wordlist)
108 .with_context(|| format!("cannot open wordlist {}", wordlist.display()))?;
109 let parsed = parse_rules(rules)
110 .with_context(|| format!("cannot parse rules file {}", rules.display()))?;
111 if parsed.is_empty() {
112 bail!("rules file {} has no rules", rules.display());
113 }
114 }
115 Attack::Hybrid {
116 wordlist,
117 charset,
118 min,
119 max,
120 } => {
121 std::fs::File::open(wordlist)
122 .with_context(|| format!("cannot open wordlist {}", wordlist.display()))?;
123 HybridIter::validate(charset, *min, *max)?;
124 }
125 Attack::Bruteforce {
126 charset,
127 min,
128 max,
129 freq_order,
130 } => {
131 BruteForce::new(charset.clone(), *min, *max, *freq_order).map(|_| ())?;
132 }
133 Attack::Rainbow(p) => {
134 std::fs::File::open(p)
135 .with_context(|| format!("cannot open PMK table {}", p.display()))?;
136 }
137 }
138 Ok(())
139 }
140}
141
142// ---------------------------------------------------------------------------
143// Charset presets (Cracker page bruteforce chips) + custom input
144// ---------------------------------------------------------------------------
145
146/// Predefined charsets the UI offers as toggle chips; the effective
147/// brute-force charset is the union of the checked presets and the
148/// custom field. Keep SPECIAL to the commonly used symbols — exotic
149/// bytes belong in the custom field.
150pub mod charset {
151 pub const LOWER: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
152 pub const UPPER: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
153 pub const DIGITS: &[u8] = b"0123456789";
154 pub const SPECIAL: &[u8] = b"!@#$%^&*()-_=+[]{};:,.<>/?";
155
156 /// Union of the selected presets + `custom`, deduplicated.
157 pub fn compose(
158 lower: bool,
159 upper: bool,
160 digits: bool,
161 special: bool,
162 custom: &[u8],
163 ) -> Vec<u8> {
164 let mut out = Vec::new();
165 for src in [
166 (lower, LOWER),
167 (upper, UPPER),
168 (digits, DIGITS),
169 (special, SPECIAL),
170 ] {
171 if src.0 {
172 out.extend_from_slice(src.1);
173 }
174 }
175 out.extend_from_slice(custom);
176 out.sort_unstable();
177 out.dedup();
178 out
179 }
180}
181
182// ---------------------------------------------------------------------------
183// Brute-force candidate generator
184// ---------------------------------------------------------------------------
185
186/// password-frequency heuristic: most-common characters first; the
187/// odometer still varies the right-most position fastest.
188const FREQ_ORDER: &[u8] = b"e1a0ir7o29nls38tc45um6!dpghwyb$vkfxqjz@EAOINSRHLTCDUMPFGYKWBVJXQZ#._-";
189
190/// Streaming `charset^len` generator for len in min..=max, clamped to the
191/// WPA passphrase range 8..=63. Odometer order: right-most position cycles
192/// fastest, words of one length exhaust before the next length starts.
193/// With `freq_order` the charset is permuted by [`FREQ_ORDER`] rank
194/// (chars absent from it keep codepoint order, appended after) — a
195/// bijection, so `space()` size and `seek()` indices are unchanged.
196pub struct BruteForce {
197 charset: Vec<u8>,
198 /// Clamped minimum length (the space starts here).
199 min_len: usize,
200 /// Current word length.
201 len: usize,
202 max_len: usize,
203 /// Odometer digits (indices into charset), same length as the word.
204 idx: Vec<usize>,
205 exhausted: bool,
206 /// Candidates yielded so far = raw stream position (the resume seek
207 /// index of the next unyielded candidate). [`BruteForce::seek`] sets it.
208 pos: u64,
209}
210
211impl BruteForce {
212 /// `Err` when the charset is empty or the clamped length range is empty
213 /// (nothing 8..=63-compatible to try).
214 pub fn new(charset: Vec<u8>, min: usize, max: usize, freq_order: bool) -> Result<Self> {
215 let mut charset = charset;
216 if freq_order {
217 let rank = |b: u8| {
218 FREQ_ORDER
219 .iter()
220 .position(|&c| c == b)
221 .unwrap_or(usize::MAX)
222 };
223 charset.sort_by_key(|&b| (rank(b), b));
224 charset.dedup();
225 } else {
226 charset.dedup();
227 }
228 if charset.is_empty() {
229 bail!("bruteforce: charset is empty");
230 }
231 // Intersect with the WPA passphrase range instead of clamping
232 // both bounds: 64..=70 must be rejected (empty intersection), not
233 // silently turned into 63..=63.
234 let lo = min.max(8);
235 let hi = max.min(63);
236 if lo > hi {
237 bail!("bruteforce: length range {min}..={max} has no WPA-legal lengths (8..=63)");
238 }
239 Ok(BruteForce {
240 charset,
241 min_len: lo,
242 len: lo,
243 max_len: hi,
244 idx: vec![0; lo],
245 exhausted: false,
246 pos: 0,
247 })
248 }
249
250 /// Total candidate count over the whole length range (may exceed u64;
251 /// used for logs only).
252 pub fn space(&self) -> u128 {
253 let base = self.charset.len() as u128;
254 (self.len..=self.max_len).map(|l| base.pow(l as u32)).sum()
255 }
256
257 /// Jump the odometer so the NEXT [`next`] yields candidate number `n`
258 /// (0-based) of the full space — the resume path. `n` beyond the space
259 /// exhausts the generator.
260 pub fn seek(&mut self, n: u64) {
261 let base = self.charset.len() as u128;
262 let mut rem = n as u128;
263 let mut len = self.min_len;
264 loop {
265 let size = base.pow(len as u32);
266 if rem < size || len == self.max_len {
267 break;
268 }
269 rem -= size;
270 len += 1;
271 }
272 if len == self.max_len && rem >= base.pow(len as u32) {
273 self.exhausted = true;
274 self.pos = n;
275 return;
276 }
277 // Odometer order: right-most digit cycles fastest → `rem` is the
278 // index in little-endian base-|charset|.
279 self.len = len;
280 self.idx = vec![0; len];
281 for pos in (0..len).rev() {
282 self.idx[pos] = (rem % base) as usize;
283 rem /= base;
284 }
285 self.exhausted = false;
286 self.pos = n;
287 }
288}
289
290impl RawPosIter for BruteForce {
291 fn raw_pos(&self) -> u64 {
292 self.pos
293 }
294}
295
296impl Iterator for BruteForce {
297 type Item = Vec<u8>;
298
299 fn next(&mut self) -> Option<Vec<u8>> {
300 if self.exhausted {
301 return None;
302 }
303 let word: Vec<u8> = self.idx.iter().map(|&d| self.charset[d]).collect();
304 self.pos += 1;
305 // Advance the odometer; carry beyond the left-most digit either
306 // grows the word length or exhausts the space.
307 let mut pos = self.idx.len();
308 loop {
309 if pos == 0 {
310 if self.len == self.max_len {
311 self.exhausted = true;
312 } else {
313 self.len += 1;
314 self.idx = vec![0; self.len];
315 }
316 break;
317 }
318 pos -= 1;
319 self.idx[pos] += 1;
320 if self.idx[pos] < self.charset.len() {
321 break;
322 }
323 self.idx[pos] = 0;
324 }
325 Some(word)
326 }
327}
328
329// ---------------------------------------------------------------------------
330// Raw stream positions (exact resume, session format v2)
331// ---------------------------------------------------------------------------
332
333/// Candidate iterators that know their exact RAW stream position: the
334/// index of the next unyielded candidate in the addressing scheme the
335/// mode's resume seek uses (flattened index for rules/hybrid, plain
336/// candidate number otherwise). Raw positions count EVERY slot —
337/// candidates filtered out below (rules/hybrid length rejects) or skipped
338/// above ([`CacheSkipIter`]) consume raw positions too. This makes a saved
339/// position an exact resume point that is INDEPENDENT of the PMK cache's
340/// contents: a mutated cache changes which candidates get skipped, never
341/// the addressing.
342trait RawPosIter: Iterator<Item = Vec<u8>> {
343 /// Raw index of the NEXT unyielded candidate (absolute — seek
344 /// functions preset it, so `raw_pos() - yields_since_seek` is not
345 /// meaningful; use the value directly).
346 fn raw_pos(&self) -> u64;
347}
348
349impl RawPosIter for Box<dyn RawPosIter> {
350 fn raw_pos(&self) -> u64 {
351 (**self).raw_pos()
352 }
353}
354
355/// Adds raw (yield-)positions to any plain `Vec<u8>` candidate stream
356/// whose resume is a plain `skip_n` (wordlist files, arcane tables: their
357/// stream addressing already IS the yield sequence). `at` is the absolute
358/// position of the next yield (resume offset).
359struct CountIter<I: Iterator<Item = Vec<u8>>> {
360 inner: I,
361 pos: u64,
362}
363
364impl<I: Iterator<Item = Vec<u8>>> CountIter<I> {
365 fn at(inner: I, pos: u64) -> Self {
366 CountIter { inner, pos }
367 }
368}
369
370impl<I: Iterator<Item = Vec<u8>>> Iterator for CountIter<I> {
371 type Item = Vec<u8>;
372
373 fn next(&mut self) -> Option<Vec<u8>> {
374 let out = self.inner.next()?;
375 self.pos += 1;
376 Some(out)
377 }
378}
379
380impl<I: Iterator<Item = Vec<u8>>> RawPosIter for CountIter<I> {
381 fn raw_pos(&self) -> u64 {
382 self.pos
383 }
384}
385
386/// FIFO of raw positions: one entry per candidate DELIVERED to the crack
387/// backend (post-cache-skip), popped once the backend confirms processing
388/// via a progress tick. The pop count aligns with the progress event's
389/// cumulative `done`, mapping it to an exact raw position. Bounded by the
390/// backend's in-flight window (≤ a couple of batches).
391type PosMap = std::rc::Rc<std::cell::RefCell<std::collections::VecDeque<u64>>>;
392
393/// Wraps the final (post-cache-skip) stream delivered to a crack backend
394/// and records the raw position after each yield for [`PosMap`].
395struct PosFeed {
396 inner: Box<dyn RawPosIter>,
397 map: PosMap,
398}
399
400impl PosFeed {
401 fn new(inner: Box<dyn RawPosIter>) -> (PosFeed, PosMap) {
402 let map: PosMap = Default::default();
403 (
404 PosFeed {
405 inner,
406 map: map.clone(),
407 },
408 map,
409 )
410 }
411}
412
413impl Iterator for PosFeed {
414 type Item = Vec<u8>;
415
416 fn next(&mut self) -> Option<Vec<u8>> {
417 let out = self.inner.next()?;
418 let raw = self.inner.raw_pos();
419 self.map.borrow_mut().push_back(raw);
420 Some(out)
421 }
422}
423
424/// Translate a backend progress count (`done` = candidates processed so
425/// far THIS run) into the absolute raw position of the last processed
426/// candidate, popping confirmed entries out of `map`. Returns `None` when
427/// the map underflows (a found-candidate early return, or a partial batch
428/// the backend never counted — in both cases the last known position is
429/// still the last reported one).
430fn raw_position_of(map: &PosMap, acked: &mut u64, done: u64) -> Option<u64> {
431 let mut raw = None;
432 let mut dq = map.borrow_mut();
433 while *acked < done {
434 match dq.pop_front() {
435 Some(p) => {
436 raw = Some(p);
437 *acked += 1;
438 }
439 None => break,
440 }
441 }
442 raw
443}
444
445// ---------------------------------------------------------------------------
446// Mutation rules (hashcat-subset) — wordlist × rules attack
447// ---------------------------------------------------------------------------
448
449/// One hashcat-style single-letter op (supported subset). `$X`/`^X` carry
450/// the literal byte; `sXY` carries (from, to).
451#[derive(Clone, Debug, PartialEq, Eq)]
452pub enum Op {
453 Noop,
454 Lower,
455 Upper,
456 Capitalize,
457 InvertCapitalize,
458 Toggle,
459 Reverse,
460 Duplicate,
461 Append(u8),
462 Prepend(u8),
463 DeleteFirst,
464 DeleteLast,
465 Replace(u8, u8),
466}
467
468/// One rule = a line's ops, applied left to right (`c $1 $9` etc.).
469pub type Rule = Vec<Op>;
470
471/// Apply `ops` to `word`, left to right. `None` when the result falls
472/// outside the WPA passphrase range 8..=63 — filtered like WordIter, but
473/// the flattened index CONSUMES that candidate (resume positions line up
474/// with the raw stream).
475fn apply_rule(ops: &Rule, word: &[u8]) -> Option<Vec<u8>> {
476 let mut w = word.to_vec();
477 for op in ops {
478 match op {
479 Op::Noop => {}
480 Op::Lower => w.make_ascii_lowercase(),
481 Op::Upper => w.make_ascii_uppercase(),
482 Op::Capitalize => {
483 w.make_ascii_lowercase();
484 if let Some(first) = w.first_mut() {
485 first.make_ascii_uppercase();
486 }
487 }
488 Op::InvertCapitalize => {
489 w.make_ascii_uppercase();
490 if let Some(first) = w.first_mut() {
491 first.make_ascii_lowercase();
492 }
493 }
494 Op::Toggle => {
495 for b in &mut w {
496 if b.is_ascii_lowercase() {
497 *b = b.to_ascii_uppercase();
498 } else if b.is_ascii_uppercase() {
499 *b = b.to_ascii_lowercase();
500 }
501 }
502 }
503 Op::Reverse => w.reverse(),
504 Op::Duplicate => {
505 let tail = w.clone();
506 w.extend_from_slice(&tail);
507 }
508 Op::Append(b) => w.push(*b),
509 Op::Prepend(b) => w.insert(0, *b),
510 Op::DeleteFirst => {
511 if !w.is_empty() {
512 w.remove(0);
513 }
514 }
515 Op::DeleteLast => {
516 w.pop();
517 }
518 Op::Replace(x, y) => {
519 for b in &mut w {
520 if b == x {
521 *b = *y;
522 }
523 }
524 }
525 }
526 }
527 (8..=63).contains(&w.len()).then_some(w)
528}
529
530/// Parse one rules line into ops. The grammar is byte-oriented: `$`/`^`
531/// take the next byte as the literal to append/prepend, `s` takes the two
532/// following bytes. Fails with a positioned message on unknown ops or
533/// truncated literals.
534fn parse_rule_line(line: &[u8], lineno: usize) -> Result<Rule> {
535 let mut ops = Vec::new();
536 let mut i = 0usize;
537 while i < line.len() {
538 let c = line[i];
539 i += 1;
540 let op = match c {
541 // Space separates ops in hashcat files ("c $1 $!" etc.) and is
542 // itself a do-nothing op there; skip it. Appending a literal
543 // space still works ("$ " — the space is $'s literal).
544 b' ' => continue,
545 b':' => Op::Noop,
546 b'l' => Op::Lower,
547 b'u' => Op::Upper,
548 b'c' => Op::Capitalize,
549 b'C' => Op::InvertCapitalize,
550 b't' => Op::Toggle,
551 b'r' => Op::Reverse,
552 b'd' => Op::Duplicate,
553 b'[' => Op::DeleteFirst,
554 b']' => Op::DeleteLast,
555 b'$' | b'^' => {
556 let Some(&lit) = line.get(i) else {
557 bail!("rules line {lineno}: `{c}` at column {i} is missing its character");
558 };
559 i += 1;
560 if c == b'$' {
561 Op::Append(lit)
562 } else {
563 Op::Prepend(lit)
564 }
565 }
566 b's' => {
567 let Some(&x) = line.get(i) else {
568 bail!(
569 "rules line {lineno}: `s` at column {i} is missing its replacement chars"
570 );
571 };
572 let Some(&y) = line.get(i + 1) else {
573 bail!(
574 "rules line {lineno}: `s` at column {i} is missing its replacement chars"
575 );
576 };
577 i += 2;
578 Op::Replace(x, y)
579 }
580 _ => bail!(
581 "rules line {lineno}: unsupported op `{}` (column {})",
582 c as char,
583 i - 1
584 ),
585 };
586 ops.push(op);
587 }
588 Ok(ops)
589}
590
591/// Parse a hashcat-subset rules file (the classic best64.rule family):
592/// blank lines and lines starting with `#` are skipped, every other line
593/// is one rule. The "::"-style noop lines parse to a single [`Op::Noop`]
594/// per `:`.
595pub fn parse_rules(path: &Path) -> Result<Vec<Rule>> {
596 use std::io::BufRead;
597
598 let f = std::fs::File::open(path)
599 .with_context(|| format!("opening rules file {}", path.display()))?;
600 let mut reader = std::io::BufReader::with_capacity(1 << 16, f);
601 let mut rules = Vec::new();
602 let mut line = String::new();
603 let mut lineno = 0usize;
604 loop {
605 line.clear();
606 let n = reader
607 .read_line(&mut line)
608 .with_context(|| format!("reading rules file {}", path.display()))?;
609 if n == 0 {
610 break;
611 }
612 lineno += 1;
613 let trimmed = line.trim_end_matches(['\r', '\n']);
614 if trimmed.is_empty() || trimmed.starts_with('#') {
615 continue;
616 }
617 rules.push(parse_rule_line(trimmed.as_bytes(), lineno)?);
618 }
619 Ok(rules)
620}
621
622/// Count of real rules (non-blank, non-comment lines) — the per-word
623/// multiplier for the rules attack's flattened space. Consumed by the
624/// cracker-page estimator (W4 UI surface).
625#[allow(dead_code)]
626pub fn rule_count(path: &Path) -> Result<u64> {
627 use std::io::BufRead;
628
629 let f = std::fs::File::open(path)
630 .with_context(|| format!("opening rules file {}", path.display()))?;
631 let mut count = 0u64;
632 for line in std::io::BufReader::with_capacity(1 << 16, f).lines() {
633 let line = line.with_context(|| format!("reading rules file {}", path.display()))?;
634 let trimmed = line.trim_end_matches(['\r', '\n']);
635 if !trimmed.is_empty() && !trimmed.starts_with('#') {
636 count += 1;
637 }
638 }
639 Ok(count)
640}
641
642/// wordlist × rules generator, WORD-MAJOR / rule-minor: rules are applied
643/// to word 0 in file order, then to word 1, and so on. The flattened
644/// candidate index of `(word_idx, rule_idx)` is `word_idx * rules_len +
645/// rule_idx`, so a resume position is a plain `skip_n` over this stream —
646/// even though rule outputs outside 8..=63 are filtered (they still
647/// consume a flattened index, matching [`apply_rule`]'s contract).
648pub struct RuleIter {
649 words: Box<dyn Iterator<Item = Vec<u8>> + Send>,
650 rules: Rc<Vec<Rule>>,
651 cur: Option<Vec<u8>>,
652 ri: usize,
653 /// Flattened slots consumed so far (`word_idx * rules_len + ri`,
654 /// absolute): the resume seek index of the next unconsumed slot.
655 flat: u64,
656}
657
658impl RuleIter {
659 pub fn new(words: Box<dyn Iterator<Item = Vec<u8>> + Send>, rules: Rc<Vec<Rule>>) -> Self {
660 if rules.is_empty() {
661 // Degenerate case: keep the stream empty rather than panic.
662 return RuleIter {
663 words: Box::new(std::iter::empty()),
664 rules,
665 cur: None,
666 ri: 0,
667 flat: 0,
668 };
669 }
670 RuleIter {
671 words,
672 rules,
673 cur: None,
674 ri: 0,
675 flat: 0,
676 }
677 }
678
679 /// Position the generator at flattened index `n` (exact resume): skip
680 /// `n / rules_len` words and continue at rule `n % rules_len` of the
681 /// next word. `n` beyond the space leaves the stream at its end.
682 pub fn seek_flat(&mut self, n: u64) {
683 let rules_len = self.rules.len() as u64;
684 if rules_len == 0 {
685 // Degenerate stream: always empty; positions are moot.
686 self.flat = n;
687 return;
688 }
689 skip_n(&mut self.words, n / rules_len);
690 let ri = (n % rules_len) as usize;
691 // cur = None makes the first next() LOAD the word — which resets
692 // ri to 0; pre-fill `cur` instead so the primed rule index
693 // survives (a wordlist failure/exhaustion just empties the
694 // stream).
695 self.cur = self.words.next();
696 self.ri = if self.cur.is_some() { ri } else { 0 };
697 self.flat = n;
698 }
699}
700
701impl RawPosIter for RuleIter {
702 fn raw_pos(&self) -> u64 {
703 self.flat
704 }
705}
706
707impl Iterator for RuleIter {
708 type Item = Vec<u8>;
709
710 fn next(&mut self) -> Option<Vec<u8>> {
711 loop {
712 if self.cur.is_none() {
713 self.cur = Some(self.words.next()?);
714 self.ri = 0;
715 }
716 let cur = self.cur.clone().expect("just filled");
717 while self.ri < self.rules.len() {
718 let r = &self.rules[self.ri];
719 self.ri += 1;
720 self.flat += 1;
721 if let Some(out) = apply_rule(r, &cur) {
722 return Some(out);
723 }
724 // Filtered: the index slot is consumed (documented above).
725 }
726 self.cur = None;
727 }
728 }
729}
730
731// ---------------------------------------------------------------------------
732// Hybrid: wordlist × append-charset sweep (word + charset^k)
733// ---------------------------------------------------------------------------
734
735/// wordlist × append-charset generator: for each word yields
736/// `word + charset^k` for k in `min..=max`, rightmost-fastest odometer
737/// like [`BruteForce`]. Suffix lengths `min`/`max` are clamped to 1..=4
738/// (the bruteforce-ish complement of the wordlist — longer suffixes
739/// belong to plain bruteforce). Candidates longer than 63 bytes are
740/// skipped AFTER consuming their flattened index (like [`RuleIter`]).
741///
742/// Flattened index of `(word_idx, inner)` is `word_idx * per_word +
743/// inner` with `per_word = Σ_{k=min..=max} |charset|^k`; `inner` walks
744/// k-blocks in ascending order with little-endian odometer order inside a
745/// block (same convention as [`BruteForce`]). `total = line_count(wordlist)
746/// * per_word` is an upper bound (length-skipping only shrinks it).
747pub struct HybridIter {
748 words: Box<dyn Iterator<Item = Vec<u8>> + Send>,
749 charset: Vec<u8>,
750 min: usize,
751 max: usize,
752 cur_word: Option<Vec<u8>>,
753 /// Suffix length currently emitted for `cur_word`.
754 k: usize,
755 /// Odometer digits for the current suffix length.
756 odo: Vec<usize>,
757 /// Set by `seek_flat`: the odometer was primed externally and the next
758 /// word load must NOT reset it.
759 primed: bool,
760 /// Flattened slots consumed so far (absolute): the resume seek index
761 /// of the next unconsumed slot.
762 flat: u64,
763 /// Slots consumed for the CURRENT word (0..=per_word).
764 inner_used: u64,
765}
766
767impl HybridIter {
768 /// `Err` when the charset is empty or the clamped suffix range is
769 /// inverted (`min` > `max` after clamping: `min` 4 with `max` 1 etc.).
770 pub fn new(
771 words: Box<dyn Iterator<Item = Vec<u8>> + Send>,
772 charset: Vec<u8>,
773 min: usize,
774 max: usize,
775 ) -> Result<Self> {
776 let (min, max) = Self::clamped_range(min, max)?;
777 let mut charset = charset;
778 charset.sort_unstable();
779 charset.dedup();
780 if charset.is_empty() {
781 bail!("hybrid: charset is empty");
782 }
783 Ok(HybridIter {
784 words,
785 charset,
786 min,
787 max,
788 cur_word: None,
789 k: min,
790 odo: vec![0; min],
791 primed: false,
792 flat: 0,
793 inner_used: 0,
794 })
795 }
796
797 /// Flag validation for [`Attack::Hybrid`] (no word stream needed).
798 pub fn validate(charset: &[u8], min: usize, max: usize) -> Result<()> {
799 let mut cs = charset.to_vec();
800 cs.sort_unstable();
801 cs.dedup();
802 if cs.is_empty() {
803 bail!("hybrid: charset is empty");
804 }
805 Self::clamped_range(min, max).map(|_| ())
806 }
807
808 fn clamped_range(min: usize, max: usize) -> Result<(usize, usize)> {
809 let lo = min.clamp(1, 4);
810 let hi = max.clamp(1, 4);
811 if lo > hi {
812 bail!("hybrid: suffix length range {min}..={max} is inverted (clamped 1..=4)");
813 }
814 Ok((lo, hi))
815 }
816
817 /// Candidates emitted per wordlist word: Σ_{k=min..=max} |charset|^k
818 /// (saturated to u64::MAX).
819 pub fn per_word(&self) -> u64 {
820 let base = self.charset.len() as u128;
821 let s: u128 = (self.min..=self.max).map(|k| base.pow(k as u32)).sum();
822 s.min(u64::MAX as u128) as u64
823 }
824
825 /// Position the generator at flattened index `n` (resume): skips
826 /// `n / per_word` words and primes the suffix odometer to emit the
827 /// remainder `n % per_word`. An `n` beyond the space leaves the stream
828 /// at its natural end.
829 pub fn seek_flat(&mut self, n: u64) {
830 let per_word = self.per_word();
831 let word_idx = n.checked_div(per_word).unwrap_or(n);
832 let inner = if per_word == 0 { 0 } else { n % per_word };
833 skip_n(&mut self.words, word_idx);
834 self.set_inner(inner as u128);
835 // The skipped words leave cur_word empty; next() loads the word at
836 // word_idx (or the stream ends) — WITHOUT clobbering the primed
837 // odometer (one word only).
838 self.cur_word = None;
839 self.primed = true;
840 self.flat = n;
841 self.inner_used = inner;
842 }
843
844 /// Consume the rest of the current word's slots without emitting
845 /// (overlong-word early exit: every remaining candidate is provably
846 /// >63 bytes, i.e. "tried" by construction).
847 fn consume_word_rest(&mut self) {
848 let rest = self.per_word().saturating_sub(self.inner_used);
849 self.flat += rest;
850 self.inner_used = self.per_word();
851 self.cur_word = None;
852 }
853
854 /// Prime the odometer so the next calls yield suffix-block index
855 /// `inner` (ascending k-blocks, little-endian odometer per block).
856 fn set_inner(&mut self, mut rem: u128) {
857 let base = self.charset.len() as u128;
858 let mut k = self.min;
859 loop {
860 let size = base.pow(k as u32);
861 if rem < size || k == self.max {
862 break;
863 }
864 rem -= size;
865 k += 1;
866 }
867 // rem can exceed the last block only when `inner` pointed past the
868 // whole per-word space (callers never produce that), but stay
869 // defensive: exhaust the stream at the first next().
870 let mut odo = vec![0usize; k];
871 for pos in (0..k).rev() {
872 odo[pos] = (rem % base) as usize;
873 rem /= base;
874 }
875 if rem > 0 {
876 // Sentinel: out-of-range digit exhausts at the first next().
877 self.k = k;
878 self.odo = vec![self.charset.len(); k];
879 return;
880 }
881 self.k = k;
882 self.odo = odo;
883 }
884}
885
886impl RawPosIter for HybridIter {
887 fn raw_pos(&self) -> u64 {
888 self.flat
889 }
890}
891
892impl Iterator for HybridIter {
893 type Item = Vec<u8>;
894
895 fn next(&mut self) -> Option<Vec<u8>> {
896 loop {
897 if self.cur_word.is_none() {
898 self.cur_word = Some(self.words.next()?);
899 // seek_flat-primed state survives the first word load;
900 // afterwards the odometer restarts at zero per word.
901 if !self.primed {
902 self.k = self.min;
903 self.odo = vec![0; self.k];
904 self.inner_used = 0;
905 }
906 self.primed = false;
907 }
908 let word = self.cur_word.clone().expect("just filled");
909 // Out-of-range sentinel from set_inner: exhaust the word.
910 if self.odo.iter().any(|&d| d >= self.charset.len()) {
911 self.consume_word_rest();
912 continue;
913 }
914 let mut cand = word.clone();
915 for d in &self.odo {
916 cand.push(self.charset[*d]);
917 }
918 self.flat += 1;
919 self.inner_used += 1;
920 // Advance the odometer: rightmost fastest; carry grows k until
921 // max is exhausted, which moves on to the next word.
922 let mut pos = self.odo.len();
923 loop {
924 if pos == 0 {
925 if self.k == self.max {
926 self.cur_word = None;
927 } else {
928 self.k += 1;
929 self.odo = vec![0; self.k];
930 }
931 break;
932 }
933 pos -= 1;
934 self.odo[pos] += 1;
935 if self.odo[pos] < self.charset.len() {
936 break;
937 }
938 self.odo[pos] = 0;
939 }
940 // >63-byte candidates are skipped but consumed the index.
941 if cand.len() <= 63 {
942 return Some(cand);
943 }
944 // word exhausted check: when the suffix made it not fit at k,
945 // larger k will not either — consume the word's remaining
946 // slots (all provably too long) and jump to the next word.
947 if self.cur_word.is_some() && word.len() + self.k + 1 > 63 {
948 self.consume_word_rest();
949 }
950 }
951 }
952}
953
954// ---------------------------------------------------------------------------
955// PMK-cache coverage filter
956// ---------------------------------------------------------------------------
957
958/// Wraps a candidate stream, dropping candidates already covered by the
959/// per-SSID PMK cache consult (they were shown not to match). Skipped
960/// candidates consume their RAW positions like any other (the cache pass
961/// did the work), so saved positions stay exact no matter how the cache
962/// changes between save and resume — see [`RawPosIter`].
963pub struct CacheSkipIter<I: Iterator<Item = Vec<u8>>> {
964 inner: I,
965 covered: HashSet<Box<[u8]>>,
966}
967
968impl<I: Iterator<Item = Vec<u8>>> CacheSkipIter<I> {
969 pub fn new(inner: I, covered: HashSet<Box<[u8]>>) -> Self {
970 CacheSkipIter { inner, covered }
971 }
972}
973
974impl<I: Iterator<Item = Vec<u8>>> Iterator for CacheSkipIter<I> {
975 type Item = Vec<u8>;
976
977 fn next(&mut self) -> Option<Vec<u8>> {
978 self.inner
979 .by_ref()
980 .find(|cand| !self.covered.contains(cand.as_slice()))
981 }
982}
983
984/// After a yield, the wrapped iterator's raw position reflects every slot
985/// pulled to produce it — including the cache-skipped ones: positions
986/// stay in RAW stream coordinates (cache contents never shift them).
987impl<I: Iterator<Item = Vec<u8>> + RawPosIter> RawPosIter for CacheSkipIter<I> {
988 fn raw_pos(&self) -> u64 {
989 self.inner.raw_pos()
990 }
991}
992
993// ---------------------------------------------------------------------------
994// Workers
995// ---------------------------------------------------------------------------
996
997fn send(tx: &Sender<Event>, ev: Event) {
998 let _ = tx.send(ev);
999}
1000
1001fn log(tx: &Sender<Event>, line: impl Into<String>) {
1002 send(tx, Event::Log(line.into()));
1003}
1004
1005fn log_err(tx: &Sender<Event>, line: impl Into<String>) {
1006 send(tx, Event::Error(line.into()));
1007}
1008
1009/// Run-scoped crack context shared by the words-family backends: target
1010/// identity, raw-position map, worst-case total, event sink, stop flag
1011/// and the CPU-only override. Bundled so [`word_crack`] stays under the
1012/// argument-count lint.
1013struct CrackCtx<'a> {
1014 target_desc: &'a str,
1015 target: &'a CrackTarget,
1016 pos_map: &'a PosMap,
1017 total: Option<u64>,
1018 tx: &'a Sender<Event>,
1019 stop: &'a Arc<AtomicBool>,
1020 force_cpu: bool,
1021}
1022
1023/// GPU (or CPU-fallback) PBKDF2 crack over a word stream — the selection
1024/// logic the cracker has always used. `total` is the worst-case candidate
1025/// count (worst-case ETA = (total - done) / hps) when the source is
1026/// countable. `pos_map` carries raw stream positions recorded by
1027/// [`PosFeed`], one per candidate DELIVERED to the backend; progress
1028/// events map backend-confirmed counts onto them, so `CrackProgress.done`
1029/// is always an exact raw position (session v2 resume index), never a
1030/// post-filter yield count. `force_cpu` skips the GPU entirely (CLI
1031/// `--cpu`); it also disables the PMK-cache sink so a forced-CPU client
1032/// run stays side-effect-free. Otherwise a PURE-CPU run (no adapter, or a
1033/// key_ver the shader cannot express) populates the per-SSID PMK cache
1034/// while it cracks — every candidate's PBKDF2 result lands in
1035/// `store::cache_file(essid)` in rainbow format.
1036///
1037/// `Err` means the GPU backend itself failed (device lost, dispatch
1038/// timeout): NOT exhaustion, NOT user stop — the caller reports
1039/// [`Event::CrackError`] and the session stays resumable.
1040fn word_crack(
1041 ctx: &CrackCtx<'_>,
1042 words: &mut dyn Iterator<Item = Vec<u8>>,
1043) -> Result<Option<String>, gpu::GpuError> {
1044 let CrackCtx {
1045 target_desc,
1046 target,
1047 pos_map,
1048 total,
1049 tx,
1050 stop,
1051 force_cpu,
1052 } = *ctx;
1053 if let Some(t) = total {
1054 log(tx, format!("cracker: worst case: {t} candidates"));
1055 }
1056 let mut progress = {
1057 let tx = tx.clone();
1058 let map = pos_map.clone();
1059 let mut acked = 0u64;
1060 move |done: u64, hps: f64| {
1061 if let Some(raw) = raw_position_of(&map, &mut acked, done) {
1062 send(
1063 &tx,
1064 Event::CrackProgress {
1065 done: raw,
1066 hps,
1067 total,
1068 },
1069 );
1070 }
1071 }
1072 };
1073 // SHA1-family targets (handshake key_ver 1|2, PMKID) crack fully
1074 // on-device (init + chain + MIC epilogue); key_ver 3 / overlong
1075 // ESSIDs stay on the CPU cracker even when a GPU exists.
1076 let adapter = if !force_cpu && gpu::gpu_verifiable(target) {
1077 GpuCracker::try_new()
1078 } else {
1079 None
1080 };
1081 match adapter {
1082 Some(g) => {
1083 log(
1084 tx,
1085 format!(
1086 "cracker: GPU backend: {} — cracking {target_desc}",
1087 g.device_name()
1088 ),
1089 );
1090 // GPU runs never populate the cache: the hit-slot readback
1091 // pipeline has no PMK readback plumbed through it.
1092 g.crack(target, words, &mut progress, stop)
1093 }
1094 None => {
1095 log(
1096 tx,
1097 if force_cpu {
1098 format!("cracker: CPU backend (forced) — cracking {target_desc}")
1099 } else {
1100 format!(
1101 "cracker: CPU backend (no adapter or non-SHA1 target) — cracking {target_desc}"
1102 )
1103 },
1104 );
1105 let mut sink = if force_cpu {
1106 None
1107 } else {
1108 let path = store::cache_file(target.essid());
1109 match rainbow::append_open(&path, target.essid()) {
1110 Ok(w) => Some(gpu::CpuPmkSink::new(w, {
1111 let tx = tx.clone();
1112 Box::new(move |line: String| log(&tx, line))
1113 })),
1114 Err(e) => {
1115 log(
1116 tx,
1117 format!(
1118 "pmk cache: cannot open cache file for writing ({e:#}) — continuing without"
1119 ),
1120 );
1121 None
1122 }
1123 }
1124 };
1125 let found = gpu::cpu_crack(target, words, &mut progress, stop, sink.as_mut());
1126 if let Some(s) = sink {
1127 match s.finish() {
1128 Ok(n) => log(
1129 tx,
1130 format!(
1131 "pmk cache: {n} PMKs cached → {}",
1132 store::cache_file(target.essid()).display()
1133 ),
1134 ),
1135 Err(e) => log(tx, format!("pmk cache: flush failed ({e:#})")),
1136 }
1137 }
1138 Ok(found)
1139 }
1140 }
1141}
1142
1143/// Rainbow run: precomputed PMKs, one PTK derivation + MIC compare per
1144/// entry (no PBKDF2). Progress ticks are time-based (~4/s) so a fast disk
1145/// is not reporting-bound.
1146pub fn rainbow_crack(
1147 target: &CrackTarget,
1148 entries: &mut dyn Iterator<Item = ([u8; 32], Vec<u8>)>,
1149 progress: &mut dyn FnMut(u64, f64),
1150 stop: &Arc<AtomicBool>,
1151) -> Option<String> {
1152 let prepared = gpu::prepare_target(target);
1153 let mut done = 0u64;
1154 let started = Instant::now();
1155 let mut last_tick = started;
1156 for (pmk, pass) in entries {
1157 done += 1;
1158 if gpu::prepared_matches(&prepared, &pmk) {
1159 progress(
1160 done,
1161 done as f64 / started.elapsed().as_secs_f64().max(1e-6),
1162 );
1163 return String::from_utf8(pass).ok();
1164 }
1165 if last_tick.elapsed() > Duration::from_millis(250) {
1166 last_tick = Instant::now();
1167 progress(
1168 done,
1169 done as f64 / started.elapsed().as_secs_f64().max(1e-6),
1170 );
1171 }
1172 if done.is_multiple_of(4096) && stop.load(Ordering::Relaxed) {
1173 return None;
1174 }
1175 }
1176 // Exhaustion: a table smaller than one tick interval would otherwise
1177 // end with zero progress ever reported (the word path ticks per
1178 // batch — match it).
1179 progress(
1180 done,
1181 done as f64 / started.elapsed().as_secs_f64().max(1e-6),
1182 );
1183 None
1184}
1185
1186/// Drop the first `n` items of a candidate stream (resume). The stream
1187/// simply runs out early when fewer than `n` remain — the caller's crack
1188/// loop then reports "exhausted" on the empty remainder.
1189fn skip_n<T>(it: &mut dyn Iterator<Item = T>, mut n: u64) {
1190 while n > 0 && it.next().is_some() {
1191 n -= 1;
1192 }
1193}
1194
1195/// Result of consulting the per-SSID PMK cache before a wordlist-family run.
1196enum CacheConsult {
1197 /// Cache contained the PSK — report as a normal find, skip the main run.
1198 Hit(String),
1199 /// Readable cache, no match: the covered passphrases to skip in the
1200 /// main iterator.
1201 Miss(HashSet<Box<[u8]>>),
1202 /// No cache, or unreadable — run everything.
1203 Skip,
1204}
1205
1206/// Per-SSID PMK cache consult (`~/wifi_lab/cache/<ssid-hex>.pmk`, rainbow
1207/// text format): if the file exists and is readable, run a quick
1208/// PBKDF2-free pass ([`rainbow_crack`]) over its entries BEFORE the main
1209/// attack. On a miss the caller wraps the main iterator in
1210/// [`CacheSkipIter`] so cached-and-ruled-out passwords are not recomputed.
1211/// Unreadable caches (open/parse/header-SSID mismatch) produce exactly
1212/// one `Log` and fall through to a full run.
1213fn consult_cache(
1214 target: &CrackTarget,
1215 attack_desc: &str,
1216 tx: &Sender<Event>,
1217 stop: &Arc<AtomicBool>,
1218) -> CacheConsult {
1219 let path = store::cache_file(target.essid());
1220 if !path.is_file() {
1221 return CacheConsult::Skip;
1222 }
1223 let mut entries = match rainbow::open(&path) {
1224 Ok((ssid, entries)) => match rainbow::check_ssid(ssid.as_deref(), target.essid()) {
1225 Ok(()) => entries,
1226 Err(e) => {
1227 log(
1228 tx,
1229 format!("pmk cache: unreadable ({e:#}), proceeding without"),
1230 );
1231 return CacheConsult::Skip;
1232 }
1233 },
1234 Err(e) => {
1235 log(
1236 tx,
1237 format!("pmk cache: unreadable ({e:#}), proceeding without"),
1238 );
1239 return CacheConsult::Skip;
1240 }
1241 };
1242 let total = wordlist::line_count(&path).ok().map(|n| n.max(1));
1243 let mut covered: HashSet<Box<[u8]>> = HashSet::new();
1244 // Tee the password out of each entry while rainbow_crack consumes.
1245 let mut teed = std::iter::from_fn(|| {
1246 entries.next().map(|(pmk, pass)| {
1247 covered.insert(pass.clone().into_boxed_slice());
1248 (pmk, pass)
1249 })
1250 });
1251 let mut progress = {
1252 let tx = tx.clone();
1253 move |done: u64, hps: f64| {
1254 send(&tx, Event::CrackProgress { done, hps, total });
1255 }
1256 };
1257 log(tx, "pmk cache: file exists — checking cached PMKs first");
1258 if let Some(pass) = rainbow_crack(target, &mut teed, &mut progress, stop) {
1259 return CacheConsult::Hit(pass);
1260 }
1261 if stop.load(Ordering::Relaxed) {
1262 // Stopped mid-consult: treat as a miss; the main run's stop checks
1263 // produce the canonical "stopped" terminator.
1264 return CacheConsult::Miss(covered);
1265 }
1266 log(
1267 tx,
1268 format!(
1269 "pmk cache: {} entries, no hit — continuing {attack_desc}",
1270 covered.len()
1271 ),
1272 );
1273 CacheConsult::Miss(covered)
1274}
1275
1276/// Start a crack run on a background thread. Always returns the stop flag;
1277/// spawn failure is reported as events instead of a thread. `resume_from`
1278/// is a RAW stream position (session v2): the candidate index the run
1279/// continues at — a flattened slot index for rules/hybrid (see
1280/// [`RuleIter::seek_flat`]/[`HybridIter::seek_flat`]), a plain skip count
1281/// for wordlist tables, an odometer index for bruteforce. Progress events
1282/// report raw positions of the FULL space from zero. `force_cpu` pins the
1283/// CPU backend (headless CLI `--cpu`) and disables PMK-cache writes.
1284/// Wordlist-family attacks first consult the per-SSID PMK cache
1285/// (`store::cache_file`): hit → the normal found-terminator without a
1286/// main run; miss → cached passwords are skipped via [`CacheSkipIter`]
1287/// WITHOUT shifting raw positions.
1288///
1289/// Terminators: found → `CrackFound` + `CrackStopped { found: true }`;
1290/// user stop / true exhaustion / setup failure → `CrackStopped { found:
1291/// false }`; GPU backend failure or worker panic → `CrackError { reason }`
1292/// (the session file stays resumable).
1293pub fn spawn_crack(
1294 target_desc: String,
1295 target: CrackTarget,
1296 attack: Attack,
1297 resume_from: u64,
1298 tx: Sender<Event>,
1299 force_cpu: bool,
1300) -> Arc<AtomicBool> {
1301 let stop = Arc::new(AtomicBool::new(false));
1302 let stop2 = stop.clone();
1303 let err_tx = tx.clone();
1304 let panic_tx = tx.clone();
1305 let result = std::thread::Builder::new()
1306 .name("wifi_lab-crack".into())
1307 .spawn(move || {
1308 let run = || {
1309 if resume_from > 0 {
1310 log(&tx, format!("cracker: resuming at candidate {resume_from}"));
1311 }
1312 // Per-SSID PMK cache consult (wordlist-family only).
1313 let wordlist_family = matches!(
1314 attack,
1315 Attack::Wordlist(_)
1316 | Attack::Rules { .. }
1317 | Attack::Hybrid { .. }
1318 | Attack::Bruteforce { .. }
1319 );
1320 let mut covered: Option<HashSet<Box<[u8]>>> = None;
1321 if wordlist_family {
1322 match consult_cache(&target, &attack.describe(), &tx, &stop2) {
1323 CacheConsult::Hit(password) => {
1324 log(&tx, format!("cracker: PASSWORD found: {password}"));
1325 send(&tx, Event::CrackFound { password });
1326 send(&tx, Event::CrackStopped { found: true });
1327 return;
1328 }
1329 CacheConsult::Miss(c) => covered = Some(c),
1330 CacheConsult::Skip => {}
1331 }
1332 }
1333 // Wrap a raw-positioned candidate stream with the coverage
1334 // filter from the cache consult (when one happened). Coverage
1335 // sits BETWEEN the raw stream and the backend: positions stay
1336 // raw, so a cache that changed since the session was saved
1337 // shifts only WHICH candidates get skipped, never the resume
1338 // address.
1339 fn with_cache<I: RawPosIter + 'static>(
1340 it: I,
1341 covered: &mut Option<HashSet<Box<[u8]>>>,
1342 ) -> Box<dyn RawPosIter> {
1343 match covered.take() {
1344 Some(c) => Box::new(CacheSkipIter::new(it, c)),
1345 None => Box::new(it),
1346 }
1347 }
1348 // Setup failures (missing files, bad rules): the error is
1349 // already logged; the run ends with the standard
1350 // not-found terminator (NOT CrackError: nothing backend died).
1351 fn setup_fail(tx: &Sender<Event>, e: &anyhow::Error) -> Result<Option<String>, gpu::GpuError> {
1352 log_err(tx, format!("cracker: {e:#}"));
1353 Ok(None)
1354 }
1355 // Snapshot the input skip counters so the run can surface
1356 // lines the iterators silently dropped (cache consult above
1357 // is excluded — it owns its own log lines).
1358 let wl_skipped_at_start = wordlist::skipped_lines();
1359 let rb_skipped_at_start = rainbow::skipped_lines();
1360 let found: Result<Option<String>, gpu::GpuError> = match &attack {
1361 Attack::Wordlist(path) => match wordlist::open(path) {
1362 Ok(mut words) => {
1363 // Line count is an upper bound (length-filtering
1364 // only shrinks the space — exactly the "worst
1365 // case" the ETA promises).
1366 let total = wordlist::line_count(path).ok();
1367 skip_n(&mut words, resume_from);
1368 let raw = CountIter::at(words, resume_from);
1369 let stream = with_cache(raw, &mut covered);
1370 let (mut feed, map) = PosFeed::new(stream);
1371 word_crack(
1372 &CrackCtx {
1373 target_desc: &target_desc,
1374 target: &target,
1375 pos_map: &map,
1376 total,
1377 tx: &tx,
1378 stop: &stop2,
1379 force_cpu,
1380 },
1381 &mut feed,
1382 )
1383 }
1384 Err(e) => setup_fail(&tx, &e),
1385 },
1386 Attack::Rules { wordlist: wl_path, rules: rules_path } => {
1387 match (wordlist::open(wl_path), parse_rules(rules_path)) {
1388 (Ok(words), Ok(rules)) => {
1389 let n_rules = rules.len() as u128;
1390 let lines = wordlist::line_count(wl_path).ok();
1391 // Worst case: every word × every rule.
1392 let total =
1393 lines.map(|l| (l as u128).saturating_mul(n_rules).min(u64::MAX as u128) as u64);
1394 let mut it = RuleIter::new(words, Rc::new(rules));
1395 // Exact flattened-index resume.
1396 it.seek_flat(resume_from);
1397 let stream = with_cache(it, &mut covered);
1398 let (mut feed, map) = PosFeed::new(stream);
1399 word_crack(
1400 &CrackCtx {
1401 target_desc: &target_desc,
1402 target: &target,
1403 pos_map: &map,
1404 total,
1405 tx: &tx,
1406 stop: &stop2,
1407 force_cpu,
1408 },
1409 &mut feed,
1410 )
1411 }
1412 (Err(e), _) => setup_fail(&tx, &e),
1413 (_, Err(e)) => setup_fail(&tx, &e),
1414 }
1415 }
1416 Attack::Hybrid { wordlist: wl_path, charset, min, max } => {
1417 match wordlist::open(wl_path) {
1418 Ok(words) => {
1419 let mut it = HybridIter::new(words, charset.clone(), *min, *max)
1420 .expect("validated");
1421 let lines = wordlist::line_count(wl_path).ok();
1422 let total = lines.map(|l| {
1423 (l as u128).saturating_mul(it.per_word() as u128).min(u64::MAX as u128)
1424 as u64
1425 });
1426 // Exact flattened-index resume.
1427 it.seek_flat(resume_from);
1428 let stream = with_cache(it, &mut covered);
1429 let (mut feed, map) = PosFeed::new(stream);
1430 word_crack(
1431 &CrackCtx {
1432 target_desc: &target_desc,
1433 target: &target,
1434 pos_map: &map,
1435 total,
1436 tx: &tx,
1437 stop: &stop2,
1438 force_cpu,
1439 },
1440 &mut feed,
1441 )
1442 }
1443 Err(e) => setup_fail(&tx, &e),
1444 }
1445 }
1446 Attack::Bruteforce { charset, min, max, freq_order } => {
1447 // validate() runs before spawn; new() cannot fail here.
1448 let mut brute =
1449 BruteForce::new(charset.clone(), *min, *max, *freq_order).expect("validated");
1450 let total = Some(brute.space().min(u64::MAX as u128) as u64);
1451 // Exact seek (no skipping): O(1) odometer math.
1452 brute.seek(resume_from);
1453 let stream = with_cache(brute, &mut covered);
1454 let (mut feed, map) = PosFeed::new(stream);
1455 word_crack(
1456 &CrackCtx {
1457 target_desc: &target_desc,
1458 target: &target,
1459 pos_map: &map,
1460 total,
1461 tx: &tx,
1462 stop: &stop2,
1463 force_cpu,
1464 },
1465 &mut feed,
1466 )
1467 }
1468 Attack::Rainbow(path) => match rainbow::open(path) {
1469 Ok((ssid, mut entries)) => {
1470 if let Err(e) = rainbow::check_ssid(ssid.as_deref(), target.essid()) {
1471 setup_fail(&tx, &e)
1472 } else {
1473 let total = wordlist::line_count(path).ok();
1474 skip_n(&mut entries, resume_from);
1475 // Rainbow entries have no cache coverage layer;
1476 // raw position = resume_from + pulls, recorded
1477 // per delivered item like the word paths.
1478 let map: PosMap = Default::default();
1479 let pull_map = map.clone();
1480 let mut pulls = resume_from;
1481 let mut feed = std::iter::from_fn(move || {
1482 let out = entries.next()?;
1483 pulls += 1;
1484 pull_map.borrow_mut().push_back(pulls);
1485 Some(out)
1486 });
1487 let mut acked = 0u64;
1488 let mut progress = {
1489 let tx = tx.clone();
1490 move |done: u64, hps: f64| {
1491 if let Some(raw) = raw_position_of(&map, &mut acked, done) {
1492 send(&tx, Event::CrackProgress { done: raw, hps, total });
1493 }
1494 }
1495 };
1496 log(
1497 &tx,
1498 format!("cracker: rainbow run (precomputed PMKs) — {target_desc}"),
1499 );
1500 Ok(rainbow_crack(&target, &mut feed, &mut progress, &stop2))
1501 }
1502 }
1503 Err(e) => setup_fail(&tx, &e),
1504 },
1505 };
1506 // One summary line per run when the input iterator silently
1507 // dropped lines (out-of-range or undecodable bytes).
1508 let skipped = if matches!(attack, Attack::Rainbow(_)) {
1509 rainbow::skipped_lines() - rb_skipped_at_start
1510 } else {
1511 wordlist::skipped_lines() - wl_skipped_at_start
1512 };
1513 if skipped > 0 {
1514 log(
1515 &tx,
1516 format!(
1517 "wordlist: {skipped} line(s) skipped (out-of-range or undecodable bytes)"
1518 ),
1519 );
1520 }
1521 match found {
1522 Err(e) => {
1523 // Backend failure (device lost, dispatch timeout,
1524 // unsupported mid-run): NOT exhaustion, NOT user stop.
1525 // The session file stays — the run may be resumed.
1526 log_err(&tx, format!("cracker: backend failed: {e} — run aborted, session resumable"));
1527 send(&tx, Event::CrackError { reason: e.to_string() });
1528 }
1529 Ok(Some(password)) => {
1530 log(&tx, format!("cracker: PASSWORD found: {password}"));
1531 send(&tx, Event::CrackFound { password });
1532 send(&tx, Event::CrackStopped { found: true });
1533 }
1534 Ok(None) => {
1535 if stop2.load(Ordering::Relaxed) {
1536 log(&tx, "cracker: stopped");
1537 } else {
1538 log(&tx, "cracker: candidates exhausted, password not found");
1539 }
1540 send(&tx, Event::CrackStopped { found: false });
1541 }
1542 }
1543 };
1544 if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)) {
1545 // A worker panic is a backend failure too: surface it as
1546 // CrackError (the session file stays for a resume) instead
1547 // of the historical silent "exhausted" mis-report.
1548 let msg = if let Some(s) = payload.downcast_ref::<&str>() {
1549 (*s).to_string()
1550 } else if let Some(s) = payload.downcast_ref::<String>() {
1551 s.clone()
1552 } else {
1553 "unknown panic payload".to_string()
1554 };
1555 log_err(&panic_tx, format!("cracker: worker panicked: {msg}"));
1556 send(&panic_tx, Event::CrackError { reason: format!("worker panicked: {msg}") });
1557 }
1558 });
1559 if let Err(e) = result {
1560 send(&err_tx, Event::Error(format!("cracker: spawn failed: {e}")));
1561 send(&err_tx, Event::CrackStopped { found: false });
1562 }
1563 stop
1564}
1565
1566/// Build a rainbow PMK table for `ssid` from a wordlist (PBKDF2 once —
1567/// GPU when available), so later runs against that SSID are PBKDF2-free.
1568/// Always ends with exactly one `RainbowBuilt` (entries written so far),
1569/// preceded by `Error` events on failure.
1570pub fn spawn_rainbow_build(
1571 ssid: String,
1572 wordlist: PathBuf,
1573 out: PathBuf,
1574 tx: Sender<Event>,
1575) -> Arc<AtomicBool> {
1576 let stop = Arc::new(AtomicBool::new(false));
1577 let stop2 = stop.clone();
1578 let err_tx = tx.clone();
1579 let out2 = out.clone();
1580 let result = std::thread::Builder::new()
1581 .name("wifi_lab-rainbow-build".into())
1582 .spawn(move || {
1583 let entries = build_table(&ssid, &wordlist, &out2, &tx, &stop2);
1584 send(
1585 &tx,
1586 Event::RainbowBuilt {
1587 path: out2.display().to_string(),
1588 entries,
1589 },
1590 );
1591 });
1592 if let Err(e) = result {
1593 send(&err_tx, Event::Error(format!("rainbow: spawn failed: {e}")));
1594 send(
1595 &err_tx,
1596 Event::RainbowBuilt {
1597 path: out.display().to_string(),
1598 entries: 0,
1599 },
1600 );
1601 }
1602 stop
1603}
1604
1605/// Batch PMK computer: raw passphrases in, one PMK per word out (GPU
1606/// kernel or test fake).
1607type PmkBatchFn<'a> = dyn FnMut(&[Vec<u8>]) -> Result<Vec<[u8; 32]>, gpu::GpuError> + 'a;
1608
1609/// Compute PMKs for EVERY word of `batch` over the GPU batch kernel.
1610/// `pmk_batch_gpu` may return only a PREFIX after its internal
1611/// halving-retry — the kernel was invoked on the head, the tail was never
1612/// attempted; loop it until the whole batch is covered (each retry itself
1613/// may return a shorter prefix). An empty `Ok` on a non-empty slice would
1614/// spin forever, so it is treated as failure. `Err` aborts the build
1615/// (the caller keeps the partial table).
1616fn gpu_pmk_batch_full(
1617 compute: &mut PmkBatchFn<'_>,
1618 batch: &[Vec<u8>],
1619) -> Result<Vec<[u8; 32]>, gpu::GpuError> {
1620 let mut out: Vec<[u8; 32]> = Vec::with_capacity(batch.len());
1621 while out.len() < batch.len() {
1622 let tail = &batch[out.len()..];
1623 let mut got = compute(tail)?;
1624 if got.is_empty() {
1625 // Not per the kernel's contract — bail rather than spin.
1626 return Err(gpu::GpuError::Unsupported(
1627 "batch kernel returned zero PMKs for a non-empty input".to_string(),
1628 ));
1629 }
1630 // Defensive: never accept more PMKs than requested words.
1631 got.truncate(tail.len());
1632 out.append(&mut got);
1633 }
1634 Ok(out)
1635}
1636
1637/// The build loop: wordlist batches → PMKs (GPU batch or per-word CPU) →
1638/// table file. Returns entries actually written.
1639fn build_table(
1640 ssid: &str,
1641 wordlist_path: &Path,
1642 out: &Path,
1643 tx: &Sender<Event>,
1644 stop: &Arc<AtomicBool>,
1645) -> u64 {
1646 let mut words = match wordlist::open(wordlist_path) {
1647 Ok(w) => w,
1648 Err(e) => {
1649 log_err(tx, format!("rainbow: {e:#}"));
1650 return 0;
1651 }
1652 };
1653 let mut table = match rainbow::create(out, ssid) {
1654 Ok(t) => t,
1655 Err(e) => {
1656 log_err(tx, format!("rainbow: {e:#}"));
1657 return 0;
1658 }
1659 };
1660 let gpu = GpuCracker::try_new();
1661 log(
1662 tx,
1663 match &gpu {
1664 Some(g) => format!(
1665 "rainbow: building via GPU ({}) → {}",
1666 g.device_name(),
1667 out.display()
1668 ),
1669 None => format!("rainbow: building via CPU → {}", out.display()),
1670 },
1671 );
1672
1673 const BATCH: usize = 4096;
1674 let salt = ssid.as_bytes();
1675 let total = wordlist::line_count(wordlist_path).ok();
1676 let mut written = 0u64;
1677 let started = Instant::now();
1678 let mut last_tick = started;
1679 'outer: loop {
1680 let mut batch: Vec<Vec<u8>> = Vec::with_capacity(BATCH);
1681 while batch.len() < BATCH {
1682 match words.next() {
1683 Some(w) => batch.push(w),
1684 None => break,
1685 }
1686 }
1687 if batch.is_empty() {
1688 break;
1689 }
1690 let pmks = match &gpu {
1691 Some(g) => {
1692 match gpu_pmk_batch_full(&mut |slice| g.pmk_batch_gpu(slice, salt), &batch) {
1693 Ok(p) => p,
1694 // Device hiccup even after the internal halving: give up,
1695 // the partial table stays usable.
1696 Err(e) => {
1697 log_err(
1698 tx,
1699 format!("rainbow: GPU batch failed ({e}) — table left partial"),
1700 );
1701 break 'outer;
1702 }
1703 }
1704 }
1705 None => batch.iter().map(|w| crypto::pmk(w, salt)).collect(),
1706 };
1707 debug_assert_eq!(pmks.len(), batch.len(), "every batch word must have a PMK");
1708 for (pmk, w) in pmks.iter().zip(batch.iter()) {
1709 if let Err(e) = table.push(pmk, w) {
1710 log_err(tx, format!("rainbow: write failed: {e:#}"));
1711 break 'outer;
1712 }
1713 written += 1;
1714 }
1715 if last_tick.elapsed() > Duration::from_millis(250) {
1716 last_tick = Instant::now();
1717 let secs = started.elapsed().as_secs_f64().max(1e-6);
1718 send(
1719 tx,
1720 Event::RainbowProgress {
1721 done: written,
1722 hps: written as f64 / secs,
1723 total,
1724 },
1725 );
1726 }
1727 if stop.load(Ordering::Relaxed) {
1728 log(tx, "rainbow: build stopped — partial table kept");
1729 break;
1730 }
1731 }
1732 let skipped_at_start = wordlist::skipped_lines();
1733 let skipped = wordlist::skipped_lines() - skipped_at_start;
1734 if skipped > 0 {
1735 log(
1736 tx,
1737 format!("wordlist: {skipped} line(s) skipped (out-of-range or undecodable bytes)"),
1738 );
1739 }
1740 match table.finish() {
1741 Ok(n) => n,
1742 Err(e) => {
1743 log_err(tx, format!("rainbow: flush failed: {e:#}"));
1744 written
1745 }
1746 }
1747}
1748
1749// ---------------------------------------------------------------------------
1750// Benchmark — measured H/s for the crack-time estimator
1751// ---------------------------------------------------------------------------
1752
1753/// CPU half of the benchmark: time `crypto::pmk` over candidate-sized
1754/// batches and report hashes/sec. Runs at least one batch; honors `stop`
1755/// between batches.
1756fn bench_cpu(secs: f64, stop: Option<&AtomicBool>) -> f64 {
1757 const BATCH: u64 = 512;
1758 let word = b"benchmark1";
1759 let salt = b"wifi_lab-bench";
1760 let started = Instant::now();
1761 let mut done = 0u64;
1762 loop {
1763 for _ in 0..BATCH {
1764 std::hint::black_box(crypto::pmk(std::hint::black_box(word), salt));
1765 }
1766 done += BATCH;
1767 let elapsed = started.elapsed().as_secs_f64();
1768 if elapsed >= secs {
1769 return done as f64 / elapsed.max(1e-6);
1770 }
1771 if let Some(s) = stop
1772 && s.load(Ordering::Relaxed)
1773 {
1774 return done as f64 / elapsed.max(1e-6);
1775 }
1776 }
1777}
1778
1779/// GPU half: batches of 4096 fixed words through the PMK kernel for
1780/// `secs`; `None` when no adapter exists (or the first dispatch fails —
1781/// the CPU number is still meaningful then).
1782fn bench_gpu(secs: f64, stop: Option<&AtomicBool>) -> Option<f64> {
1783 let g = GpuCracker::try_new()?;
1784 const BATCH: usize = 4096;
1785 let batch = vec![b"benchmark1".to_vec(); BATCH];
1786 let salt = b"wifi_lab-bench";
1787 let started = Instant::now();
1788 let mut done = 0u64;
1789 loop {
1790 // A mid-bench backend failure just ends the GPU half (the CPU
1791 // number is still meaningful).
1792 done += g.pmk_batch_gpu(&batch, salt).ok()?.len() as u64;
1793 let elapsed = started.elapsed().as_secs_f64();
1794 if elapsed >= secs {
1795 return Some(done as f64 / elapsed.max(1e-6));
1796 }
1797 if let Some(s) = stop
1798 && s.load(Ordering::Relaxed)
1799 {
1800 return Some(done as f64 / elapsed.max(1e-6));
1801 }
1802 }
1803}
1804
1805/// Measure crack throughput on this machine for `seconds` per backend:
1806/// returns `(gpu_hps, cpu_hps)` where the GPU half is `None` without an
1807/// adapter. Honoring `stop` between batches; `None` stop = run to time.
1808/// Synchronous — wrap it in [`spawn_benchmark`] for UI use.
1809#[allow(dead_code)]
1810pub fn benchmark(seconds: u32) -> (Option<f64>, f64) {
1811 let secs = seconds.max(1) as f64;
1812 (bench_gpu(secs, None), bench_cpu(secs, None))
1813}
1814
1815/// Benchmark on a background thread ("wifi_lab-benchmark"); terminates
1816/// with exactly one `Event::BenchmarkDone { gpu_hps, cpu_hps }` (on spawn
1817/// failure: an `Error` plus a zeroed `BenchmarkDone`). Honors the stop
1818/// flag between batches. The UI guards against running it alongside a
1819/// crack or rainbow build.
1820#[allow(dead_code)]
1821pub fn spawn_benchmark(seconds: u32, tx: Sender<Event>) -> Arc<AtomicBool> {
1822 let stop = Arc::new(AtomicBool::new(false));
1823 let stop2 = stop.clone();
1824 let err_tx = tx.clone();
1825 let result = std::thread::Builder::new()
1826 .name("wifi_lab-benchmark".into())
1827 .spawn(move || {
1828 log(
1829 &tx,
1830 format!("benchmark: measuring crack speed ({seconds}s per backend)"),
1831 );
1832 let secs = seconds.max(1) as f64;
1833 let gpu_hps = bench_gpu(secs, Some(&stop2));
1834 let cpu_hps = bench_cpu(secs, Some(&stop2));
1835 send(&tx, Event::BenchmarkDone { gpu_hps, cpu_hps });
1836 });
1837 if let Err(e) = result {
1838 send(
1839 &err_tx,
1840 Event::Error(format!("benchmark: spawn failed: {e}")),
1841 );
1842 send(
1843 &err_tx,
1844 Event::BenchmarkDone {
1845 gpu_hps: None,
1846 cpu_hps: 0.0,
1847 },
1848 );
1849 }
1850 stop
1851}
1852
1853#[cfg(test)]
1854mod tests {
1855 use super::*;
1856 use crate::common::{HandshakeCapture, MacAddr};
1857
1858 fn synthetic_target(ssid: &str, pass: &[u8]) -> CrackTarget {
1859 let ap: MacAddr = "aa:bb:cc:dd:ee:ff".parse().unwrap();
1860 let sta: MacAddr = "11:22:33:44:55:66".parse().unwrap();
1861 let anonce = [0x5a; 32];
1862 let snonce = [0xc3; 32];
1863 let key = crypto::pmk(pass, ssid.as_bytes());
1864 let dk = crypto::ptk(&key, &ap, &sta, &anonce, &snonce);
1865 // Minimal M2 frame (see gpu::tests::build_eapol_m2 — same layout).
1866 let mut f = Vec::with_capacity(99);
1867 f.push(0x02);
1868 f.push(0x03);
1869 f.extend_from_slice(&95u16.to_be_bytes());
1870 f.push(0x02);
1871 let info: u16 = 0x0100 | 0x0080 | 2;
1872 f.extend_from_slice(&info.to_be_bytes());
1873 f.extend_from_slice(&16u16.to_be_bytes());
1874 f.extend_from_slice(&1u64.to_be_bytes());
1875 f.extend_from_slice(&snonce);
1876 f.extend_from_slice(&[0u8; 16]);
1877 f.extend_from_slice(&[0u8; 8]);
1878 f.extend_from_slice(&[0u8; 8]);
1879 f.extend_from_slice(&[0u8; 16]);
1880 f.extend_from_slice(&0u16.to_be_bytes());
1881 let m = crypto::mic_on_zeroed(&dk, &crypto::zeroed_eapol(&f), 2);
1882 CrackTarget::Handshake(HandshakeCapture::new(
1883 ap,
1884 sta,
1885 ssid.to_string(),
1886 anonce,
1887 snonce,
1888 m,
1889 f,
1890 2,
1891 ))
1892 }
1893
1894 #[test]
1895 fn bruteforce_order_and_exhaustion() {
1896 let bf = BruteForce::new(b"ab".to_vec(), 8, 8, false).unwrap();
1897 let got: Vec<Vec<u8>> = bf.collect();
1898 assert_eq!(got.len(), 256);
1899 assert_eq!(got[0], b"aaaaaaaa");
1900 assert_eq!(got[1], b"aaaaaaab");
1901 assert_eq!(got[2], b"aaaaaaba");
1902 assert_eq!(got[255], b"bbbbbbbb");
1903 }
1904
1905 #[test]
1906 fn bruteforce_length_growth_and_clamp() {
1907 // Length grows only after the shorter space is exhausted; range is
1908 // clamped into 8..=63.
1909 let mut bf = BruteForce::new(b"z".to_vec(), 1, 100, false).unwrap();
1910 assert_eq!(bf.next().unwrap(), b"zzzzzzzz");
1911 assert_eq!(bf.next().unwrap(), b"zzzzzzzzz");
1912 let mut bf = BruteForce::new(b"z".to_vec(), 1, 9, false).unwrap();
1913 assert_eq!(bf.next().unwrap(), b"zzzzzzzz");
1914 assert_eq!(bf.next().unwrap(), b"zzzzzzzzz");
1915 assert_eq!(bf.next(), None);
1916 }
1917
1918 #[test]
1919 fn bruteforce_rejects_bad_input() {
1920 assert!(BruteForce::new(Vec::new(), 8, 12, false).is_err());
1921 assert!(BruteForce::new(b"a".to_vec(), 64, 70, false).is_err());
1922 assert!(BruteForce::new(b"a".to_vec(), 12, 8, false).is_err());
1923 }
1924
1925 #[test]
1926 fn bruteforce_seek_lands_exactly() {
1927 // seek(j) must equal collecting j items — across a length boundary.
1928 let reference: Vec<Vec<u8>> = BruteForce::new(b"abcde".to_vec(), 8, 9, false)
1929 .unwrap()
1930 .take(5usize.pow(8) + 40)
1931 .collect();
1932 for j in [0u64, 1, 17, 5u64.pow(8) - 1, 5u64.pow(8), 5u64.pow(8) + 39] {
1933 let mut bf = BruteForce::new(b"abcde".to_vec(), 8, 9, false).unwrap();
1934 bf.seek(j);
1935 let got: Vec<Vec<u8>> = bf.by_ref().take(3).collect();
1936 let want = &reference[j as usize..(j as usize + 3).min(reference.len())];
1937 assert_eq!(&got[..want.len()], want, "j={j}");
1938 }
1939 // Beyond the space: exhausted.
1940 let mut bf = BruteForce::new(b"ab".to_vec(), 8, 8, false).unwrap();
1941 bf.seek(256);
1942 assert_eq!(bf.next(), None);
1943 }
1944
1945 #[test]
1946 fn bruteforce_space_matches_stream_count() {
1947 let bf = BruteForce::new(b"abcd".to_vec(), 8, 9, false).unwrap();
1948 assert_eq!(bf.space(), 4u128.pow(8) + 4u128.pow(9));
1949 assert_eq!(bf.count() as u128, 4u128.pow(8) + 4u128.pow(9));
1950 }
1951
1952 #[test]
1953 fn rainbow_crack_finds_pass() {
1954 let pass = b"sup3r-secret";
1955 let target = synthetic_target("testnet", pass);
1956 let entries: Vec<([u8; 32], Vec<u8>)> = vec![
1957 (crypto::pmk(b"nope-nope", b"testnet"), b"nope-nope".to_vec()),
1958 (crypto::pmk(pass, b"testnet"), pass.to_vec()),
1959 ];
1960 let mut it = entries.into_iter();
1961 let stop = Arc::new(AtomicBool::new(false));
1962 let found = rainbow_crack(&target, &mut it, &mut |_, _| {}, &stop);
1963 assert_eq!(found.as_deref(), Some("sup3r-secret"));
1964 }
1965
1966 #[test]
1967 fn build_then_crack_end_to_end() {
1968 // The exact files the worker threads touch: wordlist in, table out,
1969 // crack via the table — no GPU required.
1970 let dir = std::env::temp_dir();
1971 let wl = dir.join(format!("wifi_lab-attack-wl-{}", std::process::id()));
1972 let tbl = dir.join(format!("wifi_lab-attack-tbl-{}", std::process::id()));
1973 std::fs::write(&wl, "nope-nope\nsup3r-secret\nalsonope!\n").unwrap();
1974
1975 let (etx, erx) = crossbeam_channel::unbounded();
1976 let stop = Arc::new(AtomicBool::new(false));
1977 let written = build_table("testnet", &wl, &tbl, &etx, &stop);
1978 assert_eq!(written, 3);
1979 let built: Vec<Event> = erx.try_iter().collect();
1980 assert!(!built.iter().any(|e| matches!(e, Event::Error(_))));
1981
1982 let target = synthetic_target("testnet", b"sup3r-secret");
1983 let (ssid, mut entries) = rainbow::open(&tbl).unwrap();
1984 rainbow::check_ssid(ssid.as_deref(), target.essid()).unwrap();
1985 let found = rainbow_crack(&target, &mut entries, &mut |_, _| {}, &stop);
1986 assert_eq!(found.as_deref(), Some("sup3r-secret"));
1987
1988 // Wrong-ssid table must be refused, not silently exhausted.
1989 let target2 = synthetic_target("othernet", b"sup3r-secret");
1990 assert!(rainbow::check_ssid(ssid.as_deref(), target2.essid()).is_err());
1991
1992 let _ = std::fs::remove_file(&wl);
1993 let _ = std::fs::remove_file(&tbl);
1994 }
1995
1996 #[test]
1997 fn spawn_crack_emits_progress_and_terminator() {
1998 // The full worker contract over the channel: starting a run MUST
1999 // surface progress and exactly one terminator (the historical bug
2000 // was a run that looked alive at 0 H/s forever). CPU fallback is
2001 // fine — the GPU path shares the same word_crack wrapper.
2002 let dir = std::env::temp_dir();
2003 let wl = dir.join(format!("wifi_lab-spawn-wl-{}", std::process::id()));
2004 std::fs::write(&wl, "wrong-pass1\nsup3r-secret\nwrong-pass2\n").unwrap();
2005 let target = synthetic_target("testnet", b"sup3r-secret");
2006 let (etx, erx) = crossbeam_channel::unbounded();
2007 // force_cpu: deterministic CPU run AND no PMK-cache writes into
2008 // the real ~/wifi_lab/cache from a test.
2009 let _stop = spawn_crack(
2010 target.describe(),
2011 target,
2012 Attack::Wordlist(wl.clone()),
2013 0,
2014 etx,
2015 true,
2016 );
2017 let mut found = None;
2018 let mut stopped = false;
2019 let deadline = std::time::Instant::now() + Duration::from_secs(60);
2020 while !(stopped) && std::time::Instant::now() < deadline {
2021 match erx.recv_timeout(Duration::from_secs(5)) {
2022 Ok(Event::CrackFound { password }) => found = Some(password),
2023 Ok(Event::CrackStopped { found: true }) => stopped = true,
2024 Ok(Event::CrackStopped { found: false }) => {
2025 panic!("run ended without finding the planted pass")
2026 }
2027 Ok(Event::Error(line)) => panic!("worker error: {line}"),
2028 Ok(_) => {} // Log/CrackProgress
2029 Err(_) => panic!("channel silent — no events, no terminator"),
2030 }
2031 }
2032 assert!(stopped, "no terminator within deadline");
2033 assert_eq!(found.as_deref(), Some("sup3r-secret"));
2034 let _ = std::fs::remove_file(&wl);
2035 }
2036
2037 #[test]
2038 #[ignore = "smoke: user's real stored capture + GPU; run on demand"]
2039 fn smoke_real_stored_capture() {
2040 let caps = crate::store::load_captures().expect(" ~/wifi_lab/captures.jsonl");
2041 let target = caps
2042 .iter()
2043 .find_map(|c| match c {
2044 crate::store::StoredCapture::Handshake(h) => {
2045 Some(CrackTarget::Handshake(h.clone()))
2046 }
2047 _ => None,
2048 })
2049 .expect("a stored handshake");
2050 let ssid = target.essid().to_string();
2051 eprintln!("smoke target: {}", target.describe());
2052
2053 let dir = std::env::temp_dir();
2054 let wl = dir.join("wifi_lab-smoke-wl.txt");
2055 std::fs::write(&wl, "password123\nletmein123\nqwertyuiop1\n").unwrap();
2056 let tbl = dir.join("wifi_lab-smoke.pmk");
2057
2058 let drain = |erx: &crossbeam_channel::Receiver<Event>, what: &str| {
2059 let mut saw_progress = false;
2060 let deadline = std::time::Instant::now() + Duration::from_secs(180);
2061 loop {
2062 assert!(
2063 std::time::Instant::now() < deadline,
2064 "{what}: no terminator"
2065 );
2066 match erx.recv_timeout(Duration::from_secs(10)) {
2067 Ok(
2068 Event::CrackProgress { done, hps, .. }
2069 | Event::RainbowProgress { done, hps, .. },
2070 ) => {
2071 if done > 0 {
2072 saw_progress = true;
2073 assert!(hps > 0.0, "{what}: progress with 0 H/s");
2074 }
2075 }
2076 Ok(Event::CrackStopped { found }) => {
2077 assert!(!found, "{what}: unexpected password match");
2078 break;
2079 }
2080 Ok(Event::RainbowBuilt { entries, .. }) => {
2081 assert!(entries > 0, "{what}: empty table");
2082 break;
2083 }
2084 Ok(Event::Error(l)) => panic!("{what}: {l}"),
2085 Ok(_) => {}
2086 Err(_) => panic!("{what}: channel silence"),
2087 }
2088 }
2089 assert!(
2090 saw_progress || what.contains("build"),
2091 "{what}: zero progress events"
2092 );
2093 };
2094
2095 // 1. wordlist run (GPU): the exact stuck path from the bug report.
2096 let (tx, rx) = crossbeam_channel::unbounded();
2097 let _s1 = spawn_crack(
2098 target.describe(),
2099 target.clone(),
2100 Attack::Wordlist(wl.clone()),
2101 0,
2102 tx,
2103 false,
2104 );
2105 drain(&rx, "wordlist run");
2106
2107 // 2. rainbow build then run (GPU for the build).
2108 let (tx, rx) = crossbeam_channel::unbounded();
2109 let _s2 = spawn_rainbow_build(ssid, wl.clone(), tbl.clone(), tx);
2110 drain(&rx, "rainbow build");
2111 let (tx, rx) = crossbeam_channel::unbounded();
2112 let _s3 = spawn_crack(
2113 target.describe(),
2114 target,
2115 Attack::Rainbow(tbl.clone()),
2116 0,
2117 tx,
2118 false,
2119 );
2120 drain(&rx, "rainbow run");
2121
2122 let _ = std::fs::remove_file(&wl);
2123 let _ = std::fs::remove_file(&tbl);
2124 }
2125
2126 #[test]
2127 fn resume_from_skips_checked_candidates() {
2128 // wordlist positions: 0 wrong, 1 wrong, 2 TARGET, 3 wrong.
2129 let dir = std::env::temp_dir();
2130 let wl = dir.join(format!("wifi_lab-resume-wl-{}", std::process::id()));
2131 std::fs::write(&wl, "wrong-pass1\nwrong-pass2\nsup3r-secret\nwrong-pass3\n").unwrap();
2132 let target = synthetic_target("testnet", b"sup3r-secret");
2133
2134 let run = |resume_from: u64| -> (Option<String>, bool) {
2135 let (etx, erx) = crossbeam_channel::unbounded();
2136 // force_cpu: keeps the run CPU-deterministic and the real
2137 // per-SSID PMK cache untouched.
2138 let _s = spawn_crack(
2139 target.describe(),
2140 target.clone(),
2141 Attack::Wordlist(wl.clone()),
2142 resume_from,
2143 etx,
2144 true,
2145 );
2146 let mut pass = None;
2147 let deadline = std::time::Instant::now() + Duration::from_secs(60);
2148 loop {
2149 assert!(std::time::Instant::now() < deadline, "no terminator");
2150 match erx.recv_timeout(Duration::from_secs(5)) {
2151 Ok(Event::CrackFound { password }) => pass = Some(password),
2152 Ok(Event::CrackStopped { found }) => return (pass, found),
2153 Ok(Event::Error(l)) => panic!("worker error: {l}"),
2154 Ok(_) => {}
2155 Err(_) => panic!("channel silent"),
2156 }
2157 }
2158 };
2159
2160 // Resume BEFORE the target's position: found.
2161 assert_eq!(run(2), (Some("sup3r-secret".to_string()), true));
2162 // Resume past it: exhausted without a match.
2163 assert_eq!(run(3), (None, false));
2164 let _ = std::fs::remove_file(&wl);
2165 }
2166
2167 #[test]
2168 fn validate_catches_missing_files() {
2169 assert!(
2170 Attack::Wordlist(PathBuf::from("/definitely/not/here.lst"))
2171 .validate()
2172 .is_err()
2173 );
2174 assert!(
2175 Attack::Rainbow(PathBuf::from("/definitely/not/here.pmk"))
2176 .validate()
2177 .is_err()
2178 );
2179 assert!(
2180 Attack::Bruteforce {
2181 charset: b"01".to_vec(),
2182 min: 8,
2183 max: 10,
2184 freq_order: false
2185 }
2186 .validate()
2187 .is_ok()
2188 );
2189 assert!(
2190 Attack::Rules {
2191 wordlist: PathBuf::from("/definitely/not/here.lst"),
2192 rules: PathBuf::from("/definitely/not/here.rule"),
2193 }
2194 .validate()
2195 .is_err()
2196 );
2197 assert!(
2198 Attack::Hybrid {
2199 wordlist: PathBuf::from("/definitely/not/here.lst"),
2200 charset: b"01".to_vec(),
2201 min: 1,
2202 max: 2,
2203 }
2204 .validate()
2205 .is_err()
2206 );
2207 // Inverted (clamped) hybrid suffix range is refused.
2208 assert!(HybridIter::validate(b"01", 4, 1).is_err());
2209 assert!(HybridIter::validate(&[], 1, 2).is_err());
2210 }
2211
2212 #[test]
2213 fn rule_ops_golden_table() {
2214 // One row per op, plus a compound multi-op line ("c $1 $9"-style).
2215 let cases: &[(&str, &[u8], &[u8])] = &[
2216 (":", b"password1", b"password1"),
2217 ("l", b"PassWord1", b"password1"),
2218 ("u", b"PassWord1", b"PASSWORD1"),
2219 ("c", b"pASSWORD1", b"Password1"),
2220 ("C", b"Password1", b"pASSWORD1"),
2221 ("t", b"PassWord1", b"pASSwORD1"),
2222 ("r", b"password", b"drowssap"),
2223 ("d", b"password", b"passwordpassword"),
2224 ("$1", b"password", b"password1"),
2225 ("^1", b"password", b"1password"),
2226 ("[", b"password1", b"assword1"),
2227 ("]", b"password1", b"password"),
2228 ("so0", b"password05", b"passw0rd05"),
2229 // Compound: capitalize, append "1", append "!" — the classic
2230 // "Password1!" family from an 8-char base word.
2231 ("c $1 $!", b"password", b"Password1!"),
2232 ];
2233 for (rule_text, input, want) in cases {
2234 let ops = parse_rule_line(rule_text.as_bytes(), 0).unwrap();
2235 assert_eq!(
2236 apply_rule(&ops, input).as_deref(),
2237 Some(&want[..]),
2238 "rule {rule_text:?} on {input:?}"
2239 );
2240 }
2241 // Outputs outside 8..=63 are filtered (but consume the index).
2242 let ops = parse_rule_line(b"]", 0).unwrap();
2243 assert_eq!(apply_rule(&ops, b"12345678"), None); // 7 < 8
2244 let ops = parse_rule_line(b"d d d", 0).unwrap();
2245 assert_eq!(apply_rule(&ops, b"12345678901234"), None); // 14*8 = 112 > 63
2246 }
2247
2248 #[test]
2249 fn parse_rules_skips_comments_and_blanks() {
2250 let dir = std::env::temp_dir();
2251 let path = dir.join(format!("wifi_lab-rules-{}", std::process::id()));
2252 std::fs::write(&path, "# comment\n\n:\nl\n$1\n# another\nso0\n").unwrap();
2253 let rules = parse_rules(&path).unwrap();
2254 assert_eq!(rules.len(), 4);
2255 assert_eq!(rule_count(&path).unwrap(), 4);
2256 let _ = std::fs::remove_file(&path);
2257 }
2258
2259 #[test]
2260 fn rule_iter_flatten_and_resume_continuation() {
2261 // 3 words × 2 rules: flattened order is word-major / rule-minor.
2262 let words: Vec<Vec<u8>> = vec![
2263 b"password".to_vec(),
2264 b"letmein1".to_vec(),
2265 b"hunter22".to_vec(),
2266 ];
2267 let rules = std::rc::Rc::new(vec![
2268 parse_rule_line(b":", 0).unwrap(),
2269 parse_rule_line(b"$1", 0).unwrap(),
2270 ]);
2271 let collect_from = |it: &mut dyn Iterator<Item = Vec<u8>>| -> Vec<Vec<u8>> { it.collect() };
2272 let mut full = RuleIter::new(Box::new(words.clone().into_iter()), rules.clone());
2273 let got = collect_from(&mut full);
2274 assert_eq!(
2275 got,
2276 vec![
2277 b"password".to_vec(),
2278 b"password1".to_vec(),
2279 b"letmein1".to_vec(),
2280 b"letmein11".to_vec(),
2281 b"hunter22".to_vec(),
2282 b"hunter221".to_vec(),
2283 ]
2284 );
2285 // Resume: skip_n(3) must continue exactly with candidate #3.
2286 let mut resumed = RuleIter::new(Box::new(words.into_iter()), rules);
2287 skip_n(&mut resumed, 3);
2288 assert_eq!(
2289 collect_from(&mut resumed),
2290 vec![
2291 b"letmein11".to_vec(),
2292 b"hunter22".to_vec(),
2293 b"hunter221".to_vec()
2294 ]
2295 );
2296 }
2297
2298 #[test]
2299 fn hybrid_space_math_and_order() {
2300 // charset {0,1}, k in 1..=2: per-word = 2 + 4 = 6.
2301 let words: Vec<Vec<u8>> = vec![b"password".to_vec()];
2302 let mut it = HybridIter::new(Box::new(words.into_iter()), b"01".to_vec(), 1, 2).unwrap();
2303 assert_eq!(it.per_word(), 6);
2304 let got: Vec<Vec<u8>> = it.by_ref().collect();
2305 assert_eq!(
2306 got,
2307 vec![
2308 b"password0".to_vec(),
2309 b"password1".to_vec(),
2310 b"password00".to_vec(),
2311 b"password01".to_vec(),
2312 b"password10".to_vec(),
2313 b"password11".to_vec(),
2314 ],
2315 "k-blocks ascending, odometer little-endian within a block"
2316 );
2317 }
2318
2319 #[test]
2320 fn hybrid_seek_flat_continuation() {
2321 // 2 words, per_word 6: full space is 12 candidates.
2322 let words: Vec<Vec<u8>> = vec![b"password".to_vec(), b"hunter22".to_vec()];
2323 let reference: Vec<Vec<u8>> =
2324 HybridIter::new(Box::new(words.clone().into_iter()), b"ab".to_vec(), 1, 2)
2325 .unwrap()
2326 .collect();
2327 assert_eq!(reference.len(), 12);
2328 for n in [0u64, 1, 5, 6, 7, 11] {
2329 let mut it =
2330 HybridIter::new(Box::new(words.clone().into_iter()), b"ab".to_vec(), 1, 2).unwrap();
2331 it.seek_flat(n);
2332 let got: Vec<Vec<u8>> = it.collect();
2333 assert_eq!(got, reference[n as usize..], "seek_flat({n})");
2334 }
2335 // Past the end: empty.
2336 let mut it = HybridIter::new(Box::new(words.into_iter()), b"ab".to_vec(), 1, 2).unwrap();
2337 it.seek_flat(12);
2338 assert_eq!(it.next(), None);
2339 }
2340
2341 #[test]
2342 fn hybrid_skips_overlong_but_consumes_index() {
2343 // A 63-byte word + any suffix exceeds 63 → candidates filtered,
2344 // but flattened slots still consumed: seeking past the first
2345 // word's 6 slots lands at the second word's first candidate.
2346 let long_word = vec![b'x'; 63];
2347 let words: Vec<Vec<u8>> = vec![long_word.clone(), b"password".to_vec()];
2348 let mut it =
2349 HybridIter::new(Box::new(words.clone().into_iter()), b"ab".to_vec(), 1, 2).unwrap();
2350 it.seek_flat(6);
2351 assert_eq!(it.next().unwrap(), b"passworda");
2352
2353 // EXACT semantics: running through the overlong word consumes all
2354 // of its 6 slots, so the STREAM position after the run equals the
2355 // position seek_flat(6) addresses — resume can use the live
2356 // position directly, no drift.
2357 let mut run = HybridIter::new(Box::new(words.into_iter()), b"ab".to_vec(), 1, 2).unwrap();
2358 assert_eq!(run.next().unwrap(), b"passworda");
2359 assert_eq!(run.raw_pos(), 7, "six filtered slots + one yielded");
2360 let mut resumed = HybridIter::new(
2361 Box::new(vec![long_word, b"password".to_vec()].into_iter()),
2362 b"ab".to_vec(),
2363 1,
2364 2,
2365 )
2366 .unwrap();
2367 resumed.seek_flat(7);
2368 assert_eq!(resumed.next().unwrap(), b"passwordb");
2369 }
2370
2371 #[test]
2372 fn hybrid_raw_pos_exact_through_overlong_word() {
2373 // The overlong word contributes NOTHING but still consumes its
2374 // full flattened block — raw positions jump from 0 to 6 (per_word)
2375 // to 12 without any yield, then the second word emits at 6..11.
2376 let long_word = vec![b'x'; 63];
2377 let words: Vec<Vec<u8>> = vec![long_word, b"hunter22".to_vec()];
2378 let mut it = HybridIter::new(Box::new(words.into_iter()), b"ab".to_vec(), 1, 2).unwrap();
2379 let mut positions = Vec::new();
2380 let mut out = Vec::new();
2381 while let Some(c) = it.next() {
2382 positions.push(it.raw_pos());
2383 out.push(c);
2384 }
2385 assert_eq!(out.len(), 6, "only the 8-byte word yields");
2386 assert_eq!(positions, vec![7, 8, 9, 10, 11, 12]);
2387 // Resuming at each recorded raw position must continue exactly.
2388 for (i, &pos) in positions.iter().enumerate() {
2389 let words: Vec<Vec<u8>> = vec![vec![b'x'; 63], b"hunter22".to_vec()];
2390 let mut r = HybridIter::new(Box::new(words.into_iter()), b"ab".to_vec(), 1, 2).unwrap();
2391 r.seek_flat(pos);
2392 let rest: Vec<Vec<u8>> = r.collect();
2393 assert_eq!(rest, out[i + 1..], "resume at raw {pos}");
2394 }
2395 }
2396
2397 #[test]
2398 fn rule_iter_raw_pos_and_seek_flat_exact() {
2399 // Positions count filter-consumed slots; seek_flat(pos) continues
2400 // exactly where a run at raw position `pos` would.
2401 let words: Vec<Vec<u8>> = vec![b"password".to_vec(), b"letmein1".to_vec()];
2402 let rules = Rc::new(vec![
2403 parse_rule_line(b"]", 0).unwrap(), // 8-byte word → 7 bytes: FILTERED
2404 parse_rule_line(b":", 0).unwrap(),
2405 parse_rule_line(b"$!", 0).unwrap(),
2406 ]);
2407 let mut it = RuleIter::new(Box::new(words.clone().into_iter()), rules.clone());
2408 let mut seen = Vec::new();
2409 while let Some(c) = it.next() {
2410 seen.push((it.raw_pos(), c));
2411 }
2412 // 2 words × 3 rules = 6 slots; the two `]` outputs (7 bytes) are
2413 // filtered, so 4 yields at raw positions after each slot.
2414 assert_eq!(
2415 seen,
2416 vec![
2417 (2, b"password".to_vec()),
2418 (3, b"password!".to_vec()),
2419 (5, b"letmein1".to_vec()),
2420 (6, b"letmein1!".to_vec()),
2421 ]
2422 );
2423 // Resume from every recorded position plus interesting slots
2424 // (including a filtered one) continues exactly.
2425 let reference: Vec<Vec<u8>> = seen.iter().map(|(_, c)| c.clone()).collect();
2426 for start in 0..=6u64 {
2427 let mut r = RuleIter::new(Box::new(words.clone().into_iter()), rules.clone());
2428 r.seek_flat(start);
2429 let rest: Vec<Vec<u8>> = r.collect();
2430 let want: Vec<Vec<u8>> = seen
2431 .iter()
2432 .filter(|(pos, _)| *pos > start)
2433 .map(|(_, c)| c.clone())
2434 .collect();
2435 assert_eq!(rest, want, "seek_flat({start}) of {reference:?}");
2436 }
2437 }
2438
2439 #[test]
2440 fn pos_feed_progress_maps_to_raw_positions() {
2441 // Cache-covered candidates are dropped between raw stream and
2442 // backend, and the backend reports counts in POST-skip terms; the
2443 // progress translation must still yield raw positions.
2444 let words: Vec<Vec<u8>> = (0..6u8).map(|i| vec![b'0' + i; 8]).collect();
2445 let covered: HashSet<Box<[u8]>> = [
2446 vec![b'1'; 8].into_boxed_slice(),
2447 vec![b'3'; 8].into_boxed_slice(),
2448 ]
2449 .into_iter()
2450 .collect();
2451 let raw = CountIter::at(words.into_iter(), 0);
2452 let stream: Box<dyn RawPosIter> = Box::new(CacheSkipIter::new(raw, covered));
2453 let (mut feed, map) = PosFeed::new(stream);
2454 // Backend pulls its first batch (all 4 surviving candidates), then
2455 // reports progress in two chunks.
2456 let pulled: Vec<Vec<u8>> = feed.by_ref().collect();
2457 assert_eq!(pulled.len(), 4);
2458 let mut acked = 0u64;
2459 assert_eq!(raw_position_of(&map, &mut acked, 1), Some(1));
2460 assert_eq!(
2461 raw_position_of(&map, &mut acked, 2),
2462 Some(3),
2463 "skipped raw 1,2"
2464 );
2465 assert_eq!(
2466 raw_position_of(&map, &mut acked, 4),
2467 Some(6),
2468 "skipped raw 3,4"
2469 );
2470 // Map drained: every confirmed candidate consumed exactly its raw
2471 // position; resume at 6 continues past '0'..'5'.
2472 assert!(map.borrow().is_empty());
2473 // Underflow (a progress tick beyond recorded yields) is a no-op.
2474 assert_eq!(raw_position_of(&map, &mut acked, 5), None);
2475 }
2476
2477 #[test]
2478 fn gpu_pmk_batch_tail_is_computed() {
2479 // Fake kernel: succeeds only with a PREFIX — first call returns
2480 // half, subsequent calls again shorter prefixes — the loop must
2481 // keep asking until every word has its PMK.
2482 let batch: Vec<Vec<u8>> = (0..5u8).map(|i| vec![b'a' + i; 8]).collect();
2483 let salt = b"testnet";
2484 let mut calls = 0usize;
2485 let pmks = gpu_pmk_batch_full(
2486 &mut |slice: &[Vec<u8>]| {
2487 calls += 1;
2488 let n = if slice.len() == 1 { 1 } else { slice.len() / 2 };
2489 Ok(slice[..n].iter().map(|w| crypto::pmk(w, salt)).collect())
2490 },
2491 &batch,
2492 )
2493 .unwrap();
2494 assert_eq!(pmks.len(), batch.len(), "tail words must not vanish");
2495 for (pmk, w) in pmks.iter().zip(batch.iter()) {
2496 assert_eq!(pmk, &crypto::pmk(w, salt));
2497 }
2498 assert!(
2499 calls >= 4,
2500 "prefix returns force several tail calls ({calls})"
2501 );
2502 }
2503
2504 #[test]
2505 fn gpu_pmk_batch_err_propagates_and_empty_aborts() {
2506 let batch: Vec<Vec<u8>> = vec![b"password1".to_vec(), b"password2".to_vec()];
2507 let err = gpu_pmk_batch_full(&mut |_| Err(gpu::GpuError::Lost), &batch).unwrap_err();
2508 assert_eq!(err, gpu::GpuError::Lost);
2509 // A zero-PMK Ok would spin forever without the guard.
2510 let err = gpu_pmk_batch_full(&mut |_| Ok(Vec::new()), &batch).unwrap_err();
2511 assert!(matches!(err, gpu::GpuError::Unsupported(_)));
2512 }
2513
2514 #[test]
2515 fn spawn_crack_worker_panic_becomes_crack_error() {
2516 // An invalid attack that BYPASSES validate() (empty hybrid
2517 // charset) panics inside the worker at the `.expect("validated")`
2518 // — the terminator must be CrackError, not a fake "exhausted".
2519 let target = synthetic_target("testnet", b"sup3r-secret");
2520 let wl = std::env::temp_dir().join(format!("wifi_lab-panic-wl-{}", std::process::id()));
2521 std::fs::write(&wl, "whatever1\n").unwrap();
2522 let (etx, erx) = crossbeam_channel::unbounded();
2523 let _stop = spawn_crack(
2524 "test".to_string(),
2525 target,
2526 Attack::Hybrid {
2527 wordlist: wl.clone(),
2528 charset: Vec::new(),
2529 min: 1,
2530 max: 2,
2531 },
2532 0,
2533 etx,
2534 true,
2535 );
2536 let deadline = std::time::Instant::now() + Duration::from_secs(30);
2537 let got_error = loop {
2538 assert!(
2539 std::time::Instant::now() < deadline,
2540 "no terminator after worker panic"
2541 );
2542 match erx.recv_timeout(Duration::from_secs(5)) {
2543 Ok(Event::CrackError { reason }) => break reason,
2544 Ok(Event::CrackStopped { found }) => {
2545 panic!("panic was mis-reported as CrackStopped {{ found: {found} }}")
2546 }
2547 Ok(Event::Error(_)) => {} // the panic's log line
2548 Ok(_) => {}
2549 Err(_) => panic!("channel silent — no terminator"),
2550 }
2551 };
2552 assert!(got_error.contains("panicked"));
2553 let _ = std::fs::remove_file(&wl);
2554 }
2555
2556 #[test]
2557 fn rainbow_resume_position_exact() {
2558 // Build a 3-entry table, resume at 1 and at 3: the position is a
2559 // raw entry index — 1 finds the planted pass, 3 exhausts.
2560 let dir = std::env::temp_dir();
2561 let wl = dir.join(format!("wifi_lab-rbresume-wl-{}", std::process::id()));
2562 let tbl = dir.join(format!("wifi_lab-rbresume-tbl-{}", std::process::id()));
2563 std::fs::write(&wl, "wrong-pass1\nsup3r-secret\nwrong-pass2\n").unwrap();
2564 let (etx, _erx) = crossbeam_channel::unbounded();
2565 let stop = Arc::new(AtomicBool::new(false));
2566 assert_eq!(build_table("testnet", &wl, &tbl, &etx, &stop), 3);
2567
2568 let target = synthetic_target("testnet", b"sup3r-secret");
2569 let run = |resume_from: u64| -> (Option<String>, bool) {
2570 let (etx, erx) = crossbeam_channel::unbounded();
2571 let _s = spawn_crack(
2572 target.describe(),
2573 target.clone(),
2574 Attack::Rainbow(tbl.clone()),
2575 resume_from,
2576 etx,
2577 true,
2578 );
2579 let mut pass = None;
2580 let deadline = std::time::Instant::now() + Duration::from_secs(60);
2581 loop {
2582 assert!(std::time::Instant::now() < deadline, "no terminator");
2583 match erx.recv_timeout(Duration::from_secs(5)) {
2584 Ok(Event::CrackFound { password }) => pass = Some(password),
2585 Ok(Event::CrackStopped { found }) => return (pass, found),
2586 Ok(Event::CrackError { reason }) => panic!("backend error: {reason}"),
2587 Ok(Event::Error(l)) => panic!("worker error: {l}"),
2588 Ok(_) => {}
2589 Err(_) => panic!("channel silent"),
2590 }
2591 }
2592 };
2593 assert_eq!(run(1), (Some("sup3r-secret".to_string()), true));
2594 assert_eq!(run(3), (None, false));
2595 let _ = std::fs::remove_file(&wl);
2596 let _ = std::fs::remove_file(&tbl);
2597 }
2598
2599 #[test]
2600 fn resume_progress_reports_raw_positions() {
2601 // End-to-end position semantics at the event level: a resumed
2602 // wordlist run reports progress as RAW stream positions — the
2603 // first tick after a resume at 1 with a 512-item CPU batch is raw
2604 // 513 (1 + 512 confirmed), not the old post-filter yield count.
2605 let dir = std::env::temp_dir();
2606 let wl = dir.join(format!("wifi_lab-rawpos-wl-{}", std::process::id()));
2607 let mut lines: Vec<String> = (0..700).map(|i| format!("filler-{i:04}")).collect();
2608 lines[650] = "sup3r-secret".to_string();
2609 std::fs::write(&wl, lines.join("\n") + "\n").unwrap();
2610 // A test-unique SSID keeps the real per-SSID PMK cache out of the
2611 // run (consult proceeds straight to a miss).
2612 let target = synthetic_target("rawpos-test-ssid", b"sup3r-secret");
2613 let (etx, erx) = crossbeam_channel::unbounded();
2614 let _s = spawn_crack(
2615 target.describe(),
2616 target,
2617 Attack::Wordlist(wl.clone()),
2618 1,
2619 etx,
2620 true,
2621 );
2622 let mut positions = Vec::new();
2623 let mut found = false;
2624 let deadline = std::time::Instant::now() + Duration::from_secs(120);
2625 loop {
2626 assert!(std::time::Instant::now() < deadline, "no terminator");
2627 match erx.recv_timeout(Duration::from_secs(30)) {
2628 Ok(Event::CrackProgress { done, .. }) => positions.push(done),
2629 Ok(Event::CrackFound { password }) => {
2630 assert_eq!(password, "sup3r-secret");
2631 found = true;
2632 }
2633 Ok(Event::CrackStopped { found: true }) => break,
2634 Ok(Event::CrackError { reason }) => panic!("backend error: {reason}"),
2635 Ok(Event::Error(l)) => panic!("worker error: {l}"),
2636 Ok(_) => {}
2637 Err(_) => panic!("channel silent"),
2638 }
2639 }
2640 assert!(found);
2641 // Resume(1) + first full batch of 512 confirmed = raw 513; then
2642 // the find short-circuits batch 2 before its tick.
2643 assert_eq!(positions, vec![513]);
2644 let _ = std::fs::remove_file(&wl);
2645 }
2646
2647 #[test]
2648 fn freq_order_puts_common_first_and_seeks() {
2649 // Charset with members ranked differently in FREQ_ORDER: 'e'
2650 // (rank 0) precedes 'z' (absent→end) regardless of input order.
2651 let bf = BruteForce::new(b"ze".to_vec(), 8, 8, true).unwrap();
2652 let first: Vec<Vec<u8>> = bf.take(4).collect();
2653 assert_eq!(first[0], b"eeeeeeee");
2654 assert_eq!(first[1], b"eeeeeeez");
2655 assert_eq!(first[2], b"eeeeeeze");
2656 assert_eq!(first[3], b"eeeeeezz");
2657 // Sanitizer: the space is still a bijection (size + seek match
2658 // the lexicographic construction).
2659 let freq: Vec<Vec<u8>> = BruteForce::new(b"wze1".to_vec(), 8, 8, true)
2660 .unwrap()
2661 .collect();
2662 let mut plain: Vec<Vec<u8>> = BruteForce::new(b"wze1".to_vec(), 8, 8, false)
2663 .unwrap()
2664 .collect();
2665 plain.sort();
2666 let mut freq_sorted = freq.clone();
2667 freq_sorted.sort();
2668 assert_eq!(plain, freq_sorted, "freq_order must be a permutation");
2669 // seek(n) then iterate == skip n from start.
2670 for n in [0u64, 3, 255] {
2671 let mut s = BruteForce::new(b"wze1".to_vec(), 8, 8, true).unwrap();
2672 s.seek(n);
2673 let got: Vec<Vec<u8>> = s.by_ref().take(3).collect();
2674 assert_eq!(
2675 got,
2676 freq[n as usize..(n as usize + 3).min(freq.len())],
2677 "seek({n})"
2678 );
2679 }
2680 }
2681
2682 #[test]
2683 fn cache_skip_iter_filters_covered() {
2684 let words: Vec<Vec<u8>> = vec![
2685 b"password".to_vec(),
2686 b"letmein1".to_vec(),
2687 b"hunter22".to_vec(),
2688 ];
2689 let covered: HashSet<Box<[u8]>> =
2690 [b"letmein1".as_slice().into(), b"hunter22".as_slice().into()]
2691 .into_iter()
2692 .collect();
2693 let it = CacheSkipIter::new(words.into_iter(), covered);
2694 assert_eq!(it.collect::<Vec<_>>(), vec![b"password".to_vec()]);
2695 // Empty coverage = pass-through.
2696 let words2: Vec<Vec<u8>> = vec![b"password".to_vec()];
2697 let it2 = CacheSkipIter::new(words2.into_iter(), HashSet::new());
2698 assert_eq!(it2.count(), 1);
2699 }
2700
2701 #[test]
2702 fn benchmark_cpu_half_returns_positive_hps() {
2703 // A ~0.1 s micro-run MUST return a positive throughput number
2704 // without needing a GPU.
2705 let hps = bench_cpu(0.1, None);
2706 assert!(hps > 0.0, "cpu benchmark returned {hps}");
2707 }
2708
2709 #[test]
2710 fn spawn_benchmark_terminates_with_benchmark_done() {
2711 // Contract: exactly one BenchmarkDone terminator arrives. A GPU
2712 // adapter (when present) may need a while for the first dispatch,
2713 // so wait generously before declaring a hang.
2714 let (tx, rx) = crossbeam_channel::unbounded();
2715 let stop = spawn_benchmark(1, tx);
2716 let deadline = Instant::now() + Duration::from_secs(120);
2717 let mut done_seen = false;
2718 while Instant::now() < deadline {
2719 match rx.recv_timeout(deadline.duration_since(Instant::now())) {
2720 Ok(Event::BenchmarkDone { cpu_hps, .. }) => {
2721 assert!(cpu_hps > 0.0);
2722 done_seen = true;
2723 break;
2724 }
2725 Ok(Event::Error(e)) => panic!("benchmark error: {e}"),
2726 Ok(_) => {} // Log line
2727 Err(_) => break,
2728 }
2729 }
2730 assert!(done_seen, "no BenchmarkDone within 120 s");
2731 drop(stop);
2732 }
2733}