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 opt = send_params.get('nop') 72 options = '' 73 if opt: 74 options='\x00' 75 ip = sp.IP(dst=dst_address, options=options) 76 if src_address: 77 ip.src = src_address 78 if flags: 79 ip.flags = flags 80 if tos: 81 ip.tos = tos 82 if ttl: 83 ip.ttl = ttl 84 return ip 85 86 87def send_icmp_ping(dst_address, sendif, send_params): 88 send_length = send_params['length'] 89 send_frag_length = send_params['frag_length'] 90 packets = [] 91 ether = sp.Ether() 92 if ':' in dst_address: 93 ip6 = prepare_ipv6(dst_address, send_params) 94 icmp = sp.ICMPv6EchoRequest(data=sp.raw(build_payload(send_length))) 95 if send_frag_length: 96 for packet in sp.fragment(ip6 / icmp, fragsize=send_frag_length): 97 packets.append(ether / packet) 98 else: 99 packets.append(ether / ip6 / icmp) 100 101 else: 102 ip = prepare_ipv4(dst_address, send_params) 103 icmp = sp.ICMP(type='echo-request') 104 raw = sp.raw(build_payload(send_length)) 105 if send_frag_length: 106 for packet in sp.fragment(ip / icmp / raw, fragsize=send_frag_length): 107 packets.append(ether / packet) 108 else: 109 packets.append(ether / ip / icmp / raw) 110 for packet in packets: 111 sp.sendp(packet, sendif, verbose=False) 112 113 114def send_tcp_syn(dst_address, sendif, send_params): 115 tcpopt_unaligned = send_params.get('tcpopt_unaligned') 116 seq = send_params.get('seq') 117 mss = send_params.get('mss') 118 ether = sp.Ether() 119 opts=[('Timestamp', (1, 1)), ('MSS', mss if mss else 1280)] 120 if tcpopt_unaligned: 121 opts = [('NOP', 0 )] + opts 122 if ':' in dst_address: 123 ip = prepare_ipv6(dst_address, send_params) 124 else: 125 ip = prepare_ipv4(dst_address, send_params) 126 tcp = sp.TCP( 127 sport=send_params.get('sport'), dport=send_params.get('dport'), 128 flags='S', options=opts, seq=seq, 129 ) 130 req = ether / ip / tcp 131 sp.sendp(req, iface=sendif, verbose=False) 132 133 134def send_ping(dst_address, sendif, ping_type, send_params): 135 if ping_type == 'icmp': 136 send_icmp_ping(dst_address, sendif, send_params) 137 elif ping_type == 'tcpsyn': 138 send_tcp_syn(dst_address, sendif, send_params) 139 else: 140 raise Exception('Unspported ping type') 141 142 143def check_ipv4(expect_params, packet): 144 src_address = expect_params.get('src_address') 145 dst_address = expect_params.get('dst_address') 146 flags = expect_params.get('flags') 147 tos = expect_params.get('tc') 148 ttl = expect_params.get('hlim') 149 ip = packet.getlayer(sp.IP) 150 if not ip: 151 LOGGER.debug('Packet is not IPv4!') 152 return False 153 if src_address and ip.src != src_address: 154 LOGGER.debug('Source IPv4 address does not match!') 155 return False 156 if dst_address and ip.dst != dst_address: 157 LOGGER.debug('Destination IPv4 address does not match!') 158 return False 159 chksum = ip.chksum 160 ip.chksum = None 161 new_chksum = sp.IP(sp.raw(ip)).chksum 162 if chksum != new_chksum: 163 LOGGER.debug(f'Expected IP checksum {new_chksum} but found {chksum}') 164 return False 165 if flags and ip.flags != flags: 166 LOGGER.debug(f'Wrong IP flags value {ip.flags}, expected {flags}') 167 return False 168 if tos and ip.tos != tos: 169 LOGGER.debug(f'Wrong ToS value {ip.tos}, expected {tos}') 170 return False 171 if ttl and ip.ttl != ttl: 172 LOGGER.debug(f'Wrong TTL value {ip.ttl}, expected {ttl}') 173 return False 174 return True 175 176 177def check_ipv6(expect_params, packet): 178 src_address = expect_params.get('src_address') 179 dst_address = expect_params.get('dst_address') 180 flags = expect_params.get('flags') 181 hlim = expect_params.get('hlim') 182 tc = expect_params.get('tc') 183 ip6 = packet.getlayer(sp.IPv6) 184 if not ip6: 185 LOGGER.debug('Packet is not IPv6!') 186 return False 187 if src_address and ip6.src != src_address: 188 LOGGER.debug('Source IPv6 address does not match!') 189 return False 190 if dst_address and ip6.dst != dst_address: 191 LOGGER.debug('Destination IPv6 address does not match!') 192 return False 193 # IPv6 has no IP-level checksum. 194 if flags: 195 raise Exception("There's no fragmentation flags in IPv6") 196 if hlim and ip6.hlim != hlim: 197 LOGGER.debug(f'Wrong Hop Limit value {ip6.hlim}, expected {hlim}') 198 return False 199 if tc and ip6.tc != tc: 200 LOGGER.debug(f'Wrong TC value {ip6.tc}, expected {tc}') 201 return False 202 return True 203 204 205def check_ping_4(expect_params, packet): 206 expect_length = expect_params['length'] 207 if not check_ipv4(expect_params, packet): 208 return False 209 icmp = packet.getlayer(sp.ICMP) 210 if not icmp: 211 LOGGER.debug('Packet is not IPv4 ICMP!') 212 return False 213 raw = packet.getlayer(sp.Raw) 214 if not raw: 215 LOGGER.debug('Packet contains no payload!') 216 return False 217 if raw.load != build_payload(expect_length): 218 LOGGER.debug('Payload magic does not match!') 219 return False 220 return True 221 222 223def check_ping_request_4(expect_params, packet): 224 if not check_ping_4(expect_params, packet): 225 return False 226 icmp = packet.getlayer(sp.ICMP) 227 if sp.icmptypes[icmp.type] != 'echo-request': 228 LOGGER.debug('Packet is not IPv4 ICMP Echo Request!') 229 return False 230 return True 231 232 233def check_ping_reply_4(expect_params, packet): 234 if not check_ping_4(expect_params, packet): 235 return False 236 icmp = packet.getlayer(sp.ICMP) 237 if sp.icmptypes[icmp.type] != 'echo-reply': 238 LOGGER.debug('Packet is not IPv4 ICMP Echo Reply!') 239 return False 240 return True 241 242 243def check_ping_request_6(expect_params, packet): 244 expect_length = expect_params['length'] 245 if not check_ipv6(expect_params, packet): 246 return False 247 icmp = packet.getlayer(sp.ICMPv6EchoRequest) 248 if not icmp: 249 LOGGER.debug('Packet is not IPv6 ICMP Echo Request!') 250 return False 251 if icmp.data != build_payload(expect_length): 252 LOGGER.debug('Payload magic does not match!') 253 return False 254 return True 255 256 257def check_ping_reply_6(expect_params, packet): 258 expect_length = expect_params['length'] 259 if not check_ipv6(expect_params, packet): 260 return False 261 icmp = packet.getlayer(sp.ICMPv6EchoReply) 262 if not icmp: 263 LOGGER.debug('Packet is not IPv6 ICMP Echo Reply!') 264 return False 265 if icmp.data != build_payload(expect_length): 266 LOGGER.debug('Payload magic does not match!') 267 return False 268 return True 269 270 271def check_ping_request(expect_params, packet): 272 src_address = expect_params.get('src_address') 273 dst_address = expect_params.get('dst_address') 274 if not (src_address or dst_address): 275 raise Exception('Source or destination address must be given to match the ping request!') 276 if ( 277 (src_address and ':' in src_address) or 278 (dst_address and ':' in dst_address) 279 ): 280 return check_ping_request_6(expect_params, packet) 281 else: 282 return check_ping_request_4(expect_params, packet) 283 284 285def check_ping_reply(expect_params, packet): 286 src_address = expect_params.get('src_address') 287 dst_address = expect_params.get('dst_address') 288 if not (src_address or dst_address): 289 raise Exception('Source or destination address must be given to match the ping reply!') 290 if ( 291 (src_address and ':' in src_address) or 292 (dst_address and ':' in dst_address) 293 ): 294 return check_ping_reply_6(expect_params, packet) 295 else: 296 return check_ping_reply_4(expect_params, packet) 297 298 299def check_tcp(expect_params, packet): 300 tcp_flags = expect_params.get('tcp_flags') 301 mss = expect_params.get('mss') 302 seq = expect_params.get('seq') 303 tcp = packet.getlayer(sp.TCP) 304 if not tcp: 305 LOGGER.debug('Packet is not TCP!') 306 return False 307 chksum = tcp.chksum 308 tcp.chksum = None 309 newpacket = sp.Ether(sp.raw(packet[sp.Ether])) 310 new_chksum = newpacket[sp.TCP].chksum 311 if chksum != new_chksum: 312 LOGGER.debug(f'Wrong TCP checksum {chksum}, expected {new_chksum}!') 313 return False 314 if tcp_flags and tcp.flags != tcp_flags: 315 LOGGER.debug(f'Wrong TCP flags {tcp.flags}, expected {tcp_flags}!') 316 return False 317 if seq: 318 if tcp_flags == 'S': 319 tcp_seq = tcp.seq 320 elif tcp_flags == 'SA': 321 tcp_seq = tcp.ack - 1 322 if seq != tcp_seq: 323 LOGGER.debug(f'Wrong TCP Sequence Number {tcp_seq}, expected {seq}') 324 return False 325 if mss: 326 for option in tcp.options: 327 if option[0] == 'MSS': 328 if option[1] != mss: 329 LOGGER.debug(f'Wrong TCP MSS {option[1]}, expected {mss}') 330 return False 331 return True 332 333 334def check_tcp_syn_request_4(expect_params, packet): 335 if not check_ipv4(expect_params, packet): 336 return False 337 if not check_tcp(expect_params | {'tcp_flags': 'S'}, packet): 338 return False 339 return True 340 341 342def check_tcp_syn_reply_4(expect_params, packet): 343 if not check_ipv4(expect_params, packet): 344 return False 345 if not check_tcp(expect_params | {'tcp_flags': 'SA'}, packet): 346 return False 347 return True 348 349 350def check_tcp_syn_request_6(expect_params, packet): 351 if not check_ipv6(expect_params, packet): 352 return False 353 if not check_tcp(expect_params | {'tcp_flags': 'S'}, packet): 354 return False 355 return True 356 357 358def check_tcp_syn_reply_6(expect_params, packet): 359 if not check_ipv6(expect_params, packet): 360 return False 361 if not check_tcp(expect_params | {'tcp_flags': 'SA'}, packet): 362 return False 363 return True 364 365 366def check_tcp_syn_request(expect_params, packet): 367 src_address = expect_params.get('src_address') 368 dst_address = expect_params.get('dst_address') 369 if not (src_address or dst_address): 370 raise Exception('Source or destination address must be given to match the tcp syn request!') 371 if ( 372 (src_address and ':' in src_address) or 373 (dst_address and ':' in dst_address) 374 ): 375 return check_tcp_syn_request_6(expect_params, packet) 376 else: 377 return check_tcp_syn_request_4(expect_params, packet) 378 379 380def check_tcp_syn_reply(expect_params, packet): 381 src_address = expect_params.get('src_address') 382 dst_address = expect_params.get('dst_address') 383 if not (src_address or dst_address): 384 raise Exception('Source or destination address must be given to match the tcp syn reply!') 385 if ( 386 (src_address and ':' in src_address) or 387 (dst_address and ':' in dst_address) 388 ): 389 return check_tcp_syn_reply_6(expect_params, packet) 390 else: 391 return check_tcp_syn_reply_4(expect_params, packet) 392 393 394def setup_sniffer(recvif, ping_type, sniff_type, expect_params, defrag): 395 if ping_type == 'icmp' and sniff_type == 'request': 396 checkfn = check_ping_request 397 elif ping_type == 'icmp' and sniff_type == 'reply': 398 checkfn = check_ping_reply 399 elif ping_type == 'tcpsyn' and sniff_type == 'request': 400 checkfn = check_tcp_syn_request 401 elif ping_type == 'tcpsyn' and sniff_type == 'reply': 402 checkfn = check_tcp_syn_reply 403 else: 404 raise Exception('Unspported ping or sniff type') 405 406 return Sniffer(expect_params, checkfn, recvif, defrag=defrag) 407 408 409def parse_args(): 410 parser = argparse.ArgumentParser("pft_ping.py", 411 description="Ping test tool") 412 413 # Parameters of sent ping request 414 parser.add_argument('--sendif', required=True, 415 help='The interface through which the packet(s) will be sent') 416 parser.add_argument('--to', required=True, 417 help='The destination IP address for the ping request') 418 parser.add_argument('--ping-type', 419 choices=('icmp', 'tcpsyn'), 420 help='Type of ping: ICMP (default) or TCP SYN', 421 default='icmp') 422 parser.add_argument('--fromaddr', 423 help='The source IP address for the ping request') 424 425 # Where to look for packets to analyze. 426 # The '+' format is ugly as it mixes positional with optional syntax. 427 # But we have no positional parameters so I guess it's fine to use it. 428 parser.add_argument('--recvif', nargs='+', 429 help='The interfaces on which to expect the ping request') 430 parser.add_argument('--replyif', nargs='+', 431 help='The interfaces which to expect the ping response') 432 433 # Packet settings 434 parser_send = parser.add_argument_group('Values set in transmitted packets') 435 parser_send.add_argument('--send-flags', type=str, 436 help='IPv4 fragmentation flags') 437 parser_send.add_argument('--send-frag-length', type=int, 438 help='Force IP fragmentation with given fragment length') 439 parser_send.add_argument('--send-hlim', type=int, 440 help='IPv6 Hop Limit or IPv4 Time To Live') 441 parser_send.add_argument('--send-mss', type=int, 442 help='TCP Maximum Segment Size') 443 parser_send.add_argument('--send-seq', type=int, 444 help='TCP sequence number') 445 parser_send.add_argument('--send-sport', type=int, 446 help='TCP source port') 447 parser_send.add_argument('--send-dport', type=int, default=666, 448 help='TCP destination port') 449 parser_send.add_argument('--send-length', type=int, default=len(PAYLOAD_MAGIC), 450 help='ICMP Echo Request payload size') 451 parser_send.add_argument('--send-tc', type=int, 452 help='IPv6 Traffic Class or IPv4 DiffServ / ToS') 453 parser_send.add_argument('--send-tcpopt-unaligned', action='store_true', 454 help='Include unaligned TCP options') 455 parser_send.add_argument('--send-nop', action='store_true', 456 help='Include a NOP IPv4 option') 457 458 # Expectations 459 parser_expect = parser.add_argument_group('Values expected in sniffed packets') 460 parser_expect.add_argument('--expect-flags', type=str, 461 help='IPv4 fragmentation flags') 462 parser_expect.add_argument('--expect-hlim', type=int, 463 help='IPv6 Hop Limit or IPv4 Time To Live') 464 parser_expect.add_argument('--expect-mss', type=int, 465 help='TCP Maximum Segment Size') 466 parser_send.add_argument('--expect-seq', type=int, 467 help='TCP sequence number') 468 parser_expect.add_argument('--expect-tc', type=int, 469 help='IPv6 Traffic Class or IPv4 DiffServ / ToS') 470 471 parser.add_argument('-v', '--verbose', action='store_true', 472 help=('Enable verbose logging. Apart of potentially useful information ' 473 'you might see warnings from parsing packets like NDP or other ' 474 'packets not related to the test being run. Use only when ' 475 'developing because real tests expect empty stderr and stdout.')) 476 477 return parser.parse_args() 478 479 480def main(): 481 args = parse_args() 482 483 if args.verbose: 484 LOGGER.setLevel(logging.DEBUG) 485 486 # Split parameters into send and expect parameters. Parameters might be 487 # missing from the command line, always fill the dictionaries with None. 488 send_params = {} 489 expect_params = {} 490 for param_name in ( 491 'flags', 'hlim', 'length', 'mss', 'seq', 'tc', 'frag_length', 492 'sport', 'dport', 493 ): 494 param_arg = vars(args).get(f'send_{param_name}') 495 send_params[param_name] = param_arg if param_arg else None 496 param_arg = vars(args).get(f'expect_{param_name}') 497 expect_params[param_name] = param_arg if param_arg else None 498 499 expect_params['length'] = send_params['length'] 500 send_params['tcpopt_unaligned'] = args.send_tcpopt_unaligned 501 send_params['nop'] = args.send_nop 502 send_params['src_address'] = args.fromaddr if args.fromaddr else None 503 504 # We may not have a default route. Tell scapy where to start looking for routes 505 sp.conf.iface6 = args.sendif 506 507 # Configuration sanity checking. 508 if not (args.replyif or args.recvif): 509 raise Exception('With no reply or recv interface specified no traffic ' 510 'can be sniffed and verified!' 511 ) 512 513 sniffers = [] 514 515 if send_params['frag_length']: 516 defrag = True 517 else: 518 defrag = False 519 520 if args.recvif: 521 sniffer_params = copy(expect_params) 522 sniffer_params['src_address'] = None 523 sniffer_params['dst_address'] = args.to 524 for iface in args.recvif: 525 LOGGER.debug(f'Installing receive sniffer on {iface}') 526 sniffers.append( 527 setup_sniffer(iface, args.ping_type, 'request', 528 sniffer_params, defrag, 529 )) 530 531 if args.replyif: 532 sniffer_params = copy(expect_params) 533 sniffer_params['src_address'] = args.to 534 sniffer_params['dst_address'] = None 535 for iface in args.replyif: 536 LOGGER.debug(f'Installing reply sniffer on {iface}') 537 sniffers.append( 538 setup_sniffer(iface, args.ping_type, 'reply', 539 sniffer_params, defrag, 540 )) 541 542 LOGGER.debug(f'Installed {len(sniffers)} sniffers') 543 544 send_ping(args.to, args.sendif, args.ping_type, send_params) 545 546 err = 0 547 sniffer_num = 0 548 for sniffer in sniffers: 549 sniffer.join() 550 if sniffer.correctPackets == 1: 551 LOGGER.debug(f'Expected ping has been sniffed on {sniffer._recvif}.') 552 else: 553 # Set a bit in err for each failed sniffer. 554 err |= 1<<sniffer_num 555 if sniffer.correctPackets > 1: 556 LOGGER.debug(f'Duplicated ping has been sniffed on {sniffer._recvif}!') 557 else: 558 LOGGER.debug(f'Expected ping has not been sniffed on {sniffer._recvif}!') 559 sniffer_num += 1 560 561 return err 562 563 564if __name__ == '__main__': 565 sys.exit(main()) 566