netsim 0.3.0

Run tests in network-isolated threads. Intercept and meddle with their packets.
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use {
    crate::priv_prelude::*,
    self::{
        port_map::PortMap,
        restrictions::Restrictions,
    },
};
mod port_map;
mod restrictions;

/// A simple NAT (network address translation) implementation.
///
/// For testing network code across NATs.
pub struct Nat {
    iface_sender: mpsc::UnboundedSender<Pin<Box<dyn IpSinkStream>>>,
}

/// Builder for creating a [`Nat`](crate::device::Nat).
pub struct NatBuilder {
    external_ipv4: Ipv4Addr,
    internal_ipv4_network: Ipv4Network,
    hair_pinning: bool,
    address_restricted: bool,
    port_restricted: bool,
    reply_with_rst_to_unexpected_tcp_packets: bool,
}

impl NatBuilder {
    /// Starts building a [`Nat`](crate::device::Nat). Use to configure the NAT then call
    /// [`build`](crate::device::NatBuilder::build) to create the NAT.
    ///
    /// * `external_ipv4` is the IPv4 address that the NAT uses on its external side.
    /// * `internal_ipv4_network` is the IPv4 network (eg. 192.168.0.0/16) on the internal side of
    ///   the NAT. The NAT won't forward any packets on its internal side that don't originate from
    ///   this network.
    pub fn new(external_ipv4: Ipv4Addr, internal_ipv4_network: Ipv4Network) -> NatBuilder {
        NatBuilder {
            external_ipv4,
            internal_ipv4_network,
            hair_pinning: false,
            address_restricted: false,
            port_restricted: false,
            reply_with_rst_to_unexpected_tcp_packets: false,
        }
    }

    /// Enables [NAT hair-pinning](https://en.wikipedia.org/wiki/Network_address_translation#NAT_hairpinning).
    pub fn hair_pinning(mut self) -> Self {
        self.hair_pinning = true;
        self
    }

    pub fn reply_with_rst_to_unexpected_tcp_packets(mut self) -> Self {
        self.reply_with_rst_to_unexpected_tcp_packets = true;
        self
    }

    /// Makes this NAT [address restricted](https://en.wikipedia.org/wiki/Network_address_translation#Methods_of_translation).
    pub fn address_restricted(mut self) -> Self {
        self.address_restricted = true;
        self
    }

    /// Makes this NAT [port restricted](https://en.wikipedia.org/wiki/Network_address_translation#Methods_of_translation).
    pub fn port_restricted(mut self) -> Self {
        self.port_restricted = true;
        self
    }

    /// Build the NAT. The returned `IpChannel` is the external interface of the NAT.
    pub fn build(self) -> (Nat, IpChannel) {
        let NatBuilder {
            external_ipv4,
            internal_ipv4_network,
            hair_pinning,
            address_restricted,
            port_restricted,
            reply_with_rst_to_unexpected_tcp_packets,
        } = self;
        let (iface_sender, iface_receiver) = mpsc::unbounded();
        let (channel_0, channel_1) = IpChannel::new(1);
        let tcpv4_restrictions = match (port_restricted, address_restricted) {
            (false, false) => Restrictions::Unrestricted,
            (false, true) => Restrictions::RestrictIpAddr { sent_to: HashMap::new() },
            (true, _) => Restrictions::RestrictSocketAddr { sent_to: HashMap::new() },
        };
        let udpv4_restrictions = match (port_restricted, address_restricted) {
            (false, false) => Restrictions::Unrestricted,
            (false, true) => Restrictions::RestrictIpAddr { sent_to: HashMap::new() },
            (true, _) => Restrictions::RestrictSocketAddr { sent_to: HashMap::new() },
        };
        let task = NatTask {
            iface_receiver,
            external_iface_opt: Some(channel_0),
            internal_ifaces: HashMap::new(),
            next_internal_iface_index: 0,
            external_ipv4,
            internal_ipv4_network,
            internal_addr_indexes: HashMap::new(),
            tcpv4_port_map: PortMap::new(),
            udpv4_port_map: PortMap::new(),
            hair_pinning,
            tcpv4_restrictions,
            udpv4_restrictions,
            reply_with_rst_to_unexpected_tcp_packets,
        };
        tokio::spawn(task);
        let nat = Nat { iface_sender };
        (nat, channel_1)
    }
}

