Tests Cleanup: Fix missing calls to setUpClass/tearDownClass.
[vpp.git] / test / test_ip6.py
1 #!/usr/bin/env python
2
3 import socket
4 import unittest
5
6 from parameterized import parameterized
7 import scapy.compat
8 import scapy.layers.inet6 as inet6
9 from scapy.contrib.mpls import MPLS
10 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_RS, \
11     ICMPv6ND_RA, ICMPv6NDOptMTU, ICMPv6NDOptSrcLLAddr, ICMPv6NDOptPrefixInfo, \
12     ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, ICMPv6DestUnreach, icmp6types, \
13     ICMPv6TimeExceeded, ICMPv6EchoRequest, ICMPv6EchoReply
14 from scapy.layers.l2 import Ether, Dot1Q
15 from scapy.packet import Raw
16 from scapy.utils import inet_pton, inet_ntop
17 from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ptop, in6_islladdr, \
18     in6_mactoifaceid
19 from six import moves
20
21 from framework import VppTestCase, VppTestRunner
22 from util import ppp, ip6_normalize, mk_ll_addr
23 from vpp_ip import DpoProto
24 from vpp_ip_route import VppIpRoute, VppRoutePath, find_route, VppIpMRoute, \
25     VppMRoutePath, MRouteItfFlags, MRouteEntryFlags, VppMplsIpBind, \
26     VppMplsRoute, VppMplsTable, VppIpTable
27 from vpp_neighbor import find_nbr, VppNeighbor
28 from vpp_pg_interface import is_ipv6_misc
29 from vpp_sub_interface import VppSubInterface, VppDot1QSubint
30 from ipaddress import IPv6Network, IPv4Network
31
32 AF_INET6 = socket.AF_INET6
33
34 try:
35     text_type = unicode
36 except NameError:
37     text_type = str
38
39
40 class TestIPv6ND(VppTestCase):
41     def validate_ra(self, intf, rx, dst_ip=None):
42         if not dst_ip:
43             dst_ip = intf.remote_ip6
44
45         # unicasted packets must come to the unicast mac
46         self.assertEqual(rx[Ether].dst, intf.remote_mac)
47
48         # and from the router's MAC
49         self.assertEqual(rx[Ether].src, intf.local_mac)
50
51         # the rx'd RA should be addressed to the sender's source
52         self.assertTrue(rx.haslayer(ICMPv6ND_RA))
53         self.assertEqual(in6_ptop(rx[IPv6].dst),
54                          in6_ptop(dst_ip))
55
56         # and come from the router's link local
57         self.assertTrue(in6_islladdr(rx[IPv6].src))
58         self.assertEqual(in6_ptop(rx[IPv6].src),
59                          in6_ptop(mk_ll_addr(intf.local_mac)))
60
61     def validate_na(self, intf, rx, dst_ip=None, tgt_ip=None):
62         if not dst_ip:
63             dst_ip = intf.remote_ip6
64         if not tgt_ip:
65             dst_ip = intf.local_ip6
66
67         # unicasted packets must come to the unicast mac
68         self.assertEqual(rx[Ether].dst, intf.remote_mac)
69
70         # and from the router's MAC
71         self.assertEqual(rx[Ether].src, intf.local_mac)
72
73         # the rx'd NA should be addressed to the sender's source
74         self.assertTrue(rx.haslayer(ICMPv6ND_NA))
75         self.assertEqual(in6_ptop(rx[IPv6].dst),
76                          in6_ptop(dst_ip))
77
78         # and come from the target address
79         self.assertEqual(
80             in6_ptop(rx[IPv6].src), in6_ptop(tgt_ip))
81
82         # Dest link-layer options should have the router's MAC
83         dll = rx[ICMPv6NDOptDstLLAddr]
84         self.assertEqual(dll.lladdr, intf.local_mac)
85
86     def validate_ns(self, intf, rx, tgt_ip):
87         nsma = in6_getnsma(inet_pton(AF_INET6, tgt_ip))
88         dst_ip = inet_ntop(AF_INET6, nsma)
89
90         # NS is broadcast
91         self.assertEqual(rx[Ether].dst, in6_getnsmac(nsma))
92
93         # and from the router's MAC
94         self.assertEqual(rx[Ether].src, intf.local_mac)
95
96         # the rx'd NS should be addressed to an mcast address
97         # derived from the target address
98         self.assertEqual(
99             in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip))
100
101         # expect the tgt IP in the NS header
102         ns = rx[ICMPv6ND_NS]
103         self.assertEqual(in6_ptop(ns.tgt), in6_ptop(tgt_ip))
104
105         # packet is from the router's local address
106         self.assertEqual(
107             in6_ptop(rx[IPv6].src), intf.local_ip6)
108
109         # Src link-layer options should have the router's MAC
110         sll = rx[ICMPv6NDOptSrcLLAddr]
111         self.assertEqual(sll.lladdr, intf.local_mac)
112
113     def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None,
114                            filter_out_fn=is_ipv6_misc):
115         intf.add_stream(pkts)
116         self.pg_enable_capture(self.pg_interfaces)
117         self.pg_start()
118         rx = intf.get_capture(1, filter_out_fn=filter_out_fn)
119
120         self.assertEqual(len(rx), 1)
121         rx = rx[0]
122         self.validate_ra(intf, rx, dst_ip)
123
124     def send_and_expect_na(self, intf, pkts, remark, dst_ip=None,
125                            tgt_ip=None,
126                            filter_out_fn=is_ipv6_misc):
127         intf.add_stream(pkts)
128         self.pg_enable_capture(self.pg_interfaces)
129         self.pg_start()
130         rx = intf.get_capture(1, filter_out_fn=filter_out_fn)
131
132         self.assertEqual(len(rx), 1)
133         rx = rx[0]
134         self.validate_na(intf, rx, dst_ip, tgt_ip)
135
136     def send_and_expect_ns(self, tx_intf, rx_intf, pkts, tgt_ip,
137                            filter_out_fn=is_ipv6_misc):
138         tx_intf.add_stream(pkts)
139         self.pg_enable_capture(self.pg_interfaces)
140         self.pg_start()
141         rx = rx_intf.get_capture(1, filter_out_fn=filter_out_fn)
142
143         self.assertEqual(len(rx), 1)
144         rx = rx[0]
145         self.validate_ns(rx_intf, rx, tgt_ip)
146
147     def verify_ip(self, rx, smac, dmac, sip, dip):
148         ether = rx[Ether]
149         self.assertEqual(ether.dst, dmac)
150         self.assertEqual(ether.src, smac)
151
152         ip = rx[IPv6]
153         self.assertEqual(ip.src, sip)
154         self.assertEqual(ip.dst, dip)
155
156
157 class TestIPv6(TestIPv6ND):
158     """ IPv6 Test Case """
159
160     @classmethod
161     def setUpClass(cls):
162         super(TestIPv6, cls).setUpClass()
163
164     @classmethod
165     def tearDownClass(cls):
166         super(TestIPv6, cls).tearDownClass()
167
168     def setUp(self):
169         """
170         Perform test setup before test case.
171
172         **Config:**
173             - create 3 pg interfaces
174                 - untagged pg0 interface
175                 - Dot1Q subinterface on pg1
176                 - Dot1AD subinterface on pg2
177             - setup interfaces:
178                 - put it into UP state
179                 - set IPv6 addresses
180                 - resolve neighbor address using NDP
181             - configure 200 fib entries
182
183         :ivar list interfaces: pg interfaces and subinterfaces.
184         :ivar dict flows: IPv4 packet flows in test.
185
186         *TODO:* Create AD sub interface
187         """
188         super(TestIPv6, self).setUp()
189
190         # create 3 pg interfaces
191         self.create_pg_interfaces(range(3))
192
193         # create 2 subinterfaces for p1 and pg2
194         self.sub_interfaces = [
195             VppDot1QSubint(self, self.pg1, 100),
196             VppDot1QSubint(self, self.pg2, 200)
197             # TODO: VppDot1ADSubint(self, self.pg2, 200, 300, 400)
198         ]
199
200         # packet flows mapping pg0 -> pg1.sub, pg2.sub, etc.
201         self.flows = dict()
202         self.flows[self.pg0] = [self.pg1.sub_if, self.pg2.sub_if]
203         self.flows[self.pg1.sub_if] = [self.pg0, self.pg2.sub_if]
204         self.flows[self.pg2.sub_if] = [self.pg0, self.pg1.sub_if]
205
206         # packet sizes
207         self.pg_if_packet_sizes = [64, 1500, 9020]
208
209         self.interfaces = list(self.pg_interfaces)
210         self.interfaces.extend(self.sub_interfaces)
211
212         # setup all interfaces
213         for i in self.interfaces:
214             i.admin_up()
215             i.config_ip6()
216             i.resolve_ndp()
217
218         # config 2M FIB entries
219         self.config_fib_entries(200)
220
221     def tearDown(self):
222         """Run standard test teardown and log ``show ip6 neighbors``."""
223         for i in self.interfaces:
224             i.unconfig_ip6()
225             i.ip6_disable()
226             i.admin_down()
227         for i in self.sub_interfaces:
228             i.remove_vpp_config()
229
230         super(TestIPv6, self).tearDown()
231         if not self.vpp_dead:
232             self.logger.info(self.vapi.cli("show ip6 neighbors"))
233             # info(self.vapi.cli("show ip6 fib"))  # many entries
234
235     def config_fib_entries(self, count):
236         """For each interface add to the FIB table *count* routes to
237         "fd02::1/128" destination with interface's local address as next-hop
238         address.
239
240         :param int count: Number of FIB entries.
241
242         - *TODO:* check if the next-hop address shouldn't be remote address
243           instead of local address.
244         """
245         n_int = len(self.interfaces)
246         percent = 0
247         counter = 0.0
248         dest_addr = inet_pton(AF_INET6, "fd02::1")
249         dest_addr_len = 128
250         for i in self.interfaces:
251             next_hop_address = i.local_ip6n
252             for j in range(count / n_int):
253                 self.vapi.ip_add_del_route(dst_address=dest_addr,
254                                            dst_address_length=dest_addr_len,
255                                            next_hop_address=next_hop_address,
256                                            is_ipv6=1)
257                 counter += 1
258                 if counter / count * 100 > percent:
259                     self.logger.info("Configure %d FIB entries .. %d%% done" %
260                                      (count, percent))
261                     percent += 1
262
263     def modify_packet(self, src_if, packet_size, pkt):
264         """Add load, set destination IP and extend packet to required packet
265         size for defined interface.
266
267         :param VppInterface src_if: Interface to create packet for.
268         :param int packet_size: Required packet size.
269         :param Scapy pkt: Packet to be modified.
270         """
271         dst_if_idx = packet_size / 10 % 2
272         dst_if = self.flows[src_if][dst_if_idx]
273         info = self.create_packet_info(src_if, dst_if)
274         payload = self.info_to_payload(info)
275         p = pkt / Raw(payload)
276         p[IPv6].dst = dst_if.remote_ip6
277         info.data = p.copy()
278         if isinstance(src_if, VppSubInterface):
279             p = src_if.add_dot1_layer(p)
280         self.extend_packet(p, packet_size)
281
282         return p
283
284     def create_stream(self, src_if):
285         """Create input packet stream for defined interface.
286
287         :param VppInterface src_if: Interface to create packet stream for.
288         """
289         hdr_ext = 4 if isinstance(src_if, VppSubInterface) else 0
290         pkt_tmpl = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
291                     IPv6(src=src_if.remote_ip6) /
292                     inet6.UDP(sport=1234, dport=1234))
293
294         pkts = [self.modify_packet(src_if, i, pkt_tmpl)
295                 for i in moves.range(self.pg_if_packet_sizes[0],
296                                      self.pg_if_packet_sizes[1], 10)]
297         pkts_b = [self.modify_packet(src_if, i, pkt_tmpl)
298                   for i in moves.range(self.pg_if_packet_sizes[1] + hdr_ext,
299                                        self.pg_if_packet_sizes[2] + hdr_ext,
300                                        50)]
301         pkts.extend(pkts_b)
302
303         return pkts
304
305     def verify_capture(self, dst_if, capture):
306         """Verify captured input packet stream for defined interface.
307
308         :param VppInterface dst_if: Interface to verify captured packet stream
309                                     for.
310         :param list capture: Captured packet stream.
311         """
312         self.logger.info("Verifying capture on interface %s" % dst_if.name)
313         last_info = dict()
314         for i in self.interfaces:
315             last_info[i.sw_if_index] = None
316         is_sub_if = False
317         dst_sw_if_index = dst_if.sw_if_index
318         if hasattr(dst_if, 'parent'):
319             is_sub_if = True
320         for packet in capture:
321             if is_sub_if:
322                 # Check VLAN tags and Ethernet header
323                 packet = dst_if.remove_dot1_layer(packet)
324             self.assertTrue(Dot1Q not in packet)
325             try:
326                 ip = packet[IPv6]
327                 udp = packet[inet6.UDP]
328                 payload_info = self.payload_to_info(packet[Raw])
329                 packet_index = payload_info.index
330                 self.assertEqual(payload_info.dst, dst_sw_if_index)
331                 self.logger.debug(
332                     "Got packet on port %s: src=%u (id=%u)" %
333                     (dst_if.name, payload_info.src, packet_index))
334                 next_info = self.get_next_packet_info_for_interface2(
335                     payload_info.src, dst_sw_if_index,
336                     last_info[payload_info.src])
337                 last_info[payload_info.src] = next_info
338                 self.assertTrue(next_info is not None)
339                 self.assertEqual(packet_index, next_info.index)
340                 saved_packet = next_info.data
341                 # Check standard fields
342                 self.assertEqual(
343                     ip.src, saved_packet[IPv6].src)
344                 self.assertEqual(
345                     ip.dst, saved_packet[IPv6].dst)
346                 self.assertEqual(
347                     udp.sport, saved_packet[inet6.UDP].sport)
348                 self.assertEqual(
349                     udp.dport, saved_packet[inet6.UDP].dport)
350             except:
351                 self.logger.error(ppp("Unexpected or invalid packet:", packet))
352                 raise
353         for i in self.interfaces:
354             remaining_packet = self.get_next_packet_info_for_interface2(
355                 i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
356             self.assertTrue(remaining_packet is None,
357                             "Interface %s: Packet expected from interface %s "
358                             "didn't arrive" % (dst_if.name, i.name))
359
360     def test_fib(self):
361         """ IPv6 FIB test
362
363         Test scenario:
364             - Create IPv6 stream for pg0 interface
365             - Create IPv6 tagged streams for pg1's and pg2's subinterface.
366             - Send and verify received packets on each interface.
367         """
368
369         pkts = self.create_stream(self.pg0)
370         self.pg0.add_stream(pkts)
371
372         for i in self.sub_interfaces:
373             pkts = self.create_stream(i)
374             i.parent.add_stream(pkts)
375
376         self.pg_enable_capture(self.pg_interfaces)
377         self.pg_start()
378
379         pkts = self.pg0.get_capture()
380         self.verify_capture(self.pg0, pkts)
381
382         for i in self.sub_interfaces:
383             pkts = i.parent.get_capture()
384             self.verify_capture(i, pkts)
385
386     def test_ns(self):
387         """ IPv6 Neighbour Solicitation Exceptions
388
389         Test scenario:
390            - Send an NS Sourced from an address not covered by the link sub-net
391            - Send an NS to an mcast address the router has not joined
392            - Send NS for a target address the router does not onn.
393         """
394
395         #
396         # An NS from a non link source address
397         #
398         nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
399         d = inet_ntop(AF_INET6, nsma)
400
401         p = (Ether(dst=in6_getnsmac(nsma)) /
402              IPv6(dst=d, src="2002::2") /
403              ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
404              ICMPv6NDOptSrcLLAddr(
405                  lladdr=self.pg0.remote_mac))
406         pkts = [p]
407
408         self.send_and_assert_no_replies(
409             self.pg0, pkts,
410             "No response to NS source by address not on sub-net")
411
412         #
413         # An NS for sent to a solicited mcast group the router is
414         # not a member of FAILS
415         #
416         if 0:
417             nsma = in6_getnsma(inet_pton(AF_INET6, "fd::ffff"))
418             d = inet_ntop(AF_INET6, nsma)
419
420             p = (Ether(dst=in6_getnsmac(nsma)) /
421                  IPv6(dst=d, src=self.pg0.remote_ip6) /
422                  ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
423                  ICMPv6NDOptSrcLLAddr(
424                      lladdr=self.pg0.remote_mac))
425             pkts = [p]
426
427             self.send_and_assert_no_replies(
428                 self.pg0, pkts,
429                 "No response to NS sent to unjoined mcast address")
430
431         #
432         # An NS whose target address is one the router does not own
433         #
434         nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
435         d = inet_ntop(AF_INET6, nsma)
436
437         p = (Ether(dst=in6_getnsmac(nsma)) /
438              IPv6(dst=d, src=self.pg0.remote_ip6) /
439              ICMPv6ND_NS(tgt="fd::ffff") /
440              ICMPv6NDOptSrcLLAddr(
441                  lladdr=self.pg0.remote_mac))
442         pkts = [p]
443
444         self.send_and_assert_no_replies(self.pg0, pkts,
445                                         "No response to NS for unknown target")
446
447         #
448         # A neighbor entry that has no associated FIB-entry
449         #
450         self.pg0.generate_remote_hosts(4)
451         nd_entry = VppNeighbor(self,
452                                self.pg0.sw_if_index,
453                                self.pg0.remote_hosts[2].mac,
454                                self.pg0.remote_hosts[2].ip6,
455                                is_no_fib_entry=1)
456         nd_entry.add_vpp_config()
457
458         #
459         # check we have the neighbor, but no route
460         #
461         self.assertTrue(find_nbr(self,
462                                  self.pg0.sw_if_index,
463                                  self.pg0._remote_hosts[2].ip6))
464         self.assertFalse(find_route(self,
465                                     self.pg0._remote_hosts[2].ip6,
466                                     128,
467                                     inet=AF_INET6))
468
469         #
470         # send an NS from a link local address to the interface's global
471         # address
472         #
473         p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
474              IPv6(
475                  dst=d, src=self.pg0._remote_hosts[2].ip6_ll) /
476              ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
477              ICMPv6NDOptSrcLLAddr(
478                  lladdr=self.pg0.remote_mac))
479
480         self.send_and_expect_na(self.pg0, p,
481                                 "NS from link-local",
482                                 dst_ip=self.pg0._remote_hosts[2].ip6_ll,
483                                 tgt_ip=self.pg0.local_ip6)
484
485         #
486         # we should have learned an ND entry for the peer's link-local
487         # but not inserted a route to it in the FIB
488         #
489         self.assertTrue(find_nbr(self,
490                                  self.pg0.sw_if_index,
491                                  self.pg0._remote_hosts[2].ip6_ll))
492         self.assertFalse(find_route(self,
493                                     self.pg0._remote_hosts[2].ip6_ll,
494                                     128,
495                                     inet=AF_INET6))
496
497         #
498         # An NS to the router's own Link-local
499         #
500         p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
501              IPv6(
502                  dst=d, src=self.pg0._remote_hosts[3].ip6_ll) /
503              ICMPv6ND_NS(tgt=self.pg0.local_ip6_ll) /
504              ICMPv6NDOptSrcLLAddr(
505                  lladdr=self.pg0.remote_mac))
506
507         self.send_and_expect_na(self.pg0, p,
508                                 "NS to/from link-local",
509                                 dst_ip=self.pg0._remote_hosts[3].ip6_ll,
510                                 tgt_ip=self.pg0.local_ip6_ll)
511
512         #
513         # we should have learned an ND entry for the peer's link-local
514         # but not inserted a route to it in the FIB
515         #
516         self.assertTrue(find_nbr(self,
517                                  self.pg0.sw_if_index,
518                                  self.pg0._remote_hosts[3].ip6_ll))
519         self.assertFalse(find_route(self,
520                                     self.pg0._remote_hosts[3].ip6_ll,
521                                     128,
522                                     inet=AF_INET6))
523
524     def test_ns_duplicates(self):
525         """ ND Duplicates"""
526
527         #
528         # Generate some hosts on the LAN
529         #
530         self.pg1.generate_remote_hosts(3)
531
532         #
533         # Add host 1 on pg1 and pg2
534         #
535         ns_pg1 = VppNeighbor(self,
536                              self.pg1.sw_if_index,
537                              self.pg1.remote_hosts[1].mac,
538                              self.pg1.remote_hosts[1].ip6)
539         ns_pg1.add_vpp_config()
540         ns_pg2 = VppNeighbor(self,
541                              self.pg2.sw_if_index,
542                              self.pg2.remote_mac,
543                              self.pg1.remote_hosts[1].ip6)
544         ns_pg2.add_vpp_config()
545
546         #
547         # IP packet destined for pg1 remote host arrives on pg1 again.
548         #
549         p = (Ether(dst=self.pg0.local_mac,
550                    src=self.pg0.remote_mac) /
551              IPv6(src=self.pg0.remote_ip6,
552                   dst=self.pg1.remote_hosts[1].ip6) /
553              inet6.UDP(sport=1234, dport=1234) /
554              Raw())
555
556         self.pg0.add_stream(p)
557         self.pg_enable_capture(self.pg_interfaces)
558         self.pg_start()
559
560         rx1 = self.pg1.get_capture(1)
561
562         self.verify_ip(rx1[0],
563                        self.pg1.local_mac,
564                        self.pg1.remote_hosts[1].mac,
565                        self.pg0.remote_ip6,
566                        self.pg1.remote_hosts[1].ip6)
567
568         #
569         # remove the duplicate on pg1
570         # packet stream should generate NSs out of pg1
571         #
572         ns_pg1.remove_vpp_config()
573
574         self.send_and_expect_ns(self.pg0, self.pg1,
575                                 p, self.pg1.remote_hosts[1].ip6)
576
577         #
578         # Add it back
579         #
580         ns_pg1.add_vpp_config()
581
582         self.pg0.add_stream(p)
583         self.pg_enable_capture(self.pg_interfaces)
584         self.pg_start()
585
586         rx1 = self.pg1.get_capture(1)
587
588         self.verify_ip(rx1[0],
589                        self.pg1.local_mac,
590                        self.pg1.remote_hosts[1].mac,
591                        self.pg0.remote_ip6,
592                        self.pg1.remote_hosts[1].ip6)
593
594     def validate_ra(self, intf, rx, dst_ip=None, mtu=9000, pi_opt=None):
595         if not dst_ip:
596             dst_ip = intf.remote_ip6
597
598         # unicasted packets must come to the unicast mac
599         self.assertEqual(rx[Ether].dst, intf.remote_mac)
600
601         # and from the router's MAC
602         self.assertEqual(rx[Ether].src, intf.local_mac)
603
604         # the rx'd RA should be addressed to the sender's source
605         self.assertTrue(rx.haslayer(ICMPv6ND_RA))
606         self.assertEqual(in6_ptop(rx[IPv6].dst),
607                          in6_ptop(dst_ip))
608
609         # and come from the router's link local
610         self.assertTrue(in6_islladdr(rx[IPv6].src))
611         self.assertEqual(in6_ptop(rx[IPv6].src),
612                          in6_ptop(mk_ll_addr(intf.local_mac)))
613
614         # it should contain the links MTU
615         ra = rx[ICMPv6ND_RA]
616         self.assertEqual(ra[ICMPv6NDOptMTU].mtu, mtu)
617
618         # it should contain the source's link layer address option
619         sll = ra[ICMPv6NDOptSrcLLAddr]
620         self.assertEqual(sll.lladdr, intf.local_mac)
621
622         if not pi_opt:
623             # the RA should not contain prefix information
624             self.assertFalse(ra.haslayer(
625                 ICMPv6NDOptPrefixInfo))
626         else:
627             raos = rx.getlayer(ICMPv6NDOptPrefixInfo, 1)
628
629             # the options are nested in the scapy packet in way that i cannot
630             # decipher how to decode. this 1st layer of option always returns
631             # nested classes, so a direct obj1=obj2 comparison always fails.
632             # however, the getlayer(.., 2) does give one instnace.
633             # so we cheat here and construct a new opt instance for comparison
634             rd = ICMPv6NDOptPrefixInfo(
635                 prefixlen=raos.prefixlen,
636                 prefix=raos.prefix,
637                 L=raos.L,
638                 A=raos.A)
639             if type(pi_opt) is list:
640                 for ii in range(len(pi_opt)):
641                     self.assertEqual(pi_opt[ii], rd)
642                     rd = rx.getlayer(
643                         ICMPv6NDOptPrefixInfo, ii + 2)
644             else:
645                 self.assertEqual(pi_opt, raos)
646
647     def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None,
648                            filter_out_fn=is_ipv6_misc,
649                            opt=None):
650         intf.add_stream(pkts)
651         self.pg_enable_capture(self.pg_interfaces)
652         self.pg_start()
653         rx = intf.get_capture(1, filter_out_fn=filter_out_fn)
654
655         self.assertEqual(len(rx), 1)
656         rx = rx[0]
657         self.validate_ra(intf, rx, dst_ip, pi_opt=opt)
658
659     def test_rs(self):
660         """ IPv6 Router Solicitation Exceptions
661
662         Test scenario:
663         """
664
665         #
666         # Before we begin change the IPv6 RA responses to use the unicast
667         # address - that way we will not confuse them with the periodic
668         # RAs which go to the mcast address
669         # Sit and wait for the first periodic RA.
670         #
671         # TODO
672         #
673         self.pg0.ip6_ra_config(send_unicast=1)
674
675         #
676         # An RS from a link source address
677         #  - expect an RA in return
678         #
679         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
680              IPv6(
681                  dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
682              ICMPv6ND_RS())
683         pkts = [p]
684         self.send_and_expect_ra(self.pg0, pkts, "Genuine RS")
685
686         #
687         # For the next RS sent the RA should be rate limited
688         #
689         self.send_and_assert_no_replies(self.pg0, pkts, "RA rate limited")
690
691         #
692         # When we reconfigure the IPv6 RA config,
693         # we reset the RA rate limiting,
694         # so we need to do this before each test below so as not to drop
695         # packets for rate limiting reasons. Test this works here.
696         #
697         self.pg0.ip6_ra_config(send_unicast=1)
698         self.send_and_expect_ra(self.pg0, pkts, "Rate limit reset RS")
699
700         #
701         # An RS sent from a non-link local source
702         #
703         self.pg0.ip6_ra_config(send_unicast=1)
704         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
705              IPv6(dst=self.pg0.local_ip6,
706                   src="2002::ffff") /
707              ICMPv6ND_RS())
708         pkts = [p]
709         self.send_and_assert_no_replies(self.pg0, pkts,
710                                         "RS from non-link source")
711
712         #
713         # Source an RS from a link local address
714         #
715         self.pg0.ip6_ra_config(send_unicast=1)
716         ll = mk_ll_addr(self.pg0.remote_mac)
717         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
718              IPv6(dst=self.pg0.local_ip6, src=ll) /
719              ICMPv6ND_RS())
720         pkts = [p]
721         self.send_and_expect_ra(self.pg0, pkts,
722                                 "RS sourced from link-local",
723                                 dst_ip=ll)
724
725         #
726         # Send the RS multicast
727         #
728         self.pg0.ip6_ra_config(send_unicast=1)
729         dmac = in6_getnsmac(inet_pton(AF_INET6, "ff02::2"))
730         ll = mk_ll_addr(self.pg0.remote_mac)
731         p = (Ether(dst=dmac, src=self.pg0.remote_mac) /
732              IPv6(dst="ff02::2", src=ll) /
733              ICMPv6ND_RS())
734         pkts = [p]
735         self.send_and_expect_ra(self.pg0, pkts,
736                                 "RS sourced from link-local",
737                                 dst_ip=ll)
738
739         #
740         # Source from the unspecified address ::. This happens when the RS
741         # is sent before the host has a configured address/sub-net,
742         # i.e. auto-config. Since the sender has no IP address, the reply
743         # comes back mcast - so the capture needs to not filter this.
744         # If we happen to pick up the periodic RA at this point then so be it,
745         # it's not an error.
746         #
747         self.pg0.ip6_ra_config(send_unicast=1, suppress=1)
748         p = (Ether(dst=dmac, src=self.pg0.remote_mac) /
749              IPv6(dst="ff02::2", src="::") /
750              ICMPv6ND_RS())
751         pkts = [p]
752         self.send_and_expect_ra(self.pg0, pkts,
753                                 "RS sourced from unspecified",
754                                 dst_ip="ff02::1",
755                                 filter_out_fn=None)
756
757         #
758         # Configure The RA to announce the links prefix
759         #
760         self.pg0.ip6_ra_prefix(self.pg0.local_ip6,
761                                self.pg0.local_ip6_prefix_len)
762
763         #
764         # RAs should now contain the prefix information option
765         #
766         opt = ICMPv6NDOptPrefixInfo(
767             prefixlen=self.pg0.local_ip6_prefix_len,
768             prefix=self.pg0.local_ip6,
769             L=1,
770             A=1)
771
772         self.pg0.ip6_ra_config(send_unicast=1)
773         ll = mk_ll_addr(self.pg0.remote_mac)
774         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
775              IPv6(dst=self.pg0.local_ip6, src=ll) /
776              ICMPv6ND_RS())
777         self.send_and_expect_ra(self.pg0, p,
778                                 "RA with prefix-info",
779                                 dst_ip=ll,
780                                 opt=opt)
781
782         #
783         # Change the prefix info to not off-link
784         #  L-flag is clear
785         #
786         self.pg0.ip6_ra_prefix(self.pg0.local_ip6,
787                                self.pg0.local_ip6_prefix_len,
788                                off_link=1)
789
790         opt = ICMPv6NDOptPrefixInfo(
791             prefixlen=self.pg0.local_ip6_prefix_len,
792             prefix=self.pg0.local_ip6,
793             L=0,
794             A=1)
795
796         self.pg0.ip6_ra_config(send_unicast=1)
797         self.send_and_expect_ra(self.pg0, p,
798                                 "RA with Prefix info with L-flag=0",
799                                 dst_ip=ll,
800                                 opt=opt)
801
802         #
803         # Change the prefix info to not off-link, no-autoconfig
804         #  L and A flag are clear in the advert
805         #
806         self.pg0.ip6_ra_prefix(self.pg0.local_ip6,
807                                self.pg0.local_ip6_prefix_len,
808                                off_link=1,
809                                no_autoconfig=1)
810
811         opt = ICMPv6NDOptPrefixInfo(
812             prefixlen=self.pg0.local_ip6_prefix_len,
813             prefix=self.pg0.local_ip6,
814             L=0,
815             A=0)
816
817         self.pg0.ip6_ra_config(send_unicast=1)
818         self.send_and_expect_ra(self.pg0, p,
819                                 "RA with Prefix info with A & L-flag=0",
820                                 dst_ip=ll,
821                                 opt=opt)
822
823         #
824         # Change the flag settings back to the defaults
825         #  L and A flag are set in the advert
826         #
827         self.pg0.ip6_ra_prefix(self.pg0.local_ip6,
828                                self.pg0.local_ip6_prefix_len)
829
830         opt = ICMPv6NDOptPrefixInfo(
831             prefixlen=self.pg0.local_ip6_prefix_len,
832             prefix=self.pg0.local_ip6,
833             L=1,
834             A=1)
835
836         self.pg0.ip6_ra_config(send_unicast=1)
837         self.send_and_expect_ra(self.pg0, p,
838                                 "RA with Prefix info",
839                                 dst_ip=ll,
840                                 opt=opt)
841
842         #
843         # Change the prefix info to not off-link, no-autoconfig
844         #  L and A flag are clear in the advert
845         #
846         self.pg0.ip6_ra_prefix(self.pg0.local_ip6,
847                                self.pg0.local_ip6_prefix_len,
848                                off_link=1,
849                                no_autoconfig=1)
850
851         opt = ICMPv6NDOptPrefixInfo(
852             prefixlen=self.pg0.local_ip6_prefix_len,
853             prefix=self.pg0.local_ip6,
854             L=0,
855             A=0)
856
857         self.pg0.ip6_ra_config(send_unicast=1)
858         self.send_and_expect_ra(self.pg0, p,
859                                 "RA with Prefix info with A & L-flag=0",
860                                 dst_ip=ll,
861                                 opt=opt)
862
863         #
864         # Use the reset to defaults option to revert to defaults
865         #  L and A flag are clear in the advert
866         #
867         self.pg0.ip6_ra_prefix(self.pg0.local_ip6,
868                                self.pg0.local_ip6_prefix_len,
869                                use_default=1)
870
871         opt = ICMPv6NDOptPrefixInfo(
872             prefixlen=self.pg0.local_ip6_prefix_len,
873             prefix=self.pg0.local_ip6,
874             L=1,
875             A=1)
876
877         self.pg0.ip6_ra_config(send_unicast=1)
878         self.send_and_expect_ra(self.pg0, p,
879                                 "RA with Prefix reverted to defaults",
880                                 dst_ip=ll,
881                                 opt=opt)
882
883         #
884         # Advertise Another prefix. With no L-flag/A-flag
885         #
886         self.pg0.ip6_ra_prefix(self.pg1.local_ip6,
887                                self.pg1.local_ip6_prefix_len,
888                                off_link=1,
889                                no_autoconfig=1)
890
891         opt = [ICMPv6NDOptPrefixInfo(
892             prefixlen=self.pg0.local_ip6_prefix_len,
893             prefix=self.pg0.local_ip6,
894             L=1,
895             A=1),
896             ICMPv6NDOptPrefixInfo(
897                 prefixlen=self.pg1.local_ip6_prefix_len,
898                 prefix=self.pg1.local_ip6,
899                 L=0,
900                 A=0)]
901
902         self.pg0.ip6_ra_config(send_unicast=1)
903         ll = mk_ll_addr(self.pg0.remote_mac)
904         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
905              IPv6(dst=self.pg0.local_ip6, src=ll) /
906              ICMPv6ND_RS())
907         self.send_and_expect_ra(self.pg0, p,
908                                 "RA with multiple Prefix infos",
909                                 dst_ip=ll,
910                                 opt=opt)
911
912         #
913         # Remove the first prefix-info - expect the second is still in the
914         # advert
915         #
916         self.pg0.ip6_ra_prefix(self.pg0.local_ip6,
917                                self.pg0.local_ip6_prefix_len,
918                                is_no=1)
919
920         opt = ICMPv6NDOptPrefixInfo(
921             prefixlen=self.pg1.local_ip6_prefix_len,
922             prefix=self.pg1.local_ip6,
923             L=0,
924             A=0)
925
926         self.pg0.ip6_ra_config(send_unicast=1)
927         self.send_and_expect_ra(self.pg0, p,
928                                 "RA with Prefix reverted to defaults",
929                                 dst_ip=ll,
930                                 opt=opt)
931
932         #
933         # Remove the second prefix-info - expect no prefix-info in the adverts
934         #
935         self.pg0.ip6_ra_prefix(self.pg1.local_ip6,
936                                self.pg1.local_ip6_prefix_len,
937                                is_no=1)
938
939         self.pg0.ip6_ra_config(send_unicast=1)
940         self.send_and_expect_ra(self.pg0, p,
941                                 "RA with Prefix reverted to defaults",
942                                 dst_ip=ll)
943
944         #
945         # Reset the periodic advertisements back to default values
946         #
947         self.pg0.ip6_ra_config(no=1, suppress=1, send_unicast=0)
948
949
950 class TestICMPv6Echo(VppTestCase):
951     """ ICMPv6 Echo Test Case """
952
953     @classmethod
954     def setUpClass(cls):
955         super(TestICMPv6Echo, cls).setUpClass()
956
957     @classmethod
958     def tearDownClass(cls):
959         super(TestICMPv6Echo, cls).tearDownClass()
960
961     def setUp(self):
962         super(TestICMPv6Echo, self).setUp()
963
964         # create 1 pg interface
965         self.create_pg_interfaces(range(1))
966
967         for i in self.pg_interfaces:
968             i.admin_up()
969             i.config_ip6()
970             i.resolve_ndp()
971
972     def tearDown(self):
973         super(TestICMPv6Echo, self).tearDown()
974         for i in self.pg_interfaces:
975             i.unconfig_ip6()
976             i.ip6_disable()
977             i.admin_down()
978
979     def test_icmpv6_echo(self):
980         """ VPP replies to ICMPv6 Echo Request
981
982         Test scenario:
983
984             - Receive ICMPv6 Echo Request message on pg0 interface.
985             - Check outgoing ICMPv6 Echo Reply message on pg0 interface.
986         """
987
988         icmpv6_id = 0xb
989         icmpv6_seq = 5
990         icmpv6_data = b'\x0a' * 18
991         p_echo_request = (Ether(src=self.pg0.remote_mac,
992                                 dst=self.pg0.local_mac) /
993                           IPv6(src=self.pg0.remote_ip6,
994                                dst=self.pg0.local_ip6) /
995                           ICMPv6EchoRequest(
996                               id=icmpv6_id,
997                               seq=icmpv6_seq,
998                               data=icmpv6_data))
999
1000         self.pg0.add_stream(p_echo_request)
1001         self.pg_enable_capture(self.pg_interfaces)
1002         self.pg_start()
1003
1004         rx = self.pg0.get_capture(1)
1005         rx = rx[0]
1006         ether = rx[Ether]
1007         ipv6 = rx[IPv6]
1008         icmpv6 = rx[ICMPv6EchoReply]
1009
1010         self.assertEqual(ether.src, self.pg0.local_mac)
1011         self.assertEqual(ether.dst, self.pg0.remote_mac)
1012
1013         self.assertEqual(ipv6.src, self.pg0.local_ip6)
1014         self.assertEqual(ipv6.dst, self.pg0.remote_ip6)
1015
1016         self.assertEqual(
1017             icmp6types[icmpv6.type], "Echo Reply")
1018         self.assertEqual(icmpv6.id, icmpv6_id)
1019         self.assertEqual(icmpv6.seq, icmpv6_seq)
1020         self.assertEqual(icmpv6.data, icmpv6_data)
1021
1022
1023 class TestIPv6RD(TestIPv6ND):
1024     """ IPv6 Router Discovery Test Case """
1025
1026     @classmethod
1027     def setUpClass(cls):
1028         super(TestIPv6RD, cls).setUpClass()
1029
1030     @classmethod
1031     def tearDownClass(cls):
1032         super(TestIPv6RD, cls).tearDownClass()
1033
1034     def setUp(self):
1035         super(TestIPv6RD, self).setUp()
1036
1037         # create 2 pg interfaces
1038         self.create_pg_interfaces(range(2))
1039
1040         self.interfaces = list(self.pg_interfaces)
1041
1042         # setup all interfaces
1043         for i in self.interfaces:
1044             i.admin_up()
1045             i.config_ip6()
1046
1047     def tearDown(self):
1048         for i in self.interfaces:
1049             i.unconfig_ip6()
1050             i.admin_down()
1051         super(TestIPv6RD, self).tearDown()
1052
1053     def test_rd_send_router_solicitation(self):
1054         """ Verify router solicitation packets """
1055
1056         count = 2
1057         self.pg_enable_capture(self.pg_interfaces)
1058         self.pg_start()
1059         self.vapi.ip6nd_send_router_solicitation(self.pg1.sw_if_index,
1060                                                  mrc=count)
1061         rx_list = self.pg1.get_capture(count, timeout=3)
1062         self.assertEqual(len(rx_list), count)
1063         for packet in rx_list:
1064             self.assertEqual(packet.haslayer(IPv6), 1)
1065             self.assertEqual(packet[IPv6].haslayer(
1066                 ICMPv6ND_RS), 1)
1067             dst = ip6_normalize(packet[IPv6].dst)
1068             dst2 = ip6_normalize("ff02::2")
1069             self.assert_equal(dst, dst2)
1070             src = ip6_normalize(packet[IPv6].src)
1071             src2 = ip6_normalize(self.pg1.local_ip6_ll)
1072             self.assert_equal(src, src2)
1073             self.assertTrue(
1074                 bool(packet[ICMPv6ND_RS].haslayer(
1075                     ICMPv6NDOptSrcLLAddr)))
1076             self.assert_equal(
1077                 packet[ICMPv6NDOptSrcLLAddr].lladdr,
1078                 self.pg1.local_mac)
1079
1080     def verify_prefix_info(self, reported_prefix, prefix_option):
1081         prefix = IPv6Network(
1082             text_type(prefix_option.getfieldval("prefix") +
1083                       "/" +
1084                       text_type(prefix_option.getfieldval("prefixlen"))),
1085             strict=False)
1086         self.assert_equal(reported_prefix.prefix.network_address,
1087                           prefix.network_address)
1088         L = prefix_option.getfieldval("L")
1089         A = prefix_option.getfieldval("A")
1090         option_flags = (L << 7) | (A << 6)
1091         self.assert_equal(reported_prefix.flags, option_flags)
1092         self.assert_equal(reported_prefix.valid_time,
1093                           prefix_option.getfieldval("validlifetime"))
1094         self.assert_equal(reported_prefix.preferred_time,
1095                           prefix_option.getfieldval("preferredlifetime"))
1096
1097     def test_rd_receive_router_advertisement(self):
1098         """ Verify events triggered by received RA packets """
1099
1100         self.vapi.want_ip6_ra_events()
1101
1102         prefix_info_1 = ICMPv6NDOptPrefixInfo(
1103             prefix="1::2",
1104             prefixlen=50,
1105             validlifetime=200,
1106             preferredlifetime=500,
1107             L=1,
1108             A=1,
1109         )
1110
1111         prefix_info_2 = ICMPv6NDOptPrefixInfo(
1112             prefix="7::4",
1113             prefixlen=20,
1114             validlifetime=70,
1115             preferredlifetime=1000,
1116             L=1,
1117             A=0,
1118         )
1119
1120         p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
1121              IPv6(dst=self.pg1.local_ip6_ll,
1122                   src=mk_ll_addr(self.pg1.remote_mac)) /
1123              ICMPv6ND_RA() /
1124              prefix_info_1 /
1125              prefix_info_2)
1126         self.pg1.add_stream([p])
1127         self.pg_start()
1128
1129         ev = self.vapi.wait_for_event(10, "ip6_ra_event")
1130
1131         self.assert_equal(ev.current_hop_limit, 0)
1132         self.assert_equal(ev.flags, 8)
1133         self.assert_equal(ev.router_lifetime_in_sec, 1800)
1134         self.assert_equal(ev.neighbor_reachable_time_in_msec, 0)
1135         self.assert_equal(
1136             ev.time_in_msec_between_retransmitted_neighbor_solicitations, 0)
1137
1138         self.assert_equal(ev.n_prefixes, 2)
1139
1140         self.verify_prefix_info(ev.prefixes[0], prefix_info_1)
1141         self.verify_prefix_info(ev.prefixes[1], prefix_info_2)
1142
1143
1144 class TestIPv6RDControlPlane(TestIPv6ND):
1145     """ IPv6 Router Discovery Control Plane Test Case """
1146
1147     @classmethod
1148     def setUpClass(cls):
1149         super(TestIPv6RDControlPlane, cls).setUpClass()
1150
1151     @classmethod
1152     def tearDownClass(cls):
1153         super(TestIPv6RDControlPlane, cls).tearDownClass()
1154
1155     def setUp(self):
1156         super(TestIPv6RDControlPlane, self).setUp()
1157
1158         # create 1 pg interface
1159         self.create_pg_interfaces(range(1))
1160
1161         self.interfaces = list(self.pg_interfaces)
1162
1163         # setup all interfaces
1164         for i in self.interfaces:
1165             i.admin_up()
1166             i.config_ip6()
1167
1168     def tearDown(self):
1169         super(TestIPv6RDControlPlane, self).tearDown()
1170
1171     @staticmethod
1172     def create_ra_packet(pg, routerlifetime=None):
1173         src_ip = pg.remote_ip6_ll
1174         dst_ip = pg.local_ip6
1175         if routerlifetime is not None:
1176             ra = ICMPv6ND_RA(routerlifetime=routerlifetime)
1177         else:
1178             ra = ICMPv6ND_RA()
1179         p = (Ether(dst=pg.local_mac, src=pg.remote_mac) /
1180              IPv6(dst=dst_ip, src=src_ip) / ra)
1181         return p
1182
1183     @staticmethod
1184     def get_default_routes(fib):
1185         list = []
1186         for entry in fib:
1187             if entry.address_length == 0:
1188                 for path in entry.path:
1189                     if path.sw_if_index != 0xFFFFFFFF:
1190                         default_route = {}
1191                         default_route['sw_if_index'] = path.sw_if_index
1192                         default_route['next_hop'] = path.next_hop
1193                         list.append(default_route)
1194         return list
1195
1196     @staticmethod
1197     def get_interface_addresses(fib, pg):
1198         list = []
1199         for entry in fib:
1200             if entry.address_length == 128:
1201                 path = entry.path[0]
1202                 if path.sw_if_index == pg.sw_if_index:
1203                     list.append(entry.address)
1204         return list
1205
1206     def test_all(self):
1207         """ Test handling of SLAAC addresses and default routes """
1208
1209         fib = self.vapi.ip6_fib_dump()
1210         default_routes = self.get_default_routes(fib)
1211         initial_addresses = set(self.get_interface_addresses(fib, self.pg0))
1212         self.assertEqual(default_routes, [])
1213         router_address = self.pg0.remote_ip6n_ll
1214
1215         self.vapi.ip6_nd_address_autoconfig(self.pg0.sw_if_index, 1, 1)
1216
1217         self.sleep(0.1)
1218
1219         # send RA
1220         packet = (self.create_ra_packet(
1221             self.pg0) / ICMPv6NDOptPrefixInfo(
1222             prefix="1::",
1223             prefixlen=64,
1224             validlifetime=2,
1225             preferredlifetime=2,
1226             L=1,
1227             A=1,
1228         ) / ICMPv6NDOptPrefixInfo(
1229             prefix="7::",
1230             prefixlen=20,
1231             validlifetime=1500,
1232             preferredlifetime=1000,
1233             L=1,
1234             A=0,
1235         ))
1236         self.pg0.add_stream([packet])
1237         self.pg_start()
1238
1239         self.sleep(0.1)
1240
1241         fib = self.vapi.ip6_fib_dump()
1242
1243         # check FIB for new address
1244         addresses = set(self.get_interface_addresses(fib, self.pg0))
1245         new_addresses = addresses.difference(initial_addresses)
1246         self.assertEqual(len(new_addresses), 1)
1247         prefix = list(new_addresses)[0][:8] + '\0\0\0\0\0\0\0\0'
1248         self.assertEqual(inet_ntop(AF_INET6, prefix), '1::')
1249
1250         # check FIB for new default route
1251         default_routes = self.get_default_routes(fib)
1252         self.assertEqual(len(default_routes), 1)
1253         dr = default_routes[0]
1254         self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
1255         self.assertEqual(dr['next_hop'], router_address)
1256
1257         # send RA to delete default route
1258         packet = self.create_ra_packet(self.pg0, routerlifetime=0)
1259         self.pg0.add_stream([packet])
1260         self.pg_start()
1261
1262         self.sleep(0.1)
1263
1264         # check that default route is deleted
1265         fib = self.vapi.ip6_fib_dump()
1266         default_routes = self.get_default_routes(fib)
1267         self.assertEqual(len(default_routes), 0)
1268
1269         self.sleep(0.1)
1270
1271         # send RA
1272         packet = self.create_ra_packet(self.pg0)
1273         self.pg0.add_stream([packet])
1274         self.pg_start()
1275
1276         self.sleep(0.1)
1277
1278         # check FIB for new default route
1279         fib = self.vapi.ip6_fib_dump()
1280         default_routes = self.get_default_routes(fib)
1281         self.assertEqual(len(default_routes), 1)
1282         dr = default_routes[0]
1283         self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
1284         self.assertEqual(dr['next_hop'], router_address)
1285
1286         # send RA, updating router lifetime to 1s
1287         packet = self.create_ra_packet(self.pg0, 1)
1288         self.pg0.add_stream([packet])
1289         self.pg_start()
1290
1291         self.sleep(0.1)
1292
1293         # check that default route still exists
1294         fib = self.vapi.ip6_fib_dump()
1295         default_routes = self.get_default_routes(fib)
1296         self.assertEqual(len(default_routes), 1)
1297         dr = default_routes[0]
1298         self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
1299         self.assertEqual(dr['next_hop'], router_address)
1300
1301         self.sleep(1)
1302
1303         # check that default route is deleted
1304         fib = self.vapi.ip6_fib_dump()
1305         default_routes = self.get_default_routes(fib)
1306         self.assertEqual(len(default_routes), 0)
1307
1308         # check FIB still contains the SLAAC address
1309         addresses = set(self.get_interface_addresses(fib, self.pg0))
1310         new_addresses = addresses.difference(initial_addresses)
1311         self.assertEqual(len(new_addresses), 1)
1312         prefix = list(new_addresses)[0][:8] + '\0\0\0\0\0\0\0\0'
1313         self.assertEqual(inet_ntop(AF_INET6, prefix), '1::')
1314
1315         self.sleep(1)
1316
1317         # check that SLAAC address is deleted
1318         fib = self.vapi.ip6_fib_dump()
1319         addresses = set(self.get_interface_addresses(fib, self.pg0))
1320         new_addresses = addresses.difference(initial_addresses)
1321         self.assertEqual(len(new_addresses), 0)
1322
1323
1324 class IPv6NDProxyTest(TestIPv6ND):
1325     """ IPv6 ND ProxyTest Case """
1326
1327     @classmethod
1328     def setUpClass(cls):
1329         super(IPv6NDProxyTest, cls).setUpClass()
1330
1331     @classmethod
1332     def tearDownClass(cls):
1333         super(IPv6NDProxyTest, cls).tearDownClass()
1334
1335     def setUp(self):
1336         super(IPv6NDProxyTest, self).setUp()
1337
1338         # create 3 pg interfaces
1339         self.create_pg_interfaces(range(3))
1340
1341         # pg0 is the master interface, with the configured subnet
1342         self.pg0.admin_up()
1343         self.pg0.config_ip6()
1344         self.pg0.resolve_ndp()
1345
1346         self.pg1.ip6_enable()
1347         self.pg2.ip6_enable()
1348
1349     def tearDown(self):
1350         super(IPv6NDProxyTest, self).tearDown()
1351
1352     def test_nd_proxy(self):
1353         """ IPv6 Proxy ND """
1354
1355         #
1356         # Generate some hosts in the subnet that we are proxying
1357         #
1358         self.pg0.generate_remote_hosts(8)
1359
1360         nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
1361         d = inet_ntop(AF_INET6, nsma)
1362
1363         #
1364         # Send an NS for one of those remote hosts on one of the proxy links
1365         # expect no response since it's from an address that is not
1366         # on the link that has the prefix configured
1367         #
1368         ns_pg1 = (Ether(dst=in6_getnsmac(nsma), src=self.pg1.remote_mac) /
1369                   IPv6(dst=d,
1370                        src=self.pg0._remote_hosts[2].ip6) /
1371                   ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
1372                   ICMPv6NDOptSrcLLAddr(
1373                       lladdr=self.pg0._remote_hosts[2].mac))
1374
1375         self.send_and_assert_no_replies(self.pg1, ns_pg1, "Off link NS")
1376
1377         #
1378         # Add proxy support for the host
1379         #
1380         self.vapi.ip6nd_proxy_add_del(
1381             ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6),
1382             sw_if_index=self.pg1.sw_if_index)
1383
1384         #
1385         # try that NS again. this time we expect an NA back
1386         #
1387         self.send_and_expect_na(self.pg1, ns_pg1,
1388                                 "NS to proxy entry",
1389                                 dst_ip=self.pg0._remote_hosts[2].ip6,
1390                                 tgt_ip=self.pg0.local_ip6)
1391
1392         #
1393         # ... and that we have an entry in the ND cache
1394         #
1395         self.assertTrue(find_nbr(self,
1396                                  self.pg1.sw_if_index,
1397                                  self.pg0._remote_hosts[2].ip6))
1398
1399         #
1400         # ... and we can route traffic to it
1401         #
1402         t = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
1403              IPv6(dst=self.pg0._remote_hosts[2].ip6,
1404                   src=self.pg0.remote_ip6) /
1405              inet6.UDP(sport=10000, dport=20000) /
1406              Raw('\xa5' * 100))
1407
1408         self.pg0.add_stream(t)
1409         self.pg_enable_capture(self.pg_interfaces)
1410         self.pg_start()
1411         rx = self.pg1.get_capture(1)
1412         rx = rx[0]
1413
1414         self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac)
1415         self.assertEqual(rx[Ether].src, self.pg1.local_mac)
1416
1417         self.assertEqual(rx[IPv6].src,
1418                          t[IPv6].src)
1419         self.assertEqual(rx[IPv6].dst,
1420                          t[IPv6].dst)
1421
1422         #
1423         # Test we proxy for the host on the main interface
1424         #
1425         ns_pg0 = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
1426                   IPv6(dst=d, src=self.pg0.remote_ip6) /
1427                   ICMPv6ND_NS(
1428                       tgt=self.pg0._remote_hosts[2].ip6) /
1429                   ICMPv6NDOptSrcLLAddr(
1430                       lladdr=self.pg0.remote_mac))
1431
1432         self.send_and_expect_na(self.pg0, ns_pg0,
1433                                 "NS to proxy entry on main",
1434                                 tgt_ip=self.pg0._remote_hosts[2].ip6,
1435                                 dst_ip=self.pg0.remote_ip6)
1436
1437         #
1438         # Setup and resolve proxy for another host on another interface
1439         #
1440         ns_pg2 = (Ether(dst=in6_getnsmac(nsma), src=self.pg2.remote_mac) /
1441                   IPv6(dst=d,
1442                        src=self.pg0._remote_hosts[3].ip6) /
1443                   ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
1444                   ICMPv6NDOptSrcLLAddr(
1445                       lladdr=self.pg0._remote_hosts[2].mac))
1446
1447         self.vapi.ip6nd_proxy_add_del(
1448             ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6),
1449             sw_if_index=self.pg2.sw_if_index)
1450
1451         self.send_and_expect_na(self.pg2, ns_pg2,
1452                                 "NS to proxy entry other interface",
1453                                 dst_ip=self.pg0._remote_hosts[3].ip6,
1454                                 tgt_ip=self.pg0.local_ip6)
1455
1456         self.assertTrue(find_nbr(self,
1457                                  self.pg2.sw_if_index,
1458                                  self.pg0._remote_hosts[3].ip6))
1459
1460         #
1461         # hosts can communicate. pg2->pg1
1462         #
1463         t2 = (Ether(dst=self.pg2.local_mac,
1464                     src=self.pg0.remote_hosts[3].mac) /
1465               IPv6(dst=self.pg0._remote_hosts[2].ip6,
1466                    src=self.pg0._remote_hosts[3].ip6) /
1467               inet6.UDP(sport=10000, dport=20000) /
1468               Raw('\xa5' * 100))
1469
1470         self.pg2.add_stream(t2)
1471         self.pg_enable_capture(self.pg_interfaces)
1472         self.pg_start()
1473         rx = self.pg1.get_capture(1)
1474         rx = rx[0]
1475
1476         self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac)
1477         self.assertEqual(rx[Ether].src, self.pg1.local_mac)
1478
1479         self.assertEqual(rx[IPv6].src,
1480                          t2[IPv6].src)
1481         self.assertEqual(rx[IPv6].dst,
1482                          t2[IPv6].dst)
1483
1484         #
1485         # remove the proxy configs
1486         #
1487         self.vapi.ip6nd_proxy_add_del(
1488             ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6),
1489             sw_if_index=self.pg1.sw_if_index, is_del=1)
1490         self.vapi.ip6nd_proxy_add_del(
1491             ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6),
1492             sw_if_index=self.pg2.sw_if_index, is_del=1)
1493
1494         self.assertFalse(find_nbr(self,
1495                                   self.pg2.sw_if_index,
1496                                   self.pg0._remote_hosts[3].ip6))
1497         self.assertFalse(find_nbr(self,
1498                                   self.pg1.sw_if_index,
1499                                   self.pg0._remote_hosts[2].ip6))
1500
1501         #
1502         # no longer proxy-ing...
1503         #
1504         self.send_and_assert_no_replies(self.pg0, ns_pg0, "Proxy unconfigured")
1505         self.send_and_assert_no_replies(self.pg1, ns_pg1, "Proxy unconfigured")
1506         self.send_and_assert_no_replies(self.pg2, ns_pg2, "Proxy unconfigured")
1507
1508         #
1509         # no longer forwarding. traffic generates NS out of the glean/main
1510         # interface
1511         #
1512         self.pg2.add_stream(t2)
1513         self.pg_enable_capture(self.pg_interfaces)
1514         self.pg_start()
1515
1516         rx = self.pg0.get_capture(1)
1517
1518         self.assertTrue(rx[0].haslayer(ICMPv6ND_NS))
1519
1520
1521 class TestIPNull(VppTestCase):
1522     """ IPv6 routes via NULL """
1523
1524     @classmethod
1525     def setUpClass(cls):
1526         super(TestIPNull, cls).setUpClass()
1527
1528     @classmethod
1529     def tearDownClass(cls):
1530         super(TestIPNull, cls).tearDownClass()
1531
1532     def setUp(self):
1533         super(TestIPNull, self).setUp()
1534
1535         # create 2 pg interfaces
1536         self.create_pg_interfaces(range(1))
1537
1538         for i in self.pg_interfaces:
1539             i.admin_up()
1540             i.config_ip6()
1541             i.resolve_ndp()
1542
1543     def tearDown(self):
1544         super(TestIPNull, self).tearDown()
1545         for i in self.pg_interfaces:
1546             i.unconfig_ip6()
1547             i.admin_down()
1548
1549     def test_ip_null(self):
1550         """ IP NULL route """
1551
1552         p = (Ether(src=self.pg0.remote_mac,
1553                    dst=self.pg0.local_mac) /
1554              IPv6(src=self.pg0.remote_ip6, dst="2001::1") /
1555              inet6.UDP(sport=1234, dport=1234) /
1556              Raw('\xa5' * 100))
1557
1558         #
1559         # A route via IP NULL that will reply with ICMP unreachables
1560         #
1561         ip_unreach = VppIpRoute(self, "2001::", 64, [], is_unreach=1, is_ip6=1)
1562         ip_unreach.add_vpp_config()
1563
1564         self.pg0.add_stream(p)
1565         self.pg_enable_capture(self.pg_interfaces)
1566         self.pg_start()
1567
1568         rx = self.pg0.get_capture(1)
1569         rx = rx[0]
1570         icmp = rx[ICMPv6DestUnreach]
1571
1572         # 0 = "No route to destination"
1573         self.assertEqual(icmp.code, 0)
1574
1575         # ICMP is rate limited. pause a bit
1576         self.sleep(1)
1577
1578         #
1579         # A route via IP NULL that will reply with ICMP prohibited
1580         #
1581         ip_prohibit = VppIpRoute(self, "2001::1", 128, [],
1582                                  is_prohibit=1, is_ip6=1)
1583         ip_prohibit.add_vpp_config()
1584
1585         self.pg0.add_stream(p)
1586         self.pg_enable_capture(self.pg_interfaces)
1587         self.pg_start()
1588
1589         rx = self.pg0.get_capture(1)
1590         rx = rx[0]
1591         icmp = rx[ICMPv6DestUnreach]
1592
1593         # 1 = "Communication with destination administratively prohibited"
1594         self.assertEqual(icmp.code, 1)
1595
1596
1597 class TestIPDisabled(VppTestCase):
1598     """ IPv6 disabled """
1599
1600     @classmethod
1601     def setUpClass(cls):
1602         super(TestIPDisabled, cls).setUpClass()
1603
1604     @classmethod
1605     def tearDownClass(cls):
1606         super(TestIPDisabled, cls).tearDownClass()
1607
1608     def setUp(self):
1609         super(TestIPDisabled, self).setUp()
1610
1611         # create 2 pg interfaces
1612         self.create_pg_interfaces(range(2))
1613
1614         # PG0 is IP enabled
1615         self.pg0.admin_up()
1616         self.pg0.config_ip6()
1617         self.pg0.resolve_ndp()
1618
1619         # PG 1 is not IP enabled
1620         self.pg1.admin_up()
1621
1622     def tearDown(self):
1623         super(TestIPDisabled, self).tearDown()
1624         for i in self.pg_interfaces:
1625             i.unconfig_ip4()
1626             i.admin_down()
1627
1628     def test_ip_disabled(self):
1629         """ IP Disabled """
1630
1631         #
1632         # An (S,G).
1633         # one accepting interface, pg0, 2 forwarding interfaces
1634         #
1635         route_ff_01 = VppIpMRoute(
1636             self,
1637             "::",
1638             "ffef::1", 128,
1639             MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
1640             [VppMRoutePath(self.pg1.sw_if_index,
1641                            MRouteItfFlags.MFIB_ITF_FLAG_ACCEPT),
1642              VppMRoutePath(self.pg0.sw_if_index,
1643                            MRouteItfFlags.MFIB_ITF_FLAG_FORWARD)],
1644             is_ip6=1)
1645         route_ff_01.add_vpp_config()
1646
1647         pu = (Ether(src=self.pg1.remote_mac,
1648                     dst=self.pg1.local_mac) /
1649               IPv6(src="2001::1", dst=self.pg0.remote_ip6) /
1650               inet6.UDP(sport=1234, dport=1234) /
1651               Raw('\xa5' * 100))
1652         pm = (Ether(src=self.pg1.remote_mac,
1653                     dst=self.pg1.local_mac) /
1654               IPv6(src="2001::1", dst="ffef::1") /
1655               inet6.UDP(sport=1234, dport=1234) /
1656               Raw('\xa5' * 100))
1657
1658         #
1659         # PG1 does not forward IP traffic
1660         #
1661         self.send_and_assert_no_replies(self.pg1, pu, "IPv6 disabled")
1662         self.send_and_assert_no_replies(self.pg1, pm, "IPv6 disabled")
1663
1664         #
1665         # IP enable PG1
1666         #
1667         self.pg1.config_ip6()
1668
1669         #
1670         # Now we get packets through
1671         #
1672         self.pg1.add_stream(pu)
1673         self.pg_enable_capture(self.pg_interfaces)
1674         self.pg_start()
1675         rx = self.pg0.get_capture(1)
1676
1677         self.pg1.add_stream(pm)
1678         self.pg_enable_capture(self.pg_interfaces)
1679         self.pg_start()
1680         rx = self.pg0.get_capture(1)
1681
1682         #
1683         # Disable PG1
1684         #
1685         self.pg1.unconfig_ip6()
1686
1687         #
1688         # PG1 does not forward IP traffic
1689         #
1690         self.send_and_assert_no_replies(self.pg1, pu, "IPv6 disabled")
1691         self.send_and_assert_no_replies(self.pg1, pm, "IPv6 disabled")
1692
1693
1694 class TestIP6LoadBalance(VppTestCase):
1695     """ IPv6 Load-Balancing """
1696
1697     @classmethod
1698     def setUpClass(cls):
1699         super(TestIP6LoadBalance, cls).setUpClass()
1700
1701     @classmethod
1702     def tearDownClass(cls):
1703         super(TestIP6LoadBalance, cls).tearDownClass()
1704
1705     def setUp(self):
1706         super(TestIP6LoadBalance, self).setUp()
1707
1708         self.create_pg_interfaces(range(5))
1709
1710         mpls_tbl = VppMplsTable(self, 0)
1711         mpls_tbl.add_vpp_config()
1712
1713         for i in self.pg_interfaces:
1714             i.admin_up()
1715             i.config_ip6()
1716             i.resolve_ndp()
1717             i.enable_mpls()
1718
1719     def tearDown(self):
1720         for i in self.pg_interfaces:
1721             i.unconfig_ip6()
1722             i.admin_down()
1723             i.disable_mpls()
1724         super(TestIP6LoadBalance, self).tearDown()
1725
1726     def pg_send(self, input, pkts):
1727         self.vapi.cli("clear trace")
1728         input.add_stream(pkts)
1729         self.pg_enable_capture(self.pg_interfaces)
1730         self.pg_start()
1731
1732     def send_and_expect_load_balancing(self, input, pkts, outputs):
1733         self.pg_send(input, pkts)
1734         for oo in outputs:
1735             rx = oo._get_capture(1)
1736             self.assertNotEqual(0, len(rx))
1737
1738     def send_and_expect_one_itf(self, input, pkts, itf):
1739         self.pg_send(input, pkts)
1740         rx = itf.get_capture(len(pkts))
1741
1742     def test_ip6_load_balance(self):
1743         """ IPv6 Load-Balancing """
1744
1745         #
1746         # An array of packets that differ only in the destination port
1747         #  - IP only
1748         #  - MPLS EOS
1749         #  - MPLS non-EOS
1750         #  - MPLS non-EOS with an entropy label
1751         #
1752         port_ip_pkts = []
1753         port_mpls_pkts = []
1754         port_mpls_neos_pkts = []
1755         port_ent_pkts = []
1756
1757         #
1758         # An array of packets that differ only in the source address
1759         #
1760         src_ip_pkts = []
1761         src_mpls_pkts = []
1762
1763         for ii in range(65):
1764             port_ip_hdr = (
1765                 IPv6(dst="3000::1", src="3000:1::1") /
1766                 inet6.UDP(sport=1234, dport=1234 + ii) /
1767                 Raw('\xa5' * 100))
1768             port_ip_pkts.append((Ether(src=self.pg0.remote_mac,
1769                                        dst=self.pg0.local_mac) /
1770                                  port_ip_hdr))
1771             port_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
1772                                          dst=self.pg0.local_mac) /
1773                                    MPLS(label=66, ttl=2) /
1774                                    port_ip_hdr))
1775             port_mpls_neos_pkts.append((Ether(src=self.pg0.remote_mac,
1776                                               dst=self.pg0.local_mac) /
1777                                         MPLS(label=67, ttl=2) /
1778                                         MPLS(label=77, ttl=2) /
1779                                         port_ip_hdr))
1780             port_ent_pkts.append((Ether(src=self.pg0.remote_mac,
1781                                         dst=self.pg0.local_mac) /
1782                                   MPLS(label=67, ttl=2) /
1783                                   MPLS(label=14, ttl=2) /
1784                                   MPLS(label=999, ttl=2) /
1785                                   port_ip_hdr))
1786             src_ip_hdr = (
1787                 IPv6(dst="3000::1", src="3000:1::%d" % ii) /
1788                 inet6.UDP(sport=1234, dport=1234) /
1789                 Raw('\xa5' * 100))
1790             src_ip_pkts.append((Ether(src=self.pg0.remote_mac,
1791                                       dst=self.pg0.local_mac) /
1792                                 src_ip_hdr))
1793             src_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
1794                                         dst=self.pg0.local_mac) /
1795                                   MPLS(label=66, ttl=2) /
1796                                   src_ip_hdr))
1797
1798         #
1799         # A route for the IP packets
1800         #
1801         route_3000_1 = VppIpRoute(self, "3000::1", 128,
1802                                   [VppRoutePath(self.pg1.remote_ip6,
1803                                                 self.pg1.sw_if_index,
1804                                                 proto=DpoProto.DPO_PROTO_IP6),
1805                                    VppRoutePath(self.pg2.remote_ip6,
1806                                                 self.pg2.sw_if_index,
1807                                                 proto=DpoProto.DPO_PROTO_IP6)],
1808                                   is_ip6=1)
1809         route_3000_1.add_vpp_config()
1810
1811         #
1812         # a local-label for the EOS packets
1813         #
1814         binding = VppMplsIpBind(self, 66, "3000::1", 128, is_ip6=1)
1815         binding.add_vpp_config()
1816
1817         #
1818         # An MPLS route for the non-EOS packets
1819         #
1820         route_67 = VppMplsRoute(self, 67, 0,
1821                                 [VppRoutePath(self.pg1.remote_ip6,
1822                                               self.pg1.sw_if_index,
1823                                               labels=[67],
1824                                               proto=DpoProto.DPO_PROTO_IP6),
1825                                  VppRoutePath(self.pg2.remote_ip6,
1826                                               self.pg2.sw_if_index,
1827                                               labels=[67],
1828                                               proto=DpoProto.DPO_PROTO_IP6)])
1829         route_67.add_vpp_config()
1830
1831         #
1832         # inject the packet on pg0 - expect load-balancing across the 2 paths
1833         #  - since the default hash config is to use IP src,dst and port
1834         #    src,dst
1835         # We are not going to ensure equal amounts of packets across each link,
1836         # since the hash algorithm is statistical and therefore this can never
1837         # be guaranteed. But with 64 different packets we do expect some
1838         # balancing. So instead just ensure there is traffic on each link.
1839         #
1840         self.send_and_expect_load_balancing(self.pg0, port_ip_pkts,
1841                                             [self.pg1, self.pg2])
1842         self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
1843                                             [self.pg1, self.pg2])
1844         self.send_and_expect_load_balancing(self.pg0, port_mpls_pkts,
1845                                             [self.pg1, self.pg2])
1846         self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
1847                                             [self.pg1, self.pg2])
1848         self.send_and_expect_load_balancing(self.pg0, port_mpls_neos_pkts,
1849                                             [self.pg1, self.pg2])
1850
1851         #
1852         # The packets with Entropy label in should not load-balance,
1853         # since the Entropy value is fixed.
1854         #
1855         self.send_and_expect_one_itf(self.pg0, port_ent_pkts, self.pg1)
1856
1857         #
1858         # change the flow hash config so it's only IP src,dst
1859         #  - now only the stream with differing source address will
1860         #    load-balance
1861         #
1862         self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, sport=0, dport=0,
1863                                    is_ipv6=1)
1864
1865         self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
1866                                             [self.pg1, self.pg2])
1867         self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
1868                                             [self.pg1, self.pg2])
1869         self.send_and_expect_one_itf(self.pg0, port_ip_pkts, self.pg2)
1870
1871         #
1872         # change the flow hash config back to defaults
1873         #
1874         self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, sport=1, dport=1,
1875                                    is_ipv6=1)
1876
1877         #
1878         # Recursive prefixes
1879         #  - testing that 2 stages of load-balancing occurs and there is no
1880         #    polarisation (i.e. only 2 of 4 paths are used)
1881         #
1882         port_pkts = []
1883         src_pkts = []
1884
1885         for ii in range(257):
1886             port_pkts.append((Ether(src=self.pg0.remote_mac,
1887                                     dst=self.pg0.local_mac) /
1888                               IPv6(dst="4000::1",
1889                                    src="4000:1::1") /
1890                               inet6.UDP(sport=1234,
1891                                         dport=1234 + ii) /
1892                               Raw('\xa5' * 100)))
1893             src_pkts.append((Ether(src=self.pg0.remote_mac,
1894                                    dst=self.pg0.local_mac) /
1895                              IPv6(dst="4000::1",
1896                                   src="4000:1::%d" % ii) /
1897                              inet6.UDP(sport=1234, dport=1234) /
1898                              Raw('\xa5' * 100)))
1899
1900         route_3000_2 = VppIpRoute(self, "3000::2", 128,
1901                                   [VppRoutePath(self.pg3.remote_ip6,
1902                                                 self.pg3.sw_if_index,
1903                                                 proto=DpoProto.DPO_PROTO_IP6),
1904                                    VppRoutePath(self.pg4.remote_ip6,
1905                                                 self.pg4.sw_if_index,
1906                                                 proto=DpoProto.DPO_PROTO_IP6)],
1907                                   is_ip6=1)
1908         route_3000_2.add_vpp_config()
1909
1910         route_4000_1 = VppIpRoute(self, "4000::1", 128,
1911                                   [VppRoutePath("3000::1",
1912                                                 0xffffffff,
1913                                                 proto=DpoProto.DPO_PROTO_IP6),
1914                                    VppRoutePath("3000::2",
1915                                                 0xffffffff,
1916                                                 proto=DpoProto.DPO_PROTO_IP6)],
1917                                   is_ip6=1)
1918         route_4000_1.add_vpp_config()
1919
1920         #
1921         # inject the packet on pg0 - expect load-balancing across all 4 paths
1922         #
1923         self.vapi.cli("clear trace")
1924         self.send_and_expect_load_balancing(self.pg0, port_pkts,
1925                                             [self.pg1, self.pg2,
1926                                              self.pg3, self.pg4])
1927         self.send_and_expect_load_balancing(self.pg0, src_pkts,
1928                                             [self.pg1, self.pg2,
1929                                              self.pg3, self.pg4])
1930
1931         #
1932         # Recursive prefixes
1933         #  - testing that 2 stages of load-balancing no choices
1934         #
1935         port_pkts = []
1936
1937         for ii in range(257):
1938             port_pkts.append((Ether(src=self.pg0.remote_mac,
1939                                     dst=self.pg0.local_mac) /
1940                               IPv6(dst="6000::1",
1941                                    src="6000:1::1") /
1942                               inet6.UDP(sport=1234,
1943                                         dport=1234 + ii) /
1944                               Raw('\xa5' * 100)))
1945
1946         route_5000_2 = VppIpRoute(self, "5000::2", 128,
1947                                   [VppRoutePath(self.pg3.remote_ip6,
1948                                                 self.pg3.sw_if_index,
1949                                                 proto=DpoProto.DPO_PROTO_IP6)],
1950                                   is_ip6=1)
1951         route_5000_2.add_vpp_config()
1952
1953         route_6000_1 = VppIpRoute(self, "6000::1", 128,
1954                                   [VppRoutePath("5000::2",
1955                                                 0xffffffff,
1956                                                 proto=DpoProto.DPO_PROTO_IP6)],
1957                                   is_ip6=1)
1958         route_6000_1.add_vpp_config()
1959
1960         #
1961         # inject the packet on pg0 - expect load-balancing across all 4 paths
1962         #
1963         self.vapi.cli("clear trace")
1964         self.send_and_expect_one_itf(self.pg0, port_pkts, self.pg3)
1965
1966
1967 class TestIP6Punt(VppTestCase):
1968     """ IPv6 Punt Police/Redirect """
1969
1970     @classmethod
1971     def setUpClass(cls):
1972         super(TestIP6Punt, cls).setUpClass()
1973
1974     @classmethod
1975     def tearDownClass(cls):
1976         super(TestIP6Punt, cls).tearDownClass()
1977
1978     def setUp(self):
1979         super(TestIP6Punt, self).setUp()
1980
1981         self.create_pg_interfaces(range(4))
1982
1983         for i in self.pg_interfaces:
1984             i.admin_up()
1985             i.config_ip6()
1986             i.resolve_ndp()
1987
1988     def tearDown(self):
1989         super(TestIP6Punt, self).tearDown()
1990         for i in self.pg_interfaces:
1991             i.unconfig_ip6()
1992             i.admin_down()
1993
1994     def test_ip_punt(self):
1995         """ IP6 punt police and redirect """
1996
1997         p = (Ether(src=self.pg0.remote_mac,
1998                    dst=self.pg0.local_mac) /
1999              IPv6(src=self.pg0.remote_ip6,
2000                   dst=self.pg0.local_ip6) /
2001              inet6.TCP(sport=1234, dport=1234) /
2002              Raw('\xa5' * 100))
2003
2004         pkts = p * 1025
2005
2006         #
2007         # Configure a punt redirect via pg1.
2008         #
2009         nh_addr = self.pg1.remote_ip6
2010         self.vapi.ip_punt_redirect(self.pg0.sw_if_index,
2011                                    self.pg1.sw_if_index,
2012                                    nh_addr)
2013
2014         self.send_and_expect(self.pg0, pkts, self.pg1)
2015
2016         #
2017         # add a policer
2018         #
2019         policer = self.vapi.policer_add_del(b"ip6-punt", 400, 0, 10, 0,
2020                                             rate_type=1)
2021         self.vapi.ip_punt_police(policer.policer_index, is_ip6=1)
2022
2023         self.vapi.cli("clear trace")
2024         self.pg0.add_stream(pkts)
2025         self.pg_enable_capture(self.pg_interfaces)
2026         self.pg_start()
2027
2028         #
2029         # the number of packet received should be greater than 0,
2030         # but not equal to the number sent, since some were policed
2031         #
2032         rx = self.pg1._get_capture(1)
2033         self.assertGreater(len(rx), 0)
2034         self.assertLess(len(rx), len(pkts))
2035
2036         #
2037         # remove the policer. back to full rx
2038         #
2039         self.vapi.ip_punt_police(policer.policer_index, is_add=0, is_ip6=1)
2040         self.vapi.policer_add_del(b"ip6-punt", 400, 0, 10, 0,
2041                                   rate_type=1, is_add=0)
2042         self.send_and_expect(self.pg0, pkts, self.pg1)
2043
2044         #
2045         # remove the redirect. expect full drop.
2046         #
2047         self.vapi.ip_punt_redirect(self.pg0.sw_if_index,
2048                                    self.pg1.sw_if_index,
2049                                    nh_addr,
2050                                    is_add=0)
2051         self.send_and_assert_no_replies(self.pg0, pkts,
2052                                         "IP no punt config")
2053
2054         #
2055         # Add a redirect that is not input port selective
2056         #
2057         self.vapi.ip_punt_redirect(0xffffffff,
2058                                    self.pg1.sw_if_index,
2059                                    nh_addr)
2060         self.send_and_expect(self.pg0, pkts, self.pg1)
2061
2062         self.vapi.ip_punt_redirect(0xffffffff,
2063                                    self.pg1.sw_if_index,
2064                                    nh_addr,
2065                                    is_add=0)
2066
2067     def test_ip_punt_dump(self):
2068         """ IP6 punt redirect dump"""
2069
2070         #
2071         # Configure a punt redirects
2072         #
2073         nh_addr = self.pg3.remote_ip6
2074         self.vapi.ip_punt_redirect(self.pg0.sw_if_index,
2075                                    self.pg3.sw_if_index,
2076                                    nh_addr)
2077         self.vapi.ip_punt_redirect(self.pg1.sw_if_index,
2078                                    self.pg3.sw_if_index,
2079                                    nh_addr)
2080         self.vapi.ip_punt_redirect(self.pg2.sw_if_index,
2081                                    self.pg3.sw_if_index,
2082                                    '0::0')
2083
2084         #
2085         # Dump pg0 punt redirects
2086         #
2087         punts = self.vapi.ip_punt_redirect_dump(self.pg0.sw_if_index,
2088                                                 is_ipv6=1)
2089         for p in punts:
2090             self.assertEqual(p.punt.rx_sw_if_index, self.pg0.sw_if_index)
2091
2092         #
2093         # Dump punt redirects for all interfaces
2094         #
2095         punts = self.vapi.ip_punt_redirect_dump(0xffffffff, is_ipv6=1)
2096         self.assertEqual(len(punts), 3)
2097         for p in punts:
2098             self.assertEqual(p.punt.tx_sw_if_index, self.pg3.sw_if_index)
2099         self.assertNotEqual(punts[1].punt.nh, self.pg3.remote_ip6)
2100         self.assertEqual(str(punts[2].punt.nh), '::')
2101
2102
2103 class TestIPDeag(VppTestCase):
2104     """ IPv6 Deaggregate Routes """
2105
2106     @classmethod
2107     def setUpClass(cls):
2108         super(TestIPDeag, cls).setUpClass()
2109
2110     @classmethod
2111     def tearDownClass(cls):
2112         super(TestIPDeag, cls).tearDownClass()
2113
2114     def setUp(self):
2115         super(TestIPDeag, self).setUp()
2116
2117         self.create_pg_interfaces(range(3))
2118
2119         for i in self.pg_interfaces:
2120             i.admin_up()
2121             i.config_ip6()
2122             i.resolve_ndp()
2123
2124     def tearDown(self):
2125         super(TestIPDeag, self).tearDown()
2126         for i in self.pg_interfaces:
2127             i.unconfig_ip6()
2128             i.admin_down()
2129
2130     def test_ip_deag(self):
2131         """ IP Deag Routes """
2132
2133         #
2134         # Create a table to be used for:
2135         #  1 - another destination address lookup
2136         #  2 - a source address lookup
2137         #
2138         table_dst = VppIpTable(self, 1, is_ip6=1)
2139         table_src = VppIpTable(self, 2, is_ip6=1)
2140         table_dst.add_vpp_config()
2141         table_src.add_vpp_config()
2142
2143         #
2144         # Add a route in the default table to point to a deag/
2145         # second lookup in each of these tables
2146         #
2147         route_to_dst = VppIpRoute(self, "1::1", 128,
2148                                   [VppRoutePath("::",
2149                                                 0xffffffff,
2150                                                 nh_table_id=1,
2151                                                 proto=DpoProto.DPO_PROTO_IP6)],
2152                                   is_ip6=1)
2153         route_to_src = VppIpRoute(self, "1::2", 128,
2154                                   [VppRoutePath("::",
2155                                                 0xffffffff,
2156                                                 nh_table_id=2,
2157                                                 is_source_lookup=1,
2158                                                 proto=DpoProto.DPO_PROTO_IP6)],
2159                                   is_ip6=1)
2160         route_to_dst.add_vpp_config()
2161         route_to_src.add_vpp_config()
2162
2163         #
2164         # packets to these destination are dropped, since they'll
2165         # hit the respective default routes in the second table
2166         #
2167         p_dst = (Ether(src=self.pg0.remote_mac,
2168                        dst=self.pg0.local_mac) /
2169                  IPv6(src="5::5", dst="1::1") /
2170                  inet6.TCP(sport=1234, dport=1234) /
2171                  Raw('\xa5' * 100))
2172         p_src = (Ether(src=self.pg0.remote_mac,
2173                        dst=self.pg0.local_mac) /
2174                  IPv6(src="2::2", dst="1::2") /
2175                  inet6.TCP(sport=1234, dport=1234) /
2176                  Raw('\xa5' * 100))
2177         pkts_dst = p_dst * 257
2178         pkts_src = p_src * 257
2179
2180         self.send_and_assert_no_replies(self.pg0, pkts_dst,
2181                                         "IP in dst table")
2182         self.send_and_assert_no_replies(self.pg0, pkts_src,
2183                                         "IP in src table")
2184
2185         #
2186         # add a route in the dst table to forward via pg1
2187         #
2188         route_in_dst = VppIpRoute(self, "1::1", 128,
2189                                   [VppRoutePath(self.pg1.remote_ip6,
2190                                                 self.pg1.sw_if_index,
2191                                                 proto=DpoProto.DPO_PROTO_IP6)],
2192                                   is_ip6=1,
2193                                   table_id=1)
2194         route_in_dst.add_vpp_config()
2195
2196         self.send_and_expect(self.pg0, pkts_dst, self.pg1)
2197
2198         #
2199         # add a route in the src table to forward via pg2
2200         #
2201         route_in_src = VppIpRoute(self, "2::2", 128,
2202                                   [VppRoutePath(self.pg2.remote_ip6,
2203                                                 self.pg2.sw_if_index,
2204                                                 proto=DpoProto.DPO_PROTO_IP6)],
2205                                   is_ip6=1,
2206                                   table_id=2)
2207         route_in_src.add_vpp_config()
2208         self.send_and_expect(self.pg0, pkts_src, self.pg2)
2209
2210         #
2211         # loop in the lookup DP
2212         #
2213         route_loop = VppIpRoute(self, "3::3", 128,
2214                                 [VppRoutePath("::",
2215                                               0xffffffff,
2216                                               proto=DpoProto.DPO_PROTO_IP6)],
2217                                 is_ip6=1)
2218         route_loop.add_vpp_config()
2219
2220         p_l = (Ether(src=self.pg0.remote_mac,
2221                      dst=self.pg0.local_mac) /
2222                IPv6(src="3::4", dst="3::3") /
2223                inet6.TCP(sport=1234, dport=1234) /
2224                Raw('\xa5' * 100))
2225
2226         self.send_and_assert_no_replies(self.pg0, p_l * 257,
2227                                         "IP lookup loop")
2228
2229
2230 class TestIP6Input(VppTestCase):
2231     """ IPv6 Input Exception Test Cases """
2232
2233     @classmethod
2234     def setUpClass(cls):
2235         super(TestIP6Input, cls).setUpClass()
2236
2237     @classmethod
2238     def tearDownClass(cls):
2239         super(TestIP6Input, cls).tearDownClass()
2240
2241     def setUp(self):
2242         super(TestIP6Input, self).setUp()
2243
2244         self.create_pg_interfaces(range(2))
2245
2246         for i in self.pg_interfaces:
2247             i.admin_up()
2248             i.config_ip6()
2249             i.resolve_ndp()
2250
2251     def tearDown(self):
2252         super(TestIP6Input, self).tearDown()
2253         for i in self.pg_interfaces:
2254             i.unconfig_ip6()
2255             i.admin_down()
2256
2257     def test_ip_input_icmp_reply(self):
2258         """ IP6 Input Exception - Return ICMP (3,0) """
2259         #
2260         # hop limit - ICMP replies
2261         #
2262         p_version = (Ether(src=self.pg0.remote_mac,
2263                            dst=self.pg0.local_mac) /
2264                      IPv6(src=self.pg0.remote_ip6,
2265                           dst=self.pg1.remote_ip6,
2266                           hlim=1) /
2267                      inet6.UDP(sport=1234, dport=1234) /
2268                      Raw('\xa5' * 100))
2269
2270         rx = self.send_and_expect(self.pg0, p_version * 65, self.pg0)
2271         rx = rx[0]
2272         icmp = rx[ICMPv6TimeExceeded]
2273
2274         # 0: "hop limit exceeded in transit",
2275         self.assertEqual((icmp.type, icmp.code), (3, 0))
2276
2277     icmpv6_data = '\x0a' * 18
2278     all_0s = "::"
2279     all_1s = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"
2280
2281     @parameterized.expand([
2282         # Name, src, dst, l4proto, msg, timeout
2283         ("src='iface',   dst='iface'", None, None,
2284          inet6.UDP(sport=1234, dport=1234), "funky version", None),
2285         ("src='All 0's', dst='iface'", all_0s, None,
2286          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2287         ("src='iface',   dst='All 0's'", None, all_0s,
2288          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2289         ("src='All 1's', dst='iface'", all_1s, None,
2290          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2291         ("src='iface',   dst='All 1's'", None, all_1s,
2292          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2293         ("src='All 1's', dst='All 1's'", all_1s, all_1s,
2294          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2295
2296     ])
2297     def test_ip_input_no_replies(self, name, src, dst, l4, msg, timeout):
2298
2299         self._testMethodDoc = 'IPv6 Input Exception - %s' % name
2300
2301         p_version = (Ether(src=self.pg0.remote_mac,
2302                            dst=self.pg0.local_mac) /
2303                      IPv6(src=src or self.pg0.remote_ip6,
2304                           dst=dst or self.pg1.remote_ip6,
2305                           version=3) /
2306                      l4 /
2307                      Raw('\xa5' * 100))
2308
2309         self.send_and_assert_no_replies(self.pg0, p_version * 65,
2310                                         remark=msg or "",
2311                                         timeout=timeout)
2312
2313
2314 if __name__ == '__main__':
2315     unittest.main(testRunner=VppTestRunner)