netscan 0.30.0

Cross-platform network scan library
Documentation
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use crate::host::Host;
use crate::protocol::Protocol;
use crate::scan::payload::PayloadBuilder;
use rand::seq::SliceRandom;
use std::collections::HashMap;
use std::fmt;
use std::net::{IpAddr, Ipv4Addr};
use std::str::FromStr;
use std::time::Duration;

use crate::config::{DEFAULT_HOSTS_CONCURRENCY, DEFAULT_PORTS_CONCURRENCY};

use super::payload::PayloadInfo;

/* /// Scan Type
#[derive(Deserialize, Serialize, Clone, Debug)]
pub enum ScanType {
    /// Port scan type.
    PortScan(PortScanType),
    /// Host scan type.
    HostScan(HostScanType),
}
 */

/// Port Scan Type
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum PortScanType {
    /// Default fast port scan type.
    ///
    /// Send TCP packet with SYN flag to the target ports and check response.
    TcpSynScan,
    /// Attempt TCP connection and check port status.
    ///
    /// Slow but can be run without administrator privileges.
    TcpConnectScan,
}

impl PortScanType {
    pub fn from_str(scan_type: &str) -> PortScanType {
        scan_type.parse().unwrap_or(PortScanType::TcpSynScan)
    }
    pub fn to_str(&self) -> &str {
        match self {
            PortScanType::TcpSynScan => "TCP-SYN",
            PortScanType::TcpConnectScan => "TCP-CONNECT",
        }
    }
}

impl fmt::Display for PortScanType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.to_str())
    }
}

impl FromStr for PortScanType {
    type Err = ();

    fn from_str(scan_type: &str) -> Result<Self, Self::Err> {
        match scan_type {
            "SYN" | "TCP-SYN" | "TCP_SYN" => Ok(PortScanType::TcpSynScan),
            "CONNECT" | "TCP-CONNECT" | "TCP_CONNECT" => Ok(PortScanType::TcpConnectScan),
            _ => Err(()),
        }
    }
}

#[derive(Clone, Debug)]
pub struct PortScanSetting {
    pub if_index: u32,
    pub targets: Vec<Host>,
    pub protocol: Protocol,
    pub scan_type: PortScanType,
    pub concurrency: usize,
    pub timeout: Duration,
    pub wait_time: Duration,
    pub send_rate: Duration,
    pub randomize: bool,
    pub minimize_packet: bool,
    pub dns_map: HashMap<IpAddr, String>,
    pub async_scan: bool,
}

impl Default for PortScanSetting {
    fn default() -> Self {
        Self {
            if_index: 0,
            targets: Vec::new(),
            protocol: Protocol::TCP,
            scan_type: PortScanType::TcpSynScan,
            concurrency: DEFAULT_PORTS_CONCURRENCY,
            timeout: Duration::from_secs(30),
            wait_time: Duration::from_secs(200),
            send_rate: Duration::from_millis(0),
            randomize: true,
            minimize_packet: false,
            dns_map: HashMap::new(),
            async_scan: false,
        }
    }
}

impl PortScanSetting {
    pub fn with_if_index(self, if_index: u32) -> Self {
        self.set_if_index(if_index)
    }
    pub fn with_target(self, target: Host) -> Self {
        self.add_target(target)
    }
    pub fn with_targets(self, targets: Vec<Host>) -> Self {
        self.set_targets(targets)
    }
    pub fn with_protocol(self, protocol: Protocol) -> Self {
        self.set_protocol(protocol)
    }
    pub fn with_scan_type(self, scan_type: PortScanType) -> Self {
        self.set_scan_type(scan_type)
    }
    pub fn with_concurrency(self, concurrency: usize) -> Self {
        self.set_concurrency(concurrency)
    }
    pub fn with_timeout(self, timeout: Duration) -> Self {
        self.set_timeout(timeout)
    }
    pub fn with_wait_time(self, wait_time: Duration) -> Self {
        self.set_wait_time(wait_time)
    }
    pub fn with_send_rate(self, send_rate: Duration) -> Self {
        self.set_send_rate(send_rate)
    }
    pub fn with_randomize(self, randomize: bool) -> Self {
        self.set_randomize(randomize)
    }
    pub fn with_minimize_packet(self, minimize_packet: bool) -> Self {
        self.set_minimize_packet(minimize_packet)
    }
    pub fn with_dns_map(self, dns_map: HashMap<IpAddr, String>) -> Self {
        self.set_dns_map(dns_map)
    }
    pub fn with_async_scan(self, async_scan: bool) -> Self {
        self.set_async_scan(async_scan)
    }

