airgorah 0.7.3

A WiFi security auditing software mainly based on aircrack-ng tools suite
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use std::collections::HashMap;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::MutexGuard;

use super::*;
use crate::globals::*;
use crate::types::*;

use serde::Deserialize;

use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;

/// Represents the AP section of the csv file generated by airodump
#[derive(Debug, Deserialize)]
struct RawAP {
    #[serde(rename = "BSSID")]
    bssid: String,
    #[serde(rename = " First time seen")]
    first_time_seen: String,
    #[serde(rename = " Last time seen")]
    last_time_seen: String,
    #[serde(rename = " channel")]
    channel: String,
    #[serde(rename = " Speed")]
    speed: String,
    #[serde(rename = " Privacy")]
    privacy: String,
    #[serde(rename = " Cipher")]
    _cipher: String,
    #[serde(rename = " Authentication")]
    _authentication: String,
    #[serde(rename = " Power")]
    power: String,
    #[serde(rename = " # beacons")]
    _beacons: String,
    #[serde(rename = " # IV")]
    _iv: String,
    #[serde(rename = " LAN IP")]
    _lan_ip: String,
    #[serde(rename = " ID-length")]
    id_length: String,
    #[serde(rename = " ESSID")]
    essid: String,
    #[serde(rename = " Key")]
    _key: String,
}

/// Represents the Client section of the csv file generated by airodump
#[derive(Debug, Deserialize)]
struct RawClient {
    #[serde(rename = "Station MAC")]
    station_mac: String,
    #[serde(rename = " First time seen")]
    first_time_seen: String,
    #[serde(rename = " Last time seen")]
    last_time_seen: String,
    #[serde(rename = " Power")]
    power: String,
    #[serde(rename = " # packets")]
    packets: String,
    #[serde(rename = " BSSID")]
    bssid: String,
    #[serde(rename = " Probed ESSIDs")]
    probes: String,
}

#[derive(thiserror::Error, Debug)]
pub enum ScanError {
    #[error("Could not setup scan process: no band selected")]
    NoBandSelected,

