forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

crypto.rs902 lines, 30.9 KiBHistoryRawDownload
1//! CPU reference implementation of WPA2-PSK cryptographic primitives:
2//! PBKDF2-SHA1 PMK derivation, 802.11 §12.7.1.2 PRF-512 PTK expansion,
3//! EAPOL-Key MIC (HMAC-MD5/HMAC-SHA1-128 and hand-rolled AES-128-CMAC), PMKID hash,
4//! verification and hashcat 22000 line parsing.
5
6use anyhow::{Context, Result, anyhow, bail};
7
8use crate::common::{HandshakeCapture, MacAddr, PmkidCapture};
9
10/// Something the cracker can attack: a 4-way handshake or a PMKID.
11#[derive(Clone, Debug)]
12pub enum CrackTarget {
13 Handshake(HandshakeCapture),
14 Pmkid(PmkidCapture),
15}
16
17impl CrackTarget {
18 pub fn essid(&self) -> &str {
19 match self {
20 CrackTarget::Handshake(h) => &h.essid,
21 CrackTarget::Pmkid(p) => &p.essid,
22 }
23 }
24
25 pub fn describe(&self) -> String {
26 match self {
27 CrackTarget::Handshake(h) => format!(
28 "handshake ap={} sta={} essid=\"{}\" key_ver={}",
29 h.ap, h.client, h.essid, h.key_ver
30 ),
31 CrackTarget::Pmkid(p) => {
32 format!("pmkid ap={} sta={} essid=\"{}\"", p.ap, p.client, p.essid)
33 }
34 }
35 }
36}
37
38/// PBKDF2-HMAC-SHA1 with a 20-byte digest per block. Implemented by hand so
39/// we don't depend on the pbkdf2 crate re-exports lining up with the local
40/// sha1/hmac versions (digest 0.10 vs 0.11 drift); c=4096 is the caller's
41/// problem, this version is generic.
42pub fn pbkdf2_hmac_sha1(pass: &[u8], salt: &[u8], iterations: u32, out: &mut [u8]) {
43 use hmac::{Hmac, Mac};
44 for (i, chunk) in out.chunks_mut(20).enumerate() {
45 let idx = (i + 1) as u32;
46 let mut mac = <Hmac<sha1::Sha1> as Mac>::new_from_slice(pass)
47 .expect("HMAC-SHA1 accepts any key length");
48 mac.update(salt);
49 mac.update(&idx.to_be_bytes());
50 let mut u = mac.finalize().into_bytes();
51 let mut t = u;
52 for _ in 1..iterations {
53 let mut mac = <Hmac<sha1::Sha1> as Mac>::new_from_slice(pass).expect("hmac");
54 mac.update(&u);
55 u = mac.finalize().into_bytes();
56 for (tb, ub) in t.iter_mut().zip(u.iter()) {
57 *tb ^= ub;
58 }
59 }
60 let n = chunk.len();
61 chunk.copy_from_slice(&t[..n]);
62 }
63}
64
65/// PMK = PBKDF2-HMAC-SHA1(pass, ssid, 4096, 32).
66pub fn pmk(pass: &[u8], ssid: &[u8]) -> [u8; 32] {
67 let mut out = [0u8; 32];
68 pbkdf2_hmac_sha1(pass, ssid, 4096, &mut out);
69 out
70}
71
72/// PRF message stem ("Pairwise key expansion" || 0x00 || A || B, 99
73/// bytes): A = min(ap,sta)||max(ap,sta), B = min(anonce,snonce)||
74/// max(anonce,snonce). Shared by [`ptk`] and the GPU kernel's per-target
75/// KCK message (which appends counter byte 0x01).
76pub(crate) fn prf_stem(
77 ap: &MacAddr,
78 sta: &MacAddr,
79 anonce: &[u8; 32],
80 snonce: &[u8; 32],
81) -> Vec<u8> {
82 let mut a_pair = [0u8; 12];
83 if ap.0 <= sta.0 {
84 a_pair[..6].copy_from_slice(&ap.0);
85 a_pair[6..].copy_from_slice(&sta.0);
86 } else {
87 a_pair[..6].copy_from_slice(&sta.0);
88 a_pair[6..].copy_from_slice(&ap.0);
89 }
90 let mut b_pair = [0u8; 64];
91 if anonce <= snonce {
92 b_pair[..32].copy_from_slice(anonce);
93 b_pair[32..].copy_from_slice(snonce);
94 } else {
95 b_pair[..32].copy_from_slice(snonce);
96 b_pair[32..].copy_from_slice(anonce);
97 }
98
99 let mut msg = Vec::with_capacity(22 + 1 + 12 + 64);
100 msg.extend_from_slice(b"Pairwise key expansion");
101 msg.push(0u8);
102 msg.extend_from_slice(&a_pair);
103 msg.extend_from_slice(&b_pair);
104 msg
105}
106
107/// PTK derivation per 802.11-2016 §12.7.1.2 (PRF-512):
108/// HMAC-SHA1(pmk, "Pairwise key expansion" || 0x00 || A || B || i) for i in 1..,
109/// with A = min(ap,sta)||max(ap,sta), B = min(anonce,snonce)||max(anonce,snonce).
110pub fn ptk(
111 pmk: &[u8; 32],
112 ap: &MacAddr,
113 sta: &MacAddr,
114 anonce: &[u8; 32],
115 snonce: &[u8; 32],
116) -> [u8; 64] {
117 use hmac::{Hmac, Mac};
118
119 let mut msg = prf_stem(ap, sta, anonce, snonce);
120 let stem_len = msg.len();
121 msg.push(0u8); // PRF counter byte, rewritten per round below
122
123 let mut out = [0u8; 64];
124 for (i, chunk) in out.chunks_mut(20).enumerate() {
125 msg[stem_len] = (i + 1) as u8;
126 let mut mac = <Hmac<sha1::Sha1> as Mac>::new_from_slice(pmk)
127 .expect("HMAC-SHA1 accepts any key length");
128 mac.update(&msg);
129 let digest = mac.finalize().into_bytes();
130 chunk.copy_from_slice(&digest[..chunk.len()]);
131 }
132 out
133}
134
135/// EAPOL frame with its MIC field zeroed (bytes 81..97; short frames stay
136/// untouched). The zeroed frame is CONSTANT across all candidates of one
137/// capture — crack loops compute it once and call [`mic_on_zeroed`] per
138/// candidate instead of re-copying the frame every time.
139pub fn zeroed_eapol(eapol: &[u8]) -> Vec<u8> {
140 let mut data = eapol.to_vec();
141 const MIC_OFF: usize = 81;
142 const MIC_LEN: usize = 16;
143 if data.len() >= MIC_OFF + MIC_LEN {
144 data[MIC_OFF..MIC_OFF + MIC_LEN].fill(0);
145 }
146 data
147}
148
149/// MIC over an already-MIC-zeroed frame (see [`zeroed_eapol`]). No
150/// allocation — the hot path of the cracker's per-candidate check.
151pub fn mic_on_zeroed(ptk: &[u8; 64], zeroed: &[u8], key_ver: u8) -> [u8; 16] {
152 use hmac::{Hmac, Mac};
153
154 match key_ver {
155 3 => {
156 // key_mic_len = 16 → blk_key = IGTK||0x00*8. EAPOL frames are
157 // never zero-length (header is 4 bytes), but the multi-block
158 // path covers len ≡ 0 mod 16 correctly either way.
159 let mut key = [0u8; 16];
160 key[..8].copy_from_slice(&ptk[48..56]);
161 cmac_aes128(&key, zeroed)
162 }
163 1 => {
164 // WPA1-TKIP: HMAC-MD5 keyed with KCK (hashcat -m 22000 keyver 1).
165 let mut mac =
166 <Hmac<md5::Md5> as Mac>::new_from_slice(&ptk[..16]).expect("KCK is 16 bytes");
167 mac.update(zeroed);
168 mac.finalize().into_bytes().into()
169 }
170 _ => {
171 // WPA2 and any future/unseen version in the HMAC-SHA1 family.
172 let mut mac =
173 <Hmac<sha1::Sha1> as Mac>::new_from_slice(&ptk[..16]).expect("KCK is 16 bytes");
174 mac.update(zeroed);
175 let digest = mac.finalize().into_bytes();
176 let mut out = [0u8; 16];
177 out.copy_from_slice(&digest[..16]);
178 out
179 }
180 }
181}
182
183/// PMKID = HMAC-SHA1-128(pmk, "PMK Name" || ap || sta).
184pub fn pmkid_hash(pmk: &[u8; 32], ap: &MacAddr, sta: &MacAddr) -> [u8; 16] {
185 use hmac::{Hmac, Mac};
186 let mut mac = <Hmac<sha1::Sha1> as Mac>::new_from_slice(pmk).expect("PMK is 32 bytes");
187 mac.update(b"PMK Name");
188 mac.update(&ap.0);
189 mac.update(&sta.0);
190 let digest = mac.finalize().into_bytes();
191 let mut out = [0u8; 16];
192 out.copy_from_slice(&digest[..16]);
193 out
194}
195
196/// Constant-time equality of 16-byte buffers.
197pub fn ct_eq16(a: &[u8; 16], b: &[u8; 16]) -> bool {
198 let mut diff = 0u8;
199 for i in 0..16 {
200 diff |= a[i] ^ b[i];
201 }
202 diff == 0
203}
204
205fn unhex_field(s: &str, name: &str) -> Result<Vec<u8>> {
206 if s.is_empty() || !s.len().is_multiple_of(2) || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
207 bail!("{name}: not even-length hex");
208 }
209 (0..s.len())
210 .step_by(2)
211 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(anyhow::Error::from))
212 .collect::<Result<Vec<u8>, _>>()
213 .with_context(|| format!("{name}: bad hex"))
214}
215
216fn unhex_array<const N: usize>(s: &str, name: &str) -> Result<[u8; N]> {
217 let v = unhex_field(s, name)?;
218 <[u8; N]>::try_from(v.as_slice()).map_err(|_| anyhow!("{name}: expected {N} bytes"))
219}
220
221fn parse_mac(s: &str) -> Result<MacAddr> {
222 Ok(MacAddr(unhex_array::<6>(s, "mac")?))
223}
224
225/// Parse one hashcat -m 22000 line:
226/// 01*PMKID*MAC_AP*MAC_CLIENT*ESSID(hex)*** (PMKID)
227/// 02*MIC*MAC_AP*MAC_CLIENT*ESSID(hex)*ANONCE*EAPOL(hex)[*MESSAGE_PAIR] (EAPOL)
228///
229/// The trailing message_pair field (two hex digits) is optional: absent or
230/// "00" → complete M1+M2 capture, "02" → partial M2+M3 capture
231/// ([`HandshakeCapture::partial`]).
232pub fn parse_hc22000(line: &str) -> Result<CrackTarget> {
233 let line = line.trim();
234 let fields: Vec<&str> = line.split('*').collect();
235 if fields.len() < 5 {
236 bail!("hc22000: too few fields");
237 }
238 match fields[0] {
239 "01" => {
240 let pmkid = unhex_array::<16>(fields[1], "pmkid")?;
241 let ap = parse_mac(fields[2])?;
242 let client = parse_mac(fields[3])?;
243 let essid_bytes = unhex_field(fields[4], "essid")?;
244 let essid = String::from_utf8(essid_bytes).context("hc22000: essid not valid utf-8")?;
245 Ok(CrackTarget::Pmkid(PmkidCapture {
246 ap,
247 client,
248 essid,
249 pmkid,
250 }))
251 }
252 "02" => {
253 if fields.len() < 7 {
254 bail!("hc22000 type 02: need mic*ap*client*essid*anonce*eapol");
255 }
256 let mic_bytes = unhex_array::<16>(fields[1], "mic")?;
257 let ap = parse_mac(fields[2])?;
258 let client = parse_mac(fields[3])?;
259 let essid_bytes = unhex_field(fields[4], "essid")?;
260 let essid = String::from_utf8(essid_bytes).context("hc22000: essid not valid utf-8")?;
261 let anonce = unhex_array::<32>(fields[5], "anonce")?;
262 let eapol = unhex_field(fields[6], "eapol")?;
263 if eapol.len() < 99 {
264 bail!("hc22000: eapol frame too short to carry key data");
265 }
266 // Recover snonce (offset 17..49 of EAPOL-Key frame) and key MIC
267 // version (low bits of big-endian key_info at 5..7).
268 let snonce = <[u8; 32]>::try_from(&eapol[17..49]).expect("slice checked");
269 let key_info = u16::from_be_bytes([eapol[5], eapol[6]]);
270 let key_ver = (key_info & 0x7) as u8;
271 // Trailing hashcat message_pair field (index 7), two hex
272 // digits when present: "02" marks an M2+M3 (partial M1-less)
273 // capture → `partial = true`; "00" or a legacy line ending at
274 // the eapol field → complete capture. Unknown values parse as
275 // complete (their MIC math is identical either way).
276 let message_pair = fields.get(7).copied();
277 let is_partial = message_pair == Some("02");
278 let capture = if is_partial {
279 HandshakeCapture::new_partial(
280 ap, client, essid, anonce, snonce, mic_bytes, eapol, key_ver,
281 )
282 } else {
283 HandshakeCapture::new(ap, client, essid, anonce, snonce, mic_bytes, eapol, key_ver)
284 };
285 Ok(CrackTarget::Handshake(capture))
286 }
287 other => bail!("hc22000: unsupported message pair type {other}"),
288 }
289}
290
291// ---------------------------------------------------------------------------
292// AES-128 + CMAC (RFC 4493), hand-rolled. The S-box is derived arithmetically
293// in GF(2^8) via log/exp tables for generator 0x03 (multiplicative inverse,
294// then the AES affine transform) — no 256-entry constant to typo.
295// MixColumns uses xtime-based constant multiples.
296// ---------------------------------------------------------------------------
297
298struct AesTables {
299 sbox: [u8; 256],
300 mul2: [u8; 256],
301 mul3: [u8; 256],
302}
303
304fn xtime(x: u8) -> u8 {
305 let x2 = x << 1;
306 if x & 0x80 != 0 { x2 ^ 0x1b } else { x2 }
307}
308
309fn gf_mul(mut a: u8, mut b: u8) -> u8 {
310 let mut r = 0u8;
311 while b != 0 {
312 if b & 1 != 0 {
313 r ^= a;
314 }
315 a = xtime(a);
316 b >>= 1;
317 }
318 r
319}
320
321impl AesTables {
322 fn new() -> Self {
323 let mut exp = [0u8; 256];
324 let mut log = [0u8; 256];
325 let mut v = 1u8;
326 // 0x03 is a generator of GF(2^8) under AES reduction.
327 for (i, slot) in exp.iter_mut().enumerate().take(255) {
328 *slot = v;
329 log[v as usize] = i as u8;
330 v = gf_mul(v, 0x03);
331 }
332 exp[255] = 1; // generator cycle has length 255; wrap entry
333
334 let mut sbox = [0u8; 256];
335 for (x, slot) in sbox.iter_mut().enumerate() {
336 let inv = if x == 0 {
337 0u8
338 } else {
339 exp[(255usize - log[x] as usize) % 255]
340 };
341 *slot = inv
342 ^ inv.rotate_left(1)
343 ^ inv.rotate_left(2)
344 ^ inv.rotate_left(3)
345 ^ inv.rotate_left(4)
346 ^ 0x63;
347 }
348
349 let mut t = AesTables {
350 sbox,
351 mul2: [0u8; 256],
352 mul3: [0u8; 256],
353 };
354 for x in 0..256usize {
355 t.mul2[x] = gf_mul(x as u8, 2);
356 t.mul3[x] = gf_mul(x as u8, 3);
357 }
358 t
359 }
360}
361
362struct Aes128 {
363 rk: [u8; 176],
364 t: AesTables,
365}
366
367impl Aes128 {
368 fn new(key: &[u8; 16]) -> Self {
369 let t = AesTables::new();
370 let mut rk = [0u8; 176];
371 rk[..16].copy_from_slice(key);
372 let mut i = 4usize; // words generated
373 while i < 44 {
374 let mut w = [rk[4 * i - 4], rk[4 * i - 3], rk[4 * i - 2], rk[4 * i - 1]];
375 if i.is_multiple_of(4) {
376 // RotWord + SubWord + Rcon
377 w.rotate_left(1);
378 for b in w.iter_mut() {
379 *b = t.sbox[*b as usize];
380 }
381 w[0] ^= rcon_for_round(i / 4);
382 }
383 for j in 0..4 {
384 rk[4 * i + j] = rk[4 * (i - 4) + j] ^ w[j];
385 }
386 i += 1;
387 }
388 Aes128 { rk, t }
389 }
390
391 fn encrypt_block(&self, input: &[u8; 16]) -> [u8; 16] {
392 let mut s = *input;
393 add_round_key(&mut s, &self.rk[0..16]);
394 for r in 1..10 {
395 sub_bytes(&mut s, &self.t.sbox);
396 shift_rows(&mut s);
397 mix_columns(&mut s, &self.t);
398 add_round_key(&mut s, &self.rk[16 * r..16 * r + 16]);
399 }
400 sub_bytes(&mut s, &self.t.sbox);
401 shift_rows(&mut s);
402 add_round_key(&mut s, &self.rk[160..176]);
403 s
404 }
405}
406
407fn rcon_for_round(round: usize) -> u8 {
408 // Rcon[1..=10] = 01,02,04,08,10,20,40,80,1b,36
409 const RCON: [u8; 11] = [
410 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
411 ];
412 RCON[round]
413}
414
415fn add_round_key(s: &mut [u8; 16], rk: &[u8]) {
416 for i in 0..16 {
417 s[i] ^= rk[i];
418 }
419}
420
421fn sub_bytes(s: &mut [u8; 16], sbox: &[u8; 256]) {
422 for b in s.iter_mut() {
423 *b = sbox[*b as usize];
424 }
425}
426
427fn shift_rows(s: &mut [u8; 16]) {
428 // state is column-major: s[c*4 + r]
429 let t = *s;
430 for r in 1..4 {
431 for c in 0..4 {
432 s[c * 4 + r] = t[((c + r) % 4) * 4 + r];
433 }
434 }
435}
436
437fn mix_columns(s: &mut [u8; 16], t: &AesTables) {
438 for c in 0..4 {
439 let i = c * 4;
440 let (a0, a1, a2, a3) = (s[i], s[i + 1], s[i + 2], s[i + 3]);
441 s[i] = t.mul2[a0 as usize] ^ t.mul3[a1 as usize] ^ a2 ^ a3;
442 s[i + 1] = a0 ^ t.mul2[a1 as usize] ^ t.mul3[a2 as usize] ^ a3;
443 s[i + 2] = a0 ^ a1 ^ t.mul2[a2 as usize] ^ t.mul3[a3 as usize];
444 s[i + 3] = t.mul3[a0 as usize] ^ a1 ^ a2 ^ t.mul2[a3 as usize];
445 }
446}
447
448/// AES-128-CMAC per RFC 4493.
449pub fn cmac_aes128(key: &[u8; 16], msg: &[u8]) -> [u8; 16] {
450 let aes = Aes128::new(key);
451 let l = aes.encrypt_block(&[0u8; 16]);
452 let k1 = dbl(l);
453 let k2 = dbl(k1);
454
455 let n = msg.len().div_ceil(16).max(1);
456 let complete = !msg.is_empty() && msg.len().is_multiple_of(16);
457
458 let mut m_last = [0u8; 16];
459 if complete {
460 m_last.copy_from_slice(&msg[16 * (n - 1)..]);
461 for i in 0..16 {
462 m_last[i] ^= k1[i];
463 }
464 } else {
465 let rem = if msg.is_empty() { 0 } else { msg.len() % 16 };
466 let start = if msg.is_empty() { 0 } else { msg.len() - rem };
467 m_last[..rem].copy_from_slice(&msg[start..]);
468 m_last[rem] = 0x80;
469 for i in 0..16 {
470 m_last[i] ^= k2[i];
471 }
472 }
473
474 let mut x = [0u8; 16];
475 for i in 0..n - 1 {
476 let block = &msg[16 * i..16 * i + 16];
477 for j in 0..16 {
478 x[j] ^= block[j];
479 }
480 x = aes.encrypt_block(&x);
481 }
482 for j in 0..16 {
483 x[j] ^= m_last[j];
484 }
485 aes.encrypt_block(&x)
486}
487
488fn dbl(b: [u8; 16]) -> [u8; 16] {
489 let mut out = [0u8; 16];
490 let msb = b[0] & 0x80 != 0;
491 let mut carry = 0u8;
492 for i in (0..16).rev() {
493 let new_carry = (b[i] >> 7) & 1;
494 out[i] = (b[i] << 1) | carry;
495 carry = new_carry;
496 }
497 if msb {
498 out[15] ^= 0x87;
499 }
500 out
501}
502
503// ---------------------------------------------------------------------------
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508
509 #[test]
510 fn pmk_rfc6070_c4096() {
511 // RFC 6070 PBKDF2-HMAC-SHA1: P="password" S="salt" c=4096 dkLen=20.
512 let mut out20 = [0u8; 20];
513 pbkdf2_hmac_sha1(b"password", b"salt", 4096, &mut out20);
514 assert_eq!(hex(&out20), "4b007901b765489abead49d926f721d065a429c1");
515
516 // RFC 6070 fast checks: c=1 and c=2 vectors anchor the block-1 chain.
517 let mut o1 = [0u8; 20];
518 pbkdf2_hmac_sha1(b"password", b"salt", 1, &mut o1);
519 assert_eq!(hex(&o1), "0c60c80f961f0e71f3a9b524af6012062fe037a6");
520 pbkdf2_hmac_sha1(b"password", b"salt", 2, &mut o1);
521 assert_eq!(hex(&o1), "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");
522
523 // Known WPA2 PMK vector (used by aircrack/hashcat test suites):
524 // ssid "IEEE", pass "password".
525 let k = pmk(b"password", b"IEEE");
526 assert_eq!(
527 hex(&k),
528 "f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e"
529 );
530 }
531
532 #[test]
533 fn gf_sanity() {
534 // AES xtime known sample: 0x57 * 0x13 = 0xfe (FIPS-197 example).
535 assert_eq!(gf_mul(0x57, 0x13), 0xfe);
536 let t = AesTables::new();
537 // S-box spot values (FIPS-197 Table 4/5): S(0x00)=0x63, S(0x53)=0xed.
538 assert_eq!(t.sbox[0x00], 0x63);
539 assert_eq!(t.sbox[0x53], 0xed);
540 assert_eq!(t.sbox[0x01], 0x7c);
541 assert_eq!(t.sbox[0xff], 0x16);
542 // The S-box must be a bijection.
543 let mut seen = [false; 256];
544 for &v in t.sbox.iter() {
545 assert!(!seen[v as usize], "s-box collides");
546 seen[v as usize] = true;
547 }
548 // MixColumns constants: 2 and 3 tables agree with xtime.
549 // 0x80*2 = 0x1b; 0xdb*2 = (0xdb<<1)^0x1b = 0xb6^0x1b = 0xad;
550 // 0xdb*3 = 0xdb ^ 0xad = 0x76.
551 assert_eq!(t.mul2[0x80], 0x1b);
552 assert_eq!(t.mul2[0xdb], 0xad);
553 assert_eq!(t.mul3[0xdb], 0x76);
554 }
555
556 #[test]
557 fn aes128_fips197() {
558 // FIPS-197 Appendix B / C.1 test vector.
559 let key = [
560 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
561 0x0e, 0x0f,
562 ];
563 let pt = [
564 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
565 0xee, 0xff,
566 ];
567 let aes = Aes128::new(&key);
568 let ct = aes.encrypt_block(&pt);
569 assert_eq!(hex(&ct), "69c4e0d86a7b0430d8cdb78070b4c55a");
570 }
571
572 #[test]
573 fn cmac_rfc4493() {
574 let k = unhex_field("2b7e151628aed2a6abf7158809cf4f3c", "k").unwrap();
575 let key: [u8; 16] = k.try_into().unwrap();
576
577 let m0: [u8; 0] = [];
578 assert_eq!(
579 hex(&cmac_aes128(&key, &m0)),
580 "bb1d6929e95937287fa37d129b756746"
581 );
582
583 let m16 = unhex_field("6bc1bee22e409f96e93d7e117393172a", "m").unwrap();
584 assert_eq!(
585 hex(&cmac_aes128(&key, &m16)),
586 "070a16b46b4d4144f79bdd9dd04a287c"
587 );
588
589 let m40 = unhex_field(
590 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411",
591 "m",
592 )
593 .unwrap();
594 assert_eq!(
595 hex(&cmac_aes128(&key, &m40)),
596 "dfa66747de9ae63030ca32611497c827"
597 );
598
599 let m64 = unhex_field(
600 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
601 "m",
602 )
603 .unwrap();
604 assert_eq!(
605 hex(&cmac_aes128(&key, &m64)),
606 "51f0bebf7e3b9d92fc49741779363cfe"
607 );
608 }
609
610 /// Build a minimal EAPOL-Key (WPA2 descriptor) message-2 frame with the
611 /// MIC field zeroed, exactly 99 bytes.
612 fn build_eapol_m2(key_ver: u8, snonce: &[u8; 32], replay: u64) -> Vec<u8> {
613 let mut f = Vec::with_capacity(99);
614 f.push(0x02); // EAPOL version 2
615 f.push(0x03); // type: EAPOL-Key
616 f.extend_from_slice(&95u16.to_be_bytes()); // body length
617 f.push(0x02); // descriptor type: RSN
618 let info: u16 = 0x0100 | 0x0080 | (key_ver as u16 & 0x7); // pairwise|mic|ver
619 f.extend_from_slice(&info.to_be_bytes());
620 f.extend_from_slice(&16u16.to_be_bytes()); // key length
621 f.extend_from_slice(&replay.to_be_bytes());
622 f.extend_from_slice(snonce);
623 f.extend_from_slice(&[0u8; 16]); // key IV
624 f.extend_from_slice(&[0u8; 8]); // key RSC
625 f.extend_from_slice(&[0u8; 8]); // key ID
626 f.extend_from_slice(&[0u8; 16]); // MIC (zeroed)
627 f.extend_from_slice(&0u16.to_be_bytes()); // key data len
628 assert_eq!(f.len(), 99);
629 f
630 }
631
632 fn synthetic_target(ssid: &str, pass: &[u8], key_ver: u8) -> (CrackTarget, [u8; 32]) {
633 let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
634 let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
635 let anonce: [u8; 32] = [0x5a; 32];
636 let snonce: [u8; 32] = [0xc3; 32];
637 let key = pmk(pass, ssid.as_bytes());
638 let dk = ptk(&key, &ap, &sta, &anonce, &snonce);
639 let frame = build_eapol_m2(key_ver, &snonce, 1);
640 let m = mic_on_zeroed(&dk, &zeroed_eapol(&frame), key_ver);
641 let cap =
642 HandshakeCapture::new(ap, sta, ssid.to_string(), anonce, snonce, m, frame, key_ver);
643 (CrackTarget::Handshake(cap), key)
644 }
645
646 /// End-to-end check over the surviving lowest-level APIs (the chain the
647 /// CPU cracker runs per candidate): pmk → ptk/pmkid → MIC → constant-time
648 /// compare.
649 fn verifies(target: &CrackTarget, pass: &[u8]) -> bool {
650 let key = pmk(pass, target.essid().as_bytes());
651 match target {
652 CrackTarget::Handshake(h) => {
653 let dk = ptk(&key, &h.ap, &h.client, &h.anonce, &h.snonce);
654 let got = mic_on_zeroed(&dk, &zeroed_eapol(&h.eapol_m2), h.key_ver);
655 ct_eq16(&got, h.mic())
656 }
657 CrackTarget::Pmkid(p) => {
658 let got = pmkid_hash(&key, &p.ap, &p.client);
659 ct_eq16(&got, &p.pmkid)
660 }
661 }
662 }
663
664 #[test]
665 fn synthetic_handshake_sha1_mic() {
666 let (target, _) = synthetic_target("testnet", b"sup3r-secret", 2);
667 assert!(verifies(&target, b"sup3r-secret"));
668 assert!(!verifies(&target, b"sup3r-wrong"));
669 // Tampered MIC must not verify.
670 if let CrackTarget::Handshake(mut h) = target.clone() {
671 h.eapol_m2[10] ^= 1; // flip a nonce bit → MIC mismatch
672 assert!(!verifies(&CrackTarget::Handshake(h), b"sup3r-secret"));
673 }
674 }
675
676 #[test]
677 fn synthetic_handshake_cmac_mic() {
678 let (target, _) = synthetic_target("testnet", b"sup3r-secret", 3);
679 assert!(verifies(&target, b"sup3r-secret"));
680 assert!(!verifies(&target, b"sup3r-wrong"));
681 }
682
683 #[test]
684 fn hmac_md5_rfc2202() {
685 use hmac::Mac as _;
686 // RFC 2202 test case 1: key = 0x0b×16, data = "Hi There".
687 let mut mac = <hmac::Hmac<md5::Md5> as hmac::Mac>::new_from_slice(&[0x0b; 16])
688 .expect("HMAC-MD5 takes any key length");
689 mac.update(b"Hi There");
690 assert_eq!(
691 hex(&mac.finalize().into_bytes()),
692 "9294727a3638bb1c13f48ef8158bfc9d"
693 );
694 }
695
696 #[test]
697 fn synthetic_handshake_md5_mic() {
698 // key_ver 1 (WPA1-TKIP): MIC = HMAC-MD5(KCK, zeroed frame), 16 bytes.
699 let (target, _) = synthetic_target("testnet", b"sup3r-secret", 1);
700 assert!(verifies(&target, b"sup3r-secret"));
701 assert!(!verifies(&target, b"sup3r-wrong"));
702 }
703
704 #[test]
705 fn key_ver_1_cracks_on_cpu() {
706 // Regression: a key_ver-1 target must actually crack end-to-end on
707 // the pure-CPU path (previously the SHA1 epilogue made every
708 // candidate miss — keyspace "exhausted" without a hit).
709 let (target, _) = synthetic_target("testnet", b"md5secret!", 1);
710 let mut words = vec![
711 b"wrong-pass-1".to_vec(),
712 b"wrong-pass-2".to_vec(),
713 b"md5secret!".to_vec(),
714 ]
715 .into_iter();
716 let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
717 let found = crate::gpu::cpu_crack(&target, &mut words, &mut |_, _| {}, &stop, None);
718 assert_eq!(found.as_deref(), Some("md5secret!"));
719
720 // A wordlist without the right passphrase exhausts cleanly.
721 let mut wrong = vec![b"wrong-pass-1".to_vec(), b"wrong-pass-2".to_vec()].into_iter();
722 let found = crate::gpu::cpu_crack(&target, &mut wrong, &mut |_, _| {}, &stop, None);
723 assert_eq!(found, None);
724 }
725
726 #[test]
727 fn pmkid_roundtrip() {
728 let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
729 let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
730 let key = pmk(b"sup3r-secret", b"testnet");
731 let id = pmkid_hash(&key, &ap, &sta);
732 let cap = PmkidCapture {
733 ap,
734 client: sta,
735 essid: "testnet".to_string(),
736 pmkid: id,
737 };
738 let target = CrackTarget::Pmkid(cap);
739 assert!(verifies(&target, b"sup3r-secret"));
740 assert!(!verifies(&target, b"another-pass"));
741 }
742
743 /// Export a handshake exactly like handshake::handshake_hc22000 does:
744 /// 02*MIC*MAC_AP*MAC_CLIENT*ESSID(hex)*ANONCE*EAPOL(hex)*00
745 fn export_handshake(h: &HandshakeCapture) -> String {
746 let mut s = String::new();
747 s.push_str("02*");
748 s.push_str(&hex(h.mic()));
749 s.push('*');
750 for b in h.ap.0 {
751 s.push_str(&format!("{b:02x}"));
752 }
753 s.push('*');
754 for b in h.client.0 {
755 s.push_str(&format!("{b:02x}"));
756 }
757 s.push('*');
758 for b in h.essid.as_bytes() {
759 s.push_str(&format!("{b:02x}"));
760 }
761 s.push('*');
762 for b in h.anonce {
763 s.push_str(&format!("{b:02x}"));
764 }
765 s.push('*');
766 for b in &h.eapol_m2 {
767 s.push_str(&format!("{b:02x}"));
768 }
769 s.push_str("*00");
770 s
771 }
772
773 /// Export a PMKID capture: 01*PMKID*MAC_AP*MAC_CLIENT*ESSID(hex)***
774 fn export_pmkid(p: &PmkidCapture) -> String {
775 let mut s = String::from("01*");
776 s.push_str(&hex(&p.pmkid));
777 s.push('*');
778 for b in p.ap.0 {
779 s.push_str(&format!("{b:02x}"));
780 }
781 s.push('*');
782 for b in p.client.0 {
783 s.push_str(&format!("{b:02x}"));
784 }
785 s.push('*');
786 for b in p.essid.as_bytes() {
787 s.push_str(&format!("{b:02x}"));
788 }
789 s.push_str("***");
790 s
791 }
792
793 #[test]
794 fn hc22000_handshake_roundtrip() {
795 let (target, _key) = synthetic_target("testnet", b"sup3r-secret", 2);
796 let h = match &target {
797 CrackTarget::Handshake(h) => h.clone(),
798 _ => unreachable!(),
799 };
800 let line = export_handshake(&h);
801 let parsed = parse_hc22000(&line).unwrap();
802 match &parsed {
803 CrackTarget::Handshake(p) => {
804 assert_eq!(p.ap, h.ap);
805 assert_eq!(p.client, h.client);
806 assert_eq!(p.essid, h.essid);
807 assert_eq!(&p.anonce, &h.anonce);
808 // GPU verification path must take snonce from parsed eapol.
809 assert_eq!(&p.snonce, &h.snonce);
810 assert_eq!(p.mic(), h.mic());
811 assert_eq!(p.eapol_m2, h.eapol_m2);
812 assert_eq!(p.key_ver, 2);
813 }
814 _ => panic!("wrong target type"),
815 }
816 assert!(verifies(&parsed, b"sup3r-secret"));
817 assert!(!verifies(&parsed, b"nope-nope"));
818 }
819
820 #[test]
821 fn hc22000_partial_message_pair_roundtrip() {
822 // "02" trailing field → partial capture (M2+M3, MIC math identical).
823 let (target, _key) = synthetic_target("testnet", b"sup3r-secret", 2);
824 let h = match &target {
825 CrackTarget::Handshake(h) => h.clone(),
826 _ => unreachable!(),
827 };
828 let line = format!("{}*02", export_handshake(&h).trim_end_matches("*00"));
829 let parsed = parse_hc22000(&line).unwrap();
830 match &parsed {
831 CrackTarget::Handshake(p) => {
832 assert!(p.partial, "message_pair 02 must set partial=true");
833 assert_eq!(p.mic(), h.mic());
834 assert_eq!(p.anonce, h.anonce);
835 assert_eq!(p.snonce, h.snonce);
836 }
837 _ => panic!("wrong target type"),
838 }
839 assert!(verifies(&parsed, b"sup3r-secret"));
840 assert!(!verifies(&parsed, b"nope-nope"));
841
842 // Explicit "00" → complete capture, exactly like before.
843 let line = export_handshake(&h); // ends in *00
844 let parsed = parse_hc22000(&line).unwrap();
845 match &parsed {
846 CrackTarget::Handshake(p) => assert!(!p.partial),
847 _ => panic!("wrong target type"),
848 }
849
850 // Legacy: no trailing message_pair field at all → still parses as a
851 // complete capture.
852 let line = export_handshake(&h).trim_end_matches("*00").to_string();
853 let parsed = parse_hc22000(&line).unwrap();
854 match &parsed {
855 CrackTarget::Handshake(p) => {
856 assert!(!p.partial);
857 assert_eq!(p.mic(), h.mic());
858 assert_eq!(p.eapol_m2, h.eapol_m2);
859 }
860 _ => panic!("wrong target type"),
861 }
862 assert!(verifies(&parsed, b"sup3r-secret"));
863 }
864
865 #[test]
866 fn hc22000_pmkid_roundtrip() {
867 let ap = "aa:bb:cc:dd:ee:ff".parse::<MacAddr>().unwrap();
868 let sta = "11:22:33:44:55:66".parse::<MacAddr>().unwrap();
869 let key = pmk(b"hunter2!!", b"testnet");
870 let cap = PmkidCapture {
871 ap,
872 client: sta,
873 essid: "testnet".to_string(),
874 pmkid: pmkid_hash(&key, &ap, &sta),
875 };
876 let line = export_pmkid(&cap);
877 assert!(line.ends_with("***"));
878 let parsed = parse_hc22000(&line).unwrap();
879 assert!(verifies(&parsed, b"hunter2!!"));
880 assert!(!verifies(&parsed, b"hunter3!!"));
881 }
882
883 #[test]
884 fn hc22000_rejections() {
885 assert!(parse_hc22000("").is_err());
886 assert!(parse_hc22000("03*aa*bb").is_err());
887 assert!(parse_hc22000("01*zz*aabbccddeeff*112233445566*70617261***").is_err());
888 // odd-length hex
889 assert!(parse_hc22000("01*abc*aabbccddeeff*112233445566*70***").is_err());
890 // type 02 missing eapol field
891 assert!(
892 parse_hc22000(
893 "02*070a16b46b4d4144f79bdd9dd04a287c*aabbccddeeff*112233445566*70617261*abcd"
894 )
895 .is_err()
896 );
897 }
898
899 fn hex(b: &[u8]) -> String {
900 b.iter().map(|x| format!("{x:02x}")).collect()
901 }
902}