    // support builder pattern for all fields
    pub fn set_if_index(mut self, if_index: u32) -> Self {
        self.if_index = if_index;
        self
    }
    pub fn add_target(mut self, target: Host) -> Self {
        self.targets.push(target);
        self
    }
    pub fn set_targets(mut self, targets: Vec<Host>) -> Self {
        self.targets = targets;
        self
    }
    pub fn set_protocol(mut self, protocol: Protocol) -> Self {
        self.protocol = protocol;
        self
    }
    pub fn set_scan_type(mut self, scan_type: PortScanType) -> Self {
        self.scan_type = scan_type;
        self
    }
    pub fn set_concurrency(mut self, concurrency: usize) -> Self {
        self.concurrency = concurrency;
        self
    }
    pub fn set_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }
    pub fn set_wait_time(mut self, wait_time: Duration) -> Self {
        self.wait_time = wait_time;
        self
    }
    pub fn set_send_rate(mut self, send_rate: Duration) -> Self {
        self.send_rate = send_rate;
        self
    }
    pub fn set_randomize(mut self, randomize: bool) -> Self {
        self.randomize = randomize;
        self
    }
    pub fn set_minimize_packet(mut self, minimize_packet: bool) -> Self {
        self.minimize_packet = minimize_packet;
        self
    }
    pub fn set_dns_map(mut self, dns_map: HashMap<IpAddr, String>) -> Self {
        self.dns_map = dns_map;
        self
    }
    pub fn set_async_scan(mut self, async_scan: bool) -> Self {
        self.async_scan = async_scan;
        self
    }
    pub fn randomize_hosts(&mut self) {
        let mut rng = rand::thread_rng();
        self.targets.shuffle(&mut rng);
    }
    pub fn randomize_ports(&mut self) {
        for target in &mut self.targets {
            target.ports.shuffle(&mut rand::thread_rng());
        }
    }
}

/// Host Scan Type
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum HostScanType {
    /// Default host scan type.
    ///
    /// Send ICMP echo request and check response.
    IcmpPingScan,
    /// Perform host scan for a specific service.
    ///
    /// Send TCP packets with SYN flag to a specific port and check response.
    TcpPingScan,
    /// Send UDP packets to a probably closed port and check response.
    /// This expects ICMP port unreachable message.
    UdpPingScan,
}

impl HostScanType {
    pub fn from_str(scan_type: &str) -> HostScanType {
        scan_type.parse().unwrap_or(HostScanType::IcmpPingScan)
    }
    pub fn to_str(&self) -> &str {
        match self {
            HostScanType::IcmpPingScan => "ICMP-PING",
            HostScanType::TcpPingScan => "TCP-PING",
            HostScanType::UdpPingScan => "UDP-PING",
        }
    }
}

impl fmt::Display for HostScanType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.to_str())
    }
}

impl FromStr for HostScanType {
    type Err = ();

    fn from_str(scan_type: &str) -> Result<Self, Self::Err> {
        match scan_type {
            "ICMP" | "ICMP-PING" | "ICMP_PING" => Ok(HostScanType::IcmpPingScan),
            "TCP" | "TCP-PING" | "TCP_PING" => Ok(HostScanType::TcpPingScan),
            "UDP" | "UDP-PING" | "UDP_PING" => Ok(HostScanType::UdpPingScan),
            _ => Err(()),
        }
    }
}

#[derive(Clone, Debug)]
pub struct HostScanSetting {
    pub if_index: u32,
    pub targets: Vec<Host>,
    pub protocol: Protocol,
    pub scan_type: HostScanType,
    pub concurrency: usize,
    pub timeout: Duration,
    pub wait_time: Duration,
    pub send_rate: Duration,
    pub randomize: bool,
    pub minimize_packet: bool,
    pub dns_map: HashMap<IpAddr, String>,
    pub async_scan: bool,
}

impl Default for HostScanSetting {
    fn default() -> Self {
        Self {
            if_index: 0,
            targets: Vec::new(),
            protocol: Protocol::ICMP,
            scan_type: HostScanType::IcmpPingScan,
            concurrency: DEFAULT_HOSTS_CONCURRENCY,
            timeout: Duration::from_secs(30),
            wait_time: Duration::from_secs(200),
            send_rate: Duration::from_millis(0),
            randomize: true,
            minimize_packet: false,
            dns_map: HashMap::new(),
            async_scan: false,
        }
    }
}

