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
use crate::async_io::{scan_hosts, scan_ports};
use crate::host::HostInfo;
use crate::result::{HostScanResult, PortScanResult, ScanStatus};
use crate::setting::{
    ScanSetting, ScanType, DEFAULT_HOSTS_CONCURRENCY, DEFAULT_PORTS_CONCURRENCY, DEFAULT_SRC_PORT,
};
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Async Host Scanner
#[derive(Clone, Debug)]
pub struct HostScanner {
    /// Index of network interface
    pub if_index: u32,
    /// Name of network interface
    pub if_name: String,
    /// MAC address of network interface
    pub src_mac: [u8; 6],
    /// MAC address of default gateway(or scan target host)
    pub dst_mac: [u8; 6],
    /// Source IP address
    pub src_ip: IpAddr,
    /// Source port
    pub src_port: u16,
    /// Targets
    pub targets: Vec<HostInfo>,
    /// Scan Type
    pub scan_type: ScanType,
    /// Number of host scans to run concurrently
    pub hosts_concurrency: usize,
    /// Timeout setting for entire scan task
    pub timeout: Duration,
    /// Waiting time after packet sending task is completed
    pub wait_time: Duration,
    /// Packet sending interval(0 for unlimited)
    pub send_rate: Duration,
    /// Host Scan Result
    pub scan_result: HostScanResult,
    /// Sender for progress messaging
    pub tx: Arc<Mutex<Sender<SocketAddr>>>,
    /// Receiver for progress messaging
    pub rx: Arc<Mutex<Receiver<SocketAddr>>>,
}

impl HostScanner {
    /// Create new HostScanner with source IP address
    ///
    /// Initialized with default value based on the specified IP address
    pub fn new(src_ip: IpAddr) -> Result<HostScanner, String> {
        let mut if_index: u32 = 0;
        let mut if_name: String = String::new();
        let mut src_mac: pnet_datalink::MacAddr = pnet_datalink::MacAddr::zero();
        for iface in pnet_datalink::interfaces() {
            for ip in iface.ips {
                if ip.ip() == src_ip {
                    if_index = iface.index;
                    if_name = iface.name;
                    src_mac = iface.mac.unwrap_or(pnet_datalink::MacAddr::zero());
                    break;
                }
            }
        }
        if if_index == 0 || if_name.is_empty() || src_mac == pnet_datalink::MacAddr::zero() {
            return Err(String::from(
                "Failed to create Scanner. Network Interface not found.",
            ));
        }
        let (tx, rx) = channel();
        let host_scanner = HostScanner {
            if_index: if_index,
            if_name: if_name,
            src_mac: src_mac.octets(),
            dst_mac: pnet_datalink::MacAddr::zero().octets(),
            src_ip: src_ip,
            src_port: DEFAULT_SRC_PORT,
            targets: vec![],
            scan_type: ScanType::IcmpPingScan,
            hosts_concurrency: DEFAULT_HOSTS_CONCURRENCY,
            timeout: Duration::from_millis(30000),
            wait_time: Duration::from_millis(200),
            send_rate: Duration::from_millis(1),
            scan_result: HostScanResult::new(),
            tx: Arc::new(Mutex::new(tx)),
            rx: Arc::new(Mutex::new(rx)),
        };
        Ok(host_scanner)
    }
    /// Set source IP address
    pub fn set_src_ip(&mut self, src_ip: IpAddr) {
        self.src_ip = src_ip;
    }
    /// Get source IP address
    pub fn get_src_ip(&self) -> IpAddr {
        self.src_ip.clone()
    }
    /// Add Target
    pub fn add_target(&mut self, dst: HostInfo) {
        self.targets.push(dst);
    }
    /// Set Targets
    pub fn set_targets(&mut self, dst: Vec<HostInfo>) {
        self.targets = dst;
    }
    /// Get Targets
    pub fn get_targets(&self) -> Vec<HostInfo> {
        self.targets.clone()
    }
    /// Set ScanType
    pub fn set_scan_type(&mut self, scan_type: ScanType) {
        self.scan_type = scan_type;
    }
    /// Get ScanType
    pub fn get_scan_type(&self) -> ScanType {
        self.scan_type.clone()
    }
    /// Set timeout
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = timeout;
    }
    /// Get timeout
    pub fn get_timeout(&self) -> Duration {
        self.timeout.clone()
    }
    /// Set wait time
    pub fn set_wait_time(&mut self, wait_time: Duration) {
        self.wait_time = wait_time;
    }
    /// Get wait time
    pub fn get_wait_time(&self) -> Duration {
        self.wait_time.clone()
    }
    /// Set send rate
    pub fn set_send_rate(&mut self, send_rate: Duration) {
        self.send_rate = send_rate;
    }
    /// Get send rate
    pub fn get_send_rate(&self) -> Duration {
        self.send_rate.clone()
    }
    /// Set hosts concurrency
    pub fn set_hosts_concurrency(&mut self, concurrency: usize) {
        self.hosts_concurrency = concurrency;
    }
    /// Get scan result
    pub fn get_scan_result(&self) -> HostScanResult {
        self.scan_result.clone()
    }
    /// Get progress receiver
    pub fn get_progress_receiver(&self) -> Arc<Mutex<Receiver<SocketAddr>>> {
        self.rx.clone()
    }
    /// Run Host Scan
    pub async fn run_scan(&mut self) {
        let mut ip_map: HashMap<IpAddr, String> = HashMap::new();
        for dst in self.targets.clone() {
            ip_map.insert(dst.ip_addr, dst.host_name);
        }
        let scan_setting: ScanSetting = ScanSetting {
            if_index: self.if_index.clone(),
            src_mac: pnet_datalink::MacAddr::from(self.src_mac),
            dst_mac: pnet_datalink::MacAddr::from(self.dst_mac),
            src_ip: self.src_ip.clone(),
            src_port: self.src_port.clone(),
            targets: self.targets.clone(),
            ip_map: ip_map,
            timeout: self.timeout.clone(),
            wait_time: self.wait_time.clone(),
            send_rate: self.timeout.clone(),
            scan_type: self.scan_type.clone(),
            hosts_concurrency: self.hosts_concurrency,
            ports_concurrency: DEFAULT_PORTS_CONCURRENCY,
        };
        let start_time = Instant::now();
        let mut result: HostScanResult = scan_hosts(scan_setting, &self.tx).await;
        result.scan_time = Instant::now().duration_since(start_time);
        if result.scan_time > self.timeout {
            result.scan_status = ScanStatus::Timeout;
        } else {
            result.scan_status = ScanStatus::Done;
        }
        self.scan_result = result;
    }
    /// Run scan and return result
    pub async fn scan(&mut self) -> HostScanResult {
        self.run_scan().await;
        self.scan_result.clone()
    }
}

