r-lancli 0.11.0

A command-line interface for performing network scanning operations on local area networks (LANs)
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
//! CLI for LAN Network ARP and SYN scanning
//!
//! This is the rust version of [go-lanscan cli](https://github.com/robgonnella/go-lanscan)
//!
//! # Examples
//!
//! ```bash
//! # help menu
//! sudo r-lancli --help
//!
//! # scan network
//! sudo r-lancli
//! ```
use clap::Parser;
use color_eyre::eyre::{Result, eyre};
use core::time;
use itertools::Itertools;
use r_lanlib::{
    error::Result as LibResult,
    network::{self, NetworkInterface, get_default_gateway},
    oui,
    scanners::{
        Device, IDLE_TIMEOUT, ScanMessage, Scanner, arp_scanner::ARPScanner,
        syn_scanner::SYNScanner,
    },
    targets::{ips::IPTargets, ports::PortTargets},
};
use std::{
    collections::{HashMap, HashSet},
    net::Ipv4Addr,
    sync::{
        Arc,
        mpsc::{self, Receiver},
    },
    time::Duration,
};

// 30 days
const OUI_MAX_AGE: Duration = Duration::from_secs(60 * 60 * 24 * 30);

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
/// CLI for LAN Network ARP and SYN scanning
struct Args {
    /// Comma separated list of IPs, IP ranges, and CIDR blocks to scan
    #[arg(short, long, use_value_delimiter = true)]
    targets: Vec<String>,

    /// Comma separated list of ports and port ranges to scan
    #[arg(short, long, default_value = "1-65535", use_value_delimiter = true)]
    ports: Vec<String>,

    /// Output final report in json instead of table text
    #[arg(long, default_value_t = false)]
    json: bool,

    /// Only print final output nothing else
    #[arg(short, long, default_value_t = false)]
    quiet: bool,

    /// Perform only an ARP scan (omits SYN scanning)
    #[arg(long, default_value_t = false)]
    arp_only: bool,

    /// Perform vendor lookups
    #[arg(long, default_value_t = false)]
    vendor: bool,

    /// Perform reverse dns lookups
    #[arg(long, default_value_t = false)]
    host_names: bool,

    /// Set idle timeout in milliseconds for all scanners
    #[arg(long, default_value_t = IDLE_TIMEOUT)]
    idle_timeout_ms: u16,

    /// Choose a specific network interface for the scan
    #[arg(short, long)]
    interface: Option<String>,

    /// Sets the port for outgoing / incoming packets
    #[arg(long, default_value_t = network::get_available_port().expect("cannot find open port"))]
    source_port: u16,

    /// Packet send throttle. Increasing throttle duration will result
    /// in more accurate scans and latency calculations at the expense
    /// of slower scans
    #[arg(long, value_parser = humantime::parse_duration, default_value = "200µs")]
    throttle: Duration,

    /// Prints debug logs including those from r-lanlib
    #[arg(long, default_value_t = false)]
    debug: bool,
}

fn initialize_logger(args: &Args) -> Result<()> {
    let filter = if args.quiet {
        simplelog::LevelFilter::Error
    } else if args.debug {
        simplelog::LevelFilter::Debug
    } else {
        simplelog::LevelFilter::Info
    };

    simplelog::TermLogger::init(
        filter,
        simplelog::Config::default(),
        simplelog::TerminalMode::Mixed,
        simplelog::ColorChoice::Auto,
    )?;

    Ok(())
}

fn print_args(args: &Args, interface: &NetworkInterface) {
    log::info!("configuration:");
    log::info!("targets:         {:?}", args.targets);
    log::info!("ports            {:?}", args.ports);
    log::info!("json:            {}", args.json);
    log::info!("arpOnly:         {}", args.arp_only);
    log::info!("vendor:          {}", args.vendor);
    log::info!("host_names:      {}", args.host_names);
    log::info!("quiet:           {}", args.quiet);
    log::info!("idle_timeout_ms: {}", args.idle_timeout_ms);
    log::info!(
        "interface:       {}",
        args.interface.as_deref().unwrap_or(&interface.name)
    );
    log::info!("cidr:            {}", interface.cidr);
    log::info!("user_ip:         {}", interface.ipv4);
    log::info!("source_port:     {}", args.source_port);
    log::info!("throttle         {:?}", args.throttle);
}

fn process_arp(
    scanner: &dyn Scanner,
    rx: Receiver<ScanMessage>,
) -> LibResult<(Vec<Device>, Receiver<ScanMessage>)> {
    let mut arp_results: HashSet<Device> = HashSet::new();

    log::info!("starting arp scan...");

    let handle = scanner.scan()?;

    loop {
        let msg = rx.recv()?;

        match msg {
            ScanMessage::Done => {
                log::debug!("scanning complete");
                break;
            }
            ScanMessage::ARPScanDevice(m) => {
                log::debug!("received scanning message: {:?}", m);
                arp_results.insert(m.to_owned());
            }
            _ => {}
        }
    }

    handle.join()??;

    let mut items: Vec<Device> = arp_results.into_iter().collect();
    items.sort_by_key(|i| i.ip);

    Ok((items, rx))
}

