| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | use std::fmt; |
| 18 | use std::sync::Arc; |
| 19 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 20 | use std::time::{Duration, Instant}; |
| 21 | |
| 22 | #[cfg(test)] |
| 23 | use crate::common::MacAddr; |
| 24 | use crate::crypto::{self, CrackTarget}; |
| 25 | use crate::rainbow; |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | pub(crate) enum PreparedTarget<'a> { |
| 32 | Handshake(&'a crate::common::HandshakeCapture, Vec<u8>), |
| 33 | Pmkid(&'a crate::common::PmkidCapture), |
| 34 | } |
| 35 | |
| 36 | |
| 37 | pub(crate) fn prepare_target(target: &CrackTarget) -> PreparedTarget<'_> { |
| 38 | match target { |
| 39 | CrackTarget::Handshake(h) => { |
| 40 | PreparedTarget::Handshake(h, crypto::zeroed_eapol(&h.eapol_m2)) |
| 41 | } |
| 42 | CrackTarget::Pmkid(p) => PreparedTarget::Pmkid(p), |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | |
| 47 | pub(crate) fn prepared_matches(prepared: &PreparedTarget, k: &[u8; 32]) -> bool { |
| 48 | match prepared { |
| 49 | PreparedTarget::Handshake(h, zeroed) => { |
| 50 | let dk = crypto::ptk(k, &h.ap, &h.client, &h.anonce, &h.snonce); |
| 51 | let m = crypto::mic_on_zeroed(&dk, zeroed, h.key_ver); |
| 52 | crypto::ct_eq16(&m, h.mic()) |
| 53 | } |
| 54 | PreparedTarget::Pmkid(p) => { |
| 55 | let dig = crypto::pmkid_hash(k, &p.ap, &p.client); |
| 56 | crypto::ct_eq16(&dig, &p.pmkid) |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | |
| 62 | |
| 63 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 64 | pub enum GpuError { |
| 65 | |
| 66 | Lost, |
| 67 | |
| 68 | |
| 69 | Timeout, |
| 70 | |
| 71 | |
| 72 | |
| 73 | Unsupported(String), |
| 74 | } |
| 75 | |
| 76 | impl fmt::Display for GpuError { |
| 77 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 78 | match self { |
| 79 | GpuError::Lost => write!(f, "GPU device lost (driver reset or disconnect)"), |
| 80 | GpuError::Timeout => write!(f, "GPU dispatch timed out after 30s"), |
| 81 | GpuError::Unsupported(r) => write!(f, "GPU path unsupported: {r}"), |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | impl std::error::Error for GpuError {} |
| 87 | |
| 88 | const BATCH: u32 = 1 << 16; |
| 89 | const WORKGROUP_SIZE: u32 = 256; |
| 90 | const ITERATIONS: u32 = 4096; |
| 91 | |
| 92 | const U32_PER_CAND_IN: usize = 16; |
| 93 | |
| 94 | const U32_PER_CAND_OUT: usize = 10; |
| 95 | |
| 96 | const HIT_U32: usize = 4; |
| 97 | |
| 98 | const P_HEADER: usize = 8; |
| 99 | const P_MSGS: usize = 32; |
| 100 | const P_BLK: usize = 48; |
| 101 | const PARAM_U32: usize = P_HEADER + P_MSGS + 2 * P_BLK + 4; |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | pub(crate) struct GpuTargetCtx { |
| 107 | params: Vec<u32>, |
| 108 | } |
| 109 | |
| 110 | impl GpuTargetCtx { |
| 111 | |
| 112 | |
| 113 | fn params_words(&self, n: u32) -> Vec<u32> { |
| 114 | let mut v = self.params.clone(); |
| 115 | v[4] = n; |
| 116 | v |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | |
| 121 | fn be_words(bytes: &[u8], out: &mut [u32]) { |
| 122 | for (i, w) in out.iter_mut().enumerate() { |
| 123 | let mut word = 0u32; |
| 124 | for (j, &b) in bytes.iter().skip(4 * i).take(4).enumerate() { |
| 125 | word |= (b as u32) << (24 - 8 * j); |
| 126 | } |
| 127 | *w = word; |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | |
| 132 | |
| 133 | fn padded_blocks(msg: &[u8]) -> (Vec<u32>, u32) { |
| 134 | let total_bits = ((64 + msg.len()) as u64) * 8; |
| 135 | let mut v = msg.to_vec(); |
| 136 | v.push(0x80); |
| 137 | while v.len() % 64 != 56 { |
| 138 | v.push(0); |
| 139 | } |
| 140 | v.extend_from_slice(&total_bits.to_be_bytes()); |
| 141 | let n_blocks = v.len() / 64; |
| 142 | let mut words = vec![0u32; n_blocks * 16]; |
| 143 | be_words(&v, &mut words); |
| 144 | (words, n_blocks as u32) |
| 145 | } |
| 146 | |
| 147 | |
| 148 | |
| 149 | fn u_msg(salt: &[u8], idx: u32) -> [u32; 16] { |
| 150 | let mut m = Vec::with_capacity(salt.len() + 4); |
| 151 | m.extend_from_slice(salt); |
| 152 | m.extend_from_slice(&idx.to_be_bytes()); |
| 153 | let (words, n) = padded_blocks(&m); |
| 154 | debug_assert_eq!(n, 1, "salt must fit one SHA1 block"); |
| 155 | let mut out = [0u32; 16]; |
| 156 | out.copy_from_slice(&words[..16]); |
| 157 | out |
| 158 | } |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | pub(crate) fn gpu_ctx(target: &CrackTarget) -> Option<GpuTargetCtx> { |
| 168 | let salt = target.essid().as_bytes(); |
| 169 | if salt.len() > 51 { |
| 170 | return None; |
| 171 | } |
| 172 | let u1_msg = u_msg(salt, 1); |
| 173 | let u2_msg = u_msg(salt, 2); |
| 174 | let mut blk1 = [0u32; 48]; |
| 175 | let mut blk2 = [0u32; 48]; |
| 176 | let mut mic = [0u32; 4]; |
| 177 | let (is_pmkid, n_blk1, n_blk2) = match target { |
| 178 | CrackTarget::Pmkid(p) => { |
| 179 | |
| 180 | let mut msg = Vec::with_capacity(8 + 6 + 6); |
| 181 | msg.extend_from_slice(b"PMK Name"); |
| 182 | msg.extend_from_slice(&p.ap.0); |
| 183 | msg.extend_from_slice(&p.client.0); |
| 184 | let (w, n) = padded_blocks(&msg); |
| 185 | blk1[..w.len()].copy_from_slice(&w); |
| 186 | be_words(&p.pmkid, &mut mic); |
| 187 | (1, n, 0) |
| 188 | } |
| 189 | CrackTarget::Handshake(h) => { |
| 190 | if h.key_ver != 2 || h.eapol_m2.len() < 99 { |
| 191 | return None; |
| 192 | } |
| 193 | |
| 194 | let mut prf = crypto::prf_stem(&h.ap, &h.client, &h.anonce, &h.snonce); |
| 195 | prf.push(0x01); |
| 196 | let (w1, n1) = padded_blocks(&prf); |
| 197 | if w1.len() > P_BLK { |
| 198 | return None; |
| 199 | } |
| 200 | blk1[..w1.len()].copy_from_slice(&w1); |
| 201 | |
| 202 | let zeroed = crypto::zeroed_eapol(&h.eapol_m2); |
| 203 | let (w2, n2) = padded_blocks(&zeroed); |
| 204 | if w2.len() > P_BLK { |
| 205 | |
| 206 | |
| 207 | return None; |
| 208 | } |
| 209 | blk2[..w2.len()].copy_from_slice(&w2); |
| 210 | be_words(h.mic(), &mut mic); |
| 211 | (0, n1, n2) |
| 212 | } |
| 213 | }; |
| 214 | let mut params = vec![0u32; PARAM_U32]; |
| 215 | params[0] = ITERATIONS << 1; |
| 216 | params[1] = is_pmkid; |
| 217 | params[2] = n_blk1; |
| 218 | params[3] = n_blk2; |
| 219 | params[P_HEADER..P_HEADER + 16].copy_from_slice(&u1_msg); |
| 220 | params[P_HEADER + 16..P_HEADER + 32].copy_from_slice(&u2_msg); |
| 221 | params[P_HEADER + P_MSGS..P_HEADER + P_MSGS + P_BLK].copy_from_slice(&blk1); |
| 222 | params[P_HEADER + P_MSGS + P_BLK..P_HEADER + P_MSGS + 2 * P_BLK].copy_from_slice(&blk2); |
| 223 | params[PARAM_U32 - 4..].copy_from_slice(&mic); |
| 224 | Some(GpuTargetCtx { params }) |
| 225 | } |
| 226 | |
| 227 | |
| 228 | |
| 229 | |
| 230 | pub(crate) fn gpu_verifiable(target: &CrackTarget) -> bool { |
| 231 | gpu_ctx(target).is_some() |
| 232 | } |
| 233 | |
| 234 | |
| 235 | fn pack_candidates(words: &[Vec<u8>]) -> Vec<u32> { |
| 236 | let mut out = vec![0u32; words.len() * U32_PER_CAND_IN]; |
| 237 | for (w, dst) in words.iter().zip(out.as_chunks_mut::<U32_PER_CAND_IN>().0) { |
| 238 | be_words(w, dst); |
| 239 | } |
| 240 | out |
| 241 | } |
| 242 | |
| 243 | |
| 244 | |
| 245 | struct PendingKernel { |
| 246 | read_buf: wgpu::Buffer, |
| 247 | slot: usize, |
| 248 | rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>, |
| 249 | sub: wgpu::SubmissionIndex, |
| 250 | read_u32: usize, |
| 251 | } |
| 252 | |
| 253 | |
| 254 | struct SlotGuard<'a> { |
| 255 | pool: &'a std::cell::RefCell<Option<KernelPool>>, |
| 256 | slot: usize, |
| 257 | } |
| 258 | |
| 259 | impl Drop for SlotGuard<'_> { |
| 260 | fn drop(&mut self) { |
| 261 | if let Some(pool) = self.pool.borrow_mut().as_mut() { |
| 262 | pool.free.push(self.slot); |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | |
| 268 | |
| 269 | struct KernelBufs { |
| 270 | in_buf: wgpu::Buffer, |
| 271 | out_buf: wgpu::Buffer, |
| 272 | hit_buf: wgpu::Buffer, |
| 273 | read_buf: wgpu::Buffer, |
| 274 | param_buf: wgpu::Buffer, |
| 275 | bind_group: wgpu::BindGroup, |
| 276 | } |
| 277 | |
| 278 | |
| 279 | |
| 280 | struct KernelPool { |
| 281 | bufs: Vec<KernelBufs>, |
| 282 | free: Vec<usize>, |
| 283 | } |
| 284 | |
| 285 | impl KernelPool { |
| 286 | fn new(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, cap: usize) -> Self { |
| 287 | let mut pool = KernelPool { |
| 288 | bufs: Vec::new(), |
| 289 | free: Vec::new(), |
| 290 | }; |
| 291 | for _ in 0..2 { |
| 292 | pool.push_slot(device, layout, cap); |
| 293 | } |
| 294 | pool |
| 295 | } |
| 296 | |
| 297 | fn push_slot(&mut self, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, cap: usize) { |
| 298 | let in_bytes = (cap * U32_PER_CAND_IN * 4) as u64; |
| 299 | let out_bytes = (cap * U32_PER_CAND_OUT * 4) as u64; |
| 300 | let hit_bytes = (HIT_U32 * 4) as u64; |
| 301 | let in_buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 302 | label: Some("candidates"), |
| 303 | size: in_bytes.max(16), |
| 304 | usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, |
| 305 | mapped_at_creation: false, |
| 306 | }); |
| 307 | let out_buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 308 | label: Some("pmks"), |
| 309 | size: out_bytes.max(16), |
| 310 | usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, |
| 311 | mapped_at_creation: false, |
| 312 | }); |
| 313 | let hit_buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 314 | label: Some("hits"), |
| 315 | size: hit_bytes, |
| 316 | usage: wgpu::BufferUsages::STORAGE |
| 317 | | wgpu::BufferUsages::COPY_DST |
| 318 | | wgpu::BufferUsages::COPY_SRC, |
| 319 | mapped_at_creation: false, |
| 320 | }); |
| 321 | let read_buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 322 | label: Some("readback"), |
| 323 | size: out_bytes.max(hit_bytes), |
| 324 | usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, |
| 325 | mapped_at_creation: false, |
| 326 | }); |
| 327 | let param_buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 328 | label: Some("params"), |
| 329 | size: (PARAM_U32 * 4) as u64, |
| 330 | usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, |
| 331 | mapped_at_creation: false, |
| 332 | }); |
| 333 | let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 334 | label: Some("pbkdf2-bg"), |
| 335 | layout, |
| 336 | entries: &[ |
| 337 | wgpu::BindGroupEntry { |
| 338 | binding: 0, |
| 339 | resource: param_buf.as_entire_binding(), |
| 340 | }, |
| 341 | wgpu::BindGroupEntry { |
| 342 | binding: 1, |
| 343 | resource: in_buf.as_entire_binding(), |
| 344 | }, |
| 345 | wgpu::BindGroupEntry { |
| 346 | binding: 2, |
| 347 | resource: out_buf.as_entire_binding(), |
| 348 | }, |
| 349 | wgpu::BindGroupEntry { |
| 350 | binding: 3, |
| 351 | resource: hit_buf.as_entire_binding(), |
| 352 | }, |
| 353 | ], |
| 354 | }); |
| 355 | self.bufs.push(KernelBufs { |
| 356 | in_buf, |
| 357 | out_buf, |
| 358 | hit_buf, |
| 359 | read_buf, |
| 360 | param_buf, |
| 361 | bind_group, |
| 362 | }); |
| 363 | self.free.push(self.bufs.len() - 1); |
| 364 | } |
| 365 | |
| 366 | |
| 367 | |
| 368 | fn take(&mut self, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, cap: usize) -> usize { |
| 369 | match self.free.pop() { |
| 370 | Some(i) => i, |
| 371 | None => { |
| 372 | self.push_slot(device, layout, cap); |
| 373 | self.free.pop().expect("push_slot frees the new slot") |
| 374 | } |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | |
| 380 | |
| 381 | #[derive(Clone, Copy)] |
| 382 | enum Readback { |
| 383 | Hits, |
| 384 | Pmks(usize), |
| 385 | } |
| 386 | |
| 387 | impl Readback { |
| 388 | fn bytes(self) -> usize { |
| 389 | match self { |
| 390 | Readback::Hits => HIT_U32 * 4, |
| 391 | Readback::Pmks(n) => n * U32_PER_CAND_OUT * 4, |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | pub struct GpuCracker { |
| 397 | device: wgpu::Device, |
| 398 | queue: wgpu::Queue, |
| 399 | pipeline: wgpu::ComputePipeline, |
| 400 | pmk_pipeline: wgpu::ComputePipeline, |
| 401 | layout: wgpu::BindGroupLayout, |
| 402 | name: String, |
| 403 | batch: u32, |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | pool: std::cell::RefCell<Option<KernelPool>>, |
| 409 | |
| 410 | |
| 411 | |
| 412 | lost: Arc<AtomicBool>, |
| 413 | } |
| 414 | |
| 415 | impl GpuCracker { |
| 416 | |
| 417 | |
| 418 | pub fn try_new() -> Option<Self> { |
| 419 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 420 | let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { |
| 421 | power_preference: wgpu::PowerPreference::HighPerformance, |
| 422 | force_fallback_adapter: false, |
| 423 | compatible_surface: None, |
| 424 | apply_limit_buckets: false, |
| 425 | })) |
| 426 | .ok()?; |
| 427 | let info = adapter.get_info(); |
| 428 | let limits = adapter.limits(); |
| 429 | |
| 430 | let in_bytes = u64::from(BATCH) * (U32_PER_CAND_IN as u64) * 4; |
| 431 | let out_bytes = u64::from(BATCH) * (U32_PER_CAND_OUT as u64) * 4; |
| 432 | if limits.max_storage_buffer_binding_size < in_bytes |
| 433 | || limits.max_storage_buffer_binding_size < out_bytes |
| 434 | || limits.max_buffer_size < in_bytes.max(out_bytes) |
| 435 | { |
| 436 | return None; |
| 437 | } |
| 438 | |
| 439 | let desc = wgpu::DeviceDescriptor { |
| 440 | label: Some("wifi_lab-pbkdf2"), |
| 441 | required_features: wgpu::Features::empty(), |
| 442 | required_limits: wgpu::Limits::default(), |
| 443 | experimental_features: wgpu::ExperimentalFeatures::disabled(), |
| 444 | memory_hints: wgpu::MemoryHints::Performance, |
| 445 | trace: wgpu::Trace::Off, |
| 446 | }; |
| 447 | let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?; |
| 448 | |
| 449 | let lost = Arc::new(AtomicBool::new(false)); |
| 450 | { |
| 451 | let lost = Arc::clone(&lost); |
| 452 | device.set_device_lost_callback(move |reason, msg| { |
| 453 | tracing::warn!("gpu device lost ({reason:?}): {msg}"); |
| 454 | lost.store(true, Ordering::Relaxed); |
| 455 | }); |
| 456 | } |
| 457 | |
| 458 | let shader_desc = wgpu::ShaderModuleDescriptor { |
| 459 | label: Some("pbkdf2.wgsl"), |
| 460 | source: wgpu::ShaderSource::Wgsl(include_str!("pbkdf2.wgsl").into()), |
| 461 | }; |
| 462 | |
| 463 | |
| 464 | |
| 465 | let shader = unsafe { |
| 466 | device.create_shader_module_trusted(shader_desc, wgpu::ShaderRuntimeChecks::unchecked()) |
| 467 | }; |
| 468 | |
| 469 | let storage_entry = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry { |
| 470 | binding, |
| 471 | visibility: wgpu::ShaderStages::COMPUTE, |
| 472 | ty: wgpu::BindingType::Buffer { |
| 473 | ty: wgpu::BufferBindingType::Storage { read_only }, |
| 474 | has_dynamic_offset: false, |
| 475 | min_binding_size: None, |
| 476 | }, |
| 477 | count: None, |
| 478 | }; |
| 479 | let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 480 | label: Some("pbkdf2-layout"), |
| 481 | entries: &[ |
| 482 | storage_entry(0, true), |
| 483 | storage_entry(1, true), |
| 484 | storage_entry(2, false), |
| 485 | storage_entry(3, false), |
| 486 | ], |
| 487 | }); |
| 488 | |
| 489 | let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 490 | label: Some("pbkdf2-pipeline-layout"), |
| 491 | bind_group_layouts: &[Some(&layout)], |
| 492 | immediate_size: 0, |
| 493 | }); |
| 494 | |
| 495 | let make_pipeline = |label, entry| { |
| 496 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 497 | label: Some(label), |
| 498 | layout: Some(&pipeline_layout), |
| 499 | module: &shader, |
| 500 | entry_point: Some(entry), |
| 501 | compilation_options: wgpu::PipelineCompilationOptions::default(), |
| 502 | cache: None, |
| 503 | }) |
| 504 | }; |
| 505 | let pipeline = make_pipeline("pbkdf2-crack-pipeline", "main"); |
| 506 | let pmk_pipeline = make_pipeline("pbkdf2-pmk-pipeline", "pmk_out"); |
| 507 | |
| 508 | Some(GpuCracker { |
| 509 | device, |
| 510 | queue, |
| 511 | pipeline, |
| 512 | pmk_pipeline, |
| 513 | layout, |
| 514 | name: format!("{} ({:?})", info.name, info.backend), |
| 515 | batch: BATCH, |
| 516 | pool: std::cell::RefCell::new(None), |
| 517 | lost, |
| 518 | }) |
| 519 | } |
| 520 | |
| 521 | pub fn device_name(&self) -> String { |
| 522 | self.name.clone() |
| 523 | } |
| 524 | |
| 525 | |
| 526 | |
| 527 | |
| 528 | fn submit_kernel( |
| 529 | &self, |
| 530 | inputs: &[u32], |
| 531 | params: &[u32], |
| 532 | readback: Readback, |
| 533 | pmk_pipeline: bool, |
| 534 | ) -> Option<PendingKernel> { |
| 535 | let n = inputs.len() / U32_PER_CAND_IN; |
| 536 | if n == 0 { |
| 537 | return None; |
| 538 | } |
| 539 | debug_assert!( |
| 540 | n <= self.batch as usize, |
| 541 | "kernel buffers sized for one batch" |
| 542 | ); |
| 543 | debug_assert_eq!(params.len(), PARAM_U32); |
| 544 | |
| 545 | let slot = { |
| 546 | let mut pool = self.pool.borrow_mut(); |
| 547 | let pool = pool.get_or_insert_with(|| { |
| 548 | KernelPool::new(&self.device, &self.layout, self.batch as usize) |
| 549 | }); |
| 550 | pool.take(&self.device, &self.layout, self.batch as usize) |
| 551 | }; |
| 552 | let (in_buf, out_buf, hit_buf, read_buf, param_buf, bind_group) = { |
| 553 | let pool = self.pool.borrow(); |
| 554 | let bufs = &pool.as_ref().expect("pool just created").bufs[slot]; |
| 555 | ( |
| 556 | bufs.in_buf.clone(), |
| 557 | bufs.out_buf.clone(), |
| 558 | bufs.hit_buf.clone(), |
| 559 | bufs.read_buf.clone(), |
| 560 | bufs.param_buf.clone(), |
| 561 | bufs.bind_group.clone(), |
| 562 | ) |
| 563 | }; |
| 564 | |
| 565 | self.queue |
| 566 | .write_buffer(¶m_buf, 0, u32s_as_bytes(params)); |
| 567 | self.queue.write_buffer(&hit_buf, 0, &[0u8; 16]); |
| 568 | self.queue.write_buffer(&in_buf, 0, u32s_as_bytes(inputs)); |
| 569 | |
| 570 | let read_u32 = readback.bytes() / 4; |
| 571 | let mut encoder = self |
| 572 | .device |
| 573 | .create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 574 | label: Some("pbkdf2-encoder"), |
| 575 | }); |
| 576 | { |
| 577 | let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 578 | label: Some("pbkdf2-pass"), |
| 579 | timestamp_writes: None, |
| 580 | }); |
| 581 | pass.set_pipeline(if pmk_pipeline { |
| 582 | &self.pmk_pipeline |
| 583 | } else { |
| 584 | &self.pipeline |
| 585 | }); |
| 586 | pass.set_bind_group(0, &bind_group, &[]); |
| 587 | |
| 588 | pass.dispatch_workgroups(n.div_ceil(WORKGROUP_SIZE as usize) as u32, 1, 1); |
| 589 | } |
| 590 | match readback { |
| 591 | Readback::Hits => { |
| 592 | encoder.copy_buffer_to_buffer(&hit_buf, 0, &read_buf, 0, readback.bytes() as u64) |
| 593 | } |
| 594 | Readback::Pmks(_) => { |
| 595 | encoder.copy_buffer_to_buffer(&out_buf, 0, &read_buf, 0, readback.bytes() as u64) |
| 596 | } |
| 597 | } |
| 598 | let sub = self.queue.submit([encoder.finish()]); |
| 599 | |
| 600 | let (tx, rx) = std::sync::mpsc::channel(); |
| 601 | read_buf |
| 602 | .slice(..readback.bytes() as u64) |
| 603 | .map_async(wgpu::MapMode::Read, move |res| { |
| 604 | let _ = tx.send(res); |
| 605 | }); |
| 606 | |
| 607 | Some(PendingKernel { |
| 608 | read_buf, |
| 609 | slot, |
| 610 | rx, |
| 611 | sub, |
| 612 | read_u32, |
| 613 | }) |
| 614 | } |
| 615 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | |
| 620 | |
| 621 | |
| 622 | |
| 623 | fn wait_kernel(&self, pending: PendingKernel) -> Result<Vec<u32>, GpuError> { |
| 624 | let PendingKernel { |
| 625 | read_buf, |
| 626 | slot, |
| 627 | rx, |
| 628 | sub, |
| 629 | read_u32, |
| 630 | } = pending; |
| 631 | |
| 632 | |
| 633 | let _guard = SlotGuard { |
| 634 | pool: &self.pool, |
| 635 | slot, |
| 636 | }; |
| 637 | |
| 638 | let mut waited = Duration::ZERO; |
| 639 | let step = Duration::from_millis(8); |
| 640 | let limit = Duration::from_secs(30); |
| 641 | loop { |
| 642 | match self.device.poll(wgpu::PollType::Wait { |
| 643 | submission_index: Some(sub.clone()), |
| 644 | timeout: Some(step), |
| 645 | }) { |
| 646 | Ok(_) | Err(wgpu::PollError::Timeout) => { |
| 647 | if let Ok(res) = rx.try_recv() { |
| 648 | match res { |
| 649 | Ok(()) => break, |
| 650 | Err(e) => { |
| 651 | tracing::warn!("map_async failed: {e}"); |
| 652 | read_buf.unmap(); |
| 653 | return Err(if self.lost.load(Ordering::Relaxed) { |
| 654 | GpuError::Lost |
| 655 | } else { |
| 656 | GpuError::Unsupported(format!("readback map failed: {e}")) |
| 657 | }); |
| 658 | } |
| 659 | } |
| 660 | } |
| 661 | waited += step; |
| 662 | if waited >= limit { |
| 663 | let err = if self.lost.load(Ordering::Relaxed) { |
| 664 | GpuError::Lost |
| 665 | } else { |
| 666 | tracing::warn!("gpu dispatch timed out after {limit:?}"); |
| 667 | GpuError::Timeout |
| 668 | }; |
| 669 | return Err(err); |
| 670 | } |
| 671 | } |
| 672 | Err(e) => { |
| 673 | tracing::warn!("device poll error: {e}"); |
| 674 | return Err(if self.lost.load(Ordering::Relaxed) { |
| 675 | GpuError::Lost |
| 676 | } else { |
| 677 | GpuError::Unsupported(format!("device poll error: {e}")) |
| 678 | }); |
| 679 | } |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | let bytes = read_u32 * 4; |
| 684 | let view = read_buf |
| 685 | .slice(..bytes as u64) |
| 686 | .get_mapped_range() |
| 687 | .map_err(|e| { |
| 688 | if self.lost.load(Ordering::Relaxed) { |
| 689 | GpuError::Lost |
| 690 | } else { |
| 691 | GpuError::Unsupported(format!("readback range map failed: {e}")) |
| 692 | } |
| 693 | })?; |
| 694 | let mut out = Vec::with_capacity(read_u32); |
| 695 | for chunk in view[..bytes].as_chunks::<4>().0 { |
| 696 | out.push(u32::from_le_bytes(*chunk)); |
| 697 | } |
| 698 | drop(view); |
| 699 | read_buf.unmap(); |
| 700 | Ok(out) |
| 701 | } |
| 702 | |
| 703 | |
| 704 | |
| 705 | |
| 706 | |
| 707 | |
| 708 | |
| 709 | |
| 710 | pub(crate) fn pmk_batch_gpu( |
| 711 | &self, |
| 712 | words: &[Vec<u8>], |
| 713 | salt: &[u8], |
| 714 | ) -> Result<Vec<[u8; 32]>, GpuError> { |
| 715 | if salt.len() > 51 { |
| 716 | return Err(GpuError::Unsupported(format!( |
| 717 | "salt/essid of {} bytes exceeds the shader's 51-byte one-block limit", |
| 718 | salt.len() |
| 719 | ))); |
| 720 | } |
| 721 | let mut params = vec![0u32; PARAM_U32]; |
| 722 | params[0] = ITERATIONS << 1; |
| 723 | let u1 = u_msg(salt, 1); |
| 724 | let u2 = u_msg(salt, 2); |
| 725 | params[P_HEADER..P_HEADER + 16].copy_from_slice(&u1); |
| 726 | params[P_HEADER + 16..P_HEADER + 32].copy_from_slice(&u2); |
| 727 | |
| 728 | let mut cur: &[Vec<u8>] = words; |
| 729 | let mut retried = false; |
| 730 | loop { |
| 731 | params[4] = cur.len() as u32; |
| 732 | let inputs = pack_candidates(cur); |
| 733 | let Some(sub) = self.submit_kernel(&inputs, ¶ms, Readback::Pmks(cur.len()), true) |
| 734 | else { |
| 735 | |
| 736 | return Ok(Vec::new()); |
| 737 | }; |
| 738 | match self.wait_kernel(sub) { |
| 739 | Ok(out) => { |
| 740 | let mut pmks = Vec::with_capacity(cur.len()); |
| 741 | for row in out.as_chunks::<U32_PER_CAND_OUT>().0 { |
| 742 | let mut pmk = [0u8; 32]; |
| 743 | for (i, w) in row[..8].iter().enumerate() { |
| 744 | pmk[i * 4..i * 4 + 4].copy_from_slice(&w.to_be_bytes()); |
| 745 | } |
| 746 | pmks.push(pmk); |
| 747 | } |
| 748 | return Ok(pmks); |
| 749 | } |
| 750 | Err(e) => { |
| 751 | if retried || cur.len() == 1 { |
| 752 | |
| 753 | |
| 754 | return Err(e); |
| 755 | } |
| 756 | |
| 757 | tracing::warn!( |
| 758 | "pmk batch of {} failed ({e}); halving and retrying", |
| 759 | cur.len() |
| 760 | ); |
| 761 | let half = cur.len().div_ceil(2); |
| 762 | cur = &cur[..half]; |
| 763 | retried = true; |
| 764 | } |
| 765 | } |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | |
| 774 | |
| 775 | |
| 776 | |
| 777 | |
| 778 | |
| 779 | |
| 780 | |
| 781 | |
| 782 | |
| 783 | |
| 784 | pub fn crack( |
| 785 | &self, |
| 786 | target: &CrackTarget, |
| 787 | words: &mut dyn Iterator<Item = Vec<u8>>, |
| 788 | progress: &mut dyn FnMut(u64, f64), |
| 789 | stop: &Arc<AtomicBool>, |
| 790 | ) -> Result<Option<String>, GpuError> { |
| 791 | let ctx = gpu_ctx(target).ok_or_else(|| { |
| 792 | GpuError::Unsupported( |
| 793 | "target not expressible in the SHA1 shader (key_ver/length); route via gpu_verifiable" |
| 794 | .to_string(), |
| 795 | ) |
| 796 | })?; |
| 797 | let mut done = 0u64; |
| 798 | let started = Instant::now(); |
| 799 | let batch_cap = self.batch as usize; |
| 800 | |
| 801 | fn collect(words: &mut dyn Iterator<Item = Vec<u8>>, cap: usize) -> Vec<Vec<u8>> { |
| 802 | let mut batch: Vec<Vec<u8>> = Vec::with_capacity(cap); |
| 803 | while batch.len() < cap { |
| 804 | match words.next() { |
| 805 | Some(w) => batch.push(w), |
| 806 | None => break, |
| 807 | } |
| 808 | } |
| 809 | batch |
| 810 | } |
| 811 | let tick = |done: u64, started: Instant, progress: &mut dyn FnMut(u64, f64)| { |
| 812 | let secs = started.elapsed().as_secs_f64().max(1e-6); |
| 813 | progress(done, done as f64 / secs); |
| 814 | }; |
| 815 | |
| 816 | |
| 817 | let drain = |pending: Option<PendingKernel>| { |
| 818 | if let Some(p) = pending { |
| 819 | let _ = self.wait_kernel(p); |
| 820 | } |
| 821 | }; |
| 822 | |
| 823 | let mut cur_words = collect(words, batch_cap); |
| 824 | if cur_words.is_empty() { |
| 825 | return Ok(None); |
| 826 | } |
| 827 | let mut pending = Some( |
| 828 | self.submit_kernel( |
| 829 | &pack_candidates(&cur_words), |
| 830 | &ctx.params_words(cur_words.len() as u32), |
| 831 | Readback::Hits, |
| 832 | false, |
| 833 | ) |
| 834 | .expect("non-empty batch must dispatch"), |
| 835 | ); |
| 836 | |
| 837 | loop { |
| 838 | if stop.load(Ordering::Relaxed) { |
| 839 | drain(pending.take()); |
| 840 | return Ok(None); |
| 841 | } |
| 842 | |
| 843 | |
| 844 | let next_words = collect(words, batch_cap); |
| 845 | let next_pending = if next_words.is_empty() { |
| 846 | None |
| 847 | } else { |
| 848 | Some( |
| 849 | self.submit_kernel( |
| 850 | &pack_candidates(&next_words), |
| 851 | &ctx.params_words(next_words.len() as u32), |
| 852 | Readback::Hits, |
| 853 | false, |
| 854 | ) |
| 855 | .expect("non-empty batch must dispatch"), |
| 856 | ) |
| 857 | }; |
| 858 | |
| 859 | let cur_pending = pending.take().expect("pipeline: one batch in flight"); |
| 860 | let hit = match self.wait_kernel(cur_pending) { |
| 861 | Ok(hit) => hit, |
| 862 | Err(e) => { |
| 863 | drain(next_pending); |
| 864 | return Err(e); |
| 865 | } |
| 866 | }; |
| 867 | |
| 868 | |
| 869 | if hit[0] != 0 { |
| 870 | drain(next_pending); |
| 871 | let gid = hit[1] as usize; |
| 872 | done += gid as u64 + 1; |
| 873 | tick(done, started, progress); |
| 874 | return Ok(cur_words |
| 875 | .get(gid) |
| 876 | .and_then(|w| String::from_utf8(w.clone()).ok())); |
| 877 | } |
| 878 | done += cur_words.len() as u64; |
| 879 | tick(done, started, progress); |
| 880 | |
| 881 | let Some(next_pending) = next_pending else { |
| 882 | return Ok(None); |
| 883 | }; |
| 884 | cur_words = next_words; |
| 885 | pending = Some(next_pending); |
| 886 | } |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | |
| 891 | |
| 892 | |
| 893 | |
| 894 | #[cfg(target_endian = "little")] |
| 895 | fn u32s_as_bytes(v: &[u32]) -> &[u8] { |
| 896 | |
| 897 | |
| 898 | unsafe { std::slice::from_raw_parts(v.as_ptr().cast::<u8>(), std::mem::size_of_val(v)) } |
| 899 | } |
| 900 | |
| 901 | #[cfg(target_endian = "big")] |
| 902 | compile_error!("GPU cracker wire format assumes a little-endian host"); |
| 903 | |
| 904 | |
| 905 | |
| 906 | |
| 907 | |
| 908 | |
| 909 | |
| 910 | |
| 911 | |
| 912 | |
| 913 | pub struct CpuPmkSink { |
| 914 | w: Option<rainbow::TableWriter>, |
| 915 | log: Box<dyn FnMut(String) + Send>, |
| 916 | } |
| 917 | |
| 918 | impl CpuPmkSink { |
| 919 | pub fn new(w: rainbow::TableWriter, log: Box<dyn FnMut(String) + Send>) -> Self { |
| 920 | CpuPmkSink { w: Some(w), log } |
| 921 | } |
| 922 | |
| 923 | |
| 924 | pub fn push(&mut self, pmk: &[u8; 32], word: &[u8]) { |
| 925 | if let Some(w) = &mut self.w |
| 926 | && let Err(e) = w.push(pmk, word) |
| 927 | { |
| 928 | (self.log)(format!( |
| 929 | "pmk cache: write failed ({e}) — cache left partial" |
| 930 | )); |
| 931 | self.w = None; |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | |
| 936 | pub fn finish(self) -> std::io::Result<u64> { |
| 937 | match self.w { |
| 938 | Some(w) => w.finish(), |
| 939 | None => Ok(0), |
| 940 | } |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | |
| 945 | |
| 946 | |
| 947 | pub fn cpu_crack( |
| 948 | target: &CrackTarget, |
| 949 | words: &mut dyn Iterator<Item = Vec<u8>>, |
| 950 | progress: &mut dyn FnMut(u64, f64), |
| 951 | stop: &Arc<AtomicBool>, |
| 952 | cache_sink: Option<&mut CpuPmkSink>, |
| 953 | ) -> Option<String> { |
| 954 | if matches!(target, CrackTarget::Handshake(h) if h.eapol_m2.len() < 99) { |
| 955 | return None; |
| 956 | } |
| 957 | let salt = target.essid().as_bytes(); |
| 958 | let prepared = prepare_target(target); |
| 959 | let mut sink = cache_sink; |
| 960 | let mut done = 0u64; |
| 961 | let started = Instant::now(); |
| 962 | const CPU_BATCH: usize = 512; |
| 963 | |
| 964 | loop { |
| 965 | if stop.load(Ordering::Relaxed) { |
| 966 | return None; |
| 967 | } |
| 968 | let mut batch: Vec<Vec<u8>> = Vec::with_capacity(CPU_BATCH); |
| 969 | while batch.len() < CPU_BATCH { |
| 970 | match words.next() { |
| 971 | Some(w) => batch.push(w), |
| 972 | None => break, |
| 973 | } |
| 974 | } |
| 975 | if batch.is_empty() { |
| 976 | return None; |
| 977 | } |
| 978 | for w in &batch { |
| 979 | done += 1; |
| 980 | let key = crypto::pmk(w, salt); |
| 981 | if let Some(s) = sink.as_deref_mut() { |
| 982 | s.push(&key, w); |
| 983 | } |
| 984 | if prepared_matches(&prepared, &key) { |
| 985 | return String::from_utf8(w.clone()).ok(); |
| 986 | } |
| 987 | } |
| 988 | let secs = started.elapsed().as_secs_f64().max(1e-6); |
| 989 | progress(done, done as f64 / secs); |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | |
| 994 | |
| 995 | #[cfg(test)] |
| 996 | mod tests { |
| 997 | use super::*; |
| 998 | use crate::crypto; |
| 999 | |
| 1000 | fn build_eapol_m2(key_ver: u8, snonce: &[u8; 32], replay: u64) -> Vec<u8> { |
| 1001 | let mut f = Vec::with_capacity(99); |
| 1002 | f.push(0x02); |
| 1003 | f.push(0x03); |
| 1004 | f.extend_from_slice(&95u16.to_be_bytes()); |
| 1005 | f.push(0x02); |
| 1006 | let info: u16 = 0x0100 | 0x0080 | (key_ver as u16 & 0x7); |
| 1007 | f.extend_from_slice(&info.to_be_bytes()); |
| 1008 | f.extend_from_slice(&16u16.to_be_bytes()); |
| 1009 | f.extend_from_slice(&replay.to_be_bytes()); |
| 1010 | f.extend_from_slice(snonce); |
| 1011 | f.extend_from_slice(&[0u8; 16]); |
| 1012 | f.extend_from_slice(&[0u8; 8]); |
| 1013 | f.extend_from_slice(&[0u8; 8]); |
| 1014 | f.extend_from_slice(&[0u8; 16]); |
| 1015 | f.extend_from_slice(&0u16.to_be_bytes()); |
| 1016 | f |
| 1017 | } |
| 1018 | |
| 1019 | pub(crate) fn synthetic_target(ssid: &str, pass: &[u8], key_ver: u8) -> CrackTarget { |
| 1020 | let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap(); |
| 1021 | let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap(); |
| 1022 | let anonce: [u8; 32] = [0x5a; 32]; |
| 1023 | let snonce: [u8; 32] = [0xc3; 32]; |
| 1024 | let key = crypto::pmk(pass, ssid.as_bytes()); |
| 1025 | let dk = crypto::ptk(&key, &ap, &sta, &anonce, &snonce); |
| 1026 | let frame = build_eapol_m2(key_ver, &snonce, 1); |
| 1027 | let m = crypto::mic_on_zeroed(&dk, &crypto::zeroed_eapol(&frame), key_ver); |
| 1028 | CrackTarget::Handshake(crate::common::HandshakeCapture::new( |
| 1029 | ap, |
| 1030 | sta, |
| 1031 | ssid.to_string(), |
| 1032 | anonce, |
| 1033 | snonce, |
| 1034 | m, |
| 1035 | frame, |
| 1036 | key_ver, |
| 1037 | )) |
| 1038 | } |
| 1039 | |
| 1040 | pub(crate) fn synthetic_pmkid(ssid: &str, pass: &[u8]) -> CrackTarget { |
| 1041 | let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap(); |
| 1042 | let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap(); |
| 1043 | let key = crypto::pmk(pass, ssid.as_bytes()); |
| 1044 | CrackTarget::Pmkid(crate::common::PmkidCapture { |
| 1045 | ap, |
| 1046 | client: sta, |
| 1047 | essid: ssid.to_string(), |
| 1048 | pmkid: crypto::pmkid_hash(&key, &ap, &sta), |
| 1049 | }) |
| 1050 | } |
| 1051 | |
| 1052 | #[test] |
| 1053 | fn host_padded_blocks_match_reference() { |
| 1054 | |
| 1055 | |
| 1056 | |
| 1057 | |
| 1058 | |
| 1059 | |
| 1060 | let msg = b"PMK Name012345"; |
| 1061 | let (words, n) = padded_blocks(msg); |
| 1062 | assert_eq!(n, 1); |
| 1063 | let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_be_bytes()).collect(); |
| 1064 | assert_eq!(&bytes[..msg.len()], msg); |
| 1065 | assert_eq!(bytes[msg.len()], 0x80); |
| 1066 | assert_eq!( |
| 1067 | u64::from_be_bytes(bytes[56..64].try_into().unwrap()), |
| 1068 | ((64 + msg.len()) as u64) * 8 |
| 1069 | ); |
| 1070 | } |
| 1071 | |
| 1072 | #[test] |
| 1073 | fn gpu_available_and_pmk_matches() { |
| 1074 | let Some(crk) = GpuCracker::try_new() else { |
| 1075 | eprintln!("no GPU adapter, skipping"); |
| 1076 | return; |
| 1077 | }; |
| 1078 | let salt = b"testnet"; |
| 1079 | let words: Vec<Vec<u8>> = (0..16) |
| 1080 | .map(|i| format!("cand{:06}", i).into_bytes()) |
| 1081 | .collect(); |
| 1082 | let pmks = crk |
| 1083 | .pmk_batch_gpu(&words, salt) |
| 1084 | .expect("kernel must complete"); |
| 1085 | assert_eq!(pmks.len(), words.len()); |
| 1086 | for (w, k) in words.iter().zip(pmks.iter()) { |
| 1087 | let mut dk = [0u8; 40]; |
| 1088 | crypto::pbkdf2_hmac_sha1(w, salt, 4096, &mut dk); |
| 1089 | assert_eq!(&k[..], &dk[..32], "GPU PMK mismatch for {w:?}"); |
| 1090 | |
| 1091 | assert_eq!(k, &crypto::pmk(w, salt), "crypto::pmk mismatch for {w:?}"); |
| 1092 | } |
| 1093 | } |
| 1094 | |
| 1095 | #[test] |
| 1096 | #[ignore = "perf bench: full crack-loop effective throughput"] |
| 1097 | fn crack_loop_effective_hps() { |
| 1098 | let Some(crk) = GpuCracker::try_new() else { |
| 1099 | eprintln!("no GPU adapter, skipping"); |
| 1100 | return; |
| 1101 | }; |
| 1102 | let target = synthetic_target("testnet", b"sup3r-secret", 2); |
| 1103 | const N: usize = 65536 * 6; |
| 1104 | let words: Vec<Vec<u8>> = (0..N) |
| 1105 | .map(|i| format!("probe{i:09}").into_bytes()) |
| 1106 | .collect(); |
| 1107 | let mut it = words.into_iter(); |
| 1108 | let stop = Arc::new(AtomicBool::new(false)); |
| 1109 | let t0 = Instant::now(); |
| 1110 | let found = crk.crack(&target, &mut it, &mut |_, _| {}, &stop); |
| 1111 | assert!( |
| 1112 | matches!(found, Ok(None)), |
| 1113 | "unexpected crack result: {found:?}" |
| 1114 | ); |
| 1115 | let wall = t0.elapsed().as_secs_f64(); |
| 1116 | eprintln!( |
| 1117 | "full crack loop on {}: {:.0} H/s effective ({} candidates in {:.2}s)", |
| 1118 | crk.device_name(), |
| 1119 | N as f64 / wall, |
| 1120 | N, |
| 1121 | wall |
| 1122 | ); |
| 1123 | |
| 1124 | assert!(N as f64 / wall > 50_000.0, "effective throughput collapsed"); |
| 1125 | } |
| 1126 | |
| 1127 | #[test] |
| 1128 | fn gpu_finds_planted_pass() { |
| 1129 | let Some(crk) = GpuCracker::try_new() else { |
| 1130 | eprintln!("no GPU adapter, skipping"); |
| 1131 | return; |
| 1132 | }; |
| 1133 | eprintln!("gpu device: {}", crk.device_name()); |
| 1134 | let pass = b"sup3r-secret"; |
| 1135 | let target = synthetic_target("testnet", pass, 2); |
| 1136 | |
| 1137 | const TOTAL: usize = 5000; |
| 1138 | let mut idx = 0usize; |
| 1139 | let words: Vec<Vec<u8>> = (0..TOTAL) |
| 1140 | .map(|_| { |
| 1141 | idx += 1; |
| 1142 | if idx == 3800 { |
| 1143 | pass.to_vec() |
| 1144 | } else { |
| 1145 | format!("w{:07}", idx).into_bytes() |
| 1146 | } |
| 1147 | }) |
| 1148 | .collect(); |
| 1149 | let mut it = words.into_iter(); |
| 1150 | let stop = Arc::new(AtomicBool::new(false)); |
| 1151 | let (mut last_done, mut last_hps) = (0u64, 0f64); |
| 1152 | let found = crk |
| 1153 | .crack( |
| 1154 | &target, |
| 1155 | &mut it, |
| 1156 | &mut |d, h| { |
| 1157 | last_done = d; |
| 1158 | last_hps = h; |
| 1159 | }, |
| 1160 | &stop, |
| 1161 | ) |
| 1162 | .expect("backend must not fail on this dispatch"); |
| 1163 | assert_eq!(found.as_deref(), Some("sup3r-secret")); |
| 1164 | |
| 1165 | assert!(last_done <= 65536, "progress reported {last_done}"); |
| 1166 | assert!(last_hps >= 0.0); |
| 1167 | } |
| 1168 | |
| 1169 | #[test] |
| 1170 | fn gpu_finds_planted_pmkid() { |
| 1171 | let Some(crk) = GpuCracker::try_new() else { |
| 1172 | eprintln!("no GPU adapter, skipping"); |
| 1173 | return; |
| 1174 | }; |
| 1175 | let target = synthetic_pmkid("testnet", b"hunter2!!"); |
| 1176 | let words: Vec<Vec<u8>> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()]; |
| 1177 | let mut it = words.into_iter(); |
| 1178 | let stop = Arc::new(AtomicBool::new(false)); |
| 1179 | let found = crk |
| 1180 | .crack(&target, &mut it, &mut |_, _| {}, &stop) |
| 1181 | .expect("backend must not fail on this dispatch"); |
| 1182 | assert_eq!(found.as_deref(), Some("hunter2!!")); |
| 1183 | } |
| 1184 | |
| 1185 | #[test] |
| 1186 | fn gpu_rejects_wrong_pass_and_routes_kv3() { |
| 1187 | let Some(crk) = GpuCracker::try_new() else { |
| 1188 | eprintln!("no GPU adapter, skipping"); |
| 1189 | return; |
| 1190 | }; |
| 1191 | |
| 1192 | let target = synthetic_target("testnet", b"sup3r-secret", 2); |
| 1193 | let words: Vec<Vec<u8>> = (0..64) |
| 1194 | .map(|i| format!("zz{:07}", i).into_bytes()) |
| 1195 | .collect(); |
| 1196 | let mut it = words.into_iter(); |
| 1197 | let stop = Arc::new(AtomicBool::new(false)); |
| 1198 | assert_eq!( |
| 1199 | crk.crack(&target, &mut it, &mut |_, _| {}, &stop).ok(), |
| 1200 | Some(None) |
| 1201 | ); |
| 1202 | |
| 1203 | let kv3 = synthetic_target("testnet", b"sup3r-secret", 3); |
| 1204 | assert!(!gpu_verifiable(&kv3)); |
| 1205 | |
| 1206 | let kv1 = synthetic_target("testnet", b"sup3r-secret", 1); |
| 1207 | assert!(!gpu_verifiable(&kv1)); |
| 1208 | |
| 1209 | |
| 1210 | let mut no_words = Vec::new().into_iter(); |
| 1211 | let res = crk.crack(&kv3, &mut no_words, &mut |_, _| {}, &stop); |
| 1212 | assert!(matches!(res, Err(GpuError::Unsupported(_)))); |
| 1213 | |
| 1214 | let long = synthetic_target(&"s".repeat(52), b"sup3r-secret", 2); |
| 1215 | assert!(!gpu_verifiable(&long)); |
| 1216 | } |
| 1217 | |
| 1218 | #[test] |
| 1219 | fn cpu_crack_finds_pass() { |
| 1220 | let pass = b"sup3r-secret"; |
| 1221 | let target = synthetic_target("testnet", pass, 2); |
| 1222 | let mut idx = 0usize; |
| 1223 | let words: Vec<Vec<u8>> = (0..500) |
| 1224 | .map(|_| { |
| 1225 | idx += 1; |
| 1226 | if idx == 300 { |
| 1227 | pass.to_vec() |
| 1228 | } else { |
| 1229 | format!("cpu{:07}", idx).into_bytes() |
| 1230 | } |
| 1231 | }) |
| 1232 | .collect(); |
| 1233 | let mut it = words.into_iter(); |
| 1234 | let stop = Arc::new(AtomicBool::new(false)); |
| 1235 | let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop, None); |
| 1236 | assert_eq!(found.as_deref(), Some("sup3r-secret")); |
| 1237 | } |
| 1238 | |
| 1239 | #[test] |
| 1240 | fn cpu_crack_pmkid() { |
| 1241 | let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap(); |
| 1242 | let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap(); |
| 1243 | let key = crypto::pmk(b"hunter2!!", b"testnet"); |
| 1244 | let target = CrackTarget::Pmkid(crate::common::PmkidCapture { |
| 1245 | ap, |
| 1246 | client: sta, |
| 1247 | essid: "testnet".to_string(), |
| 1248 | pmkid: crypto::pmkid_hash(&key, &ap, &sta), |
| 1249 | }); |
| 1250 | let words: Vec<Vec<u8>> = vec![b"nope-nope".to_vec(), b"hunter2!!".to_vec()]; |
| 1251 | let mut it = words.into_iter(); |
| 1252 | let stop = Arc::new(AtomicBool::new(false)); |
| 1253 | let found = cpu_crack(&target, &mut it, &mut |_, _| {}, &stop, None); |
| 1254 | assert_eq!(found.as_deref(), Some("hunter2!!")); |
| 1255 | } |
| 1256 | |
| 1257 | #[test] |
| 1258 | fn stop_flag_short_circuits() { |
| 1259 | let pass = b"sup3r-secret"; |
| 1260 | let target = synthetic_target("testnet", pass, 2); |
| 1261 | let words: Vec<Vec<u8>> = (0..2000) |
| 1262 | .map(|i| format!("zz{:07}", i).into_bytes()) |
| 1263 | .collect(); |
| 1264 | let mut it = words.into_iter(); |
| 1265 | let stop = Arc::new(AtomicBool::new(true)); |
| 1266 | assert!(cpu_crack(&target, &mut it, &mut |_, _| {}, &stop, None).is_none()); |
| 1267 | if let Some(crk) = GpuCracker::try_new() { |
| 1268 | let words2: Vec<Vec<u8>> = (0..2000) |
| 1269 | .map(|i| format!("zz{:07}", i).into_bytes()) |
| 1270 | .collect(); |
| 1271 | let mut it2 = words2.into_iter(); |
| 1272 | assert_eq!( |
| 1273 | crk.crack(&target, &mut it2, &mut |_, _| {}, &stop).ok(), |
| 1274 | Some(None) |
| 1275 | ); |
| 1276 | } |
| 1277 | } |
| 1278 | |
| 1279 | |
| 1280 | |
| 1281 | |
| 1282 | |
| 1283 | |
| 1284 | #[test] |
| 1285 | fn gpu_ctx_rejects_overlong_eapol() { |
| 1286 | let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap(); |
| 1287 | let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap(); |
| 1288 | let anonce = [0x5a; 32]; |
| 1289 | let snonce = [0xc3; 32]; |
| 1290 | let mk = |eapol_len: usize| { |
| 1291 | CrackTarget::Handshake(crate::common::HandshakeCapture::new( |
| 1292 | ap, |
| 1293 | sta, |
| 1294 | "testnet".to_string(), |
| 1295 | anonce, |
| 1296 | snonce, |
| 1297 | [0u8; 16], |
| 1298 | vec![0x01; eapol_len], |
| 1299 | 2, |
| 1300 | )) |
| 1301 | }; |
| 1302 | |
| 1303 | assert!( |
| 1304 | gpu_ctx(&mk(184)).is_none(), |
| 1305 | "overlong frame must route to CPU" |
| 1306 | ); |
| 1307 | assert!( |
| 1308 | gpu_ctx(&mk(500)).is_none(), |
| 1309 | "absurd frame must route to CPU" |
| 1310 | ); |
| 1311 | |
| 1312 | assert!( |
| 1313 | gpu_ctx(&mk(99)).is_some(), |
| 1314 | "min M2 frame must stay GPU-verifiable" |
| 1315 | ); |
| 1316 | assert!( |
| 1317 | gpu_ctx(&mk(183)).is_some(), |
| 1318 | "largest 3-block frame must stay GPU-verifiable" |
| 1319 | ); |
| 1320 | } |
| 1321 | |
| 1322 | |
| 1323 | |
| 1324 | #[test] |
| 1325 | fn gpu_ctx_routes_non_sha1_key_vers() { |
| 1326 | let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap(); |
| 1327 | let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap(); |
| 1328 | let frame = vec![0x01; 99]; |
| 1329 | for kv in [1u8, 3] { |
| 1330 | let t = CrackTarget::Handshake(crate::common::HandshakeCapture::new( |
| 1331 | ap, |
| 1332 | sta, |
| 1333 | "testnet".to_string(), |
| 1334 | [0x5a; 32], |
| 1335 | [0xc3; 32], |
| 1336 | [0u8; 16], |
| 1337 | frame.clone(), |
| 1338 | kv, |
| 1339 | )); |
| 1340 | assert!(gpu_ctx(&t).is_none(), "key_ver {kv} must route to CPU"); |
| 1341 | } |
| 1342 | } |
| 1343 | |
| 1344 | #[test] |
| 1345 | fn gpu_error_display_is_actionable() { |
| 1346 | assert!(GpuError::Lost.to_string().contains("device lost")); |
| 1347 | assert!(GpuError::Timeout.to_string().contains("timed out")); |
| 1348 | assert!(GpuError::Unsupported("x".into()).to_string().contains('x')); |
| 1349 | |
| 1350 | let e: &dyn std::error::Error = &GpuError::Lost; |
| 1351 | assert!(!e.to_string().is_empty()); |
| 1352 | } |
| 1353 | } |