impl HostScanSetting {
    pub fn with_if_index(self, if_index: u32) -> Self {
        self.set_if_index(if_index)
    }
    pub fn with_targets(self, targets: Vec<Host>) -> Self {
        self.set_targets(targets)
    }
    pub fn with_protocol(self, protocol: Protocol) -> Self {
        self.set_protocol(protocol)
    }
    pub fn with_scan_type(self, scan_type: HostScanType) -> Self {
        self.set_scan_type(scan_type)
    }
    pub fn with_concurrency(self, concurrency: usize) -> Self {
        self.set_concurrency(concurrency)
    }
    pub fn with_timeout(self, timeout: Duration) -> Self {
        self.set_timeout(timeout)
    }
    pub fn with_wait_time(self, wait_time: Duration) -> Self {
        self.set_wait_time(wait_time)
    }
    pub fn with_send_rate(self, send_rate: Duration) -> Self {
        self.set_send_rate(send_rate)
    }
    pub fn with_randomize(self, randomize: bool) -> Self {
        self.set_randomize(randomize)
    }
    pub fn with_minimize_packet(self, minimize_packet: bool) -> Self {
        self.set_minimize_packet(minimize_packet)
    }
    pub fn with_dns_map(self, dns_map: HashMap<IpAddr, String>) -> Self {
        self.set_dns_map(dns_map)
    }
    pub fn with_async_scan(self, async_scan: bool) -> Self {
        self.set_async_scan(async_scan)
    }

    // support builder pattern for all fields
    pub fn set_if_index(mut self, if_index: u32) -> Self {
        self.if_index = if_index;
        self
    }
    pub fn set_targets(mut self, targets: Vec<Host>) -> Self {
        self.targets = targets;
        self
    }
    pub fn set_protocol(mut self, protocol: Protocol) -> Self {
        self.protocol = protocol;
        self
    }
    pub fn set_scan_type(mut self, scan_type: HostScanType) -> Self {
        self.scan_type = scan_type;
        self
    }
    pub fn set_concurrency(mut self, concurrency: usize) -> Self {
        self.concurrency = concurrency;
        self
    }
    pub fn set_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }
    pub fn set_wait_time(mut self, wait_time: Duration) -> Self {
        self.wait_time = wait_time;
        self
    }
    pub fn set_send_rate(mut self, send_rate: Duration) -> Self {
        self.send_rate = send_rate;
        self
    }
    pub fn set_randomize(mut self, randomize: bool) -> Self {
        self.randomize = randomize;
        self
    }
    pub fn set_minimize_packet(mut self, minimize_packet: bool) -> Self {
        self.minimize_packet = minimize_packet;
        self
    }
    pub fn set_dns_map(mut self, dns_map: HashMap<IpAddr, String>) -> Self {
        self.dns_map = dns_map;
        self
    }
    pub fn add_target(&mut self, target: Host) {
        self.targets.push(target);
    }
    pub fn set_async_scan(mut self, async_scan: bool) -> Self {
        self.async_scan = async_scan;
        self
    }
    pub fn randomize_hosts(&mut self) {
        let mut rng = rand::thread_rng();
        self.targets.shuffle(&mut rng);
    }
    pub fn randomize_ports(&mut self) {
        for target in &mut self.targets {
            target.ports.shuffle(&mut rand::thread_rng());
        }
    }
}

/// Probe setting for service detection
#[derive(Clone, Debug)]
pub struct ServiceProbeSetting {
    /// Destination IP address
    pub ip_addr: IpAddr,
    /// Destination Host Name
    pub hostname: String,
    /// Target ports for service detection
    pub ports: Vec<u16>,
    /// TCP connect (open) timeout
    pub connect_timeout: Duration,
    /// TCP read timeout
    pub read_timeout: Duration,
    /// SSL/TLS certificate validation when detecting HTTPS services.  
    ///
    /// Default value is false, which means validation is enabled.
    pub accept_invalid_certs: bool,
    /// Payloads for specified ports.
    ///
    /// If not set, default null probe will be used. (No payload, just open TCP connection and read response)
    pub payload_map: HashMap<u16, PayloadInfo>,
    /// Concurrent connection limit for service detection
    pub concurrent_limit: usize,
}

