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