Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion daemon/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ apidocs = ["dep:utoipa", "wifi-station/utoipa"]

[dependencies]
rayhunter = { path = "../lib" }
wifi-station = "0.10.1"
wifi-station = { git = "https://github.com/jacklund/wifi-station", branch = "add-bssid" }
toml = "0.8.8"
serde = { version = "1.0.193", features = ["derive"] }
serde_repr = "0.1"
Expand Down
51 changes: 48 additions & 3 deletions daemon/src/analysis.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::sync::Arc;
use std::time::Duration;
use std::{cmp, future, pin};

use axum::Json;
Expand All @@ -7,18 +8,22 @@ use axum::{
http::StatusCode,
};
use futures::TryStreamExt;
use log::{error, info};
use log::{debug, error, info};
use rayhunter::analysis::analyzer::{AnalyzerConfig, EventType, Harness};
use rayhunter::diag::{DataType, MessagesContainer};
use rayhunter::qmdl::QmdlReader;
use serde::Serialize;
use tokio::fs::File;
use tokio::io::{AsyncWriteExt, BufWriter};
use tokio::sync::mpsc::Receiver;
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::sync::{RwLock, RwLockWriteGuard};
use tokio_util::task::TaskTracker;
use wifi_station::WifiNetwork;

use crate::qmdl_store::{FileKind, RecordingStore};
use crate::display;
use crate::notifications::{Notification, NotificationType};
use crate::qmdl_store::FileKind;
use crate::qmdl_store::RecordingStore;
use crate::server::ServerState;

