forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

common.rs723 lines, 23.8 KiBHistoryRawDownload
1//! Shared domain types — the contract between radio, attack, crypto and UI
2//! layers, AND the wire format between the UI process and the privileged
3//! service (`--privileged-worker` child): every type here (plus [`Cmd`])
4//! serializes through `serde_json` lines. Signatures and field meanings are
5//! FIXED; implementations must conform exactly. Times are `last_seen_ms`
6//! (millis since the process-local epoch, see [`now_ms`]), RSSI in dBm.
7//! Fields added after the wire format froze carry serde defaults so older
8//! records deserialize losslessly (e.g. `ClientInfo.connected`, serde
9//! default true).
10
11use std::fmt;
12use std::time::Instant;
13
14use serde::{Deserialize, Serialize};
15
16/// Process-local epoch: `now_ms` returns elapsed millis since the first
17/// deref of this static. Every process has its own epoch — values are only
18/// comparable within one process.
19#[doc(hidden)]
20static EPOCH: std::sync::LazyLock<Instant> = std::sync::LazyLock::new(Instant::now);
21
22/// Milliseconds since the process-local epoch; used for `last_seen_ms`
23/// timestamps so they cross the UI/service JSON pipe (an `Instant` can't).
24pub fn now_ms() -> u64 {
25 EPOCH.elapsed().as_millis() as u64
26}
27
28/// 6-octet 802.11 MAC address.
29#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)]
30pub struct MacAddr(pub [u8; 6]);
31
32impl MacAddr {
33 pub const BROADCAST: MacAddr = MacAddr([0xff; 6]);
34 pub const ZERO: MacAddr = MacAddr([0; 6]);
35
36 pub fn is_broadcast(&self) -> bool {
37 self.0 == [0xff; 6]
38 }
39 pub fn is_multicast(&self) -> bool {
40 self.0[0] & 1 == 1
41 }
42 pub fn is_zero(&self) -> bool {
43 self.0 == [0; 6]
44 }
45}
46
47impl fmt::Display for MacAddr {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 write!(
50 f,
51 "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
52 self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
53 )
54 }
55}
56
57impl fmt::Debug for MacAddr {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 fmt::Display::fmt(self, f)
60 }
61}
62
63impl std::str::FromStr for MacAddr {
64 type Err = anyhow::Error;
65 fn from_str(s: &str) -> Result<Self, Self::Err> {
66 let parts: Vec<&str> = s.split(':').collect();
67 anyhow::ensure!(parts.len() == 6, "MAC needs 6 octets: {s}");
68 let mut out = [0u8; 6];
69 for (i, p) in parts.iter().enumerate() {
70 out[i] = u8::from_str_radix(p, 16)?;
71 }
72 Ok(MacAddr(out))
73 }
74}
75
76/// WLAN security suite derived from RSN/WPA IEs (or lack thereof).
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
78pub enum Security {
79 Open,
80 Wep,
81 /// WPAv1 (TKIP-era, legacy WPA IE).
82 Wpa,
83 /// WPA2-PSK (RSN, no SAE).
84 Wpa2,
85 /// WPA3 (RSN with SAE AKM) or WPA2/WPA3 transition mode.
86 Wpa3,
87}
88
89impl Security {
90 pub fn label(&self) -> &'static str {
91 match self {
92 Security::Open => "OPEN",
93 Security::Wep => "WEP",
94 Security::Wpa => "WPA",
95 Security::Wpa2 => "WPA2",
96 Security::Wpa3 => "WPA2/3",
97 }
98 }
99}
100
101/// Authentication key-management suites parsed from the RSN/WPA IE.
102#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
103pub enum Akm {
104 Psk,
105 Sae,
106 Owe,
107 FtPsk,
108 PskSha256,
109 OneX,
110 Other(u8),
111}
112
113impl Akm {
114 pub fn label(self) -> &'static str {
115 match self {
116 Akm::Psk => "PSK",
117 Akm::Sae => "SAE",
118 Akm::Owe => "OWE",
119 Akm::FtPsk => "FT-PSK",
120 Akm::PskSha256 => "PSK-SHA256",
121 Akm::OneX => "802.1X",
122 Akm::Other(_) => "other",
123 }
124 }
125}
126
127/// A discovered access point. Live-updated by the scanner.
128#[derive(Clone, Debug, Serialize, Deserialize)]
129pub struct AccessPoint {
130 pub bssid: MacAddr,
131 pub ssid: String,
132 pub channel: u8,
133 pub security: Security,
134 pub rssi_dbm: i8,
135 pub beacons: u64,
136 /// Millis since the process-local epoch ([`now_ms`]) of the last frame
137 /// seen from this AP. Age display = `now_ms() - last_seen_ms`.
138 pub last_seen_ms: u64,
139 /// AKM suites advertised in the RSN/WPA IE; empty = unknown (old peers,
140 /// non-RSN APs).
141 #[serde(default)]
142 pub akms: Vec<Akm>,
143}
144
145/// A discovered client station.
146#[derive(Clone, Debug, Serialize, Deserialize)]
147pub struct ClientInfo {
148 pub mac: MacAddr,
149 /// BSSID of the AP this station is talking to, if determinable.
150 pub ap: Option<MacAddr>,
151 pub rssi_dbm: i8,
152 pub frames: u64,
153 /// Millis since the process-local epoch ([`now_ms`]) of the last frame
154 /// seen from this station.
155 pub last_seen_ms: u64,
156 /// Station liveness: true while the station is active/associated; the
157 /// scanner flips it false when it observes a deauth/disassoc affecting
158 /// the station, and any later frame from the station flips it back
159 /// true. Serde default is true so pre-field wire records deserialize
160 /// as connected.
161 #[serde(default = "crate::common::default_true")]
162 pub connected: bool,
163 /// MAC-randomization pairing: device-group id from the scanner
164 /// (`Event::ClientIdent`), when this MAC was correlated.
165 #[serde(default)]
166 pub ident_group: Option<u64>,
167 #[serde(default)]
168 pub ident_conf: Option<IdentConfidence>,
169}
170
171/// Serde `default` for fields whose absent wire value means `true`
172/// ([`ClientInfo::connected`]).
173pub fn default_true() -> bool {
174 true
175}
176
177/// A complete, crackable WPA 4-way handshake capture (M1+M2 minimum).
178#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
179pub struct HandshakeCapture {
180 pub ap: MacAddr,
181 pub client: MacAddr,
182 pub essid: String,
183 pub anonce: [u8; 32],
184 pub snonce: [u8; 32],
185 mic: [u8; 16],
186 /// Full EAPOL-Key frame payload (starting at the EAPOL version byte) of
187 /// message 2, with the MIC field NOT zeroed (zeroing happens in crypto).
188 pub eapol_m2: Vec<u8>,
189 /// RSN key-info version: 1 (HMAC-MD5 MIC, WPA1-TKIP), 2 (HMAC-SHA1 MIC)
190 /// or 3 (AES-CMAC MIC).
191 pub key_ver: u8,
192 /// Partial capture: an M2+M3 nonce pair (ANonce taken from M3, SNonce
193 /// from M2; `eapol_m2` then carries the M3 frame whose MIC is checked).
194 /// Crackable by our own engine (the PTK/MIC math is identical) and
195 /// exportable to hashcat (message_pair bit 0x02); the flag is
196 /// provenance only. Serde default keeps older wire records (all
197 /// complete captures) deserializing as `false`.
198 #[serde(default)]
199 pub partial: bool,
200}
201
202impl HandshakeCapture {
203 pub fn mic(&self) -> &[u8; 16] {
204 &self.mic
205 }
206}
207
208impl HandshakeCapture {
209 /// Complete M1+M2 capture (`partial: false`).
210 #[allow(clippy::too_many_arguments)]
211 pub fn new(
212 ap: MacAddr,
213 client: MacAddr,
214 essid: String,
215 anonce: [u8; 32],
216 snonce: [u8; 32],
217 mic: [u8; 16],
218 eapol_m2: Vec<u8>,
219 key_ver: u8,
220 ) -> Self {
221 Self {
222 ap,
223 client,
224 essid,
225 anonce,
226 snonce,
227 mic,
228 eapol_m2,
229 key_ver,
230 partial: false,
231 }
232 }
233
234 /// Partial M2+M3 capture: `anonce` from the M3, `snonce` from the M2,
235 /// `mic`/`eapol_m2` from the M3 frame.
236 #[allow(clippy::too_many_arguments)]
237 pub fn new_partial(
238 ap: MacAddr,
239 client: MacAddr,
240 essid: String,
241 anonce: [u8; 32],
242 snonce: [u8; 32],
243 mic: [u8; 16],
244 eapol_m3: Vec<u8>,
245 key_ver: u8,
246 ) -> Self {
247 Self {
248 ap,
249 client,
250 essid,
251 anonce,
252 snonce,
253 mic,
254 eapol_m2: eapol_m3,
255 key_ver,
256 partial: true,
257 }
258 }
259}
260
261/// A PMKID capture (clientless attack result).
262#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
263pub struct PmkidCapture {
264 pub ap: MacAddr,
265 pub client: MacAddr, // the station we impersonated (our MAC)
266 pub essid: String,
267 pub pmkid: [u8; 16],
268}
269
270/// Cumulative per-channel frame counters (scanner → UI snapshot).
271#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
272pub struct ChannelStat {
273 pub channel: u8,
274 pub frames: u64,
275 pub beacons: u64,
276}
277
278/// One observed probe request (client asking for a network).
279#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
280pub struct ProbeInfo {
281 pub client: MacAddr,
282 /// SSID of the probe; `None` for broadcast/wildcard probes.
283 pub ssid: Option<String>,
284 pub rssi_dbm: i8,
285 /// Millis since the process-local epoch ([`now_ms`]).
286 pub at_ms: u64,
287}
288
289/// Strength of a MAC-randomization pairing decision ([`Event::ClientIdent`]).
290/// Ordered weakest→strongest; UI displays it as `?`/`~`/`=` per `label()`.
291#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
292pub enum IdentConfidence {
293 /// Only the ordered-IE fingerprint matched — driver-class witness.
294 Probable,
295 /// Fingerprint match plus a per-frame witness: shared probed SSID or
296 /// uninterrupted 802.11 sequence numbers across the rotation.
297 Strong,
298 /// WPS UUID-E matched — the device identifies itself.
299 Exact,
300}
301
302impl IdentConfidence {
303 pub fn label(self) -> &'static str {
304 match self {
305 IdentConfidence::Probable => "?",
306 IdentConfidence::Strong => "~",
307 IdentConfidence::Exact => "=",
308 }
309 }
310}
311
312/// Which of the two capture kinds was imported from a file (store::StoredCapture
313/// stays in store.rs; common must not depend on store).
314#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
315pub enum ImportedCapture {
316 Handshake(Box<HandshakeCapture>),
317 Pmkid(PmkidCapture),
318}
319
320/// Events flowing from worker threads to the UI. In the real architecture
321/// the privileged service serializes them as `serde_json` lines on the
322/// child's stdout; in mock mode a thread pushes them onto a
323/// `crossbeam_channel::Sender<Event>` directly.
324#[derive(Clone, Debug, Serialize, Deserialize)]
325pub enum Event {
326 ApUpdated(AccessPoint),
327 ApLost(MacAddr),
328 ClientUpdated(ClientInfo),
329 /// Station silent past the scanner's client-expiry window — the UI
330 /// drops it from the clients table.
331 ClientLost(MacAddr),
332 /// Progress while collecting 4-way messages.
333 HandshakeProgress {
334 ap: MacAddr,
335 client: MacAddr,
336 /// Bitmask of collected messages: bit0=M1, bit1=M2, bit2=M3, bit3=M4.
337 have: u8,
338 },
339 HandshakeComplete(Box<HandshakeCapture>),
340 /// A capture session ended having assembled only an M2+M3 nonce pair
341 /// (see [`HandshakeCapture::partial`]). The pair is crackable like a
342 /// complete capture; the event exists so the UI can label provenance.
343 HandshakePartial(Box<HandshakeCapture>),
344 PmkidCaptured(PmkidCapture),
345 /// Count of deauth/disassoc frames actually written to the wire.
346 DeauthSent {
347 ap: MacAddr,
348 target: MacAddr,
349 count: u64,
350 },
351 /// Candidates checked so far (`done`), current throughput (`hps`),
352 /// and the worst-case candidate total (`total`, when the attack
353 /// mode's space is countable) of a running crack job. Worst-case
354 /// remaining time = (total - done) / hps.
355 CrackProgress {
356 done: u64,
357 hps: f64,
358 total: Option<u64>,
359 },
360 /// A crack job recovered the passphrase.
361 CrackFound {
362 password: String,
363 },
364 /// The active crack job ended: `found` distinguishes success from
365 /// exhaustion/user-stop (emitted after [`Event::CrackFound`] too).
366 CrackStopped {
367 found: bool,
368 },
369 /// The crack job died from a backend failure (GPU device lost, kernel
370 /// dispatch timeout, worker thread panic) — NOT keyspace exhaustion.
371 /// `found` in a preceding/following CrackStopped is meaningless here:
372 /// this event supersedes it. The UI must surface `reason`, reset the
373 /// cracker to idle, and NOT delete the resume session.
374 CrackError {
375 reason: String,
376 },
377 /// Throughput of a rainbow-table build job (PMKs written so far);
378 /// `total` is the wordlist's line count (worst-case table size).
379 RainbowProgress {
380 done: u64,
381 hps: f64,
382 total: Option<u64>,
383 },
384 /// A rainbow-table build job ended (always exactly one; `entries` is
385 /// what actually landed in `path`, 0 on failure).
386 RainbowBuilt {
387 path: String,
388 entries: u64,
389 },
390 Log(String),
391 Error(String),
392 /// Cumulative per-channel counters snapshot (emitted every ~2 s).
393 ChannelStats(Vec<ChannelStat>),
394 /// A novel probe request was observed.
395 ProbeObserved(ProbeInfo),
396 /// Deauth/disassoc storm detected on a (source, target) pair that we
397 /// did not cause — a foreign deauth attack in progress.
398 DeauthAlert {
399 source: MacAddr,
400 target: MacAddr,
401 count: u32,
402 },
403 /// A capture was imported from an external file (pcap / hc22000).
404 CaptureImported(ImportedCapture),
405 /// `mac` was correlated with a device group (MAC-randomization pairing):
406 /// every MAC witnessed on the same physical radio shares `group`.
407 ClientIdent {
408 mac: MacAddr,
409 group: u64,
410 confidence: IdentConfidence,
411 },
412 /// Crack-speed benchmark finished.
413 BenchmarkDone {
414 gpu_hps: Option<f64>,
415 cpu_hps: f64,
416 },
417}
418
419/// 2.4 GHz channel → carrier frequency (MHz).
420pub fn freq_of_channel(ch: u8) -> Option<u16> {
421 match ch {
422 1..=13 => Some(2407 + 5 * ch as u16),
423 14 => Some(2484),
424 36..=173 => Some(5000 + 5 * ch as u16),
425 _ => None,
426 }
427}
428
429/// Default hop list as FREQUENCIES (MHz): every 2.4 GHz channel, the full
430/// TR-legal 5 GHz span (incl. 132/136/140 which plain channel lists often
431/// miss), and the 6 GHz PSC channels (6, 22, 38, 54, 70, 86 =
432/// 5980/6060/6140/6220/6300/6380 MHz) — phone hotspots increasingly land
433/// on 6 GHz and are invisible to channel-lists that omit it.
434pub const HOP_FREQS_ALL: &[u16] = &[
435 // 2.4 GHz ch 1..13
436 2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452, 2457, 2462, 2467, 2472,
437 // 5 GHz ch 36..64 and 100..140
438 5180, 5200, 5220, 5240, 5260, 5280, 5300, 5320, 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640,
439 5660, 5680, 5700,
440 // 6 GHz: ONLY the phy-advertised 20 MHz channel grid (5955 + 20n,
441 // ch 1/5/9/…/85). PSC channel centers (5980/6060/…) are NOT advertised
442 // by iwlwifi and the kernel rejects them with "Unknown channel".
443 5955, 5975, 5995, 6015, 6035, 6055, 6075, 6095, 6115, 6135, 6155, 6175, 6195, 6215, 6235, 6255,
444 6275, 6295, 6315, 6335, 6355, 6375, 6395, 6415,
445];
446
447/// Commands the UI process sends to the privileged service
448/// (`--privileged-worker` child), serialized as one `serde_json` line each
449/// on the child's stdin.
450#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
451pub enum Cmd {
452 /// Switch `ifname` to monitor mode and start the channel-hopping
453 /// scanner. `ifname` is saved as the interface to restore on
454 /// StopScan/Shutdown.
455 StartScan {
456 ifname: String,
457 /// Optional static channel list (diagnostics: park on one channel
458 /// instead of hopping). `None`/empty = full hop list.
459 #[serde(default)]
460 channels: Option<Vec<u8>>,
461 /// Pcap spool file for the scan: every received raw frame (with
462 /// radiotap header) is appended to it. `None` = no spooling.
463 #[serde(default)]
464 spool: Option<std::path::PathBuf>,
465 /// Truncate the spool file on scan start (`false` = append if it
466 /// exists). UI sets `true` on a fresh scan from toggle_monitor,
467 /// `false` when re-parking channels mid-scan.
468 #[serde(default)]
469 fresh_spool: bool,
470 },
471 /// Stop the scanner, restore managed mode.
472 StopScan,
473 /// Blast `count` deauth rounds per `(bssid, channel)` entry at
474 /// `target` (broadcast allowed). Multiple entries cover dual-band
475 /// networks: the worker walks the list sequentially (one channel at a
476 /// time is all a single radio can do).
477 Deauth {
478 aps: Vec<(MacAddr, u8)>,
479 target: MacAddr,
480 count: u32,
481 },
482 /// Deauth every client of one AP at once: pins the channel, blasts
483 /// `count` rounds at each target in `targets`, then one broadcast
484 /// blast. `ap` is also recorded so the service's foreign-deauth
485 /// detector suppresses its own frames.
486 DeauthAll {
487 ap: MacAddr,
488 channel: u8,
489 targets: Vec<MacAddr>,
490 count: u32,
491 },
492 /// Clientless PMKID grab against `ap`.
493 Pmkid {
494 ap: MacAddr,
495 channel: u8,
496 essid: String,
497 },
498 /// Track 4-way handshakes of every BSSID in `targets` (dual-band
499 /// networks send the exchange on whichever band the client chose — the
500 /// parked SCANNER hops the union of channels, so a single listen
501 /// covers all bands). One channel → the worker pins it itself.
502 CaptureHs {
503 targets: Vec<(MacAddr, u8)>,
504 essid: String,
505 },
506 /// Stop NetworkManager/wpa_supplicant so they stop pinning the radio.
507 StopNetworkManager,
508 /// Stop all workers, restore the interface, exit the service.
509 Shutdown,
510}
511
512#[cfg(test)]
513mod tests {
514 use super::*;
515
516 fn ap_obj() -> AccessPoint {
517 AccessPoint {
518 bssid: MacAddr([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]),
519 ssid: "testnet".into(),
520 channel: 6,
521 security: Security::Wpa2,
522 rssi_dbm: -42,
523 beacons: 7,
524 last_seen_ms: 123_456,
525 akms: vec![Akm::Psk],
526 }
527 }
528
529 fn client_obj() -> ClientInfo {
530 ClientInfo {
531 mac: MacAddr([0x11; 6]),
532 ap: Some(MacAddr([0xaa; 6])),
533 rssi_dbm: -55,
534 frames: 3,
535 last_seen_ms: 654_321,
536 connected: true,
537 ident_group: Some(7),
538 ident_conf: Some(IdentConfidence::Strong),
539 }
540 }
541
542 fn handshake_obj() -> HandshakeCapture {
543 HandshakeCapture::new(
544 MacAddr([1; 6]),
545 MacAddr([2; 6]),
546 "labnet".into(),
547 [3u8; 32],
548 [4u8; 32],
549 [5u8; 16],
550 vec![6u8; 99],
551 2,
552 )
553 }
554
555 fn pmkid_obj() -> PmkidCapture {
556 PmkidCapture {
557 ap: MacAddr([7; 6]),
558 client: MacAddr([8; 6]),
559 essid: "corp".into(),
560 pmkid: [9u8; 16],
561 }
562 }
563
564 fn roundtrip<T>(value: &T) -> T
565 where
566 T: Serialize + for<'de> Deserialize<'de> + std::fmt::Debug,
567 {
568 let json = serde_json::to_string(value).expect("serialize");
569 serde_json::from_str(&json).unwrap_or_else(|e| panic!("deserialize {json}: {e}"))
570 }
571
572 #[test]
573 fn now_ms_is_monotonic_and_ms_scale() {
574 let a = now_ms();
575 let b = now_ms();
576 assert!(b >= a);
577 // Same-process sanity: first deref happens at most a few hundred ms
578 // before this test runs (process start); elapsed must stay small.
579 assert!(a < 120_000, "process-local epoch ms implausibly large: {a}");
580 }
581
582 #[test]
583 fn event_json_roundtrips() {
584 let cases: Vec<Event> = vec![
585 Event::ApUpdated(ap_obj()),
586 Event::ApLost(MacAddr::BROADCAST),
587 Event::ClientUpdated(client_obj()),
588 Event::HandshakeProgress {
589 ap: MacAddr([1; 6]),
590 client: MacAddr([2; 6]),
591 have: 0b1011,
592 },
593 Event::HandshakeComplete(Box::new(handshake_obj())),
594 Event::PmkidCaptured(pmkid_obj()),
595 Event::DeauthSent {
596 ap: MacAddr([1; 6]),
597 target: MacAddr::BROADCAST,
598 count: 64,
599 },
600 Event::CrackProgress {
601 done: 1000,
602 hps: 1234.5,
603 total: Some(5000),
604 },
605 Event::CrackFound {
606 password: "hunter2".into(),
607 },
608 Event::CrackStopped { found: true },
609 Event::CrackStopped { found: false },
610 Event::RainbowProgress {
611 done: 42,
612 hps: 9.5,
613 total: None,
614 },
615 Event::RainbowBuilt {
616 path: "/tmp/t.pmk".into(),
617 entries: 7,
618 },
619 Event::Log("hello".into()),
620 Event::Error("boom".into()),
621 Event::ChannelStats(vec![
622 ChannelStat {
623 channel: 6,
624 frames: 1234,
625 beacons: 56,
626 },
627 ChannelStat {
628 channel: 36,
629 frames: 78,
630 beacons: 9,
631 },
632 ]),
633 Event::ProbeObserved(ProbeInfo {
634 client: MacAddr([0x42; 6]),
635 ssid: Some("HOME-WIFI".into()),
636 rssi_dbm: -61,
637 at_ms: 987_654,
638 }),
639 Event::DeauthAlert {
640 source: MacAddr([0xde; 6]),
641 target: MacAddr::BROADCAST,
642 count: 17,
643 },
644 Event::CaptureImported(ImportedCapture::Handshake(Box::new(handshake_obj()))),
645 Event::ClientIdent {
646 mac: MacAddr([0x02, 0xa0, 0xb1, 0xc2, 0xd3, 0xe4]),
647 group: 42,
648 confidence: IdentConfidence::Exact,
649 },
650 Event::BenchmarkDone {
651 gpu_hps: Some(1_250_000.0),
652 cpu_hps: 310_000.0,
653 },
654 ];
655 for ev in &cases {
656 let json = serde_json::to_string(ev).expect("serialize");
657 let back: Event =
658 serde_json::from_str(&json).unwrap_or_else(|e| panic!("deserialize {json}: {e}"));
659 assert_eq!(format!("{ev:?}"), format!("{back:?}"));
660 }
661 }
662
663 #[test]
664 fn handshake_json_roundtrip_is_lossless() {
665 // PartialEq on the struct itself (not just Debug) — the Box in
666 // Event::HandshakeComplete must survive the wire.
667 let ev = Event::HandshakeComplete(Box::new(handshake_obj()));
668 let json = serde_json::to_string(&ev).expect("serialize");
669 let Event::HandshakeComplete(back) = serde_json::from_str(&json).expect("deserialize")
670 else {
671 panic!("variant changed shape: {json}");
672 };
673 assert_eq!(*back, handshake_obj());
674 let pm = Event::PmkidCaptured(pmkid_obj());
675 let json = serde_json::to_string(&pm).expect("serialize");
676 let Event::PmkidCaptured(back) = serde_json::from_str(&json).expect("deserialize") else {
677 panic!("variant changed shape: {json}");
678 };
679 assert_eq!(back, pmkid_obj());
680 }
681
682 #[test]
683 fn cmd_json_roundtrips() {
684 let cases: Vec<Cmd> = vec![
685 Cmd::StartScan {
686 ifname: "wlp14s0".into(),
687 channels: None,
688 spool: None,
689 fresh_spool: false,
690 },
691 Cmd::StopScan,
692 Cmd::Deauth {
693 aps: vec![(MacAddr([1; 6]), 6)],
694 target: MacAddr::BROADCAST,
695 count: 16,
696 },
697 Cmd::Pmkid {
698 ap: MacAddr([2; 6]),
699 channel: 36,
700 essid: "corp-wpa3".into(),
701 },
702 Cmd::CaptureHs {
703 targets: vec![(MacAddr([3; 6]), 11), (MacAddr([4; 6]), 60)],
704 essid: "coffeeshop".into(),
705 },
706 Cmd::StopNetworkManager,
707 Cmd::Shutdown,
708 Cmd::DeauthAll {
709 ap: MacAddr([5; 6]),
710 channel: 44,
711 targets: vec![MacAddr([6; 6]), MacAddr([7; 6])],
712 count: 8,
713 },
714 ];
715 for cmd in &cases {
716 let json = serde_json::to_string(cmd).expect("serialize");
717 let back: Cmd =
718 serde_json::from_str(&json).unwrap_or_else(|e| panic!("deserialize {json}: {e}"));
719 assert_eq!(*cmd, back);
720 }
721 assert_eq!(roundtrip(&cases[0]), cases[0]);
722 }
723}