xref: /freebsd/tests/sys/netpfil/pf/icmp.py (revision 65cc5af1cf88ed124ab16091624e918faa61c7f2)
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            "block",
57            "pass inet proto icmp icmp-type echoreq",
58            ])
59
60        ToolsHelper.print_output("/sbin/sysctl net.inet.ip.forwarding=1")
61        ToolsHelper.print_output("/sbin/pfctl -x loud")
62
63        ToolsHelper.print_output("/sbin/ifconfig %s mtu 1492" % if2name)
64
65    def vnet3_handler(self, vnet):
66        # Import in the correct vnet, so at to not confuse Scapy
67        import scapy.all as sp
68
69        ifname = vnet.iface_alias_map["if2"].name
70        ToolsHelper.print_output("/sbin/route add default 198.51.100.1")
71        ToolsHelper.print_output("/sbin/ifconfig %s inet alias 198.51.100.3/24" % ifname)
72        ToolsHelper.print_output("/sbin/ifconfig %s mtu 1492" % ifname)
73
74        def checkfn(packet):
75            icmp = packet.getlayer(sp.ICMP)
76            if not icmp:
77                return False
78
79            if icmp.type != 3:
80                return False
81
82            packet.show()
83            return True
84
85        sp.sniff(iface=ifname, stop_filter=checkfn)
86        vnet.pipe.send("Got ICMP destination unreachable packet")
87
88    @pytest.mark.require_user("root")
89    @pytest.mark.require_progs(["scapy"])
90    def test_inner_match(self):
91        vnet = self.vnet_map["vnet1"]
92        dst_vnet = self.vnet_map["vnet3"]
93        sendif = vnet.iface_alias_map["if1"].name
94
95        our_mac = ToolsHelper.get_output("/sbin/ifconfig %s ether | awk '/ether/ { print $2; }'" % sendif)
96        dst_mac = re.sub("0a$", "0b", our_mac)
97
98        # Import in the correct vnet, so at to not confuse Scapy
99        import scapy.all as sp
100
101        ToolsHelper.print_output("/sbin/route add default 192.0.2.1")
102
103        # Sanity check
104        check("/sbin/ping -c 1 192.0.2.1")
105        check("/sbin/ping -c 1 198.51.100.1")
106        check("/sbin/ping -c 2 198.51.100.3")
107
108        # Establish a state
109        pkt = sp.Ether(src=our_mac, dst=dst_mac) \
110            / sp.IP(src="192.0.2.2", dst="198.51.100.2") \
111            / sp.ICMP(type='echo-request') \
112            / "PAYLOAD"
113        sp.sendp(pkt, sendif, verbose=False)
114
115        # Now try to pass an ICMP error message piggy-backing on that state, but
116        # use a different source address
117        pkt = sp.Ether(src=our_mac, dst=dst_mac) \
118            / sp.IP(src="192.0.2.2", dst="198.51.100.3") \
119            / sp.ICMP(type='dest-unreach') \
120            / sp.IP(src="198.51.100.2", dst="192.0.2.2") \
121            / sp.ICMP(type='echo-reply')
122        sp.sendp(pkt, sendif, verbose=False)
123
124        try:
125            rcvd = self.wait_object(dst_vnet.pipe, timeout=1)
126            if rcvd:
127                raise Exception(rcvd)
128        except TimeoutError as e:
129            # We expect the timeout here. It means we didn't get the destination
130            # unreachable packet in vnet3
131            pass
132
133    def check_icmp_echo(self, sp, payload_size):
134        packet = sp.IP(dst="198.51.100.2", flags="DF") \
135            / sp.ICMP(type='echo-request') \
136            / sp.raw(bytes.fromhex('f0') * payload_size)
137
138        p = sp.sr1(packet, iface=self.vnet.iface_alias_map["if1"].name,
139            timeout=3)
140        p.show()
141
142        ip = p.getlayer(sp.IP)
143        icmp = p.getlayer(sp.ICMP)
144        assert ip
145        assert icmp
146
147        if payload_size > 1464:
148            # Expect ICMP destination unreachable, fragmentation needed
149            assert ip.src == "192.0.2.1"
150            assert ip.dst == "192.0.2.2"
151            assert icmp.type == 3 # dest-unreach
152            assert icmp.code == 4
153            assert icmp.nexthopmtu == 1492
154        else:
155            # Expect echo reply
156            assert ip.src == "198.51.100.2"
157            assert ip.dst == "192.0.2.2"
158            assert icmp.type == 0 # "echo-reply"
159            assert icmp.code == 0
160
161        return
162
163    @pytest.mark.require_user("root")
164    @pytest.mark.require_progs(["scapy"])
165    def test_fragmentation_needed(self):
166        ToolsHelper.print_output("/sbin/route add default 192.0.2.1")
167
168        ToolsHelper.print_output("/sbin/ping -c 1 198.51.100.2")
169        ToolsHelper.print_output("/sbin/ping -c 1 -D -s 1472 198.51.100.2")
170
171        # Import in the correct vnet, so at to not confuse Scapy
172        import scapy.all as sp
173
174        self.check_icmp_echo(sp, 128)
175        self.check_icmp_echo(sp, 1464)
176        self.check_icmp_echo(sp, 1468)
177