pub struct AnalysisWriter {
Expand Down Expand Up @@ -108,6 +113,7 @@ impl AnalysisStatus {
pub enum AnalysisCtrlMessage {
NewFilesQueued,
RecordingFinished(String),
WifiNetworksDetected(Vec<WifiNetwork>),
Exit,
}

Expand Down Expand Up @@ -195,6 +201,8 @@ pub fn run_analysis_thread(
qmdl_store_lock: Arc<RwLock<RecordingStore>>,
analysis_status_lock: Arc<RwLock<AnalysisStatus>>,
analyzer_config: AnalyzerConfig,
ui_update_sender: Sender<display::DisplayState>,
notification_channel: Sender<Notification>,
) {
task_tracker.spawn(async move {
loop {
Expand All @@ -215,6 +223,43 @@ pub fn run_analysis_thread(
let mut status = analysis_status_lock.write().await;
status.finished.push(name);
}
Some(AnalysisCtrlMessage::WifiNetworksDetected(networks)) => {
debug!(
"Networks detected, configured OUIs: {:?}",
analyzer_config.wifi_ouis.join(",")
);
if !analyzer_config.wifi_ouis.is_empty() {
let mut harness = Harness::new_with_config(&analyzer_config);
let mut events = harness
.analyze_wifi_ouis(networks.iter().map(|n| n.bssid.clone()).collect());
debug!("Called analyze_wifi_ouis, got events: {:?}", events);
if !events.is_empty() {
events.sort_by_key(|a| a.event_type);
if let Some(max_event) = events.pop()
&& max_event.event_type > EventType::Informational
{
info!("a heuristic triggered on this run!");
notification_channel
.send(Notification::new(
NotificationType::Warning,
format!(
"Rayhunter has detected a {:?} severity event",
max_event.event_type,
),
Some(Duration::from_secs(60 * 5)),
))
.await
.expect("Failed to send to notification channel");
ui_update_sender
.send(display::DisplayState::WarningDetected {
event_type: max_event.event_type,
})
.await
.expect("couldn't send ui update message: {}");
}
}
}
}
Some(AnalysisCtrlMessage::Exit) | None => return,
}
}
Expand Down
3 changes: 3 additions & 0 deletions daemon/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ pub struct Config {
pub dns_servers: Option<Vec<String>>,
/// WebDAV upload configuration. The upload worker runs whenever `webdav.url` is non-empty.
pub webdav: WebdavConfig,
/// Optional WiFi OUIs for analysis
pub wifi_ouis: Option<Vec<String>>,
}

/// Configuration for uploading finished QMDL recordings to a WebDAV server.
Expand Down Expand Up @@ -148,6 +150,7 @@ impl Default for Config {
wifi_enabled: false,
dns_servers: None,
webdav: WebdavConfig::default(),
wifi_ouis: None,
}
}
}
Expand Down
1 change: 1 addition & 0 deletions daemon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod key_input;
pub mod notifications;
pub mod pcap;
pub mod qmdl_store;
pub mod scan;
pub mod server;
pub mod stats;
pub mod update;
Expand Down
14 changes: 11 additions & 3 deletions daemon/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod key_input;
mod notifications;
mod pcap;
mod qmdl_store;
mod scan;
mod server;
mod stats;
mod update;
Expand All @@ -26,6 +27,7 @@ use crate::gps::{get_gps, post_gps};
use crate::notifications::{NotificationService, run_notification_worker};
use crate::pcap::get_pcap;
use crate::qmdl_store::RecordingStore;
use crate::scan::run_wifi_scanner;
use crate::server::{
ServerState, debug_set_display_state, get_config, get_qmdl, get_time, get_wifi_status, get_zip,
scan_wifi, serve_static, set_config, set_time_offset, test_notification,
Expand Down Expand Up @@ -281,6 +283,8 @@ async fn run_with_config(
qmdl_store_lock.clone(),
analysis_status_lock.clone(),
config.analyzers.clone(),
ui_update_tx.clone(),
notification_service.new_handler(),
);

run_shutdown_thread(
Expand Down Expand Up @@ -343,19 +347,23 @@ async fn run_with_config(

let state = Arc::new(ServerState {
config_path: args.config_path.clone(),
config,
config: config.clone(),
qmdl_store_lock: qmdl_store_lock.clone(),
diag_device_ctrl_sender: diag_tx,
analysis_status_lock,
analysis_sender: analysis_tx,
daemon_restart_token: restart_token.clone(),
ui_update_sender: Some(ui_update_tx),
ui_update_sender: Some(ui_update_tx.clone()),
wifi_status,
wifi_scan_lock: tokio::sync::Mutex::new(()),
gps_state: Arc::new(tokio::sync::RwLock::new(initial_gps)),
update_status_lock: update_status_lock.clone(),
});
run_server(&task_tracker, state, shutdown_token.clone()).await;
run_server(&task_tracker, state.clone(), shutdown_token.clone()).await;

if config.analyzers.wifi_oui_analyzer {
run_wifi_scanner(&task_tracker, state, shutdown_token.clone()).await;
}

task_tracker.close();
task_tracker.wait().await;
Expand Down
44 changes: 44 additions & 0 deletions daemon/src/scan.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use log::{debug, info, warn};
use std::sync::Arc;
use std::time::Duration;
use tokio::{select, task::JoinHandle, time};
use tokio_util::{sync::CancellationToken, task::TaskTracker};
use wifi_station::{STA_IFACE, scan_wifi_networks};

use crate::{analysis::AnalysisCtrlMessage, server::ServerState};

pub async fn run_wifi_scanner(
task_tracker: &TaskTracker,
state: Arc<ServerState>,
shutdown_token: CancellationToken,
) -> JoinHandle<()> {
info!("starting wifi scanner");

task_tracker.spawn(async move {
loop {
select! {
_ = shutdown_token.cancelled() => break,
_ = time::sleep(Duration::from_secs(15)) => {
if state.wifi_scan_lock.try_lock().is_err() {
warn!("WiFi scan already in progress");
continue;
}
debug!("Calling scan_wifi_networks()");
match scan_wifi_networks(STA_IFACE).await {
Ok(networks) => {
debug!("Found {} networks", networks.len());
if let Err(e) = state.analysis_sender.send(
AnalysisCtrlMessage::WifiNetworksDetected(networks)
).await {
warn!("couldn't send analysis message: {e}");
}
}
Err(e) => {
warn!("Error scanning wifi networks: {e}");
}
}
}
}
}
})
}
45 changes: 45 additions & 0 deletions daemon/web/src/lib/components/ConfigForm.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@
let scanning = $state(false);
let scanResults = $state<WifiNetwork[]>([]);
let dnsServersInput = $state('');
let wifiOUIsInput = $state('');

async function load_config() {
try {
loading = true;
config = await get_config();
dnsServersInput = config.dns_servers ? config.dns_servers.join(', ') : '';
wifiOUIsInput = config.analyzers.wifi_ouis ? config.analyzers.wifi_ouis.join(', ') : '';
message = '';
messageType = null;
poll_wifi_status();
Expand All @@ -58,6 +60,15 @@
.filter((s) => s.length > 0)
: null;

const trimmed_ouis = wifiOUIsInput.trim();
config.analyzers.wifi_ouis =
trimmed_ouis.length > 0
? trimmed_ouis
.split(',')
.map((s) => s.trim())
.filter((s) => s.length > 0)
: null;

try {
saving = true;
await set_config(config);
Expand Down Expand Up @@ -764,6 +775,40 @@
Diagnostic Analyzer
</label>
</div>

<div class="flex items-center">
<input
id="wifi_oui_analyzer"
type="checkbox"
bind:checked={config.analyzers.wifi_oui_analyzer}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label for="wifi_oui_analyzer" class="ml-2 block text-sm text-gray-700">
WiFi OUI Analyzer
</label>
</div>

{#if config.analyzers.wifi_oui_analyzer}
<div>
<label
for="wifi_ouis"
class="block text-sm font-medium text-gray-700 mb-1"
>
WiFi OUIs
</label>
<input
id="wifi_ouis"
type="text"
bind:value={wifiOUIsInput}
placeholder=""
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
/>
<p class="text-xs text-gray-500 mt-1">
Comma-separated triplets of hex octets, of the form "AB:CD:EF".
Used when WiFi OUI Analyzer is active.
</p>
</div>
{/if}
</div>
</div>

Expand Down
2 changes: 2 additions & 0 deletions daemon/web/src/lib/utils.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export interface AnalyzerConfig {
incomplete_sib: boolean;
test_analyzer: boolean;
diagnostic_analyzer: boolean;
wifi_oui_analyzer: boolean;
wifi_ouis: string[] | null;
}

export enum enabled_notifications {
Expand Down
1 change: 1 addition & 0 deletions dist/config.toml.in
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,4 @@ nas_null_cipher = true
incomplete_sib = true
test_analyzer = false
diagnostic_analyzer = true
wifi_oui_analyzer = true
30 changes: 29 additions & 1 deletion lib/src/analysis/analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use super::{
imsi_requested::ImsiRequestedAnalyzer, incomplete_sib::IncompleteSibAnalyzer,
information_element::InformationElement, nas_null_cipher::NasNullCipherAnalyzer,
null_cipher::NullCipherAnalyzer, priority_2g_downgrade::LteSib6And7DowngradeAnalyzer,
test_analyzer::TestAnalyzer,
test_analyzer::TestAnalyzer, wifi_oui_analyzer::WifiOUIAnalyzer,
};

/// A list of booleans which stores information about which analyzers are enabled
Expand All @@ -30,6 +30,8 @@ pub struct AnalyzerConfig {
pub incomplete_sib: bool,
pub test_analyzer: bool,
pub imsi_requested: bool,
pub wifi_oui_analyzer: bool,
pub wifi_ouis: Vec<String>,
}

impl Default for AnalyzerConfig {
Expand All @@ -43,6 +45,8 @@ impl Default for AnalyzerConfig {
nas_null_cipher: true,
incomplete_sib: true,
test_analyzer: false,
wifi_oui_analyzer: true,
wifi_ouis: Vec::new(),
}
}
}
Expand Down Expand Up @@ -365,13 +369,24 @@ impl Harness {
harness.add_analyzer(Box::new(DiagnosticAnalyzer {}));
}

if analyzer_config.wifi_oui_analyzer {
harness.add_analyzer(Box::new(WifiOUIAnalyzer::new(&analyzer_config.wifi_ouis)));
}

harness
}

pub fn add_analyzer(&mut self, analyzer: Box<dyn Analyzer + Send>) {
self.analyzers.push(analyzer);
}

pub fn analyze_wifi_ouis(&mut self, bssids: Vec<String>) -> Vec<Event> {
self.analyze_information_element(&InformationElement::WifiBSSIDList(bssids))
.iter()
.flat_map(|e| e.clone())
.collect::<Vec<Event>>()
}

pub fn analyze_pcap_packet(&mut self, packet: EnhancedPacketBlock) -> AnalysisRow {
self.packet_num += 1;

Expand Down Expand Up @@ -548,4 +563,17 @@ mod tests {
);
assert!(row.events[2].is_none());
}

#[test]
fn test_analyze_wifi_ouis() {
let mut analyzer_config = AnalyzerConfig::default();
analyzer_config.wifi_oui_analyzer = true;
analyzer_config.wifi_ouis = vec!["AA:BB:CC".to_string()];
let mut harness = Harness::new_with_config(&analyzer_config);
let events = harness.analyze_wifi_ouis(vec!["00:11:22:33:44:55".to_string()]);
assert!(events.is_empty());
let events = harness.analyze_wifi_ouis(vec!["AA:BB:CC:33:44:55".to_string()]);
assert_eq!(1, events.len());
assert_eq!(EventType::High, events[0].event_type);
}
}
1 change: 1 addition & 0 deletions lib/src/analysis/information_element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub enum InformationElement {
// so we box it to prevent the size of the enum (any variant) from blowing up.
LTE(Box<LteInformationElement>),
FiveG,
WifiBSSIDList(Vec<String>),
}

#[derive(Debug)]
Expand Down
Loading
Loading