crypto crypto-openssl: support hashing operations
[vpp.git] / test / test_ip6.py
1 #!/usr/bin/env python3
2
3 import socket
4 from socket import inet_pton, inet_ntop
5 import unittest
6
7 from parameterized import parameterized
8 import scapy.compat
9 import scapy.layers.inet6 as inet6
10 from scapy.layers.inet import UDP
11 from scapy.contrib.mpls import MPLS
12 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_RS, \
13     ICMPv6ND_RA, ICMPv6NDOptMTU, ICMPv6NDOptSrcLLAddr, ICMPv6NDOptPrefixInfo, \
14     ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, ICMPv6DestUnreach, icmp6types, \
15     ICMPv6TimeExceeded, ICMPv6EchoRequest, ICMPv6EchoReply, \
16     IPv6ExtHdrHopByHop, ICMPv6MLReport2, ICMPv6MLDMultAddrRec
17 from scapy.layers.l2 import Ether, Dot1Q
18 from scapy.packet import Raw
19 from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ptop, in6_islladdr, \
20     in6_mactoifaceid
21 from six import moves
22
23 from framework import VppTestCase, VppTestRunner, tag_run_solo
24 from util import ppp, ip6_normalize, mk_ll_addr
25 from vpp_papi import VppEnum
26 from vpp_ip import DpoProto, VppIpPuntPolicer, VppIpPuntRedirect, VppIpPathMtu
27 from vpp_ip_route import VppIpRoute, VppRoutePath, find_route, VppIpMRoute, \
28     VppMRoutePath, VppMplsIpBind, \
29     VppMplsRoute, VppMplsTable, VppIpTable, FibPathType, FibPathProto, \
30     VppIpInterfaceAddress, find_route_in_dump, find_mroute_in_dump, \
31     VppIp6LinkLocalAddress, VppIpRouteV2
32 from vpp_neighbor import find_nbr, VppNeighbor
33 from vpp_ipip_tun_interface import VppIpIpTunInterface
34 from vpp_pg_interface import is_ipv6_misc
35 from vpp_sub_interface import VppSubInterface, VppDot1QSubint
36 from vpp_policer import VppPolicer, PolicerAction
37 from ipaddress import IPv6Network, IPv6Address
38
39 AF_INET6 = socket.AF_INET6
40
41 try:
42     text_type = unicode
43 except NameError:
44     text_type = str
45
46 NUM_PKTS = 67
47
48
49 class TestIPv6ND(VppTestCase):
50     def validate_ra(self, intf, rx, dst_ip=None):
51         if not dst_ip:
52             dst_ip = intf.remote_ip6
53
54         # unicasted packets must come to the unicast mac
55         self.assertEqual(rx[Ether].dst, intf.remote_mac)
56
57         # and from the router's MAC
58         self.assertEqual(rx[Ether].src, intf.local_mac)
59
60         # the rx'd RA should be addressed to the sender's source
61         self.assertTrue(rx.haslayer(ICMPv6ND_RA))
62         self.assertEqual(in6_ptop(rx[IPv6].dst),
63                          in6_ptop(dst_ip))
64
65         # and come from the router's link local
66         self.assertTrue(in6_islladdr(rx[IPv6].src))
67         self.assertEqual(in6_ptop(rx[IPv6].src),
68                          in6_ptop(mk_ll_addr(intf.local_mac)))
69
70     def validate_na(self, intf, rx, dst_ip=None, tgt_ip=None):
71         if not dst_ip:
72             dst_ip = intf.remote_ip6
73         if not tgt_ip:
74             dst_ip = intf.local_ip6
75
76         # unicasted packets must come to the unicast mac
77         self.assertEqual(rx[Ether].dst, intf.remote_mac)
78
79         # and from the router's MAC
80         self.assertEqual(rx[Ether].src, intf.local_mac)
81
82         # the rx'd NA should be addressed to the sender's source
83         self.assertTrue(rx.haslayer(ICMPv6ND_NA))
84         self.assertEqual(in6_ptop(rx[IPv6].dst),
85                          in6_ptop(dst_ip))
86
87         # and come from the target address
88         self.assertEqual(
89             in6_ptop(rx[IPv6].src), in6_ptop(tgt_ip))
90
91         # Dest link-layer options should have the router's MAC
92         dll = rx[ICMPv6NDOptDstLLAddr]
93         self.assertEqual(dll.lladdr, intf.local_mac)
94
95     def validate_ns(self, intf, rx, tgt_ip):
96         nsma = in6_getnsma(inet_pton(AF_INET6, tgt_ip))
97         dst_ip = inet_ntop(AF_INET6, nsma)
98
99         # NS is broadcast
100         self.assertEqual(rx[Ether].dst, in6_getnsmac(nsma))
101
102         # and from the router's MAC
103         self.assertEqual(rx[Ether].src, intf.local_mac)
104
105         # the rx'd NS should be addressed to an mcast address
106         # derived from the target address
107         self.assertEqual(
108             in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip))
109
110         # expect the tgt IP in the NS header
111         ns = rx[ICMPv6ND_NS]
112         self.assertEqual(in6_ptop(ns.tgt), in6_ptop(tgt_ip))
113
114         # packet is from the router's local address
115         self.assertEqual(
116             in6_ptop(rx[IPv6].src), intf.local_ip6)
117
118         # Src link-layer options should have the router's MAC
119         sll = rx[ICMPv6NDOptSrcLLAddr]
120         self.assertEqual(sll.lladdr, intf.local_mac)
121
122     def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None,
123                            filter_out_fn=is_ipv6_misc):
124         intf.add_stream(pkts)
125         self.pg_enable_capture(self.pg_interfaces)
126         self.pg_start()
127         rx = intf.get_capture(1, filter_out_fn=filter_out_fn)
128
129         self.assertEqual(len(rx), 1)
130         rx = rx[0]
131         self.validate_ra(intf, rx, dst_ip)
132
133     def send_and_expect_na(self, intf, pkts, remark, dst_ip=None,
134                            tgt_ip=None,
135                            filter_out_fn=is_ipv6_misc):
136         intf.add_stream(pkts)
137         self.pg_enable_capture(self.pg_interfaces)
138         self.pg_start()
139         rx = intf.get_capture(1, filter_out_fn=filter_out_fn)
140
141         self.assertEqual(len(rx), 1)
142         rx = rx[0]
143         self.validate_na(intf, rx, dst_ip, tgt_ip)
144
145     def send_and_expect_ns(self, tx_intf, rx_intf, pkts, tgt_ip,
146                            filter_out_fn=is_ipv6_misc):
147         self.vapi.cli("clear trace")
148         tx_intf.add_stream(pkts)
149         self.pg_enable_capture(self.pg_interfaces)
150         self.pg_start()
151         rx = rx_intf.get_capture(1, filter_out_fn=filter_out_fn)
152
153         self.assertEqual(len(rx), 1)
154         rx = rx[0]
155         self.validate_ns(rx_intf, rx, tgt_ip)
156
157     def verify_ip(self, rx, smac, dmac, sip, dip):
158         ether = rx[Ether]
159         self.assertEqual(ether.dst, dmac)
160         self.assertEqual(ether.src, smac)
161
162         ip = rx[IPv6]
163         self.assertEqual(ip.src, sip)
164         self.assertEqual(ip.dst, dip)
165
166
167 @tag_run_solo
168 class TestIPv6(TestIPv6ND):
169     """ IPv6 Test Case """
170
171     @classmethod
172     def setUpClass(cls):
173         super(TestIPv6, cls).setUpClass()
174
175     @classmethod
176     def tearDownClass(cls):
177         super(TestIPv6, cls).tearDownClass()
178
179     def setUp(self):
180         """
181         Perform test setup before test case.
182
183         **Config:**
184             - create 3 pg interfaces
185                 - untagged pg0 interface
186                 - Dot1Q subinterface on pg1
187                 - Dot1AD subinterface on pg2
188             - setup interfaces:
189                 - put it into UP state
190                 - set IPv6 addresses
191                 - resolve neighbor address using NDP
192             - configure 200 fib entries
193
194         :ivar list interfaces: pg interfaces and subinterfaces.
195         :ivar dict flows: IPv4 packet flows in test.
196
197         *TODO:* Create AD sub interface
198         """
199         super(TestIPv6, self).setUp()
200
201         # create 3 pg interfaces
202         self.create_pg_interfaces(range(3))
203
204         # create 2 subinterfaces for p1 and pg2
205         self.sub_interfaces = [
206             VppDot1QSubint(self, self.pg1, 100),
207             VppDot1QSubint(self, self.pg2, 200)
208             # TODO: VppDot1ADSubint(self, self.pg2, 200, 300, 400)
209         ]
210
211         # packet flows mapping pg0 -> pg1.sub, pg2.sub, etc.
212         self.flows = dict()
213         self.flows[self.pg0] = [self.pg1.sub_if, self.pg2.sub_if]
214         self.flows[self.pg1.sub_if] = [self.pg0, self.pg2.sub_if]
215         self.flows[self.pg2.sub_if] = [self.pg0, self.pg1.sub_if]
216
217         # packet sizes
218         self.pg_if_packet_sizes = [64, 1500, 9020]
219
220         self.interfaces = list(self.pg_interfaces)
221         self.interfaces.extend(self.sub_interfaces)
222
223         # setup all interfaces
224         for i in self.interfaces:
225             i.admin_up()
226             i.config_ip6()
227             i.resolve_ndp()
228
229     def tearDown(self):
230         """Run standard test teardown and log ``show ip6 neighbors``."""
231         for i in self.interfaces:
232             i.unconfig_ip6()
233             i.admin_down()
234         for i in self.sub_interfaces:
235             i.remove_vpp_config()
236
237         super(TestIPv6, self).tearDown()
238         if not self.vpp_dead:
239             self.logger.info(self.vapi.cli("show ip6 neighbors"))
240             # info(self.vapi.cli("show ip6 fib"))  # many entries
241
242     def modify_packet(self, src_if, packet_size, pkt):
243         """Add load, set destination IP and extend packet to required packet
244         size for defined interface.
245
246         :param VppInterface src_if: Interface to create packet for.
247         :param int packet_size: Required packet size.
248         :param Scapy pkt: Packet to be modified.
249         """
250         dst_if_idx = int(packet_size / 10 % 2)
251         dst_if = self.flows[src_if][dst_if_idx]
252         info = self.create_packet_info(src_if, dst_if)
253         payload = self.info_to_payload(info)
254         p = pkt / Raw(payload)
255         p[IPv6].dst = dst_if.remote_ip6
256         info.data = p.copy()
257         if isinstance(src_if, VppSubInterface):
258             p = src_if.add_dot1_layer(p)
259         self.extend_packet(p, packet_size)
260
261         return p
262
263     def create_stream(self, src_if):
264         """Create input packet stream for defined interface.
265
266         :param VppInterface src_if: Interface to create packet stream for.
267         """
268         hdr_ext = 4 if isinstance(src_if, VppSubInterface) else 0
269         pkt_tmpl = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
270                     IPv6(src=src_if.remote_ip6) /
271                     inet6.UDP(sport=1234, dport=1234))
272
273         pkts = [self.modify_packet(src_if, i, pkt_tmpl)
274                 for i in moves.range(self.pg_if_packet_sizes[0],
275                                      self.pg_if_packet_sizes[1], 10)]
276         pkts_b = [self.modify_packet(src_if, i, pkt_tmpl)
277                   for i in moves.range(self.pg_if_packet_sizes[1] + hdr_ext,
278                                        self.pg_if_packet_sizes[2] + hdr_ext,
279                                        50)]
280         pkts.extend(pkts_b)
281
282         return pkts
283
284     def verify_capture(self, dst_if, capture):
285         """Verify captured input packet stream for defined interface.
286
287         :param VppInterface dst_if: Interface to verify captured packet stream
288                                     for.
289         :param list capture: Captured packet stream.
290         """
291         self.logger.info("Verifying capture on interface %s" % dst_if.name)
292         last_info = dict()
293         for i in self.interfaces:
294             last_info[i.sw_if_index] = None
295         is_sub_if = False
296         dst_sw_if_index = dst_if.sw_if_index
297         if hasattr(dst_if, 'parent'):
298             is_sub_if = True
299         for packet in capture:
300             if is_sub_if:
301                 # Check VLAN tags and Ethernet header
302                 packet = dst_if.remove_dot1_layer(packet)
303             self.assertTrue(Dot1Q not in packet)
304             try:
305                 ip = packet[IPv6]
306                 udp = packet[inet6.UDP]
307                 payload_info = self.payload_to_info(packet[Raw])
308                 packet_index = payload_info.index
309                 self.assertEqual(payload_info.dst, dst_sw_if_index)
310                 self.logger.debug(
311                     "Got packet on port %s: src=%u (id=%u)" %
312                     (dst_if.name, payload_info.src, packet_index))
313                 next_info = self.get_next_packet_info_for_interface2(
314                     payload_info.src, dst_sw_if_index,
315                     last_info[payload_info.src])
316                 last_info[payload_info.src] = next_info
317                 self.assertTrue(next_info is not None)
318                 self.assertEqual(packet_index, next_info.index)
319                 saved_packet = next_info.data
320                 # Check standard fields
321                 self.assertEqual(
322                     ip.src, saved_packet[IPv6].src)
323                 self.assertEqual(
324                     ip.dst, saved_packet[IPv6].dst)
325                 self.assertEqual(
326                     udp.sport, saved_packet[inet6.UDP].sport)
327                 self.assertEqual(
328                     udp.dport, saved_packet[inet6.UDP].dport)
329             except:
330                 self.logger.error(ppp("Unexpected or invalid packet:", packet))
331                 raise
332         for i in self.interfaces:
333             remaining_packet = self.get_next_packet_info_for_interface2(
334                 i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
335             self.assertTrue(remaining_packet is None,
336                             "Interface %s: Packet expected from interface %s "
337                             "didn't arrive" % (dst_if.name, i.name))
338
339     def test_next_header_anomaly(self):
340         """ IPv6 next header anomaly test
341
342         Test scenario:
343             - ipv6 next header field = Fragment Header (44)
344             - next header is ICMPv6 Echo Request
345             - wait for reassembly
346         """
347         pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
348                IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44) /
349                ICMPv6EchoRequest())
350
351         self.pg0.add_stream(pkt)
352         self.pg_start()
353
354         # wait for reassembly
355         self.sleep(10)
356
357     def test_fib(self):
358         """ IPv6 FIB test
359
360         Test scenario:
361             - Create IPv6 stream for pg0 interface
362             - Create IPv6 tagged streams for pg1's and pg2's subinterface.
363             - Send and verify received packets on each interface.
364         """
365
366         pkts = self.create_stream(self.pg0)
367         self.pg0.add_stream(pkts)
368
369         for i in self.sub_interfaces:
370             pkts = self.create_stream(i)
371             i.parent.add_stream(pkts)
372
373         self.pg_enable_capture(self.pg_interfaces)
374         self.pg_start()
375
376         pkts = self.pg0.get_capture()
377         self.verify_capture(self.pg0, pkts)
378
379         for i in self.sub_interfaces:
380             pkts = i.parent.get_capture()
381             self.verify_capture(i, pkts)
382
383     def test_ns(self):
384         """ IPv6 Neighbour Solicitation Exceptions
385
386         Test scenario:
387            - Send an NS Sourced from an address not covered by the link sub-net
388            - Send an NS to an mcast address the router has not joined
389            - Send NS for a target address the router does not onn.
390         """
391
392         #
393         # An NS from a non link source address
394         #
395         nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
396         d = inet_ntop(AF_INET6, nsma)
397
398         p = (Ether(dst=in6_getnsmac(nsma)) /
399              IPv6(dst=d, src="2002::2") /
400              ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
401              ICMPv6NDOptSrcLLAddr(
402                  lladdr=self.pg0.remote_mac))
403         pkts = [p]
404
405         self.send_and_assert_no_replies(
406             self.pg0, pkts,
407             "No response to NS source by address not on sub-net")
408
409         #
410         # An NS for sent to a solicited mcast group the router is
411         # not a member of FAILS
412         #
413         if 0:
414             nsma = in6_getnsma(inet_pton(AF_INET6, "fd::ffff"))
415             d = inet_ntop(AF_INET6, nsma)
416
417             p = (Ether(dst=in6_getnsmac(nsma)) /
418                  IPv6(dst=d, src=self.pg0.remote_ip6) /
419                  ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
420                  ICMPv6NDOptSrcLLAddr(
421                      lladdr=self.pg0.remote_mac))
422             pkts = [p]
423
424             self.send_and_assert_no_replies(
425                 self.pg0, pkts,
426                 "No response to NS sent to unjoined mcast address")
427
428         #
429         # An NS whose target address is one the router does not own
430         #
431         nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
432         d = inet_ntop(AF_INET6, nsma)
433
434         p = (Ether(dst=in6_getnsmac(nsma)) /
435              IPv6(dst=d, src=self.pg0.remote_ip6) /
436              ICMPv6ND_NS(tgt="fd::ffff") /
437              ICMPv6NDOptSrcLLAddr(
438                  lladdr=self.pg0.remote_mac))
439         pkts = [p]
440
441         self.send_and_assert_no_replies(self.pg0, pkts,
442                                         "No response to NS for unknown target")
443
444         #
445         # A neighbor entry that has no associated FIB-entry
446         #
447         self.pg0.generate_remote_hosts(4)
448         nd_entry = VppNeighbor(self,
449                                self.pg0.sw_if_index,
450                                self.pg0.remote_hosts[2].mac,
451                                self.pg0.remote_hosts[2].ip6,
452                                is_no_fib_entry=1)
453         nd_entry.add_vpp_config()
454
455         #
456         # check we have the neighbor, but no route
457         #
458         self.assertTrue(find_nbr(self,
459                                  self.pg0.sw_if_index,
460                                  self.pg0._remote_hosts[2].ip6))
461         self.assertFalse(find_route(self,
462                                     self.pg0._remote_hosts[2].ip6,
463                                     128))
464
465         #
466         # send an NS from a link local address to the interface's global
467         # address
468         #
469         p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
470              IPv6(
471                  dst=d, src=self.pg0._remote_hosts[2].ip6_ll) /
472              ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
473              ICMPv6NDOptSrcLLAddr(
474                  lladdr=self.pg0.remote_mac))
475
476         self.send_and_expect_na(self.pg0, p,
477                                 "NS from link-local",
478                                 dst_ip=self.pg0._remote_hosts[2].ip6_ll,
479                                 tgt_ip=self.pg0.local_ip6)
480
481         #
482         # we should have learned an ND entry for the peer's link-local
483         # but not inserted a route to it in the FIB
484         #
485         self.assertTrue(find_nbr(self,
486                                  self.pg0.sw_if_index,
487                                  self.pg0._remote_hosts[2].ip6_ll))
488         self.assertFalse(find_route(self,
489                                     self.pg0._remote_hosts[2].ip6_ll,
490                                     128))
491
492         #
493         # An NS to the router's own Link-local
494         #
495         p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
496              IPv6(
497                  dst=d, src=self.pg0._remote_hosts[3].ip6_ll) /
498              ICMPv6ND_NS(tgt=self.pg0.local_ip6_ll) /
499              ICMPv6NDOptSrcLLAddr(
500                  lladdr=self.pg0.remote_mac))
501
502         self.send_and_expect_na(self.pg0, p,
503                                 "NS to/from link-local",
504                                 dst_ip=self.pg0._remote_hosts[3].ip6_ll,
505                                 tgt_ip=self.pg0.local_ip6_ll)
506
507         #
508         # do not respond to a NS for the peer's address
509         #
510         p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
511              IPv6(dst=d,
512                   src=self.pg0._remote_hosts[3].ip6_ll) /
513              ICMPv6ND_NS(tgt=self.pg0._remote_hosts[3].ip6_ll) /
514              ICMPv6NDOptSrcLLAddr(
515                  lladdr=self.pg0.remote_mac))
516
517         self.send_and_assert_no_replies(self.pg0, p)
518
519         #
520         # we should have learned an ND entry for the peer's link-local
521         # but not inserted a route to it in the FIB
522         #
523         self.assertTrue(find_nbr(self,
524                                  self.pg0.sw_if_index,
525                                  self.pg0._remote_hosts[3].ip6_ll))
526         self.assertFalse(find_route(self,
527                                     self.pg0._remote_hosts[3].ip6_ll,
528                                     128))
529
530     def test_ns_duplicates(self):
531         """ ND Duplicates"""
532
533         #
534         # Generate some hosts on the LAN
535         #
536         self.pg1.generate_remote_hosts(3)
537
538         #
539         # Add host 1 on pg1 and pg2
540         #
541         ns_pg1 = VppNeighbor(self,
542                              self.pg1.sw_if_index,
543                              self.pg1.remote_hosts[1].mac,
544                              self.pg1.remote_hosts[1].ip6)
545         ns_pg1.add_vpp_config()
546         ns_pg2 = VppNeighbor(self,
547                              self.pg2.sw_if_index,
548                              self.pg2.remote_mac,
549                              self.pg1.remote_hosts[1].ip6)
550         ns_pg2.add_vpp_config()
551
552         #
553         # IP packet destined for pg1 remote host arrives on pg1 again.
554         #
555         p = (Ether(dst=self.pg0.local_mac,
556                    src=self.pg0.remote_mac) /
557              IPv6(src=self.pg0.remote_ip6,
558                   dst=self.pg1.remote_hosts[1].ip6) /
559              inet6.UDP(sport=1234, dport=1234) /
560              Raw())
561
562         self.pg0.add_stream(p)
563         self.pg_enable_capture(self.pg_interfaces)
564         self.pg_start()
565
566         rx1 = self.pg1.get_capture(1)
567
568         self.verify_ip(rx1[0],
569                        self.pg1.local_mac,
570                        self.pg1.remote_hosts[1].mac,
571                        self.pg0.remote_ip6,
572                        self.pg1.remote_hosts[1].ip6)
573
574         #
575         # remove the duplicate on pg1
576         # packet stream should generate NSs out of pg1
577         #
578         ns_pg1.remove_vpp_config()
579
580         self.send_and_expect_ns(self.pg0, self.pg1,
581                                 p, self.pg1.remote_hosts[1].ip6)
582
583         #
584         # Add it back
585         #
586         ns_pg1.add_vpp_config()
587
588         self.pg0.add_stream(p)
589         self.pg_enable_capture(self.pg_interfaces)
590         self.pg_start()
591
592         rx1 = self.pg1.get_capture(1)
593
594         self.verify_ip(rx1[0],
595                        self.pg1.local_mac,
596                        self.pg1.remote_hosts[1].mac,
597                        self.pg0.remote_ip6,
598                        self.pg1.remote_hosts[1].ip6)
599
600     def validate_ra(self, intf, rx, dst_ip=None, src_ip=None,
601                     mtu=9000, pi_opt=None):
602         if not dst_ip:
603             dst_ip = intf.remote_ip6
604         if not src_ip:
605             src_ip = mk_ll_addr(intf.local_mac)
606
607         # unicasted packets must come to the unicast mac
608         self.assertEqual(rx[Ether].dst, intf.remote_mac)
609
610         # and from the router's MAC
611         self.assertEqual(rx[Ether].src, intf.local_mac)
612
613         # the rx'd RA should be addressed to the sender's source
614         self.assertTrue(rx.haslayer(ICMPv6ND_RA))
615         self.assertEqual(in6_ptop(rx[IPv6].dst),
616                          in6_ptop(dst_ip))
617
618         # and come from the router's link local
619         self.assertTrue(in6_islladdr(rx[IPv6].src))
620         self.assertEqual(in6_ptop(rx[IPv6].src), in6_ptop(src_ip))
621
622         # it should contain the links MTU
623         ra = rx[ICMPv6ND_RA]
624         self.assertEqual(ra[ICMPv6NDOptMTU].mtu, mtu)
625
626         # it should contain the source's link layer address option
627         sll = ra[ICMPv6NDOptSrcLLAddr]
628         self.assertEqual(sll.lladdr, intf.local_mac)
629
630         if not pi_opt:
631             # the RA should not contain prefix information
632             self.assertFalse(ra.haslayer(
633                 ICMPv6NDOptPrefixInfo))
634         else:
635             raos = rx.getlayer(ICMPv6NDOptPrefixInfo, 1)
636
637             # the options are nested in the scapy packet in way that i cannot
638             # decipher how to decode. this 1st layer of option always returns
639             # nested classes, so a direct obj1=obj2 comparison always fails.
640             # however, the getlayer(.., 2) does give one instance.
641             # so we cheat here and construct a new opt instance for comparison
642             rd = ICMPv6NDOptPrefixInfo(
643                 prefixlen=raos.prefixlen,
644                 prefix=raos.prefix,
645                 L=raos.L,
646                 A=raos.A)
647             if type(pi_opt) is list:
648                 for ii in range(len(pi_opt)):
649                     self.assertEqual(pi_opt[ii], rd)
650                     rd = rx.getlayer(
651                         ICMPv6NDOptPrefixInfo, ii + 2)
652             else:
653                 self.assertEqual(pi_opt, raos, 'Expected: %s, received: %s'
654                                  % (pi_opt.show(dump=True),
655                                     raos.show(dump=True)))
656
657     def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None,
658                            filter_out_fn=is_ipv6_misc,
659                            opt=None,
660                            src_ip=None):
661         self.vapi.cli("clear trace")
662         intf.add_stream(pkts)
663         self.pg_enable_capture(self.pg_interfaces)
664         self.pg_start()
665         rx = intf.get_capture(1, filter_out_fn=filter_out_fn)
666
667         self.assertEqual(len(rx), 1)
668         rx = rx[0]
669         self.validate_ra(intf, rx, dst_ip, src_ip=src_ip, pi_opt=opt)
670
671     def test_rs(self):
672         """ IPv6 Router Solicitation Exceptions
673
674         Test scenario:
675         """
676
677         #
678         # Before we begin change the IPv6 RA responses to use the unicast
679         # address - that way we will not confuse them with the periodic
680         # RAs which go to the mcast address
681         # Sit and wait for the first periodic RA.
682         #
683         # TODO
684         #
685         self.pg0.ip6_ra_config(send_unicast=1)
686
687         #
688         # An RS from a link source address
689         #  - expect an RA in return
690         #
691         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
692              IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
693              ICMPv6ND_RS())
694         pkts = [p]
695         self.send_and_expect_ra(self.pg0, pkts, "Genuine RS")
696
697         #
698         # For the next RS sent the RA should be rate limited
699         #
700         self.send_and_assert_no_replies(self.pg0, pkts, "RA rate limited")
701
702         #
703         # When we reconfigure the IPv6 RA config,
704         # we reset the RA rate limiting,
705         # so we need to do this before each test below so as not to drop
706         # packets for rate limiting reasons. Test this works here.
707         #
708         self.pg0.ip6_ra_config(send_unicast=1)
709         self.send_and_expect_ra(self.pg0, pkts, "Rate limit reset RS")
710
711         #
712         # An RS sent from a non-link local source
713         #
714         self.pg0.ip6_ra_config(send_unicast=1)
715         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
716              IPv6(dst=self.pg0.local_ip6,
717                   src="2002::ffff") /
718              ICMPv6ND_RS())
719         pkts = [p]
720         self.send_and_assert_no_replies(self.pg0, pkts,
721                                         "RS from non-link source")
722
723         #
724         # Source an RS from a link local address
725         #
726         self.pg0.ip6_ra_config(send_unicast=1)
727         ll = mk_ll_addr(self.pg0.remote_mac)
728         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
729              IPv6(dst=self.pg0.local_ip6, src=ll) /
730              ICMPv6ND_RS())
731         pkts = [p]
732         self.send_and_expect_ra(self.pg0, pkts,
733                                 "RS sourced from link-local",
734                                 dst_ip=ll)
735
736         #
737         # Send the RS multicast
738         #
739         self.pg0.ip6_ra_config(send_unicast=1)
740         dmac = in6_getnsmac(inet_pton(AF_INET6, "ff02::2"))
741         ll = mk_ll_addr(self.pg0.remote_mac)
742         p = (Ether(dst=dmac, src=self.pg0.remote_mac) /
743              IPv6(dst="ff02::2", src=ll) /
744              ICMPv6ND_RS())
745         pkts = [p]
746         self.send_and_expect_ra(self.pg0, pkts,
747                                 "RS sourced from link-local",
748                                 dst_ip=ll)
749
750         #
751         # Source from the unspecified address ::. This happens when the RS
752         # is sent before the host has a configured address/sub-net,
753         # i.e. auto-config. Since the sender has no IP address, the reply
754         # comes back mcast - so the capture needs to not filter this.
755         # If we happen to pick up the periodic RA at this point then so be it,
756         # it's not an error.
757         #
758         self.pg0.ip6_ra_config(send_unicast=1, suppress=1)
759         p = (Ether(dst=dmac, src=self.pg0.remote_mac) /
760              IPv6(dst="ff02::2", src="::") /
761              ICMPv6ND_RS())
762         pkts = [p]
763         self.send_and_expect_ra(self.pg0, pkts,
764                                 "RS sourced from unspecified",
765                                 dst_ip="ff02::1",
766                                 filter_out_fn=None)
767
768         #
769         # Configure The RA to announce the links prefix
770         #
771         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
772                                self.pg0.local_ip6_prefix_len))
773
774         #
775         # RAs should now contain the prefix information option
776         #
777         opt = ICMPv6NDOptPrefixInfo(
778             prefixlen=self.pg0.local_ip6_prefix_len,
779             prefix=self.pg0.local_ip6,
780             L=1,
781             A=1)
782
783         self.pg0.ip6_ra_config(send_unicast=1)
784         ll = mk_ll_addr(self.pg0.remote_mac)
785         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
786              IPv6(dst=self.pg0.local_ip6, src=ll) /
787              ICMPv6ND_RS())
788         self.send_and_expect_ra(self.pg0, p,
789                                 "RA with prefix-info",
790                                 dst_ip=ll,
791                                 opt=opt)
792
793         #
794         # Change the prefix info to not off-link
795         #  L-flag is clear
796         #
797         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
798                                self.pg0.local_ip6_prefix_len),
799                                off_link=1)
800
801         opt = ICMPv6NDOptPrefixInfo(
802             prefixlen=self.pg0.local_ip6_prefix_len,
803             prefix=self.pg0.local_ip6,
804             L=0,
805             A=1)
806
807         self.pg0.ip6_ra_config(send_unicast=1)
808         self.send_and_expect_ra(self.pg0, p,
809                                 "RA with Prefix info with L-flag=0",
810                                 dst_ip=ll,
811                                 opt=opt)
812
813         #
814         # Change the prefix info to not off-link, no-autoconfig
815         #  L and A flag are clear in the advert
816         #
817         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
818                                self.pg0.local_ip6_prefix_len),
819                                off_link=1,
820                                no_autoconfig=1)
821
822         opt = ICMPv6NDOptPrefixInfo(
823             prefixlen=self.pg0.local_ip6_prefix_len,
824             prefix=self.pg0.local_ip6,
825             L=0,
826             A=0)
827
828         self.pg0.ip6_ra_config(send_unicast=1)
829         self.send_and_expect_ra(self.pg0, p,
830                                 "RA with Prefix info with A & L-flag=0",
831                                 dst_ip=ll,
832                                 opt=opt)
833
834         #
835         # Change the flag settings back to the defaults
836         #  L and A flag are set in the advert
837         #
838         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
839                                self.pg0.local_ip6_prefix_len))
840
841         opt = ICMPv6NDOptPrefixInfo(
842             prefixlen=self.pg0.local_ip6_prefix_len,
843             prefix=self.pg0.local_ip6,
844             L=1,
845             A=1)
846
847         self.pg0.ip6_ra_config(send_unicast=1)
848         self.send_and_expect_ra(self.pg0, p,
849                                 "RA with Prefix info",
850                                 dst_ip=ll,
851                                 opt=opt)
852
853         #
854         # Change the prefix info to not off-link, no-autoconfig
855         #  L and A flag are clear in the advert
856         #
857         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
858                                self.pg0.local_ip6_prefix_len),
859                                off_link=1,
860                                no_autoconfig=1)
861
862         opt = ICMPv6NDOptPrefixInfo(
863             prefixlen=self.pg0.local_ip6_prefix_len,
864             prefix=self.pg0.local_ip6,
865             L=0,
866             A=0)
867
868         self.pg0.ip6_ra_config(send_unicast=1)
869         self.send_and_expect_ra(self.pg0, p,
870                                 "RA with Prefix info with A & L-flag=0",
871                                 dst_ip=ll,
872                                 opt=opt)
873
874         #
875         # Use the reset to defaults option to revert to defaults
876         #  L and A flag are clear in the advert
877         #
878         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
879                                self.pg0.local_ip6_prefix_len),
880                                use_default=1)
881
882         opt = ICMPv6NDOptPrefixInfo(
883             prefixlen=self.pg0.local_ip6_prefix_len,
884             prefix=self.pg0.local_ip6,
885             L=1,
886             A=1)
887
888         self.pg0.ip6_ra_config(send_unicast=1)
889         self.send_and_expect_ra(self.pg0, p,
890                                 "RA with Prefix reverted to defaults",
891                                 dst_ip=ll,
892                                 opt=opt)
893
894         #
895         # Advertise Another prefix. With no L-flag/A-flag
896         #
897         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg1.local_ip6,
898                                self.pg1.local_ip6_prefix_len),
899                                off_link=1,
900                                no_autoconfig=1)
901
902         opt = [ICMPv6NDOptPrefixInfo(
903             prefixlen=self.pg0.local_ip6_prefix_len,
904             prefix=self.pg0.local_ip6,
905             L=1,
906             A=1),
907             ICMPv6NDOptPrefixInfo(
908                 prefixlen=self.pg1.local_ip6_prefix_len,
909                 prefix=self.pg1.local_ip6,
910                 L=0,
911                 A=0)]
912
913         self.pg0.ip6_ra_config(send_unicast=1)
914         ll = mk_ll_addr(self.pg0.remote_mac)
915         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
916              IPv6(dst=self.pg0.local_ip6, src=ll) /
917              ICMPv6ND_RS())
918         self.send_and_expect_ra(self.pg0, p,
919                                 "RA with multiple Prefix infos",
920                                 dst_ip=ll,
921                                 opt=opt)
922
923         #
924         # Remove the first prefix-info - expect the second is still in the
925         # advert
926         #
927         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
928                                self.pg0.local_ip6_prefix_len),
929                                is_no=1)
930
931         opt = ICMPv6NDOptPrefixInfo(
932             prefixlen=self.pg1.local_ip6_prefix_len,
933             prefix=self.pg1.local_ip6,
934             L=0,
935             A=0)
936
937         self.pg0.ip6_ra_config(send_unicast=1)
938         self.send_and_expect_ra(self.pg0, p,
939                                 "RA with Prefix reverted to defaults",
940                                 dst_ip=ll,
941                                 opt=opt)
942
943         #
944         # Remove the second prefix-info - expect no prefix-info in the adverts
945         #
946         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg1.local_ip6,
947                                self.pg1.local_ip6_prefix_len),
948                                is_no=1)
949
950         #
951         # change the link's link local, so we know that works too.
952         #
953         self.vapi.sw_interface_ip6_set_link_local_address(
954             sw_if_index=self.pg0.sw_if_index,
955             ip="fe80::88")
956
957         self.pg0.ip6_ra_config(send_unicast=1)
958         self.send_and_expect_ra(self.pg0, p,
959                                 "RA with Prefix reverted to defaults",
960                                 dst_ip=ll,
961                                 src_ip="fe80::88")
962
963         #
964         # Reset the periodic advertisements back to default values
965         #
966         self.pg0.ip6_ra_config(no=1, suppress=1, send_unicast=0)
967
968     def test_mld(self):
969         """ MLD Report """
970         #
971         # test one MLD is sent after applying an IPv6 Address on an interface
972         #
973         self.pg_enable_capture(self.pg_interfaces)
974         self.pg_start()
975
976         subitf = VppDot1QSubint(self, self.pg1, 99)
977
978         subitf.admin_up()
979         subitf.config_ip6()
980
981         rxs = self.pg1._get_capture(timeout=4, filter_out_fn=None)
982
983         #
984         # hunt for the MLD on vlan 99
985         #
986         for rx in rxs:
987             # make sure ipv6 packets with hop by hop options have
988             # correct checksums
989             self.assert_packet_checksums_valid(rx)
990             if rx.haslayer(IPv6ExtHdrHopByHop) and \
991                rx.haslayer(Dot1Q) and \
992                rx[Dot1Q].vlan == 99:
993                 mld = rx[ICMPv6MLReport2]
994
995         self.assertEqual(mld.records_number, 4)
996
997
998 class TestIPv6RouteLookup(VppTestCase):
999     """ IPv6 Route Lookup Test Case """
1000     routes = []
1001
1002     def route_lookup(self, prefix, exact):
1003         return self.vapi.api(self.vapi.papi.ip_route_lookup,
1004                              {
1005                                  'table_id': 0,
1006                                  'exact': exact,
1007                                  'prefix': prefix,
1008                              })
1009
1010     @classmethod
1011     def setUpClass(cls):
1012         super(TestIPv6RouteLookup, cls).setUpClass()
1013
1014     @classmethod
1015     def tearDownClass(cls):
1016         super(TestIPv6RouteLookup, cls).tearDownClass()
1017
1018     def setUp(self):
1019         super(TestIPv6RouteLookup, self).setUp()
1020
1021         drop_nh = VppRoutePath("::1", 0xffffffff,
1022                                type=FibPathType.FIB_PATH_TYPE_DROP)
1023
1024         # Add 3 routes
1025         r = VppIpRoute(self, "2001:1111::", 32, [drop_nh])
1026         r.add_vpp_config()
1027         self.routes.append(r)
1028
1029         r = VppIpRoute(self, "2001:1111:2222::", 48, [drop_nh])
1030         r.add_vpp_config()
1031         self.routes.append(r)
1032
1033         r = VppIpRoute(self, "2001:1111:2222::1", 128, [drop_nh])
1034         r.add_vpp_config()
1035         self.routes.append(r)
1036
1037     def tearDown(self):
1038         # Remove the routes we added
1039         for r in self.routes:
1040             r.remove_vpp_config()
1041
1042         super(TestIPv6RouteLookup, self).tearDown()
1043
1044     def test_exact_match(self):
1045         # Verify we find the host route
1046         prefix = "2001:1111:2222::1/128"
1047         result = self.route_lookup(prefix, True)
1048         assert (prefix == str(result.route.prefix))
1049
1050         # Verify we find a middle prefix route
1051         prefix = "2001:1111:2222::/48"
1052         result = self.route_lookup(prefix, True)
1053         assert (prefix == str(result.route.prefix))
1054
1055         # Verify we do not find an available LPM.
1056         with self.vapi.assert_negative_api_retval():
1057             self.route_lookup("2001::2/128", True)
1058
1059     def test_longest_prefix_match(self):
1060         # verify we find lpm
1061         lpm_prefix = "2001:1111:2222::/48"
1062         result = self.route_lookup("2001:1111:2222::2/128", False)
1063         assert (lpm_prefix == str(result.route.prefix))
1064
1065         # Verify we find the exact when not requested
1066         result = self.route_lookup(lpm_prefix, False)
1067         assert (lpm_prefix == str(result.route.prefix))
1068
1069         # Can't seem to delete the default route so no negative LPM test.
1070
1071
1072 class TestIPv6IfAddrRoute(VppTestCase):
1073     """ IPv6 Interface Addr Route Test Case """
1074
1075     @classmethod
1076     def setUpClass(cls):
1077         super(TestIPv6IfAddrRoute, cls).setUpClass()
1078
1079     @classmethod
1080     def tearDownClass(cls):
1081         super(TestIPv6IfAddrRoute, cls).tearDownClass()
1082
1083     def setUp(self):
1084         super(TestIPv6IfAddrRoute, self).setUp()
1085
1086         # create 1 pg interface
1087         self.create_pg_interfaces(range(1))
1088
1089         for i in self.pg_interfaces:
1090             i.admin_up()
1091             i.config_ip6()
1092             i.resolve_ndp()
1093
1094     def tearDown(self):
1095         super(TestIPv6IfAddrRoute, self).tearDown()
1096         for i in self.pg_interfaces:
1097             i.unconfig_ip6()
1098             i.admin_down()
1099
1100     def test_ipv6_ifaddrs_same_prefix(self):
1101         """ IPv6 Interface Addresses Same Prefix test
1102
1103         Test scenario:
1104
1105             - Verify no route in FIB for prefix 2001:10::/64
1106             - Configure IPv4 address 2001:10::10/64  on an interface
1107             - Verify route in FIB for prefix 2001:10::/64
1108             - Configure IPv4 address 2001:10::20/64 on an interface
1109             - Delete 2001:10::10/64 from interface
1110             - Verify route in FIB for prefix 2001:10::/64
1111             - Delete 2001:10::20/64 from interface
1112             - Verify no route in FIB for prefix 2001:10::/64
1113         """
1114
1115         addr1 = "2001:10::10"
1116         addr2 = "2001:10::20"
1117
1118         if_addr1 = VppIpInterfaceAddress(self, self.pg0, addr1, 64)
1119         if_addr2 = VppIpInterfaceAddress(self, self.pg0, addr2, 64)
1120         self.assertFalse(if_addr1.query_vpp_config())
1121         self.assertFalse(find_route(self, addr1, 128))
1122         self.assertFalse(find_route(self, addr2, 128))
1123
1124         # configure first address, verify route present
1125         if_addr1.add_vpp_config()
1126         self.assertTrue(if_addr1.query_vpp_config())
1127         self.assertTrue(find_route(self, addr1, 128))
1128         self.assertFalse(find_route(self, addr2, 128))
1129
1130         # configure second address, delete first, verify route not removed
1131         if_addr2.add_vpp_config()
1132         if_addr1.remove_vpp_config()
1133         self.assertFalse(if_addr1.query_vpp_config())
1134         self.assertTrue(if_addr2.query_vpp_config())
1135         self.assertFalse(find_route(self, addr1, 128))
1136         self.assertTrue(find_route(self, addr2, 128))
1137
1138         # delete second address, verify route removed
1139         if_addr2.remove_vpp_config()
1140         self.assertFalse(if_addr1.query_vpp_config())
1141         self.assertFalse(find_route(self, addr1, 128))
1142         self.assertFalse(find_route(self, addr2, 128))
1143
1144     def test_ipv6_ifaddr_del(self):
1145         """ Delete an interface address that does not exist """
1146
1147         loopbacks = self.create_loopback_interfaces(1)
1148         lo = self.lo_interfaces[0]
1149
1150         lo.config_ip6()
1151         lo.admin_up()
1152
1153         #
1154         # try and remove pg0's subnet from lo
1155         #
1156         with self.vapi.assert_negative_api_retval():
1157             self.vapi.sw_interface_add_del_address(
1158                 sw_if_index=lo.sw_if_index,
1159                 prefix=self.pg0.local_ip6_prefix,
1160                 is_add=0)
1161
1162
1163 class TestICMPv6Echo(VppTestCase):
1164     """ ICMPv6 Echo Test Case """
1165
1166     @classmethod
1167     def setUpClass(cls):
1168         super(TestICMPv6Echo, cls).setUpClass()
1169
1170     @classmethod
1171     def tearDownClass(cls):
1172         super(TestICMPv6Echo, cls).tearDownClass()
1173
1174     def setUp(self):
1175         super(TestICMPv6Echo, self).setUp()
1176
1177         # create 1 pg interface
1178         self.create_pg_interfaces(range(1))
1179
1180         for i in self.pg_interfaces:
1181             i.admin_up()
1182             i.config_ip6()
1183             i.resolve_ndp(link_layer=True)
1184             i.resolve_ndp()
1185
1186     def tearDown(self):
1187         super(TestICMPv6Echo, self).tearDown()
1188         for i in self.pg_interfaces:
1189             i.unconfig_ip6()
1190             i.admin_down()
1191
1192     def test_icmpv6_echo(self):
1193         """ VPP replies to ICMPv6 Echo Request
1194
1195         Test scenario:
1196
1197             - Receive ICMPv6 Echo Request message on pg0 interface.
1198             - Check outgoing ICMPv6 Echo Reply message on pg0 interface.
1199         """
1200
1201         # test both with global and local ipv6 addresses
1202         dsts = (self.pg0.local_ip6, self.pg0.local_ip6_ll)
1203         id = 0xb
1204         seq = 5
1205         data = b'\x0a' * 18
1206         p = list()
1207         for dst in dsts:
1208             p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
1209                       IPv6(src=self.pg0.remote_ip6, dst=dst) /
1210                       ICMPv6EchoRequest(id=id, seq=seq, data=data)))
1211
1212         self.pg0.add_stream(p)
1213         self.pg_enable_capture(self.pg_interfaces)
1214         self.pg_start()
1215         rxs = self.pg0.get_capture(len(dsts))
1216
1217         for rx, dst in zip(rxs, dsts):
1218             ether = rx[Ether]
1219             ipv6 = rx[IPv6]
1220             icmpv6 = rx[ICMPv6EchoReply]
1221             self.assertEqual(ether.src, self.pg0.local_mac)
1222             self.assertEqual(ether.dst, self.pg0.remote_mac)
1223             self.assertEqual(ipv6.src, dst)
1224             self.assertEqual(ipv6.dst, self.pg0.remote_ip6)
1225             self.assertEqual(icmp6types[icmpv6.type], "Echo Reply")
1226             self.assertEqual(icmpv6.id, id)
1227             self.assertEqual(icmpv6.seq, seq)
1228             self.assertEqual(icmpv6.data, data)
1229
1230
1231 class TestIPv6RD(TestIPv6ND):
1232     """ IPv6 Router Discovery Test Case """
1233
1234     @classmethod
1235     def setUpClass(cls):
1236         super(TestIPv6RD, cls).setUpClass()
1237
1238     @classmethod
1239     def tearDownClass(cls):
1240         super(TestIPv6RD, cls).tearDownClass()
1241
1242     def setUp(self):
1243         super(TestIPv6RD, self).setUp()
1244
1245         # create 2 pg interfaces
1246         self.create_pg_interfaces(range(2))
1247
1248         self.interfaces = list(self.pg_interfaces)
1249
1250         # setup all interfaces
1251         for i in self.interfaces:
1252             i.admin_up()
1253             i.config_ip6()
1254
1255     def tearDown(self):
1256         for i in self.interfaces:
1257             i.unconfig_ip6()
1258             i.admin_down()
1259         super(TestIPv6RD, self).tearDown()
1260
1261     def test_rd_send_router_solicitation(self):
1262         """ Verify router solicitation packets """
1263
1264         count = 2
1265         self.pg_enable_capture(self.pg_interfaces)
1266         self.pg_start()
1267         self.vapi.ip6nd_send_router_solicitation(self.pg1.sw_if_index,
1268                                                  mrc=count)
1269         rx_list = self.pg1.get_capture(count, timeout=3)
1270         self.assertEqual(len(rx_list), count)
1271         for packet in rx_list:
1272             self.assertEqual(packet.haslayer(IPv6), 1)
1273             self.assertEqual(packet[IPv6].haslayer(
1274                 ICMPv6ND_RS), 1)
1275             dst = ip6_normalize(packet[IPv6].dst)
1276             dst2 = ip6_normalize("ff02::2")
1277             self.assert_equal(dst, dst2)
1278             src = ip6_normalize(packet[IPv6].src)
1279             src2 = ip6_normalize(self.pg1.local_ip6_ll)
1280             self.assert_equal(src, src2)
1281             self.assertTrue(
1282                 bool(packet[ICMPv6ND_RS].haslayer(
1283                     ICMPv6NDOptSrcLLAddr)))
1284             self.assert_equal(
1285                 packet[ICMPv6NDOptSrcLLAddr].lladdr,
1286                 self.pg1.local_mac)
1287
1288     def verify_prefix_info(self, reported_prefix, prefix_option):
1289         prefix = IPv6Network(
1290             text_type(prefix_option.getfieldval("prefix") +
1291                       "/" +
1292                       text_type(prefix_option.getfieldval("prefixlen"))),
1293             strict=False)
1294         self.assert_equal(reported_prefix.prefix.network_address,
1295                           prefix.network_address)
1296         L = prefix_option.getfieldval("L")
1297         A = prefix_option.getfieldval("A")
1298         option_flags = (L << 7) | (A << 6)
1299         self.assert_equal(reported_prefix.flags, option_flags)
1300         self.assert_equal(reported_prefix.valid_time,
1301                           prefix_option.getfieldval("validlifetime"))
1302         self.assert_equal(reported_prefix.preferred_time,
1303                           prefix_option.getfieldval("preferredlifetime"))
1304
1305     def test_rd_receive_router_advertisement(self):
1306         """ Verify events triggered by received RA packets """
1307
1308         self.vapi.want_ip6_ra_events(enable=1)
1309
1310         prefix_info_1 = ICMPv6NDOptPrefixInfo(
1311             prefix="1::2",
1312             prefixlen=50,
1313             validlifetime=200,
1314             preferredlifetime=500,
1315             L=1,
1316             A=1,
1317         )
1318
1319         prefix_info_2 = ICMPv6NDOptPrefixInfo(
1320             prefix="7::4",
1321             prefixlen=20,
1322             validlifetime=70,
1323             preferredlifetime=1000,
1324             L=1,
1325             A=0,
1326         )
1327
1328         p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
1329              IPv6(dst=self.pg1.local_ip6_ll,
1330                   src=mk_ll_addr(self.pg1.remote_mac)) /
1331              ICMPv6ND_RA() /
1332              prefix_info_1 /
1333              prefix_info_2)
1334         self.pg1.add_stream([p])
1335         self.pg_start()
1336
1337         ev = self.vapi.wait_for_event(10, "ip6_ra_event")
1338
1339         self.assert_equal(ev.current_hop_limit, 0)
1340         self.assert_equal(ev.flags, 8)
1341         self.assert_equal(ev.router_lifetime_in_sec, 1800)
1342         self.assert_equal(ev.neighbor_reachable_time_in_msec, 0)
1343         self.assert_equal(
1344             ev.time_in_msec_between_retransmitted_neighbor_solicitations, 0)
1345
1346         self.assert_equal(ev.n_prefixes, 2)
1347
1348         self.verify_prefix_info(ev.prefixes[0], prefix_info_1)
1349         self.verify_prefix_info(ev.prefixes[1], prefix_info_2)
1350
1351
1352 class TestIPv6RDControlPlane(TestIPv6ND):
1353     """ IPv6 Router Discovery Control Plane Test Case """
1354
1355     @classmethod
1356     def setUpClass(cls):
1357         super(TestIPv6RDControlPlane, cls).setUpClass()
1358
1359     @classmethod
1360     def tearDownClass(cls):
1361         super(TestIPv6RDControlPlane, cls).tearDownClass()
1362
1363     def setUp(self):
1364         super(TestIPv6RDControlPlane, self).setUp()
1365
1366         # create 1 pg interface
1367         self.create_pg_interfaces(range(1))
1368
1369         self.interfaces = list(self.pg_interfaces)
1370
1371         # setup all interfaces
1372         for i in self.interfaces:
1373             i.admin_up()
1374             i.config_ip6()
1375
1376     def tearDown(self):
1377         super(TestIPv6RDControlPlane, self).tearDown()
1378
1379     @staticmethod
1380     def create_ra_packet(pg, routerlifetime=None):
1381         src_ip = pg.remote_ip6_ll
1382         dst_ip = pg.local_ip6
1383         if routerlifetime is not None:
1384             ra = ICMPv6ND_RA(routerlifetime=routerlifetime)
1385         else:
1386             ra = ICMPv6ND_RA()
1387         p = (Ether(dst=pg.local_mac, src=pg.remote_mac) /
1388              IPv6(dst=dst_ip, src=src_ip) / ra)
1389         return p
1390
1391     @staticmethod
1392     def get_default_routes(fib):
1393         list = []
1394         for entry in fib:
1395             if entry.route.prefix.prefixlen == 0:
1396                 for path in entry.route.paths:
1397                     if path.sw_if_index != 0xFFFFFFFF:
1398                         defaut_route = {}
1399                         defaut_route['sw_if_index'] = path.sw_if_index
1400                         defaut_route['next_hop'] = path.nh.address.ip6
1401                         list.append(defaut_route)
1402         return list
1403
1404     @staticmethod
1405     def get_interface_addresses(fib, pg):
1406         list = []
1407         for entry in fib:
1408             if entry.route.prefix.prefixlen == 128:
1409                 path = entry.route.paths[0]
1410                 if path.sw_if_index == pg.sw_if_index:
1411                     list.append(str(entry.route.prefix.network_address))
1412         return list
1413
1414     def wait_for_no_default_route(self, n_tries=50, s_time=1):
1415         while (n_tries):
1416             fib = self.vapi.ip_route_dump(0, True)
1417             default_routes = self.get_default_routes(fib)
1418             if 0 == len(default_routes):
1419                 return True
1420             n_tries = n_tries - 1
1421             self.sleep(s_time)
1422
1423         return False
1424
1425     def test_all(self):
1426         """ Test handling of SLAAC addresses and default routes """
1427
1428         fib = self.vapi.ip_route_dump(0, True)
1429         default_routes = self.get_default_routes(fib)
1430         initial_addresses = set(self.get_interface_addresses(fib, self.pg0))
1431         self.assertEqual(default_routes, [])
1432         router_address = IPv6Address(text_type(self.pg0.remote_ip6_ll))
1433
1434         self.vapi.ip6_nd_address_autoconfig(self.pg0.sw_if_index, 1, 1)
1435
1436         self.sleep(0.1)
1437
1438         # send RA
1439         packet = (self.create_ra_packet(
1440             self.pg0) / ICMPv6NDOptPrefixInfo(
1441             prefix="1::",
1442             prefixlen=64,
1443             validlifetime=2,
1444             preferredlifetime=2,
1445             L=1,
1446             A=1,
1447         ) / ICMPv6NDOptPrefixInfo(
1448             prefix="7::",
1449             prefixlen=20,
1450             validlifetime=1500,
1451             preferredlifetime=1000,
1452             L=1,
1453             A=0,
1454         ))
1455         self.pg0.add_stream([packet])
1456         self.pg_start()
1457
1458         self.sleep_on_vpp_time(0.1)
1459
1460         fib = self.vapi.ip_route_dump(0, True)
1461
1462         # check FIB for new address
1463         addresses = set(self.get_interface_addresses(fib, self.pg0))
1464         new_addresses = addresses.difference(initial_addresses)
1465         self.assertEqual(len(new_addresses), 1)
1466         prefix = IPv6Network(text_type("%s/%d" % (list(new_addresses)[0], 20)),
1467                              strict=False)
1468         self.assertEqual(prefix, IPv6Network(text_type('1::/20')))
1469
1470         # check FIB for new default route
1471         default_routes = self.get_default_routes(fib)
1472         self.assertEqual(len(default_routes), 1)
1473         dr = default_routes[0]
1474         self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
1475         self.assertEqual(dr['next_hop'], router_address)
1476
1477         # send RA to delete default route
1478         packet = self.create_ra_packet(self.pg0, routerlifetime=0)
1479         self.pg0.add_stream([packet])
1480         self.pg_start()
1481
1482         self.sleep_on_vpp_time(0.1)
1483
1484         # check that default route is deleted
1485         fib = self.vapi.ip_route_dump(0, True)
1486         default_routes = self.get_default_routes(fib)
1487         self.assertEqual(len(default_routes), 0)
1488
1489         self.sleep_on_vpp_time(0.1)
1490
1491         # send RA
1492         packet = self.create_ra_packet(self.pg0)
1493         self.pg0.add_stream([packet])
1494         self.pg_start()
1495
1496         self.sleep_on_vpp_time(0.1)
1497
1498         # check FIB for new default route
1499         fib = self.vapi.ip_route_dump(0, True)
1500         default_routes = self.get_default_routes(fib)
1501         self.assertEqual(len(default_routes), 1)
1502         dr = default_routes[0]
1503         self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
1504         self.assertEqual(dr['next_hop'], router_address)
1505
1506         # send RA, updating router lifetime to 1s
1507         packet = self.create_ra_packet(self.pg0, 1)
1508         self.pg0.add_stream([packet])
1509         self.pg_start()
1510
1511         self.sleep_on_vpp_time(0.1)
1512
1513         # check that default route still exists
1514         fib = self.vapi.ip_route_dump(0, True)
1515         default_routes = self.get_default_routes(fib)
1516         self.assertEqual(len(default_routes), 1)
1517         dr = default_routes[0]
1518         self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
1519         self.assertEqual(dr['next_hop'], router_address)
1520
1521         self.sleep_on_vpp_time(1)
1522
1523         # check that default route is deleted
1524         self.assertTrue(self.wait_for_no_default_route())
1525
1526         # check FIB still contains the SLAAC address
1527         addresses = set(self.get_interface_addresses(fib, self.pg0))
1528         new_addresses = addresses.difference(initial_addresses)
1529
1530         self.assertEqual(len(new_addresses), 1)
1531         prefix = IPv6Network(text_type("%s/%d" % (list(new_addresses)[0], 20)),
1532                              strict=False)
1533         self.assertEqual(prefix, IPv6Network(text_type('1::/20')))
1534
1535         self.sleep_on_vpp_time(1)
1536
1537         # check that SLAAC address is deleted
1538         fib = self.vapi.ip_route_dump(0, True)
1539         addresses = set(self.get_interface_addresses(fib, self.pg0))
1540         new_addresses = addresses.difference(initial_addresses)
1541         self.assertEqual(len(new_addresses), 0)
1542
1543
1544 class IPv6NDProxyTest(TestIPv6ND):
1545     """ IPv6 ND ProxyTest Case """
1546
1547     @classmethod
1548     def setUpClass(cls):
1549         super(IPv6NDProxyTest, cls).setUpClass()
1550
1551     @classmethod
1552     def tearDownClass(cls):
1553         super(IPv6NDProxyTest, cls).tearDownClass()
1554
1555     def setUp(self):
1556         super(IPv6NDProxyTest, self).setUp()
1557
1558         # create 3 pg interfaces
1559         self.create_pg_interfaces(range(3))
1560
1561         # pg0 is the master interface, with the configured subnet
1562         self.pg0.admin_up()
1563         self.pg0.config_ip6()
1564         self.pg0.resolve_ndp()
1565
1566         self.pg1.ip6_enable()
1567         self.pg2.ip6_enable()
1568
1569     def tearDown(self):
1570         super(IPv6NDProxyTest, self).tearDown()
1571
1572     def test_nd_proxy(self):
1573         """ IPv6 Proxy ND """
1574
1575         #
1576         # Generate some hosts in the subnet that we are proxying
1577         #
1578         self.pg0.generate_remote_hosts(8)
1579
1580         nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
1581         d = inet_ntop(AF_INET6, nsma)
1582
1583         #
1584         # Send an NS for one of those remote hosts on one of the proxy links
1585         # expect no response since it's from an address that is not
1586         # on the link that has the prefix configured
1587         #
1588         ns_pg1 = (Ether(dst=in6_getnsmac(nsma), src=self.pg1.remote_mac) /
1589                   IPv6(dst=d,
1590                        src=self.pg0._remote_hosts[2].ip6) /
1591                   ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
1592                   ICMPv6NDOptSrcLLAddr(
1593                       lladdr=self.pg0._remote_hosts[2].mac))
1594
1595         self.send_and_assert_no_replies(self.pg1, ns_pg1, "Off link NS")
1596
1597         #
1598         # Add proxy support for the host
1599         #
1600         self.vapi.ip6nd_proxy_add_del(
1601             is_add=1, ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6),
1602             sw_if_index=self.pg1.sw_if_index)
1603
1604         #
1605         # try that NS again. this time we expect an NA back
1606         #
1607         self.send_and_expect_na(self.pg1, ns_pg1,
1608                                 "NS to proxy entry",
1609                                 dst_ip=self.pg0._remote_hosts[2].ip6,
1610                                 tgt_ip=self.pg0.local_ip6)
1611
1612         #
1613         # ... and that we have an entry in the ND cache
1614         #
1615         self.assertTrue(find_nbr(self,
1616                                  self.pg1.sw_if_index,
1617                                  self.pg0._remote_hosts[2].ip6))
1618
1619         #
1620         # ... and we can route traffic to it
1621         #
1622         t = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
1623              IPv6(dst=self.pg0._remote_hosts[2].ip6,
1624                   src=self.pg0.remote_ip6) /
1625              inet6.UDP(sport=10000, dport=20000) /
1626              Raw(b'\xa5' * 100))
1627
1628         self.pg0.add_stream(t)
1629         self.pg_enable_capture(self.pg_interfaces)
1630         self.pg_start()
1631         rx = self.pg1.get_capture(1)
1632         rx = rx[0]
1633
1634         self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac)
1635         self.assertEqual(rx[Ether].src, self.pg1.local_mac)
1636
1637         self.assertEqual(rx[IPv6].src,
1638                          t[IPv6].src)
1639         self.assertEqual(rx[IPv6].dst,
1640                          t[IPv6].dst)
1641
1642         #
1643         # Test we proxy for the host on the main interface
1644         #
1645         ns_pg0 = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
1646                   IPv6(dst=d, src=self.pg0.remote_ip6) /
1647                   ICMPv6ND_NS(
1648                       tgt=self.pg0._remote_hosts[2].ip6) /
1649                   ICMPv6NDOptSrcLLAddr(
1650                       lladdr=self.pg0.remote_mac))
1651
1652         self.send_and_expect_na(self.pg0, ns_pg0,
1653                                 "NS to proxy entry on main",
1654                                 tgt_ip=self.pg0._remote_hosts[2].ip6,
1655                                 dst_ip=self.pg0.remote_ip6)
1656
1657         #
1658         # Setup and resolve proxy for another host on another interface
1659         #
1660         ns_pg2 = (Ether(dst=in6_getnsmac(nsma), src=self.pg2.remote_mac) /
1661                   IPv6(dst=d,
1662                        src=self.pg0._remote_hosts[3].ip6) /
1663                   ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
1664                   ICMPv6NDOptSrcLLAddr(
1665                       lladdr=self.pg0._remote_hosts[2].mac))
1666
1667         self.vapi.ip6nd_proxy_add_del(
1668             is_add=1, ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6),
1669             sw_if_index=self.pg2.sw_if_index)
1670
1671         self.send_and_expect_na(self.pg2, ns_pg2,
1672                                 "NS to proxy entry other interface",
1673                                 dst_ip=self.pg0._remote_hosts[3].ip6,
1674                                 tgt_ip=self.pg0.local_ip6)
1675
1676         self.assertTrue(find_nbr(self,
1677                                  self.pg2.sw_if_index,
1678                                  self.pg0._remote_hosts[3].ip6))
1679
1680         #
1681         # hosts can communicate. pg2->pg1
1682         #
1683         t2 = (Ether(dst=self.pg2.local_mac,
1684                     src=self.pg0.remote_hosts[3].mac) /
1685               IPv6(dst=self.pg0._remote_hosts[2].ip6,
1686                    src=self.pg0._remote_hosts[3].ip6) /
1687               inet6.UDP(sport=10000, dport=20000) /
1688               Raw(b'\xa5' * 100))
1689
1690         self.pg2.add_stream(t2)
1691         self.pg_enable_capture(self.pg_interfaces)
1692         self.pg_start()
1693         rx = self.pg1.get_capture(1)
1694         rx = rx[0]
1695
1696         self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac)
1697         self.assertEqual(rx[Ether].src, self.pg1.local_mac)
1698
1699         self.assertEqual(rx[IPv6].src,
1700                          t2[IPv6].src)
1701         self.assertEqual(rx[IPv6].dst,
1702                          t2[IPv6].dst)
1703
1704         #
1705         # remove the proxy configs
1706         #
1707         self.vapi.ip6nd_proxy_add_del(
1708             ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6),
1709             sw_if_index=self.pg1.sw_if_index, is_add=0)
1710         self.vapi.ip6nd_proxy_add_del(
1711             ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6),
1712             sw_if_index=self.pg2.sw_if_index, is_add=0)
1713
1714         self.assertFalse(find_nbr(self,
1715                                   self.pg2.sw_if_index,
1716                                   self.pg0._remote_hosts[3].ip6))
1717         self.assertFalse(find_nbr(self,
1718                                   self.pg1.sw_if_index,
1719                                   self.pg0._remote_hosts[2].ip6))
1720
1721         #
1722         # no longer proxy-ing...
1723         #
1724         self.send_and_assert_no_replies(self.pg0, ns_pg0, "Proxy unconfigured")
1725         self.send_and_assert_no_replies(self.pg1, ns_pg1, "Proxy unconfigured")
1726         self.send_and_assert_no_replies(self.pg2, ns_pg2, "Proxy unconfigured")
1727
1728         #
1729         # no longer forwarding. traffic generates NS out of the glean/main
1730         # interface
1731         #
1732         self.pg2.add_stream(t2)
1733         self.pg_enable_capture(self.pg_interfaces)
1734         self.pg_start()
1735
1736         rx = self.pg0.get_capture(1)
1737
1738         self.assertTrue(rx[0].haslayer(ICMPv6ND_NS))
1739
1740
1741 class TestIPNull(VppTestCase):
1742     """ IPv6 routes via NULL """
1743
1744     @classmethod
1745     def setUpClass(cls):
1746         super(TestIPNull, cls).setUpClass()
1747
1748     @classmethod
1749     def tearDownClass(cls):
1750         super(TestIPNull, cls).tearDownClass()
1751
1752     def setUp(self):
1753         super(TestIPNull, self).setUp()
1754
1755         # create 2 pg interfaces
1756         self.create_pg_interfaces(range(1))
1757
1758         for i in self.pg_interfaces:
1759             i.admin_up()
1760             i.config_ip6()
1761             i.resolve_ndp()
1762
1763     def tearDown(self):
1764         super(TestIPNull, self).tearDown()
1765         for i in self.pg_interfaces:
1766             i.unconfig_ip6()
1767             i.admin_down()
1768
1769     def test_ip_null(self):
1770         """ IP NULL route """
1771
1772         p = (Ether(src=self.pg0.remote_mac,
1773                    dst=self.pg0.local_mac) /
1774              IPv6(src=self.pg0.remote_ip6, dst="2001::1") /
1775              inet6.UDP(sport=1234, dport=1234) /
1776              Raw(b'\xa5' * 100))
1777
1778         #
1779         # A route via IP NULL that will reply with ICMP unreachables
1780         #
1781         ip_unreach = VppIpRoute(
1782             self, "2001::", 64,
1783             [VppRoutePath("::", 0xffffffff,
1784                           type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH)])
1785         ip_unreach.add_vpp_config()
1786
1787         self.pg0.add_stream(p)
1788         self.pg_enable_capture(self.pg_interfaces)
1789         self.pg_start()
1790
1791         rx = self.pg0.get_capture(1)
1792         rx = rx[0]
1793         icmp = rx[ICMPv6DestUnreach]
1794
1795         # 0 = "No route to destination"
1796         self.assertEqual(icmp.code, 0)
1797
1798         # ICMP is rate limited. pause a bit
1799         self.sleep(1)
1800
1801         #
1802         # A route via IP NULL that will reply with ICMP prohibited
1803         #
1804         ip_prohibit = VppIpRoute(
1805             self, "2001::1", 128,
1806             [VppRoutePath("::", 0xffffffff,
1807                           type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT)])
1808         ip_prohibit.add_vpp_config()
1809
1810         self.pg0.add_stream(p)
1811         self.pg_enable_capture(self.pg_interfaces)
1812         self.pg_start()
1813
1814         rx = self.pg0.get_capture(1)
1815         rx = rx[0]
1816         icmp = rx[ICMPv6DestUnreach]
1817
1818         # 1 = "Communication with destination administratively prohibited"
1819         self.assertEqual(icmp.code, 1)
1820
1821
1822 class TestIPDisabled(VppTestCase):
1823     """ IPv6 disabled """
1824
1825     @classmethod
1826     def setUpClass(cls):
1827         super(TestIPDisabled, cls).setUpClass()
1828
1829     @classmethod
1830     def tearDownClass(cls):
1831         super(TestIPDisabled, cls).tearDownClass()
1832
1833     def setUp(self):
1834         super(TestIPDisabled, self).setUp()
1835
1836         # create 2 pg interfaces
1837         self.create_pg_interfaces(range(2))
1838
1839         # PG0 is IP enabled
1840         self.pg0.admin_up()
1841         self.pg0.config_ip6()
1842         self.pg0.resolve_ndp()
1843
1844         # PG 1 is not IP enabled
1845         self.pg1.admin_up()
1846
1847     def tearDown(self):
1848         super(TestIPDisabled, self).tearDown()
1849         for i in self.pg_interfaces:
1850             i.unconfig_ip4()
1851             i.admin_down()
1852
1853     def test_ip_disabled(self):
1854         """ IP Disabled """
1855
1856         MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
1857         MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
1858         #
1859         # An (S,G).
1860         # one accepting interface, pg0, 2 forwarding interfaces
1861         #
1862         route_ff_01 = VppIpMRoute(
1863             self,
1864             "::",
1865             "ffef::1", 128,
1866             MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
1867             [VppMRoutePath(self.pg1.sw_if_index,
1868                            MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
1869              VppMRoutePath(self.pg0.sw_if_index,
1870                            MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
1871         route_ff_01.add_vpp_config()
1872
1873         pu = (Ether(src=self.pg1.remote_mac,
1874                     dst=self.pg1.local_mac) /
1875               IPv6(src="2001::1", dst=self.pg0.remote_ip6) /
1876               inet6.UDP(sport=1234, dport=1234) /
1877               Raw(b'\xa5' * 100))
1878         pm = (Ether(src=self.pg1.remote_mac,
1879                     dst=self.pg1.local_mac) /
1880               IPv6(src="2001::1", dst="ffef::1") /
1881               inet6.UDP(sport=1234, dport=1234) /
1882               Raw(b'\xa5' * 100))
1883
1884         #
1885         # PG1 does not forward IP traffic
1886         #
1887         self.send_and_assert_no_replies(self.pg1, pu, "IPv6 disabled")
1888         self.send_and_assert_no_replies(self.pg1, pm, "IPv6 disabled")
1889
1890         #
1891         # IP enable PG1
1892         #
1893         self.pg1.config_ip6()
1894
1895         #
1896         # Now we get packets through
1897         #
1898         self.pg1.add_stream(pu)
1899         self.pg_enable_capture(self.pg_interfaces)
1900         self.pg_start()
1901         rx = self.pg0.get_capture(1)
1902
1903         self.pg1.add_stream(pm)
1904         self.pg_enable_capture(self.pg_interfaces)
1905         self.pg_start()
1906         rx = self.pg0.get_capture(1)
1907
1908         #
1909         # Disable PG1
1910         #
1911         self.pg1.unconfig_ip6()
1912
1913         #
1914         # PG1 does not forward IP traffic
1915         #
1916         self.send_and_assert_no_replies(self.pg1, pu, "IPv6 disabled")
1917         self.send_and_assert_no_replies(self.pg1, pm, "IPv6 disabled")
1918
1919
1920 class TestIP6LoadBalance(VppTestCase):
1921     """ IPv6 Load-Balancing """
1922
1923     @classmethod
1924     def setUpClass(cls):
1925         super(TestIP6LoadBalance, cls).setUpClass()
1926
1927     @classmethod
1928     def tearDownClass(cls):
1929         super(TestIP6LoadBalance, cls).tearDownClass()
1930
1931     def setUp(self):
1932         super(TestIP6LoadBalance, self).setUp()
1933
1934         self.create_pg_interfaces(range(5))
1935
1936         mpls_tbl = VppMplsTable(self, 0)
1937         mpls_tbl.add_vpp_config()
1938
1939         for i in self.pg_interfaces:
1940             i.admin_up()
1941             i.config_ip6()
1942             i.resolve_ndp()
1943             i.enable_mpls()
1944
1945     def tearDown(self):
1946         for i in self.pg_interfaces:
1947             i.unconfig_ip6()
1948             i.admin_down()
1949             i.disable_mpls()
1950         super(TestIP6LoadBalance, self).tearDown()
1951
1952     def pg_send(self, input, pkts):
1953         self.vapi.cli("clear trace")
1954         input.add_stream(pkts)
1955         self.pg_enable_capture(self.pg_interfaces)
1956         self.pg_start()
1957
1958     def send_and_expect_load_balancing(self, input, pkts, outputs):
1959         self.pg_send(input, pkts)
1960         rxs = []
1961         for oo in outputs:
1962             rx = oo._get_capture(1)
1963             self.assertNotEqual(0, len(rx))
1964             rxs.append(rx)
1965         return rxs
1966
1967     def send_and_expect_one_itf(self, input, pkts, itf):
1968         self.pg_send(input, pkts)
1969         rx = itf.get_capture(len(pkts))
1970
1971     def test_ip6_load_balance(self):
1972         """ IPv6 Load-Balancing """
1973
1974         #
1975         # An array of packets that differ only in the destination port
1976         #  - IP only
1977         #  - MPLS EOS
1978         #  - MPLS non-EOS
1979         #  - MPLS non-EOS with an entropy label
1980         #
1981         port_ip_pkts = []
1982         port_mpls_pkts = []
1983         port_mpls_neos_pkts = []
1984         port_ent_pkts = []
1985
1986         #
1987         # An array of packets that differ only in the source address
1988         #
1989         src_ip_pkts = []
1990         src_mpls_pkts = []
1991
1992         for ii in range(NUM_PKTS):
1993             port_ip_hdr = (
1994                 IPv6(dst="3000::1", src="3000:1::1") /
1995                 inet6.UDP(sport=1234, dport=1234 + ii) /
1996                 Raw(b'\xa5' * 100))
1997             port_ip_pkts.append((Ether(src=self.pg0.remote_mac,
1998                                        dst=self.pg0.local_mac) /
1999                                  port_ip_hdr))
2000             port_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
2001                                          dst=self.pg0.local_mac) /
2002                                    MPLS(label=66, ttl=2) /
2003                                    port_ip_hdr))
2004             port_mpls_neos_pkts.append((Ether(src=self.pg0.remote_mac,
2005                                               dst=self.pg0.local_mac) /
2006                                         MPLS(label=67, ttl=2) /
2007                                         MPLS(label=77, ttl=2) /
2008                                         port_ip_hdr))
2009             port_ent_pkts.append((Ether(src=self.pg0.remote_mac,
2010                                         dst=self.pg0.local_mac) /
2011                                   MPLS(label=67, ttl=2) /
2012                                   MPLS(label=14, ttl=2) /
2013                                   MPLS(label=999, ttl=2) /
2014                                   port_ip_hdr))
2015             src_ip_hdr = (
2016                 IPv6(dst="3000::1", src="3000:1::%d" % ii) /
2017                 inet6.UDP(sport=1234, dport=1234) /
2018                 Raw(b'\xa5' * 100))
2019             src_ip_pkts.append((Ether(src=self.pg0.remote_mac,
2020                                       dst=self.pg0.local_mac) /
2021                                 src_ip_hdr))
2022             src_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
2023                                         dst=self.pg0.local_mac) /
2024                                   MPLS(label=66, ttl=2) /
2025                                   src_ip_hdr))
2026
2027         #
2028         # A route for the IP packets
2029         #
2030         route_3000_1 = VppIpRoute(self, "3000::1", 128,
2031                                   [VppRoutePath(self.pg1.remote_ip6,
2032                                                 self.pg1.sw_if_index),
2033                                    VppRoutePath(self.pg2.remote_ip6,
2034                                                 self.pg2.sw_if_index)])
2035         route_3000_1.add_vpp_config()
2036
2037         #
2038         # a local-label for the EOS packets
2039         #
2040         binding = VppMplsIpBind(self, 66, "3000::1", 128, is_ip6=1)
2041         binding.add_vpp_config()
2042
2043         #
2044         # An MPLS route for the non-EOS packets
2045         #
2046         route_67 = VppMplsRoute(self, 67, 0,
2047                                 [VppRoutePath(self.pg1.remote_ip6,
2048                                               self.pg1.sw_if_index,
2049                                               labels=[67]),
2050                                  VppRoutePath(self.pg2.remote_ip6,
2051                                               self.pg2.sw_if_index,
2052                                               labels=[67])])
2053         route_67.add_vpp_config()
2054
2055         #
2056         # inject the packet on pg0 - expect load-balancing across the 2 paths
2057         #  - since the default hash config is to use IP src,dst and port
2058         #    src,dst
2059         # We are not going to ensure equal amounts of packets across each link,
2060         # since the hash algorithm is statistical and therefore this can never
2061         # be guaranteed. But with 64 different packets we do expect some
2062         # balancing. So instead just ensure there is traffic on each link.
2063         #
2064         rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts,
2065                                                  [self.pg1, self.pg2])
2066         n_ip_pg0 = len(rx[0])
2067         self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
2068                                             [self.pg1, self.pg2])
2069         self.send_and_expect_load_balancing(self.pg0, port_mpls_pkts,
2070                                             [self.pg1, self.pg2])
2071         self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
2072                                             [self.pg1, self.pg2])
2073         rx = self.send_and_expect_load_balancing(self.pg0, port_mpls_neos_pkts,
2074                                                  [self.pg1, self.pg2])
2075         n_mpls_pg0 = len(rx[0])
2076
2077         #
2078         # change the router ID and expect the distribution changes
2079         #
2080         self.vapi.set_ip_flow_hash_router_id(router_id=0x11111111)
2081
2082         rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts,
2083                                                  [self.pg1, self.pg2])
2084         self.assertNotEqual(n_ip_pg0, len(rx[0]))
2085
2086         rx = self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
2087                                                  [self.pg1, self.pg2])
2088         self.assertNotEqual(n_mpls_pg0, len(rx[0]))
2089
2090         #
2091         # The packets with Entropy label in should not load-balance,
2092         # since the Entropy value is fixed.
2093         #
2094         self.send_and_expect_one_itf(self.pg0, port_ent_pkts, self.pg1)
2095
2096         #
2097         # change the flow hash config so it's only IP src,dst
2098         #  - now only the stream with differing source address will
2099         #    load-balance
2100         #
2101         self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, proto=1,
2102                                    sport=0, dport=0, is_ipv6=1)
2103
2104         self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
2105                                             [self.pg1, self.pg2])
2106         self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
2107                                             [self.pg1, self.pg2])
2108         self.send_and_expect_one_itf(self.pg0, port_ip_pkts, self.pg2)
2109
2110         #
2111         # change the flow hash config back to defaults
2112         #
2113         self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, sport=1, dport=1,
2114                                    proto=1, is_ipv6=1)
2115
2116         #
2117         # Recursive prefixes
2118         #  - testing that 2 stages of load-balancing occurs and there is no
2119         #    polarisation (i.e. only 2 of 4 paths are used)
2120         #
2121         port_pkts = []
2122         src_pkts = []
2123
2124         for ii in range(257):
2125             port_pkts.append((Ether(src=self.pg0.remote_mac,
2126                                     dst=self.pg0.local_mac) /
2127                               IPv6(dst="4000::1",
2128                                    src="4000:1::1") /
2129                               inet6.UDP(sport=1234,
2130                                         dport=1234 + ii) /
2131                               Raw(b'\xa5' * 100)))
2132             src_pkts.append((Ether(src=self.pg0.remote_mac,
2133                                    dst=self.pg0.local_mac) /
2134                              IPv6(dst="4000::1",
2135                                   src="4000:1::%d" % ii) /
2136                              inet6.UDP(sport=1234, dport=1234) /
2137                              Raw(b'\xa5' * 100)))
2138
2139         route_3000_2 = VppIpRoute(self, "3000::2", 128,
2140                                   [VppRoutePath(self.pg3.remote_ip6,
2141                                                 self.pg3.sw_if_index),
2142                                    VppRoutePath(self.pg4.remote_ip6,
2143                                                 self.pg4.sw_if_index)])
2144         route_3000_2.add_vpp_config()
2145
2146         route_4000_1 = VppIpRoute(self, "4000::1", 128,
2147                                   [VppRoutePath("3000::1",
2148                                                 0xffffffff),
2149                                    VppRoutePath("3000::2",
2150                                                 0xffffffff)])
2151         route_4000_1.add_vpp_config()
2152
2153         #
2154         # inject the packet on pg0 - expect load-balancing across all 4 paths
2155         #
2156         self.vapi.cli("clear trace")
2157         self.send_and_expect_load_balancing(self.pg0, port_pkts,
2158                                             [self.pg1, self.pg2,
2159                                              self.pg3, self.pg4])
2160         self.send_and_expect_load_balancing(self.pg0, src_pkts,
2161                                             [self.pg1, self.pg2,
2162                                              self.pg3, self.pg4])
2163
2164         #
2165         # Recursive prefixes
2166         #  - testing that 2 stages of load-balancing no choices
2167         #
2168         port_pkts = []
2169
2170         for ii in range(257):
2171             port_pkts.append((Ether(src=self.pg0.remote_mac,
2172                                     dst=self.pg0.local_mac) /
2173                               IPv6(dst="6000::1",
2174                                    src="6000:1::1") /
2175                               inet6.UDP(sport=1234,
2176                                         dport=1234 + ii) /
2177                               Raw(b'\xa5' * 100)))
2178
2179         route_5000_2 = VppIpRoute(self, "5000::2", 128,
2180                                   [VppRoutePath(self.pg3.remote_ip6,
2181                                                 self.pg3.sw_if_index)])
2182         route_5000_2.add_vpp_config()
2183
2184         route_6000_1 = VppIpRoute(self, "6000::1", 128,
2185                                   [VppRoutePath("5000::2",
2186                                                 0xffffffff)])
2187         route_6000_1.add_vpp_config()
2188
2189         #
2190         # inject the packet on pg0 - expect load-balancing across all 4 paths
2191         #
2192         self.vapi.cli("clear trace")
2193         self.send_and_expect_one_itf(self.pg0, port_pkts, self.pg3)
2194
2195
2196 class IP6PuntSetup(object):
2197     """ Setup for IPv6 Punt Police/Redirect """
2198
2199     def punt_setup(self):
2200         self.create_pg_interfaces(range(4))
2201
2202         for i in self.pg_interfaces:
2203             i.admin_up()
2204             i.config_ip6()
2205             i.resolve_ndp()
2206
2207         self.pkt = (Ether(src=self.pg0.remote_mac,
2208                           dst=self.pg0.local_mac) /
2209                     IPv6(src=self.pg0.remote_ip6,
2210                          dst=self.pg0.local_ip6) /
2211                     inet6.TCP(sport=1234, dport=1234) /
2212                     Raw(b'\xa5' * 100))
2213
2214     def punt_teardown(self):
2215         for i in self.pg_interfaces:
2216             i.unconfig_ip6()
2217             i.admin_down()
2218
2219
2220 class TestIP6Punt(IP6PuntSetup, VppTestCase):
2221     """ IPv6 Punt Police/Redirect """
2222
2223     def setUp(self):
2224         super(TestIP6Punt, self).setUp()
2225         super(TestIP6Punt, self).punt_setup()
2226
2227     def tearDown(self):
2228         super(TestIP6Punt, self).punt_teardown()
2229         super(TestIP6Punt, self).tearDown()
2230
2231     def test_ip_punt(self):
2232         """ IP6 punt police and redirect """
2233
2234         pkts = self.pkt * 1025
2235
2236         #
2237         # Configure a punt redirect via pg1.
2238         #
2239         nh_addr = self.pg1.remote_ip6
2240         ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index,
2241                                              self.pg1.sw_if_index, nh_addr)
2242         ip_punt_redirect.add_vpp_config()
2243
2244         self.send_and_expect(self.pg0, pkts, self.pg1)
2245
2246         #
2247         # add a policer
2248         #
2249         policer = VppPolicer(self, "ip6-punt", 400, 0, 10, 0, rate_type=1)
2250         policer.add_vpp_config()
2251         ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index,
2252                                            is_ip6=True)
2253         ip_punt_policer.add_vpp_config()
2254
2255         self.vapi.cli("clear trace")
2256         self.pg0.add_stream(pkts)
2257         self.pg_enable_capture(self.pg_interfaces)
2258         self.pg_start()
2259
2260         #
2261         # the number of packet received should be greater than 0,
2262         # but not equal to the number sent, since some were policed
2263         #
2264         rx = self.pg1._get_capture(1)
2265         stats = policer.get_stats()
2266
2267         # Single rate policer - expect conform, violate but no exceed
2268         self.assertGreater(stats['conform_packets'], 0)
2269         self.assertEqual(stats['exceed_packets'], 0)
2270         self.assertGreater(stats['violate_packets'], 0)
2271
2272         self.assertGreater(len(rx), 0)
2273         self.assertLess(len(rx), len(pkts))
2274
2275         #
2276         # remove the policer. back to full rx
2277         #
2278         ip_punt_policer.remove_vpp_config()
2279         policer.remove_vpp_config()
2280         self.send_and_expect(self.pg0, pkts, self.pg1)
2281
2282         #
2283         # remove the redirect. expect full drop.
2284         #
2285         ip_punt_redirect.remove_vpp_config()
2286         self.send_and_assert_no_replies(self.pg0, pkts,
2287                                         "IP no punt config")
2288
2289         #
2290         # Add a redirect that is not input port selective
2291         #
2292         ip_punt_redirect = VppIpPuntRedirect(self, 0xffffffff,
2293                                              self.pg1.sw_if_index, nh_addr)
2294         ip_punt_redirect.add_vpp_config()
2295         self.send_and_expect(self.pg0, pkts, self.pg1)
2296         ip_punt_redirect.remove_vpp_config()
2297
2298     def test_ip_punt_dump(self):
2299         """ IP6 punt redirect dump"""
2300
2301         #
2302         # Configure a punt redirects
2303         #
2304         nh_address = self.pg3.remote_ip6
2305         ipr_03 = VppIpPuntRedirect(self, self.pg0.sw_if_index,
2306                                    self.pg3.sw_if_index, nh_address)
2307         ipr_13 = VppIpPuntRedirect(self, self.pg1.sw_if_index,
2308                                    self.pg3.sw_if_index, nh_address)
2309         ipr_23 = VppIpPuntRedirect(self, self.pg2.sw_if_index,
2310                                    self.pg3.sw_if_index, '0::0')
2311         ipr_03.add_vpp_config()
2312         ipr_13.add_vpp_config()
2313         ipr_23.add_vpp_config()
2314
2315         #
2316         # Dump pg0 punt redirects
2317         #
2318         self.assertTrue(ipr_03.query_vpp_config())
2319         self.assertTrue(ipr_13.query_vpp_config())
2320         self.assertTrue(ipr_23.query_vpp_config())
2321
2322         #
2323         # Dump punt redirects for all interfaces
2324         #
2325         punts = self.vapi.ip_punt_redirect_dump(0xffffffff, is_ipv6=1)
2326         self.assertEqual(len(punts), 3)
2327         for p in punts:
2328             self.assertEqual(p.punt.tx_sw_if_index, self.pg3.sw_if_index)
2329         self.assertNotEqual(punts[1].punt.nh, self.pg3.remote_ip6)
2330         self.assertEqual(str(punts[2].punt.nh), '::')
2331
2332
2333 class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase):
2334     """ IPv6 Punt Police/Redirect """
2335     vpp_worker_count = 2
2336
2337     def setUp(self):
2338         super(TestIP6PuntHandoff, self).setUp()
2339         super(TestIP6PuntHandoff, self).punt_setup()
2340
2341     def tearDown(self):
2342         super(TestIP6PuntHandoff, self).punt_teardown()
2343         super(TestIP6PuntHandoff, self).tearDown()
2344
2345     def test_ip_punt(self):
2346         """ IP6 punt policer thread handoff """
2347         pkts = self.pkt * NUM_PKTS
2348
2349         #
2350         # Configure a punt redirect via pg1.
2351         #
2352         nh_addr = self.pg1.remote_ip6
2353         ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index,
2354                                              self.pg1.sw_if_index, nh_addr)
2355         ip_punt_redirect.add_vpp_config()
2356
2357         action_tx = PolicerAction(
2358             VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT,
2359             0)
2360         #
2361         # This policer drops no packets, we are just
2362         # testing that they get to the right thread.
2363         #
2364         policer = VppPolicer(self, "ip6-punt", 400, 0, 10, 0, 1,
2365                              0, 0, False, action_tx, action_tx, action_tx)
2366         policer.add_vpp_config()
2367         ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index,
2368                                            is_ip6=True)
2369         ip_punt_policer.add_vpp_config()
2370
2371         for worker in [0, 1]:
2372             self.send_and_expect(self.pg0, pkts, self.pg1, worker=worker)
2373             if worker == 0:
2374                 self.logger.debug(self.vapi.cli("show trace max 100"))
2375
2376         # Combined stats, all threads
2377         stats = policer.get_stats()
2378
2379         # Single rate policer - expect conform, violate but no exceed
2380         self.assertGreater(stats['conform_packets'], 0)
2381         self.assertEqual(stats['exceed_packets'], 0)
2382         self.assertGreater(stats['violate_packets'], 0)
2383
2384         # Worker 0, should have done all the policing
2385         stats0 = policer.get_stats(worker=0)
2386         self.assertEqual(stats, stats0)
2387
2388         # Worker 1, should have handed everything off
2389         stats1 = policer.get_stats(worker=1)
2390         self.assertEqual(stats1['conform_packets'], 0)
2391         self.assertEqual(stats1['exceed_packets'], 0)
2392         self.assertEqual(stats1['violate_packets'], 0)
2393
2394         # Bind the policer to worker 1 and repeat
2395         policer.bind_vpp_config(1, True)
2396         for worker in [0, 1]:
2397             self.send_and_expect(self.pg0, pkts, self.pg1, worker=worker)
2398             self.logger.debug(self.vapi.cli("show trace max 100"))
2399
2400         # The 2 workers should now have policed the same amount
2401         stats = policer.get_stats()
2402         stats0 = policer.get_stats(worker=0)
2403         stats1 = policer.get_stats(worker=1)
2404
2405         self.assertGreater(stats0['conform_packets'], 0)
2406         self.assertEqual(stats0['exceed_packets'], 0)
2407         self.assertGreater(stats0['violate_packets'], 0)
2408
2409         self.assertGreater(stats1['conform_packets'], 0)
2410         self.assertEqual(stats1['exceed_packets'], 0)
2411         self.assertGreater(stats1['violate_packets'], 0)
2412
2413         self.assertEqual(stats0['conform_packets'] + stats1['conform_packets'],
2414                          stats['conform_packets'])
2415
2416         self.assertEqual(stats0['violate_packets'] + stats1['violate_packets'],
2417                          stats['violate_packets'])
2418
2419         # Unbind the policer and repeat
2420         policer.bind_vpp_config(1, False)
2421         for worker in [0, 1]:
2422             self.send_and_expect(self.pg0, pkts, self.pg1, worker=worker)
2423             self.logger.debug(self.vapi.cli("show trace max 100"))
2424
2425         # The policer should auto-bind to worker 0 when packets arrive
2426         stats = policer.get_stats()
2427         stats0new = policer.get_stats(worker=0)
2428         stats1new = policer.get_stats(worker=1)
2429
2430         self.assertGreater(stats0new['conform_packets'],
2431                            stats0['conform_packets'])
2432         self.assertEqual(stats0new['exceed_packets'], 0)
2433         self.assertGreater(stats0new['violate_packets'],
2434                            stats0['violate_packets'])
2435
2436         self.assertEqual(stats1, stats1new)
2437
2438         #
2439         # Clean up
2440         #
2441         ip_punt_policer.remove_vpp_config()
2442         policer.remove_vpp_config()
2443         ip_punt_redirect.remove_vpp_config()
2444
2445
2446 class TestIPDeag(VppTestCase):
2447     """ IPv6 Deaggregate Routes """
2448
2449     @classmethod
2450     def setUpClass(cls):
2451         super(TestIPDeag, cls).setUpClass()
2452
2453     @classmethod
2454     def tearDownClass(cls):
2455         super(TestIPDeag, cls).tearDownClass()
2456
2457     def setUp(self):
2458         super(TestIPDeag, self).setUp()
2459
2460         self.create_pg_interfaces(range(3))
2461
2462         for i in self.pg_interfaces:
2463             i.admin_up()
2464             i.config_ip6()
2465             i.resolve_ndp()
2466
2467     def tearDown(self):
2468         super(TestIPDeag, self).tearDown()
2469         for i in self.pg_interfaces:
2470             i.unconfig_ip6()
2471             i.admin_down()
2472
2473     def test_ip_deag(self):
2474         """ IP Deag Routes """
2475
2476         #
2477         # Create a table to be used for:
2478         #  1 - another destination address lookup
2479         #  2 - a source address lookup
2480         #
2481         table_dst = VppIpTable(self, 1, is_ip6=1)
2482         table_src = VppIpTable(self, 2, is_ip6=1)
2483         table_dst.add_vpp_config()
2484         table_src.add_vpp_config()
2485
2486         #
2487         # Add a route in the default table to point to a deag/
2488         # second lookup in each of these tables
2489         #
2490         route_to_dst = VppIpRoute(self, "1::1", 128,
2491                                   [VppRoutePath("::",
2492                                                 0xffffffff,
2493                                                 nh_table_id=1)])
2494         route_to_src = VppIpRoute(
2495             self, "1::2", 128,
2496             [VppRoutePath("::",
2497                           0xffffffff,
2498                           nh_table_id=2,
2499                           type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP)])
2500
2501         route_to_dst.add_vpp_config()
2502         route_to_src.add_vpp_config()
2503
2504         #
2505         # packets to these destination are dropped, since they'll
2506         # hit the respective default routes in the second table
2507         #
2508         p_dst = (Ether(src=self.pg0.remote_mac,
2509                        dst=self.pg0.local_mac) /
2510                  IPv6(src="5::5", dst="1::1") /
2511                  inet6.TCP(sport=1234, dport=1234) /
2512                  Raw(b'\xa5' * 100))
2513         p_src = (Ether(src=self.pg0.remote_mac,
2514                        dst=self.pg0.local_mac) /
2515                  IPv6(src="2::2", dst="1::2") /
2516                  inet6.TCP(sport=1234, dport=1234) /
2517                  Raw(b'\xa5' * 100))
2518         pkts_dst = p_dst * 257
2519         pkts_src = p_src * 257
2520
2521         self.send_and_assert_no_replies(self.pg0, pkts_dst,
2522                                         "IP in dst table")
2523         self.send_and_assert_no_replies(self.pg0, pkts_src,
2524                                         "IP in src table")
2525
2526         #
2527         # add a route in the dst table to forward via pg1
2528         #
2529         route_in_dst = VppIpRoute(self, "1::1", 128,
2530                                   [VppRoutePath(self.pg1.remote_ip6,
2531                                                 self.pg1.sw_if_index)],
2532                                   table_id=1)
2533         route_in_dst.add_vpp_config()
2534
2535         self.send_and_expect(self.pg0, pkts_dst, self.pg1)
2536
2537         #
2538         # add a route in the src table to forward via pg2
2539         #
2540         route_in_src = VppIpRoute(self, "2::2", 128,
2541                                   [VppRoutePath(self.pg2.remote_ip6,
2542                                                 self.pg2.sw_if_index)],
2543                                   table_id=2)
2544         route_in_src.add_vpp_config()
2545         self.send_and_expect(self.pg0, pkts_src, self.pg2)
2546
2547         #
2548         # loop in the lookup DP
2549         #
2550         route_loop = VppIpRoute(self, "3::3", 128,
2551                                 [VppRoutePath("::",
2552                                               0xffffffff)])
2553         route_loop.add_vpp_config()
2554
2555         p_l = (Ether(src=self.pg0.remote_mac,
2556                      dst=self.pg0.local_mac) /
2557                IPv6(src="3::4", dst="3::3") /
2558                inet6.TCP(sport=1234, dport=1234) /
2559                Raw(b'\xa5' * 100))
2560
2561         self.send_and_assert_no_replies(self.pg0, p_l * 257,
2562                                         "IP lookup loop")
2563
2564
2565 class TestIP6Input(VppTestCase):
2566     """ IPv6 Input Exception Test Cases """
2567
2568     @classmethod
2569     def setUpClass(cls):
2570         super(TestIP6Input, cls).setUpClass()
2571
2572     @classmethod
2573     def tearDownClass(cls):
2574         super(TestIP6Input, cls).tearDownClass()
2575
2576     def setUp(self):
2577         super(TestIP6Input, self).setUp()
2578
2579         self.create_pg_interfaces(range(2))
2580
2581         for i in self.pg_interfaces:
2582             i.admin_up()
2583             i.config_ip6()
2584             i.resolve_ndp()
2585
2586     def tearDown(self):
2587         super(TestIP6Input, self).tearDown()
2588         for i in self.pg_interfaces:
2589             i.unconfig_ip6()
2590             i.admin_down()
2591
2592     def test_ip_input_icmp_reply(self):
2593         """ IP6 Input Exception - Return ICMP (3,0) """
2594         #
2595         # hop limit - ICMP replies
2596         #
2597         p_version = (Ether(src=self.pg0.remote_mac,
2598                            dst=self.pg0.local_mac) /
2599                      IPv6(src=self.pg0.remote_ip6,
2600                           dst=self.pg1.remote_ip6,
2601                           hlim=1) /
2602                      inet6.UDP(sport=1234, dport=1234) /
2603                      Raw(b'\xa5' * 100))
2604
2605         rx = self.send_and_expect(self.pg0, p_version * NUM_PKTS, self.pg0)
2606         rx = rx[0]
2607         icmp = rx[ICMPv6TimeExceeded]
2608
2609         # 0: "hop limit exceeded in transit",
2610         self.assertEqual((icmp.type, icmp.code), (3, 0))
2611
2612     icmpv6_data = '\x0a' * 18
2613     all_0s = "::"
2614     all_1s = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"
2615
2616     @parameterized.expand([
2617         # Name, src, dst, l4proto, msg, timeout
2618         ("src='iface',   dst='iface'", None, None,
2619          inet6.UDP(sport=1234, dport=1234), "funky version", None),
2620         ("src='All 0's', dst='iface'", all_0s, None,
2621          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2622         ("src='iface',   dst='All 0's'", None, all_0s,
2623          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2624         ("src='All 1's', dst='iface'", all_1s, None,
2625          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2626         ("src='iface',   dst='All 1's'", None, all_1s,
2627          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2628         ("src='All 1's', dst='All 1's'", all_1s, all_1s,
2629          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2630
2631     ])
2632     def test_ip_input_no_replies(self, name, src, dst, l4, msg, timeout):
2633
2634         self._testMethodDoc = 'IPv6 Input Exception - %s' % name
2635
2636         p_version = (Ether(src=self.pg0.remote_mac,
2637                            dst=self.pg0.local_mac) /
2638                      IPv6(src=src or self.pg0.remote_ip6,
2639                           dst=dst or self.pg1.remote_ip6,
2640                           version=3) /
2641                      l4 /
2642                      Raw(b'\xa5' * 100))
2643
2644         self.send_and_assert_no_replies(self.pg0, p_version * NUM_PKTS,
2645                                         remark=msg or "",
2646                                         timeout=timeout)
2647
2648     def test_hop_by_hop(self):
2649         """ Hop-by-hop header test """
2650
2651         p = (Ether(src=self.pg0.remote_mac,
2652                    dst=self.pg0.local_mac) /
2653              IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
2654              IPv6ExtHdrHopByHop() /
2655              inet6.UDP(sport=1234, dport=1234) /
2656              Raw(b'\xa5' * 100))
2657
2658         self.pg0.add_stream(p)
2659         self.pg_enable_capture(self.pg_interfaces)
2660         self.pg_start()
2661
2662
2663 class TestIPReplace(VppTestCase):
2664     """ IPv6 Table Replace """
2665
2666     @classmethod
2667     def setUpClass(cls):
2668         super(TestIPReplace, cls).setUpClass()
2669
2670     @classmethod
2671     def tearDownClass(cls):
2672         super(TestIPReplace, cls).tearDownClass()
2673
2674     def setUp(self):
2675         super(TestIPReplace, self).setUp()
2676
2677         self.create_pg_interfaces(range(4))
2678
2679         table_id = 1
2680         self.tables = []
2681
2682         for i in self.pg_interfaces:
2683             i.admin_up()
2684             i.config_ip6()
2685             i.generate_remote_hosts(2)
2686             self.tables.append(VppIpTable(self, table_id,
2687                                           True).add_vpp_config())
2688             table_id += 1
2689
2690     def tearDown(self):
2691         super(TestIPReplace, self).tearDown()
2692         for i in self.pg_interfaces:
2693             i.admin_down()
2694             i.unconfig_ip6()
2695
2696     def test_replace(self):
2697         """ IP Table Replace """
2698
2699         MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
2700         MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
2701         N_ROUTES = 20
2702         links = [self.pg0, self.pg1, self.pg2, self.pg3]
2703         routes = [[], [], [], []]
2704
2705         # the sizes of 'empty' tables
2706         for t in self.tables:
2707             self.assertEqual(len(t.dump()), 2)
2708             self.assertEqual(len(t.mdump()), 5)
2709
2710         # load up the tables with some routes
2711         for ii, t in enumerate(self.tables):
2712             for jj in range(1, N_ROUTES):
2713                 uni = VppIpRoute(
2714                     self, "2001::%d" % jj if jj != 0 else "2001::", 128,
2715                     [VppRoutePath(links[ii].remote_hosts[0].ip6,
2716                                   links[ii].sw_if_index),
2717                      VppRoutePath(links[ii].remote_hosts[1].ip6,
2718                                   links[ii].sw_if_index)],
2719                     table_id=t.table_id).add_vpp_config()
2720                 multi = VppIpMRoute(
2721                     self, "::",
2722                     "ff:2001::%d" % jj, 128,
2723                     MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
2724                     [VppMRoutePath(self.pg0.sw_if_index,
2725                                    MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
2726                                    proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
2727                      VppMRoutePath(self.pg1.sw_if_index,
2728                                    MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
2729                                    proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
2730                      VppMRoutePath(self.pg2.sw_if_index,
2731                                    MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
2732                                    proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
2733                      VppMRoutePath(self.pg3.sw_if_index,
2734                                    MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
2735                                    proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)],
2736                     table_id=t.table_id).add_vpp_config()
2737                 routes[ii].append({'uni': uni,
2738                                    'multi': multi})
2739
2740         #
2741         # replace the tables a few times
2742         #
2743         for kk in range(3):
2744             # replace each table
2745             for t in self.tables:
2746                 t.replace_begin()
2747
2748             # all the routes are still there
2749             for ii, t in enumerate(self.tables):
2750                 dump = t.dump()
2751                 mdump = t.mdump()
2752                 for r in routes[ii]:
2753                     self.assertTrue(find_route_in_dump(dump, r['uni'], t))
2754                     self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t))
2755
2756             # redownload the even numbered routes
2757             for ii, t in enumerate(self.tables):
2758                 for jj in range(0, N_ROUTES, 2):
2759                     routes[ii][jj]['uni'].add_vpp_config()
2760                     routes[ii][jj]['multi'].add_vpp_config()
2761
2762             # signal each table converged
2763             for t in self.tables:
2764                 t.replace_end()
2765
2766             # we should find the even routes, but not the odd
2767             for ii, t in enumerate(self.tables):
2768                 dump = t.dump()
2769                 mdump = t.mdump()
2770                 for jj in range(0, N_ROUTES, 2):
2771                     self.assertTrue(find_route_in_dump(
2772                         dump, routes[ii][jj]['uni'], t))
2773                     self.assertTrue(find_mroute_in_dump(
2774                         mdump, routes[ii][jj]['multi'], t))
2775                 for jj in range(1, N_ROUTES - 1, 2):
2776                     self.assertFalse(find_route_in_dump(
2777                         dump, routes[ii][jj]['uni'], t))
2778                     self.assertFalse(find_mroute_in_dump(
2779                         mdump, routes[ii][jj]['multi'], t))
2780
2781             # reload all the routes
2782             for ii, t in enumerate(self.tables):
2783                 for r in routes[ii]:
2784                     r['uni'].add_vpp_config()
2785                     r['multi'].add_vpp_config()
2786
2787             # all the routes are still there
2788             for ii, t in enumerate(self.tables):
2789                 dump = t.dump()
2790                 mdump = t.mdump()
2791                 for r in routes[ii]:
2792                     self.assertTrue(find_route_in_dump(dump, r['uni'], t))
2793                     self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t))
2794
2795         #
2796         # finally flush the tables for good measure
2797         #
2798         for t in self.tables:
2799             t.flush()
2800             self.assertEqual(len(t.dump()), 2)
2801             self.assertEqual(len(t.mdump()), 5)
2802
2803
2804 class TestIP6Replace(VppTestCase):
2805     """ IPv4 Interface Address Replace """
2806
2807     @classmethod
2808     def setUpClass(cls):
2809         super(TestIP6Replace, cls).setUpClass()
2810
2811     @classmethod
2812     def tearDownClass(cls):
2813         super(TestIP6Replace, cls).tearDownClass()
2814
2815     def setUp(self):
2816         super(TestIP6Replace, self).setUp()
2817
2818         self.create_pg_interfaces(range(4))
2819
2820         for i in self.pg_interfaces:
2821             i.admin_up()
2822
2823     def tearDown(self):
2824         super(TestIP6Replace, self).tearDown()
2825         for i in self.pg_interfaces:
2826             i.admin_down()
2827
2828     def get_n_pfxs(self, intf):
2829         return len(self.vapi.ip_address_dump(intf.sw_if_index, True))
2830
2831     def test_replace(self):
2832         """ IP interface address replace """
2833
2834         intf_pfxs = [[], [], [], []]
2835
2836         # add prefixes to each of the interfaces
2837         for i in range(len(self.pg_interfaces)):
2838             intf = self.pg_interfaces[i]
2839
2840             # 2001:16:x::1/64
2841             addr = "2001:16:%d::1" % intf.sw_if_index
2842             a = VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()
2843             intf_pfxs[i].append(a)
2844
2845             # 2001:16:x::2/64 - a different address in the same subnet as above
2846             addr = "2001:16:%d::2" % intf.sw_if_index
2847             a = VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()
2848             intf_pfxs[i].append(a)
2849
2850             # 2001:15:x::2/64 - a different address and subnet
2851             addr = "2001:15:%d::2" % intf.sw_if_index
2852             a = VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()
2853             intf_pfxs[i].append(a)
2854
2855         # a dump should n_address in it
2856         for intf in self.pg_interfaces:
2857             self.assertEqual(self.get_n_pfxs(intf), 3)
2858
2859         #
2860         # remove all the address thru a replace
2861         #
2862         self.vapi.sw_interface_address_replace_begin()
2863         self.vapi.sw_interface_address_replace_end()
2864         for intf in self.pg_interfaces:
2865             self.assertEqual(self.get_n_pfxs(intf), 0)
2866
2867         #
2868         # add all the interface addresses back
2869         #
2870         for p in intf_pfxs:
2871             for v in p:
2872                 v.add_vpp_config()
2873         for intf in self.pg_interfaces:
2874             self.assertEqual(self.get_n_pfxs(intf), 3)
2875
2876         #
2877         # replace again, but this time update/re-add the address on the first
2878         # two interfaces
2879         #
2880         self.vapi.sw_interface_address_replace_begin()
2881
2882         for p in intf_pfxs[:2]:
2883             for v in p:
2884                 v.add_vpp_config()
2885
2886         self.vapi.sw_interface_address_replace_end()
2887
2888         # on the first two the address still exist,
2889         # on the other two they do not
2890         for intf in self.pg_interfaces[:2]:
2891             self.assertEqual(self.get_n_pfxs(intf), 3)
2892         for p in intf_pfxs[:2]:
2893             for v in p:
2894                 self.assertTrue(v.query_vpp_config())
2895         for intf in self.pg_interfaces[2:]:
2896             self.assertEqual(self.get_n_pfxs(intf), 0)
2897
2898         #
2899         # add all the interface addresses back on the last two
2900         #
2901         for p in intf_pfxs[2:]:
2902             for v in p:
2903                 v.add_vpp_config()
2904         for intf in self.pg_interfaces:
2905             self.assertEqual(self.get_n_pfxs(intf), 3)
2906
2907         #
2908         # replace again, this time add different prefixes on all the interfaces
2909         #
2910         self.vapi.sw_interface_address_replace_begin()
2911
2912         pfxs = []
2913         for intf in self.pg_interfaces:
2914             # 2001:18:x::1/64
2915             addr = "2001:18:%d::1" % intf.sw_if_index
2916             pfxs.append(VppIpInterfaceAddress(self, intf, addr,
2917                                               64).add_vpp_config())
2918
2919         self.vapi.sw_interface_address_replace_end()
2920
2921         # only .18 should exist on each interface
2922         for intf in self.pg_interfaces:
2923             self.assertEqual(self.get_n_pfxs(intf), 1)
2924         for pfx in pfxs:
2925             self.assertTrue(pfx.query_vpp_config())
2926
2927         #
2928         # remove everything
2929         #
2930         self.vapi.sw_interface_address_replace_begin()
2931         self.vapi.sw_interface_address_replace_end()
2932         for intf in self.pg_interfaces:
2933             self.assertEqual(self.get_n_pfxs(intf), 0)
2934
2935         #
2936         # add prefixes to each interface. post-begin add the prefix from
2937         # interface X onto interface Y. this would normally be an error
2938         # since it would generate a 'duplicate address' warning. but in
2939         # this case, since what is newly downloaded is sane, it's ok
2940         #
2941         for intf in self.pg_interfaces:
2942             # 2001:18:x::1/64
2943             addr = "2001:18:%d::1" % intf.sw_if_index
2944             VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()
2945
2946         self.vapi.sw_interface_address_replace_begin()
2947
2948         pfxs = []
2949         for intf in self.pg_interfaces:
2950             # 2001:18:x::1/64
2951             addr = "2001:18:%d::1" % (intf.sw_if_index + 1)
2952             pfxs.append(VppIpInterfaceAddress(self, intf,
2953                                               addr, 64).add_vpp_config())
2954
2955         self.vapi.sw_interface_address_replace_end()
2956
2957         self.logger.info(self.vapi.cli("sh int addr"))
2958
2959         for intf in self.pg_interfaces:
2960             self.assertEqual(self.get_n_pfxs(intf), 1)
2961         for pfx in pfxs:
2962             self.assertTrue(pfx.query_vpp_config())
2963
2964
2965 class TestIP6LinkLocal(VppTestCase):
2966     """ IPv6 Link Local """
2967
2968     @classmethod
2969     def setUpClass(cls):
2970         super(TestIP6LinkLocal, cls).setUpClass()
2971
2972     @classmethod
2973     def tearDownClass(cls):
2974         super(TestIP6LinkLocal, cls).tearDownClass()
2975
2976     def setUp(self):
2977         super(TestIP6LinkLocal, self).setUp()
2978
2979         self.create_pg_interfaces(range(2))
2980
2981         for i in self.pg_interfaces:
2982             i.admin_up()
2983
2984     def tearDown(self):
2985         super(TestIP6LinkLocal, self).tearDown()
2986         for i in self.pg_interfaces:
2987             i.admin_down()
2988
2989     def test_ip6_ll(self):
2990         """ IPv6 Link Local """
2991
2992         #
2993         # two APIs to add a link local address.
2994         #   1 - just like any other prefix
2995         #   2 - with the special set LL API
2996         #
2997
2998         #
2999         # First with the API to set a 'normal' prefix
3000         #
3001         ll1 = "fe80:1::1"
3002         ll2 = "fe80:2::2"
3003         ll3 = "fe80:3::3"
3004
3005         VppIpInterfaceAddress(self, self.pg0, ll1, 128).add_vpp_config()
3006
3007         #
3008         # should be able to ping the ll
3009         #
3010         p_echo_request_1 = (Ether(src=self.pg0.remote_mac,
3011                                   dst=self.pg0.local_mac) /
3012                             IPv6(src=ll2,
3013                                  dst=ll1) /
3014                             ICMPv6EchoRequest())
3015
3016         self.send_and_expect(self.pg0, [p_echo_request_1], self.pg0)
3017
3018         #
3019         # change the link-local on pg0
3020         #
3021         v_ll3 = VppIpInterfaceAddress(self, self.pg0,
3022                                       ll3, 128).add_vpp_config()
3023
3024         p_echo_request_3 = (Ether(src=self.pg0.remote_mac,
3025                                   dst=self.pg0.local_mac) /
3026                             IPv6(src=ll2,
3027                                  dst=ll3) /
3028                             ICMPv6EchoRequest())
3029
3030         self.send_and_expect(self.pg0, [p_echo_request_3], self.pg0)
3031
3032         #
3033         # set a normal v6 prefix on the link
3034         #
3035         self.pg0.config_ip6()
3036
3037         self.send_and_expect(self.pg0, [p_echo_request_3], self.pg0)
3038
3039         # the link-local cannot be removed
3040         with self.vapi.assert_negative_api_retval():
3041             v_ll3.remove_vpp_config()
3042
3043         #
3044         # Use the specific link-local API on pg1
3045         #
3046         VppIp6LinkLocalAddress(self, self.pg1, ll1).add_vpp_config()
3047         self.send_and_expect(self.pg1, [p_echo_request_1], self.pg1)
3048
3049         VppIp6LinkLocalAddress(self, self.pg1, ll3).add_vpp_config()
3050         self.send_and_expect(self.pg1, [p_echo_request_3], self.pg1)
3051
3052
3053 class TestIPv6PathMTU(VppTestCase):
3054     """ IPv6 Path MTU """
3055
3056     def setUp(self):
3057         super(TestIPv6PathMTU, self).setUp()
3058
3059         self.create_pg_interfaces(range(2))
3060
3061         # setup all interfaces
3062         for i in self.pg_interfaces:
3063             i.admin_up()
3064             i.config_ip6()
3065             i.resolve_ndp()
3066
3067     def tearDown(self):
3068         super(TestIPv6PathMTU, self).tearDown()
3069         for i in self.pg_interfaces:
3070             i.unconfig_ip6()
3071             i.admin_down()
3072
3073     def test_path_mtu_local(self):
3074         """ Path MTU for attached neighbour """
3075
3076         self.vapi.cli("set log class ip level debug")
3077         #
3078         # The goal here is not test that fragmentation works correctly,
3079         # that's done elsewhere, the intent is to ensure that the Path MTU
3080         # settings are honoured.
3081         #
3082
3083         #
3084         # IPv6 will only frag locally generated packets, so use tunnelled
3085         # packets post encap
3086         #
3087         tun = VppIpIpTunInterface(
3088             self,
3089             self.pg1,
3090             self.pg1.local_ip6,
3091             self.pg1.remote_ip6)
3092         tun.add_vpp_config()
3093         tun.admin_up()
3094         tun.config_ip6()
3095
3096         # set the interface MTU to a reasonable value
3097         self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
3098                                        [2800, 0, 0, 0])
3099
3100         p_2k = (Ether(dst=self.pg0.local_mac,
3101                       src=self.pg0.remote_mac) /
3102                 IPv6(src=self.pg0.remote_ip6,
3103                      dst=tun.remote_ip6) /
3104                 UDP(sport=1234, dport=5678) /
3105                 Raw(b'0xa' * 1000))
3106         p_1k = (Ether(dst=self.pg0.local_mac,
3107                       src=self.pg0.remote_mac) /
3108                 IPv6(src=self.pg0.remote_ip6,
3109                      dst=tun.remote_ip6) /
3110                 UDP(sport=1234, dport=5678) /
3111                 Raw(b'0xa' * 600))
3112
3113         nbr = VppNeighbor(self,
3114                           self.pg1.sw_if_index,
3115                           self.pg1.remote_mac,
3116                           self.pg1.remote_ip6).add_vpp_config()
3117
3118         # this is now the interface MTU frags
3119         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
3120         self.send_and_expect(self.pg0, [p_1k], self.pg1)
3121
3122         # drop the path MTU for this neighbour to below the interface MTU
3123         # expect more frags
3124         pmtu = VppIpPathMtu(self, self.pg1.remote_ip6, 1300).add_vpp_config()
3125
3126         # print/format the adj delegate and trackers
3127         self.logger.info(self.vapi.cli("sh ip pmtu"))
3128         self.logger.info(self.vapi.cli("sh adj 7"))
3129
3130         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
3131         self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
3132
3133         # increase the path MTU to more than the interface
3134         # expect to use the interface MTU
3135         pmtu.modify(8192)
3136
3137         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
3138         self.send_and_expect(self.pg0, [p_1k], self.pg1)
3139
3140         # go back to an MTU from the path
3141         pmtu.modify(1300)
3142
3143         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
3144         self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
3145
3146         # raise the interface's MTU
3147         # should still use that of the path
3148         self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
3149                                        [2000, 0, 0, 0])
3150         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
3151         self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
3152
3153         # set path high and interface low
3154         pmtu.modify(2000)
3155         self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
3156                                        [1300, 0, 0, 0])
3157         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
3158         self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
3159
3160         # remove the path MTU
3161         self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
3162                                        [2800, 0, 0, 0])
3163         pmtu.modify(0)
3164
3165         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
3166         self.send_and_expect(self.pg0, [p_1k], self.pg1)
3167
3168     def test_path_mtu_remote(self):
3169         """ Path MTU for remote neighbour """
3170
3171         self.vapi.cli("set log class ip level debug")
3172         #
3173         # The goal here is not test that fragmentation works correctly,
3174         # that's done elsewhere, the intent is to ensure that the Path MTU
3175         # settings are honoured.
3176         #
3177         tun_dst = "2001::1"
3178
3179         route = VppIpRoute(
3180             self, tun_dst, 64,
3181             [VppRoutePath(self.pg1.remote_ip6,
3182                           self.pg1.sw_if_index)]).add_vpp_config()
3183
3184         #
3185         # IPv6 will only frag locally generated packets, so use tunnelled
3186         # packets post encap
3187         #
3188         tun = VppIpIpTunInterface(
3189             self,
3190             self.pg1,
3191             self.pg1.local_ip6,
3192             tun_dst)
3193         tun.add_vpp_config()
3194         tun.admin_up()
3195         tun.config_ip6()
3196
3197         # set the interface MTU to a reasonable value
3198         self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
3199                                        [2800, 0, 0, 0])
3200
3201         p_2k = (Ether(dst=self.pg0.local_mac,
3202                       src=self.pg0.remote_mac) /
3203                 IPv6(src=self.pg0.remote_ip6,
3204                      dst=tun.remote_ip6) /
3205                 UDP(sport=1234, dport=5678) /
3206                 Raw(b'0xa' * 1000))
3207         p_1k = (Ether(dst=self.pg0.local_mac,
3208                       src=self.pg0.remote_mac) /
3209                 IPv6(src=self.pg0.remote_ip6,
3210                      dst=tun.remote_ip6) /
3211                 UDP(sport=1234, dport=5678) /
3212                 Raw(b'0xa' * 600))
3213
3214         nbr = VppNeighbor(self,
3215                           self.pg1.sw_if_index,
3216                           self.pg1.remote_mac,
3217                           self.pg1.remote_ip6).add_vpp_config()
3218
3219         # this is now the interface MTU frags
3220         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
3221         self.send_and_expect(self.pg0, [p_1k], self.pg1)
3222
3223         # drop the path MTU for this neighbour to below the interface MTU
3224         # expect more frags
3225         pmtu = VppIpPathMtu(self, tun_dst, 1300).add_vpp_config()
3226
3227         # print/format the fib entry/dpo
3228         self.logger.info(self.vapi.cli("sh ip6 fib 2001::1"))
3229
3230         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
3231         self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
3232
3233         # increase the path MTU to more than the interface
3234         # expect to use the interface MTU
3235         pmtu.modify(8192)
3236
3237         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
3238         self.send_and_expect(self.pg0, [p_1k], self.pg1)
3239
3240         # go back to an MTU from the path
3241         pmtu.modify(1300)
3242
3243         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
3244         self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
3245
3246         # raise the interface's MTU
3247         # should still use that of the path
3248         self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
3249                                        [2000, 0, 0, 0])
3250         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
3251         self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
3252
3253         # turn the tun_dst into an attached neighbour
3254         route.modify([VppRoutePath("::",
3255                                    self.pg1.sw_if_index)])
3256         nbr2 = VppNeighbor(self,
3257                            self.pg1.sw_if_index,
3258                            self.pg1.remote_mac,
3259                            tun_dst).add_vpp_config()
3260
3261         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
3262         self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
3263
3264         # add back to not attached
3265         nbr2.remove_vpp_config()
3266         route.modify([VppRoutePath(self.pg1.remote_ip6,
3267                                    self.pg1.sw_if_index)])
3268
3269         # set path high and interface low
3270         pmtu.modify(2000)
3271         self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
3272                                        [1300, 0, 0, 0])
3273         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
3274         self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
3275
3276         # remove the path MTU
3277         self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
3278                                        [2800, 0, 0, 0])
3279         pmtu.remove_vpp_config()
3280         self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
3281         self.send_and_expect(self.pg0, [p_1k], self.pg1)
3282
3283
3284 class TestIPFibSource(VppTestCase):
3285     """ IPv6 Table FibSource """
3286
3287     @classmethod
3288     def setUpClass(cls):
3289         super(TestIPFibSource, cls).setUpClass()
3290
3291     @classmethod
3292     def tearDownClass(cls):
3293         super(TestIPFibSource, cls).tearDownClass()
3294
3295     def setUp(self):
3296         super(TestIPFibSource, self).setUp()
3297
3298         self.create_pg_interfaces(range(2))
3299
3300         for i in self.pg_interfaces:
3301             i.admin_up()
3302             i.config_ip6()
3303             i.resolve_arp()
3304             i.generate_remote_hosts(2)
3305             i.configure_ipv6_neighbors()
3306
3307     def tearDown(self):
3308         super(TestIPFibSource, self).tearDown()
3309         for i in self.pg_interfaces:
3310             i.admin_down()
3311             i.unconfig_ip4()
3312
3313     def test_fib_source(self):
3314         """ IP Table FibSource """
3315
3316         routes = self.vapi.ip_route_v2_dump(0, True)
3317
3318         # 2 interfaces (4 routes) + 2 specials + 4 neighbours = 10 routes
3319         self.assertEqual(len(routes), 10)
3320
3321         # dump all the sources in the FIB
3322         sources = self.vapi.fib_source_dump()
3323         for source in sources:
3324             if (source.src.name == "API"):
3325                 api_source = source.src
3326             if (source.src.name == "interface"):
3327                 intf_source = source.src
3328             if (source.src.name == "adjacency"):
3329                 adj_source = source.src
3330             if (source.src.name == "special"):
3331                 special_source = source.src
3332             if (source.src.name == "default-route"):
3333                 dr_source = source.src
3334
3335         # dump the individual route types
3336         routes = self.vapi.ip_route_v2_dump(0, True, src=adj_source.id)
3337         self.assertEqual(len(routes), 4)
3338         routes = self.vapi.ip_route_v2_dump(0, True, src=intf_source.id)
3339         self.assertEqual(len(routes), 4)
3340         routes = self.vapi.ip_route_v2_dump(0, True, src=special_source.id)
3341         self.assertEqual(len(routes), 1)
3342         routes = self.vapi.ip_route_v2_dump(0, True, src=dr_source.id)
3343         self.assertEqual(len(routes), 1)
3344
3345         # add a new soure that'a better than the API
3346         self.vapi.fib_source_add(src={'name': "bgp",
3347                                       "priority": api_source.priority - 1})
3348
3349         # dump all the sources to check our new one is there
3350         sources = self.vapi.fib_source_dump()
3351
3352         for source in sources:
3353             if (source.src.name == "bgp"):
3354                 bgp_source = source.src
3355
3356         self.assertTrue(bgp_source)
3357         self.assertEqual(bgp_source.priority,
3358                          api_source.priority - 1)
3359
3360         # add a route with the default API source
3361         r1 = VppIpRouteV2(
3362             self, "2001::1", 128,
3363             [VppRoutePath(self.pg0.remote_ip6,
3364                           self.pg0.sw_if_index)]).add_vpp_config()
3365
3366         r2 = VppIpRouteV2(self, "2001::1", 128,
3367                           [VppRoutePath(self.pg1.remote_ip6,
3368                                         self.pg1.sw_if_index)],
3369                           src=bgp_source.id).add_vpp_config()
3370
3371         # ensure the BGP source takes priority
3372         p = (Ether(src=self.pg0.remote_mac,
3373                    dst=self.pg0.local_mac) /
3374              IPv6(src=self.pg0.remote_ip6, dst="2001::1") /
3375              inet6.UDP(sport=1234, dport=1234) /
3376              Raw(b'\xa5' * 100))
3377
3378         self.send_and_expect(self.pg0, [p], self.pg1)
3379
3380         r2.remove_vpp_config()
3381         r1.remove_vpp_config()
3382
3383         self.assertFalse(find_route(self, "2001::1", 128))
3384
3385
3386 if __name__ == '__main__':
3387     unittest.main(testRunner=VppTestRunner)