xref: /freebsd-13-stable/tests/sys/netpfil/common/pft_ping.py (revision 48a202f5b2190f89c4a755c36155a054b721a19e)
1#!/usr/bin/env python3
2#
3# SPDX-License-Identifier: BSD-2-Clause
4#
5# Copyright (c) 2017 Kristof Provost <kp@FreeBSD.org>
6# Copyright (c) 2023 Kajetan Staszkiewicz <vegeta@tuxpowered.net>
7#
8# Redistribution and use in source and binary forms, with or without
9# modification, are permitted provided that the following conditions
10# are met:
11# 1. Redistributions of source code must retain the above copyright
12#    notice, this list of conditions and the following disclaimer.
13# 2. Redistributions in binary form must reproduce the above copyright
14#    notice, this list of conditions and the following disclaimer in the
15#    documentation and/or other materials provided with the distribution.
16#
17# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27# SUCH DAMAGE.
28#
29
30import argparse
31import logging
32logging.getLogger("scapy").setLevel(logging.CRITICAL)
33import math
34import scapy.all as sp
35import sys
36
37from copy import copy
38from sniffer import Sniffer
39
40logging.basicConfig(format='%(message)s')
41LOGGER = logging.getLogger(__name__)
42
43PAYLOAD_MAGIC = bytes.fromhex('42c0ffee')
44
45def build_payload(l):
46    pl = len(PAYLOAD_MAGIC)
47    ret = PAYLOAD_MAGIC * math.floor(l/pl)
48    ret += PAYLOAD_MAGIC[0:(l % pl)]
49    return ret
50
51
52def prepare_ipv6(dst_address, send_params):
53    src_address = send_params.get('src_address')
54    hlim = send_params.get('hlim')
55    tc = send_params.get('tc')
56    ip6 = sp.IPv6(dst=dst_address)
57    if src_address:
58        ip6.src = src_address
59    if hlim:
60        ip6.hlim = hlim
61    if tc:
62        ip6.tc = tc
63    return ip6
64
65
66def prepare_ipv4(dst_address, send_params):
67    src_address = send_params.get('src_address')
68    flags = send_params.get('flags')
69    tos = send_params.get('tc')
70    ttl = send_params.get('hlim')
71    ip = sp.IP(dst=dst_address)
72    if src_address:
73        ip.src = src_address
74    if flags:
75        ip.flags = flags
76    if tos:
77        ip.tos = tos
78    if ttl:
79        ip.ttl = ttl
80    return ip
81
82
83def send_icmp_ping(dst_address, sendif, send_params):
84    send_length = send_params['length']
85    ether = sp.Ether()
86    if ':' in dst_address:
87        ip6 = prepare_ipv6(dst_address, send_params)
88        icmp = sp.ICMPv6EchoRequest(data=sp.raw(build_payload(send_length)))
89        req = ether / ip6 / icmp
90    else:
91        ip = prepare_ipv4(dst_address, send_params)
92        icmp = sp.ICMP(type='echo-request')
93        raw = sp.raw(build_payload(send_length))
94        req = ether / ip / icmp / raw
95    sp.sendp(req, sendif, verbose=False)
96
97
98def send_tcp_syn(dst_address, sendif, send_params):
99    tcpopt_unaligned = send_params.get('tcpopt_unaligned')
100    seq = send_params.get('seq')
101    mss = send_params.get('mss')
102    ether = sp.Ether()
103    opts=[('Timestamp', (1, 1)), ('MSS', mss if mss else 1280)]
104    if tcpopt_unaligned:
105        opts = [('NOP', 0 )] + opts
106    if ':' in dst_address:
107        ip = prepare_ipv6(dst_address, send_params)
108    else:
109        ip = prepare_ipv4(dst_address, send_params)
110    tcp = sp.TCP(dport=666, flags='S', options=opts, seq=seq)
111    req = ether / ip / tcp
112    sp.sendp(req, iface=sendif, verbose=False)
113
114
115def send_ping(dst_address, sendif, ping_type, send_params):
116    if ping_type == 'icmp':
117        send_icmp_ping(dst_address, sendif, send_params)
118    elif ping_type == 'tcpsyn':
119        send_tcp_syn(dst_address, sendif, send_params)
120    else:
121        raise Exception('Unspported ping type')
122
123
124def check_ipv4(expect_params, packet):
125    src_address = expect_params.get('src_address')
126    dst_address = expect_params.get('dst_address')
127    flags = expect_params.get('flags')
128    tos = expect_params.get('tc')
129    ttl = expect_params.get('hlim')
130    ip = packet.getlayer(sp.IP)
131    if not ip:
132        LOGGER.debug('Packet is not IPv4!')
133        return False
134    if src_address and ip.src != src_address:
135        LOGGER.debug('Source IPv4 address does not match!')
136        return False
137    if dst_address and ip.dst != dst_address:
138        LOGGER.debug('Destination IPv4 address does not match!')
139        return False
140    if flags and ip.flags != flags:
141        LOGGER.debug(f'Wrong IP flags value {ip.flags}, expected {flags}')
142        return False
143    if tos and ip.tos != tos:
144        LOGGER.debug(f'Wrong ToS value {ip.tos}, expected {tos}')
145        return False
146    if ttl and ip.ttl != ttl:
147        LOGGER.debug(f'Wrong TTL value {ip.ttl}, expected {ttl}')
148        return False
149    return True
150
151
152def check_ipv6(expect_params, packet):
153    src_address = expect_params.get('src_address')
154    dst_address = expect_params.get('dst_address')
155    flags = expect_params.get('flags')
156    hlim = expect_params.get('hlim')
157    tc = expect_params.get('tc')
158    ip6 = packet.getlayer(sp.IPv6)
159    if not ip6:
160        LOGGER.debug('Packet is not IPv6!')
161        return False
162    if src_address and ip6.src != src_address:
163        LOGGER.debug('Source IPv6 address does not match!')
164        return False
165    if dst_address and ip6.dst != dst_address:
166        LOGGER.debug('Destination IPv6 address does not match!')
167        return False
168    # IPv6 has no IP-level checksum.
169    if flags:
170        raise Exception("There's no fragmentation flags in IPv6")
171    if hlim and ip6.hlim != hlim:
172        LOGGER.debug(f'Wrong Hop Limit value {ip6.hlim}, expected {hlim}')
173        return False
174    if tc and ip6.tc != tc:
175        LOGGER.debug(f'Wrong TC value {ip6.tc}, expected {tc}')
176        return False
177    return True
178
179def check_ping_4(expect_params, packet):
180    expect_length = expect_params['length']
181    if not check_ipv4(expect_params, packet):
182        return False
183    icmp = packet.getlayer(sp.ICMP)
184    if not icmp:
185        LOGGER.debug('Packet is not IPv4 ICMP!')
186        return False
187    raw = packet.getlayer(sp.Raw)
188    if not raw:
189        LOGGER.debug('Packet contains no payload!')
190        return False
191    if raw.load != build_payload(expect_length):
192        LOGGER.debug('Payload magic does not match!')
193        return False
194    return True
195
196def check_ping_request_4(expect_params, packet):
197    if not check_ping_4(expect_params, packet):
198        return False
199    icmp = packet.getlayer(sp.ICMP)
200    if sp.icmptypes[icmp.type] != 'echo-request':
201        LOGGER.debug('Packet is not IPv4 ICMP Echo Request!')
202        return False
203    return True
204
205
206def check_ping_reply_4(expect_params, packet):
207    if not check_ping_4(expect_params, packet):
208        return False
209    icmp = packet.getlayer(sp.ICMP)
210    if sp.icmptypes[icmp.type] != 'echo-reply':
211        LOGGER.debug('Packet is not IPv4 ICMP Echo Reply!')
212        return False
213    return True
214
215
216def check_ping_request_6(expect_params, packet):
217    expect_length = expect_params['length']
218    if not check_ipv6(expect_params, packet):
219        return False
220    icmp = packet.getlayer(sp.ICMPv6EchoRequest)
221    if not icmp:
222        LOGGER.debug('Packet is not IPv6 ICMP Echo Request!')
223        return False
224    if icmp.data != build_payload(expect_length):
225        LOGGER.debug('Payload magic does not match!')
226        return False
227    return True
228
229
230def check_ping_reply_6(expect_params, packet):
231    expect_length = expect_params['length']
232    if not check_ipv6(expect_params, packet):
233        return False
234    icmp = packet.getlayer(sp.ICMPv6EchoReply)
235    if not icmp:
236        LOGGER.debug('Packet is not IPv6 ICMP Echo Reply!')
237        return False
238    if icmp.data != build_payload(expect_length):
239        LOGGER.debug('Payload magic does not match!')
240        return False
241    return True
242
243
244def check_ping_request(expect_params, packet):
245    src_address = expect_params.get('src_address')
246    dst_address = expect_params.get('dst_address')
247    if not (src_address or dst_address):
248        raise Exception('Source or destination address must be given to match the ping request!')
249    if (
250        (src_address and ':' in src_address) or
251        (dst_address and ':' in dst_address)
252    ):
253        return check_ping_request_6(expect_params, packet)
254    else:
255        return check_ping_request_4(expect_params, packet)
256
257def check_ping_reply(expect_params, packet):
258    src_address = expect_params.get('src_address')
259    dst_address = expect_params.get('dst_address')
260    if not (src_address or dst_address):
261        raise Exception('Source or destination address must be given to match the ping reply!')
262    if (
263        (src_address and ':' in src_address) or
264        (dst_address and ':' in dst_address)
265    ):
266        return check_ping_reply_6(expect_params, packet)
267    else:
268        return check_ping_reply_4(expect_params, packet)
269
270def check_tcp(expect_params, packet):
271    tcp_flags = expect_params.get('tcp_flags')
272    mss = expect_params.get('mss')
273    seq = expect_params.get('seq')
274    tcp = packet.getlayer(sp.TCP)
275    if not tcp:
276        LOGGER.debug('Packet is not TCP!')
277        return False
278    chksum = tcp.chksum
279    tcp.chksum = None
280    newpacket = sp.Ether(sp.raw(packet[sp.Ether]))
281    new_chksum = newpacket[sp.TCP].chksum
282    if chksum != new_chksum:
283        LOGGER.debug(f'Wrong TCP checksum {chksum}, expected {new_chksum}!')
284        return False
285    if tcp_flags and tcp.flags != tcp_flags:
286        LOGGER.debug(f'Wrong TCP flags {tcp.flags}, expected {tcp_flags}!')
287        return False
288    if seq:
289        if tcp_flags == 'S':
290            tcp_seq = tcp.seq
291        elif tcp_flags == 'SA':
292            tcp_seq = tcp.ack - 1
293        if seq != tcp_seq:
294            LOGGER.debug(f'Wrong TCP Sequence Number {tcp_seq}, expected {seq}')
295            return False
296    if mss:
297        for option in tcp.options:
298            if option[0] == 'MSS':
299                if option[1] != mss:
300                    LOGGER.debug(f'Wrong TCP MSS {option[1]}, expected {mss}')
301                    return False
302    return True
303
304
305def check_tcp_syn_request_4(expect_params, packet):
306    if not check_ipv4(expect_params, packet):
307        return False
308    if not check_tcp(expect_params | {'tcp_flags': 'S'}, packet):
309        return False
310    return True
311
312
313def check_tcp_syn_reply_4(expect_params, packet):
314    if not check_ipv4(expect_params, packet):
315        return False
316    if not check_tcp(expect_params | {'tcp_flags': 'SA'}, packet):
317        return False
318    return True
319
320
321def check_tcp_syn_request_6(expect_params, packet):
322    if not check_ipv6(expect_params, packet):
323        return False
324    if not check_tcp(expect_params | {'tcp_flags': 'S'}, packet):
325        return False
326    return True
327
328
329def check_tcp_syn_reply_6(expect_params, packet):
330    if not check_ipv6(expect_params, packet):
331        return False
332    if not check_tcp(expect_params | {'tcp_flags': 'SA'}, packet):
333        return False
334    return True
335
336
337def check_tcp_syn_request(expect_params, packet):
338    src_address = expect_params.get('src_address')
339    dst_address = expect_params.get('dst_address')
340    if not (src_address or dst_address):
341        raise Exception('Source or destination address must be given to match the tcp syn request!')
342    if (
343        (src_address and ':' in src_address) or
344        (dst_address and ':' in dst_address)
345    ):
346        return check_tcp_syn_request_6(expect_params, packet)
347    else:
348        return check_tcp_syn_request_4(expect_params, packet)
349
350
351def check_tcp_syn_reply(expect_params, packet):
352    src_address = expect_params.get('src_address')
353    dst_address = expect_params.get('dst_address')
354    if not (src_address or dst_address):
355        raise Exception('Source or destination address must be given to match the tcp syn reply!')
356    if (
357        (src_address and ':' in src_address) or
358        (dst_address and ':' in dst_address)
359    ):
360        return check_tcp_syn_reply_6(expect_params, packet)
361    else:
362        return check_tcp_syn_reply_4(expect_params, packet)
363
364
365def setup_sniffer(recvif, ping_type, sniff_type, expect_params):
366    if ping_type == 'icmp' and sniff_type == 'request':
367        checkfn = check_ping_request
368    elif ping_type == 'icmp' and sniff_type == 'reply':
369        checkfn = check_ping_reply
370    elif ping_type == 'tcpsyn' and sniff_type == 'request':
371        checkfn = check_tcp_syn_request
372    elif ping_type == 'tcpsyn' and sniff_type == 'reply':
373        checkfn = check_tcp_syn_reply
374    else:
375        raise Exception('Unspported ping or sniff type')
376
377    return Sniffer(expect_params, checkfn, recvif)
378
379
380def parse_args():
381    parser = argparse.ArgumentParser("pft_ping.py",
382        description="Ping test tool")
383
384    # Parameters of sent ping request
385    parser.add_argument('--sendif', nargs=1,
386        required=True,
387        help='The interface through which the packet(s) will be sent')
388    parser.add_argument('--to', nargs=1,
389        required=True,
390        help='The destination IP address for the ping request')
391    parser.add_argument('--ping-type',
392        choices=('icmp', 'tcpsyn'),
393        help='Type of ping: ICMP (default) or TCP SYN',
394        default='icmp')
395    parser.add_argument('--fromaddr', nargs=1,
396        help='The source IP address for the ping request')
397
398    # Where to look for packets to analyze.
399    # The '+' format is ugly as it mixes positional with optional syntax.
400    # But we have no positional parameters so I guess it's fine to use it.
401    parser.add_argument('--recvif', nargs='+',
402        help='The interfaces on which to expect the ping request')
403    parser.add_argument('--replyif', nargs='+',
404        help='The interfaces which to expect the ping response')
405
406    # Packet settings
407    parser_send = parser.add_argument_group('Values set in transmitted packets')
408    parser_send.add_argument('--send-flags', nargs=1, type=str,
409        help='IPv4 fragmentation flags')
410    parser_send.add_argument('--send-hlim', nargs=1, type=int,
411        help='IPv6 Hop Limit or IPv4 Time To Live')
412    parser_send.add_argument('--send-mss', nargs=1, type=int,
413        help='TCP Maximum Segment Size')
414    parser_send.add_argument('--send-seq', nargs=1, type=int,
415        help='TCP sequence number')
416    parser_send.add_argument('--send-length', nargs=1, type=int,
417        default=[len(PAYLOAD_MAGIC)], help='ICMP Echo Request payload size')
418    parser_send.add_argument('--send-tc', nargs=1, type=int,
419        help='IPv6 Traffic Class or IPv4 DiffServ / ToS')
420    parser_send.add_argument('--send-tcpopt-unaligned', action='store_true',
421            help='Include unaligned TCP options')
422
423    # Expectations
424    parser_expect = parser.add_argument_group('Values expected in sniffed packets')
425    parser_expect.add_argument('--expect-flags', nargs=1, type=str,
426        help='IPv4 fragmentation flags')
427    parser_expect.add_argument('--expect-hlim', nargs=1, type=int,
428        help='IPv6 Hop Limit or IPv4 Time To Live')
429    parser_expect.add_argument('--expect-mss', nargs=1, type=int,
430        help='TCP Maximum Segment Size')
431    parser_send.add_argument('--expect-seq', nargs=1, type=int,
432        help='TCP sequence number')
433    parser_expect.add_argument('--expect-tc', nargs=1, type=int,
434        help='IPv6 Traffic Class or IPv4 DiffServ / ToS')
435
436    parser.add_argument('-v', '--verbose', action='store_true',
437        help=('Enable verbose logging. Apart of potentially useful information '
438            'you might see warnings from parsing packets like NDP or other '
439            'packets not related to the test being run. Use only when '
440            'developing because real tests expect empty stderr and stdout.'))
441
442    return parser.parse_args()
443
444
445def main():
446    args = parse_args()
447
448    if args.verbose:
449        LOGGER.setLevel(logging.DEBUG)
450
451    # Dig out real values of program arguments
452    send_if = args.sendif[0]
453    reply_ifs = args.replyif
454    recv_ifs = args.recvif
455    dst_address = args.to[0]
456
457    # Standardize parameters which have nargs=1.
458    send_params = {}
459    expect_params = {}
460    for param_name in ('flags', 'hlim', 'length', 'mss', 'seq', 'tc'):
461        param_arg = vars(args).get(f'send_{param_name}')
462        send_params[param_name] = param_arg[0] if param_arg else None
463        param_arg = vars(args).get(f'expect_{param_name}')
464        expect_params[param_name] = param_arg[0] if param_arg else None
465
466    expect_params['length'] = send_params['length']
467    send_params['tcpopt_unaligned'] = args.send_tcpopt_unaligned
468    send_params['src_address'] = args.fromaddr[0] if args.fromaddr else None
469
470    # We may not have a default route. Tell scapy where to start looking for routes
471    sp.conf.iface6 = send_if
472
473    # Configuration sanity checking.
474    if not (reply_ifs or recv_ifs):
475        raise Exception('With no reply or recv interface specified no traffic '
476            'can be sniffed and verified!'
477        )
478
479    sniffers = []
480
481    if recv_ifs:
482        sniffer_params = copy(expect_params)
483        sniffer_params['src_address'] = None
484        sniffer_params['dst_address'] = dst_address
485        for iface in recv_ifs:
486            LOGGER.debug(f'Installing receive sniffer on {iface}')
487            sniffers.append(
488                setup_sniffer(iface, args.ping_type, 'request', sniffer_params,
489            ))
490
491    if reply_ifs:
492        sniffer_params = copy(expect_params)
493        sniffer_params['src_address'] = dst_address
494        sniffer_params['dst_address'] = None
495        for iface in reply_ifs:
496            LOGGER.debug(f'Installing reply sniffer on {iface}')
497            sniffers.append(
498                setup_sniffer(iface, args.ping_type, 'reply', sniffer_params,
499            ))
500
501    LOGGER.debug(f'Installed {len(sniffers)} sniffers')
502
503    send_ping(dst_address, send_if, args.ping_type, send_params)
504
505    err = 0
506    sniffer_num = 0
507    for sniffer in sniffers:
508        sniffer.join()
509        if sniffer.correctPackets == 1:
510            LOGGER.debug(f'Expected ping has been sniffed on {sniffer._recvif}.')
511        else:
512            # Set a bit in err for each failed sniffer.
513            err |= 1<<sniffer_num
514            if sniffer.correctPackets > 1:
515                LOGGER.debug(f'Duplicated ping has been sniffed on {sniffer._recvif}!')
516            else:
517                LOGGER.debug(f'Expected ping has not been sniffed on {sniffer._recvif}!')
518        sniffer_num += 1
519
520    return err
521
522
523if __name__ == '__main__':
524    sys.exit(main())
525