/// Async Port Scanner
#[derive(Clone, Debug)]
pub struct PortScanner {
    /// Index of network interface
    pub if_index: u32,
    /// Name of network interface
    pub if_name: String,
    /// MAC address of network interface
    pub src_mac: [u8; 6],
    /// MAC address of default gateway(or scan target host)
    pub dst_mac: [u8; 6],
    /// Source IP address
    pub src_ip: IpAddr,
    /// Source port
    pub src_port: u16,
    /// Targets
    pub targets: Vec<HostInfo>,
    /// Scan Type
    pub scan_type: ScanType,
    /// Number of host scans to run concurrently
    pub hosts_concurrency: usize,
    /// Number of port scans to run concurrently
    pub ports_concurrency: usize,
    /// Timeout setting for entire scan task
    pub timeout: Duration,
    /// Waiting time after packet sending task is completed
    pub wait_time: Duration,
    /// Packet sending interval(0 for unlimited)
    pub send_rate: Duration,
    /// Port Scan Result
    pub scan_result: PortScanResult,
    /// Sender for progress messaging
    pub tx: Arc<Mutex<Sender<SocketAddr>>>,
    /// Receiver for progress messaging
    pub rx: Arc<Mutex<Receiver<SocketAddr>>>,
}

impl PortScanner {
    /// Create new PortScanner with source IP address
    ///
    /// Initialized with default value based on the specified IP address
    pub fn new(src_ip: IpAddr) -> Result<PortScanner, String> {
        let mut if_index: u32 = 0;
        let mut if_name: String = String::new();
        let mut src_mac: pnet_datalink::MacAddr = pnet_datalink::MacAddr::zero();
        for iface in pnet_datalink::interfaces() {
            for ip in iface.ips {
                if ip.ip() == src_ip {
                    if_index = iface.index;
                    if_name = iface.name;
                    src_mac = iface.mac.unwrap_or(pnet_datalink::MacAddr::zero());
                    break;
                }
            }
        }
        if if_index == 0 || if_name.is_empty() || src_mac == pnet_datalink::MacAddr::zero() {
            return Err(String::from(
                "Failed to create Scanner. Network Interface not found.",
            ));
        }
        let (tx, rx) = channel();
        let port_scanner = PortScanner {
            if_index: if_index,
            if_name: if_name,
            src_mac: src_mac.octets(),
            dst_mac: pnet_datalink::MacAddr::zero().octets(),
            src_ip: src_ip,
            src_port: DEFAULT_SRC_PORT,
            targets: vec![],
            scan_type: ScanType::TcpSynScan,
            hosts_concurrency: DEFAULT_HOSTS_CONCURRENCY,
            ports_concurrency: DEFAULT_PORTS_CONCURRENCY,
            timeout: Duration::from_millis(30000),
            wait_time: Duration::from_millis(200),
            send_rate: Duration::from_millis(1),
            scan_result: PortScanResult::new(),
            tx: Arc::new(Mutex::new(tx)),
            rx: Arc::new(Mutex::new(rx)),
        };
        Ok(port_scanner)
    }
    /// Set source IP address
    pub fn set_src_ip(&mut self, src_ip: IpAddr) {
        self.src_ip = src_ip;
    }
    /// Get source IP address
    pub fn get_src_ip(&self) -> IpAddr {
        self.src_ip.clone()
    }
    /// Add Target
    pub fn add_target(&mut self, dst: HostInfo) {
        self.targets.push(dst);
    }
    /// Set Targets
    pub fn set_targets(&mut self, dst: Vec<HostInfo>) {
        self.targets = dst;
    }
    /// Get targets
    pub fn get_targets(&self) -> Vec<HostInfo> {
        self.targets.clone()
    }
    /// Set ScanType
    pub fn set_scan_type(&mut self, scan_type: ScanType) {
        self.scan_type = scan_type;
    }
    /// Get ScanType
    pub fn get_scan_type(&self) -> ScanType {
        self.scan_type.clone()
    }
    /// Set timeout
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = timeout;
    }
    /// Get timeout
    pub fn get_timeout(&self) -> Duration {
        self.timeout.clone()
    }
    /// Set wait time
    pub fn set_wait_time(&mut self, wait_time: Duration) {
        self.wait_time = wait_time;
    }
    /// Get wait time
    pub fn get_wait_time(&self) -> Duration {
        self.wait_time.clone()
    }
    /// Set send rate
    pub fn set_send_rate(&mut self, send_rate: Duration) {
        self.send_rate = send_rate;
    }
    /// Get send rate
    pub fn get_send_rate(&self) -> Duration {
        self.send_rate.clone()
    }
    /// Set hosts concurrency
    pub fn set_hosts_concurrency(&mut self, concurrency: usize) {
        self.hosts_concurrency = concurrency;
    }
    /// Set ports concurrency
    pub fn set_ports_concurrency(&mut self, concurrency: usize) {
        self.ports_concurrency = concurrency;
    }
    /// Get scan result
    pub fn get_scan_result(&self) -> PortScanResult {
        self.scan_result.clone()
    }
    /// Get progress receiver
    pub fn get_progress_receiver(&self) -> Arc<Mutex<Receiver<SocketAddr>>> {
        self.rx.clone()
    }
    /// Run Port Scan
    pub async fn run_scan(&mut self) {
        let mut ip_map: HashMap<IpAddr, String> = HashMap::new();
        for dst in self.targets.clone() {
            ip_map.insert(dst.ip_addr, dst.host_name);
        }
        let scan_setting: ScanSetting = ScanSetting {
            if_index: self.if_index.clone(),
            src_mac: pnet_datalink::MacAddr::from(self.src_mac),
            dst_mac: pnet_datalink::MacAddr::from(self.dst_mac),
            src_ip: self.src_ip.clone(),
            src_port: self.src_port.clone(),
            targets: self.targets.clone(),
            ip_map: ip_map,
            timeout: self.timeout.clone(),
            wait_time: self.wait_time.clone(),
            send_rate: self.timeout.clone(),
            scan_type: self.scan_type.clone(),
            hosts_concurrency: self.hosts_concurrency,
            ports_concurrency: self.ports_concurrency,
        };
        let start_time = Instant::now();
        let mut result: PortScanResult = scan_ports(scan_setting, &self.tx).await;
        result.scan_time = Instant::now().duration_since(start_time);
        if result.scan_status != ScanStatus::Error {
            if result.scan_time > self.timeout {
                result.scan_status = ScanStatus::Timeout;
            } else {
                result.scan_status = ScanStatus::Done;
            }
        }
        self.scan_result = result;
    }
    /// Run scan and return result
    pub async fn scan(&mut self) -> PortScanResult {
        self.run_scan().await;
        self.scan_result.clone()
    }
}