forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

attacks.rs1341 lines, 48.5 KiBHistoryRawDownload
1//! Attacks page: target banner, capture/PMKID/deauth triggers (mock-injected
2//! into the event channel), capture cards, hc22000 export.
3
4use std::path::{Path, PathBuf};
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use gpui::{
8 Context, Entity, IntoElement, ParentElement, Styled, Window, div, prelude::FluentBuilder, px,
9};
10use gpuikit::elements::badge::badge;
11use gpuikit::elements::button::button;
12use gpuikit::elements::card::card;
13use gpuikit::elements::loading_indicator::loading_indicator;
14use gpuikit::elements::text_field::text_field;
15use gpuikit::elements::typography::{h3, small, text};
16use gpuikit::layout::{h_stack, v_stack};
17use gpuikit::theme::{ActiveTheme, Themeable};
18
19use crate::common::{Akm, ClientInfo, Cmd, Event, HandshakeCapture, MacAddr, PmkidCapture};
20use crate::ui::app::AppRoot;
21use crate::ui::mock;
22
23fn unix_secs() -> u64 {
24 SystemTime::now()
25 .duration_since(UNIX_EPOCH)
26 .map(|d| d.as_secs())
27 .unwrap_or(0)
28}
29
30fn hex(bytes: &[u8]) -> String {
31 let mut out = String::with_capacity(bytes.len() * 2);
32 for b in bytes {
33 out.push_str(&format!("{b:02x}"));
34 }
35 out
36}
37
38/// Export all captures: platform save dialog if it opens, otherwise a fixed
39/// fallback path under ./captures. Uses the crate's hc22000 formatting
40/// (single source of truth in [`crate::handshake`]).
41fn export_hc22000(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
42 let (lines, total) = {
43 let app = view.read(cx);
44 let mut lines: Vec<String> = app
45 .state
46 .handshakes
47 .iter()
48 .map(crate::handshake::handshake_hc22000)
49 // Partial M2+M3 captures export too (hashcat m22000 accepts
50 // them via the trailing 02 message-pair field). Partials
51 // also join the normal capture list, so the sort/dedup
52 // below keeps doubles out of the file.
53 .chain(
54 app.state
55 .partials
56 .iter()
57 .map(crate::handshake::handshake_hc22000),
58 )
59 .chain(app.state.pmkids.iter().map(crate::handshake::pmkid_hc22000))
60 .collect();
61 lines.sort_unstable();
62 lines.dedup();
63 // Log line counts what actually lands in the file (deduped).
64 let total = lines.len();
65 (lines, total)
66 };
67 if lines.is_empty() {
68 view.update(cx, |app, cx| {
69 app.state.push_log("export: no captures yet");
70 cx.notify();
71 });
72 return;
73 }
74
75 let suggested = format!("wifi_lab-{}.hc22000", unix_secs());
76 let prompt = cx.prompt_for_new_path(Path::new("./captures"), Some(&suggested));
77 let body = lines.join("\n") + "\n";
78 let weak = view.downgrade();
79 cx.spawn(async move |cx| {
80 // Dialog refused/cancelled → fixed fallback; explicit cancel aborts.
81 let path: Option<PathBuf> = match prompt.await {
82 Ok(Ok(Some(p))) => Some(p),
83 Ok(Ok(None)) => None,
84 _ => Some(PathBuf::from("./captures").join(&suggested)),
85 };
86 let _ = weak.update(cx, |app, cx| {
87 match path {
88 None => app.state.push_log("export: cancelled"),
89 Some(path) => {
90 if let Some(parent) = path.parent() {
91 let _ = std::fs::create_dir_all(parent);
92 }
93 match std::fs::write(&path, &body) {
94 Ok(()) => app.state.push_log(format!(
95 "export: {} captures → {}",
96 total,
97 path.display()
98 )),
99 Err(e) => app
100 .state
101 .push_log(format!("export FAILED: {e} ({})", path.display())),
102 }
103 }
104 }
105 cx.notify();
106 });
107 })
108 .detach();
109}
110
111/// Export the raw pcap spool (every frame the scanner saw since the
112/// capture started) via the platform save dialog; falls back to a fixed
113/// path under ./captures when the dialog is refused.
114fn export_pcap(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
115 let spool = crate::store::data_dir().join("spool.pcap");
116 if !spool.is_file() {
117 view.update(cx, |app, cx| {
118 app.state
119 .push_log("pcap export: no spool yet — start a capture first");
120 cx.notify();
121 });
122 return;
123 }
124
125 let suggested = format!("wifi_lab-{}.pcap", unix_secs());
126 let prompt = cx.prompt_for_new_path(Path::new("./captures"), Some(&suggested));
127 let weak = view.downgrade();
128 cx.spawn(async move |cx| {
129 // Dialog refused/cancelled → fixed fallback; explicit cancel aborts.
130 let path: Option<PathBuf> = match prompt.await {
131 Ok(Ok(Some(p))) => Some(p),
132 Ok(Ok(None)) => None,
133 _ => Some(PathBuf::from("./captures").join(&suggested)),
134 };
135 let _ = weak.update(cx, |app, cx| {
136 match path {
137 None => app.state.push_log("pcap export: cancelled"),
138 Some(path) => {
139 if let Some(parent) = path.parent() {
140 let _ = std::fs::create_dir_all(parent);
141 }
142 match std::fs::copy(&spool, &path) {
143 Ok(n) => app
144 .state
145 .push_log(format!("pcap export: {n} bytes → {}", path.display())),
146 Err(e) => app
147 .state
148 .push_log(format!("pcap export FAILED: {e} ({})", path.display())),
149 }
150 }
151 }
152 cx.notify();
153 });
154 })
155 .detach();
156}
157
158/// Selected target with its current AP row (channel + essid).
159fn target_info(app: &AppRoot) -> Option<(MacAddr, u8, String)> {
160 let ap = app.selected?;
161 let row = app.state.aps.get(&ap)?;
162 Some((ap, row.channel, row.ssid.clone()))
163}
164
165/// The selected target's AP row for rendering: the live record wins;
166/// otherwise the snapshot taken at click time (host-capture mode never
167/// re-scans, so a valid target may have no live row at all). Second tuple
168/// element is true when falling back to the (possibly stale) snapshot.
169fn target_row(app: &AppRoot) -> Option<(&crate::common::AccessPoint, bool)> {
170 let sel = app.selected?;
171 if let Some(row) = app.state.aps.get(&sel) {
172 return Some((row, false));
173 }
174 app.selected_ap.as_ref().map(|row| (row, true))
175}
176
177/// Material already captured for this AP (dual-band siblings count as
178/// their own BSSIDs — a handshake grabbed on the 5 GHz twin crackable
179/// for the same password, so count the whole ESSID family).
180fn material_for(app: &AppRoot, ap: &crate::common::AccessPoint) -> (usize, usize) {
181 let essids = sibling_targets(app, &ap.ssid)
182 .into_iter()
183 .map(|(b, _)| b)
184 .collect::<Vec<_>>();
185 let hs = app
186 .state
187 .handshakes
188 .iter()
189 .filter(|h| essids.contains(&h.ap))
190 .count();
191 let pm = app
192 .state
193 .pmkids
194 .iter()
195 .filter(|p| essids.contains(&p.ap))
196 .count();
197 (hs, pm)
198}
199
200/// One-line "best next move" for the selected target, computed from what
201/// the scanner already knows — the answer to "which button do I press".
202/// Second tuple element: true = actionable path, false = dead end (the
203/// card colors accordingly).
204fn advisor(app: &AppRoot, ap: &crate::common::AccessPoint) -> (&'static str, bool) {
205 use crate::common::Security;
206 let akms = &ap.akms;
207 let sae = !akms.is_empty()
208 && akms.contains(&Akm::Sae)
209 && !akms.contains(&Akm::Psk)
210 && !akms.contains(&Akm::PskSha256);
211 if sae {
212 return (
213 "advice: SAE-only — no offline-crackable material exists (dead end for today)",
214 false,
215 );
216 }
217 match ap.security {
218 Security::Open => return ("advice: open network — nothing to crack", false),
219 Security::Wep => {
220 return (
221 "advice: WEP — ancient; out of scope here (use dedicated tools)",
222 false,
223 );
224 }
225 _ => {}
226 }
227 if !akms.is_empty() && akms.contains(&Akm::Owe) && !akms.contains(&Akm::Psk) {
228 return (
229 "advice: OWE (enhanced open) — no password to recover",
230 false,
231 );
232 }
233 let (hs, pm) = material_for(app, ap);
234 if hs + pm > 0 {
235 return (
236 "advice: capture material in hand — crack it on the Cracker page",
237 true,
238 );
239 }
240 if sae_transition(akms) {
241 return (
242 "advice: WPA3 transition (PSK still offered) — handshake capture or PMKID works",
243 true,
244 );
245 }
246 if connected_clients(app, ap.bssid).is_empty() {
247 (
248 "advice: no clients mapped — run PMKID first (clientless), then park a handshake capture",
249 true,
250 )
251 } else {
252 (
253 "advice: deauth a client while handshake capture runs — it re-auths with a fresh 4-way",
254 true,
255 )
256 }
257}
258
259fn sae_transition(akms: &[Akm]) -> bool {
260 akms.contains(&Akm::Sae) && (akms.contains(&Akm::Psk) || akms.contains(&Akm::PskSha256))
261}
262
263/// WPA3 SAE-only targets yield no offline-crackable material: the
264/// dragonfly handshake can't be brute-forced offline and SAE APs never
265/// hand out a PMKID. Transition-mode APs (PSK alongside SAE) still work.
266fn sae_only(app: &AppRoot) -> bool {
267 let Some((row, _stale)) = target_row(app) else {
268 return false;
269 };
270 let akms = &row.akms;
271 !akms.is_empty()
272 && akms.contains(&Akm::Sae)
273 && !akms.contains(&Akm::Psk)
274 && !akms.contains(&Akm::PskSha256)
275}
276
277/// Capture Handshake.
278/// Mock mode: drive a fresh fabricated 4-way through the event pipeline.
279/// Real mode: spawn the backend capture worker (channel probed first via
280/// a zero-count deauth pulse); progress/completion arrive as real events.
281fn capture_handshake(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
282 view.update(cx, |app, cx| {
283 let Some(ap) = app.selected else {
284 app.state.push_log("handshake: no target selected");
285 cx.notify();
286 return;
287 };
288 if app.attacking_handshake {
289 return;
290 }
291 if !app.is_mock && !app.state.iface_running {
292 app.state
293 .push_log("handshake: start capture first (attacks need the radio in monitor mode)");
294 cx.notify();
295 return;
296 }
297 app.attacking_handshake = true;
298 cx.notify();
299
300 if !app.is_mock {
301 let Some((_sel_bssid, _sel_ch, essid)) = target_info(app) else {
302 app.state
303 .push_log("handshake: target AP not in scan table yet");
304 app.attacking_handshake = false;
305 cx.notify();
306 return;
307 };
308 // Dual-band: watch EVERY BSSID of this ESSID (the scanner
309 // parks on the union of channels, so all bands are covered).
310 let targets = sibling_targets(app, &essid);
311 let channels = channels_of(&targets);
312 app.state.push_log(format!(
313 "handshake capture on {essid} — {} bssid(s), ch [{}]… deauth a client to force re-auth",
314 targets.len(),
315 channels.iter().map(u8::to_string).collect::<Vec<_>>().join(", ")
316 ));
317 park_channels(app, &channels);
318 if let Some(svc) = &app.service {
319 svc.cmd(&Cmd::CaptureHs { targets, essid });
320 }
321 cx.notify();
322 return;
323 }
324
325 // ---- mock path ----
326 let essid = app
327 .state
328 .aps
329 .get(&ap)
330 .map(|a| a.ssid.clone())
331 .unwrap_or_else(|| ap.to_string());
332 // Prefer a client actually associated with the target.
333 let client = app
334 .state
335 .clients
336 .values()
337 .find(|c| c.ap == Some(ap))
338 .map(|c| c.mac)
339 .unwrap_or(mock::MOCK_CLIENTS[0]);
340 app.state
341 .push_log(format!("handshake capture on {essid} ({ap}), targeting {client}…"));
342 cx.notify();
343
344 let tx = app.tx.clone();
345 let essid_ev = essid.clone();
346 let salt = unix_secs();
347 cx.spawn(async move |this, cx| {
348 let _ = tx.send(Event::HandshakeProgress {
349 ap,
350 client,
351 have: 0b0001,
352 });
353 cx.background_executor()
354 .timer(Duration::from_millis(900))
355 .await;
356 let _ = tx.send(Event::HandshakeProgress {
357 ap,
358 client,
359 have: 0b0011,
360 });
361 cx.background_executor()
362 .timer(Duration::from_millis(900))
363 .await;
364 let cap = mock::fabricate_handshake(ap, client, &essid_ev, salt);
365 let _ = tx.send(Event::HandshakeComplete(Box::new(cap)));
366 let _ = this.update(cx, |app, cx| {
367 app.attacking_handshake = false;
368 cx.notify();
369 });
370 })
371 .detach();
372 });
373}
374
375/// PMKID attack: client-less, one exchange, captured PMKID arrives shortly.
376fn pmkid_attack(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
377 view.update(cx, |app, cx| {
378 let Some(ap) = app.selected else {
379 app.state.push_log("pmkid: no target selected");
380 cx.notify();
381 return;
382 };
383 if app.attacking_pmkid {
384 return;
385 }
386 if !app.is_mock && !app.state.iface_running {
387 app.state
388 .push_log("pmkid: start capture first (attacks need the radio in monitor mode)");
389 cx.notify();
390 return;
391 }
392 app.attacking_pmkid = true;
393 cx.notify();
394
395 if !app.is_mock {
396 let Some((ap, channel, essid)) = target_info(app) else {
397 app.state.push_log("pmkid: target AP not in scan table yet");
398 app.attacking_pmkid = false;
399 cx.notify();
400 return;
401 };
402 app.state
403 .push_log(format!("pmkid attack on {essid} ({ap}, ch {channel})…"));
404 park_channels(app, &[channel]);
405 if let Some(svc) = &app.service {
406 svc.cmd(&Cmd::Pmkid { ap, channel, essid });
407 }
408 cx.notify();
409 return;
410 }
411
412 // ---- mock path ----
413 let essid = app
414 .state
415 .aps
416 .get(&ap)
417 .map(|a| a.ssid.clone())
418 .unwrap_or_else(|| ap.to_string());
419 app.state
420 .push_log(format!("pmkid attack on {essid} ({ap})…"));
421 cx.notify();
422
423 let tx = app.tx.clone();
424 let salt = unix_secs() ^ 0x77;
425 cx.spawn(async move |this, cx| {
426 cx.background_executor()
427 .timer(Duration::from_millis(1200))
428 .await;
429 let cap = mock::fabricate_pmkid(ap, mock::MOCK_CLIENTS[3], &essid, salt);
430 let _ = tx.send(Event::PmkidCaptured(cap));
431 let _ = this.update(cx, |app, cx| {
432 app.attacking_pmkid = false;
433 cx.notify();
434 });
435 })
436 .detach();
437 });
438}
439
440/// Every BSSID sharing the target's ESSID, with the selected target
441/// first — dual-band routers broadcast one SSID on several bands and the
442/// client picks one; attacks must cover all of them. Falls back to just
443/// the selected target when nothing else is known.
444fn sibling_targets(app: &AppRoot, essid: &str) -> Vec<(MacAddr, u8)> {
445 let mut targets: Vec<(MacAddr, u8)> = Vec::new();
446 let mut others: Vec<(MacAddr, u8)> = Vec::new();
447 for a in app.state.aps.values() {
448 if a.ssid == essid && a.channel != 0 {
449 if Some(a.bssid) == app.selected {
450 targets.push((a.bssid, a.channel));
451 } else {
452 others.push((a.bssid, a.channel));
453 }
454 }
455 }
456 targets.extend(others);
457 targets
458}
459
460/// Union of channels of a target list (sorted, deduped, zeros dropped).
461fn channels_of(targets: &[(MacAddr, u8)]) -> Vec<u8> {
462 let mut ch: Vec<u8> = targets.iter().map(|(_, c)| *c).collect();
463 ch.sort_unstable();
464 ch.dedup();
465 ch
466}
467
468/// Restrict the scanner to the target channels so attack workers aren't
469/// fighting the 100 ms spectrum-wide hopper (capture/PMKID listen, deauth
470/// injects — a far-away radio is mostly deaf/blind). Restarts the scanner
471/// with the restricted plan when not already parked on it; a no-op
472/// otherwise and in mock mode.
473fn park_channels(app: &mut AppRoot, channels: &[u8]) {
474 let mut want = channels.to_vec();
475 want.sort_unstable();
476 want.dedup();
477 if app.is_mock || want.is_empty() || app.parked_channels.as_deref() == Some(&want) {
478 return;
479 }
480 // A channel-plan restart also stops any running attack worker — the
481 // new plan invalidates them; the caller (re)spawns its own worker
482 // right after.
483 if let Some(svc) = &app.service {
484 svc.cmd(&Cmd::StartScan {
485 ifname: app.state.ifname.clone(),
486 channels: Some(want.clone()),
487 // Keep appending to the same spool across attack-mode restarts
488 // — only the toggle-monitor start truncates.
489 spool: Some(crate::store::data_dir().join("spool.pcap")),
490 fresh_spool: false,
491 });
492 app.parked_channels = Some(want.clone());
493 app.state.push_log(format!(
494 "scanner parked on ch [{}] (attack mode)",
495 want.iter()
496 .map(u8::to_string)
497 .collect::<Vec<_>>()
498 .join(", ")
499 ));
500 }
501}
502
503/// Parse the trimmed deauth round-count field. Rejects unparseable or
504/// zero input with a ready-to-log message (the blast must NOT fire on
505/// it): the pre-fix code silently fired 64 rounds at a live target via
506/// `parse().unwrap_or(64)` — no validation error on a destructive
507/// button. Mirrors the cracker page's length-field rejection. Valid
508/// numbers pass through unclamped; callers clamp to `u32::MAX` as
509/// before (64 rounds ≈ 2 s of airtime per direction — short bursts
510/// slip entirely under a power-save client's doze window).
511fn parse_deauth_count(raw: &str) -> Result<u64, String> {
512 let count: u64 = raw
513 .parse()
514 .map_err(|_| format!("deauth: bad round count '{raw}' — nothing sent"))?;
515 if count == 0 {
516 return Err("deauth: round count must be at least 1 — nothing sent".to_string());
517 }
518 Ok(count)
519}
520
521/// Deauth `target` (a station, or [`MacAddr::BROADCAST`] for the whole
522/// net) against the selected AP, `count` rounds from the count field.
523/// Real mode blasts from the service's own socket; mock mode fabricates
524/// the same DeauthSent event the real worker emits.
525fn do_deauth(app: &mut AppRoot, cx: &mut Context<AppRoot>, target: MacAddr) {
526 let Some(ap) = app.selected else {
527 app.state.push_log("deauth: no target selected");
528 cx.notify();
529 return;
530 };
531 let count64: u64 = match parse_deauth_count(app.deauth_input.read(cx).content().trim()) {
532 Ok(count) => count,
533 Err(msg) => {
534 app.state.push_log(msg);
535 cx.notify();
536 return;
537 }
538 };
539
540 if !app.is_mock {
541 if !app.state.iface_running {
542 app.state
543 .push_log("deauth: start capture first (injection needs monitor mode)");
544 cx.notify();
545 return;
546 }
547 if app.service.is_none() {
548 app.state
549 .push_log("deauth: start capture first (the service owns the radio)");
550 cx.notify();
551 return;
552 }
553 let Some((_sel_bssid, _sel_ch, essid)) = target_info(app) else {
554 app.state
555 .push_log("deauth: target AP not in scan table yet");
556 cx.notify();
557 return;
558 };
559 // Dual-band: blast every BSSID of this ESSID — the client picks
560 // the band, we don't get to. The service worker walks the list
561 // sequentially.
562 let aps = sibling_targets(app, &essid);
563 let channels = channels_of(&aps);
564 // Park ONCE on the final plan before sending ANY attack command:
565 // a channel-plan restart stop-joins all workers, so parking later
566 // would kill the capture worker armed just below.
567 park_channels(app, &channels);
568 // A deauth without a listener yields nothing: arm a handshake
569 // capture first when none is running (the flag is app-global —
570 // one target at a time, matching the attacks page). CaptureHs is
571 // handled before Deauth (single command pipe), and the service
572 // holds the channel synchronously there, so the blast can't shake
573 // a client loose onto an unwatched band.
574 if !app.attacking_handshake {
575 app.attacking_handshake = true;
576 app.state.push_log(format!(
577 "deauth: no capture running — auto-armed handshake capture on {essid}"
578 ));
579 // Presence was checked at the top of this branch, but keep
580 // the dependency local: a reordered closure must degrade to
581 // a log line, never a panic abort.
582 let Some(svc) = app.service.as_ref() else {
583 app.attacking_handshake = false;
584 app.state
585 .push_log("deauth: service disconnected — capture not armed");
586 cx.notify();
587 return;
588 };
589 svc.cmd(&Cmd::CaptureHs {
590 targets: aps.clone(),
591 essid: essid.clone(),
592 });
593 }
594 let count = count64.min(u32::MAX as u64) as u32;
595 let kind = if target.is_broadcast() {
596 "broadcast".to_string()
597 } else {
598 format!("client {target}")
599 };
600 app.state.push_log(format!(
601 "deauth: {count} rounds → {kind} ({} bssid(s), ch [{}])",
602 aps.len(),
603 channels
604 .iter()
605 .map(u8::to_string)
606 .collect::<Vec<_>>()
607 .join(", ")
608 ));
609 let Some(svc) = app.service.as_ref() else {
610 app.state
611 .push_log("deauth: service disconnected — blast not sent");
612 cx.notify();
613 return;
614 };
615 svc.cmd(&Cmd::Deauth {
616 aps: aps.clone(),
617 target,
618 count,
619 });
620 // Optimistic DOWN marking: monitor-mode TX never loops back to
621 // the scanner socket (verified: PACKET_OUTGOING never surfaces on
622 // mt7921e injection), so the scanner can't observe our own blast
623 // and the row would stay "up" until the client talks again
624 // (ClientUpdated flips it back) or ages out. Broadcast → every
625 // station mapped to a sibling BSSID of this ESSID.
626 for cl in app.state.clients.values_mut() {
627 let blasted = if target.is_broadcast() {
628 cl.ap.is_some_and(|cap| aps.iter().any(|(b, _)| *b == cap))
629 } else {
630 cl.mac == target
631 };
632 if blasted {
633 cl.connected = false;
634 }
635 }
636 cx.notify();
637 return;
638 }
639
640 let _ = app.tx.send(Event::DeauthSent {
641 ap,
642 target,
643 count: count64,
644 });
645 // Same optimistic DOWN marking as the real branch (see there).
646 for cl in app.state.clients.values_mut() {
647 let blasted = if target.is_broadcast() {
648 cl.ap.is_none_or(|cap| cap == ap)
649 } else {
650 cl.mac == target
651 };
652 if blasted {
653 cl.connected = false;
654 }
655 }
656 cx.notify();
657}
658
659/// A client row counts as belonging to the selected target when the
660/// scanner mapped it there — OR when its AP is unknown (the scanner often
661/// never resolves the association; trust the user's pick).
662fn client_on_target(app: &AppRoot, mac: &MacAddr, ap: MacAddr) -> bool {
663 app.state
664 .clients
665 .get(mac)
666 .is_some_and(|c| c.ap.is_none_or(|cap| cap == ap))
667}
668
669/// Deauth button: a selected client row (see [`client_on_target`]) wins;
670/// otherwise deauth the whole net broadcast-style.
671fn deauth(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
672 view.update(cx, |app, cx| {
673 let target = app
674 .selected
675 .and_then(|ap| {
676 app.selected_client
677 .filter(|mac| client_on_target(app, mac, ap))
678 })
679 .unwrap_or(MacAddr::BROADCAST);
680 do_deauth(app, cx, target);
681 });
682}
683
684/// Per-station Deauth button in the stations table: fires immediately at
685/// that station, no handshake capture required.
686fn deauth_station(view: &Entity<AppRoot>, station: MacAddr, cx: &mut gpui::App) {
687 view.update(cx, |app, cx| do_deauth(app, cx, station));
688}
689
690/// Connected clients mapped to the selected AP (strict association —
691/// `client_on_target`'s "unknown AP" leniency would sweep strangers into
692/// a bulk blast).
693fn connected_clients(app: &AppRoot, ap: MacAddr) -> Vec<MacAddr> {
694 let mut macs: Vec<MacAddr> = app
695 .state
696 .clients
697 .values()
698 .filter(|c| c.ap == Some(ap) && c.connected && !c.mac.is_broadcast())
699 .map(|c| c.mac)
700 .collect();
701 macs.sort();
702 macs
703}
704
705/// Bulk deauth: every connected client of the selected AP in one service
706/// job (single channel pin, per-client rounds, then one broadcast blast).
707/// Mock mode fabricates the same DeauthSent stream per client.
708fn deauth_all(view: &Entity<AppRoot>, cx: &mut gpui::App) {
709 view.update(cx, |app, cx| {
710 let Some(ap) = app.selected else {
711 app.state.push_log("deauth-all: no target selected");
712 cx.notify();
713 return;
714 };
715 let targets = connected_clients(app, ap);
716 if targets.len() < 2 {
717 app.state
718 .push_log("deauth-all: fewer than 2 connected clients — deauth them one by one");
719 cx.notify();
720 return;
721 }
722 let count64: u64 = match parse_deauth_count(app.deauth_input.read(cx).content().trim()) {
723 Ok(count) => count,
724 Err(msg) => {
725 app.state.push_log(msg);
726 cx.notify();
727 return;
728 }
729 };
730
731 if !app.is_mock {
732 if !app.state.iface_running || app.service.is_none() {
733 app.state
734 .push_log("deauth-all: start capture first (injection needs monitor mode)");
735 cx.notify();
736 return;
737 }
738 let Some((_sel_bssid, channel, essid)) = target_info(app) else {
739 app.state
740 .push_log("deauth-all: target AP not in scan table yet");
741 cx.notify();
742 return;
743 };
744 // Park before ANY attack command (see do_deauth) and arm a
745 // capture so the forced re-auths land in a listener.
746 park_channels(app, &[channel]);
747 if !app.attacking_handshake {
748 app.attacking_handshake = true;
749 app.state.push_log(format!(
750 "deauth-all: no capture running — auto-armed handshake capture on {essid}"
751 ));
752 let aps = sibling_targets(app, &essid);
753 let Some(svc) = app.service.as_ref() else {
754 app.attacking_handshake = false;
755 app.state
756 .push_log("deauth-all: service disconnected — capture not armed");
757 cx.notify();
758 return;
759 };
760 svc.cmd(&Cmd::CaptureHs {
761 targets: aps,
762 essid,
763 });
764 }
765 let count = count64.min(u32::MAX as u64) as u32;
766 app.state.push_log(format!(
767 "deauth-all: {count} rounds → {} clients of {ap} (ch {channel})",
768 targets.len()
769 ));
770 let Some(svc) = app.service.as_ref() else {
771 app.state
772 .push_log("deauth-all: service disconnected — blast not sent");
773 cx.notify();
774 return;
775 };
776 svc.cmd(&Cmd::DeauthAll {
777 ap,
778 channel,
779 targets: targets.clone(),
780 count,
781 });
782 // Optimistic DOWN marking (see do_deauth).
783 for cl in app.state.clients.values_mut() {
784 if targets.contains(&cl.mac) {
785 cl.connected = false;
786 }
787 }
788 cx.notify();
789 return;
790 }
791
792 // ---- mock path ----
793 for target in &targets {
794 let _ = app.tx.send(Event::DeauthSent {
795 ap,
796 target: *target,
797 count: count64,
798 });
799 }
800 for cl in app.state.clients.values_mut() {
801 if targets.contains(&cl.mac) {
802 cl.connected = false;
803 }
804 }
805 cx.notify();
806 });
807}
808
809fn kv(label: &str, value: impl Into<String>) -> gpui::Div {
810 h_stack()
811 .gap_2()
812 .child(div().w(px(90.)).text_xs().child(label.to_string()))
813 .child(text(value.into()).code().small().into_any_element())
814}
815
816fn handshake_card(hs: &HandshakeCapture, crackable: bool) -> gpuikit::elements::card::Card {
817 card()
818 .title(format!("{} — handshake", hs.essid))
819 .description(format!("{} ⇄ {}", hs.ap, hs.client))
820 .body(
821 v_stack()
822 .gap_1()
823 .child(kv("key version", format!("{}", hs.key_ver)))
824 .child(kv("anonce", hex(&hs.anonce[..8])))
825 .child(h_stack().gap_2().child(if crackable {
826 badge("crackable").secondary()
827 } else {
828 badge("partial")
829 }))
830 .into_any_element(),
831 )
832}
833
834fn pmkid_card(pm: &PmkidCapture) -> gpuikit::elements::card::Card {
835 card()
836 .title(format!("{} — PMKID", pm.essid))
837 .description(format!("AP {}", pm.ap))
838 .body(
839 v_stack()
840 .gap_1()
841 .child(kv("pmkid", hex(&pm.pmkid)))
842 .child(kv("via (our mac)", pm.client.to_string()))
843 .child(h_stack().gap_2().child(badge("crackable").secondary()))
844 .into_any_element(),
845 )
846}
847
848pub fn render(
849 app: &mut AppRoot,
850 view: &Entity<AppRoot>,
851 _window: &mut Window,
852 cx: &mut Context<AppRoot>,
853) -> gpui::Div {
854 let theme = cx.theme().clone();
855
856 // Client chip for the banner: the selected client counts when it's
857 // mapped to the target AP or its association is unknown (scanner often
858 // never resolves it).
859 let banner_client: Option<MacAddr> = app.selected.and_then(|ap| {
860 app.selected_client
861 .filter(|mac| client_on_target(app, mac, ap))
862 });
863
864 // Target context card: everything Networks knows about the target,
865 // one glance, plus a computed "best next move". Falls back to the
866 // click-time snapshot when the AP has no live row (host-capture
867 // lock never re-scans) so the card can't silently go blank.
868 let target_block: gpui::AnyElement = match target_row(app) {
869 Some((ap, stale)) => {
870 let bssid = ap.bssid;
871 let (hs_n, pm_n) = material_for(app, ap);
872 let siblings = sibling_targets(app, &ap.ssid).len();
873 let akm_join = ap
874 .akms
875 .iter()
876 .map(|a| a.label())
877 .collect::<Vec<_>>()
878 .join("+");
879 let spark = app.state.rssi_hist.get(&bssid).cloned();
880 let label = app.state.labels.get(&bssid).cloned();
881 let (advice, actionable) = advisor(app, ap);
882 let client_line = banner_client.map(|c| {
883 let lbl = app
884 .state
885 .labels
886 .get(&c)
887 .map(|l| format!(" “{l}”"))
888 .unwrap_or_default();
889 text(format!("client: {c}{lbl}"))
890 .code()
891 .small()
892 .into_any_element()
893 });
894 v_stack()
895 .gap_2()
896 .p_3()
897 .rounded_md()
898 .border_1()
899 .border_color(theme.border())
900 .bg(theme.surface())
901 .child(h3(format!(
902 "target: {}{}",
903 ap.ssid,
904 label.map(|l| format!(" “{l}”")).unwrap_or_default()
905 )))
906 .child(small(format!(
907 "{bssid} · ch {} ({} GHz) · vendor {}{}",
908 ap.channel,
909 crate::ui::networks::band(ap.channel),
910 crate::ui::networks::vendor_of(&bssid),
911 if stale { " · last scan snapshot" } else { "" }
912 )))
913 .child(
914 v_stack()
915 .gap_2()
916 .child(
917 h_stack()
918 .gap_2()
919 .items_center()
920 .child(crate::ui::networks::sec_badge_label(
921 &crate::ui::networks::sec_label(ap),
922 ap.security,
923 ))
924 .children((!akm_join.is_empty()).then(|| small(akm_join)))
925 .children(
926 (siblings > 1).then(|| {
927 badge(format!("dual-band x{siblings}")).secondary()
928 }),
929 ),
930 )
931 .child(
932 h_stack()
933 .gap_3()
934 .items_center()
935 .child(crate::ui::networks::sparkline(
936 spark.as_ref(),
937 theme.accent(),
938 ))
939 .child(small(format!(
940 "{} dBm · {} beacons · seen {} ago",
941 ap.rssi_dbm,
942 ap.beacons,
943 crate::ui::networks::age(ap.last_seen_ms)
944 ))),
945 )
946 .child(small(format!(
947 "material for this AP family: {hs_n} handshake(s) · {pm_n} PMKID(s)"
948 )))
949 .children(client_line)
950 // Every risk tag, unabridged — the Networks
951 // page's FLAGS column collapses overflow into
952 // `+N`, this is where the full list is read.
953 .children({
954 let tags = crate::ui::networks::risk_tags(ap, &app.state.rogue_ssids);
955 (!tags.is_empty()).then(|| {
956 div().text_xs().text_color(theme.warning()).child(format!(
957 "risk: {}",
958 tags.iter().map(|t| t.label).collect::<Vec<_>>().join(", ")
959 ))
960 })
961 })
962 .child(
963 div()
964 .text_xs()
965 .text_color(if actionable {
966 theme.accent()
967 } else {
968 theme.warning()
969 })
970 .child(advice),
971 ),
972 )
973 .into_any_element()
974 }
975 None => h_stack()
976 .gap_3()
977 .items_center()
978 .child(h3("target: none selected"))
979 .child(small("pick an AP on the Networks page"))
980 .into_any_element(),
981 };
982
983 let no_target = app.selected.is_none();
984 // Real mode without a running capture has no radio: block the buttons
985 // (a matching hint sits next to them).
986 let not_running = !app.is_mock && !app.state.iface_running;
987 let blocked = no_target || not_running;
988 // SAE-only: no offline attack applies (see sae_only).
989 let sae = sae_only(app);
990 let hs_running = app.attacking_handshake;
991 let pm_running = app.attacking_pmkid;
992
993 // Bulk-deauth candidates: strictly-mapped connected clients of the
994 // selected AP. Click-time count for the button label.
995 let deauth_targets: usize = app
996 .selected
997 .map(|ap| connected_clients(app, ap).len())
998 .unwrap_or(0);
999 app.deauth_all_targets = deauth_targets;
1000
1001 let actions = h_stack()
1002 .gap_3()
1003 .items_center()
1004 .child(
1005 button("btn-handshake", "Capture Handshake")
1006 .disabled(blocked || hs_running || sae)
1007 .on_click({
1008 let view = view.clone();
1009 move |_, window, cx| capture_handshake(&view, window, cx)
1010 }),
1011 )
1012 .child(
1013 button("btn-pmkid", "PMKID Attack")
1014 .disabled(blocked || pm_running || sae)
1015 .on_click({
1016 let view = view.clone();
1017 move |_, window, cx| pmkid_attack(&view, window, cx)
1018 }),
1019 )
1020 .child(
1021 button(
1022 "btn-deauth",
1023 if banner_client.is_some() {
1024 "Deauth client"
1025 } else {
1026 "Deauth all"
1027 },
1028 )
1029 .destructive()
1030 .disabled(blocked || sae)
1031 .on_click({
1032 let view = view.clone();
1033 move |_, window, cx| deauth(&view, window, cx)
1034 }),
1035 )
1036 .children((deauth_targets >= 2).then(|| {
1037 button(
1038 "btn-deauth-all",
1039 format!("Deauth all clients ({deauth_targets})"),
1040 )
1041 .destructive()
1042 .disabled(blocked || sae)
1043 .on_click({
1044 let view = view.clone();
1045 move |_, _window, cx| deauth_all(&view, cx)
1046 })
1047 }))
1048 .child(
1049 div()
1050 .w(px(90.))
1051 .child(text_field(&app.deauth_input, cx).placeholder("count")),
1052 )
1053 .when(hs_running || pm_running, |el| {
1054 el.child(loading_indicator().small())
1055 .child(small("working…"))
1056 })
1057 .when(not_running, |el| {
1058 el.child(small("start capture first to enable attacks"))
1059 });
1060
1061 // In-flight 4-way attempts shown with their message bitmask.
1062 let progress_cards: Vec<gpui::AnyElement> = app
1063 .hs_progress
1064 .iter()
1065 .map(|((ap, client), have)| {
1066 card()
1067 .title(format!("collecting 4-way… {}/4", have.count_ones()))
1068 .description(format!("{ap} ⇄ {client}"))
1069 .body(
1070 h_stack()
1071 .gap_2()
1072 .child(loading_indicator().small())
1073 .into_any_element(),
1074 )
1075 .into_any_element()
1076 })
1077 .collect();
1078
1079 // Stations of the target: deauth a client directly (forces its
1080 // re-auth → its 4-way handshake) without touching anything else.
1081 let stations: Vec<&ClientInfo> = app
1082 .selected
1083 .map(|sel| {
1084 app.state
1085 .clients
1086 .values()
1087 .filter(|c| client_on_target(app, &c.mac, sel) && !c.mac.is_broadcast())
1088 .collect()
1089 })
1090 .unwrap_or_default();
1091
1092 let stations_block = app.selected.map(|_sel| {
1093 let rows: Vec<gpui::AnyElement> = stations
1094 .iter()
1095 .map(|cl| {
1096 let mac = cl.mac;
1097 let ap_of = cl.ap;
1098 let view = view.clone();
1099 // MAC-randomization pairing chip: live row's own fields,
1100 // overlaid by the pairing record (wire fields can lag).
1101 let ident = app
1102 .state
1103 .idents
1104 .get(&mac)
1105 .copied()
1106 .or(cl.ident_group.zip(cl.ident_conf));
1107 h_stack()
1108 .w_full()
1109 .gap_3()
1110 .items_center()
1111 .px_2()
1112 .py_1()
1113 .child(
1114 v_stack()
1115 .w(px(170.))
1116 .child(text(mac.to_string()).code().small().into_any_element())
1117 .child(
1118 div()
1119 .text_xs()
1120 .text_color(theme.fg_muted())
1121 .child(crate::ui::networks::vendor_of(&mac)),
1122 ),
1123 )
1124 .children(app.state.labels.get(&mac).map(|l| small(format!("“{l}”"))))
1125 .children(ident.map(|(gid, conf)| {
1126 let n = app.state.ident_groups.get(&gid).map_or(1, |ms| ms.len());
1127 let mut el = div()
1128 .w(px(90.))
1129 .text_xs()
1130 .child(format!("#{gid}{} ({n})", conf.label()));
1131 if n > 1 {
1132 el = el.text_color(theme.accent());
1133 } else {
1134 el = el.text_color(theme.fg_muted());
1135 }
1136 el
1137 }))
1138 .child(
1139 div()
1140 .w(px(70.))
1141 .text_xs()
1142 .child(format!("{} dBm", cl.rssi_dbm)),
1143 )
1144 .child(
1145 div()
1146 .w(px(60.))
1147 .text_xs()
1148 .child(format!("{} fr", cl.frames)),
1149 )
1150 .child(
1151 div()
1152 .w(px(50.))
1153 .text_xs()
1154 .child(crate::ui::networks::age(cl.last_seen_ms)),
1155 )
1156 .children(
1157 (ap_of.is_none())
1158 .then(|| small("AP unmapped — treating as target's station")),
1159 )
1160 .child(div().flex_1())
1161 .child(
1162 button(
1163 gpui::SharedString::from(format!("deauth-sta-{mac}")),
1164 "Deauth client",
1165 )
1166 .destructive()
1167 .disabled(!app.is_mock && !app.state.iface_running)
1168 .on_click(move |_, _window, cx| deauth_station(&view, mac, cx)),
1169 )
1170 .into_any_element()
1171 })
1172 .collect();
1173
1174 let body = if rows.is_empty() {
1175 div()
1176 .child(small(
1177 "no stations seen on this AP yet — click any client row on the Networks page \
1178 to target it here anyway",
1179 ))
1180 .into_any_element()
1181 } else {
1182 v_stack().gap_1().children(rows).into_any_element()
1183 };
1184
1185 v_stack()
1186 .gap_2()
1187 .child(
1188 h_stack()
1189 .items_center()
1190 .gap_3()
1191 .child(h3("Stations"))
1192 .child(small(format!(
1193 "{} — deauth one to force its handshake while capture runs",
1194 stations.len()
1195 ))),
1196 )
1197 .child(body)
1198 .into_any_element()
1199 });
1200
1201 // Recent attack-relevant activity, so every button press leaves a
1202 // visible trace on THIS page (the full history lives on the Log page).
1203 const ACTIVITY_LINES: usize = 8;
1204 let activity: Vec<String> = app
1205 .state
1206 .log
1207 .iter()
1208 .filter(|line| {
1209 [
1210 "deauth",
1211 "handshake",
1212 "pmkid",
1213 "4-way",
1214 "scanner parked",
1215 "ERROR",
1216 "PASSWORD",
1217 "target selected",
1218 "client selected",
1219 ]
1220 .iter()
1221 .any(|p| line.starts_with(p))
1222 })
1223 .rev()
1224 .take(ACTIVITY_LINES)
1225 .cloned()
1226 .collect::<Vec<_>>()
1227 .into_iter()
1228 .rev()
1229 .collect();
1230
1231 let mut page = v_stack()
1232 .size_full()
1233 .gap_3()
1234 .p_4()
1235 .child(target_block)
1236 .when(sae, |el| {
1237 el.child(div().text_xs().text_color(theme.warning()).child(
1238 "SAE-only AP — no offline-crackable handshake or PMKID \
1239 (WPA3 transition APs with PSK AKM are fine)",
1240 ))
1241 })
1242 .child(actions)
1243 .children(progress_cards)
1244 .children(stations_block)
1245 .child(gpuikit::elements::separator::separator())
1246 .child(
1247 h_stack()
1248 .items_center()
1249 .gap_3()
1250 .child(h3("Captures"))
1251 .child(small(format!(
1252 "{} handshakes · {} PMKIDs",
1253 app.state.handshakes.len(),
1254 app.state.pmkids.len()
1255 )))
1256 .child(div().flex_1())
1257 .child(button("btn-export-pcap", "Export .pcap").on_click({
1258 let view = view.clone();
1259 move |_, window, cx| export_pcap(&view, window, cx)
1260 }))
1261 .child(button("btn-export", "Export .hc22000").on_click({
1262 let view = view.clone();
1263 move |_, window, cx| export_hc22000(&view, window, cx)
1264 })),
1265 );
1266
1267 let cards: Vec<gpui::AnyElement> = app
1268 .state
1269 .handshakes
1270 .iter()
1271 .map(|hs| handshake_card(hs, true).into_any_element())
1272 .chain(
1273 app.state
1274 .pmkids
1275 .iter()
1276 .map(|pm| pmkid_card(pm).into_any_element()),
1277 )
1278 .collect();
1279 if cards.is_empty() {
1280 page = page.child(small("nothing captured yet — run an attack"));
1281 } else {
1282 page = page.child(v_stack().gap_2().children(cards));
1283 }
1284
1285 page = page
1286 .child(gpuikit::elements::separator::separator())
1287 .child(h3("Activity"))
1288 .child(if activity.is_empty() {
1289 small("nothing yet — attack output appears here (full history on the Log page)")
1290 .into_any_element()
1291 } else {
1292 v_stack()
1293 .gap_1()
1294 .p_2()
1295 .rounded_md()
1296 .bg(theme.surface())
1297 .children(activity.iter().map(|line| {
1298 div()
1299 .text_xs()
1300 .text_color(theme.fg_muted())
1301 .child(line.clone())
1302 .into_any_element()
1303 }))
1304 .into_any_element()
1305 });
1306
1307 page.text_color(theme.fg())
1308}
1309
1310#[cfg(test)]
1311mod tests {
1312 use super::parse_deauth_count;
1313
1314 #[test]
1315 fn deauth_count_valid_numbers_pass_through() {
1316 assert_eq!(parse_deauth_count("16"), Ok(16));
1317 assert_eq!(parse_deauth_count("1"), Ok(1));
1318 // Overlong values parse fine; callers clamp to u32::MAX.
1319 assert_eq!(parse_deauth_count("42949672960"), Ok(42949672960));
1320 }
1321
1322 #[test]
1323 fn deauth_count_garbage_is_rejected_not_defaulted() {
1324 // Regression: unparseable input used to fall through
1325 // `.parse().unwrap_or(64)` and fire 64 rounds at a live target
1326 // with no validation error.
1327 assert!(parse_deauth_count("abc").is_err());
1328 assert!(parse_deauth_count("").is_err());
1329 assert!(parse_deauth_count("6.4").is_err());
1330 assert!(parse_deauth_count("-4").is_err());
1331 assert!(parse_deauth_count("abc").unwrap_err().contains("'abc'"));
1332 }
1333
1334 #[test]
1335 fn deauth_count_zero_is_rejected_as_noop() {
1336 // 0 rounds is a silent no-op on a destructive button — reject
1337 // with a message instead of "sending" nothing.
1338 let err = parse_deauth_count("0").unwrap_err();
1339 assert!(err.contains("at least 1"));
1340 }
1341}