-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathnet.rs
295 lines (263 loc) · 11.5 KB
/
net.rs
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
use crate::http::HttpError;
use crate::token::{ApplicationProtocol, Protocol};
use crate::DgwState;
use axum::extract::ws::Message;
use axum::extract::{Query, WebSocketUpgrade};
use axum::response::Response;
use axum::{Json, Router};
use network_scanner::interfaces::{self, MacAddr};
use network_scanner::scanner::{self, NetworkScannerParams};
use serde::Serialize;
use std::net::IpAddr;
pub fn make_router<S>(state: DgwState) -> Router<S> {
let router = Router::new().route("/scan", axum::routing::get(handle_network_scan));
let router = if state.conf_handle.get_conf().debug.enable_unstable {
// This route is currently unstable and disabled by default.
router.route("/config", axum::routing::get(get_net_config))
} else {
router
};
router.with_state(state)
}
pub async fn handle_network_scan(
_token: crate::extract::NetScanToken,
ws: WebSocketUpgrade,
query_params: Query<NetworkScanQueryParams>,
) -> Result<Response, HttpError> {
let scanner_params: NetworkScannerParams = query_params.0.into();
let scanner = scanner::NetworkScanner::new(scanner_params).map_err(|e| {
error!(error = format!("{e:#}"), "Failed to create network scanner");
HttpError::internal().build(e)
})?;
let res = ws.on_upgrade(move |mut websocket| async move {
let stream = match scanner.start() {
Ok(stream) => stream,
Err(e) => {
error!(error = format!("{e:#}"), "Failed to start network scan");
return;
}
};
info!("Network scan started");
loop {
tokio::select! {
result = stream.recv() => {
let Some(entry) = result else {
let _ = websocket
.send(Message::Close(Some(axum::extract::ws::CloseFrame {
code: axum::extract::ws::close_code::NORMAL,
reason: std::borrow::Cow::from("network scan finished successfully"),
})))
.await;
break;
};
let response = NetworkScanResponse::new(entry.addr, entry.port, entry.hostname, entry.service_type);
let Ok(response) = serde_json::to_string(&response) else {
warn!("Failed to serialize response");
continue;
};
if let Err(error) = websocket.send(Message::Text(response)).await {
warn!(%error, "Failed to send message");
// It is very likely that the websocket is already closed, but send it as a precaution.
let _ = websocket
.send(Message::Close(Some(axum::extract::ws::CloseFrame {
code: axum::extract::ws::close_code::ABNORMAL,
reason: std::borrow::Cow::from("network scan finished prematurely."),
})))
.await;
break;
}
},
msg = websocket.recv() => {
let Some(msg) = msg else {
break;
};
if let Ok(Message::Close(_)) = msg {
break;
}
}
}
}
// Stop the network scanner, whatever the code path (error or not).
stream.stop();
// In case the websocket is not closed yet.
// If the logic above is correct, it’s not necessary.
let _ = websocket.close().await;
info!("Network scan finished");
});
Ok(res)
}
#[derive(Debug, Deserialize)]
pub struct NetworkScanQueryParams {
/// Interval in milliseconds (default is 200)
pub ping_interval: Option<u64>,
/// Timeout in milliseconds (default is 500)
pub ping_timeout: Option<u64>,
/// Timeout in milliseconds (default is 1000)
pub broadcast_timeout: Option<u64>,
/// Timeout in milliseconds (default is 1000)
pub port_scan_timeout: Option<u64>,
/// Timeout in milliseconds (default is 1000)
pub netbios_timeout: Option<u64>,
/// Interval in milliseconds (default is 200)
pub netbios_interval: Option<u64>,
/// The maximum time for each mdns query in milliseconds. (default is 5 * 1000)
pub mdns_query_timeout: Option<u64>,
/// The maximum duration for whole networking scan in milliseconds. Highly suggested!
pub max_wait: Option<u64>,
}
const COMMON_PORTS: [u16; 11] = [22, 23, 80, 443, 389, 636, 3283, 3389, 5900, 5985, 5986];
impl From<NetworkScanQueryParams> for NetworkScannerParams {
fn from(val: NetworkScanQueryParams) -> Self {
NetworkScannerParams {
ports: COMMON_PORTS.to_vec(),
ping_interval: val.ping_interval.unwrap_or(200),
ping_timeout: val.ping_timeout.unwrap_or(500),
broadcast_timeout: val.broadcast_timeout.unwrap_or(1000),
port_scan_timeout: val.port_scan_timeout.unwrap_or(1000),
netbios_timeout: val.netbios_timeout.unwrap_or(1000),
max_wait_time: val.max_wait.unwrap_or(120 * 1000),
netbios_interval: val.netbios_interval.unwrap_or(200),
mdns_query_timeout: val.mdns_query_timeout.unwrap_or(5 * 1000), // in milliseconds
}
}
}
#[derive(Debug, Serialize)]
pub struct NetworkScanResponse {
pub ip: IpAddr,
pub hostname: Option<String>,
pub protocol: ApplicationProtocol,
}
impl NetworkScanResponse {
fn new(ip: IpAddr, port: u16, dns: Option<String>, service_type: Option<scanner::ServiceType>) -> Self {
let hostname = dns;
let protocol = if let Some(protocol) = service_type {
match protocol {
scanner::ServiceType::Ssh => ApplicationProtocol::Known(Protocol::Ssh),
scanner::ServiceType::Telnet => ApplicationProtocol::Known(Protocol::Telnet),
scanner::ServiceType::Http => ApplicationProtocol::Known(Protocol::Http),
scanner::ServiceType::Https => ApplicationProtocol::Known(Protocol::Https),
scanner::ServiceType::Ldap => ApplicationProtocol::Known(Protocol::Ldap),
scanner::ServiceType::Ldaps => ApplicationProtocol::Known(Protocol::Ldaps),
scanner::ServiceType::Rdp => ApplicationProtocol::Known(Protocol::Rdp),
scanner::ServiceType::Vnc => ApplicationProtocol::Known(Protocol::Vnc),
scanner::ServiceType::Ard => ApplicationProtocol::Known(Protocol::Ard),
scanner::ServiceType::Sftp => ApplicationProtocol::Known(Protocol::Sftp),
scanner::ServiceType::Scp => ApplicationProtocol::Known(Protocol::Scp),
}
} else {
match port {
22 => ApplicationProtocol::Known(Protocol::Ssh),
23 => ApplicationProtocol::Known(Protocol::Telnet),
80 => ApplicationProtocol::Known(Protocol::Http),
443 => ApplicationProtocol::Known(Protocol::Https),
389 => ApplicationProtocol::Known(Protocol::Ldap),
636 => ApplicationProtocol::Known(Protocol::Ldaps),
3389 => ApplicationProtocol::Known(Protocol::Rdp),
5900 => ApplicationProtocol::Known(Protocol::Vnc),
5985 => ApplicationProtocol::Known(Protocol::WinrmHttpPwsh),
5986 => ApplicationProtocol::Known(Protocol::WinrmHttpsPwsh),
_ => ApplicationProtocol::unknown(),
}
};
Self { ip, hostname, protocol }
}
}
#[derive(Debug, Deserialize)]
pub struct NetworkConfigParams {
pub ignore_ipv6: Option<bool>,
pub include_loopback: Option<bool>,
}
/// Lists network interfaces
#[cfg_attr(feature = "openapi", utoipa::path(
get,
operation_id = "GetNetConfig",
tag = "Net",
path = "/jet/net/config",
params(
(name = "ignore_ipv6", description = "Ignore IPv6 addresses", type = "boolean", example = false),
(name = "include_loopback", description = "Include loopback interfaces", type = "boolean", example = true),
),
responses(
(status = 200, description = "Network interfaces", body = [Vec<NetworkInterface>]),
(status = 400, description = "Bad request"),
(status = 401, description = "Invalid or missing authorization token"),
(status = 403, description = "Insufficient permissions"),
(status = 500, description = "Unexpected server error"),
),
security(("netscan_token" = [])),
))]
pub async fn get_net_config(
Query(params): Query<NetworkConfigParams>,
_token: crate::extract::NetScanToken,
) -> Result<Json<Vec<NetworkInterface>>, HttpError> {
let mut filter = interfaces::Filter::default();
if let Some(ignore_ipv6) = params.ignore_ipv6 {
filter.ignore_ipv6 = ignore_ipv6;
}
if let Some(include_loopback) = params.include_loopback {
filter.include_loopback = include_loopback;
}
let interfaces = interfaces::get_network_interfaces(filter)
.await
.map_err(HttpError::internal().with_msg("failed to get network interfaces").err())?
.into_iter()
.map(NetworkInterface::from)
.collect();
Ok(Json(interfaces))
}
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[derive(Debug, Clone, Serialize)]
pub struct InterfaceAddress {
pub ip: IpAddr,
pub prefixlen: u32,
}
/// Network interface configuration
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[derive(Debug, Clone, Serialize)]
pub struct NetworkInterface {
/// The id is a Windows specific concept, does not exist in linux
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
/// The description of the interface, also Windows specific
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[cfg_attr(feature = "openapi", schema(value_type = Option<String>))]
#[serde(skip_serializing_if = "Option::is_none")]
pub mac_address: Option<MacAddr>,
// routes is the list of IP addresses and their prefix lengths that this interface routes to.
#[cfg_attr(feature = "openapi", schema(value_type = Vec<InterfaceAddress>))]
pub routes: Vec<InterfaceAddress>,
#[cfg_attr(feature = "openapi", schema(value_type = bool))]
pub is_up: bool,
#[cfg_attr(feature = "openapi", schema(value_type = Vec<String>))]
pub gateways: Vec<IpAddr>,
#[cfg_attr(feature = "openapi", schema(value_type = Vec<String>))]
pub nameservers: Vec<IpAddr>,
#[cfg_attr(feature = "openapi", schema(value_type = String))]
pub name: String,
// Assigned IP addresses to this interface
#[cfg_attr(feature = "openapi", schema(value_type = Vec<IpAddr>))]
pub ip_adresses: Vec<IpAddr>,
}
impl From<interfaces::NetworkInterface> for NetworkInterface {
fn from(iface: interfaces::NetworkInterface) -> Self {
Self {
id: iface.id,
name: iface.name,
description: iface.description,
mac_address: iface.mac_address,
ip_adresses: iface.ip_adresses,
routes: iface
.routes
.into_iter()
.map(|addr| InterfaceAddress {
ip: addr.ip,
prefixlen: addr.prefixlen,
})
.collect(),
is_up: iface.operational_status,
gateways: iface.gateways,
nameservers: iface.dns_servers,
}
}
}