Extend contract — additive wire format, correlation/import/benchmark events
Browse files at this commit62d713b070979a117d403f4cb1889a1a7ef64300Parent: 60df998- docs
- extend contract — additive wire format, correlation/import/benchmark events
1 changed file +459 -23
- docs/CONTRACT.md +459 -23
docs/CONTRACT.mdmodified+459 -23
| @@ -1,12 +1,47 @@ | ||
| 1 | 1 | # wifilab — module contract |
| 2 | 2 | |
| 3 | 3 | Single bin crate `wifilab`. All modules live flat under `src/`. Shared domain |
| 4 | -types are in `src/common.rs` (MacAddr, Security, AccessPoint, ClientInfo, | |
| 5 | -HandshakeCapture, PmkidCapture, Event, channel lists). These are FIXED. | |
| 4 | +types are in `src/common.rs` (MacAddr, Security, Akm, AccessPoint, ClientInfo, | |
| 5 | +HandshakeCapture, PmkidCapture, ChannelStat, ProbeInfo, ImportedCapture, | |
| 6 | +Event, Cmd, channel lists). The wire format evolves ADDITIVELY ONLY: new enum | |
| 7 | +variants may be appended (externally-tagged serde, ordering free) and new | |
| 8 | +struct/enum fields must carry `#[serde(default)]` so older records | |
| 9 | +deserialize losslessly (precedent: `ClientInfo.connected`, | |
| 10 | +`Cmd::StartScan.spool`/`fresh_spool`, `AccessPoint.akms`). Never rename, | |
| 11 | +remove, or change the meaning of existing variants/fields. | |
| 12 | + | |
| 13 | +## imported-capture (common.rs) | |
| 14 | +`Event::CaptureImported(ImportedCapture)` carries a capture recovered from an | |
| 15 | +external file (pcap/hc22000 import): `ImportedCapture::Handshake(Box< | |
| 16 | +HandshakeCapture>) | Pmkid(PmkidCapture)`. `store::StoredCapture` stays in | |
| 17 | +store.rs (common must not depend on store); the UI converts at the boundary. | |
| 18 | +Other wire additions: `Event::ChannelStats(Vec<ChannelStat>)` (cumulative | |
| 19 | +per-channel frame/beacon counters), `Event::ProbeObserved(ProbeInfo)` (novel | |
| 20 | +probe request), `Event::DeauthAlert { source, target, count }` (≥10 deauths | |
| 21 | +per (src,dst) pair per 10 s from a source we did not cause), | |
| 22 | +`Event::BenchmarkDone { gpu_hps: Option<f64>, cpu_hps: f64 }`, and | |
| 23 | +`Cmd::DeauthAll { ap, channel, targets, count }` (pin `channel`, blast | |
| 24 | +`count` rounds at each target then one broadcast blast). | |
| 25 | +`AccessPoint.akms` lists the RSN/WPA AKM suites (empty = unknown; deduped | |
| 26 | +in first-seen order); `Akm` labels: Psk→"PSK", Sae→"SAE", Owe→"OWE", | |
| 27 | +FtPsk→"FT-PSK", PskSha256→"PSK-SHA256", OneX→"802.1X", Other(_)→"other". | |
| 28 | + | |
| 29 | +## device-correlation (common.rs) | |
| 30 | +`Event::ClientIdent { mac, group, confidence }`: `mac` was correlated by | |
| 31 | +the scanner into device group `group` (u64, 1-based, process-lifetime | |
| 32 | +stable) — the MAC-randomization pairing: all MACs witnessed on one physical | |
| 33 | +radio share the group id. `IdentConfidence` = `Probable` ("?": ordered-IE | |
| 34 | +fingerprint match only) < `Strong` ("~": fingerprint + shared probed SSID | |
| 35 | +or uninterrupted 802.11 sequence numbers) < `Exact` ("=": WPS UUID-E | |
| 36 | +match). Emitted once per pairing decision (first assignment, or re-entry | |
| 37 | +after the 15-minute scanner-side group TTL). `ClientInfo` gains | |
| 38 | +`ident_group`/`ident_conf` (serde-default mirrors of the last decision). | |
| 6 | 39 | |
| 7 | 40 | Everything must compile with `cargo check` on stable Rust 1.99, edition 2024. |
| 8 | 41 | Errors: `anyhow::Result` at module boundaries. No new dependencies beyond |
| 9 | -`Cargo.toml`. No `unsafe` outside `rawsock.rs`. | |
| 42 | +`Cargo.toml` (which already includes `notify-rust` for the desktop | |
| 43 | +notification on password found — best-effort, headless/no-D-Bus drops the | |
| 44 | +error). No `unsafe` outside `rawsock.rs`. | |
| 10 | 45 | |
| 11 | 46 | ## radiotap.rs (owner: radio-core) |
| 12 | 47 | Zero-copy radiotap parser + TX injection header. |
| @@ -38,11 +73,36 @@ pub struct MgmtInfo { | ||
| 38 | 73 | pub ssid: Option<String>, // None if hidden/zero-len |
| 39 | 74 | pub channel: Option<u8>, // DS parameter set IE |
| 40 | 75 | pub security: Security, // from RSN/WPA IEs + capability privacy bit |
| 76 | + pub akms: Vec<Akm>, // AKM suites from RSN/WPA IE; empty for open/WEP | |
| 41 | 77 | } |
| 42 | 78 | /// Parse beacon OR probe-response; None for other/broken frames. |
| 43 | 79 | pub fn parse_beacon_or_probe(f: &[u8]) -> Option<MgmtInfo>; |
| 44 | 80 | /// Parse probe-request → Some(ssid of probe) — used to discover clients. |
| 45 | 81 | pub fn parse_probe_req(f: &[u8]) -> Option<(MacAddr /*sta*/, Option<String>)>; |
| 82 | +/// Association/reassociation request → (station, bssid, ssid). | |
| 83 | +/// ssid None for hidden (empty / NUL-padded SSID IE). Subtype 0 = assoc, | |
| 84 | +/// subtype 1 = reassoc. | |
| 85 | +pub fn parse_assoc_req(f: &[u8]) -> Option<(MacAddr, MacAddr, Option<String>)>; | |
| 86 | + | |
| 87 | +// -- device correlation (MAC-randomization pairing; scanner.rs::GroupBook | |
| 88 | +// consumes these, one event per frame, scanner decides identity) ------- | |
| 89 | +/// 12-bit per-transmitter sequence number (bytes 22-24, seq<<4|frag). | |
| 90 | +pub fn seq_of(f: &[u8]) -> Option<u16>; | |
| 91 | +/// Ordered-IE fingerprint: FNV-1a over (tag,len) pairs + full rate-tag | |
| 92 | +/// payloads + vendor-IE OUI+type tuples. The SSID tag's LENGTH is excluded | |
| 93 | +/// (directed vs wildcard probes of one radio must hash equal). | |
| 94 | +pub fn ie_fingerprint(f: &[u8], ie_off: usize) -> Option<u32>; | |
| 95 | +/// WPS UUID-E (vendor IE 00:50:f2:04, attribute 0x1047) if present. | |
| 96 | +pub fn wps_uuid_e(f: &[u8], ie_off: usize) -> Option<[u8; 16]>; | |
| 97 | + | |
| 98 | +pub struct ProbeIdent { pub sta: MacAddr, pub ssid: Option<String>, pub fingerprint: u32, pub uuid: Option<[u8; 16]> } | |
| 99 | +pub struct AssocIdent { pub sta: MacAddr, pub bssid: MacAddr, pub ssid: Option<String>, pub fingerprint: u32, pub uuid: Option<[u8; 16]> } | |
| 100 | +/// Probe request with correlation material; None when the IE chain can't | |
| 101 | +/// be fingerprinted (or it's not a probe request). IEs walk from 24. | |
| 102 | +pub fn parse_probe_ident(f: &[u8]) -> Option<ProbeIdent>; | |
| 103 | +/// Assoc/reassoc with correlation material (same offsets as | |
| 104 | +/// `parse_assoc_req`). Hidden/NUL-padded SSID → None. | |
| 105 | +pub fn parse_assoc_ident(f: &[u8]) -> Option<AssocIdent>; | |
| 46 | 106 | /// Parse deauth/disassoc → (from-ap MacAddr as transmitter, target addr1). |
| 47 | 107 | pub fn parse_deauth(f: &[u8]) -> Option<(MacAddr, MacAddr)>; |
| 48 | 108 | /// Extract (bssid, station) that best describes a data frame's endpoints |
| @@ -80,6 +140,33 @@ Sequence control may be left 0. Duration 314. FCS omitted (driver appends). | ||
| 80 | 140 | Unit tests must cover parse↔build roundtrips and the classic 4way M1..M4 flag |
| 81 | 141 | matrices. |
| 82 | 142 | |
| 143 | +AKM parsing (`MgmtInfo.akms`): in the RSN IE body the AKM suite list sits at | |
| 144 | +`8 + 4×pairwise_count` (after version(2) group(4) pairwise_cnt(2) | |
| 145 | +pairwise[4n] akm_cnt(2)); each suite is OUI 00:0f:ac + type byte. Only the | |
| 146 | +type byte is inspected: | |
| 147 | + | |
| 148 | +| type | Akm | label | | |
| 149 | +|------|---------------|--------------| | |
| 150 | +| 1 | `OneX` | 802.1X | | |
| 151 | +| 2 | `Psk` | PSK | | |
| 152 | +| 4 | `FtPsk` | FT-PSK | | |
| 153 | +| 6 | `PskSha256` | PSK-SHA256 | | |
| 154 | +| 8 | `Sae` | SAE | | |
| 155 | +| 18 | `Owe` | OWE | | |
| 156 | +| any other | `Other(t)` | other | | |
| 157 | + | |
| 158 | +The vendor WPA IE (tag 221, OUI+type 00:50:f2:01) implies WPA1, which only | |
| 159 | +ever used PSK key management, so a single `Akm::Psk` is pushed. The | |
| 160 | +`Security` label (WPA3 iff SAE present) is independent of this list. The | |
| 161 | +final list is DEDUPED (first-seen order kept): a mixed WPA+WPA2 AP must | |
| 162 | +not surface `PSK+PSK`. | |
| 163 | + | |
| 164 | +`parse_assoc_req` frame offsets (receivers check `f.len() < ie_off` first): | |
| 165 | +addr1 (bssid) at 4, addr2 (station) at 10; fixed params capability(2) + | |
| 166 | +listen interval(2) at 24; IEs walk from 28 for subtype 0, from 34 for | |
| 167 | +subtype 1 (reassoc inserts the 6-byte current-AP address). SSID IE (tag 0) | |
| 168 | +is taken if non-empty and not NUL-padded. | |
| 169 | + | |
| 83 | 170 | ## rawsock.rs (owner: radio-core) |
| 84 | 171 | Only module allowed to use `unsafe` (libc AF_PACKET). |
| 85 | 172 | |
| @@ -110,26 +197,136 @@ pub fn to_managed(ifname: &str) -> anyhow::Result<()>; | ||
| 110 | 197 | pub fn set_channel(ifname: &str, ch: u8) -> anyhow::Result<()>; |
| 111 | 198 | /// Parse `iw dev` for the current channel; Err if not determinable. |
| 112 | 199 | pub fn current_channel(ifname: &str) -> anyhow::Result<u8>; |
| 200 | +/// Reload the driver bound to ifname's device (mt76 monitor-TX wedge | |
| 201 | +/// recovery); waits for re-enumeration, leaves the managed vif DOWN. | |
| 202 | +/// Destroys ALL vifs on the phy — recreate the monitor vif afterwards. | |
| 203 | +pub fn reset_driver(ifname: &str) -> anyhow::Result<()>; | |
| 113 | 204 | /// Wireless interfaces present (from /sys/class/net/*/wireless). |
| 114 | 205 | pub fn list_wifi_ifaces() -> Vec<String>; |
| 115 | 206 | /// Our own MAC on ifname. |
| 116 | 207 | pub fn mac_of(ifname: &str) -> anyhow::Result<crate::common::MacAddr>; |
| 117 | 208 | /// True when running with euid 0; UI surfaces a warning otherwise. |
| 118 | 209 | pub fn is_root() -> bool; |
| 210 | +/// Stop NetworkManager (systemctl stop). Requires root. | |
| 211 | +pub fn stop_networkmanager() -> anyhow::Result<()>; | |
| 212 | +/// Start NetworkManager again (systemctl start); best-effort restore on exit. | |
| 213 | +pub fn start_networkmanager() -> anyhow::Result<()>; | |
| 214 | +/// True when the monitor vif `<ifname>mon` no longer exists (post-scan | |
| 215 | +/// restore check: remaining monitor vif → interface left in monitor mode). | |
| 216 | +pub fn monitor_gone(ifname: &str) -> bool; | |
| 119 | 217 | // note: NetworkManager/wpa_supplicant interference is the caller's concern; |
| 120 | 218 | // expose `kill_interferers()` that runs NM radio off like airmon does NOT — |
| 121 | 219 | // instead just document required state. |
| 122 | 220 | ``` |
| 123 | 221 | |
| 222 | +## oui.rs (owner: ui) | |
| 223 | +MAC prefix → vendor lookup backed by CHECKED-IN snapshot files, one line | |
| 224 | +per entry: `HEX|Vendor` (uppercase hex prefix, `|`, vendor name truncated | |
| 225 | +to 32 chars; sorted ascending LC_ALL=C byte order, deduplicated BY PREFIX — | |
| 226 | +first vendor wins for historical re-registrations, e.g. 0001C8, 080030): | |
| 227 | +- `src/data/oui.txt` — MA-L 24-bit (6 hex chars), IEEE MA-L registry | |
| 228 | + (`https://standards-oui.ieee.org/oui/oui.txt`, lines `XX-XX-XX (hex)`) | |
| 229 | +- `src/data/oui28.txt` — MA-M 28-bit (7 hex chars), IEEE MA-M registry | |
| 230 | + (`.../oui28/mam.txt`: base `XX-XX-XX (hex)` line + `(base 16)` range | |
| 231 | + line; key = base<<4 | range-top-nibble) | |
| 232 | +- `src/data/oui36.txt` — MA-S 36-bit (9 hex chars), IEEE MA-S registry | |
| 233 | + (`.../oui36/oui36.txt`, same pairing; key = base<<12 | range-top-12-bits) | |
| 234 | +Refresh by re-downloading and re-normalizing, never hand-edit rows. | |
| 235 | +Lookup is LONGEST-PREFIX-FIRST (MA-S → MA-M → MA-L): the sub-assignment | |
| 236 | +vendors sit under someone else's MA-L base, so specificity wins. Files are | |
| 237 | +compile-time data: `include_str!` + parsed once into sorted `LazyLock` | |
| 238 | +vecs, binary-searched — the binary | |
| 239 | +has no network or runtime-file dependency for lookups, and vendor strings | |
| 240 | +reflect the snapshot date, not live registrations. | |
| 241 | + | |
| 242 | +```rust | |
| 243 | +/// Locally administered = first-byte U/L bit set (mac.0[0] & 0x02): the | |
| 244 | +/// randomized/rotated MACs modern stations send. These have no IEEE vendor; | |
| 245 | +/// the UI shows them as "random", not "unknown". | |
| 246 | +pub fn is_locally_administered(mac: &crate::common::MacAddr) -> bool; | |
| 247 | +/// Vendor for a MAC's prefix (longest-first MA-S → MA-M → MA-L); None for | |
| 248 | +/// locally-administered or unknown prefixes. | |
| 249 | +pub fn lookup(mac: &crate::common::MacAddr) -> Option<&'static str>; | |
| 250 | +``` | |
| 251 | + | |
| 124 | 252 | ## scanner.rs (owner: attacks) |
| 125 | 253 | ```rust |
| 126 | -pub struct ScannerConfig { pub ifname: String, pub channels: Vec<u8>, pub dwell_ms: u32, pub rssi_floor: i8 } | |
| 254 | +pub struct ScannerConfig { | |
| 255 | + pub ifname: String, pub freqs: Vec<u16>, pub dwell_ms: u32, pub rssi_floor: i8, | |
| 256 | + pub pin: std::sync::Arc<crate::iface::ChannelPin>, | |
| 257 | + /// Monitor interface's own MAC — deauth TX never trips the storm detector. | |
| 258 | + pub own_mac: crate::common::MacAddr, | |
| 259 | + /// BSSIDs of APs being user-deauthed right now (suppressed like own_mac). | |
| 260 | + pub deauth_suppress: std::sync::Arc<std::sync::Mutex<std::collections::HashSet<crate::common::MacAddr>>>, | |
| 261 | + /// Shared pcap spool writer (linktype 127; raw frames WITH radiotap header). | |
| 262 | + pub spool: Option<std::sync::Arc<std::sync::Mutex<crate::pcapout::PcapWriter>>>, | |
| 263 | +} | |
| 127 | 264 | /// Blocking channel-hop passive scan. Sends Event::{ApUpdated,ApLost, |
| 128 | -/// ClientUpdated,Log} into `tx`; returns when `stop` flips true. | |
| 265 | +/// ClientUpdated,ChannelStats,ProbeObserved,DeauthAlert,Log} into `tx`; | |
| 266 | +/// returns when `stop` flips true. | |
| 129 | 267 | pub fn run(cfg: ScannerConfig, tx: crossbeam_channel::Sender<Event>, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) -> anyhow::Result<()>; |
| 130 | 268 | ``` |
| 131 | 269 | APs expire (ApLost) after 30 s silent; clients after 60 s. Clients learned |
| 132 | -from data frames + probe requests. Deduplicate by BSSID; keep best RSSI. | |
| 270 | +from data frames + probe requests; an observed deauth/disassoc flags the | |
| 271 | +target `connected=false` (any later frame flips it back). Deduplicate by | |
| 272 | +BSSID; keep best RSSI. | |
| 273 | + | |
| 274 | +New SCANNER behaviors (W2): | |
| 275 | +- **Channel stats**: cumulative per-channel `(frames, beacons)` histogram, | |
| 276 | + attributed by radiotap carrier freq (fallback: last-tuned freq), emitted | |
| 277 | + as ONE `Event::ChannelStats` every 2 s. | |
| 278 | +- **Probe panel**: novel (client, ssid) probe requests emit | |
| 279 | + `Event::ProbeObserved`; repeats within 60 s are deduped (state reaped on | |
| 280 | + the expire pass). | |
| 281 | +- **Hidden SSID / AKM**: assoc/reassoc-req frames (`dot11::parse_assoc_req`) | |
| 282 | + bind client→AP AND fill in an AP's empty ssid (emit-on-change ApUpdated); | |
| 283 | + beacon/probe-resp `MgmtInfo.akms` populate `AccessPoint.akms` (changes are | |
| 284 | + emit-on-change too). | |
| 285 | +- **Device correlation (MAC-randomization pairing)**: probe/assoc frames | |
| 286 | + feed `GroupBook` (fingerprint + WPS UUID-E + probed-SSID set + sequence | |
| 287 | + numbers — the same frame's `dot11::parse_probe_ident`/`parse_assoc_ident` | |
| 288 | + + `seq_of` products). One `Event::ClientIdent { mac, group, confidence }` | |
| 289 | + per pairing decision; groups live 15 min (outliving the 60 s client-row | |
| 290 | + TTL so a rotated MAC that appears after the old row expired still lands | |
| 291 | + in the same group). Key witness rules: UUID-E equal → Exact; fingerprint | |
| 292 | + + shared probed SSID or seq continuation (delta 1..=32 within the 12-bit | |
| 293 | + wrap) → Strong; fingerprint alone → Probable; fingerprint mismatch → | |
| 294 | + never paired (except via UUID-E, which is matched before fingerprints so | |
| 295 | + it survives a chain change). A MAC joins at most one live group and | |
| 296 | + groups never merge post-hoc: a later-arriving bridge fingerprint does | |
| 297 | + not rejoin groups that split early. Pairing runs BEFORE client creation | |
| 298 | + so the creation event already carries `ident_group`/`ident_conf`. | |
| 299 | +- **Foreign-deauth detection**: ≥10 deauth/disassoc frames per | |
| 300 | + (source, target) pair within a 10 s sliding window → one | |
| 301 | + `Event::DeauthAlert`, then a 30 s per-pair cooldown. Frames sourced from | |
| 302 | + `own_mac` or a BSSID in `deauth_suppress` (our own blasts carry the | |
| 303 | + victim AP as transmitter) never count. Window logic is the pure | |
| 304 | + `pub(crate) fn deauth_alert(&mut VecDeque<u64>, now)`. | |
| 305 | +- **Pcap spool**: when `cfg.spool` is set, every raw frame straight off the | |
| 306 | + socket (radiotap included, linktype 127) is appended via the shared | |
| 307 | + writer. The service (service.rs) picks the writer on `Cmd::StartScan`: | |
| 308 | + `fresh_spool` → `pcapout::create` (truncate), else a NEW path → | |
| 309 | + `pcapout::from_path_append`; same path + non-fresh REUSES the open | |
| 310 | + writer. Open failure → one error log, scan runs spool-less. At runtime, | |
| 311 | + 3 consecutive append errors → one `Event::Log("pcap spool disabled: …")` | |
| 312 | + and the spool is latched off for that scan. | |
| 313 | + | |
| 314 | +Service-side `start_scan` runs an injection CANARY (wildcard probes → | |
| 315 | +expect probe responses) before spawning workers: mt76/mt7921e wedges its | |
| 316 | +monitor-TX path silently (send() succeeds, RX healthy, nothing radiates); | |
| 317 | +on failure the service reloads the driver via `iface::reset_driver` and | |
| 318 | +recreates the monitor vif, logging loudly either way. The UI additionally | |
| 319 | +marks deauth targets down optimistically (monitor TX never loops back to | |
| 320 | +the scanner socket) and sweeps client rows silent > 60 s as a backstop for | |
| 321 | +scanner restarts. | |
| 322 | + | |
| 323 | +Service exit hygiene (W2): `Cmd::Deauth`/`Cmd::DeauthAll` workers register | |
| 324 | +their victim BSSIDs in `deauth_suppress` for their lifetime (scanner storm | |
| 325 | +detector suppression). `Cmd::StopNetworkManager` sets a flag; `stop_scan` | |
| 326 | +(and thus the shutdown tail) runs the restore-check — a surviving | |
| 327 | +`<if>mon` vif yields `Event::Error` with the exact `iw dev <if>mon del` | |
| 328 | +fix — and best-effort restarts NetworkManager (`Event::Log` on success) | |
| 329 | +when that flag is set. | |
| 133 | 330 | |
| 134 | 331 | ## handshake.rs (owner: attacks) |
| 135 | 332 | 4-way tracker + hc22000/hashcat-22000 export. |
| @@ -159,9 +356,11 @@ AP-less ESSID unknown → skip capture (cannot crack without salt). | ||
| 159 | 356 | /// Send `count` deauth frames ap→target and target→ap (both directions), |
| 160 | 357 | /// rate-limited to ~64 pps, plus Event::DeauthSent every 32 frames. |
| 161 | 358 | /// If target is BROADCAST: broadcast deauth from AP side only. |
| 359 | +/// `stop` is checked per round and breaks the blast cleanly. | |
| 162 | 360 | /// Returns frames actually sent. |
| 163 | 361 | pub fn blast(sock: &RawSocket, ap: &MacAddr, target: &MacAddr, |
| 164 | - count: u32, tx: &crossbeam_channel::Sender<Event>) -> anyhow::Result<u64>; | |
| 362 | + count: u32, tx: &crossbeam_channel::Sender<Event>, | |
| 363 | + stop: &std::sync::atomic::AtomicBool) -> anyhow::Result<u64>; | |
| 165 | 364 | pub const REASON_UNSPECIFIED: u16 = 1; |
| 166 | 365 | pub const REASON_CLASS2: u16 = 6; |
| 167 | 366 | pub const REASON_CLASS3: u16 = 7; |
| @@ -200,7 +399,30 @@ export→parse→verify == true. | ||
| 200 | 399 | |
| 201 | 400 | ## gpu.rs + pbkdf2.wgsl (owner: cracker) |
| 202 | 401 | wgpu compute cracker. Must run on Vulkan (radv) headless, fall back to CPU |
| 203 | -(on `GpuCracker::try_new() -> Option`). | |
| 402 | +(on `GpuCracker::try_new() -> Option`). FULL-PIPELINE kernel: the shader | |
| 403 | +does per candidate the HMAC key midstates (2 compressions), U1/U2 from | |
| 404 | +host-precomputed padded salt messages, the 4095-iteration chained HMAC | |
| 405 | +loop (registers only), and the verify EPILOGUE on-device (PTK-KCK HMAC + | |
| 406 | +EAPOL MIC compare, or PMKID compare — everything SHA1-family). The host | |
| 407 | +packs raw candidate bytes only (BE u32 words ×16) and reads back a | |
| 408 | +16-byte hit slot per batch — midstate upload + CPU MIC phases were the | |
| 409 | +pipeline's throughput ceiling (effective had run at ~1/3 of kernel-only). | |
| 410 | +Verify messages arrive PRE-PADDED in params (constant per run; padding | |
| 411 | +follows the implicit 64-byte HMAC pad prefix, bitlen = (64+len)*8). | |
| 412 | +Targets with AES-CMAC MIC (key_ver 3), frames < 99 B, or ESSIDs > 51 B | |
| 413 | +are NOT expressible in the shader: `gpu_verifiable()` routes them to | |
| 414 | +cpu_crack even when a GPU adapter exists (attack.rs). Fast path: | |
| 415 | +`create_shader_module_trusted(..., ShaderRuntimeChecks::unchecked())` | |
| 416 | +(static module; the tail guard `idx >= params.n` clamps partial batches). | |
| 417 | +Dispatch buffers + bind group live in a persistent 2-slot pool | |
| 418 | +(`KernelPool`); uploads are zero-copy (native-LE u32 slice, BE hosts fail | |
| 419 | +at compile time). The `pmk_out` entry point (same module) writes PMK rows | |
| 420 | +for the rainbow-table build. Measured on radv (RX 9060 XT, 108 VGPRs, | |
| 421 | +no spills): ~320k H/s effective ≈ kernel-only (was 135–190k pipelined / | |
| 422 | +240k kernel-only before the epilogue; hashcat on the same card: ~1.09 | |
| 423 | +MH/s — remaining gap is shader codegen, benchmarked and documented in | |
| 424 | +dev/research; a 2-candidates/thread ILP interleave measured −9% and was | |
| 425 | +rejected: 144 VGPR cost outweighed dual-issue gains). | |
| 204 | 426 | ```rust |
| 205 | 427 | pub struct GpuCracker; |
| 206 | 428 | impl GpuCracker { |
| @@ -216,23 +438,42 @@ impl GpuCracker { | ||
| 216 | 438 | stop: &std::sync::Arc<std::sync::atomic::AtomicBool>) |
| 217 | 439 | -> Option<String>; |
| 218 | 440 | } |
| 441 | +/// PMK sink for pure-CPU runs: every tried candidate's PMK is pushed to | |
| 442 | +/// the per-SSID cache (attack.rs supplies it; GPU runs NEVER get one — | |
| 443 | +/// no PMK readback is plumbed through the verify pipeline). The first | |
| 444 | +/// push error logs ONCE via the callback, then the sink self-disables. | |
| 445 | +pub struct CpuPmkSink; | |
| 446 | +impl CpuPmkSink { | |
| 447 | + pub fn new(w: rainbow::TableWriter, log: Box<dyn FnMut(String) + Send>) -> Self; | |
| 448 | + pub fn push(&mut self, pmk: &[u8; 32], word: &[u8]); | |
| 449 | + /// Flush; entries appended by THIS sink. | |
| 450 | + pub fn finish(self) -> std::io::Result<u64>; | |
| 451 | +} | |
| 452 | +/// cache_sink receives (pmk, word) per tried candidate (pure-CPU pmk | |
| 453 | +/// cache population; None anywhere else). | |
| 219 | 454 | pub fn cpu_crack(target: &CrackTarget, words: &mut dyn Iterator<Item = Vec<u8>>, |
| 220 | 455 | progress: &mut dyn FnMut(u64, f64), |
| 221 | - stop: &std::sync::Arc<std::sync::atomic::AtomicBool>) -> Option<String>; | |
| 222 | -``` | |
| 223 | -Algorithm (hashcat-style): host computes per candidate SHA1 midstate for | |
| 224 | -ipad/opad HMAC keys **and U1 = PRF(state, salt||0x00000001), U1' (block | |
| 225 | -2 = ...||0x00000002)** — salt = target essid, so U1/U1' are per-candidate×2 | |
| 226 | -only because key pads differ. Upload SoA arrays {sha1 midstate a,b ×2 (5 u32 | |
| 227 | -each), u1 (5), u1'(5)}. Kernel runs 4095 chained HMAC iterations per block | |
| 228 | -(U = HMAC(P, U); T ^= U) producing 40 bytes → PMK[0..20]|PMK2[0..20] → PMK = | |
| 229 | -first20||first12. Host then derives PTK+MIC per PMK on CPU (cheap relative to | |
| 230 | -4096 HMACs) and compares. Batch size tuned to adapter limits (start 65536 | |
| 231 | -candidates, halve on timeout). WGSL uses u32 SHA1, no naga extensions. | |
| 232 | -Correctness test: gpu crack must agree with crypto::verify on a synthetic | |
| 233 | -target and find a planted passphrase mid-wordlist; also cross-check PMK of | |
| 234 | -first 32 candidates vs pbkdf2 crate. Mark GPU test `#[ignore]`? NO — must run | |
| 235 | -in CI-less env: if no adapter, test early-returns Ok. | |
| 456 | + stop: &std::sync::Arc<std::sync::atomic::AtomicBool>, | |
| 457 | + cache_sink: Option<&mut CpuPmkSink>) -> Option<String>; | |
| 458 | +``` | |
| 459 | +Benchmark note (attack.rs): `benchmark(seconds) -> (Option<f64>, f64)` | |
| 460 | +measures raw PBKDF2 throughput — GPU half batches 4096 fixed words | |
| 461 | +through `pmk_batch_gpu`, CPU half times `crypto::pmk` over 512-word | |
| 462 | +batches; the numbers feed the cracker-page crack-time estimator and | |
| 463 | +`Event::BenchmarkDone`. | |
| 464 | +Kernel algorithm: candidate wire format = password bytes packed BE into | |
| 465 | +16 u32 (zero pad; WPA passphrases ≤ 63 B never spill the HMAC key block). | |
| 466 | +U1/U2 message blocks (salt||INT32BE(1|2), padded) are constant per run | |
| 467 | +and precomputed host-side into params. SHA1 uses hashcat's minimal-op | |
| 468 | +round forms (Ch: `d ^ (b & (c ^ d))`; Maj: `(b & c) ^ (d & (b ^ c))`) and | |
| 469 | +the doubled-step (rotl-2) message schedule for t ≥ 32 — bit-identical, | |
| 470 | +shorter serial depth. t2[3]/t2[4] XOR accumulation is dropped (PMK needs | |
| 471 | +only t2[0..12] bytes). Batch 65536 candidates, workgroup 256 (swept | |
| 472 | +64/128/256; 256 consistently ~2% faster), 30 s dispatch timeout guard. | |
| 473 | +Correctness tests: GPU crack finds planted passphrases (handshake kv2 and | |
| 474 | +PMKID), rejects wrong candidates, PMK rows bit-exact vs crypto::pmk | |
| 475 | +(RFC 6070-anchored), key_ver 3 and >51 B ESSIDs route to CPU. GPU tests | |
| 476 | +run un-ignored; with no adapter they early-return Ok. | |
| 236 | 477 | |
| 237 | 478 | ## wordlist.rs (owner: cracker) |
| 238 | 479 | ```rust |
| @@ -240,3 +481,198 @@ in CI-less env: if no adapter, test early-returns Ok. | ||
| 240 | 481 | /// yielding trimmed 8..=63-byte candidates, counting progress. |
| 241 | 482 | pub fn open(path: &std::path::Path) -> anyhow::Result<Box<dyn Iterator<Item = Vec<u8>> + Send>>; |
| 242 | 483 | ``` |
| 484 | + | |
| 485 | +## attack.rs (owner: cracker) — attack modes + UI-side workers | |
| 486 | +Cracking is a **UI-process job, fully independent of the radio/capture | |
| 487 | +state**: candidates and the GPU need no privileges, so no capture | |
| 488 | +start/stop (or even service spawn) precondition exists. The UI selects an | |
| 489 | +`Attack`, `validate()`s it (fail-fast, no zombie run), then `spawn_crack` | |
| 490 | +starts the worker thread and returns its stop flag. Worker event contract | |
| 491 | +(one terminator always): progress via `CrackProgress`, then | |
| 492 | +`CrackFound`+`CrackStopped{found:true}` or `CrackStopped{found:false}`. | |
| 493 | +```rust | |
| 494 | +pub enum Attack { Wordlist(PathBuf), Rules { wordlist: PathBuf, rules: PathBuf }, | |
| 495 | + Hybrid { wordlist: PathBuf, charset: Vec<u8>, min: usize, max: usize }, | |
| 496 | + Bruteforce { charset: Vec<u8>, min: usize, max: usize, #[serde(default)] freq_order: bool }, Rainbow(PathBuf) } | |
| 497 | +impl Attack { pub fn describe(&self) -> String; pub fn validate(&self) -> anyhow::Result<()>; } | |
| 498 | +/// Charset presets unioned with the custom field (UI chips). SPECIAL is | |
| 499 | +/// only the common symbols; exotic bytes go into the custom field. | |
| 500 | +pub mod charset { pub const LOWER/UPPER/DIGITS/SPECIAL: &[u8]; pub fn compose(...) -> Vec<u8>; } | |
| 501 | +/// Odometer-order charset^len generator, clamped to WPA 8..=63; `space()` = total candidates. | |
| 502 | +/// freq_order permutes the charset by a password-frequency rank literal | |
| 503 | +/// (bijection: space size and seek indices unchanged). | |
| 504 | +pub struct BruteForce; | |
| 505 | +impl BruteForce { pub fn new(charset: Vec<u8>, min: usize, max: usize, freq_order: bool) -> anyhow::Result<Self>; pub fn space(&self) -> u128; | |
| 506 | + /// O(1) jump to candidate index n (little-endian odometer math) — the resume path. | |
| 507 | + pub fn seek(&mut self, n: u64); } | |
| 508 | +/// Hashcat-subset rules (`: l u c C t r d $X ^X [ ] sXY`; spaces separate ops, | |
| 509 | +/// `#` comments, blank lines skipped). Rule outputs outside 8..=63 are | |
| 510 | +/// filtered but STILL CONSUME their flattened index — resume stays exact. | |
| 511 | +pub fn parse_rules(path: &Path) -> anyhow::Result<Vec<Rule>>; | |
| 512 | +pub fn rule_count(path: &Path) -> anyhow::Result<u64>; | |
| 513 | +/// wordlist × rules, WORD-MAJOR/rule-minor: flattened index = word_idx*rules_len | |
| 514 | +/// + rule_idx, so resume is a plain skip_n over the stream. | |
| 515 | +pub struct RuleIter; | |
| 516 | +/// wordlist × append-charset ("hybrid"): word + charset^k for k in min..=max | |
| 517 | +/// (clamped 1..=4), rightmost-fastest odometer; candidates >63 B skipped after | |
| 518 | +/// consuming their index. Flattened index = word_idx*per_word + inner with | |
| 519 | +/// per_word = Σ|charset|^k; total = line_count(wordlist) × per_word (upper bound). | |
| 520 | +pub struct HybridIter; | |
| 521 | +impl HybridIter { | |
| 522 | + pub fn new(words: Box<dyn Iterator<Item = Vec<u8>> + Send>, charset: Vec<u8>, min: usize, max: usize) -> anyhow::Result<Self>; | |
| 523 | + pub fn validate(charset: &[u8], min: usize, max: usize) -> anyhow::Result<()>; | |
| 524 | + pub fn per_word(&self) -> u64; | |
| 525 | + /// Exact flattened-index resume (skip words + prime the odometer). | |
| 526 | + pub fn seek_flat(&mut self, n: u64); | |
| 527 | +} | |
| 528 | +/// Drops candidates covered by the PMK cache consult (a miss proves they | |
| 529 | +/// are not the password); resume indices still refer to the RAW stream. | |
| 530 | +pub struct CacheSkipIter<I: Iterator<Item = Vec<u8>>>; | |
| 531 | +/// Rainbow run: precomputed PMKs, one PTK+MIC compare each, no PBKDF2. | |
| 532 | +pub fn rainbow_crack(target: &CrackTarget, entries: &mut dyn Iterator<Item = ([u8; 32], Vec<u8>)>, | |
| 533 | + progress: &mut dyn FnMut(u64, f64), stop: &Arc<AtomicBool>) -> Option<String>; | |
| 534 | +/// resume_from: skip/seek past that many leading candidates (flattened | |
| 535 | +/// index for rules/hybrid); progress events still count against the FULL | |
| 536 | +/// space (ETA stays meaningful). force_cpu pins the CPU backend and | |
| 537 | +/// DISABLES PMK-cache writes (headless CLI `--cpu`, side-effect-free). | |
| 538 | +/// Wordlist-family runs first consult the per-SSID PMK cache | |
| 539 | +/// (store::cache_file): hit → CrackFound+found-terminator with NO main run; | |
| 540 | +/// miss → Log "pmk cache: N entries, no hit — continuing …" and the main | |
| 541 | +/// iterator is CacheSkipIter-wrapped; unreadable cache → ONE Log, full run. | |
| 542 | +/// Pure-CPU main runs POPULATE the cache (gpu::CpuPmkSink via | |
| 543 | +/// rainbow::append_open); GPU runs never do. | |
| 544 | +pub fn spawn_crack(target_desc: String, target: CrackTarget, attack: Attack, resume_from: u64, tx: Sender<Event>, force_cpu: bool) -> Arc<AtomicBool>; | |
| 545 | +/// Build job: PMK-table from wordlist (GPU when available). Progress via | |
| 546 | +/// RainbowProgress; ALWAYS ends with exactly one RainbowBuilt (entries written). | |
| 547 | +pub fn spawn_rainbow_build(ssid: String, wordlist: PathBuf, out: PathBuf, tx: Sender<Event>) -> Arc<AtomicBool>; | |
| 548 | +/// Measured H/s for the crack-time estimator: GPU batches of 4096 via | |
| 549 | +/// pmk_batch_gpu (None without an adapter), CPU via crypto::pmk loop. | |
| 550 | +pub fn benchmark(seconds: u32) -> (Option<f64>, f64); | |
| 551 | +/// Background benchmark thread; exactly one Event::BenchmarkDone terminator | |
| 552 | +/// (a zeroed one follows the Error on spawn failure). Honors stop between batches. | |
| 553 | +pub fn spawn_benchmark(seconds: u32, tx: Sender<Event>) -> Arc<AtomicBool>; | |
| 554 | +``` | |
| 555 | + | |
| 556 | +## rainbow.rs (owner: cracker) — SSID-scoped PMK tables | |
| 557 | +"Rainbow" for WPA: PMK = PBKDF2(pass, essid) is SSID-bound, so a table is | |
| 558 | +reusable for every capture of one SSID. Text format, one entry per line: | |
| 559 | +`# wifilab-pmk v1 ssid=<essid>` header, then `<64-hex-pmk> <pass>`. | |
| 560 | +```rust | |
| 561 | +/// Returns header SSID (None when absent — MUST be refused by the caller | |
| 562 | +/// via check_ssid, PMKs compare-fail silently on the wrong SSID). | |
| 563 | +pub fn open(path: &Path) -> anyhow::Result<(Option<String>, Box<dyn Iterator<Item = ([u8; 32], Vec<u8>)> + Send>)>; | |
| 564 | +/// Fresh table with header; truncates. Parent directories are created | |
| 565 | +/// (the per-SSID cache lives in ~/wifilab/cache/, created on use). | |
| 566 | +pub fn create(path: &Path, ssid: &str) -> anyhow::Result<TableWriter>; | |
| 567 | +/// Per-SSID cache writer: missing/zero-length file → create-with-header; | |
| 568 | +/// existing file → header SSID MUST pass check_ssid (mismatch = Err, the | |
| 569 | +/// table is never poisoned by appends for another SSID), then open append. | |
| 570 | +pub fn append_open(path: &Path, ssid: &str) -> anyhow::Result<TableWriter>; | |
| 571 | +pub fn check_ssid(table_ssid: Option<&str>, target_ssid: &str) -> anyhow::Result<()>; | |
| 572 | +``` | |
| 573 | + | |
| 574 | +## store.rs — persistence (labels, captures, session, PMK cache, profiles) | |
| 575 | +PMK cache: `~/wifilab/cache/<ssid-hex>.pmk` (rainbow text format) — | |
| 576 | +`pub fn cache_dir() -> PathBuf` (data_dir()/cache, create_dir_all on use), | |
| 577 | +`pub fn cache_file(ssid: &str) -> PathBuf` (filename = lowercase hex of the | |
| 578 | +SSID bytes + `.pmk`). Profiles: `~/wifilab/profiles.json` — | |
| 579 | +```rust | |
| 580 | +pub struct CrackProfile { pub name: String, pub mode: String, pub wordlist: String, pub rules: Option<String> } | |
| 581 | +pub struct Profiles { pub profiles: Vec<CrackProfile>, pub recent_wordlists: Vec<String> } | |
| 582 | +pub fn load_profiles() -> anyhow::Result<Profiles>; // missing/parse-err -> default (eprintln log, then fresh) | |
| 583 | +pub fn save_profiles(&Profiles) -> anyhow::Result<()>; // tmp+rename | |
| 584 | +pub fn remember_wordlist(&mut Profiles, path: &str); // front-insert dedup, cap 5 | |
| 585 | +``` | |
| 586 | + | |
| 587 | +## Crack session (store.rs) — resume after stop/crash | |
| 588 | +`~/wifilab/crack-session.json`: `{capture: StoredCapture, attack, done, | |
| 589 | +total}` — autosaved by the UI every ~2 s of progress (atomic tmp+rename, | |
| 590 | +so a crash cannot tear it), finalized on Stop, deleted on found/exhausted, | |
| 591 | +restored at startup and matched back to a loaded capture by value | |
| 592 | +equality. Wordlist/table resume re-opens and skips `done` candidates; | |
| 593 | +bruteforce `seek`s in O(1). | |
| 594 | +```rust | |
| 595 | +pub struct CrackSession { pub capture: StoredCapture, pub attack: Attack, pub done: u64, pub total: Option<u64> } | |
| 596 | +pub fn save_session(&CrackSession) -> anyhow::Result<()>; | |
| 597 | +pub fn load_session() -> anyhow::Result<Option<CrackSession>>; | |
| 598 | +pub fn clear_session() -> anyhow::Result<()>; | |
| 599 | +``` | |
| 600 | + | |
| 601 | +## pcapout.rs — libpcap capture-file writer (spool + export) | |
| 602 | +Standard libpcap (DLT) file. Global header and every per-packet record are | |
| 603 | +little-endian; recorded timestamps are wall-clock (`SystemTime`), lengths | |
| 604 | +are `incl_len == orig_len == frame.len()` (spool frames are the raw socket | |
| 605 | +read incl. radiotap header). | |
| 606 | +```rust | |
| 607 | +pub struct PcapWriter { /* BufWriter<File> */ } // flushes on finish() and Drop | |
| 608 | +pub fn create(path: &Path) -> std::io::Result<PcapWriter>; // truncate + global header | |
| 609 | +pub fn from_path_append(path: &Path) -> std::io::Result<PcapWriter>; // existing non-empty file: append, NO header rewrite; missing/empty: like create | |
| 610 | +impl PcapWriter { pub fn append(&mut self, frame: &[u8]) -> std::io::Result<()>; pub fn finish(&mut self) -> std::io::Result<()>; } | |
| 611 | +``` | |
| 612 | +Writer field layout (all LE): magic `0xa1b2c3d4`, version 2.4, thiszone 0, | |
| 613 | +sigfigs 0, snaplen 65535, linktype 127 (`DLT_IEEE802_11_RADIO`). | |
| 614 | + | |
| 615 | +## pcapin.rs — capture-file importer | |
| 616 | +`pub fn extract(path: &Path) -> anyhow::Result<Vec<common::ImportedCapture>>` | |
| 617 | +— the headless/CLI-capable entry point used by the UI Import button. | |
| 618 | +Importer guarantees: | |
| 619 | +- Both byte orders of the file magic are accepted (`0xa1b2c3d4` LE, | |
| 620 | + `0xd4c3b2a1` BE); all other magics → error. | |
| 621 | +- Supported linktypes: 127 (`DLT_IEEE802_11_RADIO`, radiotap prefix stripped | |
| 622 | + via `radiotap::strip`; malformed prefixes are skipped and counted) and 105 | |
| 623 | + (`DLT_IEEE802_11`, raw 802.11). Any other linktype → error naming the | |
| 624 | + numeric linktype. | |
| 625 | +- Two in-memory passes: (1) beacons/probe-responses → bssid→essid map; | |
| 626 | + (2) EAPOL frames → `parse_eapol` → `parse_eapol_key` → `handshake::Tracker` | |
| 627 | + (progress events drained internally, never surfaced); M1-shaped keys are | |
| 628 | + additionally scanned for PMKID KDEs (`pmkid::extract_pmkid`), | |
| 629 | + yielding `ImportedCapture::Pmkid` with the observed station as `client`. | |
| 630 | +- essid-skip semantics: a capture (handshake or PMKID) whose AP's essid is | |
| 631 | + not resolvable from the file's beacons/probe-responses is uncrackable | |
| 632 | + (essid = PBKDF2 salt) and is skipped; skips are reported via | |
| 633 | + `tracing::warn!`, not in the return value. `extract` therefore returns | |
| 634 | + only crackable captures. | |
| 635 | +`pub(crate) fn frames(path: &Path) -> io::Result<(u32, Vec<Vec<u8>>)>` | |
| 636 | +returns (linktype, frame payloads) after global-header validation; packet | |
| 637 | +records with truncated payload → `UnexpectedEof`. | |
| 638 | + | |
| 639 | +## cli.rs — headless `wifilab crack` subcommand | |
| 640 | +Clap subcommand on the main binary (`src/main.rs` `Commands::Crack`); runs | |
| 641 | +with NO UI, no radio, no root — `--privileged-worker` dispatch stays ahead | |
| 642 | +of it and is untouched. `main.rs` owns the derived `CrackArgs`/`CliMode` | |
| 643 | +clap structs and converts them 1:1 into the owned, clap-free | |
| 644 | +`cli::CliCrack` for testability. | |
| 645 | +```rust | |
| 646 | +pub struct CliCrack { pub capture: String, pub mode: String /* "wordlist"|"rules"|"bruteforce" */, | |
| 647 | + pub wordlist: Option<String>, pub rules: Option<String>, pub min: usize, pub max: usize, | |
| 648 | + pub hybrid: bool, pub lower: bool, pub upper: bool, pub digits: bool, pub special: bool, | |
| 649 | + pub cpu: bool } | |
| 650 | +pub fn run_crack_cli(args: CliCrack, out: &mut dyn std::io::Write) -> i32; | |
| 651 | +``` | |
| 652 | +Flags: `--capture` (required hc22000 file), `--mode wordlist|rules|bruteforce` | |
| 653 | +(default wordlist), `--wordlist` (required by wordlist/rules/hybrid), | |
| 654 | +`--rules` (required by rules), `--min 8` / `--max 12`, `--hybrid` | |
| 655 | +(wordlist × append-charset sweep; takes precedence over `--mode`), | |
| 656 | +`--lower/--upper/--digits/--special` charset chips — when ALL chips are | |
| 657 | +false the charset defaults to lower+digits. `--cpu` forces the CPU backend | |
| 658 | +(`spawn_crack(.., force_cpu: true)`). | |
| 659 | +Target rule: the capture file is read as text; each line is tried as | |
| 660 | +`crypto::parse_hc22000(line.strip_prefix("WPA*").unwrap_or(line))` (the | |
| 661 | +hashcat `WPA*` prefix is stripped because parse takes the bare form) and | |
| 662 | +the FIRST parseable line is the target — unparseable lines are skipped | |
| 663 | +silently; none parseable → `error: no crackable WPA* line in <path>` + exit 2. | |
| 664 | +Exit codes: 0 password found (`FOUND: <password>` on the sink), 1 keyspace | |
| 665 | +exhausted, 2 usage/IO error (unreadable capture, no crackable line, missing | |
| 666 | +wordlist-family file, `attack.validate()` failure, engine `Error` event). | |
| 667 | +Progress throttled to one `done/total @ H/s` line per 2 s; engine `Log` | |
| 668 | +lines pass through verbatim. | |
| 669 | +Cache semantics: consult-only intent lives in the ENGINE, not the CLI — | |
| 670 | +wordlist-family runs always CONSULT the per-SSID PMK cache | |
| 671 | +(`store::cache_file`). Writes: `--cpu` (force_cpu) disables the cache sink, | |
| 672 | +so a forced-CPU CLI run is fully side-effect-free. Without `--cpu` on a | |
| 673 | +GPU-less machine the pure-CPU fallback DOES append newly computed PMKs to | |
| 674 | +`~/wifilab/cache` (engine semantics) — later runs of the same SSID benefit. | |
| 675 | +Tests: `cli_crack_finds_fabricated` (fabricated-mic capture crackable by | |
| 676 | +the mock password → wordlist → exit 0, `FOUND:` on the sink; pinned | |
| 677 | +password constant must track ui/cracker.rs `MOCK_PASSWORD`), | |
| 678 | +`cli_crack_missing_files_exit_2` (both usage-error paths). |