xref: /freebsd/tests/sys/netpfil/pf/nat66.py (revision b985c9ca)
1#
2# SPDX-License-Identifier: BSD-2-Clause
3#
4# Copyright (c) 2024 Rubicon Communications, LLC (Netgate)
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9# 1. Redistributions of source code must retain the above copyright
10#    notice, this list of conditions and the following disclaimer.
11# 2. Redistributions in binary form must reproduce the above copyright
12#    notice, this list of conditions and the following disclaimer in the
13#    documentation and/or other materials provided with the distribution.
14#
15# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25# SUCH DAMAGE.
26
27import ctypes
28import ipaddress
29import pytest
30import re
31import socket
32import threading
33import time
34from atf_python.sys.net.tools import ToolsHelper
35from atf_python.sys.net.vnet import VnetTestTemplate
36
37class DelayedSend(threading.Thread):
38    def __init__(self, packet):
39        threading.Thread.__init__(self)
40        self._packet = packet
41
42        self.start()
43
44    def run(self):
45        import scapy.all as sp
46        time.sleep(1)
47        sp.send(self._packet)
48
49class TestNAT66(VnetTestTemplate):
50    REQUIRED_MODULES = [ "pf" ]
51    TOPOLOGY = {
52        "vnet1": {"ifaces": ["if1"]},
53        "vnet2": {"ifaces": ["if1", "if2"]},
54        "vnet3": {"ifaces": ["if2"]},
55        "if1": {"prefixes6": [("2001:db8::2/64", "2001:db8::1/64")]},
56        "if2": {"prefixes6": [("2001:db8:1::1/64", "2001:db8:1::2/64")]},
57    }
58
59    def vnet2_handler(self, vnet):
60        ifname = vnet.iface_alias_map["if1"].name
61        ToolsHelper.print_output("/sbin/ifconfig %s mtu 9000" % ifname)
62        outifname = vnet.iface_alias_map["if2"].name
63
64        ToolsHelper.print_output("/sbin/pfctl -e")
65        ToolsHelper.pf_rules([
66            "set reassemble yes",
67            "binat inet6 from 2001:db8::/64 to 2001:db8:1::/64 -> 2001:db8:42::/64",
68            "binat inet6 from 2001:db8:1::/64 to 2001:db8:42::/64 -> 2001:db8::/64",
69            "pass inet6 proto icmp6",
70            "pass in route-to ( %s 2001:db8:1::2 ) inet6 from 2001:db8::3 to 2001:db8:1::/64" % outifname])
71
72        ToolsHelper.print_output("/sbin/sysctl net.inet6.ip6.forwarding=1")
73
74    def vnet3_handler(self, vnet):
75        ToolsHelper.print_output("/sbin/route add -6 2001:db8:42::/64 2001:db8:1::1")
76
77    def check_icmp_too_big(self, sp, payload_size, frag_size=None, src="2001:db8::2"):
78        packet = sp.IPv6(src=src, dst="2001:db8:1::2") \
79            / sp.ICMPv6EchoRequest(data=sp.raw(bytes.fromhex('f0') * payload_size))
80
81        if frag_size is not None:
82            packet = sp.fragment6(packet, frag_size)
83
84        # Delay the send so the sniffer is running when we transmit.
85        s = DelayedSend(packet)
86
87        packets = sp.sniff(iface=self.vnet.iface_alias_map["if1"].name,
88            timeout=3)
89        found=False
90        for p in packets:
91            # We can't get a reply to this
92            assert not p.getlayer(sp.ICMPv6EchoReply)
93
94            if not p.getlayer(sp.ICMPv6PacketTooBig):
95                continue
96
97            ip6 = p.getlayer(sp.IPv6)
98            icmp6 = p.getlayer(sp.ICMPv6PacketTooBig)
99
100            # Error is from the router vnet
101            assert ip6.src == "2001:db8::1"
102            assert ip6.dst == src
103
104            # And the relevant MTU is 1500
105            assert icmp6.mtu == 1500
106
107            # The icmp6 error contains our original IPv6 packet
108            err = icmp6.getlayer(sp.IPerror6)
109            assert err.src == src
110            assert err.dst == "2001:db8:1::2"
111            assert err.nh == 58
112
113            found = True
114
115        assert found
116
117    def check_icmp_echo(self, sp, payload_size, src="2001:db8::2"):
118        packet = sp.IPv6(src=src, dst="2001:db8:1::2") \
119            / sp.ICMPv6EchoRequest(data=sp.raw(bytes.fromhex('f0') * payload_size))
120
121        # Delay the send so the sniffer is running when we transmit.
122        s = DelayedSend(packet)
123
124        packets = sp.sniff(iface=self.vnet.iface_alias_map["if1"].name,
125            timeout=3)
126        found=False
127        for p in packets:
128            if not p.getlayer(sp.ICMPv6EchoReply):
129                continue
130
131            ip6 = p.getlayer(sp.IPv6)
132            icmp6 = p.getlayer(sp.ICMPv6EchoReply)
133
134            # Error is from the router vnet
135            assert ip6.src == "2001:db8:1::2"
136            assert ip6.dst == src
137
138            found = True
139
140        assert found
141
142    @pytest.mark.require_user("root")
143    def test_npt_icmp(self):
144        cl_vnet = self.vnet_map["vnet1"]
145        ifname = cl_vnet.iface_alias_map["if1"].name
146        ToolsHelper.print_output("/sbin/ifconfig %s mtu 9000" % ifname)
147
148        ToolsHelper.print_output("/sbin/route add -6 2001:db8:1::/64 2001:db8::1")
149
150        # For unclear reasons vnet3 doesn't respond to the first ping.
151        # Just send two for now.
152        ToolsHelper.print_output("/sbin/ping -6 -c 1 2001:db8:1::2")
153        ToolsHelper.print_output("/sbin/ping -6 -c 1 2001:db8:1::2")
154
155        # Import in the correct vnet, so at to not confuse Scapy
156        import scapy.all as sp
157
158        # A ping that easily passes without fragmentation
159        self.check_icmp_echo(sp, 128)
160
161        # Send a ping that just barely doesn't need to be fragmented
162        self.check_icmp_echo(sp, 1452)
163
164        # Send a ping that just barely needs to be fragmented
165        self.check_icmp_too_big(sp, 1453)
166
167        # A ping that arrives fragmented
168        self.check_icmp_too_big(sp, 12000, 5000)
169
170    @pytest.mark.require_user("root")
171    def test_npt_route_to_icmp(self):
172        cl_vnet = self.vnet_map["vnet1"]
173        ifname = cl_vnet.iface_alias_map["if1"].name
174        ToolsHelper.print_output("/sbin/ifconfig %s mtu 9000" % ifname)
175        ToolsHelper.print_output("/sbin/ifconfig %s inet6 alias 2001:db8::3/64" % ifname)
176
177        ToolsHelper.print_output("/sbin/route add -6 2001:db8:1::/64 2001:db8::1")
178
179        # For unclear reasons vnet3 doesn't respond to the first ping.
180        # Just send two for now.
181        ToolsHelper.print_output("/sbin/ping -6 -c 1 -S 2001:db8::3 2001:db8:1::2")
182        ToolsHelper.print_output("/sbin/ping -6 -c 1 -S 2001:db8::3 2001:db8:1::2")
183
184        # Import in the correct vnet, so at to not confuse Scapy
185        import scapy.all as sp
186
187        # A ping that easily passes without fragmentation
188        self.check_icmp_echo(sp, 128, src="2001:db8::3")
189
190        # Send a ping that just barely doesn't need to be fragmented
191        self.check_icmp_echo(sp, 1452, src="2001:db8::3")
192
193        # Send a ping that just barely needs to be fragmented
194        self.check_icmp_too_big(sp, 1453, src="2001:db8::3")
195
196        # A ping that arrives fragmented
197        self.check_icmp_too_big(sp, 12000, 5000, src="2001:db8::3")
198