forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiB5d9149dTahinli1 month ago7 commits

gpu.rs887 lines, 32.4 KiBHistoryRawDownload
1//! GPU-accelerated WPA2-PSK cracker (wgpu compute, see pbkdf2.wgsl) plus a
2//! CPU streaming cracker of the same shape.
3//!
4//! Algorithm: the host computes per candidate the SHA1 midstates for the two
5//! HMAC pad prefixes (key = passphrase, salt = ESSID absorbed in the ipad
6//! leg) and the first PBKDF2 outputs U1/U2 for both 20-byte blocks. The GPU
7//! then executes the remaining 4095 chained HMAC rounds per block and emits
8//! T1||T2 (40 bytes): PMK = T1 || T2[0..12]. PTK + MIC are derived per PMK on
9//! the host — that is cheap relative to the 4096 HMACs it replaces. For
10//! key_ver 3 targets the MIC is AES-CMAC (bus duty: PTK+KCK never leave the
11//! host side of the reference implementation).
12
13use std::num::NonZeroU64;
14use std::sync::Arc;
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::time::{Duration, Instant};
17
18/// Pack the first 64 message bytes into the 16 FIPS SHA1 message words
19/// (big-endian parse, per FIPS 180-1).
20fn 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
29use crate::crypto::{self, CrackTarget};
30#[cfg(test)]
31use crate::common::MacAddr;
32
33const BATCH: u32 = 1 << 16;
34const WORKGROUP_SIZE: u32 = 64;
35const ITERATIONS: u32 = 4096;
36const U32_PER_CAND_IN: usize = 20; // ipad(5) opad(5) u1(5) u2(5)
37const U32_PER_CAND_OUT: usize = 10; // T1(5) T2(5)
38
39const K: [u32; 4] = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
40const IV: [u32; 5] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
41
42// ---------------------------------------------------------------------------
43// Host-side SHA1 midstate helpers (mirror of the WGSL kernel).
44// ---------------------------------------------------------------------------
45
46/// One FIPS 180-1 SHA1 compression over exactly one 64-byte block, starting
47/// from a 5×u32 state. `block` holds the message words BE-parsed as the
48/// standard requires; states and the running chain stay in value domain
49/// end-to-end (this is also the WGSL kernel's domain).
50fn compress5(state: &mut [u32; 5], block: &[u32; 16]) {
51 let mut w = [0u32; 80];
52 w[..16].copy_from_slice(block);
53 for t in 16..80 {
54 let x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
55 w[t] = x.rotate_left(1);
56 }
57 let (mut a, mut b, mut c, mut d, mut e) = (state[0], state[1], state[2], state[3], state[4]);
58 for (t, &wt) in w.iter().enumerate() {
59 let f = match t {
60 0..=19 => (b & c) | (!b & d),
61 20..=39 | 60..=79 => b ^ c ^ d,
62 _ => (b & c) | (b & d) | (c & d),
63 };
64 let k = K[t / 20];
65 let temp = a
66 .rotate_left(5)
67 .wrapping_add(f)
68 .wrapping_add(e)
69 .wrapping_add(k)
70 .wrapping_add(wt);
71 e = d;
72 d = c;
73 c = b.rotate_left(30);
74 b = a;
75 a = temp;
76 }
77 state[0] = state[0].wrapping_add(a);
78 state[1] = state[1].wrapping_add(b);
79 state[2] = state[2].wrapping_add(c);
80 state[3] = state[3].wrapping_add(d);
81 state[4] = state[4].wrapping_add(e);
82}
83
84/// Finalize a two-block SHA1 message given the state after block 1: place
85/// the tail, append padding/bit-length for the total (64 + tail.len()) byte
86/// message, compress once. Returns the 5-word state (the FIPS digest words).
87fn finalize_64(state_after_b1: &[u32; 5], tail: &[u8]) -> [u32; 5] {
88 debug_assert!(tail.len() < 56);
89 let total_len = (64 + tail.len()) as u64;
90 let mut blk = [0u8; 64];
91 blk[..tail.len()].copy_from_slice(tail);
92 blk[tail.len()] = 0x80;
93 blk[56..64].copy_from_slice(&(total_len * 8).to_be_bytes());
94 let mut st = *state_after_b1;
95 compress5(&mut st, &pack16(&blk));
96 st
97}
98
99/// First PBKDF2 block digest for a candidate: U_idx = HMAC(P, salt ||
100/// INT32BE(idx)), using precomputed pad midstates. Inner leg message is
101/// (P^ipad) || salt || BE32(idx) (64 + salt.len() + 4 bytes), outer leg is
102/// (P^opad) || inner_digest (84 bytes, 672 bits).
103fn hmac_first(ipad: &[u32; 5], opad: &[u32; 5], salt: &[u8], block_idx: u32) -> [u32; 5] {
104 let mut tail = [0u8; 68];
105 tail[..salt.len()].copy_from_slice(salt);
106 tail[salt.len()..salt.len() + 4].copy_from_slice(&block_idx.to_be_bytes());
107 let inner = finalize_64(ipad, &tail[..salt.len() + 4]);
108
109 let mut outer_blk = [0u32; 16];
110 outer_blk[..5].copy_from_slice(&inner);
111 outer_blk[5] = 0x8000_0000;
112 outer_blk[15] = 672;
113 let mut st = *opad;
114 compress5(&mut st, &outer_blk);
115 st
116}
117
118/// Mirror of the WGSL `hmac_mid`: one chained HMAC round (two compresses)
119/// over the 20-byte value `u` given the pad midstates.
120fn hmac_midstate_host(ipad: &[u32; 5], opad: &[u32; 5], u: &[u32; 5]) -> [u32; 5] {
121 let mut msg = [0u32; 16];
122 msg[..5].copy_from_slice(u);
123 msg[5] = 0x8000_0000;
124 msg[15] = 672;
125
126 let mut st = *ipad;
127 compress5(&mut st, &msg);
128
129 let mut outer = [0u32; 16];
130 outer[..5].copy_from_slice(&st);
131 outer[5] = 0x8000_0000;
132 outer[15] = 672;
133
134 let mut st2 = *opad;
135 compress5(&mut st2, &outer);
136 st2
137}
138
139/// Per-candidate kernel inputs for one passphrase.
140fn candidate_inputs(pass: &[u8], salt: &[u8]) -> [u32; U32_PER_CAND_IN] {
141 debug_assert!((8..=63).contains(&pass.len()));
142
143 let mut ipad_blk = [0x36u8; 64];
144 let mut opad_blk = [0x5cu8; 64];
145 for (i, &b) in pass.iter().enumerate() {
146 ipad_blk[i] ^= b;
147 opad_blk[i] ^= b;
148 }
149
150 let mut ipad = IV;
151 let mut opad = IV;
152 compress5(&mut ipad, &pack16(&ipad_blk));
153 compress5(&mut opad, &pack16(&opad_blk));
154
155 // U_i = HMAC(P, salt || INT32BE(i)): inner leg via the ipad midstate,
156 // outer leg one compress over the opad midstate (also 84-byte total
157 // message → bit length 672, same layout as the chained rounds).
158 let u1 = hmac_first(&ipad, &opad, salt, 1);
159 let u2 = hmac_first(&ipad, &opad, salt, 2);
160
161 let mut out = [0u32; U32_PER_CAND_IN];
162 out[..5].copy_from_slice(&ipad);
163 out[5..10].copy_from_slice(&opad);
164 out[10..15].copy_from_slice(&u1);
165 out[15..20].copy_from_slice(&u2);
166 out
167}
168
169/// Finish the two PBKDF2 blocks for one candidate entirely on the CPU
170/// (reference + fallback path).
171fn pmk_via_midstates(inputs: &[u32; U32_PER_CAND_IN]) -> [u8; 32] {
172 let mut ipad = [0u32; 5];
173 let mut opad = [0u32; 5];
174 let mut u1 = [0u32; 5];
175 let mut u2 = [0u32; 5];
176 ipad.copy_from_slice(&inputs[..5]);
177 opad.copy_from_slice(&inputs[5..10]);
178 u1.copy_from_slice(&inputs[10..15]);
179 u2.copy_from_slice(&inputs[15..20]);
180
181 let mut t1 = u1;
182 let mut t2 = u2;
183 for _ in 1..ITERATIONS {
184 u1 = hmac_midstate_host(&ipad, &opad, &u1);
185 for i in 0..5 {
186 t1[i] ^= u1[i];
187 }
188 u2 = hmac_midstate_host(&ipad, &opad, &u2);
189 for i in 0..5 {
190 t2[i] ^= u2[i];
191 }
192 }
193
194 let mut pmk_bytes = [0u8; 32];
195 for i in 0..5 {
196 pmk_bytes[i * 4..i * 4 + 4].copy_from_slice(&t1[i].to_be_bytes());
197 }
198 for i in 0..3 {
199 pmk_bytes[20 + i * 4..20 + i * 4 + 4].copy_from_slice(&t2[i].to_be_bytes());
200 }
201 pmk_bytes
202}
203
204// ---------------------------------------------------------------------------
205// GPU cracker
206// ---------------------------------------------------------------------------
207
208pub struct GpuCracker {
209 device: wgpu::Device,
210 queue: wgpu::Queue,
211 pipeline: wgpu::ComputePipeline,
212 layout: wgpu::BindGroupLayout,
213 name: String,
214 batch: u32,
215}
216
217impl GpuCracker {
218 /// None when no suitable adapter/device exists (caller falls back to the
219 /// CPU cracker).
220 pub fn try_new() -> Option<Self> {
221 let instance =
222 wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
223 let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
224 power_preference: wgpu::PowerPreference::HighPerformance,
225 force_fallback_adapter: false,
226 compatible_surface: None,
227 apply_limit_buckets: false,
228 }))
229 .ok()?;
230 let info = adapter.get_info();
231 let limits = adapter.limits();
232 // Need storage buffers of BATCH × 80 B in and BATCH × 40 B out.
233 let in_bytes = u64::from(BATCH) * (U32_PER_CAND_IN as u64) * 4;
234 let out_bytes = u64::from(BATCH) * (U32_PER_CAND_OUT as u64) * 4;
235 if u64::from(limits.max_storage_buffer_binding_size) < in_bytes
236 || u64::from(limits.max_storage_buffer_binding_size) < out_bytes
237 || limits.max_buffer_size < in_bytes.max(out_bytes)
238 {
239 return None;
240 }
241
242 let desc = wgpu::DeviceDescriptor {
243 label: Some("wifilab-pbkdf2"),
244 required_features: wgpu::Features::empty(),
245 required_limits: wgpu::Limits::default(),
246 experimental_features: wgpu::ExperimentalFeatures::disabled(),
247 memory_hints: wgpu::MemoryHints::Performance,
248 trace: wgpu::Trace::Off,
249 };
250 let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?;
251
252 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
253 label: Some("pbkdf2.wgsl"),
254 source: wgpu::ShaderSource::Wgsl(include_str!("pbkdf2.wgsl").into()),
255 });
256
257 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
258 label: Some("pbkdf2-layout"),
259 entries: &[
260 // params uniform
261 wgpu::BindGroupLayoutEntry {
262 binding: 0,
263 visibility: wgpu::ShaderStages::COMPUTE,
264 ty: wgpu::BindingType::Buffer {
265 ty: wgpu::BufferBindingType::Uniform,
266 has_dynamic_offset: false,
267 min_binding_size: NonZeroU64::new(16),
268 },
269 count: None,
270 },
271 // midstates in
272 wgpu::BindGroupLayoutEntry {
273 binding: 1,
274 visibility: wgpu::ShaderStages::COMPUTE,
275 ty: wgpu::BindingType::Buffer {
276 ty: wgpu::BufferBindingType::Storage { read_only: true },
277 has_dynamic_offset: false,
278 min_binding_size: None,
279 },
280 count: None,
281 },
282 // outputs out
283 wgpu::BindGroupLayoutEntry {
284 binding: 2,
285 visibility: wgpu::ShaderStages::COMPUTE,
286 ty: wgpu::BindingType::Buffer {
287 ty: wgpu::BufferBindingType::Storage { read_only: false },
288 has_dynamic_offset: false,
289 min_binding_size: None,
290 },
291 count: None,
292 },
293 ],
294 });
295
296 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
297 label: Some("pbkdf2-pipeline-layout"),
298 bind_group_layouts: &[Some(&layout)],
299 immediate_size: 0,
300 });
301
302 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
303 label: Some("pbkdf2-pipeline"),
304 layout: Some(&pipeline_layout),
305 module: &shader,
306 entry_point: Some("main"),
307 compilation_options: wgpu::PipelineCompilationOptions::default(),
308 cache: None,
309 });
310
311 Some(GpuCracker {
312 device,
313 queue,
314 pipeline,
315 layout,
316 name: format!("{} ({:?})", info.name, info.backend),
317 batch: BATCH,
318 })
319 }
320
321 pub fn device_name(&self) -> String {
322 self.name.clone()
323 }
324
325 /// Measured full-attack throughput for progress reporting (4096-iteration
326 /// batches). Runs 4 batches through `pmk_batch_gpu` and returns H/s.
327 #[cfg(test)]
328 fn measured_hps(&self) -> Option<f64> {
329 let pass: Vec<u8> = b"benchmk1".to_vec();
330 let salt = b"benchmark-ssid";
331 let mut inputs = Vec::with_capacity(self.batch as usize * U32_PER_CAND_IN);
332 for i in 0..self.batch as usize {
333 let mut w = pass.clone();
334 w[0] = b'a' + (i % 26) as u8;
335 inputs.extend_from_slice(&candidate_inputs(&w, salt));
336 }
337 // Warm-up batch: covers one-time SPIR-V->ISA compile & memory init.
338 self.run_kernel(&inputs)?;
339 const BATCHES: u32 = 8;
340 let t0 = Instant::now();
341 let mut ok = true;
342 for _ in 0..BATCHES {
343 let mut inp = inputs.clone();
344 inp[0] = inp[0].wrapping_add(1);
345 ok &= self.run_kernel(&inp).is_some();
346 }
347 if !ok {
348 return None;
349 }
350 let secs = t0.elapsed().as_secs_f64();
351 Some(self.batch as f64 * f64::from(BATCHES) / secs)
352 }
353
354 /// Run one kernel batch over `inputs` (n×20 u32, on the wire as u32 LE).
355 /// Returns the n×10 u32 output words, or None on device-lost/hang.
356 fn run_kernel(&self, inputs: &[u32]) -> Option<Vec<u32>> {
357 let n = inputs.len() / U32_PER_CAND_IN;
358 if n == 0 {
359 return Some(Vec::new());
360 }
361
362 let in_bytes = (inputs.len() * 4) as u64;
363 let out_u32 = n * U32_PER_CAND_OUT;
364 let out_bytes = (out_u32 * 4) as u64;
365
366 let in_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
367 label: Some("midstates"),
368 size: in_bytes.max(16),
369 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
370 mapped_at_creation: false,
371 });
372 let out_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
373 label: Some("t1t2"),
374 size: out_bytes.max(16),
375 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
376 mapped_at_creation: false,
377 });
378 let read_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
379 label: Some("readback"),
380 size: out_bytes.max(16),
381 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
382 mapped_at_creation: false,
383 });
384 let param_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
385 label: Some("params"),
386 size: 16,
387 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
388 mapped_at_creation: false,
389 });
390
391 let flags: u32 = ITERATIONS << 1;
392 let params: [u32; 4] = [flags, 0, 0, 0];
393 self.queue
394 .write_buffer(&param_buf, 0, &u32s_as_bytes(&params));
395 let in_bytes_vec = u32s_as_bytes(inputs);
396 self.queue.write_buffer(&in_buf, 0, &in_bytes_vec);
397
398 let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
399 label: Some("pbkdf2-bg"),
400 layout: &self.layout,
401 entries: &[
402 wgpu::BindGroupEntry {
403 binding: 0,
404 resource: param_buf.as_entire_binding(),
405 },
406 wgpu::BindGroupEntry {
407 binding: 1,
408 resource: in_buf.as_entire_binding(),
409 },
410 wgpu::BindGroupEntry {
411 binding: 2,
412 resource: out_buf.as_entire_binding(),
413 },
414 ],
415 });
416
417 let mut encoder = self
418 .device
419 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
420 label: Some("pbkdf2-encoder"),
421 });
422 {
423 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
424 label: Some("pbkdf2-pass"),
425 timestamp_writes: None,
426 });
427 pass.set_pipeline(&self.pipeline);
428 pass.set_bind_group(0, &bind_group, &[]);
429 pass.dispatch_workgroups(n.div_ceil(WORKGROUP_SIZE as usize) as u32, 1, 1);
430 }
431 encoder.copy_buffer_to_buffer(&out_buf, 0, &read_buf, 0, out_bytes);
432 let sub = self.queue.submit([encoder.finish()]);
433
434 // Wait for the shader with timeout; a hung/compute-heavy dispatch is
435 // reported so the caller can halve the batch.
436 let (tx, rx) = std::sync::mpsc::channel();
437 read_buf
438 .slice(..)
439 .map_async(wgpu::MapMode::Read, move |res| {
440 let _ = tx.send(res);
441 });
442
443 let mut waited = Duration::ZERO;
444 let step = Duration::from_millis(50);
445 let limit = Duration::from_secs(30);
446 loop {
447 match self.device.poll(wgpu::PollType::Wait {
448 submission_index: Some(sub.clone()),
449 timeout: Some(step),
450 }) {
451 Ok(_) | Err(wgpu::PollError::Timeout) => {
452 if let Ok(res) = rx.try_recv() {
453 match res {
454 Ok(()) => break,
455 Err(e) => {
456 tracing::warn!("map_async failed: {e}");
457 read_buf.unmap();
458 return None;
459 }
460 }
461 }
462 waited += step;
463 if waited >= limit {
464 tracing::warn!("gpu dispatch timed out after {limit:?}");
465 return None;
466 }
467 }
468 Err(e) => {
469 tracing::warn!("device poll error: {e}");
470 return None;
471 }
472 }
473 }
474
475 let view = read_buf.slice(..).get_mapped_range().ok()?;
476 let mut out = Vec::with_capacity(out_u32);
477 for chunk in view[..(out_u32 * 4)].chunks_exact(4) {
478 out.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
479 }
480 drop(view);
481 read_buf.unmap();
482 Some(out)
483 }
484
485 /// Compute PMKs for a word batch. Halves the batch size once on
486 /// device-lost/timeout; on a repeated failure returns None.
487 fn pmk_batch_gpu(&self, words: &[Vec<u8>], salt: &[u8]) -> Option<Vec<[u8; 32]>> {
488 let mut cur: Vec<Vec<u8>> = words.to_vec();
489 let mut attempts = 0u8;
490 loop {
491 let mut inputs = Vec::with_capacity(cur.len() * U32_PER_CAND_IN);
492 for w in &cur {
493 inputs.extend_from_slice(&candidate_inputs(w, salt));
494 }
495 if let Some(out) = self.run_kernel(&inputs) {
496 return Some(assemble_pmks(&out));
497 }
498 attempts += 1;
499 if attempts > 1 || cur.len() == 1 {
500 return None;
501 }
502 let half = cur.len().div_ceil(2);
503 cur = cur[..half].to_vec();
504 }
505 }
506
507 /// Stream `words` through the GPU, calling `progress(done, hps)` once per
508 /// dispatched batch (also when a partial final batch ran). Honors `stop`
509 /// between batches. Returns the passphrase on MIC match.
510 pub fn crack(
511 &self,
512 target: &CrackTarget,
513 words: &mut dyn Iterator<Item = Vec<u8>>,
514 progress: &mut dyn FnMut(u64, f64),
515 stop: &Arc<AtomicBool>,
516 ) -> Option<String> {
517 if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) {
518 return None;
519 }
520 let salt = target.essid().as_bytes();
521 let mut done = 0u64;
522 let started = Instant::now();
523 let mut batch_cap = self.batch as usize;
524
525 loop {
526 if stop.load(Ordering::Relaxed) {
527 return None;
528 }
529 let mut batch: Vec<Vec<u8>> = Vec::with_capacity(batch_cap);
530 while batch.len() < batch_cap {
531 match words.next() {
532 Some(w) => batch.push(w),
533 None => break,
534 }
535 }
536 if batch.is_empty() {
537 return None;
538 }
539
540 let pmks = self.pmk_batch_gpu(&batch, salt)?;
541 // If the PMK batch shrunk because of a device hiccup the tail
542 // candidates are re-attempted below; keep bookkeeping accurate by
543 // scanning only what came back and re-queueing the rest.
544 let checked = pmks.len();
545 for (i, k) in pmks.iter().enumerate() {
546 done += 1;
547 if target_matches(target, k) {
548 return String::from_utf8(batch[i].clone()).ok();
549 }
550 }
551 let secs = started.elapsed().as_secs_f64().max(1e-6);
552 progress(done, done as f64 / secs);
553
554 if checked < batch.len() {
555 // Device hiccup path: retry the remaining words in smaller
556 // chunks before continuing the stream.
557 let rest = batch[checked..].to_vec();
558 for chunk in rest.chunks(batch_cap.div_ceil(2).max(1)) {
559 if stop.load(Ordering::Relaxed) {
560 return None;
561 }
562 let pmks = self.pmk_batch_gpu(chunk, salt)?;
563 for (i, k) in pmks.iter().enumerate() {
564 done += 1;
565 if target_matches(target, k) {
566 return String::from_utf8(chunk[i].clone()).ok();
567 }
568 }
569 let secs = started.elapsed().as_secs_f64().max(1e-6);
570 progress(done, done as f64 / secs);
571 }
572 batch_cap = batch_cap.div_ceil(2).max(1024);
573 }
574 }
575 }
576}
577
578/// Little-endian byte serialization of a u32 slice for queue.write_buffer.
579/// The kernel reads raw u32s; on this CPU (x86-64, LE) this matches memory
580/// layout, and serializing keeps the wire format explicit for any host.
581fn u32s_as_bytes(v: &[u32]) -> Vec<u8> {
582 let mut out = Vec::with_capacity(v.len() * 4);
583 for &w in v {
584 out.extend_from_slice(&w.to_le_bytes());
585 }
586 out
587}
588
589fn assemble_pmks(out: &[u32]) -> Vec<[u8; 32]> {
590 let n = out.len() / U32_PER_CAND_OUT;
591 let mut pmks = Vec::with_capacity(n);
592 for c in 0..n {
593 let mut pmk = [0u8; 32];
594 let row = &out[c * U32_PER_CAND_OUT..(c + 1) * U32_PER_CAND_OUT];
595 for i in 0..8 {
596 pmk[i * 4..i * 4 + 4].copy_from_slice(&row[i].to_be_bytes());
597 }
598 pmks.push(pmk);
599 }
600 pmks
601}
602
603/// MIC/PMKID check of one PMK against the target.
604fn target_matches(target: &CrackTarget, k: &[u8; 32]) -> bool {
605 match target {
606 CrackTarget::Handshake(h) => {
607 let dk = crypto::ptk(k, &h.ap, &h.client, &h.anonce, &h.snonce);
608 let m = crypto::mic(&dk, &h.eapol_m2, h.key_ver);
609 crypto::ct_eq16(&m, h.mic())
610 }
611 CrackTarget::Pmkid(p) => {
612 let dig = crypto::pmkid_hash(k, &p.ap, &p.client);
613 crypto::ct_eq16(&dig, &p.pmkid)
614 }
615 }
616}
617
618// ---------------------------------------------------------------------------
619// CPU cracker (reference-fallback path)
620// ---------------------------------------------------------------------------
621
622/// Streaming CPU cracker with the same contract as `GpuCracker::crack`.
623pub fn cpu_crack(
624 target: &CrackTarget,
625 words: &mut dyn Iterator<Item = Vec<u8>>,
626 progress: &mut dyn FnMut(u64, f64),
627 stop: &Arc<AtomicBool>,
628) -> Option<String> {
629 if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) {
630 return None;
631 }
632 let salt = target.essid().as_bytes();
633 let mut done = 0u64;
634 let started = Instant::now();
635 const CPU_BATCH: usize = 512;
636
637 loop {
638 if stop.load(Ordering::Relaxed) {
639 return None;
640 }
641 let mut batch: Vec<Vec<u8>> = Vec::with_capacity(CPU_BATCH);
642 while batch.len() < CPU_BATCH {
643 match words.next() {
644 Some(w) => batch.push(w),
645 None => break,
646 }
647 }
648 if batch.is_empty() {
649 return None;
650 }
651 for w in &batch {
652 done += 1;
653 let key = crypto::pmk(w, salt);
654 if target_matches(target, &key) {
655 return String::from_utf8(w.clone()).ok();
656 }
657 }
658 let secs = started.elapsed().as_secs_f64().max(1e-6);
659 progress(done, done as f64 / secs);
660 }
661}
662
663// ---------------------------------------------------------------------------
664
665#[cfg(test)]
666mod tests {
667 use super::*;
668 use crate::crypto;
669
670 fn build_eapol_m2(key_ver: u8, snonce: &[u8; 32], replay: u64) -> Vec<u8> {
671 let mut f = Vec::with_capacity(99);
672 f.push(0x02);
673 f.push(0x03);
674 f.extend_from_slice(&95u16.to_be_bytes());
675 f.push(0x02);
676 let info: u16 = 0x0100 | 0x0080 | (key_ver as u16 & 0x7);
677 f.extend_from_slice(&info.to_be_bytes());
678 f.extend_from_slice(&16u16.to_be_bytes());
679 f.extend_from_slice(&replay.to_be_bytes());
680 f.extend_from_slice(snonce);
681 f.extend_from_slice(&[0u8; 16]);
682 f.extend_from_slice(&[0u8; 8]);
683 f.extend_from_slice(&[0u8; 8]);
684 f.extend_from_slice(&[0u8; 16]);
685 f.extend_from_slice(&0u16.to_be_bytes());
686 f
687 }
688
689 fn synthetic_target(ssid: &str, pass: &[u8], key_ver: u8) -> CrackTarget {
690 let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
691 let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
692 let anonce: [u8; 32] = [0x5a; 32];
693 let snonce: [u8; 32] = [0xc3; 32];
694 let key = crypto::pmk(pass, ssid.as_bytes());
695 let dk = crypto::ptk(&key, &ap, &sta, &anonce, &snonce);
696 let frame = build_eapol_m2(key_ver, &snonce, 1);
697 let m = crypto::mic(&dk, &frame, key_ver);
698 CrackTarget::Handshake(crate::common::HandshakeCapture::new(
699 ap,
700 sta,
701 ssid.to_string(),
702 anonce,
703 snonce,
704 m,
705 frame,
706 key_ver,
707 ))
708 }
709
710 #[test]
711 fn host_midstate_matches_pbkdf2() {
712 // candidate_inputs + pmk_via_midstates must equal crypto's
713 // PBKDF2-HMAC-SHA1 (itself pinned to RFC 6070 + the IEEE wpa vector
714 // in crypto::tests) for arbitrary passphrases and salts.
715 for pass in [&b"password1"[..], b"sup3r-secret", &vec![b'x'; 63][..], b"87654321"] {
716 for ssid in [&b"IEEE"[..], b"parafin", b"", b"long-ssid-0123456789"] {
717 let inputs = candidate_inputs(pass, ssid);
718 let got = pmk_via_midstates(&inputs);
719 let mut dk = [0u8; 40];
720 crypto::pbkdf2_hmac_sha1(pass, ssid, 4096, &mut dk);
721 assert_eq!(&got[..], &dk[..32], "pass={pass:?} ssid={ssid:?}");
722 }
723 }
724 }
725
726 #[test]
727 fn gpu_available_and_pmk_matches() {
728 let Some(crk) = GpuCracker::try_new() else {
729 eprintln!("no GPU adapter, skipping");
730 return;
731 };
732 let salt = b"parafin";
733 let words: Vec<Vec<u8>> = (0..16)
734 .map(|i| format!("cand{:06}", i).into_bytes())
735 .collect();
736 let mut inputs = Vec::new();
737 for w in &words {
738 inputs.extend_from_slice(&candidate_inputs(w, salt));
739 }
740 let out = crk.run_kernel(&inputs).expect("kernel must complete");
741 let pmks = assemble_pmks(&out);
742 for (w, k) in words.iter().zip(pmks.iter()) {
743 let mut dk = [0u8; 40];
744 crypto::pbkdf2_hmac_sha1(w, salt, 4096, &mut dk);
745 assert_eq!(&k[..], &dk[..32], "GPU PMK mismatch for {w:?}");
746 // Also bit-exact vs the RFC-anchored crypto::pmk.
747 assert_eq!(k, &crypto::pmk(w, salt), "crypto::pmk mismatch for {w:?}");
748 }
749 }
750
751 #[test]
752 fn gpu_finds_planted_pass() {
753 let Some(crk) = GpuCracker::try_new() else {
754 eprintln!("no GPU adapter, skipping");
755 return;
756 };
757 eprintln!("gpu device: {}", crk.device_name());
758 let pass = b"sup3r-secret";
759 let target = synthetic_target("parafin", pass, 2);
760
761 const TOTAL: usize = 5000;
762 let mut idx = 0usize;
763 let words: Vec<Vec<u8>> = (0..TOTAL)
764 .map(|_| {
765 idx += 1;
766 if idx == 3800 {
767 pass.to_vec()
768 } else {
769 format!("w{:07}", idx).into_bytes()
770 }
771 })
772 .collect();
773 let mut it = words.into_iter();
774 let stop = Arc::new(AtomicBool::new(false));
775 let (mut last_done, mut last_hps) = (0u64, 0f64);
776 let found = crk.crack(
777 &target,
778 &mut it,
779 &mut |d, h| {
780 last_done = d;
781 last_hps = h;
782 },
783 &stop,
784 );
785 assert_eq!(found.as_deref(), Some("sup3r-secret"));
786 // crack returns immediately at the match, possibly before the
787 // batch-end progress tick, so progress may be anything ≤ 65536.
788 assert!(last_done <= 65536, "progress reported {last_done}");
789 assert!(last_hps >= 0.0);
790 }
791
792 #[test]
793 fn gpu_agrees_with_crypto_verify_on_synthetic() {
794 let Some(_crk) = GpuCracker::try_new() else {
795 eprintln!("no GPU adapter, skipping");
796 return;
797 };
798 // The GPU path (kernel) for a batch containing the right pass must
799 // identify exactly the candidates crypto::verify accepts.
800 let crk = _crk;
801 let pass = b"sup3r-secret";
802 let target = synthetic_target("parafin", pass, 2);
803 let cands: Vec<Vec<u8>> = (0..64)
804 .map(|i| if i == 33 { pass.to_vec() } else { format!("zz{:07}", i).into_bytes() })
805 .collect();
806 let mut inputs = Vec::new();
807 for w in &cands {
808 inputs.extend_from_slice(&candidate_inputs(w, b"parafin"));
809 }
810 let out = crk.run_kernel(&inputs).expect("kernel");
811 let pmks = assemble_pmks(&out);
812 let mut hits = 0;
813 for (w, k) in cands.iter().zip(pmks.iter()) {
814 let gpu_hit = target_matches(&target, k);
815 let cpu_hit = crypto::verify(&target, w);
816 assert_eq!(gpu_hit, cpu_hit, "disagreement on {w:?}");
817 hits += gpu_hit as usize;
818 }
819 assert_eq!(hits, 1);
820 }
821
822 #[test]
823 fn pmk64_benchmark_hps() {
824 let Some(crk) = GpuCracker::try_new() else {
825 eprintln!("no GPU adapter, skipping benchmark");
826 return;
827 };
828 let hps = crk.measured_hps().expect("kernel must succeed");
829 eprintln!(
830 "GPU PBKDF2-WPA2 throughput on {}: {:.0} H/s",
831 crk.device_name(),
832 hps
833 );
834 assert!(hps > 1000.0, "suspiciously slow: {hps} H/s");
835 }
836
837 #[test]
838 fn cpu_crack_finds_pass() {
839 let pass = b"sup3r-secret";
840 let target = synthetic_target("parafin", pass, 2);
841 let mut idx = 0usize;
842 let words: Vec<Vec<u8>> = (0..500)
843 .map(|_| {
844 idx += 1;
845 if idx == 300 { pass.to_vec() } else { format!("cpu{:07}", idx).into_bytes() }
846 })
847 .collect();
848 let mut it = words.into_iter();
849 let stop = Arc::new(AtomicBool::new(false));
850 let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop);
851 assert_eq!(found.as_deref(), Some("sup3r-secret"));
852 }
853
854 #[test]
855 fn cpu_crack_pmkid() {
856 let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
857 let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
858 let key = crypto::pmk(b"hunter2!!", b"parafin");
859 let target = CrackTarget::Pmkid(crate::common::PmkidCapture {
860 ap,
861 client: sta,
862 essid: "parafin".to_string(),
863 pmkid: crypto::pmkid_hash(&key, &ap, &sta),
864 });
865 let words: Vec<Vec<u8>> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()];
866 let mut it = words.into_iter();
867 let stop = Arc::new(AtomicBool::new(false));
868 let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop);
869 assert_eq!(found.as_deref(), Some("hunter2!!"));
870 }
871
872 #[test]
873 fn stop_flag_short_circuits() {
874 let pass = b"sup3r-secret";
875 let target = synthetic_target("parafin", pass, 2);
876 let words: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();
877 let mut it = words.into_iter();
878 let stop = Arc::new(AtomicBool::new(true));
879 assert!(cpu_crack(&target, &mut it, &mut |_, _| {}, &stop).is_none());
880 if let Some(crk) = GpuCracker::try_new() {
881 let words2: Vec<Vec<u8>> = (0..2000).map(|i| format!("zz{:07}", i).into_bytes()).collect();
882 let mut it2 = words2.into_iter();
883 assert!(crk.crack(&target, &mut it2, &mut |_, _| {}, &stop).is_none());
884 }
885 }
886}
887