#!/usr/bin/env python3
#
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2021 Kristof Provost <kp@FreeBSD.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#

import argparse
import logging
logging.getLogger("scapy").setLevel(logging.CRITICAL)
import scapy.all as sp
import sys
import os
curdir = os.path.dirname(os.path.realpath(__file__))
netpfil_common = curdir + "/../netpfil/common"
sys.path.append(netpfil_common)
from sniffer import Sniffer

def check_stp(args, packet):
	stp = packet.getlayer(sp.STP)
	if stp is None:
		return False

	if stp.rootmac != "00:0c:29:01:01:01":
		return False

	# Ensure we don't get confused by valid STP packets generated by if_bridge
	if (stp.maxage >= 6 and stp.maxage <= 40) and \
	    (stp.hellotime >= 1 and stp.hellotime <= 2) and \
	    (stp.fwddelay >= 4 and stp.fwddelay <= 30):
		return False

	print("This packet should have been dropped")
	print(packet.show())
	return True

def invalid_stp(send_if):
	llc = sp.Ether(src="00:0c:29:0b:91:0a", dst="01:80:C2:00:00:00") \
	    / sp.LLC()

	# Bad maxage
	stp = llc / sp.STP(proto=0, rootid=32768, rootmac="00:0c:29:01:01:01", \
	        bridgeid=32768, bridgemac="00:0c:29:01:01:01", \
	        portid=0x8007, maxage=41, hellotime=2, fwddelay=30)
	sp.sendp(stp, iface=send_if, verbose=False)
	stp = llc / sp.STP(proto=0, rootid=32768, rootmac="00:0c:29:01:01:01", \
	        bridgeid=32768, bridgemac="00:0c:29:01:01:01", \
	        portid=0x8007, maxage=5, hellotime=2, fwddelay=30)
	sp.sendp(stp, iface=send_if, verbose=False)

	# Bad hellotime
	stp = llc / sp.STP(proto=0, rootid=32768, rootmac="00:0c:29:01:01:01", \
	        bridgeid=32768, bridgemac="00:0c:29:01:01:01", \
	        portid=0x8007, maxage=40, hellotime=3, fwddelay=30)
	sp.sendp(stp, iface=send_if, verbose=False)
	stp = llc / sp.STP(proto=0, rootid=32768, rootmac="00:0c:29:01:01:01", \
	        bridgeid=32768, bridgemac="00:0c:29:01:01:01", \
	        portid=0x8007, maxage=40, hellotime=1, fwddelay=30)
	sp.sendp(stp, iface=send_if, verbose=False)

	# Bad fwddelay
	stp = llc / sp.STP(proto=0, rootid=32768, rootmac="00:0c:29:01:01:01", \
	        bridgeid=32768, bridgemac="00:0c:29:01:01:01", \
	        portid=0x8007, maxage=40, hellotime=2, fwddelay=31)
	sp.sendp(stp, iface=send_if, verbose=False)
	stp = llc / sp.STP(proto=0, rootid=32768, rootmac="00:0c:29:01:01:01", \
	        bridgeid=32768, bridgemac="00:0c:29:01:01:01", \
	        portid=0x8007, maxage=40, hellotime=2, fwddelay=3)
	sp.sendp(stp, iface=send_if, verbose=False)

def main():
	parser = argparse.ArgumentParser("stp.py",
		description="STP test tool")
	parser.add_argument('--sendif', nargs=1,
		required=True,
		help='The interface through which the packet(s) will be sent')
	parser.add_argument('--recvif', nargs=1,
		help='The interface on which to expect the ICMP echo request')

	args = parser.parse_args()

	sniffer = Sniffer(args, check_stp, args.recvif[0])

	invalid_stp(args.sendif[0])

	sniffer.join()

	# The 'correct' packet is a corrupt STP packet, so it shouldn't turn up.
	if sniffer.correctPackets:
		sys.exit(1)

if __name__ == '__main__':
	main()
