#!/usr/bin/env python1# -2# SPDX-License-Identifier: BSD-2-Clause3#4# Copyright (c) 2020 Alexander V. Chernikov5#6# Redistribution and use in source and binary forms, with or without7# modification, are permitted provided that the following conditions8# are met:9# 1. Redistributions of source code must retain the above copyright10# notice, this list of conditions and the following disclaimer.11# 2. Redistributions in binary form must reproduce the above copyright12# notice, this list of conditions and the following disclaimer in the13# documentation and/or other materials provided with the distribution.14#15# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND16# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE18# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE19# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL20# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS21# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)22# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT23# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY24# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF25# SUCH DAMAGE.26#27#282930from socket import socket, PF_DIVERT, SOCK_RAW31import logging32logging.getLogger("scapy").setLevel(logging.CRITICAL)33import scapy.all as sc34import argparse353637def parse_args():38parser = argparse.ArgumentParser(description='divert socket tester')39parser.add_argument('--dip', type=str, help='destination packet IP')40parser.add_argument('--sip', type=str, help='source packet IP')41parser.add_argument('--divert_port', type=int, default=6668,42help='divert port to use')43parser.add_argument('--test_name', type=str, required=True,44help='test name to run')45return parser.parse_args()464748def ipdivert_ip_output_remote_success(args):49packet = sc.IP(dst=args.dip) / sc.ICMP(type='echo-request')50with socket(PF_DIVERT, SOCK_RAW, 0) as s:51s.bind(('0.0.0.0', args.divert_port))52s.sendto(bytes(packet), ('0.0.0.0', 0))535455def ipdivert_ip6_output_remote_success(args):56packet = sc.IPv6(dst=args.dip) / sc.ICMPv6EchoRequest()57with socket(PF_DIVERT, SOCK_RAW, 0) as s:58s.bind(('0.0.0.0', args.divert_port))59s.sendto(bytes(packet), ('0.0.0.0', 0))606162def ipdivert_ip_input_local_success(args):63"""Sends IPv4 packet to OS stack as inbound local packet."""64packet = sc.IP(dst=args.dip,src=args.sip) / sc.ICMP(type='echo-request')65with socket(PF_DIVERT, SOCK_RAW, 0) as s:66s.bind(('0.0.0.0', args.divert_port))67s.sendto(bytes(packet), (args.dip, 0))686970# XXX: IPv6 local divert is currently not supported71# TODO: add IPv4 ifname output verification727374def main():75args = parse_args()76test_ptr = globals()[args.test_name]77test_ptr(args)787980if __name__ == '__main__':81main()828384