//! Channel utilization analysis, wireless anomaly detection (WIDS), and WPA3 indicators. //! //! Everything here is derived passively from the captured scan table without injecting frames. //! Both the live UI and the standalone audit report consume this model. //! use crate::radiotap::{self, Band}; use crate::scan::AccessPoint; use serde::Serialize; use std::collections::HashMap; #[derive(Debug, Clone, Serialize)] pub struct ChannelCandidate { pub channel: u32, pub freq_mhz: u16, pub band: String, pub score: f32, pub aps: usize, pub dfs: bool, } #[derive(Debug, Clone, Serialize)] pub struct BandReport { pub band: String, pub candidates: Vec, pub recommended: Option, pub used_channels: Vec, } #[derive(Debug, Clone, Serialize)] pub struct Finding { pub id: String, pub severity: String, pub title: String, pub detail: String, pub bssid: Option, pub ssid: Option, } #[derive(Debug, Clone, Serialize)] pub struct Wpa3Info { pub bssid: String, pub ssid: Option, pub mode: String, pub pmf: bool, pub pmf_required: bool, pub transition: bool, pub notes: Vec, } #[derive(Debug, Clone, Serialize, Default)] pub struct Analysis { pub bands: Vec, pub findings: Vec, pub wpa3: Vec, pub deauth_60s: u32, } const BAND_24: &str = "2.4 GHz"; const BAND_5: &str = "5 GHz"; const BAND_6: &str = "6 GHz"; fn band_label(band: Band) -> &'static str { match band { Band::B2G4 => BAND_24, Band::B5 => BAND_5, Band::B6 => BAND_6, Band::Unknown => BAND_24, } } fn ap_freq(ap: &AccessPoint) -> Option<(u16, Band)> { if let Some(freq) = ap.freq_mhz { return Some((freq, radiotap::band_for_freq(freq))); } let band = ap.band?; let channel = ap.channel?; radiotap::channel_to_freq(channel, band).map(|freq| (freq, band)) } fn ap_width(ap: &AccessPoint) -> u16 { ap.width_mhz.filter(|w| *w >= 20).unwrap_or(20) } fn candidates_for(band: Band) -> Vec { match band { Band::B2G4 => (1..=14).collect(), Band::B5 => { let mut chans: Vec = (36..=64).step_by(4).collect(); chans.extend((100..=144).step_by(4)); chans.extend((149..=177).step_by(4)); chans.extend([182, 184, 188, 192, 196]); chans } Band::B6 => (1..=233).step_by(4).collect(), Band::Unknown => Vec::new(), } } fn is_dfs(channel: u32) -> bool { (52..=64).contains(&channel) || (100..=144).contains(&channel) } fn signal_weight(dbm: Option) -> f32 { let dbm = dbm.unwrap_or(-75) as f32; (1.0 - ((-dbm - 30.0) / 70.0)).clamp(0.15, 1.0) } fn overlap_score(candidate_freq: u16, aps: &[(u16, u16, f32)]) -> (f32, usize) { let half = 10.0f32; let mut score = 0.0f32; let mut count = 0usize; for (freq, width, weight) in aps { let ap_half = *width as f32 / 2.0; let lo = (candidate_freq as f32 - half).max(*freq as f32 - ap_half); let hi = (candidate_freq as f32 + half).min(*freq as f32 + ap_half); let overlap = (hi - lo).max(0.0) / (half * 2.0); if overlap > 0.0 { score += overlap * weight; count += 1; } } (score, count) } fn band_report(band: Band, aps: &[&AccessPoint]) -> BandReport { let mut occupied: Vec<(u16, u16, f32)> = Vec::new(); let mut used = Vec::new(); for ap in aps { let Some((freq, _)) = ap_freq(ap) else { continue; }; occupied.push(( freq, ap_width(ap), signal_weight(ap.signal_dbm.or(ap.max_signal_dbm)), )); if let Some(ch) = ap.channel { used.push(ch); } } used.sort_unstable(); used.dedup(); let mut candidates: Vec = candidates_for(band) .into_iter() .filter_map(|channel| { radiotap::channel_to_freq(channel, band).map(|freq| { let (score, count) = overlap_score(freq, &occupied); ChannelCandidate { channel, freq_mhz: freq, band: band_label(band).to_string(), score: (score * 1000.0).round() / 1000.0, aps: count, dfs: is_dfs(channel), } }) }) .collect(); let preferred: Vec = match band { Band::B2G4 => vec![1, 6, 11], _ => Vec::new(), }; let recommended = if preferred.is_empty() { candidates .iter() .filter(|c| !c.dfs) .min_by(|a, b| a.score.total_cmp(&b.score)) .or_else(|| candidates.iter().min_by(|a, b| a.score.total_cmp(&b.score))) .map(|c| c.channel) } else { preferred .into_iter() .filter_map(|ch| candidates.iter().find(|c| c.channel == ch)) .min_by(|a, b| a.score.total_cmp(&b.score)) .map(|c| c.channel) }; candidates.sort_by(|a, b| { a.score .total_cmp(&b.score) .then_with(|| a.channel.cmp(&b.channel)) }); candidates.truncate(8); BandReport { band: band_label(band).to_string(), candidates, recommended, used_channels: used, } } fn finding( id: &str, severity: &str, title: impl Into, detail: impl Into, ap: Option<&AccessPoint>, ) -> Finding { Finding { id: id.into(), severity: severity.into(), title: title.into(), detail: detail.into(), bssid: ap.map(|a| a.bssid.clone()), ssid: ap.and_then(|a| a.ssid.clone()), } } fn security_rank(security: Option<&str>) -> u8 { match security { Some("Open") => 0, Some("WEP") => 1, Some("WPA") => 2, Some("WPA2-EAP") => 3, Some("WPA2") => 4, Some("WPA2/WPA3") => 5, Some("WPA3-EAP") => 6, Some("WPA3") => 7, Some("OWE") => 4, _ => 3, } } fn wpa3_info(ap: &AccessPoint) -> Option { let sec = ap.security.as_deref()?; let is_wpa3 = sec.contains("WPA3") || sec == "OWE"; if !is_wpa3 { return None; } let transition = sec == "WPA2/WPA3"; let mut notes = Vec::new(); if transition { notes.push( "Modo de transição aceita WPA2: um cliente pode ser induzido a usar o modo mais fraco." .into(), ); } if !ap.pmf { notes .push("PMF não anunciado; WPA3 pressupõe proteção de quadros de gerenciamento.".into()); } else if !ap.pmf_required && !transition { notes.push("PMF suportado, mas não obrigatório.".into()); } if ap.wps { notes.push("WPS ativo em rede WPA3 — combinação incomum e enfraquece o conjunto.".into()); } if ap.wps_locked == Some(false) { notes.push("WPS destravado: PIN pode ser testado.".into()); } Some(Wpa3Info { bssid: ap.bssid.clone(), ssid: ap.ssid.clone(), mode: sec.to_string(), pmf: ap.pmf, pmf_required: ap.pmf_required, transition, notes, }) } pub fn analyze(aps: &[AccessPoint], deauth_60s: u32, now: u64) -> Analysis { let mut findings = Vec::new(); let mut wpa3 = Vec::new(); let bands = [Band::B2G4, Band::B5, Band::B6] .into_iter() .filter_map(|band| { let filtered: Vec<&AccessPoint> = aps .iter() .filter(|ap| ap_freq(ap).is_some_and(|(_, b)| b == band)) .collect(); if filtered.is_empty() { None } else { Some(band_report(band, &filtered)) } }) .collect(); // Same SSID advertised with mixed security suites (e.g. WPA2 alongside Open) // is a classic Evil Twin indicator. let mut by_ssid: HashMap> = HashMap::new(); for ap in aps { if let Some(ssid) = ap.ssid.as_deref().filter(|s| !s.is_empty()) { by_ssid.entry(ssid.to_string()).or_default().push(ap); } } for (ssid, group) in &by_ssid { if group.len() < 2 { continue; } let mut ranks: Vec = group .iter() .map(|a| security_rank(a.security.as_deref())) .collect(); ranks.sort_unstable(); ranks.dedup(); if ranks.len() > 1 { let detail = group .iter() .map(|a| format!("{} ({})", a.bssid, a.security.as_deref().unwrap_or("—"))) .collect::>() .join(", "); findings.push(finding( "evil_twin_security", "bad", format!("SSID “{ssid}” com seguranças diferentes"), format!("O mesmo nome aparece em BSSIDs com níveis de segurança distintos: {detail}. Pode ser um evil twin ou um AP mal configurado."), None, )); } } if deauth_60s >= 40 { findings.push(finding( "deauth_flood", "bad", "Rajada de desautenticação", format!("{deauth_60s} quadros de desautenticação/desassociação no último minuto. Pode ser ataque de desautenticação ou um AP instável."), None, )); } let recent_aps = aps .iter() .filter(|a| now.saturating_sub(a.first_seen_unix) <= 60) .count(); if recent_aps >= 60 { findings.push(finding( "beacon_flood", "warn", "Muitos BSSIDs novos", format!("{recent_aps} BSSIDs apareceram no último minuto — possível beacon flood ou ambiente muito denso."), None, )); } for ap in aps { let label = ap .ssid .clone() .filter(|s| !s.is_empty()) .unwrap_or_else(|| ap.bssid.clone()); match ap.security.as_deref() { Some("Open") => findings.push(finding( "open", "bad", format!("Rede aberta: {label}"), "Sem cifra no Wi-Fi; o tráfego fica exposto a qualquer estação no alcance.", Some(ap), )), Some("WEP") => findings.push(finding( "wep", "bad", format!("WEP em {label}"), "WEP é quebrável em minutos; trate a rede como aberta.", Some(ap), )), Some("WPA") => findings.push(finding( "wpa1", "warn", format!("WPA1 (TKIP) em {label}"), "WPA1/TKIP tem fraquezas conhecidas; migre para WPA2/CCMP ou WPA3.", Some(ap), )), _ => {} } if ap.wps { findings.push(finding( "wps", if ap.wps_locked == Some(true) { "info" } else { "warn" }, format!("WPS ativo em {label}"), if ap.wps_locked == Some(true) { "O AP anuncia WPS com configuração travada." } else { "WPS sem lock explícito; PIN pode ser testado com reaver/bully." }, Some(ap), )); } if !ap.pmf && matches!( ap.security.as_deref(), Some("WPA2") | Some("WPA2-EAP") | Some("WPA2/WPA3") ) { findings.push(finding( "no_pmf", "warn", format!("Sem PMF em {label}"), "Desautenticação e desassociação não são protegidas; clientes podem ser expulsos para facilitar a captura de handshake.", Some(ap), )); } if ap.pmf_required && ap.security.as_deref().is_some_and(|s| s.contains("WPA3")) && !ap.pmf { findings.push(finding( "pmf_inconsistent", "warn", format!("PMF inconsistente em {label}"), "O AP anuncia WPA3, mas não anuncia PMF; verifique a configuração.", Some(ap), )); } if ap.wps && ap.security.as_deref().is_some_and(|s| s.contains("WPA3")) { findings.push(finding( "wpa3_wps", "warn", format!("WPA3 com WPS em {label}"), "WPS não faz parte do WPA3 e abre uma via mais fraca de associação.", Some(ap), )); } if let Some(info) = wpa3_info(ap) { wpa3.push(info); } } findings.sort_by_key(|f| match f.severity.as_str() { "bad" => 0, "warn" => 1, _ => 2, }); Analysis { bands, findings, wpa3, deauth_60s, } } #[cfg(test)] mod tests { use super::*; use crate::scan::ScanTable; use crate::testutil::{ap, beacon_frame, radiotap_wrap}; fn ingest(table: &mut ScanTable, ssid: &str, channel: u8, signal: i8, akms: &[u8]) { let frame = beacon_frame(ap(), ssid, channel, akms); table.ingest_at( &radiotap_wrap(&frame, 2407 + channel as u16 * 5, signal), 100, ); } #[test] fn recommends_16_or_11_in_24() { let mut table = ScanTable::new(); ingest(&mut table, "Casa", 6, -40, &[2]); let result = table.analysis(); let band = result .bands .iter() .find(|b| b.band == BAND_24) .expect("2.4"); assert!(matches!(band.recommended, Some(1 | 6 | 11))); } #[test] fn flags_same_ssid_with_different_security() { let mut table = ScanTable::new(); ingest(&mut table, "Loja", 6, -40, &[2]); let twin = beacon_frame([0x02, 0x11, 0x22, 0x33, 0x44, 0x55], "Loja", 11, &[]); table.ingest_at(&radiotap_wrap(&twin, 2462, -50), 100); let result = table.analysis(); assert!(result.findings.iter().any(|f| f.id == "evil_twin_security")); } #[test] fn flags_wps_and_weak_networks() { let mut table = ScanTable::new(); let frame = beacon_frame(ap(), "Antiga", 1, &[]); table.ingest_at(&radiotap_wrap(&frame, 2412, -60), 100); let result = table.analysis(); assert!(result .findings .iter() .any(|f| f.id == "wep" || f.id == "open")); } }