struct NatTask {
    iface_receiver: mpsc::UnboundedReceiver<Pin<Box<dyn IpSinkStream>>>,
    external_iface_opt: Option<IpChannel>,
    internal_ifaces: HashMap<usize, Pin<Box<dyn IpSinkStream>>>,
    next_internal_iface_index: usize,
    external_ipv4: Ipv4Addr,
    internal_ipv4_network: Ipv4Network,
    internal_addr_indexes: HashMap<IpAddr, usize>,
    tcpv4_port_map: PortMap,
    udpv4_port_map: PortMap,
    hair_pinning: bool,
    tcpv4_restrictions: Restrictions,
    udpv4_restrictions: Restrictions,
    reply_with_rst_to_unexpected_tcp_packets: bool,
}

impl Nat {
    /// Insert an interface into the internal side of this NAT. Packets sent by this interface to
    /// addresses outside the NAT's internal network will be address translated and sent out
    /// the NAT's external interface. This creates a port-mapping which allows external hosts to
    /// send packets back through the NAT to this interface.
    pub fn insert_iface<S>(&mut self, iface: S)
    where
        S: IpSinkStream,
    {
        let iface = Box::pin(iface);
        self.iface_sender.unbounded_send(iface).unwrap();
    }
}

impl NatTask {
    fn poll_flush_outgoing(&mut self, cx: &mut task::Context) -> Poll<()> {
        let mut any_pending = false;

        match &mut self.external_iface_opt {
            None => (),
            Some(external_iface) => {
                match Pin::new(external_iface).poll_flush(cx) {
                    Poll::Ready(Ok(())) => (),
                    Poll::Ready(Err(_)) => {
                        self.external_iface_opt = None;
                    },
                    Poll::Pending => {
                        any_pending = true;
                    },
                }
            },
        }

        let mut defunct_indexes = Vec::new();
        for (index, internal_iface) in &mut self.internal_ifaces {
            match Pin::new(internal_iface).poll_flush(cx) {
                Poll::Ready(Ok(())) => (),
                Poll::Ready(Err(_)) => {
                    defunct_indexes.push(*index);
                },
                Poll::Pending => {
                    any_pending = true;
                },
            }
        }
        for index in defunct_indexes {
            self.internal_ifaces.remove(&index).unwrap();
        }
        if any_pending {
            Poll::Pending
        } else {
            Poll::Ready(())
        }
    }

    fn poll_ready_outgoing(&mut self, cx: &mut task::Context) -> Poll<()> {
        match self.poll_flush_outgoing(cx) {
            Poll::Ready(()) => return Poll::Ready(()),
            Poll::Pending => (),
        }

        let mut any_pending = false;

        match &mut self.external_iface_opt {
            None => (),
            Some(external_iface) => {
                match Pin::new(external_iface).poll_ready(cx) {
                    Poll::Ready(Ok(())) => (),
                    Poll::Ready(Err(_)) => {
                        self.external_iface_opt = None;
                    },
                    Poll::Pending => {
                        any_pending = true;
                    },
                }
            },
        }

        let mut defunct_indexes = Vec::new();
        for (index, internal_iface) in &mut self.internal_ifaces {
            match Pin::new(internal_iface).poll_ready(cx) {
                Poll::Ready(Ok(())) => (),
                Poll::Ready(Err(_)) => {
                    defunct_indexes.push(*index);
                },
                Poll::Pending => {
                    any_pending = true;
                },
            }
        }
        for index in defunct_indexes {
            self.internal_ifaces.remove(&index).unwrap();
        }
        if any_pending {
            Poll::Pending
        } else {
            Poll::Ready(())
        }
    }