fn print_arp(args: &Args, devices: &Vec<Device>) -> Result<()> {
    log::info!("arp results:");

    if args.quiet && !args.arp_only {
        // only print results of SYN scanner
        return Ok(());
    }

    if args.json {
        let j: String = serde_json::to_string(&devices)?;
        println!("{}", j);
    } else {
        let mut arp_table = prettytable::Table::new();

        arp_table.add_row(prettytable::row![
            "IP", "HOSTNAME", "MAC", "VENDOR", "LATENCY",
        ]);

        for d in devices.iter() {
            let ip_field = if d.is_current_host {
                format!("{} [YOU]", d.ip)
            } else if d.is_gateway {
                format!("{} [GTWY]", d.ip)
            } else {
                d.ip.to_string()
            };
            let latency = d
                .latency_ms
                .map(|ms| format!("{}ms", ms))
                .unwrap_or_default();
            arp_table.add_row(prettytable::row![
                ip_field, d.hostname, d.mac, d.vendor, latency
            ]);
        }

        arp_table.printstd();
    }

    Ok(())
}

fn process_syn(
    scanner: &dyn Scanner,
    devices: Vec<Device>,
    rx: Receiver<ScanMessage>,
) -> LibResult<HashMap<Ipv4Addr, Device>> {
    let mut syn_results: HashMap<Ipv4Addr, Device> = HashMap::new();

    for d in devices.iter() {
        syn_results.insert(d.ip, d.clone());
    }

    log::info!("starting syn scan...");

    let handle = scanner.scan()?;

    loop {
        let msg = rx.recv()?;

        match msg {
            ScanMessage::Done => {
                log::debug!("scanning complete");
                break;
            }
            ScanMessage::SYNScanDevice(device) => {
                log::debug!("received syn scanning device: {:?}", device);
                let found_device = syn_results.get_mut(&device.ip);
                match found_device {
                    Some(d) => d.open_ports.0.extend(device.open_ports.0),
                    None => {
                        log::warn!(
                            "received syn result for unknown device: {:?}",
                            device
                        );
                    }
                }
            }
            _ => {}
        }
    }

    handle.join()??;

    Ok(syn_results)
}

fn print_syn(
    args: &Args,
    device_map: &HashMap<Ipv4Addr, Device>,
) -> Result<()> {
    log::info!("syn results:");

    let devices: Vec<_> = device_map.values().cloned().sorted().collect();

    if args.json {
        let j: String = serde_json::to_string(&devices)?;
        println!("{}", j);
    } else {
        let mut syn_table: prettytable::Table = prettytable::Table::new();

        syn_table.add_row(prettytable::row![
            "IP",
            "HOSTNAME",
            "MAC",
            "VENDOR",
            "LATENCY",
            "OPEN_PORTS",
        ]);

        for d in devices {
            let ip_field = if d.is_current_host {
                format!("{} [YOU]", d.ip)
            } else if d.is_gateway {
                format!("{} [GTWY]", d.ip)
            } else {
                d.ip.to_string()
            };

            let latency = d
                .latency_ms
                .map(|ms| format!("{}ms", ms))
                .unwrap_or_default();

            let ports: Vec<_> = d
                .open_ports
                .to_sorted_vec()
                .into_iter()
                .map(|p| p.to_string())
                .collect();
            syn_table.add_row(prettytable::row![
                ip_field,
                d.hostname,
                d.mac,
                d.vendor,
                latency,
                ports.join(", ")
            ]);
        }
        syn_table.printstd();
    }

    Ok(())
}

#[cfg(unix)]
fn is_root() -> bool {
    nix::unistd::geteuid().is_root()
}

#[cfg(windows)]
fn is_root() -> bool {
    // On Windows, check if running as Administrator
    // This is a simplified check - raw socket operations require admin privileges
    use std::process::Command;
    Command::new("net")
        .args(["session"])
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

fn main() -> Result<()> {
    color_eyre::install()?;

    let mut args = Args::parse();

    initialize_logger(&args)?;

    if !is_root() {
        return Err(eyre!("permission denied: must run with root privileges"));
    }

    let interface = match &args.interface {
        Some(name) => network::get_interface(name)?,
        None => network::get_default_interface()?,
    };

    args.interface = Some(interface.name.clone());

    if args.targets.is_empty() {
        args.targets = vec![interface.cidr.clone()]
    }

    print_args(&args, &interface);

    let (tx, rx) = mpsc::channel::<ScanMessage>();

    let wire = r_lanlib::wire::default(&interface)?;

    let interface = Arc::new(interface);

    let oui = if args.vendor {
        Some(oui::default("r-lanscan", OUI_MAX_AGE)?)
    } else {
        None
    };

    let arp = ARPScanner::builder()
        .interface(Arc::clone(&interface))
        .wire(wire.clone())
        .gateway(get_default_gateway())
        .targets(
            IPTargets::new(args.targets.clone())
                .map_err(|e| eyre!("Invalid IP targets: {}", e))?,
        )
        .source_port(args.source_port)
        .include_vendor(args.vendor)
        .include_host_names(args.host_names)
        .idle_timeout(time::Duration::from_millis(args.idle_timeout_ms.into()))
        .notifier(tx.clone())
        .throttle(args.throttle)
        .oui(oui)
        .build()?;

    let (arp_results, rx) = process_arp(&arp, rx)?;

    print_arp(&args, &arp_results)?;

    if args.arp_only {
        return Ok(());
    }

    let syn = SYNScanner::builder()
        .interface(interface)
        .wire(wire)
        .targets(arp_results.clone())
        .ports(
            PortTargets::new(args.ports.clone())
                .map_err(|e| eyre!("Invalid port targets: {}", e))?,
        )
        .source_port(args.source_port)
        .idle_timeout(time::Duration::from_millis(args.idle_timeout_ms.into()))
        .notifier(tx)
        .throttle(args.throttle)
        .build()?;

    let final_results = process_syn(&syn, arp_results, rx)?;
    print_syn(&args, &final_results)?;

    Ok(())
}

#[cfg(test)]
#[path = "./main_tests.rs"]
mod tests;