    #[error("Input/Output error: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Kill error: errno code: {0}")]
    KillError(#[from] nix::errno::Errno),
}

/// Check if a scan is currently running
pub fn is_scan_process() -> bool {
    SCAN_PROC.lock().unwrap().is_some()
}

/// Check if the content of the channel filter is valid
pub fn is_valid_channel_filter(channel_filter: &str, ghz_2_4_but: bool, ghz_5_but: bool) -> bool {
    let channel_list: Vec<String> = channel_filter
        .split_terminator(',')
        .map(String::from)
        .collect();

    let mut channel_buf = vec![];

    if channel_filter.ends_with(',') {
        return false;
    }

    for channel_str in channel_list {
        let channel = match channel_str.parse::<u32>() {
            Ok(chan) => chan,
            Err(_) => return false,
        };

        if channel < 1 || (15..=35).contains(&channel) || channel > 165 {
            return false;
        }

        if (1..=14).contains(&channel) && !ghz_2_4_but {
            return false;
        }

        if (36..=165).contains(&channel) && !ghz_5_but {
            return false;
        }

        if channel_buf.contains(&channel) {
            return false;
        }

        channel_buf.push(channel);
    }

    true
}

/// Set the scan process
pub fn set_scan_process(
    iface: &str,
    ghz_2_4: bool,
    ghz_5: bool,
    channel_filter: Option<String>,
) -> Result<(), ScanError> {
    if !ghz_2_4 && !ghz_5 {
        return Err(ScanError::NoBandSelected);
    }

    stop_scan_process()?;

    let live_scan_path = get_live_scan_path();
    let mut proc_args = vec![
        iface,
        "-a",
        "--output-format",
        "csv,cap",
        "-w",
        &live_scan_path,
        "--write-interval",
        "1",
    ];

    let mut band = String::new();

    if ghz_5 {
        band += "a";
    }

    if ghz_2_4 {
        band += "bg";
    }

    proc_args.push("--band");
    proc_args.push(&band);

    let channels;

    if let Some(ref filter) = channel_filter {
        channels = filter;

        proc_args.push("--channel");
        proc_args.push(channels);
    }

    let child = Command::new("airodump-ng")
        .args(proc_args)
        .stdout(Stdio::null())
        .spawn()?;

    SCAN_PROC.lock().unwrap().replace(child);

    log::info!(
        "scan started: 2.4ghz: {}, 5ghz: {}, channel filter: {:?}",
        ghz_2_4,
        ghz_5,
        channel_filter
    );

    Ok(())
}

/// Stop the scan process
pub fn stop_scan_process() -> Result<(), ScanError> {
    if let Some(child) = SCAN_PROC.lock().unwrap().as_mut() {
        let child_pid = Pid::from_raw(child.id() as i32);

        kill(child_pid, Signal::SIGTERM)?;

        log::info!("scan stopped, sent SIGTERM to pid {}", child_pid);

        child.wait()?;
    }

    SCAN_PROC.lock().unwrap().take();

    let old_path_exists = Path::new(&(get_old_scan_path() + get_cap_ext())).exists();
    let live_path_exists = Path::new(&(get_live_scan_path() + get_cap_ext())).exists();

    std::fs::remove_file(get_live_scan_path() + get_csv_ext()).ok();

    if !live_path_exists {
        return Ok(());
    }

    if !old_path_exists {
        std::fs::rename(
            get_live_scan_path() + get_cap_ext(),
            get_old_scan_path() + get_cap_ext(),
        )
        .ok();
        return Ok(());
    }

    std::process::Command::new("mergecap")
        .args([
            "-a",
            "-F",
            "pcap",
            "-w",
            &(get_merge_scan_path() + get_cap_ext()),
            &(get_old_scan_path() + get_cap_ext()),
            &(get_live_scan_path() + get_cap_ext()),
        ])
        .status()?;

    std::fs::remove_file(get_live_scan_path() + get_cap_ext()).ok();
    std::fs::remove_file(get_old_scan_path() + get_cap_ext()).ok();
    std::fs::rename(
        get_merge_scan_path() + get_cap_ext(),
        get_old_scan_path() + get_cap_ext(),
    )
    .ok();

    Ok(())
}

/// Get the data captured from airodump
pub fn get_airodump_data() -> HashMap<String, AP> {
    let mut aps: HashMap<String, AP> = HashMap::new();

    for attacked_ap in get_attack_pool().iter() {
        aps.insert(attacked_ap.0.clone(), attacked_ap.1 .0.clone());
    }

    let mut glob_aps = get_aps();

    for ap in glob_aps.iter() {
        aps.insert(ap.0.clone(), ap.1.clone());
    }

    let full_path = get_live_scan_path() + get_csv_ext();
    let csv_file = match std::fs::read_to_string(full_path) {
        Ok(file) => file,
        Err(_) => return aps,
    };

    let file_parts: Vec<&str> = csv_file.split("\r\n\r\n").collect();
    let ap_part = if !file_parts.is_empty() {
        file_parts[0]
    } else {
        ""
    };
    let cli_part = if file_parts.len() >= 2 {
        file_parts[1]
    } else {
        ""
    };

    let mut ap_reader = csv::Reader::from_reader(ap_part.as_bytes());
    let mut cli_reader = csv::Reader::from_reader(cli_part.as_bytes());

    for result in ap_reader.deserialize::<RawAP>().flatten() {
        let channel_nb = result.channel.trim_start().parse::<i32>().unwrap_or(-1);
        let band = if channel_nb > 14 {
            "5 GHz".to_string()
        } else {
            "2.4 GHz".to_string()
        };
        let bssid = result.bssid.trim_start().to_string();
        let mut essid = result.essid.trim_start().to_string();
        let mut hidden = false;

        let old_ap_data = glob_aps.get(&bssid);

        if essid.is_empty() {
            hidden = true;
            essid = format!("[Hidden] (length: {})", result.id_length.trim_start());

            if let Some(old_ap_data) = old_ap_data {
                if !old_ap_data.essid.starts_with("[Hidden] (length:") {
                    essid = old_ap_data.essid.clone();
                }
            }
        }

        let old_data = aps.insert(
            bssid.clone(),
            AP {
                essid,
                bssid: bssid.clone(),
                band,
                channel: result.channel.trim_start().to_string(),
                speed: result.speed.trim_start().to_string(),
                power: result.power.trim_start().to_string(),
                privacy: match result.privacy.trim_start() {
                    "" => "Unknown".to_string(),
                    e => {
                        let array = e
                            .split_whitespace()
                            .map(|s| s.to_string())
                            .collect::<Vec<String>>();
                        array.first().unwrap_or(&"Unknown".to_string()).to_string()
                    }
                },
                hidden,
                handshake: {
                    match old_ap_data {
                        Some(ap) => ap.handshake,
                        None => false,
                    }
                },
                saved_handshake: match old_ap_data {
                    Some(ap) => ap.saved_handshake.clone(),
                    None => None,
                },
                first_time_seen: {
                    match old_ap_data {
                        Some(ap) => ap.first_time_seen.clone(),
                        None => result.first_time_seen.trim_start().to_string(),
                    }
                },
                last_time_seen: result.last_time_seen.trim_start().to_string(),
                clients: HashMap::new(),
            },
        );

        if let Some(ap) = old_data {
            aps.get_mut(&bssid).unwrap().clients = ap.clients;
        }
    }

    for result in cli_reader.deserialize::<RawClient>().flatten() {
        let mac = result.station_mac.trim_start().to_string();
        let client_vendor = super::find_vendor(&mac);

        match aps.get_mut(result.bssid.trim_start()) {
            Some(ap) => {
                let old_client = ap.clients.get(&mac);

                ap.clients.insert(
                    mac.clone(),
                    Client {
                        mac,
                        packets: result.packets.trim_start().to_string(),
                        power: result.power.trim_start().to_string(),
                        first_time_seen: {
                            match old_client {
                                Some(client) => client.first_time_seen.clone(),
                                None => result.first_time_seen.trim_start().to_string(),
                            }
                        },
                        last_time_seen: result.last_time_seen.trim_start().to_string(),
                        vendor: client_vendor,
                        probes: result.probes.trim_start().to_string(),
                    },
                );
            }
            None => {
                let unlinked_clients = get_unlinked_clients().clone();
                let old_client = unlinked_clients.get(&mac);

                get_unlinked_clients().insert(
                    mac.clone(),
                    Client {
                        mac,
                        packets: result.packets.trim_start().to_string(),
                        power: result.power.trim_start().to_string(),
                        first_time_seen: {
                            match old_client {
                                Some(client) => client.first_time_seen.clone(),
                                None => result.first_time_seen.trim_start().to_string(),
                            }
                        },
                        last_time_seen: result.last_time_seen.trim_start().to_string(),
                        vendor: client_vendor,
                        probes: result.probes.trim_start().to_string(),
                    },
                );
            }
        }
    }

    for (bssid, ap) in aps.iter() {
        glob_aps.insert(bssid.clone(), ap.clone());
    }

    aps
}

pub fn get_aps() -> MutexGuard<'static, HashMap<String, AP>> {
    APS.lock().unwrap()
}

pub fn get_unlinked_clients() -> MutexGuard<'static, HashMap<String, Client>> {
    UNLINKED_CLIENTS.lock().unwrap()
}

pub fn get_cap_ext() -> &'static str {
    "-01.cap"
}

pub fn get_csv_ext() -> &'static str {
    "-01.csv"
}

pub fn get_live_scan_path() -> String {
    format!("{}-{}", LIVE_SCAN_PATH, std::process::id())
}

pub fn get_old_scan_path() -> String {
    format!("{}-{}", OLD_SCAN_PATH, std::process::id())
}

pub fn get_merge_scan_path() -> String {
    format!("{}-{}", MERGE_SCAN_PATH, std::process::id())
}