xref: /freebsd/tests/sys/netpfil/pf/icmp.py (revision 32f793e2297619e1cb835c0938396ab6f6d0a6b3)
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 pytest
28import subprocess
29import re
30from atf_python.sys.net.tools import ToolsHelper
31from atf_python.sys.net.vnet import VnetTestTemplate
32
33def check(cmd):
34    ps = subprocess.Popen(cmd, shell=True)
35    ret = ps.wait()
36    if ret != 0:
37        raise Exception("Command %s returned %d" % (cmd, ret))
38
39class TestICMP(VnetTestTemplate):
40    REQUIRED_MODULES = [ "pf" ]
41    TOPOLOGY = {
42        "vnet1": {"ifaces": ["if1"]},
43        "vnet2": {"ifaces": ["if1", "if2"]},
44        "vnet3": {"ifaces": ["if2"]},
45        "if1": {"prefixes4": [("192.0.2.2/24", "192.0.2.1/24")]},
46        "if2": {"prefixes4": [("198.51.100.1/24", "198.51.100.2/24")]},
47    }
48
49    def vnet2_handler(self, vnet):
50        ifname = vnet.iface_alias_map["if1"].name
51        if2name = vnet.iface_alias_map["if2"].name
52
53        ToolsHelper.print_output("/sbin/pfctl -e")
54        ToolsHelper.pf_rules([
55            "set reassemble yes",
56            "set state-policy if-bound",
57            "block",
58            "pass inet proto icmp icmp-type echoreq",
59            ])
60
61        ToolsHelper.print_output("/sbin/sysctl net.inet.ip.forwarding=1")
62        ToolsHelper.print_output("/sbin/pfctl -x loud")
63
64        ToolsHelper.print_output("/sbin/ifconfig %s mtu 1492" % if2name)
65
66    def vnet3_handler(self, vnet):
67        # Import in the correct vnet, so at to not confuse Scapy
68        import scapy.all as sp
69
70        ifname = vnet.iface_alias_map["if2"].name
71        ToolsHelper.print_output("/sbin/route add default 198.51.100.1")
72        ToolsHelper.print_output("/sbin/ifconfig %s inet alias 198.51.100.3/24" % ifname)
73        ToolsHelper.print_output("/sbin/ifconfig %s mtu 1492" % ifname)
74
75        def checkfn(packet):
76            icmp = packet.getlayer(sp.ICMP)
77            if not icmp:
78                return False
79
80            if icmp.type != 3:
81                return False
82
83            packet.show()
84            return True
85
86        sp.sniff(iface=ifname, stop_filter=checkfn)
87        vnet.pipe.send("Got ICMP destination unreachable packet")
88
89    @pytest.mark.require_user("root")
90    @pytest.mark.require_progs(["scapy"])
91    def test_inner_match(self):
92        vnet = self.vnet_map["vnet1"]
93        dst_vnet = self.vnet_map["vnet3"]
94        sendif = vnet.iface_alias_map["if1"].name
95
96        our_mac = ToolsHelper.get_output("/sbin/ifconfig %s ether | awk '/ether/ { print $2; }'" % sendif)
97        dst_mac = re.sub("0a$", "0b", our_mac)
98
99        # Import in the correct vnet, so at to not confuse Scapy
100        import scapy.all as sp
101
102        ToolsHelper.print_output("/sbin/route add default 192.0.2.1")
103
104        # Sanity check
105        check("/sbin/ping -c 1 192.0.2.1")
106        check("/sbin/ping -c 1 198.51.100.1")
107        check("/sbin/ping -c 2 198.51.100.3")
108
109        # Establish a state
110        pkt = sp.Ether(src=our_mac, dst=dst_mac) \
111            / sp.IP(src="192.0.2.2", dst="198.51.100.2") \
112            / sp.ICMP(type='echo-request') \
113            / "PAYLOAD"
114        sp.sendp(pkt, sendif, verbose=False)
115
116        # Now try to pass an ICMP error message piggy-backing on that state, but
117        # use a different source address
118        pkt = sp.Ether(src=our_mac, dst=dst_mac) \
119            / sp.IP(src="192.0.2.2", dst="198.51.100.3") \
120            / sp.ICMP(type='dest-unreach') \
121            / sp.IP(src="198.51.100.2", dst="192.0.2.2") \
122            / sp.ICMP(type='echo-reply')
123        sp.sendp(pkt, sendif, verbose=False)
124
125        try:
126            rcvd = self.wait_object(dst_vnet.pipe, timeout=1)
127            if rcvd:
128                raise Exception(rcvd)
129        except TimeoutError as e:
130            # We expect the timeout here. It means we didn't get the destination
131            # unreachable packet in vnet3
132            pass
133
134    def check_icmp_echo(self, sp, payload_size):
135        packet = sp.IP(dst="198.51.100.2", flags="DF") \
136            / sp.ICMP(type='echo-request') \
137            / sp.raw(bytes.fromhex('f0') * payload_size)
138
139        p = sp.sr1(packet, iface=self.vnet.iface_alias_map["if1"].name,
140            timeout=3)
141        p.show()
142
143        ip = p.getlayer(sp.IP)
144        icmp = p.getlayer(sp.ICMP)
145        assert ip
146        assert icmp
147
148        if payload_size > 1464:
149            # Expect ICMP destination unreachable, fragmentation needed
150            assert ip.src == "192.0.2.1"
151            assert ip.dst == "192.0.2.2"
152            assert icmp.type == 3 # dest-unreach
153            assert icmp.code == 4
154            assert icmp.nexthopmtu == 1492
155        else:
156            # Expect echo reply
157            assert ip.src == "198.51.100.2"
158            assert ip.dst == "192.0.2.2"
159            assert icmp.type == 0 # "echo-reply"
160            assert icmp.code == 0
161
162        return
163
164    @pytest.mark.require_user("root")
165    @pytest.mark.require_progs(["scapy"])
166    def test_fragmentation_needed(self):
167        ToolsHelper.print_output("/sbin/route add default 192.0.2.1")
168
169        ToolsHelper.print_output("/sbin/ping -c 1 198.51.100.2")
170        ToolsHelper.print_output("/sbin/ping -c 1 -D -s 1472 198.51.100.2")
171
172        # Import in the correct vnet, so at to not confuse Scapy
173        import scapy.all as sp
174
175        self.check_icmp_echo(sp, 128)
176        self.check_icmp_echo(sp, 1464)
177        self.check_icmp_echo(sp, 1468)
178
179class TestICMP_NAT(VnetTestTemplate):
180    REQUIRED_MODULES = [ "pf" ]
181    TOPOLOGY = {
182        "vnet1": {"ifaces": ["if1"]},
183        "vnet2": {"ifaces": ["if1", "if2"]},
184        "vnet3": {"ifaces": ["if2"]},
185        "if1": {"prefixes4": [("192.0.2.2/24", "192.0.2.1/24")]},
186        "if2": {"prefixes4": [("198.51.100.1/24", "198.51.100.2/24")]},
187    }
188
189    def vnet2_handler(self, vnet):
190        ifname = vnet.iface_alias_map["if1"].name
191        if2name = vnet.iface_alias_map["if2"].name
192
193        ToolsHelper.print_output("/sbin/pfctl -e")
194        ToolsHelper.pf_rules([
195            "set reassemble yes",
196            "set state-policy if-bound",
197            "nat on %s inet from 192.0.2.0/24 to any -> (%s)" % (if2name, if2name),
198            "block",
199            "pass inet proto icmp icmp-type echoreq",
200            ])
201
202        ToolsHelper.print_output("/sbin/sysctl net.inet.ip.forwarding=1")
203        ToolsHelper.print_output("/sbin/pfctl -x loud")
204
205    def vnet3_handler(self, vnet):
206        ifname = vnet.iface_alias_map["if2"].name
207        ToolsHelper.print_output("/sbin/ifconfig %s inet alias 198.51.100.3/24" % ifname)
208
209    @pytest.mark.require_user("root")
210    @pytest.mark.require_progs(["scapy"])
211    def test_id_conflict(self):
212        """
213            Test ICMP echo requests with the same ID from different clients.
214            Windows does this, and it can confuse pf.
215        """
216        ifname = self.vnet.iface_alias_map["if1"].name
217        ToolsHelper.print_output("/sbin/route add default 192.0.2.1")
218        ToolsHelper.print_output("/sbin/ifconfig %s inet alias 192.0.2.3/24" % ifname)
219
220        ToolsHelper.print_output("/sbin/ping -c 1 192.0.2.1")
221        ToolsHelper.print_output("/sbin/ping -c 1 198.51.100.1")
222        ToolsHelper.print_output("/sbin/ping -c 1 198.51.100.2")
223        ToolsHelper.print_output("/sbin/ping -c 1 198.51.100.3")
224
225        # Import in the correct vnet, so at to not confuse Scapy
226        import scapy.all as sp
227
228        # Address one
229        packet = sp.IP(src="192.0.2.2", dst="198.51.100.2", flags="DF") \
230            / sp.ICMP(type='echo-request', id=42) \
231            / sp.raw(bytes.fromhex('f0') * 16)
232
233        p = sp.sr1(packet, timeout=3)
234        p.show()
235        ip = p.getlayer(sp.IP)
236        icmp = p.getlayer(sp.ICMP)
237        assert ip
238        assert icmp
239        assert ip.dst == "192.0.2.2"
240        assert icmp.id == 42
241
242        # Address one
243        packet = sp.IP(src="192.0.2.3", dst="198.51.100.2", flags="DF") \
244            / sp.ICMP(type='echo-request', id=42) \
245            / sp.raw(bytes.fromhex('f0') * 16)
246
247        p = sp.sr1(packet, timeout=3)
248        p.show()
249        ip = p.getlayer(sp.IP)
250        icmp = p.getlayer(sp.ICMP)
251        assert ip
252        assert icmp
253        assert ip.dst == "192.0.2.3"
254        assert icmp.id == 42
255