    fn poll_next_incoming_external(&mut self, cx: &mut task::Context) -> Poll<Box<IpPacket>> {
        match &mut self.external_iface_opt {
            None => Poll::Pending,
            Some(external_iface) => {
                match Pin::new(external_iface).poll_next(cx) {
                    Poll::Ready(Some(Ok(packet))) => Poll::Ready(packet),
                    Poll::Ready(Some(Err(_))) | Poll::Ready(None) => {
                        self.external_iface_opt = None;
                        Poll::Pending
                    },
                    Poll::Pending => Poll::Pending,
                }
            },
        }
    }

    fn poll_next_incoming_internal(&mut self, cx: &mut task::Context) -> Poll<(usize, Box<IpPacket>)> {
        let mut defunct_indexes = Vec::new();
        let mut index_packet_opt = None;
        for (index, internal_iface) in &mut self.internal_ifaces {
            match Pin::new(internal_iface).poll_next(cx) {
                Poll::Ready(Some(Ok(packet))) => {
                    index_packet_opt = Some((*index, packet));
                    break;
                },
                Poll::Ready(Some(Err(_))) | Poll::Ready(None) => {
                    defunct_indexes.push(*index);
                },
                Poll::Pending => (),
            }
        }
        for index in defunct_indexes {
            self.internal_ifaces.remove(&index).unwrap();
        }
        match index_packet_opt {
            Some((index, packet)) => Poll::Ready((index, packet)),
            None => Poll::Pending,
        }
    }

    fn dispatch_incoming_external(&mut self, packet: Box<IpPacket>) {
        if log_enabled!(Level::Debug) {
            debug!("{}: received from external iface: {:?}", self.external_ipv4, packet);
        }

        match packet.version_box() {
            IpPacketVersion::V6(_) => (),
            IpPacketVersion::V4(packet) => {
                if packet.destination_addr() != self.external_ipv4 {
                    debug!(
                        "{}: dropping external packet addressed to different ip {}",
                        self.external_ipv4, packet.destination_addr(),
                    );
                    return;
                }
                match packet.protocol_box() {
                    Ipv4PacketProtocol::Tcp(mut packet) => {
                        let port = packet.destination_port();
                        let mapped_addr_opt = if self.tcpv4_restrictions.incoming_allowed(port, packet.source_addr()) {
                            self.tcpv4_port_map.incoming_addr(port)
                        } else {
                            None
                        };
                        let mapped_addr = match mapped_addr_opt {
                            Some(mapped_addr) => mapped_addr,
                            None => {
                                if self.reply_with_rst_to_unexpected_tcp_packets {
                                    let mut rst_packet = Tcpv4Packet::new();
                                    rst_packet.set_flags(TcpPacketFlags {
                                        rst: true,
                                        ack: true,
                                        .. TcpPacketFlags::default()
                                    });
                                    rst_packet.set_source_addr(packet.destination_addr());
                                    rst_packet.set_destination_addr(packet.source_addr());
                                    rst_packet.set_ack_number(packet.seq_number().wrapping_add(1));
                                    match &mut self.external_iface_opt {
                                        None => (),
                                        Some(external_iface) => {
                                            match Pin::new(external_iface).start_send(rst_packet.ip_packet_box()) {
                                                Ok(()) => (),
                                                Err(_) => {
                                                    self.external_iface_opt = None;
                                                },
                                            }
                                        },
                                    }
                                }
                                debug!(
                                    "{}: dropping external packet addressed to unmapped or disallowed port {}",
                                    self.external_ipv4, packet.destination_addr(),
                                );
                                return;
                            },
                        };
                        let iface_index = match self.internal_addr_indexes.get(&IpAddr::V4(*mapped_addr.ip())) {
                            Some(iface_index) => iface_index,
                            None => return,
                        };
                        let internal_iface = match self.internal_ifaces.get_mut(iface_index) {
                            Some(internal_iface) => internal_iface,
                            None => return,
                        };
                        packet.set_destination_addr(mapped_addr);
                        if log_enabled!(Level::Debug) {
                            debug!(
                                "{}: forwarding translated packet on internal iface #{} {:?}",
                                self.external_ipv4,
                                iface_index,
                                packet,
                            );
                        }
                        match Pin::new(internal_iface).start_send(packet.ip_packet_box()) {
                            Ok(()) => (),
                            Err(_) => {
                                self.internal_ifaces.remove(iface_index);
                            },
                        }
                    },
                    Ipv4PacketProtocol::Udp(mut packet) => {
                        let port = packet.destination_port();
                        let mapped_addr_opt = if self.udpv4_restrictions.incoming_allowed(port, packet.source_addr()) {
                            self.udpv4_port_map.incoming_addr(port)
                        } else {
                            None
                        };
                        let mapped_addr = match mapped_addr_opt {
                            Some(mapped_addr) => mapped_addr,
                            None => {
                                debug!(
                                    "{}: dropping external packet addressed to unmapped or disallowed port {}",
                                    self.external_ipv4, packet.destination_addr(),
                                );
                                return;
                            },
                        };
                        let iface_index = match self.internal_addr_indexes.get(&IpAddr::V4(*mapped_addr.ip())) {
                            Some(iface_index) => iface_index,
                            None => return,
                        };
                        let internal_iface = match self.internal_ifaces.get_mut(iface_index) {
                            Some(internal_iface) => internal_iface,
                            None => return,
                        };
                        packet.set_destination_addr(mapped_addr);
                        if log_enabled!(Level::Debug) {
                            debug!(
                                "{}: forwarding translated packet on internal iface #{} {:?}",
                                self.external_ipv4,
                                iface_index,
                                packet,
                            );
                        }
                        match Pin::new(internal_iface).start_send(packet.ip_packet_box()) {
                            Ok(()) => (),
                            Err(_) => {
                                self.internal_ifaces.remove(iface_index);
                            },
                        }
                    },
                    Ipv4PacketProtocol::Icmp(_) => (),
                    Ipv4PacketProtocol::Unknown { .. } => (),
                }
            },
        }
    }