impl ServiceProbeSetting {
    /// Create new ProbeSetting
    pub fn new() -> ServiceProbeSetting {
        ServiceProbeSetting {
            ip_addr: IpAddr::V4(Ipv4Addr::LOCALHOST),
            hostname: String::new(),
            ports: vec![],
            connect_timeout: Duration::from_millis(200),
            read_timeout: Duration::from_secs(5),
            accept_invalid_certs: false,
            payload_map: HashMap::new(),
            concurrent_limit: 10,
        }
    }
    pub fn default(ip_addr: IpAddr, hostname: String, ports: Vec<u16>) -> ServiceProbeSetting {
        let mut payload_map: HashMap<u16, PayloadInfo> = HashMap::new();
        let http_head = PayloadBuilder::http_head();
        let https_head = PayloadBuilder::https_head(&hostname);
        payload_map.insert(80, http_head.clone());
        payload_map.insert(443, https_head.clone());
        payload_map.insert(8080, http_head);
        payload_map.insert(8443, https_head);
        ServiceProbeSetting {
            ip_addr: ip_addr,
            hostname: hostname,
            ports: ports,
            connect_timeout: Duration::from_secs(1),
            read_timeout: Duration::from_secs(5),
            accept_invalid_certs: false,
            payload_map: payload_map,
            concurrent_limit: 10,
        }
    }
    /// Builder-style variant of `with_ip_addr` for chaining from owned values.
    pub fn with_target_ip(mut self, ip_addr: IpAddr) -> Self {
        self.ip_addr = ip_addr;
        self
    }
    /// Builder-style variant of `with_hostname` for chaining from owned values.
    pub fn with_target_hostname(mut self, hostname: String) -> Self {
        self.hostname = hostname;
        if self.ip_addr == IpAddr::V4(Ipv4Addr::LOCALHOST)
            || self.ip_addr == IpAddr::V4(Ipv4Addr::UNSPECIFIED)
            || self.ip_addr == IpAddr::V6(std::net::Ipv6Addr::LOCALHOST)
            || self.ip_addr == IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED)
        {
            if let Some(ip_addr) = crate::dns::lookup_host_name(&self.hostname) {
                self.ip_addr = ip_addr;
            }
        }
        self
    }
    /// Builder-style setter for target ports.
    pub fn with_ports(mut self, ports: Vec<u16>) -> Self {
        self.ports = ports;
        self
    }
    /// Builder-style setter for connect timeout.
    pub fn with_connect_timeout(mut self, connect_timeout: Duration) -> Self {
        self.connect_timeout = connect_timeout;
        self
    }
    /// Builder-style setter for read timeout.
    pub fn with_read_timeout(mut self, read_timeout: Duration) -> Self {
        self.read_timeout = read_timeout;
        self
    }
    /// Builder-style setter for concurrent probe limit.
    pub fn with_concurrent_limit(mut self, concurrent_limit: usize) -> Self {
        self.concurrent_limit = concurrent_limit;
        self
    }
    /// Set Destination IP address
    pub fn with_ip_addr(&mut self, ip_addr: IpAddr) -> &mut Self {
        self.ip_addr = ip_addr;
        self
    }
    /// Set Destination Host Name. If IP address is not set, it will be resolved from the hostname.
    pub fn with_hostname(&mut self, hostname: String) -> &mut Self {
        self.hostname = hostname;
        if self.ip_addr == IpAddr::V4(Ipv4Addr::LOCALHOST)
            || self.ip_addr == IpAddr::V4(Ipv4Addr::UNSPECIFIED)
            || self.ip_addr == IpAddr::V6(std::net::Ipv6Addr::LOCALHOST)
            || self.ip_addr == IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED)
        {
            if let Some(ip_addr) = crate::dns::lookup_host_name(&self.hostname) {
                self.ip_addr = ip_addr;
            }
        }
        self
    }
    /// Add target port
    pub fn add_port(&mut self, port: u16) {
        self.ports.push(port);
    }
    /// Set connect (open) timeout in milliseconds
    pub fn set_connect_timeout_millis(&mut self, connect_timeout_millis: u64) {
        self.connect_timeout = Duration::from_millis(connect_timeout_millis);
    }
    /// Set TCP read timeout in milliseconds
    pub fn set_read_timeout_millis(&mut self, read_timeout_millis: u64) {
        self.read_timeout = Duration::from_millis(read_timeout_millis);
    }
}