forge
Explore
Log in

Don't you dare go Hollow

Rework PBKDF2 kernel and cracker for batched multi-target runs

Browse files at this commit

7971998a1b2e310032e753f92f26810e3a4b2afbAhmet Kaan GümüşParent: 3dbcafb
  • perf
    • rework PBKDF2 kernel and cracker for batched multi-target runs
Show full message
⚡️ perf(gpu): rework PBKDF2 kernel and cracker for batched multi-target runs
src/gpu.rsmodified+651 -462
@@ -1,217 +1,351 @@
11 //! GPU-accelerated WPA2-PSK cracker (wgpu compute, see pbkdf2.wgsl) plus a
22 //! CPU streaming cracker of the same shape.
33 //!
4-//! Algorithm: the host computes per candidate the SHA1 midstates for the two
5-//! HMAC pad prefixes (key = passphrase, salt = ESSID absorbed in the ipad
6-//! leg) and the first PBKDF2 outputs U1/U2 for both 20-byte blocks. The GPU
7-//! then executes the remaining 4095 chained HMAC rounds per block and emits
8-//! T1||T2 (40 bytes): PMK = T1 || T2[0..12]. PTK + MIC are derived per PMK on
9-//! the host — that is cheap relative to the 4096 HMACs it replaces. For
10-//! key_ver 3 targets the MIC is AES-CMAC (bus duty: PTK+KCK never leave the
11-//! host side of the reference implementation).
12-
13-use std::num::NonZeroU64;
4+//! Full-pipeline architecture: the host packs raw candidate bytes only.
5+//! The kernel itself derives the HMAC pad midstates (2 compressions),
6+//! computes U1/U2 from host-precomputed padded salt messages, runs the
7+//! 4095-iteration chained HMAC loop (registers only), and performs the
8+//! verify EPILOGUE on-device (PTK-KCK HMAC + EAPOL MIC compare, or PMKID
9+//! compare). Per batch the host reads back a 16-byte hit slot instead of
10+//! batch×40B of PMKs — the previous midstate/upload + CPU MIC phases were
11+//! the pipeline's throughput ceiling.
12+//!
13+//! Targets whose MIC is AES-CMAC (key_ver 3) are not expressible in this
14+//! shader; [`gpu_verifiable`] routes them to the CPU cracker.
15+
1416 use std::sync::Arc;
1517 use std::sync::atomic::{AtomicBool, Ordering};
1618 use std::time::{Duration, Instant};
1719
18-/// Pack the first 64 message bytes into the 16 FIPS SHA1 message words
19-/// (big-endian parse, per FIPS 180-1).
20-fn pack16(bytes: &[u8]) -> [u32; 16] {
21- debug_assert!(bytes.len() >= 64);
22- let mut out = [0u32; 16];
23- for (i, w) in out.iter_mut().enumerate() {
24- *w = u32::from_be_bytes([bytes[4 * i], bytes[4 * i + 1], bytes[4 * i + 2], bytes[4 * i + 3]]);
25- }
26- out
27-}
28-
2920 use crate::crypto::{self, CrackTarget};
21+use crate::rainbow;
3022 #[cfg(test)]
3123 use crate::common::MacAddr;
3224
25+/// Target view with the candidate-invariant parts precomputed — the MIC
26+/// zeroing of the EAPOL frame is fixed for the whole run ([`crypto::mic`]
27+/// re-copies and re-zeroes the frame per call, which is measurable at
28+/// 65536 candidates per batch).
29+pub(crate) enum PreparedTarget<'a> {
30+ Handshake(&'a crate::common::HandshakeCapture, Vec<u8>),
31+ Pmkid(&'a crate::common::PmkidCapture),
32+}
33+
34+/// Prepare once per crack run (CPU + rainbow paths).
35+pub(crate) fn prepare_target(target: &CrackTarget) -> PreparedTarget<'_> {
36+ match target {
37+ CrackTarget::Handshake(h) => {
38+ PreparedTarget::Handshake(h, crypto::zeroed_eapol(&h.eapol_m2))
39+ }
40+ CrackTarget::Pmkid(p) => PreparedTarget::Pmkid(p),
41+ }
42+}
43+
44+/// MIC/PMKID check of one PMK against a [`PreparedTarget`].
45+pub(crate) fn prepared_matches(prepared: &PreparedTarget, k: &[u8; 32]) -> bool {
46+ match prepared {
47+ PreparedTarget::Handshake(h, zeroed) => {
48+ let dk = crypto::ptk(k, &h.ap, &h.client, &h.anonce, &h.snonce);
49+ let m = crypto::mic_on_zeroed(&dk, zeroed, h.key_ver);
50+ crypto::ct_eq16(&m, h.mic())
51+ }
52+ PreparedTarget::Pmkid(p) => {
53+ let dig = crypto::pmkid_hash(k, &p.ap, &p.client);
54+ crypto::ct_eq16(&dig, &p.pmkid)
55+ }
56+ }
57+}
58+
3359 const BATCH: u32 = 1 << 16;
34-const WORKGROUP_SIZE: u32 = 64;
60+const WORKGROUP_SIZE: u32 = 256;
3561 const ITERATIONS: u32 = 4096;
36-const U32_PER_CAND_IN: usize = 20; // ipad(5) opad(5) u1(5) u2(5)
37-const U32_PER_CAND_OUT: usize = 10; // T1(5) T2(5)
62+/// Candidate wire format: password bytes packed BE into 16 u32 (zero pad).
63+const U32_PER_CAND_IN: usize = 16;
64+/// PMK rows for the pmk_out (rainbow-build) entry: 8 words PMK + 2 pad.
65+const U32_PER_CAND_OUT: usize = 10;
66+/// Hit slot: [flag, gid] + pad.
67+const HIT_U32: usize = 4;
68+// Params layout (u32 words) — MUST mirror `struct Params` in pbkdf2.wgsl.
69+const P_HEADER: usize = 8;
70+const P_MSGS: usize = 32; // u1_msg || u2_msg
71+const P_BLK: usize = 48;
72+const PARAM_U32: usize = P_HEADER + P_MSGS + 2 * P_BLK + 4;
73+
74+/// Everything the kernel needs per crack run: the params words, built
75+/// once at target-prepare time (only word 4, the batch candidate count,
76+/// varies per dispatch).
77+pub(crate) struct GpuTargetCtx {
78+ params: Vec<u32>,
79+}
3880
39-const K: [u32; 4] = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
40-const IV: [u32; 5] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
81+impl GpuTargetCtx {
82+ /// Params words for one dispatch (`n` = candidate count). Clone of
83+ /// the per-run template: 560 B, negligible per batch.
84+ fn params_words(&self, n: u32) -> Vec<u32> {
85+ let mut v = self.params.clone();
86+ v[4] = n;
87+ v
88+ }
89+}
4190
42-// ---------------------------------------------------------------------------
43-// Host-side SHA1 midstate helpers (mirror of the WGSL kernel).
44-// ---------------------------------------------------------------------------
91+/// Big-endian pack of `bytes` into u32 words (SHA1's message-word view).
92+fn be_words(bytes: &[u8], out: &mut [u32]) {
93+ for (i, w) in out.iter_mut().enumerate() {
94+ let mut word = 0u32;
95+ for (j, &b) in bytes.iter().skip(4 * i).take(4).enumerate() {
96+ word |= (b as u32) << (24 - 8 * j);
97+ }
98+ *w = word;
99+ }
100+}
45101
46-/// One FIPS 180-1 SHA1 compression over exactly one 64-byte block, starting
47-/// from a 5×u32 state. `block` holds the message words BE-parsed as the
48-/// standard requires; states and the running chain stay in value domain
49-/// end-to-end (this is also the WGSL kernel's domain).
50-fn compress5(state: &mut [u32; 5], block: &[u32; 16]) {
51- let mut w = [0u32; 80];
52- w[..16].copy_from_slice(block);
53- for t in 16..80 {
54- let x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
55- w[t] = x.rotate_left(1);
56- }
57- let (mut a, mut b, mut c, mut d, mut e) = (state[0], state[1], state[2], state[3], state[4]);
58- for (t, &wt) in w.iter().enumerate() {
59- let f = match t {
60- 0..=19 => (b & c) | (!b & d),
61- 20..=39 | 60..=79 => b ^ c ^ d,
62- _ => (b & c) | (b & d) | (c & d),
63- };
64- let k = K[t / 20];
65- let temp = a
66- .rotate_left(5)
67- .wrapping_add(f)
68- .wrapping_add(e)
69- .wrapping_add(k)
70- .wrapping_add(wt);
71- e = d;
72- d = c;
73- c = b.rotate_left(30);
74- b = a;
75- a = temp;
76- }
77- state[0] = state[0].wrapping_add(a);
78- state[1] = state[1].wrapping_add(b);
79- state[2] = state[2].wrapping_add(c);
80- state[3] = state[3].wrapping_add(d);
81- state[4] = state[4].wrapping_add(e);
102+/// FIPS-pad an HMAC message (following the implicit 64-byte pad prefix)
103+/// and pack into BE 64-byte-block words; returns (words, block count).
104+fn padded_blocks(msg: &[u8]) -> (Vec<u32>, u32) {
105+ let total_bits = ((64 + msg.len()) as u64) * 8;
106+ let mut v = msg.to_vec();
107+ v.push(0x80);
108+ while v.len() % 64 != 56 {
109+ v.push(0);
110+ }
111+ v.extend_from_slice(&total_bits.to_be_bytes());
112+ let n_blocks = v.len() / 64;
113+ let mut words = vec![0u32; n_blocks * 16];
114+ be_words(&v, &mut words);
115+ (words, n_blocks as u32)
82116 }
83117
84-/// Finalize a two-block SHA1 message given the state after block 1: place
85-/// the tail, append padding/bit-length for the total (64 + tail.len()) byte
86-/// message, compress once. Returns the 5-word state (the FIPS digest words).
87-fn finalize_64(state_after_b1: &[u32; 5], tail: &[u8]) -> [u32; 5] {
88- debug_assert!(tail.len() < 56);
89- let total_len = (64 + tail.len()) as u64;
90- let mut blk = [0u8; 64];
91- blk[..tail.len()].copy_from_slice(tail);
92- blk[tail.len()] = 0x80;
93- blk[56..64].copy_from_slice(&(total_len * 8).to_be_bytes());
94- let mut st = *state_after_b1;
95- compress5(&mut st, &pack16(&blk));
96- st
118+/// U-block message for PBKDF2: salt || INT32BE(idx), padded whole. Must
119+/// fit one block (salt ≤ 51 bytes, incl. the 9 padding bytes).
120+fn u_msg(salt: &[u8], idx: u32) -> [u32; 16] {
121+ let mut m = Vec::with_capacity(salt.len() + 4);
122+ m.extend_from_slice(salt);
123+ m.extend_from_slice(&idx.to_be_bytes());
124+ let (words, n) = padded_blocks(&m);
125+ debug_assert_eq!(n, 1, "salt must fit one SHA1 block");
126+ let mut out = [0u32; 16];
127+ out.copy_from_slice(&words[..16]);
128+ out
97129 }
98130
99-/// First PBKDF2 block digest for a candidate: U_idx = HMAC(P, salt ||
100-/// INT32BE(idx)), using precomputed pad midstates. Inner leg message is
101-/// (P^ipad) || salt || BE32(idx) (64 + salt.len() + 4 bytes), outer leg is
102-/// (P^opad) || inner_digest (84 bytes, 672 bits).
103-fn hmac_first(ipad: &[u32; 5], opad: &[u32; 5], salt: &[u8], block_idx: u32) -> [u32; 5] {
104- let mut tail = [0u8; 68];
105- tail[..salt.len()].copy_from_slice(salt);
106- tail[salt.len()..salt.len() + 4].copy_from_slice(&block_idx.to_be_bytes());
107- let inner = finalize_64(ipad, &tail[..salt.len() + 4]);
108-
109- let mut outer_blk = [0u32; 16];
110- outer_blk[..5].copy_from_slice(&inner);
111- outer_blk[5] = 0x8000_0000;
112- outer_blk[15] = 672;
113- let mut st = *opad;
114- compress5(&mut st, &outer_blk);
115- st
131+/// Build the kernel verify context. None when the target is not
132+/// expressible in the SHA1-only shader: AES-CMIC handshake (key_ver 3),
133+/// truncated frame, or overlong ESSID (> 51 bytes — spills the U block).
134+pub(crate) fn gpu_ctx(target: &CrackTarget) -> Option<GpuTargetCtx> {
135+ let salt = target.essid().as_bytes();
136+ if salt.len() > 51 {
137+ return None;
138+ }
139+ let u1_msg = u_msg(salt, 1);
140+ let u2_msg = u_msg(salt, 2);
141+ let mut blk1 = [0u32; 48];
142+ let mut blk2 = [0u32; 48];
143+ let mut mic = [0u32; 4];
144+ let (is_pmkid, n_blk1, n_blk2) = match target {
145+ CrackTarget::Pmkid(p) => {
146+ // PMKID = HMAC-SHA1-128(PMK, "PMK Name" || ap || sta)[0..16].
147+ let mut msg = Vec::with_capacity(8 + 6 + 6);
148+ msg.extend_from_slice(b"PMK Name");
149+ msg.extend_from_slice(&p.ap.0);
150+ msg.extend_from_slice(&p.client.0);
151+ let (w, n) = padded_blocks(&msg);
152+ blk1[..w.len()].copy_from_slice(&w);
153+ be_words(&p.pmkid, &mut mic);
154+ (1, n, 0)
155+ }
156+ CrackTarget::Handshake(h) => {
157+ if h.key_ver == 3 || h.eapol_m2.len() < 99 {
158+ return None;
159+ }
160+ // blk1: PRF message round 1 = prf_stem || 0x01 → KCK.
161+ let mut prf = crypto::prf_stem(&h.ap, &h.client, &h.anonce, &h.snonce);
162+ prf.push(0x01);
163+ let (w1, n1) = padded_blocks(&prf);
164+ blk1[..w1.len()].copy_from_slice(&w1);
165+ // blk2: zeroed EAPOL frame (MIC message; 2..3 blocks).
166+ let zeroed = crypto::zeroed_eapol(&h.eapol_m2);
167+ let (w2, n2) = padded_blocks(&zeroed);
168+ blk2[..w2.len()].copy_from_slice(&w2);
169+ be_words(h.mic(), &mut mic);
170+ (0, n1, n2)
171+ }
172+ };
173+ let mut params = vec![0u32; PARAM_U32];
174+ params[0] = ITERATIONS << 1;
175+ params[1] = is_pmkid;
176+ params[2] = n_blk1;
177+ params[3] = n_blk2;
178+ params[P_HEADER..P_HEADER + 16].copy_from_slice(&u1_msg);
179+ params[P_HEADER + 16..P_HEADER + 32].copy_from_slice(&u2_msg);
180+ params[P_HEADER + P_MSGS..P_HEADER + P_MSGS + P_BLK].copy_from_slice(&blk1);
181+ params[P_HEADER + P_MSGS + P_BLK..P_HEADER + P_MSGS + 2 * P_BLK].copy_from_slice(&blk2);
182+ params[PARAM_U32 - 4..].copy_from_slice(&mic);
183+ Some(GpuTargetCtx { params })
116184 }
117185
118-/// Mirror of the WGSL `hmac_mid`: one chained HMAC round (two compresses)
119-/// over the 20-byte value `u` given the pad midstates.
120-fn hmac_midstate_host(ipad: &[u32; 5], opad: &[u32; 5], u: &[u32; 5]) -> [u32; 5] {
121- let mut msg = [0u32; 16];
122- msg[..5].copy_from_slice(u);
123- msg[5] = 0x8000_0000;
124- msg[15] = 672;
125-
126- let mut st = *ipad;
127- compress5(&mut st, &msg);
128-
129- let mut outer = [0u32; 16];
130- outer[..5].copy_from_slice(&st);
131- outer[5] = 0x8000_0000;
132- outer[15] = 672;
133-
134- let mut st2 = *opad;
135- compress5(&mut st2, &outer);
136- st2
186+/// Whether the GPU shader can verify this target (SHA1-family only; the
187+/// AES-CMAC key_ver 3 path stays on the CPU cracker).
188+pub(crate) fn gpu_verifiable(target: &CrackTarget) -> bool {
189+ gpu_ctx(target).is_some()
137190 }
138191
139-/// Per-candidate kernel inputs for one passphrase.
140-fn candidate_inputs(pass: &[u8], salt: &[u8]) -> [u32; U32_PER_CAND_IN] {
141- debug_assert!((8..=63).contains(&pass.len()));
142-
143- let mut ipad_blk = [0x36u8; 64];
144- let mut opad_blk = [0x5cu8; 64];
145- for (i, &b) in pass.iter().enumerate() {
146- ipad_blk[i] ^= b;
147- opad_blk[i] ^= b;
148- }
149-
150- let mut ipad = IV;
151- let mut opad = IV;
152- compress5(&mut ipad, &pack16(&ipad_blk));
153- compress5(&mut opad, &pack16(&opad_blk));
154-
155- // U_i = HMAC(P, salt || INT32BE(i)): inner leg via the ipad midstate,
156- // outer leg one compress over the opad midstate (also 84-byte total
157- // message → bit length 672, same layout as the chained rounds).
158- let u1 = hmac_first(&ipad, &opad, salt, 1);
159- let u2 = hmac_first(&ipad, &opad, salt, 2);
160-
161- let mut out = [0u32; U32_PER_CAND_IN];
162- out[..5].copy_from_slice(&ipad);
163- out[5..10].copy_from_slice(&opad);
164- out[10..15].copy_from_slice(&u1);
165- out[15..20].copy_from_slice(&u2);
192+/// Pack raw passphrases into the kernel wire format (BE words, zero pad).
193+fn pack_candidates(words: &[Vec<u8>]) -> Vec<u32> {
194+ let mut out = vec![0u32; words.len() * U32_PER_CAND_IN];
195+ for (w, dst) in words.iter().zip(out.chunks_exact_mut(U32_PER_CAND_IN)) {
196+ be_words(w, dst);
197+ }
166198 out
167199 }
168200
169-/// Finish the two PBKDF2 blocks for one candidate entirely on the CPU
170-/// (reference + fallback path).
171-fn pmk_via_midstates(inputs: &[u32; U32_PER_CAND_IN]) -> [u8; 32] {
172- let mut ipad = [0u32; 5];
173- let mut opad = [0u32; 5];
174- let mut u1 = [0u32; 5];
175- let mut u2 = [0u32; 5];
176- ipad.copy_from_slice(&inputs[..5]);
177- opad.copy_from_slice(&inputs[5..10]);
178- u1.copy_from_slice(&inputs[10..15]);
179- u2.copy_from_slice(&inputs[15..20]);
180-
181- let mut t1 = u1;
182- let mut t2 = u2;
183- for _ in 1..ITERATIONS {
184- u1 = hmac_midstate_host(&ipad, &opad, &u1);
185- for i in 0..5 {
186- t1[i] ^= u1[i];
201+/// One in-flight kernel dispatch. Buffers live in the pool; the handle
202+/// carries what waiting/returning needs.
203+struct PendingKernel {
204+ read_buf: wgpu::Buffer,
205+ slot: usize,
206+ rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
207+ sub: wgpu::SubmissionIndex,
208+ read_u32: usize,
209+}
210+
211+/// Returns a pool slot on drop, on ANY exit path of `wait_kernel`.
212+struct SlotGuard<'a> {
213+ pool: &'a std::cell::RefCell<Option<KernelPool>>,
214+ slot: usize,
215+}
216+
217+impl Drop for SlotGuard<'_> {
218+ fn drop(&mut self) {
219+ if let Some(pool) = self.pool.borrow_mut().as_mut() {
220+ pool.free.push(self.slot);
187221 }
188- u2 = hmac_midstate_host(&ipad, &opad, &u2);
189- for i in 0..5 {
190- t2[i] ^= u2[i];
222+ }
223+}
224+
225+/// One persistent set of dispatch buffers + bind group, sized for a full
226+/// batch (the 16-byte param/hit writes per batch are near-free).
227+struct KernelBufs {
228+ in_buf: wgpu::Buffer,
229+ out_buf: wgpu::Buffer,
230+ hit_buf: wgpu::Buffer,
231+ read_buf: wgpu::Buffer,
232+ param_buf: wgpu::Buffer,
233+ bind_group: wgpu::BindGroup,
234+}
235+
236+/// Free-slot allocator over persistent [`KernelBufs`]; starts with 2
237+/// slots (pipeline depth), grows on demand rather than failing.
238+struct KernelPool {
239+ bufs: Vec<KernelBufs>,
240+ free: Vec<usize>,
241+}
242+
243+impl KernelPool {
244+ fn new(
245+ device: &wgpu::Device,
246+ layout: &wgpu::BindGroupLayout,
247+ cap: usize,
248+ ) -> Self {
249+ let mut pool = KernelPool { bufs: Vec::new(), free: Vec::new() };
250+ for _ in 0..2 {
251+ pool.push_slot(device, layout, cap);
191252 }
253+ pool
192254 }
193255
194- let mut pmk_bytes = [0u8; 32];
195- for i in 0..5 {
196- pmk_bytes[i * 4..i * 4 + 4].copy_from_slice(&t1[i].to_be_bytes());
256+ fn push_slot(&mut self, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, cap: usize) {
257+ let in_bytes = (cap * U32_PER_CAND_IN * 4) as u64;
258+ let out_bytes = (cap * U32_PER_CAND_OUT * 4) as u64;
259+ let hit_bytes = (HIT_U32 * 4) as u64;
260+ let in_buf = device.create_buffer(&wgpu::BufferDescriptor {
261+ label: Some("candidates"),
262+ size: in_bytes.max(16),
263+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
264+ mapped_at_creation: false,
265+ });
266+ let out_buf = device.create_buffer(&wgpu::BufferDescriptor {
267+ label: Some("pmks"),
268+ size: out_bytes.max(16),
269+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
270+ mapped_at_creation: false,
271+ });
272+ let hit_buf = device.create_buffer(&wgpu::BufferDescriptor {
273+ label: Some("hits"),
274+ size: hit_bytes,
275+ usage: wgpu::BufferUsages::STORAGE
276+ | wgpu::BufferUsages::COPY_DST
277+ | wgpu::BufferUsages::COPY_SRC,
278+ mapped_at_creation: false,
279+ });
280+ let read_buf = device.create_buffer(&wgpu::BufferDescriptor {
281+ label: Some("readback"),
282+ size: out_bytes.max(hit_bytes),
283+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
284+ mapped_at_creation: false,
285+ });
286+ let param_buf = device.create_buffer(&wgpu::BufferDescriptor {
287+ label: Some("params"),
288+ size: (PARAM_U32 * 4) as u64,
289+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
290+ mapped_at_creation: false,
291+ });
292+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
293+ label: Some("pbkdf2-bg"),
294+ layout,
295+ entries: &[
296+ wgpu::BindGroupEntry { binding: 0, resource: param_buf.as_entire_binding() },
297+ wgpu::BindGroupEntry { binding: 1, resource: in_buf.as_entire_binding() },
298+ wgpu::BindGroupEntry { binding: 2, resource: out_buf.as_entire_binding() },
299+ wgpu::BindGroupEntry { binding: 3, resource: hit_buf.as_entire_binding() },
300+ ],
301+ });
302+ self.bufs.push(KernelBufs { in_buf, out_buf, hit_buf, read_buf, param_buf, bind_group });
303+ self.free.push(self.bufs.len() - 1);
197304 }
198- for i in 0..3 {
199- pmk_bytes[20 + i * 4..20 + i * 4 + 4].copy_from_slice(&t2[i].to_be_bytes());
305+
306+ /// Take a free slot (index), growing the pool when the pipeline is
307+ /// deeper than anticipated.
308+ fn take(&mut self, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, cap: usize) -> usize {
309+ match self.free.pop() {
310+ Some(i) => i,
311+ None => {
312+ self.push_slot(device, layout, cap);
313+ self.free.pop().expect("push_slot frees the new slot")
314+ }
315+ }
200316 }
201- pmk_bytes
202317 }
203318
204-// ---------------------------------------------------------------------------
205-// GPU cracker
206-// ---------------------------------------------------------------------------
319+/// Read-back scope of a dispatch: 16-byte hit slot (crack runs) or full
320+/// PMK rows (rainbow-build runs).
321+#[derive(Clone, Copy)]
322+enum Readback {
323+ Hits,
324+ Pmks(usize),
325+}
326+
327+impl Readback {
328+ fn bytes(self) -> usize {
329+ match self {
330+ Readback::Hits => HIT_U32 * 4,
331+ Readback::Pmks(n) => n * U32_PER_CAND_OUT * 4,
332+ }
333+ }
334+}
207335
208336 pub struct GpuCracker {
209337 device: wgpu::Device,
210338 queue: wgpu::Queue,
211339 pipeline: wgpu::ComputePipeline,
340+ pmk_pipeline: wgpu::ComputePipeline,
212341 layout: wgpu::BindGroupLayout,
213342 name: String,
214343 batch: u32,
344+ /// Persistent dispatch buffers, two slots — the pipeline keeps at most
345+ /// two kernels in flight (current + next); creating buffers per batch
346+ /// was the dominant host-side churn. Interior mutability: `crack`
347+ /// borrows `&self`.
348+ pool: std::cell::RefCell<Option<KernelPool>>,
215349 }
216350
217351 impl GpuCracker {
@@ -229,7 +363,7 @@ impl GpuCracker {
229363 .ok()?;
230364 let info = adapter.get_info();
231365 let limits = adapter.limits();
232- // Need storage buffers of BATCH × 80 B in and BATCH × 40 B out.
366+ // Need storage buffers of BATCH × 64 B in and BATCH × 40 B out.
233367 let in_bytes = u64::from(BATCH) * (U32_PER_CAND_IN as u64) * 4;
234368 let out_bytes = u64::from(BATCH) * (U32_PER_CAND_OUT as u64) * 4;
235369 if u64::from(limits.max_storage_buffer_binding_size) < in_bytes
@@ -249,47 +383,35 @@ impl GpuCracker {
249383 };
250384 let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?;
251385
252- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
386+ let shader_desc = wgpu::ShaderModuleDescriptor {
253387 label: Some("pbkdf2.wgsl"),
254388 source: wgpu::ShaderSource::Wgsl(include_str!("pbkdf2.wgsl").into()),
255- });
389+ };
390+ // The module carries no user input; skip naga's runtime bounds
391+ // checks (a tail-item guard in WGSL already clamps the last
392+ // partial batch). SAFETY: module is a static, trusted WGSL source.
393+ let shader = unsafe {
394+ device
395+ .create_shader_module_trusted(shader_desc, wgpu::ShaderRuntimeChecks::unchecked())
396+ };
256397
398+ let storage_entry = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {
399+ binding,
400+ visibility: wgpu::ShaderStages::COMPUTE,
401+ ty: wgpu::BindingType::Buffer {
402+ ty: wgpu::BufferBindingType::Storage { read_only },
403+ has_dynamic_offset: false,
404+ min_binding_size: None,
405+ },
406+ count: None,
407+ };
257408 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
258409 label: Some("pbkdf2-layout"),
259410 entries: &[
260- // params uniform
261- wgpu::BindGroupLayoutEntry {
262- binding: 0,
263- visibility: wgpu::ShaderStages::COMPUTE,
264- ty: wgpu::BindingType::Buffer {
265- ty: wgpu::BufferBindingType::Uniform,
266- has_dynamic_offset: false,
267- min_binding_size: NonZeroU64::new(16),
268- },
269- count: None,
270- },
271- // midstates in
272- wgpu::BindGroupLayoutEntry {
273- binding: 1,
274- visibility: wgpu::ShaderStages::COMPUTE,
275- ty: wgpu::BindingType::Buffer {
276- ty: wgpu::BufferBindingType::Storage { read_only: true },
277- has_dynamic_offset: false,
278- min_binding_size: None,
279- },
280- count: None,
281- },
282- // outputs out
283- wgpu::BindGroupLayoutEntry {
284- binding: 2,
285- visibility: wgpu::ShaderStages::COMPUTE,
286- ty: wgpu::BindingType::Buffer {
287- ty: wgpu::BufferBindingType::Storage { read_only: false },
288- has_dynamic_offset: false,
289- min_binding_size: None,
290- },
291- count: None,
292- },
411+ storage_entry(0, true), // params
412+ storage_entry(1, true), // candidates
413+ storage_entry(2, false), // outputs
414+ storage_entry(3, false), // hits
293415 ],
294416 });
295417
@@ -299,22 +421,28 @@ impl GpuCracker {
299421 immediate_size: 0,
300422 });
301423
302- let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
303- label: Some("pbkdf2-pipeline"),
304- layout: Some(&pipeline_layout),
305- module: &shader,
306- entry_point: Some("main"),
307- compilation_options: wgpu::PipelineCompilationOptions::default(),
308- cache: None,
309- });
424+ let make_pipeline = |label, entry| {
425+ device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
426+ label: Some(label),
427+ layout: Some(&pipeline_layout),
428+ module: &shader,
429+ entry_point: Some(entry),
430+ compilation_options: wgpu::PipelineCompilationOptions::default(),
431+ cache: None,
432+ })
433+ };
434+ let pipeline = make_pipeline("pbkdf2-crack-pipeline", "main");
435+ let pmk_pipeline = make_pipeline("pbkdf2-pmk-pipeline", "pmk_out");
310436
311437 Some(GpuCracker {
312438 device,
313439 queue,
314440 pipeline,
441+ pmk_pipeline,
315442 layout,
316443 name: format!("{} ({:?})", info.name, info.backend),
317444 batch: BATCH,
445+ pool: std::cell::RefCell::new(None),
318446 })
319447 }
320448
@@ -322,98 +450,48 @@ impl GpuCracker {
322450 self.name.clone()
323451 }
324452
325- /// Measured full-attack throughput for progress reporting (4096-iteration
326- /// batches). Runs 4 batches through `pmk_batch_gpu` and returns H/s.
327- #[cfg(test)]
328- fn measured_hps(&self) -> Option<f64> {
329- let pass: Vec<u8> = b"benchmk1".to_vec();
330- let salt = b"benchmark-ssid";
331- let mut inputs = Vec::with_capacity(self.batch as usize * U32_PER_CAND_IN);
332- for i in 0..self.batch as usize {
333- let mut w = pass.clone();
334- w[0] = b'a' + (i % 26) as u8;
335- inputs.extend_from_slice(&candidate_inputs(&w, salt));
336- }
337- // Warm-up batch: covers one-time SPIR-V->ISA compile & memory init.
338- self.run_kernel(&inputs)?;
339- const BATCHES: u32 = 8;
340- let t0 = Instant::now();
341- let mut ok = true;
342- for _ in 0..BATCHES {
343- let mut inp = inputs.clone();
344- inp[0] = inp[0].wrapping_add(1);
345- ok &= self.run_kernel(&inp).is_some();
346- }
347- if !ok {
348- return None;
349- }
350- let secs = t0.elapsed().as_secs_f64();
351- Some(self.batch as f64 * f64::from(BATCHES) / secs)
352- }
353-
354- /// Run one kernel batch over `inputs` (n×20 u32, on the wire as u32 LE).
355- /// Returns the n×10 u32 output words, or None on device-lost/hang.
356- fn run_kernel(&self, inputs: &[u32]) -> Option<Vec<u32>> {
453+ /// Dispatch WITHOUT waiting: returns an in-flight handle so next-batch
454+ /// packing overlaps the GPU. `params` is 140 u32 (see [`GpuTargetCtx`]);
455+ /// `pipeline` picks main vs pmk_out. None for empty input.
456+ fn submit_kernel(
457+ &self,
458+ inputs: &[u32],
459+ params: &[u32],
460+ readback: Readback,
461+ pmk_pipeline: bool,
462+ ) -> Option<PendingKernel> {
357463 let n = inputs.len() / U32_PER_CAND_IN;
358464 if n == 0 {
359- return Some(Vec::new());
465+ return None;
360466 }
467+ debug_assert!(n <= self.batch as usize, "kernel buffers sized for one batch");
468+ debug_assert_eq!(params.len(), PARAM_U32);
361469
362- let in_bytes = (inputs.len() * 4) as u64;
363- let out_u32 = n * U32_PER_CAND_OUT;
364- let out_bytes = (out_u32 * 4) as u64;
365-
366- let in_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
367- label: Some("midstates"),
368- size: in_bytes.max(16),
369- usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
370- mapped_at_creation: false,
371- });
372- let out_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
373- label: Some("t1t2"),
374- size: out_bytes.max(16),
375- usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
376- mapped_at_creation: false,
377- });
378- let read_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
379- label: Some("readback"),
380- size: out_bytes.max(16),
381- usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
382- mapped_at_creation: false,
383- });
384- let param_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
385- label: Some("params"),
386- size: 16,
387- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
388- mapped_at_creation: false,
389- });
390-
391- let flags: u32 = ITERATIONS << 1;
392- let params: [u32; 4] = [flags, 0, 0, 0];
393- self.queue
394- .write_buffer(&param_buf, 0, &u32s_as_bytes(&params));
395- let in_bytes_vec = u32s_as_bytes(inputs);
396- self.queue.write_buffer(&in_buf, 0, &in_bytes_vec);
470+ let slot = {
471+ let mut pool = self.pool.borrow_mut();
472+ let pool = pool.get_or_insert_with(|| {
473+ KernelPool::new(&self.device, &self.layout, self.batch as usize)
474+ });
475+ pool.take(&self.device, &self.layout, self.batch as usize)
476+ };
477+ let (in_buf, out_buf, hit_buf, read_buf, param_buf, bind_group) = {
478+ let pool = self.pool.borrow();
479+ let bufs = &pool.as_ref().expect("pool just created").bufs[slot];
480+ (
481+ bufs.in_buf.clone(),
482+ bufs.out_buf.clone(),
483+ bufs.hit_buf.clone(),
484+ bufs.read_buf.clone(),
485+ bufs.param_buf.clone(),
486+ bufs.bind_group.clone(),
487+ )
488+ };
397489
398- let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
399- label: Some("pbkdf2-bg"),
400- layout: &self.layout,
401- entries: &[
402- wgpu::BindGroupEntry {
403- binding: 0,
404- resource: param_buf.as_entire_binding(),
405- },
406- wgpu::BindGroupEntry {
407- binding: 1,
408- resource: in_buf.as_entire_binding(),
409- },
410- wgpu::BindGroupEntry {
411- binding: 2,
412- resource: out_buf.as_entire_binding(),
413- },
414- ],
415- });
490+ self.queue.write_buffer(&param_buf, 0, u32s_as_bytes(params));
491+ self.queue.write_buffer(&hit_buf, 0, &[0u8; 16]);
492+ self.queue.write_buffer(&in_buf, 0, u32s_as_bytes(inputs));
416493
494+ let read_u32 = readback.bytes() / 4;
417495 let mut encoder = self
418496 .device
419497 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
@@ -424,24 +502,46 @@ impl GpuCracker {
424502 label: Some("pbkdf2-pass"),
425503 timestamp_writes: None,
426504 });
427- pass.set_pipeline(&self.pipeline);
505+ pass.set_pipeline(if pmk_pipeline { &self.pmk_pipeline } else { &self.pipeline });
428506 pass.set_bind_group(0, &bind_group, &[]);
507+ // Two candidates per thread.
429508 pass.dispatch_workgroups(n.div_ceil(WORKGROUP_SIZE as usize) as u32, 1, 1);
430509 }
431- encoder.copy_buffer_to_buffer(&out_buf, 0, &read_buf, 0, out_bytes);
510+ match readback {
511+ Readback::Hits => {
512+ encoder.copy_buffer_to_buffer(&hit_buf, 0, &read_buf, 0, readback.bytes() as u64)
513+ }
514+ Readback::Pmks(_) => encoder.copy_buffer_to_buffer(
515+ &out_buf,
516+ 0,
517+ &read_buf,
518+ 0,
519+ readback.bytes() as u64,
520+ ),
521+ }
432522 let sub = self.queue.submit([encoder.finish()]);
433523
434- // Wait for the shader with timeout; a hung/compute-heavy dispatch is
435- // reported so the caller can halve the batch.
436524 let (tx, rx) = std::sync::mpsc::channel();
437525 read_buf
438- .slice(..)
526+ .slice(..readback.bytes() as u64)
439527 .map_async(wgpu::MapMode::Read, move |res| {
440528 let _ = tx.send(res);
441529 });
442530
531+ Some(PendingKernel { read_buf, slot, rx, sub, read_u32 })
532+ }
533+
534+ /// Wait on a dispatched kernel (timeout: hung/compute-heavy dispatch)
535+ /// and read back the requested words. None on device-lost/hang. The
536+ /// pool slot is freed for the next dispatch.
537+ fn wait_kernel(&self, pending: PendingKernel) -> Option<Vec<u32>> {
538+ let PendingKernel { read_buf, slot, rx, sub, read_u32 } = pending;
539+ // Any exit path returns the slot; a wedged slot must not deadlock
540+ // a later run.
541+ let _guard = SlotGuard { pool: &self.pool, slot };
542+
443543 let mut waited = Duration::ZERO;
444- let step = Duration::from_millis(50);
544+ let step = Duration::from_millis(8);
445545 let limit = Duration::from_secs(30);
446546 loop {
447547 match self.device.poll(wgpu::PollType::Wait {
@@ -472,9 +572,10 @@ impl GpuCracker {
472572 }
473573 }
474574
475- let view = read_buf.slice(..).get_mapped_range().ok()?;
476- let mut out = Vec::with_capacity(out_u32);
477- for chunk in view[..(out_u32 * 4)].chunks_exact(4) {
575+ let bytes = read_u32 * 4;
576+ let view = read_buf.slice(..bytes as u64).get_mapped_range().ok()?;
577+ let mut out = Vec::with_capacity(read_u32);
578+ for chunk in view[..bytes].chunks_exact(4) {
478579 out.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
479580 }
480581 drop(view);
@@ -482,18 +583,37 @@ impl GpuCracker {
482583 Some(out)
483584 }
484585
485- /// Compute PMKs for a word batch. Halves the batch size once on
486- /// device-lost/timeout; on a repeated failure returns None.
487- fn pmk_batch_gpu(&self, words: &[Vec<u8>], salt: &[u8]) -> Option<Vec<[u8; 32]>> {
586+ /// Compute PMKs for a word batch (rainbow-table build; `pmk_out`
587+ /// pipeline). Halves the batch size once on device-lost/timeout; on a
588+ /// repeated failure returns None.
589+ pub(crate) fn pmk_batch_gpu(&self, words: &[Vec<u8>], salt: &[u8]) -> Option<Vec<[u8; 32]>> {
590+ if salt.len() > 51 {
591+ return None;
592+ }
593+ let mut params = vec![0u32; PARAM_U32];
594+ params[0] = ITERATIONS << 1;
595+ let u1 = u_msg(salt, 1);
596+ let u2 = u_msg(salt, 2);
597+ params[P_HEADER..P_HEADER + 16].copy_from_slice(&u1);
598+ params[P_HEADER + 16..P_HEADER + 32].copy_from_slice(&u2);
599+
488600 let mut cur: Vec<Vec<u8>> = words.to_vec();
489601 let mut attempts = 0u8;
490602 loop {
491- let mut inputs = Vec::with_capacity(cur.len() * U32_PER_CAND_IN);
492- for w in &cur {
493- inputs.extend_from_slice(&candidate_inputs(w, salt));
494- }
495- if let Some(out) = self.run_kernel(&inputs) {
496- return Some(assemble_pmks(&out));
603+ params[4] = cur.len() as u32;
604+ let inputs = pack_candidates(&cur);
605+ let sub =
606+ self.submit_kernel(&inputs, &params, Readback::Pmks(cur.len()), true)?;
607+ if let Some(out) = self.wait_kernel(sub) {
608+ let mut pmks = Vec::with_capacity(cur.len());
609+ for row in out.chunks_exact(U32_PER_CAND_OUT) {
610+ let mut pmk = [0u8; 32];
611+ for (i, w) in row[..8].iter().enumerate() {
612+ pmk[i * 4..i * 4 + 4].copy_from_slice(&w.to_be_bytes());
613+ }
614+ pmks.push(pmk);
615+ }
616+ return Some(pmks);
497617 }
498618 attempts += 1;
499619 if attempts > 1 || cur.len() == 1 {
@@ -504,9 +624,14 @@ impl GpuCracker {
504624 }
505625 }
506626
507- /// Stream `words` through the GPU, calling `progress(done, hps)` once per
508- /// dispatched batch (also when a partial final batch ran). Honors `stop`
509- /// between batches. Returns the passphrase on MIC match.
627+ /// Stream `words` through the GPU, calling `progress(done, hps)` per
628+ /// finished batch. Honors `stop` between batches. Returns the
629+ /// passphrase on an on-device MIC/PMKID match (hit-slot readback).
630+ ///
631+ /// The kernel verifies candidates itself: per batch the host packs
632+ /// raw bytes (memcpy-rate), uploads 64B/candidate and read back a
633+ /// 16-byte hit slot — the previous midstate/upload + CPU-MIC phases
634+ /// were the throughput bottleneck, not the chain.
510635 pub fn crack(
511636 &self,
512637 target: &CrackTarget,
@@ -514,122 +639,157 @@ impl GpuCracker {
514639 progress: &mut dyn FnMut(u64, f64),
515640 stop: &Arc<AtomicBool>,
516641 ) -> Option<String> {
517- if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) {
518- return None;
519- }
520- let salt = target.essid().as_bytes();
642+ let ctx = gpu_ctx(target)?;
521643 let mut done = 0u64;
522644 let started = Instant::now();
523- let mut batch_cap = self.batch as usize;
645+ let batch_cap = self.batch as usize;
524646
525- loop {
526- if stop.load(Ordering::Relaxed) {
527- return None;
528- }
529- let mut batch: Vec<Vec<u8>> = Vec::with_capacity(batch_cap);
530- while batch.len() < batch_cap {
647+ fn collect(words: &mut dyn Iterator<Item = Vec<u8>>, cap: usize) -> Vec<Vec<u8>> {
648+ let mut batch: Vec<Vec<u8>> = Vec::with_capacity(cap);
649+ while batch.len() < cap {
531650 match words.next() {
532651 Some(w) => batch.push(w),
533652 None => break,
534653 }
535654 }
536- if batch.is_empty() {
537- return None;
538- }
539-
540- let pmks = self.pmk_batch_gpu(&batch, salt)?;
541- // If the PMK batch shrunk because of a device hiccup the tail
542- // candidates are re-attempted below; keep bookkeeping accurate by
543- // scanning only what came back and re-queueing the rest.
544- let checked = pmks.len();
545- for (i, k) in pmks.iter().enumerate() {
546- done += 1;
547- if target_matches(target, k) {
548- return String::from_utf8(batch[i].clone()).ok();
549- }
550- }
655+ batch
656+ }
657+ let tick = |done: u64, started: Instant, progress: &mut dyn FnMut(u64, f64)| {
551658 let secs = started.elapsed().as_secs_f64().max(1e-6);
552659 progress(done, done as f64 / secs);
660+ };
661+ // Drain an aborted pipeline slot: never drop a mapped-read buffer
662+ // without polling it through.
663+ let drain = |pending: Option<PendingKernel>| {
664+ if let Some(p) = pending {
665+ let _ = self.wait_kernel(p);
666+ }
667+ };
553668
554- if checked < batch.len() {
555- // Device hiccup path: retry the remaining words in smaller
556- // chunks before continuing the stream.
557- let rest = batch[checked..].to_vec();
558- for chunk in rest.chunks(batch_cap.div_ceil(2).max(1)) {
559- if stop.load(Ordering::Relaxed) {
560- return None;
561- }
562- let pmks = self.pmk_batch_gpu(chunk, salt)?;
563- for (i, k) in pmks.iter().enumerate() {
564- done += 1;
565- if target_matches(target, k) {
566- return String::from_utf8(chunk[i].clone()).ok();
567- }
568- }
569- let secs = started.elapsed().as_secs_f64().max(1e-6);
570- progress(done, done as f64 / secs);
571- }
572- batch_cap = batch_cap.div_ceil(2).max(1024);
669+ let mut cur_words = collect(words, batch_cap);
670+ if cur_words.is_empty() {
671+ return None;
672+ }
673+ let mut pending = Some(self.submit_kernel(
674+ &pack_candidates(&cur_words),
675+ &ctx.params_words(cur_words.len() as u32),
676+ Readback::Hits,
677+ false,
678+ )?);
679+
680+ loop {
681+ if stop.load(Ordering::Relaxed) {
682+ drain(pending.take());
683+ return None;
573684 }
685+ // While the GPU verifies batch N on-device: fetch + pack the
686+ // next batch and hand it to the GPU as soon as possible.
687+ let next_words = collect(words, batch_cap);
688+ let next_pending = if next_words.is_empty() {
689+ None
690+ } else {
691+ Some(self.submit_kernel(
692+ &pack_candidates(&next_words),
693+ &ctx.params_words(next_words.len() as u32),
694+ Readback::Hits,
695+ false,
696+ )?)
697+ };
698+
699+ let cur_pending = pending.take().expect("pipeline: one batch in flight");
700+ let Some(hit) = self.wait_kernel(cur_pending) else {
701+ drain(next_pending);
702+ return None;
703+ };
704+ // A hit slot write is dispatched-and-completed before the map
705+ // resolves: flag==1 with gid valid.
706+ if hit[0] != 0 {
707+ drain(next_pending);
708+ let gid = hit[1] as usize;
709+ done += gid as u64 + 1;
710+ tick(done, started, progress);
711+ return cur_words.get(gid).and_then(|w| String::from_utf8(w.clone()).ok());
712+ }
713+ done += cur_words.len() as u64;
714+ tick(done, started, progress);
715+
716+ let Some(next_pending) = next_pending else {
717+ return None; // stream exhausted; nothing in flight
718+ };
719+ cur_words = next_words;
720+ pending = Some(next_pending);
574721 }
575722 }
576723 }
577724
578-/// Little-endian byte serialization of a u32 slice for queue.write_buffer.
579-/// The kernel reads raw u32s; on this CPU (x86-64, LE) this matches memory
580-/// layout, and serializing keeps the wire format explicit for any host.
581-fn u32s_as_bytes(v: &[u32]) -> Vec<u8> {
582- let mut out = Vec::with_capacity(v.len() * 4);
583- for &w in v {
584- out.extend_from_slice(&w.to_le_bytes());
585- }
586- out
725+/// Borrow a `&[u32]` as `&[u8]` for queue.write_buffer WITHOUT copying
726+/// (65536-candidate batches make the old 5 MiB memcpy per dispatch
727+/// measurable). Compiled only for little-endian hosts: the kernel's wire
728+/// format is native LE u32, matching memory layout.
729+#[cfg(target_endian = "little")]
730+fn u32s_as_bytes(v: &[u32]) -> &[u8] {
731+ // SAFETY: u32 has no padding and outlives the call; the kernel expects
732+ // exactly these bytes.
733+ unsafe { std::slice::from_raw_parts(v.as_ptr().cast::<u8>(), std::mem::size_of_val(v)) }
587734 }
588735
589-fn assemble_pmks(out: &[u32]) -> Vec<[u8; 32]> {
590- let n = out.len() / U32_PER_CAND_OUT;
591- let mut pmks = Vec::with_capacity(n);
592- for c in 0..n {
593- let mut pmk = [0u8; 32];
594- let row = &out[c * U32_PER_CAND_OUT..(c + 1) * U32_PER_CAND_OUT];
595- for i in 0..8 {
596- pmk[i * 4..i * 4 + 4].copy_from_slice(&row[i].to_be_bytes());
597- }
598- pmks.push(pmk);
599- }
600- pmks
736+#[cfg(target_endian = "big")]
737+compile_error!("GPU cracker wire format assumes a little-endian host");
738+
739+// ---------------------------------------------------------------------------
740+// CPU cracker (reference-fallback path)
741+// ---------------------------------------------------------------------------
742+
743+/// Per-word PMK sink for pure-CPU cracks (per-SSID PMK cache population):
744+/// the caller feeds the PMK already computed for the compare, so caching
745+/// costs only the write. The first push error is surfaced through the log
746+/// callback ONCE, then the sink disables itself silently — a partially
747+/// written cache stays readable and useful.
748+pub struct CpuPmkSink {
749+ w: Option<rainbow::TableWriter>,
750+ log: Box<dyn FnMut(String) + Send>,
601751 }
602752
603-/// MIC/PMKID check of one PMK against the target.
604-fn target_matches(target: &CrackTarget, k: &[u8; 32]) -> bool {
605- match target {
606- CrackTarget::Handshake(h) => {
607- let dk = crypto::ptk(k, &h.ap, &h.client, &h.anonce, &h.snonce);
608- let m = crypto::mic(&dk, &h.eapol_m2, h.key_ver);
609- crypto::ct_eq16(&m, h.mic())
753+impl CpuPmkSink {
754+ pub fn new(w: rainbow::TableWriter, log: Box<dyn FnMut(String) + Send>) -> Self {
755+ CpuPmkSink { w: Some(w), log }
756+ }
757+
758+ /// Write `(pmk, word)`; errors log once and then disable the sink.
759+ pub fn push(&mut self, pmk: &[u8; 32], word: &[u8]) {
760+ if let Some(w) = &mut self.w {
761+ if let Err(e) = w.push(pmk, word) {
762+ (self.log)(format!("pmk cache: write failed ({e}) — cache left partial"));
763+ self.w = None;
764+ }
610765 }
611- CrackTarget::Pmkid(p) => {
612- let dig = crypto::pmkid_hash(k, &p.ap, &p.client);
613- crypto::ct_eq16(&dig, &p.pmkid)
766+ }
767+
768+ /// Flush the writer; number of entries appended by THIS sink.
769+ pub fn finish(self) -> std::io::Result<u64> {
770+ match self.w {
771+ Some(w) => w.finish(),
772+ None => Ok(0),
614773 }
615774 }
616775 }
617776
618-// ---------------------------------------------------------------------------
619-// CPU cracker (reference-fallback path)
620-// ---------------------------------------------------------------------------
621-
622777 /// Streaming CPU cracker with the same contract as `GpuCracker::crack`.
778+/// `cache_sink`, when given, receives `(pmk, word)` for every tried
779+/// candidate (PMK cache population: pure-CPU runs only, caller's policy).
623780 pub fn cpu_crack(
624781 target: &CrackTarget,
625782 words: &mut dyn Iterator<Item = Vec<u8>>,
626783 progress: &mut dyn FnMut(u64, f64),
627784 stop: &Arc<AtomicBool>,
785+ cache_sink: Option<&mut CpuPmkSink>,
628786 ) -> Option<String> {
629787 if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) {
630788 return None;
631789 }
632790 let salt = target.essid().as_bytes();
791+ let prepared = prepare_target(target);
792+ let mut sink = cache_sink;
633793 let mut done = 0u64;
634794 let started = Instant::now();
635795 const CPU_BATCH: usize = 512;
@@ -651,7 +811,10 @@ pub fn cpu_crack(
651811 for w in &batch {
652812 done += 1;
653813 let key = crypto::pmk(w, salt);
654- if target_matches(target, &key) {
814+ if let Some(s) = sink.as_deref_mut() {
815+ s.push(&key, w);
816+ }
817+ if prepared_matches(&prepared, &key) {
655818 return String::from_utf8(w.clone()).ok();
656819 }
657820 }
@@ -686,7 +849,7 @@ mod tests {
686849 f
687850 }
688851
689- fn synthetic_target(ssid: &str, pass: &[u8], key_ver: u8) -> CrackTarget {
852+ pub(crate) fn synthetic_target(ssid: &str, pass: &[u8], key_ver: u8) -> CrackTarget {
690853 let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
691854 let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
692855 let anonce: [u8; 32] = [0x5a; 32];
@@ -707,20 +870,36 @@ mod tests {
707870 ))
708871 }
709872
873+ pub(crate) fn synthetic_pmkid(ssid: &str, pass: &[u8]) -> CrackTarget {
874+ let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
875+ let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
876+ let key = crypto::pmk(pass, ssid.as_bytes());
877+ CrackTarget::Pmkid(crate::common::PmkidCapture {
878+ ap,
879+ client: sta,
880+ essid: ssid.to_string(),
881+ pmkid: crypto::pmkid_hash(&key, &ap, &sta),
882+ })
883+ }
884+
710885 #[test]
711- fn host_midstate_matches_pbkdf2() {
712- // candidate_inputs + pmk_via_midstates must equal crypto's
713- // PBKDF2-HMAC-SHA1 (itself pinned to RFC 6070 + the IEEE wpa vector
714- // in crypto::tests) for arbitrary passphrases and salts.
715- for pass in [&b"password1"[..], b"sup3r-secret", &vec![b'x'; 63][..], b"87654321"] {
716- for ssid in [&b"IEEE"[..], b"parafin", b"", b"long-ssid-0123456789"] {
717- let inputs = candidate_inputs(pass, ssid);
718- let got = pmk_via_midstates(&inputs);
719- let mut dk = [0u8; 40];
720- crypto::pbkdf2_hmac_sha1(pass, ssid, 4096, &mut dk);
721- assert_eq!(&got[..], &dk[..32], "pass={pass:?} ssid={ssid:?}");
722- }
723- }
886+ fn host_padded_blocks_match_reference() {
887+ // The host's padded HMAC message blocks must be exactly what the
888+ // reference sha1/hmac stack computes: HMAC(K, msg) from a given
889+ // midstate pair must equal feeding the padded blocks through
890+ // compress-free reference code. Easiest ground truth: verify()
891+ // covers the whole chain via crypto::verify in target tests; here
892+ // pin just the padding invariants (0x80 at len, bitlen tail).
893+ let msg = b"PMK Name012345";
894+ let (words, n) = padded_blocks(msg);
895+ assert_eq!(n, 1);
896+ let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_be_bytes()).collect();
897+ assert_eq!(&bytes[..msg.len()], msg);
898+ assert_eq!(bytes[msg.len()], 0x80);
899+ assert_eq!(
900+ u64::from_be_bytes(bytes[56..64].try_into().unwrap()),
901+ ((64 + msg.len()) as u64) * 8
902+ );
724903 }
725904
726905 #[test]
@@ -733,12 +912,8 @@ mod tests {
733912 let words: Vec<Vec<u8>> = (0..16)
734913 .map(|i| format!("cand{:06}", i).into_bytes())
735914 .collect();
736- let mut inputs = Vec::new();
737- for w in &words {
738- inputs.extend_from_slice(&candidate_inputs(w, salt));
739- }
740- let out = crk.run_kernel(&inputs).expect("kernel must complete");
741- let pmks = assemble_pmks(&out);
915+ let pmks = crk.pmk_batch_gpu(&words, salt).expect("kernel must complete");
916+ assert_eq!(pmks.len(), words.len());
742917 for (w, k) in words.iter().zip(pmks.iter()) {
743918 let mut dk = [0u8; 40];
744919 crypto::pbkdf2_hmac_sha1(w, salt, 4096, &mut dk);
@@ -748,6 +923,33 @@ mod tests {
748923 }
749924 }
750925
926+ #[test]
927+ #[ignore = "perf bench: full crack-loop effective throughput"]
928+ fn crack_loop_effective_hps() {
929+ let Some(crk) = GpuCracker::try_new() else {
930+ eprintln!("no GPU adapter, skipping");
931+ return;
932+ };
933+ let target = synthetic_target("parafin", b"sup3r-secret", 2);
934+ const N: usize = 65536 * 6;
935+ let words: Vec<Vec<u8>> = (0..N).map(|i| format!("probe{i:09}").into_bytes()).collect();
936+ let mut it = words.into_iter();
937+ let stop = Arc::new(AtomicBool::new(false));
938+ let t0 = Instant::now();
939+ let found = crk.crack(&target, &mut it, &mut |_, _| {}, &stop);
940+ assert!(found.is_none());
941+ let wall = t0.elapsed().as_secs_f64();
942+ eprintln!(
943+ "full crack loop on {}: {:.0} H/s effective ({} candidates in {:.2}s)",
944+ crk.device_name(),
945+ N as f64 / wall,
946+ N,
947+ wall
948+ );
949+ // Sanity: effective must be within 4x of kernel-only, never CPU-slow.
950+ assert!(N as f64 / wall > 50_000.0, "effective throughput collapsed");
951+ }
952+
751953 #[test]
752954 fn gpu_finds_planted_pass() {
753955 let Some(crk) = GpuCracker::try_new() else {
@@ -783,55 +985,43 @@ mod tests {
783985 &stop,
784986 );
785987 assert_eq!(found.as_deref(), Some("sup3r-secret"));
786- // crack returns immediately at the match, possibly before the
787- // batch-end progress tick, so progress may be anything ≤ 65536.
988+ // crack returns at the hit batch, possibly before end-of-batch.
788989 assert!(last_done <= 65536, "progress reported {last_done}");
789990 assert!(last_hps >= 0.0);
790991 }
791992
792993 #[test]
793- fn gpu_agrees_with_crypto_verify_on_synthetic() {
794- let Some(_crk) = GpuCracker::try_new() else {
994+ fn gpu_finds_planted_pmkid() {
995+ let Some(crk) = GpuCracker::try_new() else {
795996 eprintln!("no GPU adapter, skipping");
796997 return;
797998 };
798- // The GPU path (kernel) for a batch containing the right pass must
799- // identify exactly the candidates crypto::verify accepts.
800- let crk = _crk;
801- let pass = b"sup3r-secret";
802- let target = synthetic_target("parafin", pass, 2);
803- let cands: Vec<Vec<u8>> = (0..64)
804- .map(|i| if i == 33 { pass.to_vec() } else { format!("zz{:07}", i).into_bytes() })
805- .collect();
806- let mut inputs = Vec::new();
807- for w in &cands {
808- inputs.extend_from_slice(&candidate_inputs(w, b"parafin"));
809- }
810- let out = crk.run_kernel(&inputs).expect("kernel");
811- let pmks = assemble_pmks(&out);
812- let mut hits = 0;
813- for (w, k) in cands.iter().zip(pmks.iter()) {
814- let gpu_hit = target_matches(&target, k);
815- let cpu_hit = crypto::verify(&target, w);
816- assert_eq!(gpu_hit, cpu_hit, "disagreement on {w:?}");
817- hits += gpu_hit as usize;
818- }
819- assert_eq!(hits, 1);
999+ let target = synthetic_pmkid("parafin", b"hunter2!!");
1000+ let words: Vec<Vec<u8>> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()];
1001+ let mut it = words.into_iter();
1002+ let stop = Arc::new(AtomicBool::new(false));
1003+ let found = crk.crack(&target, &mut it, &mut |_, _| {}, &stop);
1004+ assert_eq!(found.as_deref(), Some("hunter2!!"));
8201005 }
8211006
8221007 #[test]
823- fn pmk64_benchmark_hps() {
1008+ fn gpu_rejects_wrong_pass_and_routes_kv3() {
8241009 let Some(crk) = GpuCracker::try_new() else {
825- eprintln!("no GPU adapter, skipping benchmark");
1010+ eprintln!("no GPU adapter, skipping");
8261011 return;
8271012 };
828- let hps = crk.measured_hps().expect("kernel must succeed");
829- eprintln!(
830- "GPU PBKDF2-WPA2 throughput on {}: {:.0} H/s",
831- crk.device_name(),
832- hps
833- );
834- assert!(hps > 1000.0, "suspiciously slow: {hps} H/s");
1013+ // Wrong candidate must NOT trip the on-device verifier.
1014+ let target = synthetic_target("parafin", b"sup3r-secret", 2);
1015+ let words: Vec<Vec<u8>> = (0..64).map(|i| format!("zz{:07}", i).into_bytes()).collect();
1016+ let mut it = words.into_iter();
1017+ let stop = Arc::new(AtomicBool::new(false));
1018+ assert!(crk.crack(&target, &mut it, &mut |_, _| {}, &stop).is_none());
1019+ // key_ver 3 (AES-CMAC) is not expressible in the SHA1 shader.
1020+ let kv3 = synthetic_target("parafin", b"sup3r-secret", 3);
1021+ assert!(!gpu_verifiable(&kv3));
1022+ // ...and long ESSIDs (spill the one-block U message) route to CPU.
1023+ let long = synthetic_target(&"s".repeat(52), b"sup3r-secret", 2);
1024+ assert!(!gpu_verifiable(&long));
8351025 }
8361026
8371027 #[test]
@@ -847,7 +1037,7 @@ mod tests {
8471037 .collect();
8481038 let mut it = words.into_iter();
8491039 let stop = Arc::new(AtomicBool::new(false));
850- let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop);
1040+ let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop, None);
8511041 assert_eq!(found.as_deref(), Some("sup3r-secret"));
8521042 }
8531043
@@ -865,7 +1055,7 @@ mod tests {
8651055 let words: Vec<Vec<u8>> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()];
8661056 let mut it = words.into_iter();
8671057 let stop = Arc::new(AtomicBool::new(false));
868- let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop);
1058+ let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop, None);
8691059 assert_eq!(found.as_deref(), Some("hunter2!!"));
8701060 }
8711061
@@ -876,7 +1066,7 @@ mod tests {
8761066 let words: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();
8771067 let mut it = words.into_iter();
8781068 let stop = Arc::new(AtomicBool::new(true));
879- assert!(cpu_crack(&target, &mut it, &mut |_, _| {}, &stop).is_none());
1069+ assert!(cpu_crack(&target, &mut it, &mut |_, _| {}, &stop, None).is_none());
8801070 if let Some(crk) = GpuCracker::try_new() {
8811071 let words2: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();
8821072 let mut it2 = words2.into_iter();
@@ -884,4 +1074,3 @@ mod tests {
8841074 }
8851075 }
8861076 }
887-
src/pbkdf2.wgslmodified+272 -160
@@ -1,38 +1,49 @@
1-// PBKDF2-HMAC-SHA1 inner-loop kernel for WPA2-PSK cracking (WGSL).
1+// PBKDF2-HMAC-SHA1 full-pipeline kernel for WPA2-PSK cracking (WGSL).
22 //
3-// The host precomputes, per candidate passphrase P and fixed salt (ESSID):
4-// ipad_state = SHA1 state after absorbing (P^ipad) || salt (5×u32)
5-// opad_state = SHA1 state after absorbing (P^opad) || 0x00*44 (5×u32)
6-// u1 = digest words of HMAC(P, salt||INT32BE(1)) (5×u32, BE)
7-// u2 = digest words of HMAC(P, salt||INT32BE(2)) (5×u32, BE)
3+// Per candidate the shader does EVERYTHING (host only packs raw bytes):
4+// 1. HMAC key midstates from the passphrase (2 compresses),
5+// 2. U1/U2 for both PBKDF2 blocks from host-precomputed padded messages
6+// (salt||INT32BE(1|2) — constant across candidates, passed via params),
7+// 3. the 4095-iteration chained HMAC loop (registers only),
8+// 4. the verify epilogue: PTK-KCK HMAC + EAPOL MIC compare (handshake)
9+// or PMKID compare — hit slot readback instead of streaming PMKs.
810 //
9-// Each invocation continues the PBKDF2 loop from iteration 2 to 4096 for both
10-// 20-byte blocks:
11-// U_i = HMAC_via_midstates(U_{i-1}); T ^= U_i
12-// HMAC_via_midstates(x) with a 20-byte message is exactly two SHA1 compresses:
13-// inner = compress(ipad_state, x||0x80||0x00*35||0x000002dc)
14-// outer = compress(opad_state, inner||0x80||0x00*35||0x00000294)
15-// Emit per candidate 40 bytes: T1||T2 (PBKDF2 dkLen=40); the host slices
16-// PMK = T1 || T2[0..12].
11+// Verify messages arrive PRE-PADDED in params (they are constant per
12+// target): sha1 padding appended AFTER an implicit 64-byte HMAC pad
13+// prefix, i.e. total message length = 64 + msg_len.
14+//
15+// Candidate wire format: 16 u32 per candidate, the password bytes packed
16+// big-endian and zero-padded (passphrases are 8..=63 so they never spill
17+// the 64-byte HMAC key block).
1718
1819 struct Params {
19- // (iteration_count << 1) | cmac_flag. iteration_count is the PBKDF2 c
20- // value (4096); the kernel runs c-1 chained rounds after U1/U2.
21- // cmac_flag is informational (host uses it to pick the reference path in
22- // tests); MIC computation always happens on the host.
23- flags: u32,
20+ flags: u32, // (iteration_count << 1)
21+ is_pmkid: u32, // 1 = compare blk1 HMAC against mic (PMKID path)
22+ n_blk1: u32, // padded 64-byte blocks in blk1
23+ n_blk2: u32, // padded blocks in blk2 (handshake MIC message)
24+ n: u32, // candidate count in this dispatch
2425 pad0: u32,
2526 pad1: u32,
2627 pad2: u32,
28+ u1_msg: array<u32, 16>,
29+ u2_msg: array<u32, 16>,
30+ blk1: array<u32, 48>, // PMKID msg (1 blk) or PTK-PRF msg (2 blk)
31+ blk2: array<u32, 48>, // zeroed EAPOL frame (2..3 blk); unused for PMKID
32+ mic: array<u32, 4>, // target MIC / PMKID words (BE)
2733 }
2834
29-@group(0) @binding(0) var<uniform> params: Params;
30-@group(0) @binding(1) var<storage, read> midstates: array<u32>; // 20 u32 / candidate
31-@group(0) @binding(2) var<storage, read_write> outputs: array<u32>; // 10 u32 / candidate
35+@group(0) @binding(0) var<storage, read> params: Params;
36+@group(0) @binding(1) var<storage, read> candidates: array<u32>; // 16 u32 / cand
37+@group(0) @binding(2) var<storage, read_write> outputs: array<u32>; // 10 u32 / cand (pmk_out only)
38+@group(0) @binding(3) var<storage, read_write> hits: array<atomic<u32>>; // [0]=flag [1]=gid
39+
40+const IV: array<u32, 5u> = array<u32, 5u>(0x67452301u, 0xefcdab89u, 0x98badcfeu, 0x10325476u, 0xc3d2e1f0u);
3241
3342 // One SHA1 compression: state (5×u32) over exactly one 64-byte block.
34-// All 80 rounds are unrolled: dynamic array indexing would demote
35-// w[80] to scratch memory and multiply every compress by memory ops.
43+// All 80 rounds unrolled (dynamic indexing would demote w[] to scratch).
44+// Round functions use hashcat's minimal-op forms; the message schedule
45+// uses the doubled-step (rotl2) recurrence for t>=32 — bit-identical to
46+// the standard recurrence but with roughly half the serial depth.
3647 fn sha1_compress(state_in: ptr<function, array<u32, 5u>>, block: ptr<function, array<u32, 16u>>) {
3748 let w0 = (*block)[0];
3849 let w1 = (*block)[1];
@@ -66,79 +77,79 @@ fn sha1_compress(state_in: ptr<function, array<u32, 5u>>, block: ptr<function, a
6677 let w29 = (((w26 ^ w21 ^ w15 ^ w13) << 1u) | ((w26 ^ w21 ^ w15 ^ w13) >> 31u));
6778 let w30 = (((w27 ^ w22 ^ w16 ^ w14) << 1u) | ((w27 ^ w22 ^ w16 ^ w14) >> 31u));
6879 let w31 = (((w28 ^ w23 ^ w17 ^ w15) << 1u) | ((w28 ^ w23 ^ w17 ^ w15) >> 31u));
69- let w32 = (((w29 ^ w24 ^ w18 ^ w16) << 1u) | ((w29 ^ w24 ^ w18 ^ w16) >> 31u));
70- let w33 = (((w30 ^ w25 ^ w19 ^ w17) << 1u) | ((w30 ^ w25 ^ w19 ^ w17) >> 31u));
71- let w34 = (((w31 ^ w26 ^ w20 ^ w18) << 1u) | ((w31 ^ w26 ^ w20 ^ w18) >> 31u));
72- let w35 = (((w32 ^ w27 ^ w21 ^ w19) << 1u) | ((w32 ^ w27 ^ w21 ^ w19) >> 31u));
73- let w36 = (((w33 ^ w28 ^ w22 ^ w20) << 1u) | ((w33 ^ w28 ^ w22 ^ w20) >> 31u));
74- let w37 = (((w34 ^ w29 ^ w23 ^ w21) << 1u) | ((w34 ^ w29 ^ w23 ^ w21) >> 31u));
75- let w38 = (((w35 ^ w30 ^ w24 ^ w22) << 1u) | ((w35 ^ w30 ^ w24 ^ w22) >> 31u));
76- let w39 = (((w36 ^ w31 ^ w25 ^ w23) << 1u) | ((w36 ^ w31 ^ w25 ^ w23) >> 31u));
77- let w40 = (((w37 ^ w32 ^ w26 ^ w24) << 1u) | ((w37 ^ w32 ^ w26 ^ w24) >> 31u));
78- let w41 = (((w38 ^ w33 ^ w27 ^ w25) << 1u) | ((w38 ^ w33 ^ w27 ^ w25) >> 31u));
79- let w42 = (((w39 ^ w34 ^ w28 ^ w26) << 1u) | ((w39 ^ w34 ^ w28 ^ w26) >> 31u));
80- let w43 = (((w40 ^ w35 ^ w29 ^ w27) << 1u) | ((w40 ^ w35 ^ w29 ^ w27) >> 31u));
81- let w44 = (((w41 ^ w36 ^ w30 ^ w28) << 1u) | ((w41 ^ w36 ^ w30 ^ w28) >> 31u));
82- let w45 = (((w42 ^ w37 ^ w31 ^ w29) << 1u) | ((w42 ^ w37 ^ w31 ^ w29) >> 31u));
83- let w46 = (((w43 ^ w38 ^ w32 ^ w30) << 1u) | ((w43 ^ w38 ^ w32 ^ w30) >> 31u));
84- let w47 = (((w44 ^ w39 ^ w33 ^ w31) << 1u) | ((w44 ^ w39 ^ w33 ^ w31) >> 31u));
85- let w48 = (((w45 ^ w40 ^ w34 ^ w32) << 1u) | ((w45 ^ w40 ^ w34 ^ w32) >> 31u));
86- let w49 = (((w46 ^ w41 ^ w35 ^ w33) << 1u) | ((w46 ^ w41 ^ w35 ^ w33) >> 31u));
87- let w50 = (((w47 ^ w42 ^ w36 ^ w34) << 1u) | ((w47 ^ w42 ^ w36 ^ w34) >> 31u));
88- let w51 = (((w48 ^ w43 ^ w37 ^ w35) << 1u) | ((w48 ^ w43 ^ w37 ^ w35) >> 31u));
89- let w52 = (((w49 ^ w44 ^ w38 ^ w36) << 1u) | ((w49 ^ w44 ^ w38 ^ w36) >> 31u));
90- let w53 = (((w50 ^ w45 ^ w39 ^ w37) << 1u) | ((w50 ^ w45 ^ w39 ^ w37) >> 31u));
91- let w54 = (((w51 ^ w46 ^ w40 ^ w38) << 1u) | ((w51 ^ w46 ^ w40 ^ w38) >> 31u));
92- let w55 = (((w52 ^ w47 ^ w41 ^ w39) << 1u) | ((w52 ^ w47 ^ w41 ^ w39) >> 31u));
93- let w56 = (((w53 ^ w48 ^ w42 ^ w40) << 1u) | ((w53 ^ w48 ^ w42 ^ w40) >> 31u));
94- let w57 = (((w54 ^ w49 ^ w43 ^ w41) << 1u) | ((w54 ^ w49 ^ w43 ^ w41) >> 31u));
95- let w58 = (((w55 ^ w50 ^ w44 ^ w42) << 1u) | ((w55 ^ w50 ^ w44 ^ w42) >> 31u));
96- let w59 = (((w56 ^ w51 ^ w45 ^ w43) << 1u) | ((w56 ^ w51 ^ w45 ^ w43) >> 31u));
97- let w60 = (((w57 ^ w52 ^ w46 ^ w44) << 1u) | ((w57 ^ w52 ^ w46 ^ w44) >> 31u));
98- let w61 = (((w58 ^ w53 ^ w47 ^ w45) << 1u) | ((w58 ^ w53 ^ w47 ^ w45) >> 31u));
99- let w62 = (((w59 ^ w54 ^ w48 ^ w46) << 1u) | ((w59 ^ w54 ^ w48 ^ w46) >> 31u));
100- let w63 = (((w60 ^ w55 ^ w49 ^ w47) << 1u) | ((w60 ^ w55 ^ w49 ^ w47) >> 31u));
101- let w64 = (((w61 ^ w56 ^ w50 ^ w48) << 1u) | ((w61 ^ w56 ^ w50 ^ w48) >> 31u));
102- let w65 = (((w62 ^ w57 ^ w51 ^ w49) << 1u) | ((w62 ^ w57 ^ w51 ^ w49) >> 31u));
103- let w66 = (((w63 ^ w58 ^ w52 ^ w50) << 1u) | ((w63 ^ w58 ^ w52 ^ w50) >> 31u));
104- let w67 = (((w64 ^ w59 ^ w53 ^ w51) << 1u) | ((w64 ^ w59 ^ w53 ^ w51) >> 31u));
105- let w68 = (((w65 ^ w60 ^ w54 ^ w52) << 1u) | ((w65 ^ w60 ^ w54 ^ w52) >> 31u));
106- let w69 = (((w66 ^ w61 ^ w55 ^ w53) << 1u) | ((w66 ^ w61 ^ w55 ^ w53) >> 31u));
107- let w70 = (((w67 ^ w62 ^ w56 ^ w54) << 1u) | ((w67 ^ w62 ^ w56 ^ w54) >> 31u));
108- let w71 = (((w68 ^ w63 ^ w57 ^ w55) << 1u) | ((w68 ^ w63 ^ w57 ^ w55) >> 31u));
109- let w72 = (((w69 ^ w64 ^ w58 ^ w56) << 1u) | ((w69 ^ w64 ^ w58 ^ w56) >> 31u));
110- let w73 = (((w70 ^ w65 ^ w59 ^ w57) << 1u) | ((w70 ^ w65 ^ w59 ^ w57) >> 31u));
111- let w74 = (((w71 ^ w66 ^ w60 ^ w58) << 1u) | ((w71 ^ w66 ^ w60 ^ w58) >> 31u));
112- let w75 = (((w72 ^ w67 ^ w61 ^ w59) << 1u) | ((w72 ^ w67 ^ w61 ^ w59) >> 31u));
113- let w76 = (((w73 ^ w68 ^ w62 ^ w60) << 1u) | ((w73 ^ w68 ^ w62 ^ w60) >> 31u));
114- let w77 = (((w74 ^ w69 ^ w63 ^ w61) << 1u) | ((w74 ^ w69 ^ w63 ^ w61) >> 31u));
115- let w78 = (((w75 ^ w70 ^ w64 ^ w62) << 1u) | ((w75 ^ w70 ^ w64 ^ w62) >> 31u));
116- let w79 = (((w76 ^ w71 ^ w65 ^ w63) << 1u) | ((w76 ^ w71 ^ w65 ^ w63) >> 31u));
80+ let w32 = (((w26 ^ w16 ^ w4 ^ w0) << 2u) | ((w26 ^ w16 ^ w4 ^ w0) >> 30u));
81+ let w33 = (((w27 ^ w17 ^ w5 ^ w1) << 2u) | ((w27 ^ w17 ^ w5 ^ w1) >> 30u));
82+ let w34 = (((w28 ^ w18 ^ w6 ^ w2) << 2u) | ((w28 ^ w18 ^ w6 ^ w2) >> 30u));
83+ let w35 = (((w29 ^ w19 ^ w7 ^ w3) << 2u) | ((w29 ^ w19 ^ w7 ^ w3) >> 30u));
84+ let w36 = (((w30 ^ w20 ^ w8 ^ w4) << 2u) | ((w30 ^ w20 ^ w8 ^ w4) >> 30u));
85+ let w37 = (((w31 ^ w21 ^ w9 ^ w5) << 2u) | ((w31 ^ w21 ^ w9 ^ w5) >> 30u));
86+ let w38 = (((w32 ^ w22 ^ w10 ^ w6) << 2u) | ((w32 ^ w22 ^ w10 ^ w6) >> 30u));
87+ let w39 = (((w33 ^ w23 ^ w11 ^ w7) << 2u) | ((w33 ^ w23 ^ w11 ^ w7) >> 30u));
88+ let w40 = (((w34 ^ w24 ^ w12 ^ w8) << 2u) | ((w34 ^ w24 ^ w12 ^ w8) >> 30u));
89+ let w41 = (((w35 ^ w25 ^ w13 ^ w9) << 2u) | ((w35 ^ w25 ^ w13 ^ w9) >> 30u));
90+ let w42 = (((w36 ^ w26 ^ w14 ^ w10) << 2u) | ((w36 ^ w26 ^ w14 ^ w10) >> 30u));
91+ let w43 = (((w37 ^ w27 ^ w15 ^ w11) << 2u) | ((w37 ^ w27 ^ w15 ^ w11) >> 30u));
92+ let w44 = (((w38 ^ w28 ^ w16 ^ w12) << 2u) | ((w38 ^ w28 ^ w16 ^ w12) >> 30u));
93+ let w45 = (((w39 ^ w29 ^ w17 ^ w13) << 2u) | ((w39 ^ w29 ^ w17 ^ w13) >> 30u));
94+ let w46 = (((w40 ^ w30 ^ w18 ^ w14) << 2u) | ((w40 ^ w30 ^ w18 ^ w14) >> 30u));
95+ let w47 = (((w41 ^ w31 ^ w19 ^ w15) << 2u) | ((w41 ^ w31 ^ w19 ^ w15) >> 30u));
96+ let w48 = (((w42 ^ w32 ^ w20 ^ w16) << 2u) | ((w42 ^ w32 ^ w20 ^ w16) >> 30u));
97+ let w49 = (((w43 ^ w33 ^ w21 ^ w17) << 2u) | ((w43 ^ w33 ^ w21 ^ w17) >> 30u));
98+ let w50 = (((w44 ^ w34 ^ w22 ^ w18) << 2u) | ((w44 ^ w34 ^ w22 ^ w18) >> 30u));
99+ let w51 = (((w45 ^ w35 ^ w23 ^ w19) << 2u) | ((w45 ^ w35 ^ w23 ^ w19) >> 30u));
100+ let w52 = (((w46 ^ w36 ^ w24 ^ w20) << 2u) | ((w46 ^ w36 ^ w24 ^ w20) >> 30u));
101+ let w53 = (((w47 ^ w37 ^ w25 ^ w21) << 2u) | ((w47 ^ w37 ^ w25 ^ w21) >> 30u));
102+ let w54 = (((w48 ^ w38 ^ w26 ^ w22) << 2u) | ((w48 ^ w38 ^ w26 ^ w22) >> 30u));
103+ let w55 = (((w49 ^ w39 ^ w27 ^ w23) << 2u) | ((w49 ^ w39 ^ w27 ^ w23) >> 30u));
104+ let w56 = (((w50 ^ w40 ^ w28 ^ w24) << 2u) | ((w50 ^ w40 ^ w28 ^ w24) >> 30u));
105+ let w57 = (((w51 ^ w41 ^ w29 ^ w25) << 2u) | ((w51 ^ w41 ^ w29 ^ w25) >> 30u));
106+ let w58 = (((w52 ^ w42 ^ w30 ^ w26) << 2u) | ((w52 ^ w42 ^ w30 ^ w26) >> 30u));
107+ let w59 = (((w53 ^ w43 ^ w31 ^ w27) << 2u) | ((w53 ^ w43 ^ w31 ^ w27) >> 30u));
108+ let w60 = (((w54 ^ w44 ^ w32 ^ w28) << 2u) | ((w54 ^ w44 ^ w32 ^ w28) >> 30u));
109+ let w61 = (((w55 ^ w45 ^ w33 ^ w29) << 2u) | ((w55 ^ w45 ^ w33 ^ w29) >> 30u));
110+ let w62 = (((w56 ^ w46 ^ w34 ^ w30) << 2u) | ((w56 ^ w46 ^ w34 ^ w30) >> 30u));
111+ let w63 = (((w57 ^ w47 ^ w35 ^ w31) << 2u) | ((w57 ^ w47 ^ w35 ^ w31) >> 30u));
112+ let w64 = (((w58 ^ w48 ^ w36 ^ w32) << 2u) | ((w58 ^ w48 ^ w36 ^ w32) >> 30u));
113+ let w65 = (((w59 ^ w49 ^ w37 ^ w33) << 2u) | ((w59 ^ w49 ^ w37 ^ w33) >> 30u));
114+ let w66 = (((w60 ^ w50 ^ w38 ^ w34) << 2u) | ((w60 ^ w50 ^ w38 ^ w34) >> 30u));
115+ let w67 = (((w61 ^ w51 ^ w39 ^ w35) << 2u) | ((w61 ^ w51 ^ w39 ^ w35) >> 30u));
116+ let w68 = (((w62 ^ w52 ^ w40 ^ w36) << 2u) | ((w62 ^ w52 ^ w40 ^ w36) >> 30u));
117+ let w69 = (((w63 ^ w53 ^ w41 ^ w37) << 2u) | ((w63 ^ w53 ^ w41 ^ w37) >> 30u));
118+ let w70 = (((w64 ^ w54 ^ w42 ^ w38) << 2u) | ((w64 ^ w54 ^ w42 ^ w38) >> 30u));
119+ let w71 = (((w65 ^ w55 ^ w43 ^ w39) << 2u) | ((w65 ^ w55 ^ w43 ^ w39) >> 30u));
120+ let w72 = (((w66 ^ w56 ^ w44 ^ w40) << 2u) | ((w66 ^ w56 ^ w44 ^ w40) >> 30u));
121+ let w73 = (((w67 ^ w57 ^ w45 ^ w41) << 2u) | ((w67 ^ w57 ^ w45 ^ w41) >> 30u));
122+ let w74 = (((w68 ^ w58 ^ w46 ^ w42) << 2u) | ((w68 ^ w58 ^ w46 ^ w42) >> 30u));
123+ let w75 = (((w69 ^ w59 ^ w47 ^ w43) << 2u) | ((w69 ^ w59 ^ w47 ^ w43) >> 30u));
124+ let w76 = (((w70 ^ w60 ^ w48 ^ w44) << 2u) | ((w70 ^ w60 ^ w48 ^ w44) >> 30u));
125+ let w77 = (((w71 ^ w61 ^ w49 ^ w45) << 2u) | ((w71 ^ w61 ^ w49 ^ w45) >> 30u));
126+ let w78 = (((w72 ^ w62 ^ w50 ^ w46) << 2u) | ((w72 ^ w62 ^ w50 ^ w46) >> 30u));
127+ let w79 = (((w73 ^ w63 ^ w51 ^ w47) << 2u) | ((w73 ^ w63 ^ w51 ^ w47) >> 30u));
117128 var a = (*state_in)[0];
118129 var b = (*state_in)[1];
119130 var c = (*state_in)[2];
120131 var d = (*state_in)[3];
121132 var e = (*state_in)[4];
122- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w0; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
123- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w1; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
124- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w2; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
125- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w3; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
126- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w4; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
127- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w5; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
128- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w6; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
129- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w7; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
130- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w8; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
131- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w9; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
132- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w10; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
133- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w11; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
134- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w12; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
135- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w13; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
136- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w14; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
137- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w15; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
138- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w16; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
139- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w17; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
140- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w18; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
141- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (~b & d)) + e + 0x5a827999u + w19; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
133+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w0; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
134+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w1; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
135+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w2; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
136+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w3; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
137+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w4; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
138+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w5; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
139+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w6; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
140+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w7; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
141+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w8; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
142+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w9; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
143+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w10; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
144+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w11; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
145+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w12; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
146+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w13; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
147+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w14; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
148+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w15; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
149+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w16; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
150+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w17; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
151+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w18; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
152+ { let tmp = ((a << 5u) | (a >> 27u)) + (d ^ (b & (c ^ d))) + e + 0x5a827999u + w19; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
142153 { 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; }
143154 { 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; }
144155 { 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; }
@@ -159,26 +170,26 @@ fn sha1_compress(state_in: ptr<function, array<u32, 5u>>, block: ptr<function, a
159170 { 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; }
160171 { 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; }
161172 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w39; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
162- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w40; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
163- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w41; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
164- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w42; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
165- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w43; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
166- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w44; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
167- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w45; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
168- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w46; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
169- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w47; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
170- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w48; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
171- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w49; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
172- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w50; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
173- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w51; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
174- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w52; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
175- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w53; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
176- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w54; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
177- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w55; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
178- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w56; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
179- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w57; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
180- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w58; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
181- { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) | (b & d) | (c & d)) + e + 0x8f1bbcdcu + w59; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
173+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w40; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
174+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w41; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
175+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w42; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
176+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w43; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
177+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w44; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
178+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w45; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
179+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w46; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
180+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w47; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
181+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w48; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
182+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w49; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
183+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w50; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
184+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w51; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
185+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w52; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
186+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w53; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
187+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w54; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
188+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w55; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
189+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w56; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
190+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w57; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
191+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w58; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
192+ { let tmp = ((a << 5u) | (a >> 27u)) + ((b & c) ^ (d & (b ^ c))) + e + 0x8f1bbcdcu + w59; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
182193 { 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; }
183194 { 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; }
184195 { 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; }
@@ -206,60 +217,102 @@ fn sha1_compress(state_in: ptr<function, array<u32, 5u>>, block: ptr<function, a
206217 (*state_in)[4] = (*state_in)[4] + e;
207218 }
208219
209-// Message block layout for HMAC of a 20-byte value after a 64-byte presalt
210-// midstate/absorbed prefix: x[0..5] || 0x80 || zeros || 32-bit BE bit-length.
211-fn hmac_block(u: ptr<function, array<u32, 5u>>, bitlen: u32) -> array<u32, 16u> {
212- var blk: array<u32, 16u>;
213- blk[0] = (*u)[0];
214- blk[1] = (*u)[1];
215- blk[2] = (*u)[2];
216- blk[3] = (*u)[3];
217- blk[4] = (*u)[4];
218- blk[5] = 0x80000000u;
219- for (var i = 6u; i < 15u; i = i + 1u) {
220- blk[i] = 0u;
221- }
222- blk[15] = bitlen;
223- return blk;
220+// Build the standard outer-leg block for HMAC whose inner digest is `h`:
221+// h[0..5] || 0x80 || zeros || bitlen (always 672 = (64+20)*8 here).
222+fn outer_block(h: array<u32, 5u>) -> array<u32, 16u> {
223+ return array<u32, 16u>(h[0], h[1], h[2], h[3], h[4], 0x80000000u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 672u);
224224 }
225225
226-// U = HMAC(pad midstates, U) — two compressions. The message seen by each leg
227-// (after the absorbed 64-byte pad prefix) is 64 + 20 = 84 bytes = 672 bits.
228-fn hmac_mid(u: ptr<function, array<u32, 5u>>, ipad: ptr<function, array<u32, 5u>>, opad: ptr<function, array<u32, 5u>>) {
229- var in_state: array<u32, 5u> = *ipad;
230- var blk = hmac_block(u, 672u);
231- sha1_compress(&in_state, &blk);
226+// U1/U2: inner compress over the host-precomputed padded salt||counter
227+// message from the ipad midstate, outer over the opad midstate.
228+fn hmac_first(ipad: array<u32, 5u>, opad: array<u32, 5u>, msg: array<u32, 16u>) -> array<u32, 5u> {
229+ var st = ipad;
230+ var m = msg;
231+ sha1_compress(&st, &m);
232+ var st2 = opad;
233+ var ob = outer_block(st);
234+ sha1_compress(&st2, &ob);
235+ return st2;
236+}
232237
233- var out_state: array<u32, 5u> = *opad;
234- var blk2 = hmac_block(&in_state, 672u);
235- sha1_compress(&out_state, &blk2);
238+// One chained PBKDF2 iteration: U = HMAC(U) via the pad midstates.
239+fn hmac_mid(u: ptr<function, array<u32, 5u>>, ipad: ptr<function, array<u32, 5u>>, opad: ptr<function, array<u32, 5u>>) {
240+ var st = *ipad;
241+ var m = outer_block(*u);
242+ sha1_compress(&st, &m);
243+ var st2 = *opad;
244+ var ob = outer_block(st);
245+ sha1_compress(&st2, &ob);
246+ *u = st2;
247+}
236248
237- *u = out_state;
249+// HMAC over host-pre-padded message blocks (`which`: 0 = params.blk1,
250+// 1 = params.blk2), starting from the pad midstates. `n` <= 3.
251+fn hmac_padded(ipad: array<u32, 5u>, opad: array<u32, 5u>, which: u32, n: u32) -> array<u32, 5u> {
252+ var st = ipad;
253+ for (var b = 0u; b < n; b = b + 1u) {
254+ var m: array<u32, 16u>;
255+ for (var j = 0u; j < 16u; j = j + 1u) {
256+ m[j] = select(params.blk1[b * 16u + j], params.blk2[b * 16u + j], which == 1u);
257+ }
258+ sha1_compress(&st, &m);
259+ }
260+ var st2 = opad;
261+ var ob = outer_block(st);
262+ sha1_compress(&st2, &ob);
263+ return st2;
238264 }
239265
240-@compute @workgroup_size(64)
241-fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
242- let idx = gid.x;
243- if idx >= arrayLength(&outputs) / 10u {
244- return;
266+// Per-candidate HMAC pad midstates from the raw password key block.
267+fn key_midstates(base: u32) -> array<array<u32, 5u>, 2u> {
268+ var ib: array<u32, 16u>;
269+ var ob: array<u32, 16u>;
270+ for (var i = 0u; i < 16u; i = i + 1u) {
271+ let kb = candidates[base + i];
272+ ib[i] = kb ^ 0x36363636u;
273+ ob[i] = kb ^ 0x5c5c5c5cu;
245274 }
275+ var ipad = IV;
276+ sha1_compress(&ipad, &ib);
277+ var opad = IV;
278+ sha1_compress(&opad, &ob);
279+ return array<array<u32, 5u>, 2u>(ipad, opad);
280+}
246281
247- let base_in = idx * 20u;
248- var ipad: array<u32, 5u>;
249- var opad: array<u32, 5u>;
250- var u1: array<u32, 5u>;
251- var u2: array<u32, 5u>;
252- for (var i = 0u; i < 5u; i = i + 1u) {
253- ipad[i] = midstates[base_in + i];
254- opad[i] = midstates[base_in + 5u + i];
255- u1[i] = midstates[base_in + 10u + i];
256- u2[i] = midstates[base_in + 15u + i];
282+// HMAC pad midstates for an 8-word key (the PMK) or 4-word key (KCK):
283+// key words in w[0..word_count), rest of the 64-byte block zero — both
284+// folded into the pad XOR (x ^ 0 == x).
285+fn short_key_midstates(w0: u32, w1: u32, w2: u32, w3: u32, word_count: u32) -> array<array<u32, 5u>, 2u> {
286+ var ib: array<u32, 16u>;
287+ var ob: array<u32, 16u>;
288+ let ws = array<u32, 4u>(w0, w1, w2, w3);
289+ for (var i = 0u; i < 16u; i = i + 1u) {
290+ var kb = 0u;
291+ if i < word_count {
292+ kb = ws[i];
293+ }
294+ ib[i] = kb ^ 0x36363636u;
295+ ob[i] = kb ^ 0x5c5c5c5cu;
257296 }
297+ var ipad = IV;
298+ sha1_compress(&ipad, &ib);
299+ var opad = IV;
300+ sha1_compress(&opad, &ob);
301+ return array<array<u32, 5u>, 2u>(ipad, opad);
302+}
258303
259- let iterations = params.flags >> 1u;
304+// The PBKDF2 core: midstates -> U1/U2 -> 4095 chained iterations.
305+// Returns PMK words (BE): t1[0..5] || t2[0..3] packed in a 16-word block.
306+fn pbkdf2_chain(base: u32) -> array<u32, 16u> {
307+ let mids = key_midstates(base);
308+ var ipad = mids[0];
309+ var opad = mids[1];
310+ var u1 = hmac_first(ipad, opad, params.u1_msg);
311+ var u2 = hmac_first(ipad, opad, params.u2_msg);
260312
261313 var t1 = u1;
262314 var t2 = u2;
315+ let iterations = params.flags >> 1u;
263316 for (var i = 1u; i < iterations; i = i + 1u) {
264317 hmac_mid(&u1, &ipad, &opad);
265318 t1[0] = t1[0] ^ u1[0];
@@ -268,18 +321,77 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
268321 t1[3] = t1[3] ^ u1[3];
269322 t1[4] = t1[4] ^ u1[4];
270323 hmac_mid(&u2, &ipad, &opad);
324+ // Tail cut: PMK needs only t2[10..12] bytes → never accumulate
325+ // t2[3]/t2[4] (u2 itself stays complete for the chain).
271326 t2[0] = t2[0] ^ u2[0];
272327 t2[1] = t2[1] ^ u2[1];
273328 t2[2] = t2[2] ^ u2[2];
274- t2[3] = t2[3] ^ u2[3];
275- t2[4] = t2[4] ^ u2[4];
276329 }
330+ var pk: array<u32, 16u>;
331+ for (var i = 0u; i < 5u; i = i + 1u) { pk[i] = t1[i]; }
332+ for (var i = 0u; i < 3u; i = i + 1u) { pk[5u + i] = t2[i]; }
333+ for (var i = 8u; i < 16u; i = i + 1u) { pk[i] = 0u; }
334+ return pk;
335+}
336+
337+@compute @workgroup_size(256)
338+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
339+ let idx = gid.x;
340+ if idx >= params.n {
341+ return;
342+ }
343+ let base = idx * 16u;
344+ var pk = pbkdf2_chain(base);
277345
278- let base_out = idx * 10u;
279- for (var i = 0u; i < 5u; i = i + 1u) {
280- outputs[base_out + i] = t1[i];
346+ // Epilogue: match the candidate's PMK against the capture on-device.
347+ // PMK midstates (32-byte key: all 8 words of pk[0..8]).
348+ var pk_ib: array<u32, 16u>;
349+ var pk_ob: array<u32, 16u>;
350+ for (var i = 0u; i < 16u; i = i + 1u) {
351+ var kb = 0u;
352+ if i < 8u {
353+ kb = pk[i];
354+ }
355+ pk_ib[i] = kb ^ 0x36363636u;
356+ pk_ob[i] = kb ^ 0x5c5c5c5cu;
357+ }
358+ var pk_ipad = IV;
359+ sha1_compress(&pk_ipad, &pk_ib);
360+ var pk_opad = IV;
361+ sha1_compress(&pk_opad, &pk_ob);
362+
363+ let val1 = hmac_padded(pk_ipad, pk_opad, 0u, params.n_blk1);
364+
365+ var matched = false;
366+ if params.is_pmkid == 1u {
367+ matched = val1[0] == params.mic[0] && val1[1] == params.mic[1]
368+ && val1[2] == params.mic[2] && val1[3] == params.mic[3];
369+ } else {
370+ // KCK = first 4 words; MIC = HMAC-SHA1(KCK, zeroed EAPOL).
371+ let kmids = short_key_midstates(val1[0], val1[1], val1[2], val1[3], 4u);
372+ let mval = hmac_padded(kmids[0], kmids[1], 1u, params.n_blk2);
373+ matched = mval[0] == params.mic[0] && mval[1] == params.mic[1]
374+ && mval[2] == params.mic[2] && mval[3] == params.mic[3];
375+ }
376+ if matched {
377+ // Recoverable word is whatever the flag write publishes; the host
378+ // reads both words after full dispatch completion (no torn race).
379+ atomicStore(&hits[1u], idx);
380+ atomicStore(&hits[0u], 1u);
381+ }
382+}
383+
384+// Rainbow-build entry: PMK out (no verify epilogue).
385+@compute @workgroup_size(256)
386+fn pmk_out(@builtin(global_invocation_id) gid: vec3<u32>) {
387+ let idx = gid.x;
388+ if idx >= params.n {
389+ return;
281390 }
282- for (var i = 0u; i < 5u; i = i + 1u) {
283- outputs[base_out + 5u + i] = t2[i];
391+ let base = idx * 16u;
392+ let pk = pbkdf2_chain(base);
393+ let base_out = idx * 10u;
394+ for (var i = 0u; i < 8u; i = i + 1u) {
395+ outputs[base_out + i] = pk[i];
284396 }
285397 }