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 @@
1 //! GPU-accelerated WPA2-PSK cracker (wgpu compute, see pbkdf2.wgsl) plus a1 //! GPU-accelerated WPA2-PSK cracker (wgpu compute, see pbkdf2.wgsl) plus a
2 //! CPU streaming cracker of the same shape.2 //! CPU streaming cracker of the same shape.
3 //!3 //!
4-//! Algorithm: the host computes per candidate the SHA1 midstates for the two4+//! Full-pipeline architecture: the host packs raw candidate bytes only.
5-//! HMAC pad prefixes (key = passphrase, salt = ESSID absorbed in the ipad5+//! The kernel itself derives the HMAC pad midstates (2 compressions),
6-//! leg) and the first PBKDF2 outputs U1/U2 for both 20-byte blocks. The GPU6+//! computes U1/U2 from host-precomputed padded salt messages, runs the
7-//! then executes the remaining 4095 chained HMAC rounds per block and emits7+//! 4095-iteration chained HMAC loop (registers only), and performs the
8-//! T1||T2 (40 bytes): PMK = T1 || T2[0..12]. PTK + MIC are derived per PMK on8+//! verify EPILOGUE on-device (PTK-KCK HMAC + EAPOL MIC compare, or PMKID
9-//! the host — that is cheap relative to the 4096 HMACs it replaces. For9+//! compare). Per batch the host reads back a 16-byte hit slot instead of
10-//! key_ver 3 targets the MIC is AES-CMAC (bus duty: PTK+KCK never leave the10+//! batch×40B of PMKs — the previous midstate/upload + CPU MIC phases were
11-//! host side of the reference implementation).11+//! the pipeline's throughput ceiling.
12-12+//!
13-use std::num::NonZeroU64;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+
14 use std::sync::Arc;16 use std::sync::Arc;
15 use std::sync::atomic::{AtomicBool, Ordering};17 use std::sync::atomic::{AtomicBool, Ordering};
16 use std::time::{Duration, Instant};18 use std::time::{Duration, Instant};
17 19
18-/// Pack the first 64 message bytes into the 16 FIPS SHA1 message words
19-/// (big-endian parse, per FIPS 180-1).
20-fn pack16(bytes: &[u8]) -> [u32; 16] {
21- debug_assert!(bytes.len() >= 64);
22- let mut out = [0u32; 16];
23- for (i, w) in out.iter_mut().enumerate() {
24- *w = u32::from_be_bytes([bytes[4 * i], bytes[4 * i + 1], bytes[4 * i + 2], bytes[4 * i + 3]]);
25- }
26- out
27-}
28-
29 use crate::crypto::{self, CrackTarget};20 use crate::crypto::{self, CrackTarget};
21+use crate::rainbow;
30 #[cfg(test)]22 #[cfg(test)]
31 use crate::common::MacAddr;23 use crate::common::MacAddr;
32 24
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+
33 const BATCH: u32 = 1 << 16;59 const BATCH: u32 = 1 << 16;
34-const WORKGROUP_SIZE: u32 = 64;60+const WORKGROUP_SIZE: u32 = 256;
35 const ITERATIONS: u32 = 4096;61 const ITERATIONS: u32 = 4096;
36-const U32_PER_CAND_IN: usize = 20; // ipad(5) opad(5) u1(5) u2(5)62+/// Candidate wire format: password bytes packed BE into 16 u32 (zero pad).
37-const U32_PER_CAND_OUT: usize = 10; // T1(5) T2(5)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+}
38 80
39-const K: [u32; 4] = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];81+impl GpuTargetCtx {
40-const IV: [u32; 5] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];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+}
41 90
42-// ---------------------------------------------------------------------------91+/// Big-endian pack of `bytes` into u32 words (SHA1's message-word view).
43-// Host-side SHA1 midstate helpers (mirror of the WGSL kernel).92+fn be_words(bytes: &[u8], out: &mut [u32]) {
44-// ---------------------------------------------------------------------------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+}
45 101
46-/// One FIPS 180-1 SHA1 compression over exactly one 64-byte block, starting102+/// FIPS-pad an HMAC message (following the implicit 64-byte pad prefix)
47-/// from a 5×u32 state. `block` holds the message words BE-parsed as the103+/// and pack into BE 64-byte-block words; returns (words, block count).
48-/// standard requires; states and the running chain stay in value domain104+fn padded_blocks(msg: &[u8]) -> (Vec<u32>, u32) {
49-/// end-to-end (this is also the WGSL kernel's domain).105+ let total_bits = ((64 + msg.len()) as u64) * 8;
50-fn compress5(state: &mut [u32; 5], block: &[u32; 16]) {106+ let mut v = msg.to_vec();
51- let mut w = [0u32; 80];107+ v.push(0x80);
52- w[..16].copy_from_slice(block);108+ while v.len() % 64 != 56 {
53- for t in 16..80 {109+ v.push(0);
54- let x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];110+ }
55- w[t] = x.rotate_left(1);111+ v.extend_from_slice(&total_bits.to_be_bytes());
56- }112+ let n_blocks = v.len() / 64;
57- let (mut a, mut b, mut c, mut d, mut e) = (state[0], state[1], state[2], state[3], state[4]);113+ let mut words = vec![0u32; n_blocks * 16];
58- for (t, &wt) in w.iter().enumerate() {114+ be_words(&v, &mut words);
59- let f = match t {115+ (words, n_blocks as u32)
60- 0..=19 => (b & c) | (!b & d),
61- 20..=39 | 60..=79 => b ^ c ^ d,
62- _ => (b & c) | (b & d) | (c & d),
63- };
64- let k = K[t / 20];
65- let temp = a
66- .rotate_left(5)
67- .wrapping_add(f)
68- .wrapping_add(e)
69- .wrapping_add(k)
70- .wrapping_add(wt);
71- e = d;
72- d = c;
73- c = b.rotate_left(30);
74- b = a;
75- a = temp;
76- }
77- state[0] = state[0].wrapping_add(a);
78- state[1] = state[1].wrapping_add(b);
79- state[2] = state[2].wrapping_add(c);
80- state[3] = state[3].wrapping_add(d);
81- state[4] = state[4].wrapping_add(e);
82 }116 }
83 117
84-/// Finalize a two-block SHA1 message given the state after block 1: place118+/// U-block message for PBKDF2: salt || INT32BE(idx), padded whole. Must
85-/// the tail, append padding/bit-length for the total (64 + tail.len()) byte119+/// fit one block (salt ≤ 51 bytes, incl. the 9 padding bytes).
86-/// message, compress once. Returns the 5-word state (the FIPS digest words).120+fn u_msg(salt: &[u8], idx: u32) -> [u32; 16] {
87-fn finalize_64(state_after_b1: &[u32; 5], tail: &[u8]) -> [u32; 5] {121+ let mut m = Vec::with_capacity(salt.len() + 4);
88- debug_assert!(tail.len() < 56);122+ m.extend_from_slice(salt);
89- let total_len = (64 + tail.len()) as u64;123+ m.extend_from_slice(&idx.to_be_bytes());
90- let mut blk = [0u8; 64];124+ let (words, n) = padded_blocks(&m);
91- blk[..tail.len()].copy_from_slice(tail);125+ debug_assert_eq!(n, 1, "salt must fit one SHA1 block");
92- blk[tail.len()] = 0x80;126+ let mut out = [0u32; 16];
93- blk[56..64].copy_from_slice(&(total_len * 8).to_be_bytes());127+ out.copy_from_slice(&words[..16]);
94- let mut st = *state_after_b1;128+ out
95- compress5(&mut st, &pack16(&blk));
96- st
97 }129 }
98 130
99-/// First PBKDF2 block digest for a candidate: U_idx = HMAC(P, salt ||131+/// Build the kernel verify context. None when the target is not
100-/// INT32BE(idx)), using precomputed pad midstates. Inner leg message is132+/// expressible in the SHA1-only shader: AES-CMIC handshake (key_ver 3),
101-/// (P^ipad) || salt || BE32(idx) (64 + salt.len() + 4 bytes), outer leg is133+/// truncated frame, or overlong ESSID (> 51 bytes — spills the U block).
102-/// (P^opad) || inner_digest (84 bytes, 672 bits).134+pub(crate) fn gpu_ctx(target: &CrackTarget) -> Option<GpuTargetCtx> {
103-fn hmac_first(ipad: &[u32; 5], opad: &[u32; 5], salt: &[u8], block_idx: u32) -> [u32; 5] {135+ let salt = target.essid().as_bytes();
104- let mut tail = [0u8; 68];136+ if salt.len() > 51 {
105- tail[..salt.len()].copy_from_slice(salt);137+ return None;
106- tail[salt.len()..salt.len() + 4].copy_from_slice(&block_idx.to_be_bytes());138+ }
107- let inner = finalize_64(ipad, &tail[..salt.len() + 4]);139+ let u1_msg = u_msg(salt, 1);
108-140+ let u2_msg = u_msg(salt, 2);
109- let mut outer_blk = [0u32; 16];141+ let mut blk1 = [0u32; 48];
110- outer_blk[..5].copy_from_slice(&inner);142+ let mut blk2 = [0u32; 48];
111- outer_blk[5] = 0x8000_0000;143+ let mut mic = [0u32; 4];
112- outer_blk[15] = 672;144+ let (is_pmkid, n_blk1, n_blk2) = match target {
113- let mut st = *opad;145+ CrackTarget::Pmkid(p) => {
114- compress5(&mut st, &outer_blk);146+ // PMKID = HMAC-SHA1-128(PMK, "PMK Name" || ap || sta)[0..16].
115- st147+ 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 })
116 }184 }
117 185
118-/// Mirror of the WGSL `hmac_mid`: one chained HMAC round (two compresses)186+/// Whether the GPU shader can verify this target (SHA1-family only; the
119-/// over the 20-byte value `u` given the pad midstates.187+/// AES-CMAC key_ver 3 path stays on the CPU cracker).
120-fn hmac_midstate_host(ipad: &[u32; 5], opad: &[u32; 5], u: &[u32; 5]) -> [u32; 5] {188+pub(crate) fn gpu_verifiable(target: &CrackTarget) -> bool {
121- let mut msg = [0u32; 16];189+ gpu_ctx(target).is_some()
122- msg[..5].copy_from_slice(u);
123- msg[5] = 0x8000_0000;
124- msg[15] = 672;
125-
126- let mut st = *ipad;
127- compress5(&mut st, &msg);
128-
129- let mut outer = [0u32; 16];
130- outer[..5].copy_from_slice(&st);
131- outer[5] = 0x8000_0000;
132- outer[15] = 672;
133-
134- let mut st2 = *opad;
135- compress5(&mut st2, &outer);
136- st2
137 }190 }
138 191
139-/// Per-candidate kernel inputs for one passphrase.192+/// Pack raw passphrases into the kernel wire format (BE words, zero pad).
140-fn candidate_inputs(pass: &[u8], salt: &[u8]) -> [u32; U32_PER_CAND_IN] {193+fn pack_candidates(words: &[Vec<u8>]) -> Vec<u32> {
141- debug_assert!((8..=63).contains(&pass.len()));194+ let mut out = vec![0u32; words.len() * U32_PER_CAND_IN];
142-195+ for (w, dst) in words.iter().zip(out.chunks_exact_mut(U32_PER_CAND_IN)) {
143- let mut ipad_blk = [0x36u8; 64];196+ be_words(w, dst);
144- let mut opad_blk = [0x5cu8; 64];197+ }
145- for (i, &b) in pass.iter().enumerate() {
146- ipad_blk[i] ^= b;
147- opad_blk[i] ^= b;
148- }
149-
150- let mut ipad = IV;
151- let mut opad = IV;
152- compress5(&mut ipad, &pack16(&ipad_blk));
153- compress5(&mut opad, &pack16(&opad_blk));
154-
155- // U_i = HMAC(P, salt || INT32BE(i)): inner leg via the ipad midstate,
156- // outer leg one compress over the opad midstate (also 84-byte total
157- // message → bit length 672, same layout as the chained rounds).
158- let u1 = hmac_first(&ipad, &opad, salt, 1);
159- let u2 = hmac_first(&ipad, &opad, salt, 2);
160-
161- let mut out = [0u32; U32_PER_CAND_IN];
162- out[..5].copy_from_slice(&ipad);
163- out[5..10].copy_from_slice(&opad);
164- out[10..15].copy_from_slice(&u1);
165- out[15..20].copy_from_slice(&u2);
166 out198 out
167 }199 }
168 200
169-/// Finish the two PBKDF2 blocks for one candidate entirely on the CPU201+/// One in-flight kernel dispatch. Buffers live in the pool; the handle
170-/// (reference + fallback path).202+/// carries what waiting/returning needs.
171-fn pmk_via_midstates(inputs: &[u32; U32_PER_CAND_IN]) -> [u8; 32] {203+struct PendingKernel {
172- let mut ipad = [0u32; 5];204+ read_buf: wgpu::Buffer,
173- let mut opad = [0u32; 5];205+ slot: usize,
174- let mut u1 = [0u32; 5];206+ rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
175- let mut u2 = [0u32; 5];207+ sub: wgpu::SubmissionIndex,
176- ipad.copy_from_slice(&inputs[..5]);208+ read_u32: usize,
177- opad.copy_from_slice(&inputs[5..10]);209+}
178- u1.copy_from_slice(&inputs[10..15]);210+
179- u2.copy_from_slice(&inputs[15..20]);211+/// Returns a pool slot on drop, on ANY exit path of `wait_kernel`.
180-212+struct SlotGuard<'a> {
181- let mut t1 = u1;213+ pool: &'a std::cell::RefCell<Option<KernelPool>>,
182- let mut t2 = u2;214+ slot: usize,
183- for _ in 1..ITERATIONS {215+}
184- u1 = hmac_midstate_host(&ipad, &opad, &u1);216+
185- for i in 0..5 {217+impl Drop for SlotGuard<'_> {
186- t1[i] ^= u1[i];218+ fn drop(&mut self) {
219+ if let Some(pool) = self.pool.borrow_mut().as_mut() {
220+ pool.free.push(self.slot);
187 }221 }
188- u2 = hmac_midstate_host(&ipad, &opad, &u2);222+ }
189- for i in 0..5 {223+}
190- t2[i] ^= u2[i];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);
191 }252 }
253+ pool
192 }254 }
193 255
194- let mut pmk_bytes = [0u8; 32];256+ fn push_slot(&mut self, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, cap: usize) {
195- for i in 0..5 {257+ let in_bytes = (cap * U32_PER_CAND_IN * 4) as u64;
196- pmk_bytes[i * 4..i * 4 + 4].copy_from_slice(&t1[i].to_be_bytes());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);
197 }304 }
198- for i in 0..3 {305+
199- pmk_bytes[20 + i * 4..20 + i * 4 + 4].copy_from_slice(&t2[i].to_be_bytes());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+ }
200 }316 }
201- pmk_bytes
202 }317 }
203 318
204-// ---------------------------------------------------------------------------319+/// Read-back scope of a dispatch: 16-byte hit slot (crack runs) or full
205-// GPU cracker320+/// PMK rows (rainbow-build runs).
206-// ---------------------------------------------------------------------------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+}
207 335
208 pub struct GpuCracker {336 pub struct GpuCracker {
209 device: wgpu::Device,337 device: wgpu::Device,
210 queue: wgpu::Queue,338 queue: wgpu::Queue,
211 pipeline: wgpu::ComputePipeline,339 pipeline: wgpu::ComputePipeline,
340+ pmk_pipeline: wgpu::ComputePipeline,
212 layout: wgpu::BindGroupLayout,341 layout: wgpu::BindGroupLayout,
213 name: String,342 name: String,
214 batch: u32,343 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>>,
215 }349 }
216 350
217 impl GpuCracker {351 impl GpuCracker {
@@ -229,7 +363,7 @@ impl GpuCracker {
229 .ok()?;363 .ok()?;
230 let info = adapter.get_info();364 let info = adapter.get_info();
231 let limits = adapter.limits();365 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.
233 let in_bytes = u64::from(BATCH) * (U32_PER_CAND_IN as u64) * 4;367 let in_bytes = u64::from(BATCH) * (U32_PER_CAND_IN as u64) * 4;
234 let out_bytes = u64::from(BATCH) * (U32_PER_CAND_OUT as u64) * 4;368 let out_bytes = u64::from(BATCH) * (U32_PER_CAND_OUT as u64) * 4;
235 if u64::from(limits.max_storage_buffer_binding_size) < in_bytes369 if u64::from(limits.max_storage_buffer_binding_size) < in_bytes
@@ -249,47 +383,35 @@ impl GpuCracker {
249 };383 };
250 let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?;384 let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?;
251 385
252- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {386+ let shader_desc = wgpu::ShaderModuleDescriptor {
253 label: Some("pbkdf2.wgsl"),387 label: Some("pbkdf2.wgsl"),
254 source: wgpu::ShaderSource::Wgsl(include_str!("pbkdf2.wgsl").into()),388 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+ };
256 397
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+ };
257 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {408 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
258 label: Some("pbkdf2-layout"),409 label: Some("pbkdf2-layout"),
259 entries: &[410 entries: &[
260- // params uniform411+ storage_entry(0, true), // params
261- wgpu::BindGroupLayoutEntry {412+ storage_entry(1, true), // candidates
262- binding: 0,413+ storage_entry(2, false), // outputs
263- visibility: wgpu::ShaderStages::COMPUTE,414+ storage_entry(3, false), // hits
264- ty: wgpu::BindingType::Buffer {
265- ty: wgpu::BufferBindingType::Uniform,
266- has_dynamic_offset: false,
267- min_binding_size: NonZeroU64::new(16),
268- },
269- count: None,
270- },
271- // midstates in
272- wgpu::BindGroupLayoutEntry {
273- binding: 1,
274- visibility: wgpu::ShaderStages::COMPUTE,
275- ty: wgpu::BindingType::Buffer {
276- ty: wgpu::BufferBindingType::Storage { read_only: true },
277- has_dynamic_offset: false,
278- min_binding_size: None,
279- },
280- count: None,
281- },
282- // outputs out
283- wgpu::BindGroupLayoutEntry {
284- binding: 2,
285- visibility: wgpu::ShaderStages::COMPUTE,
286- ty: wgpu::BindingType::Buffer {
287- ty: wgpu::BufferBindingType::Storage { read_only: false },
288- has_dynamic_offset: false,
289- min_binding_size: None,
290- },
291- count: None,
292- },
293 ],415 ],
294 });416 });
295 417
@@ -299,22 +421,28 @@ impl GpuCracker {
299 immediate_size: 0,421 immediate_size: 0,
300 });422 });
301 423
302- let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {424+ let make_pipeline = |label, entry| {
303- label: Some("pbkdf2-pipeline"),425+ device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
304- layout: Some(&pipeline_layout),426+ label: Some(label),
305- module: &shader,427+ layout: Some(&pipeline_layout),
306- entry_point: Some("main"),428+ module: &shader,
307- compilation_options: wgpu::PipelineCompilationOptions::default(),429+ entry_point: Some(entry),
308- cache: None,430+ compilation_options: wgpu::PipelineCompilationOptions::default(),
309- });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");
310 436
311 Some(GpuCracker {437 Some(GpuCracker {
312 device,438 device,
313 queue,439 queue,
314 pipeline,440 pipeline,
441+ pmk_pipeline,
315 layout,442 layout,
316 name: format!("{} ({:?})", info.name, info.backend),443 name: format!("{} ({:?})", info.name, info.backend),
317 batch: BATCH,444 batch: BATCH,
445+ pool: std::cell::RefCell::new(None),
318 })446 })
319 }447 }
320 448
@@ -322,98 +450,48 @@ impl GpuCracker {
322 self.name.clone()450 self.name.clone()
323 }451 }
324 452
325- /// Measured full-attack throughput for progress reporting (4096-iteration453+ /// Dispatch WITHOUT waiting: returns an in-flight handle so next-batch
326- /// batches). Runs 4 batches through `pmk_batch_gpu` and returns H/s.454+ /// packing overlaps the GPU. `params` is 140 u32 (see [`GpuTargetCtx`]);
327- #[cfg(test)]455+ /// `pipeline` picks main vs pmk_out. None for empty input.
328- fn measured_hps(&self) -> Option<f64> {456+ fn submit_kernel(
329- let pass: Vec<u8> = b"benchmk1".to_vec();457+ &self,
330- let salt = b"benchmark-ssid";458+ inputs: &[u32],
331- let mut inputs = Vec::with_capacity(self.batch as usize * U32_PER_CAND_IN);459+ params: &[u32],
332- for i in 0..self.batch as usize {460+ readback: Readback,
333- let mut w = pass.clone();461+ pmk_pipeline: bool,
334- w[0] = b'a' + (i % 26) as u8;462+ ) -> Option<PendingKernel> {
335- inputs.extend_from_slice(&candidate_inputs(&w, salt));
336- }
337- // Warm-up batch: covers one-time SPIR-V->ISA compile & memory init.
338- self.run_kernel(&inputs)?;
339- const BATCHES: u32 = 8;
340- let t0 = Instant::now();
341- let mut ok = true;
342- for _ in 0..BATCHES {
343- let mut inp = inputs.clone();
344- inp[0] = inp[0].wrapping_add(1);
345- ok &= self.run_kernel(&inp).is_some();
346- }
347- if !ok {
348- return None;
349- }
350- let secs = t0.elapsed().as_secs_f64();
351- Some(self.batch as f64 * f64::from(BATCHES) / secs)
352- }
353-
354- /// Run one kernel batch over `inputs` (n×20 u32, on the wire as u32 LE).
355- /// Returns the n×10 u32 output words, or None on device-lost/hang.
356- fn run_kernel(&self, inputs: &[u32]) -> Option<Vec<u32>> {
357 let n = inputs.len() / U32_PER_CAND_IN;463 let n = inputs.len() / U32_PER_CAND_IN;
358 if n == 0 {464 if n == 0 {
359- return Some(Vec::new());465+ return None;
360 }466 }
467+ debug_assert!(n <= self.batch as usize, "kernel buffers sized for one batch");
468+ debug_assert_eq!(params.len(), PARAM_U32);
361 469
362- let in_bytes = (inputs.len() * 4) as u64;470+ let slot = {
363- let out_u32 = n * U32_PER_CAND_OUT;471+ let mut pool = self.pool.borrow_mut();
364- let out_bytes = (out_u32 * 4) as u64;472+ let pool = pool.get_or_insert_with(|| {
365-473+ KernelPool::new(&self.device, &self.layout, self.batch as usize)
366- let in_buf = self.device.create_buffer(&wgpu::BufferDescriptor {474+ });
367- label: Some("midstates"),475+ pool.take(&self.device, &self.layout, self.batch as usize)
368- size: in_bytes.max(16),476+ };
369- usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,477+ let (in_buf, out_buf, hit_buf, read_buf, param_buf, bind_group) = {
370- mapped_at_creation: false,478+ let pool = self.pool.borrow();
371- });479+ let bufs = &pool.as_ref().expect("pool just created").bufs[slot];
372- let out_buf = self.device.create_buffer(&wgpu::BufferDescriptor {480+ (
373- label: Some("t1t2"),481+ bufs.in_buf.clone(),
374- size: out_bytes.max(16),482+ bufs.out_buf.clone(),
375- usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,483+ bufs.hit_buf.clone(),
376- mapped_at_creation: false,484+ bufs.read_buf.clone(),
377- });485+ bufs.param_buf.clone(),
378- let read_buf = self.device.create_buffer(&wgpu::BufferDescriptor {486+ bufs.bind_group.clone(),
379- label: Some("readback"),487+ )
380- size: out_bytes.max(16),488+ };
381- usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
382- mapped_at_creation: false,
383- });
384- let param_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
385- label: Some("params"),
386- size: 16,
387- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
388- mapped_at_creation: false,
389- });
390-
391- let flags: u32 = ITERATIONS << 1;
392- let params: [u32; 4] = [flags, 0, 0, 0];
393- self.queue
394- .write_buffer(&param_buf, 0, &u32s_as_bytes(&params));
395- let in_bytes_vec = u32s_as_bytes(inputs);
396- self.queue.write_buffer(&in_buf, 0, &in_bytes_vec);
397 489
398- let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {490+ self.queue.write_buffer(&param_buf, 0, u32s_as_bytes(params));
399- label: Some("pbkdf2-bg"),491+ self.queue.write_buffer(&hit_buf, 0, &[0u8; 16]);
400- layout: &self.layout,492+ self.queue.write_buffer(&in_buf, 0, u32s_as_bytes(inputs));
401- entries: &[
402- wgpu::BindGroupEntry {
403- binding: 0,
404- resource: param_buf.as_entire_binding(),
405- },
406- wgpu::BindGroupEntry {
407- binding: 1,
408- resource: in_buf.as_entire_binding(),
409- },
410- wgpu::BindGroupEntry {
411- binding: 2,
412- resource: out_buf.as_entire_binding(),
413- },
414- ],
415- });
416 493
494+ let read_u32 = readback.bytes() / 4;
417 let mut encoder = self495 let mut encoder = self
418 .device496 .device
419 .create_command_encoder(&wgpu::CommandEncoderDescriptor {497 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
@@ -424,24 +502,46 @@ impl GpuCracker {
424 label: Some("pbkdf2-pass"),502 label: Some("pbkdf2-pass"),
425 timestamp_writes: None,503 timestamp_writes: None,
426 });504 });
427- pass.set_pipeline(&self.pipeline);505+ pass.set_pipeline(if pmk_pipeline { &self.pmk_pipeline } else { &self.pipeline });
428 pass.set_bind_group(0, &bind_group, &[]);506 pass.set_bind_group(0, &bind_group, &[]);
507+ // Two candidates per thread.
429 pass.dispatch_workgroups(n.div_ceil(WORKGROUP_SIZE as usize) as u32, 1, 1);508 pass.dispatch_workgroups(n.div_ceil(WORKGROUP_SIZE as usize) as u32, 1, 1);
430 }509 }
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+ }
432 let sub = self.queue.submit([encoder.finish()]);522 let sub = self.queue.submit([encoder.finish()]);
433 523
434- // Wait for the shader with timeout; a hung/compute-heavy dispatch is
435- // reported so the caller can halve the batch.
436 let (tx, rx) = std::sync::mpsc::channel();524 let (tx, rx) = std::sync::mpsc::channel();
437 read_buf525 read_buf
438- .slice(..)526+ .slice(..readback.bytes() as u64)
439 .map_async(wgpu::MapMode::Read, move |res| {527 .map_async(wgpu::MapMode::Read, move |res| {
440 let _ = tx.send(res);528 let _ = tx.send(res);
441 });529 });
442 530
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+
443 let mut waited = Duration::ZERO;543 let mut waited = Duration::ZERO;
444- let step = Duration::from_millis(50);544+ let step = Duration::from_millis(8);
445 let limit = Duration::from_secs(30);545 let limit = Duration::from_secs(30);
446 loop {546 loop {
447 match self.device.poll(wgpu::PollType::Wait {547 match self.device.poll(wgpu::PollType::Wait {
@@ -472,9 +572,10 @@ impl GpuCracker {
472 }572 }
473 }573 }
474 574
475- let view = read_buf.slice(..).get_mapped_range().ok()?;575+ let bytes = read_u32 * 4;
476- let mut out = Vec::with_capacity(out_u32);576+ let view = read_buf.slice(..bytes as u64).get_mapped_range().ok()?;
477- for chunk in view[..(out_u32 * 4)].chunks_exact(4) {577+ let mut out = Vec::with_capacity(read_u32);
578+ for chunk in view[..bytes].chunks_exact(4) {
478 out.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));579 out.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
479 }580 }
480 drop(view);581 drop(view);
@@ -482,18 +583,37 @@ impl GpuCracker {
482 Some(out)583 Some(out)
483 }584 }
484 585
485- /// Compute PMKs for a word batch. Halves the batch size once on586+ /// Compute PMKs for a word batch (rainbow-table build; `pmk_out`
486- /// device-lost/timeout; on a repeated failure returns None.587+ /// pipeline). Halves the batch size once on device-lost/timeout; on a
487- fn pmk_batch_gpu(&self, words: &[Vec<u8>], salt: &[u8]) -> Option<Vec<[u8; 32]>> {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+
488 let mut cur: Vec<Vec<u8>> = words.to_vec();600 let mut cur: Vec<Vec<u8>> = words.to_vec();
489 let mut attempts = 0u8;601 let mut attempts = 0u8;
490 loop {602 loop {
491- let mut inputs = Vec::with_capacity(cur.len() * U32_PER_CAND_IN);603+ params[4] = cur.len() as u32;
492- for w in &cur {604+ let inputs = pack_candidates(&cur);
493- inputs.extend_from_slice(&candidate_inputs(w, salt));605+ let sub =
494- }606+ self.submit_kernel(&inputs, &params, Readback::Pmks(cur.len()), true)?;
495- if let Some(out) = self.run_kernel(&inputs) {607+ if let Some(out) = self.wait_kernel(sub) {
496- return Some(assemble_pmks(&out));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);
497 }617 }
498 attempts += 1;618 attempts += 1;
499 if attempts > 1 || cur.len() == 1 {619 if attempts > 1 || cur.len() == 1 {
@@ -504,9 +624,14 @@ impl GpuCracker {
504 }624 }
505 }625 }
506 626
507- /// Stream `words` through the GPU, calling `progress(done, hps)` once per627+ /// Stream `words` through the GPU, calling `progress(done, hps)` per
508- /// dispatched batch (also when a partial final batch ran). Honors `stop`628+ /// finished batch. Honors `stop` between batches. Returns the
509- /// between batches. Returns the passphrase on MIC match.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.
510 pub fn crack(635 pub fn crack(
511 &self,636 &self,
512 target: &CrackTarget,637 target: &CrackTarget,
@@ -514,122 +639,157 @@ impl GpuCracker {
514 progress: &mut dyn FnMut(u64, f64),639 progress: &mut dyn FnMut(u64, f64),
515 stop: &Arc<AtomicBool>,640 stop: &Arc<AtomicBool>,
516 ) -> Option<String> {641 ) -> Option<String> {
517- if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) {642+ let ctx = gpu_ctx(target)?;
518- return None;
519- }
520- let salt = target.essid().as_bytes();
521 let mut done = 0u64;643 let mut done = 0u64;
522 let started = Instant::now();644 let started = Instant::now();
523- let mut batch_cap = self.batch as usize;645+ let batch_cap = self.batch as usize;
524 646
525- loop {647+ fn collect(words: &mut dyn Iterator<Item = Vec<u8>>, cap: usize) -> Vec<Vec<u8>> {
526- if stop.load(Ordering::Relaxed) {648+ let mut batch: Vec<Vec<u8>> = Vec::with_capacity(cap);
527- return None;649+ while batch.len() < cap {
528- }
529- let mut batch: Vec<Vec<u8>> = Vec::with_capacity(batch_cap);
530- while batch.len() < batch_cap {
531 match words.next() {650 match words.next() {
532 Some(w) => batch.push(w),651 Some(w) => batch.push(w),
533 None => break,652 None => break,
534 }653 }
535 }654 }
536- if batch.is_empty() {655+ batch
537- return None;656+ }
538- }657+ let tick = |done: u64, started: Instant, progress: &mut dyn FnMut(u64, f64)| {
539-
540- let pmks = self.pmk_batch_gpu(&batch, salt)?;
541- // If the PMK batch shrunk because of a device hiccup the tail
542- // candidates are re-attempted below; keep bookkeeping accurate by
543- // scanning only what came back and re-queueing the rest.
544- let checked = pmks.len();
545- for (i, k) in pmks.iter().enumerate() {
546- done += 1;
547- if target_matches(target, k) {
548- return String::from_utf8(batch[i].clone()).ok();
549- }
550- }
551 let secs = started.elapsed().as_secs_f64().max(1e-6);658 let secs = started.elapsed().as_secs_f64().max(1e-6);
552 progress(done, done as f64 / secs);659 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+ };
553 668
554- if checked < batch.len() {669+ let mut cur_words = collect(words, batch_cap);
555- // Device hiccup path: retry the remaining words in smaller670+ if cur_words.is_empty() {
556- // chunks before continuing the stream.671+ return None;
557- let rest = batch[checked..].to_vec();672+ }
558- for chunk in rest.chunks(batch_cap.div_ceil(2).max(1)) {673+ let mut pending = Some(self.submit_kernel(
559- if stop.load(Ordering::Relaxed) {674+ &pack_candidates(&cur_words),
560- return None;675+ &ctx.params_words(cur_words.len() as u32),
561- }676+ Readback::Hits,
562- let pmks = self.pmk_batch_gpu(chunk, salt)?;677+ false,
563- for (i, k) in pmks.iter().enumerate() {678+ )?);
564- done += 1;679+
565- if target_matches(target, k) {680+ loop {
566- return String::from_utf8(chunk[i].clone()).ok();681+ if stop.load(Ordering::Relaxed) {
567- }682+ drain(pending.take());
568- }683+ return None;
569- let secs = started.elapsed().as_secs_f64().max(1e-6);
570- progress(done, done as f64 / secs);
571- }
572- batch_cap = batch_cap.div_ceil(2).max(1024);
573 }684 }
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);
574 }721 }
575 }722 }
576 }723 }
577 724
578-/// Little-endian byte serialization of a u32 slice for queue.write_buffer.725+/// Borrow a `&[u32]` as `&[u8]` for queue.write_buffer WITHOUT copying
579-/// The kernel reads raw u32s; on this CPU (x86-64, LE) this matches memory726+/// (65536-candidate batches make the old 5 MiB memcpy per dispatch
580-/// layout, and serializing keeps the wire format explicit for any host.727+/// measurable). Compiled only for little-endian hosts: the kernel's wire
581-fn u32s_as_bytes(v: &[u32]) -> Vec<u8> {728+/// format is native LE u32, matching memory layout.
582- let mut out = Vec::with_capacity(v.len() * 4);729+#[cfg(target_endian = "little")]
583- for &w in v {730+fn u32s_as_bytes(v: &[u32]) -> &[u8] {
584- out.extend_from_slice(&w.to_le_bytes());731+ // SAFETY: u32 has no padding and outlives the call; the kernel expects
585- }732+ // exactly these bytes.
586- out733+ unsafe { std::slice::from_raw_parts(v.as_ptr().cast::<u8>(), std::mem::size_of_val(v)) }
587 }734 }
588 735
589-fn assemble_pmks(out: &[u32]) -> Vec<[u8; 32]> {736+#[cfg(target_endian = "big")]
590- let n = out.len() / U32_PER_CAND_OUT;737+compile_error!("GPU cracker wire format assumes a little-endian host");
591- let mut pmks = Vec::with_capacity(n);738+
592- for c in 0..n {739+// ---------------------------------------------------------------------------
593- let mut pmk = [0u8; 32];740+// CPU cracker (reference-fallback path)
594- let row = &out[c * U32_PER_CAND_OUT..(c + 1) * U32_PER_CAND_OUT];741+// ---------------------------------------------------------------------------
595- for i in 0..8 {742+
596- pmk[i * 4..i * 4 + 4].copy_from_slice(&row[i].to_be_bytes());743+/// Per-word PMK sink for pure-CPU cracks (per-SSID PMK cache population):
597- }744+/// the caller feeds the PMK already computed for the compare, so caching
598- pmks.push(pmk);745+/// costs only the write. The first push error is surfaced through the log
599- }746+/// callback ONCE, then the sink disables itself silently — a partially
600- pmks747+/// written cache stays readable and useful.
748+pub struct CpuPmkSink {
749+ w: Option<rainbow::TableWriter>,
750+ log: Box<dyn FnMut(String) + Send>,
601 }751 }
602 752
603-/// MIC/PMKID check of one PMK against the target.753+impl CpuPmkSink {
604-fn target_matches(target: &CrackTarget, k: &[u8; 32]) -> bool {754+ pub fn new(w: rainbow::TableWriter, log: Box<dyn FnMut(String) + Send>) -> Self {
605- match target {755+ CpuPmkSink { w: Some(w), log }
606- CrackTarget::Handshake(h) => {756+ }
607- let dk = crypto::ptk(k, &h.ap, &h.client, &h.anonce, &h.snonce);757+
608- let m = crypto::mic(&dk, &h.eapol_m2, h.key_ver);758+ /// Write `(pmk, word)`; errors log once and then disable the sink.
609- crypto::ct_eq16(&m, h.mic())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+ }
610 }765 }
611- CrackTarget::Pmkid(p) => {766+ }
612- let dig = crypto::pmkid_hash(k, &p.ap, &p.client);767+
613- crypto::ct_eq16(&dig, &p.pmkid)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),
614 }773 }
615 }774 }
616 }775 }
617 776
618-// ---------------------------------------------------------------------------
619-// CPU cracker (reference-fallback path)
620-// ---------------------------------------------------------------------------
621-
622 /// Streaming CPU cracker with the same contract as `GpuCracker::crack`.777 /// 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).
623 pub fn cpu_crack(780 pub fn cpu_crack(
624 target: &CrackTarget,781 target: &CrackTarget,
625 words: &mut dyn Iterator<Item = Vec<u8>>,782 words: &mut dyn Iterator<Item = Vec<u8>>,
626 progress: &mut dyn FnMut(u64, f64),783 progress: &mut dyn FnMut(u64, f64),
627 stop: &Arc<AtomicBool>,784 stop: &Arc<AtomicBool>,
785+ cache_sink: Option<&mut CpuPmkSink>,
628 ) -> Option<String> {786 ) -> Option<String> {
629 if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) {787 if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) {
630 return None;788 return None;
631 }789 }
632 let salt = target.essid().as_bytes();790 let salt = target.essid().as_bytes();
791+ let prepared = prepare_target(target);
792+ let mut sink = cache_sink;
633 let mut done = 0u64;793 let mut done = 0u64;
634 let started = Instant::now();794 let started = Instant::now();
635 const CPU_BATCH: usize = 512;795 const CPU_BATCH: usize = 512;
@@ -651,7 +811,10 @@ pub fn cpu_crack(
651 for w in &batch {811 for w in &batch {
652 done += 1;812 done += 1;
653 let key = crypto::pmk(w, salt);813 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) {
655 return String::from_utf8(w.clone()).ok();818 return String::from_utf8(w.clone()).ok();
656 }819 }
657 }820 }
@@ -686,7 +849,7 @@ mod tests {
686 f849 f
687 }850 }
688 851
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 {
690 let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();853 let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
691 let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();854 let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
692 let anonce: [u8; 32] = [0x5a; 32];855 let anonce: [u8; 32] = [0x5a; 32];
@@ -707,20 +870,36 @@ mod tests {
707 ))870 ))
708 }871 }
709 872
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+
710 #[test]885 #[test]
711- fn host_midstate_matches_pbkdf2() {886+ fn host_padded_blocks_match_reference() {
712- // candidate_inputs + pmk_via_midstates must equal crypto's887+ // The host's padded HMAC message blocks must be exactly what the
713- // PBKDF2-HMAC-SHA1 (itself pinned to RFC 6070 + the IEEE wpa vector888+ // reference sha1/hmac stack computes: HMAC(K, msg) from a given
714- // in crypto::tests) for arbitrary passphrases and salts.889+ // midstate pair must equal feeding the padded blocks through
715- for pass in [&b"password1"[..], b"sup3r-secret", &vec![b'x'; 63][..], b"87654321"] {890+ // compress-free reference code. Easiest ground truth: verify()
716- for ssid in [&b"IEEE"[..], b"parafin", b"", b"long-ssid-0123456789"] {891+ // covers the whole chain via crypto::verify in target tests; here
717- let inputs = candidate_inputs(pass, ssid);892+ // pin just the padding invariants (0x80 at len, bitlen tail).
718- let got = pmk_via_midstates(&inputs);893+ let msg = b"PMK Name012345";
719- let mut dk = [0u8; 40];894+ let (words, n) = padded_blocks(msg);
720- crypto::pbkdf2_hmac_sha1(pass, ssid, 4096, &mut dk);895+ assert_eq!(n, 1);
721- assert_eq!(&got[..], &dk[..32], "pass={pass:?} ssid={ssid:?}");896+ let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_be_bytes()).collect();
722- }897+ assert_eq!(&bytes[..msg.len()], msg);
723- }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+ );
724 }903 }
725 904
726 #[test]905 #[test]
@@ -733,12 +912,8 @@ mod tests {
733 let words: Vec<Vec<u8>> = (0..16)912 let words: Vec<Vec<u8>> = (0..16)
734 .map(|i| format!("cand{:06}", i).into_bytes())913 .map(|i| format!("cand{:06}", i).into_bytes())
735 .collect();914 .collect();
736- let mut inputs = Vec::new();915+ let pmks = crk.pmk_batch_gpu(&words, salt).expect("kernel must complete");
737- for w in &words {916+ assert_eq!(pmks.len(), words.len());
738- inputs.extend_from_slice(&candidate_inputs(w, salt));
739- }
740- let out = crk.run_kernel(&inputs).expect("kernel must complete");
741- let pmks = assemble_pmks(&out);
742 for (w, k) in words.iter().zip(pmks.iter()) {917 for (w, k) in words.iter().zip(pmks.iter()) {
743 let mut dk = [0u8; 40];918 let mut dk = [0u8; 40];
744 crypto::pbkdf2_hmac_sha1(w, salt, 4096, &mut dk);919 crypto::pbkdf2_hmac_sha1(w, salt, 4096, &mut dk);
@@ -748,6 +923,33 @@ mod tests {
748 }923 }
749 }924 }
750 925
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+
751 #[test]953 #[test]
752 fn gpu_finds_planted_pass() {954 fn gpu_finds_planted_pass() {
753 let Some(crk) = GpuCracker::try_new() else {955 let Some(crk) = GpuCracker::try_new() else {
@@ -783,55 +985,43 @@ mod tests {
783 &stop,985 &stop,
784 );986 );
785 assert_eq!(found.as_deref(), Some("sup3r-secret"));987 assert_eq!(found.as_deref(), Some("sup3r-secret"));
786- // crack returns immediately at the match, possibly before the988+ // crack returns at the hit batch, possibly before end-of-batch.
787- // batch-end progress tick, so progress may be anything ≤ 65536.
788 assert!(last_done <= 65536, "progress reported {last_done}");989 assert!(last_done <= 65536, "progress reported {last_done}");
789 assert!(last_hps >= 0.0);990 assert!(last_hps >= 0.0);
790 }991 }
791 992
792 #[test]993 #[test]
793- fn gpu_agrees_with_crypto_verify_on_synthetic() {994+ fn gpu_finds_planted_pmkid() {
794- let Some(_crk) = GpuCracker::try_new() else {995+ let Some(crk) = GpuCracker::try_new() else {
795 eprintln!("no GPU adapter, skipping");996 eprintln!("no GPU adapter, skipping");
796 return;997 return;
797 };998 };
798- // The GPU path (kernel) for a batch containing the right pass must999+ let target = synthetic_pmkid("parafin", b"hunter2!!");
799- // identify exactly the candidates crypto::verify accepts.1000+ let words: Vec<Vec<u8>> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()];
800- let crk = _crk;1001+ let mut it = words.into_iter();
801- let pass = b"sup3r-secret";1002+ let stop = Arc::new(AtomicBool::new(false));
802- let target = synthetic_target("parafin", pass, 2);1003+ let found = crk.crack(&target, &mut it, &mut |_, _| {}, &stop);
803- let cands: Vec<Vec<u8>> = (0..64)1004+ assert_eq!(found.as_deref(), Some("hunter2!!"));
804- .map(|i| if i == 33 { pass.to_vec() } else { format!("zz{:07}", i).into_bytes() })
805- .collect();
806- let mut inputs = Vec::new();
807- for w in &cands {
808- inputs.extend_from_slice(&candidate_inputs(w, b"parafin"));
809- }
810- let out = crk.run_kernel(&inputs).expect("kernel");
811- let pmks = assemble_pmks(&out);
812- let mut hits = 0;
813- for (w, k) in cands.iter().zip(pmks.iter()) {
814- let gpu_hit = target_matches(&target, k);
815- let cpu_hit = crypto::verify(&target, w);
816- assert_eq!(gpu_hit, cpu_hit, "disagreement on {w:?}");
817- hits += gpu_hit as usize;
818- }
819- assert_eq!(hits, 1);
820 }1005 }
821 1006
822 #[test]1007 #[test]
823- fn pmk64_benchmark_hps() {1008+ fn gpu_rejects_wrong_pass_and_routes_kv3() {
824 let Some(crk) = GpuCracker::try_new() else {1009 let Some(crk) = GpuCracker::try_new() else {
825- eprintln!("no GPU adapter, skipping benchmark");1010+ eprintln!("no GPU adapter, skipping");
826 return;1011 return;
827 };1012 };
828- let hps = crk.measured_hps().expect("kernel must succeed");1013+ // Wrong candidate must NOT trip the on-device verifier.
829- eprintln!(1014+ let target = synthetic_target("parafin", b"sup3r-secret", 2);
830- "GPU PBKDF2-WPA2 throughput on {}: {:.0} H/s",1015+ let words: Vec<Vec<u8>> = (0..64).map(|i| format!("zz{:07}", i).into_bytes()).collect();
831- crk.device_name(),1016+ let mut it = words.into_iter();
832- hps1017+ let stop = Arc::new(AtomicBool::new(false));
833- );1018+ assert!(crk.crack(&target, &mut it, &mut |_, _| {}, &stop).is_none());
834- assert!(hps > 1000.0, "suspiciously slow: {hps} H/s");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));
835 }1025 }
836 1026
837 #[test]1027 #[test]
@@ -847,7 +1037,7 @@ mod tests {
847 .collect();1037 .collect();
848 let mut it = words.into_iter();1038 let mut it = words.into_iter();
849 let stop = Arc::new(AtomicBool::new(false));1039 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);
851 assert_eq!(found.as_deref(), Some("sup3r-secret"));1041 assert_eq!(found.as_deref(), Some("sup3r-secret"));
852 }1042 }
853 1043
@@ -865,7 +1055,7 @@ mod tests {
865 let words: Vec<Vec<u8>> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()];1055 let words: Vec<Vec<u8>> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()];
866 let mut it = words.into_iter();1056 let mut it = words.into_iter();
867 let stop = Arc::new(AtomicBool::new(false));1057 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);
869 assert_eq!(found.as_deref(), Some("hunter2!!"));1059 assert_eq!(found.as_deref(), Some("hunter2!!"));
870 }1060 }
871 1061
@@ -876,7 +1066,7 @@ mod tests {
876 let words: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();1066 let words: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();
877 let mut it = words.into_iter();1067 let mut it = words.into_iter();
878 let stop = Arc::new(AtomicBool::new(true));1068 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());
880 if let Some(crk) = GpuCracker::try_new() {1070 if let Some(crk) = GpuCracker::try_new() {
881 let words2: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();1071 let words2: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();
882 let mut it2 = words2.into_iter();1072 let mut it2 = words2.into_iter();
@@ -884,4 +1074,3 @@ mod tests {
884 }1074 }
885 }1075 }
886 }1076 }
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).
2 //2 //
3-// The host precomputes, per candidate passphrase P and fixed salt (ESSID):3+// Per candidate the shader does EVERYTHING (host only packs raw bytes):
4-// ipad_state = SHA1 state after absorbing (P^ipad) || salt (5×u32)4+// 1. HMAC key midstates from the passphrase (2 compresses),
5-// opad_state = SHA1 state after absorbing (P^opad) || 0x00*44 (5×u32)5+// 2. U1/U2 for both PBKDF2 blocks from host-precomputed padded messages
6-// u1 = digest words of HMAC(P, salt||INT32BE(1)) (5×u32, BE)6+// (salt||INT32BE(1|2) — constant across candidates, passed via params),
7-// u2 = digest words of HMAC(P, salt||INT32BE(2)) (5×u32, BE)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.
8 //10 //
9-// Each invocation continues the PBKDF2 loop from iteration 2 to 4096 for both11+// Verify messages arrive PRE-PADDED in params (they are constant per
10-// 20-byte blocks:12+// target): sha1 padding appended AFTER an implicit 64-byte HMAC pad
11-// U_i = HMAC_via_midstates(U_{i-1}); T ^= U_i13+// prefix, i.e. total message length = 64 + msg_len.
12-// HMAC_via_midstates(x) with a 20-byte message is exactly two SHA1 compresses:14+//
13-// inner = compress(ipad_state, x||0x80||0x00*35||0x000002dc)15+// Candidate wire format: 16 u32 per candidate, the password bytes packed
14-// outer = compress(opad_state, inner||0x80||0x00*35||0x00000294)16+// big-endian and zero-padded (passphrases are 8..=63 so they never spill
15-// Emit per candidate 40 bytes: T1||T2 (PBKDF2 dkLen=40); the host slices17+// the 64-byte HMAC key block).
16-// PMK = T1 || T2[0..12].
17 18
18 struct Params {19 struct Params {
19- // (iteration_count << 1) | cmac_flag. iteration_count is the PBKDF2 c20+ flags: u32, // (iteration_count << 1)
20- // value (4096); the kernel runs c-1 chained rounds after U1/U2.21+ is_pmkid: u32, // 1 = compare blk1 HMAC against mic (PMKID path)
21- // cmac_flag is informational (host uses it to pick the reference path in22+ n_blk1: u32, // padded 64-byte blocks in blk1
22- // tests); MIC computation always happens on the host.23+ n_blk2: u32, // padded blocks in blk2 (handshake MIC message)
23- flags: u32,24+ n: u32, // candidate count in this dispatch
24 pad0: u32,25 pad0: u32,
25 pad1: u32,26 pad1: u32,
26 pad2: u32,27 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)
27 }33 }
28 34
29-@group(0) @binding(0) var<uniform> params: Params;35+@group(0) @binding(0) var<storage, read> params: Params;
30-@group(0) @binding(1) var<storage, read> midstates: array<u32>; // 20 u32 / candidate36+@group(0) @binding(1) var<storage, read> candidates: array<u32>; // 16 u32 / cand
31-@group(0) @binding(2) var<storage, read_write> outputs: array<u32>; // 10 u32 / candidate37+@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);
32 41
33 // One SHA1 compression: state (5×u32) over exactly one 64-byte block.42 // One SHA1 compression: state (5×u32) over exactly one 64-byte block.
34-// All 80 rounds are unrolled: dynamic array indexing would demote43+// All 80 rounds unrolled (dynamic indexing would demote w[] to scratch).
35-// w[80] to scratch memory and multiply every compress by memory ops.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.
36 fn sha1_compress(state_in: ptr<function, array<u32, 5u>>, block: ptr<function, array<u32, 16u>>) {47 fn sha1_compress(state_in: ptr<function, array<u32, 5u>>, block: ptr<function, array<u32, 16u>>) {
37 let w0 = (*block)[0];48 let w0 = (*block)[0];
38 let w1 = (*block)[1];49 let w1 = (*block)[1];
@@ -66,79 +77,79 @@ fn sha1_compress(state_in: ptr<function, array<u32, 5u>>, block: ptr<function, a
66 let w29 = (((w26 ^ w21 ^ w15 ^ w13) << 1u) | ((w26 ^ w21 ^ w15 ^ w13) >> 31u));77 let w29 = (((w26 ^ w21 ^ w15 ^ w13) << 1u) | ((w26 ^ w21 ^ w15 ^ w13) >> 31u));
67 let w30 = (((w27 ^ w22 ^ w16 ^ w14) << 1u) | ((w27 ^ w22 ^ w16 ^ w14) >> 31u));78 let w30 = (((w27 ^ w22 ^ w16 ^ w14) << 1u) | ((w27 ^ w22 ^ w16 ^ w14) >> 31u));
68 let w31 = (((w28 ^ w23 ^ w17 ^ w15) << 1u) | ((w28 ^ w23 ^ w17 ^ w15) >> 31u));79 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));80+ let w32 = (((w26 ^ w16 ^ w4 ^ w0) << 2u) | ((w26 ^ w16 ^ w4 ^ w0) >> 30u));
70- let w33 = (((w30 ^ w25 ^ w19 ^ w17) << 1u) | ((w30 ^ w25 ^ w19 ^ w17) >> 31u));81+ let w33 = (((w27 ^ w17 ^ w5 ^ w1) << 2u) | ((w27 ^ w17 ^ w5 ^ w1) >> 30u));
71- let w34 = (((w31 ^ w26 ^ w20 ^ w18) << 1u) | ((w31 ^ w26 ^ w20 ^ w18) >> 31u));82+ let w34 = (((w28 ^ w18 ^ w6 ^ w2) << 2u) | ((w28 ^ w18 ^ w6 ^ w2) >> 30u));
72- let w35 = (((w32 ^ w27 ^ w21 ^ w19) << 1u) | ((w32 ^ w27 ^ w21 ^ w19) >> 31u));83+ let w35 = (((w29 ^ w19 ^ w7 ^ w3) << 2u) | ((w29 ^ w19 ^ w7 ^ w3) >> 30u));
73- let w36 = (((w33 ^ w28 ^ w22 ^ w20) << 1u) | ((w33 ^ w28 ^ w22 ^ w20) >> 31u));84+ let w36 = (((w30 ^ w20 ^ w8 ^ w4) << 2u) | ((w30 ^ w20 ^ w8 ^ w4) >> 30u));
74- let w37 = (((w34 ^ w29 ^ w23 ^ w21) << 1u) | ((w34 ^ w29 ^ w23 ^ w21) >> 31u));85+ let w37 = (((w31 ^ w21 ^ w9 ^ w5) << 2u) | ((w31 ^ w21 ^ w9 ^ w5) >> 30u));
75- let w38 = (((w35 ^ w30 ^ w24 ^ w22) << 1u) | ((w35 ^ w30 ^ w24 ^ w22) >> 31u));86+ let w38 = (((w32 ^ w22 ^ w10 ^ w6) << 2u) | ((w32 ^ w22 ^ w10 ^ w6) >> 30u));
76- let w39 = (((w36 ^ w31 ^ w25 ^ w23) << 1u) | ((w36 ^ w31 ^ w25 ^ w23) >> 31u));87+ let w39 = (((w33 ^ w23 ^ w11 ^ w7) << 2u) | ((w33 ^ w23 ^ w11 ^ w7) >> 30u));
77- let w40 = (((w37 ^ w32 ^ w26 ^ w24) << 1u) | ((w37 ^ w32 ^ w26 ^ w24) >> 31u));88+ let w40 = (((w34 ^ w24 ^ w12 ^ w8) << 2u) | ((w34 ^ w24 ^ w12 ^ w8) >> 30u));
78- let w41 = (((w38 ^ w33 ^ w27 ^ w25) << 1u) | ((w38 ^ w33 ^ w27 ^ w25) >> 31u));89+ let w41 = (((w35 ^ w25 ^ w13 ^ w9) << 2u) | ((w35 ^ w25 ^ w13 ^ w9) >> 30u));
79- let w42 = (((w39 ^ w34 ^ w28 ^ w26) << 1u) | ((w39 ^ w34 ^ w28 ^ w26) >> 31u));90+ let w42 = (((w36 ^ w26 ^ w14 ^ w10) << 2u) | ((w36 ^ w26 ^ w14 ^ w10) >> 30u));
80- let w43 = (((w40 ^ w35 ^ w29 ^ w27) << 1u) | ((w40 ^ w35 ^ w29 ^ w27) >> 31u));91+ let w43 = (((w37 ^ w27 ^ w15 ^ w11) << 2u) | ((w37 ^ w27 ^ w15 ^ w11) >> 30u));
81- let w44 = (((w41 ^ w36 ^ w30 ^ w28) << 1u) | ((w41 ^ w36 ^ w30 ^ w28) >> 31u));92+ let w44 = (((w38 ^ w28 ^ w16 ^ w12) << 2u) | ((w38 ^ w28 ^ w16 ^ w12) >> 30u));
82- let w45 = (((w42 ^ w37 ^ w31 ^ w29) << 1u) | ((w42 ^ w37 ^ w31 ^ w29) >> 31u));93+ let w45 = (((w39 ^ w29 ^ w17 ^ w13) << 2u) | ((w39 ^ w29 ^ w17 ^ w13) >> 30u));
83- let w46 = (((w43 ^ w38 ^ w32 ^ w30) << 1u) | ((w43 ^ w38 ^ w32 ^ w30) >> 31u));94+ let w46 = (((w40 ^ w30 ^ w18 ^ w14) << 2u) | ((w40 ^ w30 ^ w18 ^ w14) >> 30u));
84- let w47 = (((w44 ^ w39 ^ w33 ^ w31) << 1u) | ((w44 ^ w39 ^ w33 ^ w31) >> 31u));95+ let w47 = (((w41 ^ w31 ^ w19 ^ w15) << 2u) | ((w41 ^ w31 ^ w19 ^ w15) >> 30u));
85- let w48 = (((w45 ^ w40 ^ w34 ^ w32) << 1u) | ((w45 ^ w40 ^ w34 ^ w32) >> 31u));96+ let w48 = (((w42 ^ w32 ^ w20 ^ w16) << 2u) | ((w42 ^ w32 ^ w20 ^ w16) >> 30u));
86- let w49 = (((w46 ^ w41 ^ w35 ^ w33) << 1u) | ((w46 ^ w41 ^ w35 ^ w33) >> 31u));97+ let w49 = (((w43 ^ w33 ^ w21 ^ w17) << 2u) | ((w43 ^ w33 ^ w21 ^ w17) >> 30u));
87- let w50 = (((w47 ^ w42 ^ w36 ^ w34) << 1u) | ((w47 ^ w42 ^ w36 ^ w34) >> 31u));98+ let w50 = (((w44 ^ w34 ^ w22 ^ w18) << 2u) | ((w44 ^ w34 ^ w22 ^ w18) >> 30u));
88- let w51 = (((w48 ^ w43 ^ w37 ^ w35) << 1u) | ((w48 ^ w43 ^ w37 ^ w35) >> 31u));99+ let w51 = (((w45 ^ w35 ^ w23 ^ w19) << 2u) | ((w45 ^ w35 ^ w23 ^ w19) >> 30u));
89- let w52 = (((w49 ^ w44 ^ w38 ^ w36) << 1u) | ((w49 ^ w44 ^ w38 ^ w36) >> 31u));100+ let w52 = (((w46 ^ w36 ^ w24 ^ w20) << 2u) | ((w46 ^ w36 ^ w24 ^ w20) >> 30u));
90- let w53 = (((w50 ^ w45 ^ w39 ^ w37) << 1u) | ((w50 ^ w45 ^ w39 ^ w37) >> 31u));101+ let w53 = (((w47 ^ w37 ^ w25 ^ w21) << 2u) | ((w47 ^ w37 ^ w25 ^ w21) >> 30u));
91- let w54 = (((w51 ^ w46 ^ w40 ^ w38) << 1u) | ((w51 ^ w46 ^ w40 ^ w38) >> 31u));102+ let w54 = (((w48 ^ w38 ^ w26 ^ w22) << 2u) | ((w48 ^ w38 ^ w26 ^ w22) >> 30u));
92- let w55 = (((w52 ^ w47 ^ w41 ^ w39) << 1u) | ((w52 ^ w47 ^ w41 ^ w39) >> 31u));103+ let w55 = (((w49 ^ w39 ^ w27 ^ w23) << 2u) | ((w49 ^ w39 ^ w27 ^ w23) >> 30u));
93- let w56 = (((w53 ^ w48 ^ w42 ^ w40) << 1u) | ((w53 ^ w48 ^ w42 ^ w40) >> 31u));104+ let w56 = (((w50 ^ w40 ^ w28 ^ w24) << 2u) | ((w50 ^ w40 ^ w28 ^ w24) >> 30u));
94- let w57 = (((w54 ^ w49 ^ w43 ^ w41) << 1u) | ((w54 ^ w49 ^ w43 ^ w41) >> 31u));105+ let w57 = (((w51 ^ w41 ^ w29 ^ w25) << 2u) | ((w51 ^ w41 ^ w29 ^ w25) >> 30u));
95- let w58 = (((w55 ^ w50 ^ w44 ^ w42) << 1u) | ((w55 ^ w50 ^ w44 ^ w42) >> 31u));106+ let w58 = (((w52 ^ w42 ^ w30 ^ w26) << 2u) | ((w52 ^ w42 ^ w30 ^ w26) >> 30u));
96- let w59 = (((w56 ^ w51 ^ w45 ^ w43) << 1u) | ((w56 ^ w51 ^ w45 ^ w43) >> 31u));107+ let w59 = (((w53 ^ w43 ^ w31 ^ w27) << 2u) | ((w53 ^ w43 ^ w31 ^ w27) >> 30u));
97- let w60 = (((w57 ^ w52 ^ w46 ^ w44) << 1u) | ((w57 ^ w52 ^ w46 ^ w44) >> 31u));108+ let w60 = (((w54 ^ w44 ^ w32 ^ w28) << 2u) | ((w54 ^ w44 ^ w32 ^ w28) >> 30u));
98- let w61 = (((w58 ^ w53 ^ w47 ^ w45) << 1u) | ((w58 ^ w53 ^ w47 ^ w45) >> 31u));109+ let w61 = (((w55 ^ w45 ^ w33 ^ w29) << 2u) | ((w55 ^ w45 ^ w33 ^ w29) >> 30u));
99- let w62 = (((w59 ^ w54 ^ w48 ^ w46) << 1u) | ((w59 ^ w54 ^ w48 ^ w46) >> 31u));110+ let w62 = (((w56 ^ w46 ^ w34 ^ w30) << 2u) | ((w56 ^ w46 ^ w34 ^ w30) >> 30u));
100- let w63 = (((w60 ^ w55 ^ w49 ^ w47) << 1u) | ((w60 ^ w55 ^ w49 ^ w47) >> 31u));111+ let w63 = (((w57 ^ w47 ^ w35 ^ w31) << 2u) | ((w57 ^ w47 ^ w35 ^ w31) >> 30u));
101- let w64 = (((w61 ^ w56 ^ w50 ^ w48) << 1u) | ((w61 ^ w56 ^ w50 ^ w48) >> 31u));112+ let w64 = (((w58 ^ w48 ^ w36 ^ w32) << 2u) | ((w58 ^ w48 ^ w36 ^ w32) >> 30u));
102- let w65 = (((w62 ^ w57 ^ w51 ^ w49) << 1u) | ((w62 ^ w57 ^ w51 ^ w49) >> 31u));113+ let w65 = (((w59 ^ w49 ^ w37 ^ w33) << 2u) | ((w59 ^ w49 ^ w37 ^ w33) >> 30u));
103- let w66 = (((w63 ^ w58 ^ w52 ^ w50) << 1u) | ((w63 ^ w58 ^ w52 ^ w50) >> 31u));114+ let w66 = (((w60 ^ w50 ^ w38 ^ w34) << 2u) | ((w60 ^ w50 ^ w38 ^ w34) >> 30u));
104- let w67 = (((w64 ^ w59 ^ w53 ^ w51) << 1u) | ((w64 ^ w59 ^ w53 ^ w51) >> 31u));115+ let w67 = (((w61 ^ w51 ^ w39 ^ w35) << 2u) | ((w61 ^ w51 ^ w39 ^ w35) >> 30u));
105- let w68 = (((w65 ^ w60 ^ w54 ^ w52) << 1u) | ((w65 ^ w60 ^ w54 ^ w52) >> 31u));116+ let w68 = (((w62 ^ w52 ^ w40 ^ w36) << 2u) | ((w62 ^ w52 ^ w40 ^ w36) >> 30u));
106- let w69 = (((w66 ^ w61 ^ w55 ^ w53) << 1u) | ((w66 ^ w61 ^ w55 ^ w53) >> 31u));117+ let w69 = (((w63 ^ w53 ^ w41 ^ w37) << 2u) | ((w63 ^ w53 ^ w41 ^ w37) >> 30u));
107- let w70 = (((w67 ^ w62 ^ w56 ^ w54) << 1u) | ((w67 ^ w62 ^ w56 ^ w54) >> 31u));118+ let w70 = (((w64 ^ w54 ^ w42 ^ w38) << 2u) | ((w64 ^ w54 ^ w42 ^ w38) >> 30u));
108- let w71 = (((w68 ^ w63 ^ w57 ^ w55) << 1u) | ((w68 ^ w63 ^ w57 ^ w55) >> 31u));119+ let w71 = (((w65 ^ w55 ^ w43 ^ w39) << 2u) | ((w65 ^ w55 ^ w43 ^ w39) >> 30u));
109- let w72 = (((w69 ^ w64 ^ w58 ^ w56) << 1u) | ((w69 ^ w64 ^ w58 ^ w56) >> 31u));120+ let w72 = (((w66 ^ w56 ^ w44 ^ w40) << 2u) | ((w66 ^ w56 ^ w44 ^ w40) >> 30u));
110- let w73 = (((w70 ^ w65 ^ w59 ^ w57) << 1u) | ((w70 ^ w65 ^ w59 ^ w57) >> 31u));121+ let w73 = (((w67 ^ w57 ^ w45 ^ w41) << 2u) | ((w67 ^ w57 ^ w45 ^ w41) >> 30u));
111- let w74 = (((w71 ^ w66 ^ w60 ^ w58) << 1u) | ((w71 ^ w66 ^ w60 ^ w58) >> 31u));122+ let w74 = (((w68 ^ w58 ^ w46 ^ w42) << 2u) | ((w68 ^ w58 ^ w46 ^ w42) >> 30u));
112- let w75 = (((w72 ^ w67 ^ w61 ^ w59) << 1u) | ((w72 ^ w67 ^ w61 ^ w59) >> 31u));123+ let w75 = (((w69 ^ w59 ^ w47 ^ w43) << 2u) | ((w69 ^ w59 ^ w47 ^ w43) >> 30u));
113- let w76 = (((w73 ^ w68 ^ w62 ^ w60) << 1u) | ((w73 ^ w68 ^ w62 ^ w60) >> 31u));124+ let w76 = (((w70 ^ w60 ^ w48 ^ w44) << 2u) | ((w70 ^ w60 ^ w48 ^ w44) >> 30u));
114- let w77 = (((w74 ^ w69 ^ w63 ^ w61) << 1u) | ((w74 ^ w69 ^ w63 ^ w61) >> 31u));125+ let w77 = (((w71 ^ w61 ^ w49 ^ w45) << 2u) | ((w71 ^ w61 ^ w49 ^ w45) >> 30u));
115- let w78 = (((w75 ^ w70 ^ w64 ^ w62) << 1u) | ((w75 ^ w70 ^ w64 ^ w62) >> 31u));126+ let w78 = (((w72 ^ w62 ^ w50 ^ w46) << 2u) | ((w72 ^ w62 ^ w50 ^ w46) >> 30u));
116- let w79 = (((w76 ^ w71 ^ w65 ^ w63) << 1u) | ((w76 ^ w71 ^ w65 ^ w63) >> 31u));127+ let w79 = (((w73 ^ w63 ^ w51 ^ w47) << 2u) | ((w73 ^ w63 ^ w51 ^ w47) >> 30u));
117 var a = (*state_in)[0];128 var a = (*state_in)[0];
118 var b = (*state_in)[1];129 var b = (*state_in)[1];
119 var c = (*state_in)[2];130 var c = (*state_in)[2];
120 var d = (*state_in)[3];131 var d = (*state_in)[3];
121 var e = (*state_in)[4];132 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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
142 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w20; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }153 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w20; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
143 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w21; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }154 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w21; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
144 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w22; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }155 { 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
159 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w37; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }170 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w37; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
160 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w38; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }171 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w38; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
161 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0x6ed9eba1u + w39; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }172 { 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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
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; }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; }
182 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w60; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }193 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w60; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
183 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w61; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }194 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w61; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }
184 { let tmp = ((a << 5u) | (a >> 27u)) + (b ^ c ^ d) + e + 0xca62c1d6u + w62; e = d; d = c; c = ((b << 30u) | (b >> 2u)); b = a; a = tmp; }195 { 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
206 (*state_in)[4] = (*state_in)[4] + e;217 (*state_in)[4] = (*state_in)[4] + e;
207 }218 }
208 219
209-// Message block layout for HMAC of a 20-byte value after a 64-byte presalt220+// Build the standard outer-leg block for HMAC whose inner digest is `h`:
210-// midstate/absorbed prefix: x[0..5] || 0x80 || zeros || 32-bit BE bit-length.221+// h[0..5] || 0x80 || zeros || bitlen (always 672 = (64+20)*8 here).
211-fn hmac_block(u: ptr<function, array<u32, 5u>>, bitlen: u32) -> array<u32, 16u> {222+fn outer_block(h: array<u32, 5u>) -> array<u32, 16u> {
212- var blk: 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);
213- blk[0] = (*u)[0];
214- blk[1] = (*u)[1];
215- blk[2] = (*u)[2];
216- blk[3] = (*u)[3];
217- blk[4] = (*u)[4];
218- blk[5] = 0x80000000u;
219- for (var i = 6u; i < 15u; i = i + 1u) {
220- blk[i] = 0u;
221- }
222- blk[15] = bitlen;
223- return blk;
224 }224 }
225 225
226-// U = HMAC(pad midstates, U) — two compressions. The message seen by each leg226+// U1/U2: inner compress over the host-precomputed padded salt||counter
227-// (after the absorbed 64-byte pad prefix) is 64 + 20 = 84 bytes = 672 bits.227+// message from the ipad midstate, outer over the opad midstate.
228-fn hmac_mid(u: ptr<function, array<u32, 5u>>, ipad: ptr<function, array<u32, 5u>>, opad: ptr<function, array<u32, 5u>>) {228+fn hmac_first(ipad: array<u32, 5u>, opad: array<u32, 5u>, msg: array<u32, 16u>) -> array<u32, 5u> {
229- var in_state: array<u32, 5u> = *ipad;229+ var st = ipad;
230- var blk = hmac_block(u, 672u);230+ var m = msg;
231- sha1_compress(&in_state, &blk);231+ sha1_compress(&st, &m);
232+ var st2 = opad;
233+ var ob = outer_block(st);
234+ sha1_compress(&st2, &ob);
235+ return st2;
236+}
232 237
233- var out_state: array<u32, 5u> = *opad;238+// One chained PBKDF2 iteration: U = HMAC(U) via the pad midstates.
234- var blk2 = hmac_block(&in_state, 672u);239+fn hmac_mid(u: ptr<function, array<u32, 5u>>, ipad: ptr<function, array<u32, 5u>>, opad: ptr<function, array<u32, 5u>>) {
235- sha1_compress(&out_state, &blk2);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+}
236 248
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;
238 }264 }
239 265
240-@compute @workgroup_size(64)266+// Per-candidate HMAC pad midstates from the raw password key block.
241-fn main(@builtin(global_invocation_id) gid: vec3<u32>) {267+fn key_midstates(base: u32) -> array<array<u32, 5u>, 2u> {
242- let idx = gid.x;268+ var ib: array<u32, 16u>;
243- if idx >= arrayLength(&outputs) / 10u {269+ var ob: array<u32, 16u>;
244- return;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;
245 }274 }
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+}
246 281
247- let base_in = idx * 20u;282+// HMAC pad midstates for an 8-word key (the PMK) or 4-word key (KCK):
248- var ipad: array<u32, 5u>;283+// key words in w[0..word_count), rest of the 64-byte block zero — both
249- var opad: array<u32, 5u>;284+// folded into the pad XOR (x ^ 0 == x).
250- var u1: array<u32, 5u>;285+fn short_key_midstates(w0: u32, w1: u32, w2: u32, w3: u32, word_count: u32) -> array<array<u32, 5u>, 2u> {
251- var u2: array<u32, 5u>;286+ var ib: array<u32, 16u>;
252- for (var i = 0u; i < 5u; i = i + 1u) {287+ var ob: array<u32, 16u>;
253- ipad[i] = midstates[base_in + i];288+ let ws = array<u32, 4u>(w0, w1, w2, w3);
254- opad[i] = midstates[base_in + 5u + i];289+ for (var i = 0u; i < 16u; i = i + 1u) {
255- u1[i] = midstates[base_in + 10u + i];290+ var kb = 0u;
256- u2[i] = midstates[base_in + 15u + i];291+ if i < word_count {
292+ kb = ws[i];
293+ }
294+ ib[i] = kb ^ 0x36363636u;
295+ ob[i] = kb ^ 0x5c5c5c5cu;
257 }296 }
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+}
258 303
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);
260 312
261 var t1 = u1;313 var t1 = u1;
262 var t2 = u2;314 var t2 = u2;
315+ let iterations = params.flags >> 1u;
263 for (var i = 1u; i < iterations; i = i + 1u) {316 for (var i = 1u; i < iterations; i = i + 1u) {
264 hmac_mid(&u1, &ipad, &opad);317 hmac_mid(&u1, &ipad, &opad);
265 t1[0] = t1[0] ^ u1[0];318 t1[0] = t1[0] ^ u1[0];
@@ -268,18 +321,77 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
268 t1[3] = t1[3] ^ u1[3];321 t1[3] = t1[3] ^ u1[3];
269 t1[4] = t1[4] ^ u1[4];322 t1[4] = t1[4] ^ u1[4];
270 hmac_mid(&u2, &ipad, &opad);323 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).
271 t2[0] = t2[0] ^ u2[0];326 t2[0] = t2[0] ^ u2[0];
272 t2[1] = t2[1] ^ u2[1];327 t2[1] = t2[1] ^ u2[1];
273 t2[2] = t2[2] ^ u2[2];328 t2[2] = t2[2] ^ u2[2];
274- t2[3] = t2[3] ^ u2[3];
275- t2[4] = t2[4] ^ u2[4];
276 }329 }
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);
277 345
278- let base_out = idx * 10u;346+ // Epilogue: match the candidate's PMK against the capture on-device.
279- for (var i = 0u; i < 5u; i = i + 1u) {347+ // PMK midstates (32-byte key: all 8 words of pk[0..8]).
280- outputs[base_out + i] = t1[i];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;
281 }390 }
282- for (var i = 0u; i < 5u; i = i + 1u) {391+ let base = idx * 16u;
283- outputs[base_out + 5u + i] = t2[i];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];
284 }396 }
285 }397 }