forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

handshake.rs848 lines, 28.6 KiBHistoryRawDownload
1//! 4-way handshake tracker + hashcat-22000 export.
2//!
3//! A capture is crackable once we hold M1 (ANonce) and a matching M2
4//! (SNonce + MIC) with a consistent replay counter. M4 only informs
5//! progress; an M2+M3 pair that never completed (ANonce from M3, SNonce
6//! from M2) is still crackable material and is drained as a *partial*
7//! capture at session teardown via [`Tracker::take_partials`].
8
9use std::collections::HashMap;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::time::{Duration, Instant};
13
14use anyhow::{Context, Result};
15use crossbeam_channel::Sender;
16
17use crate::common::{Event, HandshakeCapture, MacAddr, PmkidCapture};
18use crate::dot11::{EapolKey, eapol_4way_msg, parse_eapol, parse_eapol_key};
19use crate::radiotap;
20use crate::rawsock::RawSocket;
21
22/// Per-(ap, sta) state older than this is dropped (replays are long dead).
23const STATE_TTL: Duration = Duration::from_secs(120);
24
25/// Partial 4-way collection for one (ap, sta) pair.
26#[derive(Default)]
27struct PairState {
28 m1: Option<Msg>,
29 m2: Option<Msg>,
30 /// Newest M2 that never paired an M1 (partial-capture material).
31 unpaired_m2: Option<Msg>,
32 /// M3 seen at least once (progress bitmask).
33 m3_seen: bool,
34 /// Newest M3 with nonzero MIC+nonce (partial-capture material).
35 m3_msg: Option<Msg>,
36 m4: bool,
37 /// Latest non-empty essid heard for this pair (partials need the salt).
38 essid: Option<String>,
39 /// Last time any message for this pair arrived.
40 touched: Option<Instant>,
41 /// Set once HandshakeComplete has been emitted (don't re-fire).
42 done: bool,
43}
44
45#[derive(Clone)]
46struct Msg {
47 replay_counter: u64,
48 nonce: [u8; 32],
49 mic: [u8; 16],
50 key_ver: u8,
51 /// Full EAPOL frame starting at the version byte (M2/M3 need it).
52 raw: Vec<u8>,
53}
54
55impl PairState {
56 fn mask(&self) -> u8 {
57 let mut m = 0u8;
58 if self.m1.is_some() {
59 m |= 1;
60 }
61 if self.m2.is_some() {
62 m |= 1 << 1;
63 }
64 if self.m3_seen {
65 m |= 1 << 2;
66 }
67 if self.m4 {
68 m |= 1 << 3;
69 }
70 m
71 }
72}
73
74pub struct Tracker {
75 pairs: HashMap<(MacAddr, MacAddr), PairState>,
76}
77
78impl Default for Tracker {
79 fn default() -> Self {
80 Self::new()
81 }
82}
83
84impl Tracker {
85 pub fn new() -> Self {
86 Self {
87 pairs: HashMap::new(),
88 }
89 }
90
91 /// Feed a parsed EAPOL-Key frame observed between `ap` and `sta`, with
92 /// the AP's current essid (empty/unknown essid → no capture possible;
93 /// progress is still tracked lightly for consistent state cleanup).
94 ///
95 /// Emits [`Event::HandshakeProgress`] on each newly collected message and
96 /// returns `Some(capture)` exactly once when an M1+M2 pair completes.
97 pub fn ingest(
98 &mut self,
99 ap: MacAddr,
100 sta: MacAddr,
101 essid: &str,
102 key: &EapolKey,
103 tx: &Sender<Event>,
104 ) -> Option<HandshakeCapture> {
105 // Drop long-dead pairs on traffic (keeps the map bounded).
106 self.reap();
107
108 let msg_no = eapol_4way_msg(key);
109 if msg_no == 0 {
110 return None;
111 }
112
113 let st = self.pairs.entry((ap, sta)).or_default();
114 st.touched = Some(Instant::now());
115 // Partials are built at teardown with no essid argument around —
116 // remember the latest non-empty one per pair.
117 if !essid.is_empty() {
118 st.essid = Some(essid.to_string());
119 }
120 let mut emit_progress = false;
121
122 match msg_no {
123 1 => {
124 // M1: ANonce, no MIC. Keep the newest M1 (retransmissions
125 // bump the replay counter).
126 st.m1 = Some(Msg {
127 replay_counter: key.replay_counter,
128 nonce: key.nonce,
129 mic: key.mic,
130 key_ver: key.key_ver,
131 raw: key.raw.to_vec(),
132 });
133 emit_progress = true;
134 }
135 2 => {
136 // M2: SNonce + MIC must be nonzero to be crackable.
137 if key.mic.iter().any(|&b| b != 0) && key.nonce.iter().any(|&b| b != 0) {
138 let msg = Msg {
139 replay_counter: key.replay_counter,
140 nonce: key.nonce,
141 mic: key.mic,
142 key_ver: key.key_ver,
143 raw: key.raw.to_vec(),
144 };
145 st.m2 = Some(msg.clone());
146 // M2s arriving after completion are not partials.
147 if !st.done {
148 st.unpaired_m2 = Some(msg);
149 }
150 emit_progress = true;
151 }
152 }
153 3 => {
154 if !st.m3_seen {
155 st.m3_seen = true;
156 emit_progress = true;
157 }
158 // Partial material: the newest usable M3 (ANonce + MIC).
159 if key.mic.iter().any(|&b| b != 0) && key.nonce.iter().any(|&b| b != 0) {
160 st.m3_msg = Some(Msg {
161 replay_counter: key.replay_counter,
162 nonce: key.nonce,
163 mic: key.mic,
164 key_ver: key.key_ver,
165 raw: key.raw.to_vec(),
166 });
167 }
168 }
169 4 if !st.m4 => {
170 st.m4 = true;
171 emit_progress = true;
172 }
173 _ => {}
174 }
175
176 if emit_progress {
177 let _ = tx.send(Event::HandshakeProgress {
178 ap,
179 client: sta,
180 have: st.mask(),
181 });
182 }
183
184 if st.done {
185 return None;
186 }
187 let (Some(m1), Some(m2)) = (&st.m1, &st.m2) else {
188 return None;
189 };
190 // Replay-counter consistency: rc(M2) == rc(M1); an M1 retransmission
191 // seen after M2 may be exactly one behind (rc(M1) == rc(M2) - 1),
192 // both refer to the same exchange.
193 let rc_consistent =
194 m1.replay_counter == m2.replay_counter || m1.replay_counter + 1 == m2.replay_counter;
195 if !rc_consistent {
196 return None;
197 }
198 if essid.is_empty() {
199 return None; // cannot crack without the salt
200 }
201
202 st.done = true;
203 Some(HandshakeCapture::new(
204 ap,
205 sta,
206 essid.to_string(),
207 m1.nonce,
208 m2.nonce,
209 m2.mic,
210 m2.raw.clone(),
211 m2.key_ver,
212 ))
213 }
214
215 /// Session-teardown partial capture: every (ap, client) pair that saw
216 /// BOTH an M2 which never completed an M1+M2 pair AND an M3 yields a
217 /// [`HandshakeCapture::new_partial`] — ANonce from the newest M3, SNonce
218 /// from the newest unpaired M2, MIC + EAPOL frame from the M3, key_ver
219 /// from the M3 key_info. The PTK/MIC math is identical, so these are
220 /// crackable like complete captures.
221 ///
222 /// Pairs that already produced a complete capture are excluded, as are
223 /// pairs whose essid was never known (no salt → uncrackable). Drained
224 /// material is dropped: a second call returns nothing until new
225 /// messages arrive.
226 pub fn take_partials(&mut self) -> Vec<HandshakeCapture> {
227 let mut out = Vec::new();
228 for ((ap, sta), st) in self.pairs.iter_mut() {
229 if st.done {
230 continue;
231 }
232 let (unpaired_m2, m3) = (st.unpaired_m2.take(), st.m3_msg.take());
233 let (Some(m2), Some(m3), Some(essid)) = (unpaired_m2, m3, st.essid.clone()) else {
234 continue;
235 };
236 out.push(HandshakeCapture::new_partial(
237 *ap, *sta, essid, m3.nonce, m2.nonce, m3.mic, m3.raw, m3.key_ver,
238 ));
239 }
240 out
241 }
242
243 /// Drop pairs untouched for longer than the replay window.
244 fn reap(&mut self) {
245 let now = Instant::now();
246 self.pairs.retain(|_, st| match st.touched {
247 Some(t) => now.duration_since(t) <= STATE_TTL,
248 None => false,
249 });
250 }
251}
252
253fn hex_push(out: &mut String, bytes: &[u8]) {
254 for b in bytes {
255 out.push_str(&format!("{b:02x}"));
256 }
257}
258
259/// hashcat -m 22000 WPA-PBKDF2 line for a handshake (message-pair type 02):
260/// `WPA*02*mic*mac_ap*mac_client*essid*anonce*eapol*<pair>`
261/// (EAPOL carries the MIC not-zeroed; the trailing message-pair field is
262/// `00` for a replay-verified M1+M2 capture, `02` for a partial M2+M3 one).
263/// The `WPA*` prefix is emitted for modern hashcat.
264pub fn handshake_hc22000(h: &HandshakeCapture) -> String {
265 let mut s = String::from("WPA*02*");
266 hex_push(&mut s, h.mic());
267 s.push('*');
268 hex_push(&mut s, &h.ap.0);
269 s.push('*');
270 hex_push(&mut s, &h.client.0);
271 s.push('*');
272 hex_push(&mut s, h.essid.as_bytes());
273 s.push('*');
274 hex_push(&mut s, &h.anonce);
275 s.push('*');
276 hex_push(&mut s, &h.eapol_m2);
277 s.push_str(if h.partial { "*02" } else { "*00" });
278 s
279}
280
281/// hashcat -m 22000 PMKID line (type 01):
282/// `WPA*01*pmkid*mac_ap*mac_client*essid***`
283pub fn pmkid_hc22000(p: &PmkidCapture) -> String {
284 let mut s = String::from("WPA*01*");
285 hex_push(&mut s, &p.pmkid);
286 s.push('*');
287 hex_push(&mut s, &p.ap.0);
288 s.push('*');
289 hex_push(&mut s, &p.client.0);
290 s.push('*');
291 hex_push(&mut s, p.essid.as_bytes());
292 s.push_str("***");
293 s
294}
295
296/// Frame poll cadence: how long one recv call may block before the stop
297/// flag is re-checked (250 ms per the backend contract).
298pub const CAPTURE_POLL_MS: u32 = 250;
299
300/// Active 4-way capture loop against `ap`: receives frames from `sock`
301/// (already bound to a monitor interface on the right channel), tracks
302/// every EAPOL exchange involving `ap`, and emits
303/// [`Event::HandshakeProgress`]/[`Event::HandshakeComplete`] through the
304/// internal [`Tracker`]. M1+M2 stays the primary path (HandshakeComplete
305/// fires from inside the loop exactly as before); partial M2+M3 material is
306/// EXTRA, surfaced only at teardown.
307///
308/// Returns `Ok((complete, partials))` once a crackable capture was sent,
309/// the `stop` flag flipped, or nothing but timeouts arrived for a long
310/// stretch: `complete` says a full M1+M2 capture landed, `partials` is the
311/// tracker's [`Tracker::take_partials`] drain — the caller turns each into
312/// [`Event::HandshakePartial`].
313pub fn capture_loop(
314 sock: &RawSocket,
315 targets: &[MacAddr],
316 essid: &str,
317 tx: &Sender<Event>,
318 stop: &Arc<AtomicBool>,
319) -> Result<(bool, Vec<HandshakeCapture>)> {
320 sock.set_timeout(CAPTURE_POLL_MS)?;
321 let _ = tx.send(Event::Log(format!(
322 "handshake: listening for 4-way on {} ({essid})",
323 if targets.len() == 1 {
324 targets[0].to_string()
325 } else {
326 format!("{} bssids", targets.len())
327 }
328 )));
329
330 let mut tracker = Tracker::new();
331 let mut buf = vec![0u8; crate::rawsock::RECV_BUFSZ];
332 let mut truncated_dropped: u64 = 0;
333 // ~4 minutes of dead air without a single EAPOL message → give up.
334 let mut idle_deadline = Instant::now() + Duration::from_secs(240);
335
336 // Diagnostics: a silent capture must be distinguishable from deaf radio
337 // (0 frames) vs wrong AP (EAPOL on other BSSIDs) vs client simply not
338 // reassociating (EAPOL on target but no 4-way yet) → periodic stats.
339 let mut frames: u64 = 0;
340 let mut eapol_other: u64 = 0;
341 let mut last_stats = Instant::now();
342 const STATS_EVERY: Duration = Duration::from_secs(30);
343
344 loop {
345 if stop.load(Ordering::Relaxed) {
346 return Ok((false, tracker.take_partials()));
347 }
348 if Instant::now() >= idle_deadline {
349 return Ok((false, tracker.take_partials()));
350 }
351 if last_stats.elapsed() >= STATS_EVERY {
352 last_stats = Instant::now();
353 let _ = tx.send(Event::Log(format!(
354 "handshake: still listening — {frames} frames, {eapol_other} EAPOL on other BSSIDs, {truncated_dropped} truncated dropped"
355 )));
356 }
357 let m = match sock.recv_msg(&mut buf) {
358 Ok(m) => m,
359 Err(e)
360 if [libc::EAGAIN, libc::EWOULDBLOCK, libc::ETIMEDOUT]
361 .contains(&e.raw_os_error().unwrap_or(0)) =>
362 {
363 continue;
364 }
365 Err(e) => return Err(e).context("handshake capture recv"),
366 };
367 if m.truncated() {
368 // Over-long frame (A-MSDU aggregate): dropped whole — a partial
369 // frame would parse as garbage and could be spooled as if real.
370 truncated_dropped += 1;
371 if truncated_dropped == 1 {
372 let _ = tx.send(Event::Log(format!(
373 "handshake: frame >{} B dropped (truncated); counting",
374 crate::rawsock::RECV_BUFSZ
375 )));
376 }
377 continue;
378 }
379 let n = m.len;
380 let Some((_meta, frame)) = radiotap::strip(&buf[..n]) else {
381 continue;
382 };
383 frames += 1;
384 if frames == 1 {
385 let _ = tx.send(Event::Log(
386 "handshake: receiving frames (radio OK)".to_string(),
387 ));
388 }
389 let Some((bssid, _ap_is_sender, eapol)) = parse_eapol(frame) else {
390 continue;
391 };
392 if !targets.contains(&bssid) {
393 eapol_other += 1;
394 continue;
395 }
396 // Relevant traffic renews the idle window.
397 idle_deadline = Instant::now() + Duration::from_secs(240);
398 let sta = crate::dot11::data_endpoints(frame)
399 .map(|(a, b)| if a == bssid { b } else { a })
400 .unwrap_or(MacAddr::ZERO);
401 if sta.is_zero() || sta.is_multicast() {
402 continue;
403 }
404 let Some(key) = parse_eapol_key(eapol) else {
405 continue;
406 };
407 // The FRAME's BSSID is the truth (dual-band: may differ from the
408 // BSSID the user clicked).
409 if let Some(cap) = tracker.ingest(bssid, sta, essid, &key, tx) {
410 let _ = tx.send(Event::HandshakeComplete(Box::new(cap)));
411 return Ok((true, tracker.take_partials()));
412 }
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419
420 fn ap() -> MacAddr {
421 "aa:bb:cc:dd:ee:ff".parse().unwrap()
422 }
423
424 fn sta() -> MacAddr {
425 "11:22:33:44:55:66".parse().unwrap()
426 }
427
428 const KEY_VER2: u16 = 2;
429 const INSTALL: u16 = 1 << 6;
430 const ACK: u16 = 1 << 7;
431 const MIC: u16 = 1 << 8;
432 const SECURE: u16 = 1 << 9;
433
434 /// Build a synthetic EAPOL-Key frame (eapol v2, type key, len 95).
435 fn eapol_key(key_info: u16, rc: u64, nonce: [u8; 32], mic: [u8; 16]) -> Vec<u8> {
436 let mut f = vec![2u8, 3, 0, 95]; // eapol hdr: v2, key, len=95 (desc)
437 f.push(2); // descriptor type: RSN
438 f.extend_from_slice(&key_info.to_be_bytes());
439 f.extend_from_slice(&[0u8; 2]); // key length
440 f.extend_from_slice(&rc.to_be_bytes());
441 f.extend_from_slice(&nonce);
442 f.extend_from_slice(&[0u8; 16]); // iv
443 f.extend_from_slice(&[0u8; 8]); // rsc
444 f.extend_from_slice(&[0u8; 8]); // id
445 f.extend_from_slice(&mic);
446 f.extend_from_slice(&[0u8; 2]); // key_data_len = 0
447 f
448 }
449
450 fn parse(bytes: &[u8]) -> EapolKey<'_> {
451 crate::dot11::parse_eapol_key(bytes).expect("well-formed eapol")
452 }
453
454 fn m1(rc: u64, anonce: [u8; 32]) -> Vec<u8> {
455 eapol_key(KEY_VER2 | ACK, rc, anonce, [0u8; 16])
456 }
457
458 fn m2(rc: u64, snonce: [u8; 32], mic: [u8; 16]) -> Vec<u8> {
459 eapol_key(KEY_VER2 | MIC, rc, snonce, mic)
460 }
461
462 fn m3(rc: u64, anonce: [u8; 32], mic: [u8; 16]) -> Vec<u8> {
463 eapol_key(KEY_VER2 | ACK | MIC | INSTALL | SECURE, rc, anonce, mic)
464 }
465
466 fn m4(rc: u64, mic: [u8; 16]) -> Vec<u8> {
467 eapol_key(KEY_VER2 | MIC | SECURE, rc, [0u8; 32], mic)
468 }
469
470 fn drain(rx: &crossbeam_channel::Receiver<Event>) -> Vec<Event> {
471 let mut out = Vec::new();
472 while let Ok(e) = rx.try_recv() {
473 out.push(e);
474 }
475 out
476 }
477
478 #[test]
479 fn m1_then_m2_yields_capture_and_progress() {
480 let (tx, rx) = crossbeam_channel::unbounded();
481 let mut t = Tracker::new();
482 let anonce = [7u8; 32];
483 let snonce = [9u8; 32];
484 let mic = [0xabu8; 16];
485
486 assert!(
487 t.ingest(ap(), sta(), "testnet", &parse(&m1(3, anonce)), &tx)
488 .is_none()
489 );
490 let cap = t
491 .ingest(ap(), sta(), "testnet", &parse(&m2(3, snonce, mic)), &tx)
492 .expect("M1+M2 complete");
493 assert_eq!(cap.ap, ap());
494 assert_eq!(cap.client, sta());
495 assert_eq!(cap.essid, "testnet");
496 assert_eq!(cap.anonce, anonce);
497 assert_eq!(cap.snonce, snonce);
498 assert_eq!(cap.mic(), &mic);
499 assert_eq!(cap.key_ver, 2);
500 assert!(!cap.eapol_m2.is_empty());
501
502 let evs = drain(&rx);
503 assert!(matches!(&evs[0], Event::HandshakeProgress { have: 1, .. }));
504 assert!(matches!(
505 &evs[1],
506 Event::HandshakeProgress { have: 0b0011, .. }
507 ));
508
509 // Subsequent M3/M4 inform progress but don't re-emit a capture.
510 assert!(
511 t.ingest(ap(), sta(), "testnet", &parse(&m3(3, anonce, mic)), &tx)
512 .is_none()
513 );
514 assert!(
515 t.ingest(ap(), sta(), "testnet", &parse(&m4(4, mic)), &tx)
516 .is_none()
517 );
518 let evs = drain(&rx);
519 assert!(matches!(
520 &evs[0],
521 Event::HandshakeProgress { have: 0b0111, .. }
522 ));
523 assert!(matches!(
524 &evs[1],
525 Event::HandshakeProgress { have: 0b1111, .. }
526 ));
527 }
528
529 #[test]
530 fn m2_first_then_matching_m1_completes() {
531 let (tx, _rx) = crossbeam_channel::unbounded();
532 let mut t = Tracker::new();
533 let mic = [1u8; 16];
534 assert!(
535 t.ingest(ap(), sta(), "testnet", &parse(&m2(5, [9u8; 32], mic)), &tx)
536 .is_none()
537 );
538 // Exact rc match.
539 let cap = t
540 .ingest(ap(), sta(), "testnet", &parse(&m1(5, [7u8; 32])), &tx)
541 .expect("late M1 pairs with buffered M2");
542 assert_eq!(cap.snonce, [9u8; 32]);
543 }
544
545 #[test]
546 fn m1_retransmit_one_behind_still_pairs() {
547 let (tx, _rx) = crossbeam_channel::unbounded();
548 let mut t = Tracker::new();
549 let mic = [1u8; 16];
550 t.ingest(ap(), sta(), "testnet", &parse(&m2(5, [9u8; 32], mic)), &tx);
551 // retransmit tolerance: rc(M1) == rc(M2) - 1
552 let cap = t
553 .ingest(ap(), sta(), "testnet", &parse(&m1(4, [7u8; 32])), &tx)
554 .expect("rc2-1 retransmit tolerated");
555 assert_eq!(cap.anonce, [7u8; 32]);
556 }
557
558 #[test]
559 fn rc_mismatch_blocks_capture() {
560 let (tx, _rx) = crossbeam_channel::unbounded();
561 let mut t = Tracker::new();
562 let mic = [1u8; 16];
563 t.ingest(ap(), sta(), "testnet", &parse(&m1(1, [7u8; 32])), &tx);
564 // rc(M2)=5 is neither equal nor M1+1 → no capture.
565 assert!(
566 t.ingest(ap(), sta(), "testnet", &parse(&m2(5, [9u8; 32], mic)), &tx)
567 .is_none()
568 );
569 }
570
571 #[test]
572 fn zero_mic_or_nonce_m2_ignored() {
573 let (tx, _rx) = crossbeam_channel::unbounded();
574 let mut t = Tracker::new();
575 let anonce = [7u8; 32];
576 t.ingest(ap(), sta(), "testnet", &parse(&m1(3, anonce)), &tx);
577 // Zero MIC M2 (e.g. autogenerated junk) must not complete a capture.
578 assert!(
579 t.ingest(
580 ap(),
581 sta(),
582 "testnet",
583 &parse(&m2(3, [9u8; 32], [0u8; 16])),
584 &tx
585 )
586 .is_none()
587 );
588 // Zero nonce (bogus) likewise.
589 assert!(
590 t.ingest(
591 ap(),
592 sta(),
593 "testnet",
594 &parse(&m2(3, [0u8; 32], [1u8; 16])),
595 &tx
596 )
597 .is_none()
598 );
599 }
600
601 #[test]
602 fn empty_essid_skips_capture_but_keeps_state() {
603 let (tx, _rx) = crossbeam_channel::unbounded();
604 let mut t = Tracker::new();
605 let mic = [1u8; 16];
606 t.ingest(ap(), sta(), "", &parse(&m1(3, [7u8; 32])), &tx);
607 assert!(
608 t.ingest(ap(), sta(), "", &parse(&m2(3, [9u8; 32], mic)), &tx)
609 .is_none()
610 );
611 // When the ESSID becomes known, the buffered pair can complete…
612 // …but ingest needs a fresh message to re-trigger; feed an M3 (progress)
613 // then a retransmitted M1 which re-pairs.
614 }
615
616 #[test]
617 fn partial_m2_m3_drained_at_teardown() {
618 let (tx, _rx) = crossbeam_channel::unbounded();
619 let mut t = Tracker::new();
620 let anonce = [7u8; 32];
621 let snonce = [9u8; 32];
622 let mic2 = [0x11u8; 16];
623 let mic3 = [0xabu8; 16];
624 // M2 with no M1 yet, then M3: never completed.
625 assert!(
626 t.ingest(ap(), sta(), "testnet", &parse(&m2(5, snonce, mic2)), &tx)
627 .is_none()
628 );
629 let m3f = m3(6, anonce, mic3);
630 assert!(
631 t.ingest(ap(), sta(), "testnet", &parse(&m3f), &tx)
632 .is_none()
633 );
634
635 let partials = t.take_partials();
636 assert_eq!(partials.len(), 1);
637 let p = &partials[0];
638 assert!(p.partial);
639 assert_eq!(p.ap, ap());
640 assert_eq!(p.client, sta());
641 assert_eq!(p.essid, "testnet");
642 // ANonce ← M3, SNonce ← M2, MIC + EAPOL ← M3 frame.
643 assert_eq!(p.anonce, anonce);
644 assert_eq!(p.snonce, snonce);
645 assert_eq!(p.mic(), &mic3);
646 assert_eq!(p.eapol_m2, m3f);
647 assert_eq!(p.key_ver, 2);
648
649 // Drain-once: material is gone until new messages arrive.
650 assert!(t.take_partials().is_empty());
651 }
652
653 #[test]
654 fn partial_needs_both_unpaired_m2_and_m3() {
655 let (tx, _rx) = crossbeam_channel::unbounded();
656 let mic = [1u8; 16];
657 // M2 only.
658 let mut t = Tracker::new();
659 t.ingest(ap(), sta(), "testnet", &parse(&m2(5, [9u8; 32], mic)), &tx);
660 assert!(t.take_partials().is_empty());
661 // M3 only.
662 let mut t = Tracker::new();
663 t.ingest(ap(), sta(), "testnet", &parse(&m3(5, [7u8; 32], mic)), &tx);
664 assert!(t.take_partials().is_empty());
665 }
666
667 #[test]
668 fn completed_pair_leaves_no_partial() {
669 let (tx, _rx) = crossbeam_channel::unbounded();
670 let mut t = Tracker::new();
671 let mic = [1u8; 16];
672 t.ingest(ap(), sta(), "testnet", &parse(&m1(3, [7u8; 32])), &tx);
673 assert!(
674 t.ingest(ap(), sta(), "testnet", &parse(&m2(3, [9u8; 32], mic)), &tx)
675 .is_some()
676 );
677 t.ingest(ap(), sta(), "testnet", &parse(&m3(4, [7u8; 32], mic)), &tx);
678 // The M2 paired an M1 — nothing partial remains for this pair.
679 assert!(t.take_partials().is_empty());
680 }
681
682 #[test]
683 fn partial_skipped_without_essid() {
684 let (tx, _rx) = crossbeam_channel::unbounded();
685 let mut t = Tracker::new();
686 let mic = [1u8; 16];
687 // Unknown essid: no salt → not crackable → no partial.
688 t.ingest(ap(), sta(), "", &parse(&m2(5, [9u8; 32], mic)), &tx);
689 t.ingest(ap(), sta(), "", &parse(&m3(6, [7u8; 32], mic)), &tx);
690 assert!(t.take_partials().is_empty());
691 }
692
693 #[test]
694 fn partial_newest_of_each_wins() {
695 let (tx, _rx) = crossbeam_channel::unbounded();
696 let mut t = Tracker::new();
697 let mic = [1u8; 16];
698 t.ingest(ap(), sta(), "net", &parse(&m2(5, [1u8; 32], mic)), &tx);
699 t.ingest(ap(), sta(), "net", &parse(&m2(6, [2u8; 32], mic)), &tx);
700 t.ingest(ap(), sta(), "net", &parse(&m3(6, [3u8; 32], mic)), &tx);
701 t.ingest(ap(), sta(), "net", &parse(&m3(7, [4u8; 32], mic)), &tx);
702 let p = t.take_partials();
703 assert_eq!(p.len(), 1);
704 assert_eq!(p[0].snonce, [2u8; 32]); // newest unpaired M2
705 assert_eq!(p[0].anonce, [4u8; 32]); // newest M3
706 }
707
708 #[test]
709 fn hc22000_message_pair_field_marks_partials() {
710 let complete = HandshakeCapture::new(
711 ap(),
712 sta(),
713 "testnet".into(),
714 [7u8; 32],
715 [9u8; 32],
716 [0xabu8; 16],
717 m2(3, [9u8; 32], [0xabu8; 16]),
718 2,
719 );
720 let line = handshake_hc22000(&complete);
721 assert!(line.ends_with("*00"), "{line}");
722 assert!(crate::crypto::parse_hc22000(line.strip_prefix("WPA*").unwrap()).is_ok());
723
724 let partial = HandshakeCapture::new_partial(
725 ap(),
726 sta(),
727 "testnet".into(),
728 [7u8; 32],
729 [9u8; 32],
730 [0xabu8; 16],
731 m3(4, [7u8; 32], [0xabu8; 16]),
732 2,
733 );
734 let line = handshake_hc22000(&partial);
735 assert!(line.ends_with("*02"), "{line}");
736 // Must stay parseable by crypto (partial flag restored there on "02").
737 match crate::crypto::parse_hc22000(line.strip_prefix("WPA*").unwrap()) {
738 Ok(crate::crypto::CrackTarget::Handshake(h)) => {
739 assert_eq!(h.ap, partial.ap);
740 assert_eq!(h.client, partial.client);
741 assert_eq!(h.essid, partial.essid);
742 assert_eq!(h.anonce, partial.anonce);
743 assert_eq!(h.mic(), partial.mic());
744 assert_eq!(h.eapol_m2, partial.eapol_m2);
745 assert_eq!(h.key_ver, partial.key_ver);
746 }
747 other => panic!("partial export must parse as a handshake: {other:?}"),
748 }
749 // Old field-less export form stays parseable.
750 let bare = line.strip_prefix("WPA*").unwrap();
751 let legacy = bare.strip_suffix("*02").unwrap();
752 assert!(crate::crypto::parse_hc22000(legacy).is_ok());
753 }
754
755 #[test]
756 fn hc22000_handshake_shape() {
757 let cap = HandshakeCapture::new(
758 ap(),
759 sta(),
760 "testnet".into(),
761 [7u8; 32],
762 [9u8; 32],
763 [0xabu8; 16],
764 m2(3, [9u8; 32], [0xabu8; 16]),
765 2,
766 );
767 let line = handshake_hc22000(&cap);
768 assert!(line.starts_with("WPA*02*"));
769 // Strip WPA* prefix → classic hc22000 fields; field 0 == "02".
770 let bare = line.strip_prefix("WPA*").unwrap();
771 assert_eq!(bare.split('*').next(), Some("02"));
772 assert!(bare.contains("aabbccddeeff"));
773 assert!(bare.contains("112233445566"));
774 assert!(bare.contains(&"07".repeat(32))); // anonce
775 // essid "testnet" hex
776 assert!(bare.contains("746573746e6574"));
777 }
778
779 #[test]
780 fn hc22000_pmkid_shape() {
781 let cap = PmkidCapture {
782 ap: ap(),
783 client: sta(),
784 essid: "testnet".into(),
785 pmkid: [0x42u8; 16],
786 };
787 let line = pmkid_hc22000(&cap);
788 assert_eq!(
789 line,
790 format!(
791 "WPA*01*{}*aabbccddeeff*112233445566*746573746e6574***",
792 "42".repeat(16)
793 )
794 );
795 }
796
797 #[test]
798 fn hc22000_roundtrips_through_crypto_parser() {
799 // Handshake: bare (WPA*-stripped) form must load via crypto's parser
800 // and preserve every field.
801 let cap = HandshakeCapture::new(
802 ap(),
803 sta(),
804 "testnet".into(),
805 [7u8; 32],
806 [9u8; 32],
807 [0xabu8; 16],
808 m2(3, [9u8; 32], [0xabu8; 16]),
809 2,
810 );
811 let line = handshake_hc22000(&cap);
812 let bare = line.strip_prefix("WPA*").unwrap();
813 let parsed =
814 crate::crypto::parse_hc22000(bare).expect("crypto parser must accept our export");
815 match parsed {
816 crate::crypto::CrackTarget::Handshake(h) => {
817 assert_eq!(h.ap, cap.ap);
818 assert_eq!(h.client, cap.client);
819 assert_eq!(h.essid, cap.essid);
820 assert_eq!(h.anonce, cap.anonce);
821 assert_eq!(h.snonce, cap.snonce);
822 assert_eq!(h.mic(), cap.mic());
823 assert_eq!(h.eapol_m2, cap.eapol_m2);
824 assert_eq!(h.key_ver, cap.key_ver);
825 }
826 _ => panic!("wrong target type"),
827 }
828
829 let pmkid_line = pmkid_hc22000(&PmkidCapture {
830 ap: ap(),
831 client: sta(),
832 essid: "testnet".into(),
833 pmkid: [0x42u8; 16],
834 });
835 let bare = pmkid_line.strip_prefix("WPA*").unwrap();
836 let parsed =
837 crate::crypto::parse_hc22000(bare).expect("crypto parser must accept our pmkid export");
838 match parsed {
839 crate::crypto::CrackTarget::Pmkid(p) => {
840 assert_eq!(p.ap, ap());
841 assert_eq!(p.client, sta());
842 assert_eq!(p.essid, "testnet");
843 assert_eq!(p.pmkid, [0x42u8; 16]);
844 }
845 _ => panic!("wrong target type"),
846 }
847 }
848}