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
|
use std::{
future::poll_fn,
net::{IpAddr, SocketAddr},
time::Duration,
};
use futures::{StreamExt, channel::oneshot, pin_mut};
pub use pcap::Direction;
use pcap::PacketCodec;
use pnet_packet::{
Packet, ethernet::EtherTypes, ip::IpNextHeaderProtocol, ipv4::Ipv4Packet, ipv6::Ipv6Packet,
tcp::TcpPacket, udp::UdpPacket,
};
pub use pnet_packet::ip::IpNextHeaderProtocols as IpHeaderProtocols;
use crate::{tests::config::TEST_CONFIG, vm::network::CUSTOM_TUN_INTERFACE_NAME};
struct Codec {
no_frame: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedPacket {
pub source: SocketAddr,
pub destination: SocketAddr,
pub protocol: IpNextHeaderProtocol,
pub payload: Vec<u8>,
}
impl PacketCodec for Codec {
type Item = Option<ParsedPacket>;
fn decode(&mut self, packet: pcap::Packet<'_>) -> Self::Item {
if self.no_frame {
// skip utun header specifying an address family
#[cfg(target_os = "macos")]
let data = &packet.data[4..];
#[cfg(not(target_os = "macos"))]
let data = packet.data;
let ip_version = (data[0] & 0xf0) >> 4;
return match ip_version {
4 => Self::parse_ipv4(data),
6 => Self::parse_ipv6(data),
version => {
log::debug!("Ignoring unknown IP version: {version}");
None
}
};
}
let frame = pnet_packet::ethernet::EthernetPacket::new(packet.data).or_else(|| {
log::error!("Received invalid ethernet frame");
None
})?;
match frame.get_ethertype() {
EtherTypes::Ipv4 => Self::parse_ipv4(frame.payload()),
EtherTypes::Ipv6 => Self::parse_ipv6(frame.payload()),
ethertype => {
log::trace!("Ignoring unknown ethertype: {ethertype}");
None
}
}
}
}
impl Codec {
fn parse_ipv4(payload: &[u8]) -> Option<ParsedPacket> {
let packet = Ipv4Packet::new(payload).or_else(|| {
log::error!("invalid v4 packet");
None
})?;
let mut source = SocketAddr::new(IpAddr::V4(packet.get_source()), 0);
let mut destination = SocketAddr::new(IpAddr::V4(packet.get_destination()), 0);
let mut payload = vec![];
let protocol = packet.get_next_level_protocol();
match protocol {
IpHeaderProtocols::Tcp => {
let seg = TcpPacket::new(packet.payload()).or_else(|| {
log::error!("invalid TCP segment");
None
})?;
source.set_port(seg.get_source());
destination.set_port(seg.get_destination());
payload = seg.payload().to_vec();
}
IpHeaderProtocols::Udp => {
let seg = UdpPacket::new(packet.payload()).or_else(|| {
log::error!("invalid UDP fragment");
None
})?;
source.set_port(seg.get_source());
destination.set_port(seg.get_destination());
payload = seg.payload().to_vec();
}
IpHeaderProtocols::Icmp => {}
proto => log::warn!("ignoring v4 packet, transport/protocol type {proto}"),
}
Some(ParsedPacket {
source,
destination,
protocol,
payload,
})
}
fn parse_ipv6(payload: &[u8]) -> Option<ParsedPacket> {
let packet = Ipv6Packet::new(payload).or_else(|| {
log::error!("invalid v6 packet");
None
})?;
let mut source = SocketAddr::new(IpAddr::V6(packet.get_source()), 0);
let mut destination = SocketAddr::new(IpAddr::V6(packet.get_destination()), 0);
let mut payload = vec![];
let protocol = packet.get_next_header();
match protocol {
IpHeaderProtocols::Tcp => {
let seg = TcpPacket::new(packet.payload()).or_else(|| {
log::error!("invalid TCP segment");
None
})?;
source.set_port(seg.get_source());
destination.set_port(seg.get_destination());
payload = seg.payload().to_vec();
}
IpHeaderProtocols::Udp => {
let seg = UdpPacket::new(packet.payload()).or_else(|| {
log::error!("invalid UDP fragment");
None
})?;
source.set_port(seg.get_source());
destination.set_port(seg.get_destination());
payload = seg.payload().to_vec();
}
IpHeaderProtocols::Icmpv6 => {}
proto => log::warn!("ignoring v6 packet, transport/protocol type {proto}"),
}
Some(ParsedPacket {
source,
destination,
protocol,
payload,
})
}
}
#[derive(Debug, thiserror::Error)]
#[error("Packet monitor stopped unexpectedly")]
pub struct MonitorUnexpectedlyStopped;
pub struct PacketMonitor {
handle: tokio::task::JoinHandle<Result<MonitorResult, MonitorUnexpectedlyStopped>>,
stop_tx: oneshot::Sender<()>,
}
pub struct MonitorResult {
pub packets: Vec<ParsedPacket>,
pub discarded_packets: usize,
}
impl PacketMonitor {
/// Stop monitoring and return the result.
pub async fn into_result(self) -> Result<MonitorResult, MonitorUnexpectedlyStopped> {
let _ = self.stop_tx.send(());
self.handle.await.expect("monitor panicked")
}
/// Wait for monitor to stop on its own.
pub async fn wait(self) -> Result<MonitorResult, MonitorUnexpectedlyStopped> {
self.handle.await.expect("monitor panicked")
}
}
#[derive(Default)]
pub struct MonitorOptions {
pub timeout: Option<Duration>,
pub direction: Option<Direction>,
pub no_frame: bool,
}
pub async fn start_packet_monitor(
filter_fn: impl Fn(&ParsedPacket) -> bool + Send + 'static,
monitor_options: MonitorOptions,
) -> PacketMonitor {
start_packet_monitor_until(filter_fn, |_| true, monitor_options).await
}
pub async fn start_packet_monitor_until(
filter_fn: impl Fn(&ParsedPacket) -> bool + Send + 'static,
should_continue_fn: impl FnMut(&ParsedPacket) -> bool + Send + 'static,
monitor_options: MonitorOptions,
) -> PacketMonitor {
start_packet_monitor_for_interface(
&TEST_CONFIG.host_bridge_name,
filter_fn,
should_continue_fn,
monitor_options,
)
.await
}
pub async fn start_tunnel_packet_monitor_until(
filter_fn: impl Fn(&ParsedPacket) -> bool + Send + 'static,
should_continue_fn: impl FnMut(&ParsedPacket) -> bool + Send + 'static,
mut monitor_options: MonitorOptions,
) -> PacketMonitor {
monitor_options.no_frame = true;
start_packet_monitor_for_interface(
CUSTOM_TUN_INTERFACE_NAME,
filter_fn,
should_continue_fn,
monitor_options,
)
.await
}
async fn start_packet_monitor_for_interface(
interface: &str,
filter_fn: impl Fn(&ParsedPacket) -> bool + Send + 'static,
mut should_continue_fn: impl FnMut(&ParsedPacket) -> bool + Send + 'static,
monitor_options: MonitorOptions,
) -> PacketMonitor {
let dev = pcap::Capture::from_device(interface)
.expect("Failed to open capture handle")
.immediate_mode(true)
.open()
.expect("Failed to activate capture");
if let Some(direction) = monitor_options.direction {
dev.direction(direction).unwrap();
}
let dev = dev.setnonblock().unwrap();
let (is_receiving_tx, is_receiving_rx) = oneshot::channel();
let packet_stream = dev
.stream(Codec {
no_frame: monitor_options.no_frame,
})
.unwrap();
let (stop_tx, mut stop_rx) = oneshot::channel();
let interface = interface.to_owned();
let handle = tokio::spawn(async move {
let mut monitor_result = MonitorResult {
packets: vec![],
discarded_packets: 0,
};
let mut packet_stream = packet_stream.fuse();
let timeout = async move {
if let Some(timeout) = monitor_options.timeout {
tokio::time::sleep(timeout).await
} else {
futures::future::pending().await
}
};
pin_mut!(timeout);
let mut is_receiving_tx = Some(is_receiving_tx);
loop {
let mut next_packet_fut = packet_stream.next();
let next_packet =
poll_fn(|ctx| poll_and_notify(ctx, &mut next_packet_fut, &mut is_receiving_tx));
tokio::select! {
_stop = &mut stop_rx => {
log::trace!("stopping packet monitor");
break Ok(monitor_result);
}
_timeout = &mut timeout => {
log::info!("monitor timed out");
break Ok(monitor_result);
}
maybe_next_packet = next_packet => {
let Some(Ok(packet)) = maybe_next_packet else {
log::error!("lost packet stream");
break Err(MonitorUnexpectedlyStopped);
};
let Some(packet) = packet else { continue };
if !filter_fn(&packet) {
log::trace!("{interface} \"{packet:?}\" does not match closure conditions");
monitor_result.discarded_packets =
monitor_result.discarded_packets.saturating_add(1);
} else {
log::trace!("{interface} \"{packet:?}\" matches closure conditions");
let should_continue = should_continue_fn(&packet);
monitor_result.packets.push(packet);
if !should_continue {
break Ok(monitor_result);
}
}
}
}
}
});
// Wait for the loop to start receiving its first packet
let _ = is_receiving_rx.await;
PacketMonitor { stop_tx, handle }
}
/// Poll the future once and notify `tx` that it has been polled. Then return
/// the result of this polling.
fn poll_and_notify<F: std::future::Future<Output = O> + Unpin, O>(
context: &mut std::task::Context<'_>,
fut: &mut F,
tx: &mut Option<oneshot::Sender<()>>,
) -> std::task::Poll<O> {
let result = std::pin::Pin::new(fut).poll(context);
if let Some(tx) = tx.take() {
let _ = tx.send(());
}
result
}
|