    fn dispatch_incoming_internal(&mut self, iface_index: usize, packet: Box<IpPacket>) {
        if log_enabled!(Level::Debug) {
            debug!(
                "{}: received on internal iface #{}: {:?}",
                self.external_ipv4,
                iface_index,
                packet,
            );
        }

        match packet.version_box() {
            IpPacketVersion::V6(packet) => {
                self.internal_addr_indexes.insert(IpAddr::V6(packet.source_addr()), iface_index);
            },
            IpPacketVersion::V4(packet) => {
                if !self.internal_ipv4_network.contains(packet.source_addr()) {
                    debug!(
                        "{}: dropping internal packet from wrong network {}, {}",
                        self.external_ipv4, packet.source_addr(), self.internal_ipv4_network,
                    );
                    return;
                }
                self.internal_addr_indexes.insert(IpAddr::V4(packet.source_addr()), iface_index);
                let destination_ip = packet.destination_addr();
                if self.internal_ipv4_network.contains(destination_ip) {
                    let iface_index = match self.internal_addr_indexes.get(&IpAddr::V4(destination_ip)) {
                        Some(iface_index) => iface_index,
                        None => {
                            debug!(
                                "{}: dropping internal packet addressed to unknown internal device {}",
                                self.external_ipv4, packet.destination_addr(),
                            );
                            return;
                        },
                    };
                    let internal_iface = match self.internal_ifaces.get_mut(iface_index) {
                        Some(internal_iface) => internal_iface,
                        None => return,
                    };
                    match Pin::new(internal_iface).start_send(packet.ip_packet_box()) {
                        Ok(()) => (),
                        Err(_) => {
                            self.internal_ifaces.remove(iface_index);
                        },
                    }
                } else {
                    match packet.protocol_box() {
                        Ipv4PacketProtocol::Tcp(mut packet) => {
                            let internal_addr = packet.source_addr();
                            let port = self.tcpv4_port_map.outgoing_port(internal_addr);
                            self.tcpv4_restrictions.sending(port, packet.destination_addr());
                            packet.set_source_addr(SocketAddrV4::new(self.external_ipv4, port));
                            if log_enabled!(Level::Debug) {
                                debug!(
                                    "{}: translated outgoing packet {:?}",
                                    self.external_ipv4,
                                    packet,
                                );
                            }
                            if *packet.destination_addr().ip() == self.external_ipv4 {
                                if self.hair_pinning {
                                    self.dispatch_incoming_external(packet.ip_packet_box());
                                } else {
                                    debug!(
                                        "{}: dropped internal packet from {} addressed to own external address {} since hair-pinning is disabled",
                                        self.external_ipv4, packet.source_addr(), packet.destination_addr(),
                                    );
                                }
                            } else {
                                match &mut self.external_iface_opt {
                                    None => (),
                                    Some(external_iface) => {
                                        match Pin::new(external_iface).start_send(packet.ip_packet_box()) {
                                            Ok(()) => (),
                                            Err(_) => {
                                                self.external_iface_opt = None;
                                            },
                                        }
                                    },
                                }
                            }
                        },
                        Ipv4PacketProtocol::Udp(mut packet) => {
                            let internal_addr = packet.source_addr();
                            let port = self.udpv4_port_map.outgoing_port(internal_addr);
                            self.udpv4_restrictions.sending(port, packet.destination_addr());
                            packet.set_source_addr(SocketAddrV4::new(self.external_ipv4, port));
                            if log_enabled!(Level::Debug) {
                                debug!(
                                    "{}: translated outgoing packet {:?}",
                                    self.external_ipv4,
                                    packet,
                                );
                            }
                            if *packet.destination_addr().ip() == self.external_ipv4 {
                                if self.hair_pinning {
                                    self.dispatch_incoming_external(packet.ip_packet_box());
                                } else {
                                    debug!(
                                        "{}: dropped internal packet from {} addressed to own external address {} since hair-pinning is disabled",
                                        self.external_ipv4, packet.source_addr(), packet.destination_addr(),
                                    );
                                }
                            } else {
                                match &mut self.external_iface_opt {
                                    None => (),
                                    Some(external_iface) => {
                                        match Pin::new(external_iface).start_send(packet.ip_packet_box()) {
                                            Ok(()) => (),
                                            Err(_) => {
                                                self.external_iface_opt = None;
                                            },
                                        }
                                    },
                                }
                            }
                        },
                        Ipv4PacketProtocol::Icmp(_) => (),
                        Ipv4PacketProtocol::Unknown { .. } => (),
                    }
                }
            },
        }
    }

    fn poll_inner(&mut self, cx: &mut task::Context) -> Poll<()> {
        loop {
            match Pin::new(&mut self.iface_receiver).poll_next(cx) {
                Poll::Ready(Some(iface)) => {
                    self.internal_ifaces.insert(self.next_internal_iface_index, iface);
                    self.next_internal_iface_index += 1;
                },
                Poll::Ready(None) => return Poll::Ready(()),
                Poll::Pending => break,
            }
        }

        loop {
            match self.poll_ready_outgoing(cx) {
                Poll::Ready(()) => (),
                Poll::Pending => return Poll::Pending,
            }

            match self.poll_next_incoming_external(cx) {
                Poll::Ready(packet) => {
                    self.dispatch_incoming_external(packet);
                    continue;
                },
                Poll::Pending => (),
            }

            match self.poll_next_incoming_internal(cx) {
                Poll::Ready((index, packet)) => {
                    self.dispatch_incoming_internal(index, packet);
                    continue;
                },
                Poll::Pending => (),
            }

            break Poll::Pending;
        }
    }
}

impl Future for NatTask {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<()> {
        let this = self.get_mut();
        this.poll_inner(cx)
    }
}