#!/usr/bin/env python3 import socket from socket import inet_pton, inet_ntop import unittest from parameterized import parameterized import scapy.compat import scapy.layers.inet6 as inet6 from scapy.layers.inet import UDP, IP from scapy.contrib.mpls import MPLS from scapy.layers.inet6 import ( IPv6, ICMPv6ND_NS, ICMPv6ND_RS, ICMPv6ND_RA, ICMPv6NDOptMTU, ICMPv6NDOptSrcLLAddr, ICMPv6NDOptPrefixInfo, ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, ICMPv6DestUnreach, icmp6types, ICMPv6TimeExceeded, ICMPv6EchoRequest, ICMPv6EchoReply, IPv6ExtHdrHopByHop, ICMPv6MLReport2, ICMPv6MLDMultAddrRec, ) from scapy.layers.l2 import Ether, Dot1Q, GRE from scapy.packet import Raw from scapy.utils6 import ( in6_getnsma, in6_getnsmac, in6_ptop, in6_islladdr, in6_mactoifaceid, ) from six import moves from framework import VppTestCase, VppTestRunner, tag_run_solo from util import ppp, ip6_normalize, mk_ll_addr from vpp_papi import VppEnum from vpp_ip import DpoProto, VppIpPuntPolicer, VppIpPuntRedirect, VppIpPathMtu from vpp_ip_route import ( VppIpRoute, VppRoutePath, find_route, VppIpMRoute, VppMRoutePath, VppMplsIpBind, VppMplsRoute, VppMplsTable, VppIpTable, FibPathType, FibPathProto, VppIpInterfaceAddress, find_route_in_dump, find_mroute_in_dump, VppIp6LinkLocalAddress, VppIpRouteV2, ) from vpp_neighbor import find_nbr, VppNeighbor from vpp_ipip_tun_interface import VppIpIpTunInterface from vpp_pg_interface import is_ipv6_misc from vpp_sub_interface import VppSubInterface, VppDot1QSubint from vpp_policer import VppPolicer, PolicerAction from ipaddress import IPv6Network, IPv6Address from vpp_gre_interface import VppGreInterface from vpp_teib import VppTeib AF_INET6 = socket.AF_INET6 try: text_type = unicode except NameError: text_type = str NUM_PKTS = 67 class TestIPv6ND(VppTestCase): def validate_ra(self, intf, rx, dst_ip=None): if not dst_ip: dst_ip = intf.remote_ip6 # unicasted packets must come to the unicast mac self.assertEqual(rx[Ether].dst, intf.remote_mac) # and from the router's MAC self.assertEqual(rx[Ether].src, intf.local_mac) # the rx'd RA should be addressed to the sender's source self.assertTrue(rx.haslayer(ICMPv6ND_RA)) self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip)) # and come from the router's link local self.assertTrue(in6_islladdr(rx[IPv6].src)) self.assertEqual(in6_ptop(rx[IPv6].src), in6_ptop(mk_ll_addr(intf.local_mac))) def validate_na(self, intf, rx, dst_ip=None, tgt_ip=None): if not dst_ip: dst_ip = intf.remote_ip6 if not tgt_ip: dst_ip = intf.local_ip6 # unicasted packets must come to the unicast mac self.assertEqual(rx[Ether].dst, intf.remote_mac) # and from the router's MAC self.assertEqual(rx[Ether].src, intf.local_mac) # the rx'd NA should be addressed to the sender's source self.assertTrue(rx.haslayer(ICMPv6ND_NA)) self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip)) # and come from the target address self.assertEqual(in6_ptop(rx[IPv6].src), in6_ptop(tgt_ip)) # Dest link-layer options should have the router's MAC dll = rx[ICMPv6NDOptDstLLAddr] self.assertEqual(dll.lladdr, intf.local_mac) def validate_ns(self, intf, rx, tgt_ip): nsma = in6_getnsma(inet_pton(AF_INET6, tgt_ip)) dst_ip = inet_ntop(AF_INET6, nsma) # NS is broadcast self.assertEqual(rx[Ether].dst, in6_getnsmac(nsma)) # and from the router's MAC self.assertEqual(rx[Ether].src, intf.local_mac) # the rx'd NS should be addressed to an mcast address # derived from the target address self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip)) # expect the tgt IP in the NS header ns = rx[ICMPv6ND_NS] self.assertEqual(in6_ptop(ns.tgt), in6_ptop(tgt_ip)) # packet is from the router's local address self.assertEqual(in6_ptop(rx[IPv6].src), intf.local_ip6) # Src link-layer options should have the router's MAC sll = rx[ICMPv6NDOptSrcLLAddr] self.assertEqual(sll.lladdr, intf.local_mac) def send_and_expect_ra( self, intf, pkts, remark, dst_ip=None, filter_out_fn=is_ipv6_misc ): intf.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = intf.get_capture(1, filter_out_fn=filter_out_fn) self.assertEqual(len(rx), 1) rx = rx[0] self.validate_ra(intf, rx, dst_ip) def send_and_expect_na( self, intf, pkts, remark, dst_ip=None, tgt_ip=None, filter_out_fn=is_ipv6_misc ): intf.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = intf.get_capture(1, filter_out_fn=filter_out_fn) self.assertEqual(len(rx), 1) rx = rx[0] self.validate_na(intf, rx, dst_ip, tgt_ip) def send_and_expect_ns( self, tx_intf, rx_intf, pkts, tgt_ip, filter_out_fn=is_ipv6_misc ): self.vapi.cli("clear trace") tx_intf.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = rx_intf.get_capture(1, filter_out_fn=filter_out_fn) self.assertEqual(len(rx), 1) rx = rx[0] self.validate_ns(rx_intf, rx, tgt_ip) def verify_ip(self, rx, smac, dmac, sip, dip): ether = rx[Ether] self.assertEqual(ether.dst, dmac) self.assertEqual(ether.src, smac) ip = rx[IPv6] self.assertEqual(ip.src, sip) self.assertEqual(ip.dst, dip) def get_ip6_nd_rx_requests(self, itf): """Get IP6 ND RX request stats for and interface""" return self.statistics["/net/ip6-nd/rx/requests"][:, itf.sw_if_index].sum() def get_ip6_nd_tx_requests(self, itf): """Get IP6 ND TX request stats for and interface""" return self.statistics["/net/ip6-nd/tx/requests"][:, itf.sw_if_index].sum() def get_ip6_nd_rx_replies(self, itf): """Get IP6 ND RX replies stats for and interface""" return self.statistics["/net/ip6-nd/rx/replies"][:, itf.sw_if_index].sum() def get_ip6_nd_tx_replies(self, itf): """Get IP6 ND TX replies stats for and interface""" return self.statistics["/net/ip6-nd/tx/replies"][:, itf.sw_if_index].sum() @tag_run_solo class TestIPv6(TestIPv6ND): """IPv6 Test Case""" @classmethod def setUpClass(cls): super(TestIPv6, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIPv6, cls).tearDownClass() def setUp(self): """ Perform test setup before test case. **Config:** - create 3 pg interfaces - untagged pg0 interface - Dot1Q subinterface on pg1 - Dot1AD subinterface on pg2 - setup interfaces: - put it into UP state - set IPv6 addresses - resolve neighbor address using NDP - configure 200 fib entries :ivar list interfaces: pg interfaces and subinterfaces. :ivar dict flows: IPv4 packet flows in test. *TODO:* Create AD sub interface """ super(TestIPv6, self).setUp() # create 3 pg interfaces self.create_pg_interfaces(range(3)) # create 2 subinterfaces for p1 and pg2 self.sub_interfaces = [ VppDot1QSubint(self, self.pg1, 100), VppDot1QSubint(self, self.pg2, 200) # TODO: VppDot1ADSubint(self, self.pg2, 200, 300, 400) ] # packet flows mapping pg0 -> pg1.sub, pg2.sub, etc. self.flows = dict() self.flows[self.pg0] = [self.pg1.sub_if, self.pg2.sub_if] self.flows[self.pg1.sub_if] = [self.pg0, self.pg2.sub_if] self.flows[self.pg2.sub_if] = [self.pg0, self.pg1.sub_if] # packet sizes self.pg_if_packet_sizes = [64, 1500, 9020] self.interfaces = list(self.pg_interfaces) self.interfaces.extend(self.sub_interfaces) # setup all interfaces for i in self.interfaces: i.admin_up() i.config_ip6() i.resolve_ndp() def tearDown(self): """Run standard test teardown and log ``show ip6 neighbors``.""" for i in self.interfaces: i.unconfig_ip6() i.admin_down() for i in self.sub_interfaces: i.remove_vpp_config() super(TestIPv6, self).tearDown() if not self.vpp_dead: self.logger.info(self.vapi.cli("show ip6 neighbors")) # info(self.vapi.cli("show ip6 fib")) # many entries def modify_packet(self, src_if, packet_size, pkt): """Add load, set destination IP and extend packet to required packet size for defined interface. :param VppInterface src_if: Interface to create packet for. :param int packet_size: Required packet size. :param Scapy pkt: Packet to be modified. """ dst_if_idx = int(packet_size / 10 % 2) dst_if = self.flows[src_if][dst_if_idx] info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(info) p = pkt / Raw(payload) p[IPv6].dst = dst_if.remote_ip6 info.data = p.copy() if isinstance(src_if, VppSubInterface): p = src_if.add_dot1_layer(p) self.extend_packet(p, packet_size) return p def create_stream(self, src_if): """Create input packet stream for defined interface. :param VppInterface src_if: Interface to create packet stream for. """ hdr_ext = 4 if isinstance(src_if, VppSubInterface) else 0 pkt_tmpl = ( Ether(dst=src_if.local_mac, src=src_if.remote_mac) / IPv6(src=src_if.remote_ip6) / inet6.UDP(sport=1234, dport=1234) ) pkts = [ self.modify_packet(src_if, i, pkt_tmpl) for i in moves.range( self.pg_if_packet_sizes[0], self.pg_if_packet_sizes[1], 10 ) ] pkts_b = [ self.modify_packet(src_if, i, pkt_tmpl) for i in moves.range( self.pg_if_packet_sizes[1] + hdr_ext, self.pg_if_packet_sizes[2] + hdr_ext, 50, ) ] pkts.extend(pkts_b) return pkts def verify_capture(self, dst_if, capture): """Verify captured input packet stream for defined interface. :param VppInterface dst_if: Interface to verify captured packet stream for. :param list capture: Captured packet stream. """ self.logger.info("Verifying capture on interface %s" % dst_if.name) last_info = dict() for i in self.interfaces: last_info[i.sw_if_index] = None is_sub_if = False dst_sw_if_index = dst_if.sw_if_index if hasattr(dst_if, "parent"): is_sub_if = True for packet in capture: if is_sub_if: # Check VLAN tags and Ethernet header packet = dst_if.remove_dot1_layer(packet) self.assertTrue(Dot1Q not in packet) try: ip = packet[IPv6] udp = packet[inet6.UDP] payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug( "Got packet on port %s: src=%u (id=%u)" % (dst_if.name, payload_info.src, packet_index) ) next_info = self.get_next_packet_info_for_interface2( payload_info.src, dst_sw_if_index, last_info[payload_info.src] ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) saved_packet = next_info.data # Check standard fields self.assertEqual(ip.src, saved_packet[IPv6].src) self.assertEqual(ip.dst, saved_packet[IPv6].dst) self.assertEqual(udp.sport, saved_packet[inet6.UDP].sport) self.assertEqual(udp.dport, saved_packet[inet6.UDP].dport) except: self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for i in self.interfaces: remaining_packet = self.get_next_packet_info_for_interface2( i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index] ) self.assertTrue( remaining_packet is None, "Interface %s: Packet expected from interface %s " "didn't arrive" % (dst_if.name, i.name), ) def test_next_header_anomaly(self): """IPv6 next header anomaly test Test scenario: - ipv6 next header field = Fragment Header (44) - next header is ICMPv6 Echo Request - wait for reassembly """ pkt = ( Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44) / ICMPv6EchoRequest() ) self.pg0.add_stream(pkt) self.pg_start() # wait for reassembly self.sleep(10) def test_fib(self): """IPv6 FIB test Test scenario: - Create IPv6 stream for pg0 interface - Create IPv6 tagged streams for pg1's and pg2's subinterface. - Send and verify received packets on each interface. """ pkts = self.create_stream(self.pg0) self.pg0.add_stream(pkts) for i in self.sub_interfaces: pkts = self.create_stream(i) i.parent.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() pkts = self.pg0.get_capture() self.verify_capture(self.pg0, pkts) for i in self.sub_interfaces: pkts = i.parent.get_capture() self.verify_capture(i, pkts) def test_ns(self): """IPv6 Neighbour Solicitation Exceptions Test scena
/*
* l2_input.h : layer 2 input packet processing
*
* Copyright (c) 2013 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef included_vnet_l2_input_h
#define included_vnet_l2_input_h
#include <vlib/vlib.h>
#include <vnet/vnet.h>
#include <vnet/l2/l2_bd.h>
#include <vnet/ethernet/packet.h>
#include <vnet/ip/ip.h>
/* Per-subinterface L2 feature configuration */
typedef struct
{
union
{
u16 bd_index; /* bridge domain id */
u32 output_sw_if_index; /* for xconnect */
};
/* config for which input features are configured on this interface */
u32 feature_bitmap;
/* split horizon group */
u8 shg;
/* Interface mode. If both are 0, this interface is in L3 mode */
u8 xconnect;
u8 bridge;
/* this is the bvi interface for the bridge-domain */
u8 bvi;
} l2_input_config_t;
typedef struct
{
/* Next nodes for the feature bitmap */
u32 feat_next_node_index[32];
/* config vector indexed by sw_if_index */
l2_input_config_t *configs;
/* bridge domain config vector indexed by bd_index */
l2_bridge_domain_t *bd_configs;
/* convenience variables */
vlib_main_t *vlib_main;
vnet_main_t *vnet_main;
} l2input_main_t;
extern l2input_main_t l2input_main;
extern vlib_node_registration_t l2input_node;
static_always_inline l2_bridge_domain_t *
l2input_bd_config_from_index (l2input_main_t * l2im, u32 bd_index)
{
l2_bridge_domain_t *bd_config;
bd_config = vec_elt_at_index (l2im->bd_configs, bd_index);
return bd_is_valid (bd_config) ? bd_config : NULL;
}
static_always_inline l2_bridge_domain_t *
l2input_bd_config (u32 bd_index)
{
l2input_main_t *mp = &l2input_main;
l2_bridge_domain_t *bd_config;
vec_validate (mp->bd_configs, bd_index);
bd_config = vec_elt_at_index (mp->bd_configs, bd_index);
return bd_config;
}
/* L2 input indication packet is from BVI, using -2 */
#define L2INPUT_BVI ((u32) (~0-1))
/* L2 input features */
/* Mappings from feature ID to graph node name in reverse order */
#define foreach_l2input_feat \
_(DROP, "feature-bitmap-drop") \
_(XCONNECT, "l2-output") \
_(FLOOD, "l2-flood") \
_(ARP_TERM, "arp-term-l2bd") \
_(UU_FLOOD, "l2-flood") \
_(GBP_FWD, "gbp-fwd") \
_(UU_FWD, "l2-uu-fwd") \
_(FWD, "l2-fwd") \
_(RW, "l2-rw") \
_(LEARN, "l2-learn") \
_(L2_EMULATION, "l2-emulation") \
_(GBP_LEARN, "gbp-learn-l2") \
_(GBP_NULL_CLASSIFY, "gbp-null-classify") \
_(GBP_SRC_CLASSIFY, "gbp-src-classify") \
_(VTR, "l2-input-vtr") \
_(L2_IP_QOS_RECORD, "l2-ip-qos-record") \
_(VPATH, "vpath-input-l2") \
_(ACL, "l2-input-acl") \
_(POLICER_CLAS, "l2-policer-classify") \
_(INPUT_FEAT_ARC, "l2-input-feat-arc") \
_(INPUT_CLASSIFY, "l2-input-classify") \
_(SPAN, "span-l2-input")
/* Feature bitmap positions */
typedef enum
{
#define _(sym,str) L2INPUT_FEAT_##sym##_BIT,
foreach_l2input_feat
#undef _
L2INPUT_N_FEAT
} l2input_feat_t;
STATIC_ASSERT (L2INPUT_N_FEAT <= 32, "too many l2 input features");
/* Feature bit masks */
typedef enum
{
L2INPUT_FEAT_NONE = 0,
#define _(sym,str) L2INPUT_FEAT_##sym = (1<<L2INPUT_FEAT_##sym##_BIT),
foreach_l2input_feat
#undef _
L2INPUT_VALID_MASK =
#define _(sym,str) L2INPUT_FEAT_##sym |
foreach_l2input_feat
#undef _
0
} l2input_feat_masks_t;
STATIC_ASSERT ((u64) L2INPUT_VALID_MASK == (1ull << L2INPUT_N_FEAT) - 1, "");
/** Return an array of strings containing graph node names of each feature */
char **l2input_get_feat_names (void);
/* arg0 - u32 feature_bitmap, arg1 - u32 verbose */
u8 *format_l2_input_features (u8 * s, va_list * args);
static_always_inline u8
bd_feature_flood (l2_bridge_domain_t * bd_config)
{
return ((bd_config->feature_bitmap & L2INPUT_FEAT_FLOOD) ==
L2INPUT_FEAT_FLOOD);
}
static_always_inline u8
bd_feature_uu_flood (l2_bridge_domain_t * bd_config)
{
return ((bd_config->feature_bitmap & L2INPUT_FEAT_UU_FLOOD) ==
L2INPUT_FEAT_UU_FLOOD);
}
static_always_inline u8
bd_feature_forward (l2_bridge_domain_t * bd_config)
{
return ((bd_config->feature_bitmap & L2INPUT_FEAT_FWD) == L2INPUT_FEAT_FWD);
}
static_always_inline u8
bd_feature_learn (l2_bridge_domain_t * bd_config)
{
return ((bd_config->feature_bitmap & L2INPUT_FEAT_LEARN) ==
L2INPUT_FEAT_LEARN);
}
static_always_inline u8
bd_feature_arp_term (l2_bridge_domain_t * bd_config)
{
return ((bd_config->feature_bitmap & L2INPUT_FEAT_ARP_TERM) ==
L2INPUT_FEAT_ARP_TERM);
}
/** Masks for eliminating features that do not apply to a packet */
/** Get a pointer to the config for the given interface */
l2_input_config_t *l2input_intf_config (u32 sw_if_index);
/* Enable (or disable) the feature in the bitmap for the given interface */
u32 l2input_intf_bitmap_enable (u32 sw_if_index,
l2input_feat_masks_t feature_bitmap,
u32 enable);
/* Sets modifies flags from a bridge domain */
u32 l2input_set_bridge_features (u32 bd_index, u32 feat_mask, u32 feat_value);
void l2input_interface_mac_change (u32 sw_if_index,
const u8 * old_address,
const u8 * new_address);
#define MODE_L3 0
#define MODE_L2_BRIDGE 1
#define MODE_L2_XC 2
#define MODE_L2_CLASSIFY 3
#define MODE_ERROR_ETH 1
#define MODE_ERROR_BVI_DEF 2
u32 set_int_l2_mode (vlib_main_t * vm,
vnet_main_t * vnet_main,
u32 mode,
u32 sw_if_index,
u32 bd_index, l2_bd_port_type_t port_type,
u32 shg, u32 xc_sw_if_index);
static inline void
vnet_update_l2_len (vlib_buffer_t * b)
{
ethernet_header_t *eth;
u16 ethertype;
u8 vlan_count = 0;
/* point at current l2 hdr */
eth = vlib_buffer_get_current (b);
/*
* l2-output pays no attention to this
* but the tag push/pop code on an l2 subif needs it.
*
* Determine l2 header len, check for up to 2 vlans
*/
vnet_buffer (b)->l2.l2_len = sizeof (ethernet_header_t);
ethertype = clib_net_to_host_u16 (eth->type);
if (ethernet_frame_is_tagged (ethertype))
{
ethernet_vlan_header_t *vlan;
vnet_buffer (b)->l2.l2_len += sizeof (*vlan);
vlan_count = 1;
vlan = (void *) (eth + 1);
ethertype = clib_net_to_host_u16 (vlan->type);
if (ethertype == ETHERNET_TYPE_VLAN)
{
vnet_buffer (b)->l2.l2_len += sizeof (*vlan);
vlan_count = 2;
}
}
ethernet_buffer_set_vlan_count (b, vlan_count);
}
/*
* Compute flow hash of an ethernet packet, use 5-tuple hash if L3 packet
* is ip4 or ip6. Otherwise hash on smac/dmac/etype.
* The vlib buffer current pointer is expected to be at ethernet header
* and vnet l2.l2_len is expected to be setup already.
*/
static inline u32
vnet_l2_compute_flow_hash (vlib_buffer_t * b)
{
ethernet_header_t *eh = vlib_buffer_get_current (b);
u8 *l3h = (u8 *) eh + vnet_buffer (b)->l2.l2_len;
u16 ethertype = clib_net_to_host_u16 (*(u16 *) (l3h - 2));
if (ethertype == ETHERNET_TYPE_IP4)
return ip4_compute_flow_hash ((ip4_header_t *) l3h, IP_FLOW_HASH_DEFAULT);
else if (ethertype == ETHERNET_TYPE_IP6)
return ip6_compute_flow_hash ((ip6_header_t *) l3h, IP_FLOW_HASH_DEFAULT);
else
{
u32 a, b, c;
u32 *ap = (u32 *) & eh->dst_address[2];
u32 *bp = (u32 *) & eh->src_address[2];
a = *ap;
b = *bp;
c = ethertype;
hash_v3_mix32 (a, b, c);
hash_v3_finalize32 (a, b, c);
return c;
}
}
#endif
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/