summaryrefslogtreecommitdiffstats
path: root/test
diff options
context:
space:
mode:
authorNeale Ranns <nranns@cisco.com>2016-11-15 09:46:51 +0000
committerDamjan Marion <dmarion.lists@gmail.com>2016-11-22 21:26:55 +0000
commit177bbdcd8fa4e7621c5bdd3afd8c6e74b603e096 (patch)
treecf234b5bf8d79dac6a43570a903a11de44e26497 /test
parent7afe9e38269a30682a5e392b0e876e18d1465c31 (diff)
GRE tests and fixes
Change-Id: I234240e9bdd4b69ad64a17b1449ae1e81c0edaca Signed-off-by: Neale Ranns <nranns@cisco.com>
Diffstat (limited to 'test')
-rw-r--r--test/Makefile30
-rw-r--r--test/framework.py2
-rw-r--r--test/patches/scapy-2.3.3/gre-layers.patch25
-rw-r--r--test/test_gre.py700
-rw-r--r--test/vpp_gre_interface.py34
-rw-r--r--test/vpp_interface.py31
-rw-r--r--test/vpp_ip_route.py46
-rw-r--r--test/vpp_papi_provider.py51
-rw-r--r--test/vpp_sub_interface.py3
9 files changed, 917 insertions, 5 deletions
diff --git a/test/Makefile b/test/Makefile
index aac637d3e5f..de6aaa7a793 100644
--- a/test/Makefile
+++ b/test/Makefile
@@ -6,23 +6,45 @@ ifndef VPP_PYTHON_PREFIX
endif
PYTHON_VENV_PATH=$(VPP_PYTHON_PREFIX)/virtualenv
-PYTHON_DEPENDS=scapy pexpect
+PYTHON_DEPENDS=scapy==2.3.3 pexpect
+SCAPY_SOURCE=$(WS_ROOT)/build-root/python/virtualenv/lib/python2.7/site-packages/
-test: wipe verify-python-path
+
+.pip-install.ok:
@virtualenv $(PYTHON_VENV_PATH)
@bash -c "source $(PYTHON_VENV_PATH)/bin/activate && pip install $(PYTHON_DEPENDS)"
+ @touch $@
+
+.pip-patch.ok: .pip-install.ok
+ @echo --- patching ---
+ for f in $(CURDIR)/patches/scapy-2.3.3/*.patch ; do \
+ echo Applying patch: $$(basename $$f) ; \
+ patch -p1 -d $(SCAPY_SOURCE) < $$f ; \
+ done
+ @touch $@
+
+.install.ok: .pip-patch.ok
@bash -c "source $(PYTHON_VENV_PATH)/bin/activate && cd $(WS_ROOT)/vpp-api/python && python setup.py install"
+ @touch $@
+
+PHONIES=.install.ok .pip-patch.ok .pip-install.ok
+.PHONY: $(PHONIES)
+
+test: reset verify-python-path .install.ok
@bash -c "source $(PYTHON_VENV_PATH)/bin/activate && python run_tests.py discover -p test_$(TEST)\"*.py\""
-retest: wipe verify-python-path
+retest: reset verify-python-path
@bash -c "source $(PYTHON_VENV_PATH)/bin/activate && python run_tests.py discover -p test_$(TEST)\"*.py\""
.PHONY: wipe doc
-wipe:
+reset:
@rm -f /dev/shm/vpp-unittest-*
@rm -rf /tmp/vpp-unittest-*
+wipe: reset
+ @rm -f $(PHONIES)
+
doc: verify-python-path
@virtualenv $(PYTHON_VENV_PATH)
@bash -c "source $(PYTHON_VENV_PATH)/bin/activate && pip install $(PYTHON_DEPENDS) sphinx"
diff --git a/test/framework.py b/test/framework.py
index 227428ef9c2..1375f076dd6 100644
--- a/test/framework.py
+++ b/test/framework.py
@@ -265,8 +265,8 @@ class VppTestCase(unittest.TestCase):
def tearDown(self):
""" Show various debug prints after each test """
if not self.vpp_dead:
- self.logger.info(self.vapi.ppcli("show int"))
self.logger.debug(self.vapi.cli("show trace"))
+ self.logger.info(self.vapi.ppcli("show int"))
self.logger.info(self.vapi.ppcli("show hardware"))
self.logger.info(self.vapi.ppcli("show error"))
self.logger.info(self.vapi.ppcli("show run"))
diff --git a/test/patches/scapy-2.3.3/gre-layers.patch b/test/patches/scapy-2.3.3/gre-layers.patch
new file mode 100644
index 00000000000..605a705b0f7
--- /dev/null
+++ b/test/patches/scapy-2.3.3/gre-layers.patch
@@ -0,0 +1,25 @@
+diff --git a/scapy/layers/inet6.py b/scapy/layers/inet6.py
+index 03b80ec..a7e1e0f 100644
+--- a/scapy/layers/inet6.py
++++ b/scapy/layers/inet6.py
+@@ -3722,6 +3722,7 @@ conf.l2types.register(31, IPv6)
+
+ bind_layers(Ether, IPv6, type = 0x86dd )
+ bind_layers(CookedLinux, IPv6, proto = 0x86dd )
++bind_layers(GRE, IPv6, proto = 0x86dd )
+ bind_layers(IPerror6, TCPerror, nh = socket.IPPROTO_TCP )
+ bind_layers(IPerror6, UDPerror, nh = socket.IPPROTO_UDP )
+ bind_layers(IPv6, TCP, nh = socket.IPPROTO_TCP )
+diff --git a/scapy/layers/l2.py b/scapy/layers/l2.py
+index 4f491d2..661a5da 100644
+--- a/scapy/layers/l2.py
++++ b/scapy/layers/l2.py
+@@ -628,7 +628,7 @@ bind_layers( CookedLinux, EAPOL, proto=34958)
+ bind_layers( GRE, LLC, proto=122)
+ bind_layers( GRE, Dot1Q, proto=33024)
+ bind_layers( GRE, Dot1AD, type=0x88a8)
+-bind_layers( GRE, Ether, proto=1)
++bind_layers( GRE, Ether, proto=0x6558)
+ bind_layers( GRE, ARP, proto=2054)
+ bind_layers( GRE, EAPOL, proto=34958)
+ bind_layers( GRE, GRErouting, { "routing_present" : 1 } )
diff --git a/test/test_gre.py b/test/test_gre.py
new file mode 100644
index 00000000000..b5a1e346eca
--- /dev/null
+++ b/test/test_gre.py
@@ -0,0 +1,700 @@
+#!/usr/bin/env python
+
+import unittest
+import socket
+from logging import *
+
+from framework import VppTestCase, VppTestRunner
+from vpp_sub_interface import VppSubInterface, VppDot1QSubint, VppDot1ADSubint
+from vpp_gre_interface import VppGreInterface
+from vpp_ip_route import IpRoute, IpPath
+from vpp_papi_provider import L2_VTR_OP
+
+from scapy.packet import Raw
+from scapy.layers.l2 import Ether, Dot1Q, ARP, GRE
+from scapy.layers.inet import IP, UDP
+from scapy.layers.inet6 import ICMPv6ND_NS, IPv6, UDP
+from scapy.contrib.mpls import MPLS
+from scapy.volatile import RandMAC, RandIP
+
+
+class TestGRE(VppTestCase):
+ """ GRE Test Case """
+
+ @classmethod
+ def setUpClass(cls):
+ super(TestGRE, cls).setUpClass()
+
+ def setUp(self):
+ super(TestGRE, self).setUp()
+
+ # create 2 pg interfaces - set one in a non-default table.
+ self.create_pg_interfaces(range(2))
+
+ self.pg1.set_table_ip4(1)
+ for i in self.pg_interfaces:
+ i.admin_up()
+ i.config_ip4()
+ i.resolve_arp()
+
+ def tearDown(self):
+ super(TestGRE, self).tearDown()
+
+ def create_stream_ip4(self, src_if, src_ip, dst_ip):
+ pkts = []
+ for i in range(0, 257):
+ info = self.create_packet_info(src_if.sw_if_index,
+ src_if.sw_if_index)
+ payload = self.info_to_payload(info)
+ p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
+ IP(src=src_ip, dst=dst_ip) /
+ UDP(sport=1234, dport=1234) /
+ Raw(payload))
+ info.data = p.copy()
+ pkts.append(p)
+ return pkts
+
+ def create_tunnel_stream_4o4(self, src_if,
+ tunnel_src, tunnel_dst,
+ src_ip, dst_ip):
+ pkts = []
+ for i in range(0, 257):
+ info = self.create_packet_info(src_if.sw_if_index,
+ src_if.sw_if_index)
+ payload = self.info_to_payload(info)
+ p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
+ IP(src=tunnel_src, dst=tunnel_dst) /
+ GRE() /
+ IP(src=src_ip, dst=dst_ip) /
+ UDP(sport=1234, dport=1234) /
+ Raw(payload))
+ info.data = p.copy()
+ pkts.append(p)
+ return pkts
+
+ def create_tunnel_stream_6o4(self, src_if,
+ tunnel_src, tunnel_dst,
+ src_ip, dst_ip):
+ pkts = []
+ for i in range(0, 257):
+ info = self.create_packet_info(src_if.sw_if_index,
+ src_if.sw_if_index)
+ payload = self.info_to_payload(info)
+ p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
+ IP(src=tunnel_src, dst=tunnel_dst) /
+ GRE() /
+ IPv6(src=src_ip, dst=dst_ip) /
+ UDP(sport=1234, dport=1234) /
+ Raw(payload))
+ info.data = p.copy()
+ pkts.append(p)
+ return pkts
+
+ def create_tunnel_stream_l2o4(self, src_if,
+ tunnel_src, tunnel_dst):
+ pkts = []
+ for i in range(0, 257):
+ info = self.create_packet_info(src_if.sw_if_index,
+ src_if.sw_if_index)
+ payload = self.info_to_payload(info)
+ p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
+ IP(src=tunnel_src, dst=tunnel_dst) /
+ GRE() /
+ Ether(dst=RandMAC('*:*:*:*:*:*'),
+ src=RandMAC('*:*:*:*:*:*')) /
+ IP(src=str(RandIP()), dst=str(RandIP())) /
+ UDP(sport=1234, dport=1234) /
+ Raw(payload))
+ info.data = p.copy()
+ pkts.append(p)
+ return pkts
+
+ def create_tunnel_stream_vlano4(self, src_if,
+ tunnel_src, tunnel_dst, vlan):
+ pkts = []
+ for i in range(0, 257):
+ info = self.create_packet_info(src_if.sw_if_index,
+ src_if.sw_if_index)
+ payload = self.info_to_payload(info)
+ p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
+ IP(src=tunnel_src, dst=tunnel_dst) /
+ GRE() /
+ Ether(dst=RandMAC('*:*:*:*:*:*'),
+ src=RandMAC('*:*:*:*:*:*')) /
+ Dot1Q(vlan=vlan) /
+ IP(src=str(RandIP()), dst=str(RandIP())) /
+ UDP(sport=1234, dport=1234) /
+ Raw(payload))
+ info.data = p.copy()
+ pkts.append(p)
+ return pkts
+
+ def verify_filter(self, capture, sent):
+ if not len(capture) == len(sent):
+ # filter out any IPv6 RAs from the captur
+ for p in capture:
+ if (p.haslayer(ICMPv6ND_RA)):
+ capture.remove(p)
+ return capture
+
+ def verify_tunneled_4o4(self, src_if, capture, sent,
+ tunnel_src, tunnel_dst):
+
+ capture = self.verify_filter(capture, sent)
+ self.assertEqual(len(capture), len(sent))
+
+ for i in range(len(capture)):
+ try:
+ tx = sent[i]
+ rx = capture[i]
+
+ tx_ip = tx[IP]
+ rx_ip = rx[IP]
+
+ self.assertEqual(rx_ip.src, tunnel_src)
+ self.assertEqual(rx_ip.dst, tunnel_dst)
+
+ rx_gre = rx[GRE]
+ rx_ip = rx_gre[IP]
+
+ self.assertEqual(rx_ip.src, tx_ip.src)
+ self.assertEqual(rx_ip.dst, tx_ip.dst)
+ # IP processing post pop has decremented the TTL
+ self.assertEqual(rx_ip.ttl + 1, tx_ip.ttl)
+
+ except:
+ rx.show()
+ tx.show()
+ raise
+
+ def verify_tunneled_l2o4(self, src_if, capture, sent,
+ tunnel_src, tunnel_dst):
+ capture = self.verify_filter(capture, sent)
+ self.assertEqual(len(capture), len(sent))
+
+ for i in range(len(capture)):
+ try:
+ tx = sent[i]
+ rx = capture[i]
+
+ tx_ip = tx[IP]
+ rx_ip = rx[IP]
+
+ self.assertEqual(rx_ip.src, tunnel_src)
+ self.assertEqual(rx_ip.dst, tunnel_dst)
+
+ rx_gre = rx[GRE]
+ rx_l2 = rx_gre[Ether]
+ rx_ip = rx_l2[IP]
+ tx_gre = tx[GRE]
+ tx_l2 = tx_gre[Ether]
+ tx_ip = tx_l2[IP]
+
+ self.assertEqual(rx_ip.src, tx_ip.src)
+ self.assertEqual(rx_ip.dst, tx_ip.dst)
+ # bridged, not L3 forwarded, so no TTL decrement
+ self.assertEqual(rx_ip.ttl, tx_ip.ttl)
+
+ except:
+ rx.show()
+ tx.show()
+ raise
+
+ def verify_tunneled_vlano4(self, src_if, capture, sent,
+ tunnel_src, tunnel_dst, vlan):
+ try:
+ capture = self.verify_filter(capture, sent)
+ self.assertEqual(len(capture), len(sent))
+ except:
+ capture.show()
+ raise
+
+ for i in range(len(capture)):
+ try:
+ tx = sent[i]
+ rx = capture[i]
+
+ tx_ip = tx[IP]
+ rx_ip = rx[IP]
+
+ self.assertEqual(rx_ip.src, tunnel_src)
+ self.assertEqual(rx_ip.dst, tunnel_dst)
+
+ rx_gre = rx[GRE]
+ rx_l2 = rx_gre[Ether]
+ rx_vlan = rx_l2[Dot1Q]
+ rx_ip = rx_l2[IP]
+
+ self.assertEqual(rx_vlan.vlan, vlan)
+
+ tx_gre = tx[GRE]
+ tx_l2 = tx_gre[Ether]
+ tx_ip = tx_l2[IP]
+
+ self.assertEqual(rx_ip.src, tx_ip.src)
+ self.assertEqual(rx_ip.dst, tx_ip.dst)
+ # bridged, not L3 forwarded, so no TTL decrement
+ self.assertEqual(rx_ip.ttl, tx_ip.ttl)
+
+ except:
+ rx.show()
+ tx.show()
+ raise
+
+ def verify_decapped_4o4(self, src_if, capture, sent):
+ capture = self.verify_filter(capture, sent)
+ self.assertEqual(len(capture), len(sent))
+
+ for i in range(len(capture)):
+ try:
+ tx = sent[i]
+ rx = capture[i]
+
+ tx_ip = tx[IP]
+ rx_ip = rx[IP]
+ tx_gre = tx[GRE]
+ tx_ip = tx_gre[IP]
+
+ self.assertEqual(rx_ip.src, tx_ip.src)
+ self.assertEqual(rx_ip.dst, tx_ip.dst)
+ # IP processing post pop has decremented the TTL
+ self.assertEqual(rx_ip.ttl + 1, tx_ip.ttl)
+
+ except:
+ rx.show()
+ tx.show()
+ raise
+
+ def verify_decapped_6o4(self, src_if, capture, sent):
+ capture = self.verify_filter(capture, sent)
+ self.assertEqual(len(capture), len(sent))
+
+ for i in range(len(capture)):
+ try:
+ tx = sent[i]
+ rx = capture[i]
+
+ tx_ip = tx[IP]
+ rx_ip = rx[IPv6]
+ tx_gre = tx[GRE]
+ tx_ip = tx_gre[IPv6]
+
+ self.assertEqual(rx_ip.src, tx_ip.src)
+ self.assertEqual(rx_ip.dst, tx_ip.dst)
+ self.assertEqual(rx_ip.hlim + 1, tx_ip.hlim)
+
+ except:
+ rx.show()
+ tx.show()
+ raise
+
+ def test_gre(self):
+ """ GRE tunnel Tests """
+
+ #
+ # Create an L3 GRE tunnel.
+ # - set it admin up
+ # - assign an IP Addres
+ # - Add a route via the tunnel
+ #
+ gre_if = VppGreInterface(self,
+ self.pg0.local_ip4,
+ "1.1.1.2")
+ gre_if.add_vpp_config()
+
+ #
+ # The double create (create the same tunnel twice) should fail,
+ # and we should still be able to use the original
+ #
+ try:
+ gre_if.add_vpp_config()
+ except Exception:
+ pass
+ else:
+ self.fail("Double GRE tunnel add does not fail")
+
+ gre_if.admin_up()
+ gre_if.config_ip4()
+
+ route_via_tun = IpRoute(self, "4.4.4.4", 32,
+ [IpPath("0.0.0.0", gre_if.sw_if_index)])
+
+ route_via_tun.add_vpp_config()
+
+ #
+ # Send a packet stream that is routed into the tunnel
+ # - they are all dropped since the tunnel's desintation IP
+ # is unresolved - or resolves via the default route - which
+ # which is a drop.
+ #
+ tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "4.4.4.4")
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+
+ try:
+ self.assertEqual(0, len(rx))
+ except:
+ error("GRE packets forwarded without DIP resolved")
+ error(rx.show())
+ raise
+
+ #
+ # Add a route that resolves the tunnel's destination
+ #
+ route_tun_dst = IpRoute(self, "1.1.1.2", 32,
+ [IpPath(self.pg0.remote_ip4, self.pg0.sw_if_index)])
+ route_tun_dst.add_vpp_config()
+
+ #
+ # Send a packet stream that is routed into the tunnel
+ # - packets are GRE encapped
+ #
+ self.vapi.cli("clear trace")
+ tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "4.4.4.4")
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ self.verify_tunneled_4o4(self.pg0, rx, tx,
+ self.pg0.local_ip4, "1.1.1.2")
+
+ #
+ # Send tunneled packets that match the created tunnel and
+ # are decapped and forwarded
+ #
+ self.vapi.cli("clear trace")
+ tx = self.create_tunnel_stream_4o4(self.pg0,
+ "1.1.1.2",
+ self.pg0.local_ip4,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4)
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ self.verify_decapped_4o4(self.pg0, rx, tx)
+
+ #
+ # Send tunneled packets that do not match the tunnel's src
+ #
+ self.vapi.cli("clear trace")
+ tx = self.create_tunnel_stream_4o4(self.pg0,
+ "1.1.1.3",
+ self.pg0.local_ip4,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4)
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ try:
+ self.assertEqual(0, len(rx))
+ except:
+ error("GRE packets forwarded despite no SRC address match")
+ error(rx.show())
+ raise
+
+ #
+ # Configure IPv6 on the PG interface so we can route IPv6
+ # packets
+ #
+ self.pg0.config_ip6()
+ self.pg0.resolve_ndp()
+
+ #
+ # Send IPv6 tunnel encapslated packets
+ # - dropped since IPv6 is not enabled on the tunnel
+ #
+ self.vapi.cli("clear trace")
+ tx = self.create_tunnel_stream_6o4(self.pg0,
+ "1.1.1.2",
+ self.pg0.local_ip4,
+ self.pg0.local_ip6,
+ self.pg0.remote_ip6)
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ try:
+ self.assertEqual(0, len(rx))
+ except:
+ error("IPv6 GRE packets forwarded despite IPv6 not enabled on tunnel")
+ error(rx.show())
+ raise
+
+ #
+ # Enable IPv6 on the tunnel
+ #
+ gre_if.config_ip6()
+
+ #
+ # Send IPv6 tunnel encapslated packets
+ # - forwarded since IPv6 is enabled on the tunnel
+ #
+ self.vapi.cli("clear trace")
+ tx = self.create_tunnel_stream_6o4(self.pg0,
+ "1.1.1.2",
+ self.pg0.local_ip4,
+ self.pg0.local_ip6,
+ self.pg0.remote_ip6)
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ self.verify_decapped_6o4(self.pg0, rx, tx)
+
+ #
+ # test case cleanup
+ #
+ route_tun_dst.remove_vpp_config()
+ route_via_tun.remove_vpp_config()
+ gre_if.remove_vpp_config()
+
+ self.pg0.unconfig_ip6()
+
+ def test_gre_vrf(self):
+ """ GRE tunnel VRF Tests """
+
+ #
+ # Create an L3 GRE tunnel whose destination is in the non-default
+ # table. The underlay is thus non-default - the overlay is still
+ # the default.
+ # - set it admin up
+ # - assign an IP Addres
+ #
+ gre_if = VppGreInterface(self, self.pg1.local_ip4,
+ "2.2.2.2",
+ outer_fib_id=1)
+ gre_if.add_vpp_config()
+ gre_if.admin_up()
+ gre_if.config_ip4()
+
+ #
+ # Add a route via the tunnel - in the overlay
+ #
+ route_via_tun = IpRoute(self, "9.9.9.9", 32,
+ [IpPath("0.0.0.0", gre_if.sw_if_index)])
+ route_via_tun.add_vpp_config()
+
+ #
+ # Add a route that resolves the tunnel's destination - in the
+ # underlay table
+ #
+ route_tun_dst = IpRoute(self, "2.2.2.2", 32, table_id=1,
+ paths=[IpPath(self.pg1.remote_ip4,
+ self.pg1.sw_if_index)])
+ route_tun_dst.add_vpp_config()
+
+ #
+ # Send a packet stream that is routed into the tunnel
+ # packets are sent in on pg0 which is in the default table
+ # - packets are GRE encapped
+ #
+ self.vapi.cli("clear trace")
+ tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "9.9.9.9")
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg1.get_capture()
+ self.verify_tunneled_4o4(self.pg1, rx, tx,
+ self.pg1.local_ip4, "2.2.2.2")
+
+ #
+ # Send tunneled packets that match the created tunnel and
+ # are decapped and forwarded. This tests the decap lookup
+ # does not happen in the encap table
+ #
+ self.vapi.cli("clear trace")
+ tx = self.create_tunnel_stream_4o4(self.pg1,
+ "2.2.2.2",
+ self.pg1.local_ip4,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4)
+ self.pg1.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ self.verify_decapped_4o4(self.pg0, rx, tx)
+
+ #
+ # test case cleanup
+ #
+ route_tun_dst.remove_vpp_config()
+ route_via_tun.remove_vpp_config()
+ gre_if.remove_vpp_config()
+
+ def test_gre_l2(self):
+ """ GRE tunnel L2 Tests """
+
+ #
+ # Add routes to resolve the tunnel destinations
+ #
+ route_tun1_dst = IpRoute(self, "2.2.2.2", 32,
+ [IpPath(self.pg0.remote_ip4,
+ self.pg0.sw_if_index)])
+ route_tun2_dst = IpRoute(self, "2.2.2.3", 32,
+ [IpPath(self.pg0.remote_ip4,
+ self.pg0.sw_if_index)])
+
+ route_tun1_dst.add_vpp_config()
+ route_tun2_dst.add_vpp_config()
+
+ #
+ # Create 2 L2 GRE tunnels and x-connect them
+ #
+ gre_if1 = VppGreInterface(self, self.pg0.local_ip4,
+ "2.2.2.2",
+ is_teb=1)
+ gre_if2 = VppGreInterface(self, self.pg0.local_ip4,
+ "2.2.2.3",
+ is_teb=1)
+ gre_if1.add_vpp_config()
+ gre_if2.add_vpp_config()
+
+ gre_if1.admin_up()
+ gre_if2.admin_up()
+
+ self.vapi.sw_interface_set_l2_xconnect(gre_if1.sw_if_index,
+ gre_if2.sw_if_index,
+ enable=1)
+ self.vapi.sw_interface_set_l2_xconnect(gre_if2.sw_if_index,
+ gre_if1.sw_if_index,
+ enable=1)
+
+ #
+ # Send in tunnel encapped L2. expect out tunnel encapped L2
+ # in both directions
+ #
+ self.vapi.cli("clear trace")
+ tx = self.create_tunnel_stream_l2o4(self.pg0,
+ "2.2.2.2",
+ self.pg0.local_ip4)
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ self.verify_tunneled_l2o4(self.pg0, rx, tx,
+ self.pg0.local_ip4,
+ "2.2.2.3")
+
+ self.vapi.cli("clear trace")
+ tx = self.create_tunnel_stream_l2o4(self.pg0,
+ "2.2.2.3",
+ self.pg0.local_ip4)
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ self.verify_tunneled_l2o4(self.pg0, rx, tx,
+ self.pg0.local_ip4,
+ "2.2.2.2")
+
+ self.vapi.sw_interface_set_l2_xconnect(gre_if1.sw_if_index,
+ gre_if2.sw_if_index,
+ enable=0)
+ self.vapi.sw_interface_set_l2_xconnect(gre_if2.sw_if_index,
+ gre_if1.sw_if_index,
+ enable=0)
+
+ #
+ # Create a VLAN sub-interfaces on the GRE TEB interfaces
+ # then x-connect them
+ #
+ gre_if_11 = VppDot1QSubint(self, gre_if1, 11)
+ gre_if_12 = VppDot1QSubint(self, gre_if2, 12)
+
+ # gre_if_11.add_vpp_config()
+ # gre_if_12.add_vpp_config()
+
+ gre_if_11.admin_up()
+ gre_if_12.admin_up()
+
+ self.vapi.sw_interface_set_l2_xconnect(gre_if_11.sw_if_index,
+ gre_if_12.sw_if_index,
+ enable=1)
+ self.vapi.sw_interface_set_l2_xconnect(gre_if_12.sw_if_index,
+ gre_if_11.sw_if_index,
+ enable=1)
+
+ #
+ # Configure both to pop thier respective VLAN tags,
+ # so that during the x-coonect they will subsequently push
+ #
+ self.vapi.sw_interface_set_l2_tag_rewrite(gre_if_12.sw_if_index,
+ L2_VTR_OP.L2_POP_1,
+ 12)
+ self.vapi.sw_interface_set_l2_tag_rewrite(gre_if_11.sw_if_index,
+ L2_VTR_OP.L2_POP_1,
+ 11)
+
+ #
+ # Send traffic in both directiond - expect the VLAN tags to
+ # be swapped.
+ #
+ self.vapi.cli("clear trace")
+ tx = self.create_tunnel_stream_vlano4(self.pg0,
+ "2.2.2.2",
+ self.pg0.local_ip4,
+ 11)
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ self.verify_tunneled_vlano4(self.pg0, rx, tx,
+ self.pg0.local_ip4,
+ "2.2.2.3",
+ 12)
+
+ self.vapi.cli("clear trace")
+ tx = self.create_tunnel_stream_vlano4(self.pg0,
+ "2.2.2.3",
+ self.pg0.local_ip4,
+ 12)
+ self.pg0.add_stream(tx)
+
+ self.pg_enable_capture(self.pg_interfaces)
+ self.pg_start()
+
+ rx = self.pg0.get_capture()
+ self.verify_tunneled_vlano4(self.pg0, rx, tx,
+ self.pg0.local_ip4,
+ "2.2.2.2",
+ 11)
+
+ #
+ # Cleanup Test resources
+ #
+ gre_if_11.remove_vpp_config()
+ gre_if_12.remove_vpp_config()
+ gre_if1.remove_vpp_config()
+ gre_if2.remove_vpp_config()
+ route_tun1_dst.add_vpp_config()
+ route_tun2_dst.add_vpp_config()
+
+
+if __name__ == '__main__':
+ unittest.main(testRunner=VppTestRunner)
diff --git a/test/vpp_gre_interface.py b/test/vpp_gre_interface.py
new file mode 100644
index 00000000000..b6a66332a99
--- /dev/null
+++ b/test/vpp_gre_interface.py
@@ -0,0 +1,34 @@
+
+from vpp_interface import VppInterface
+import socket
+
+
+class VppGreInterface(VppInterface):
+ """
+ VPP GRE interface
+ """
+
+ def __init__(self, test, src_ip, dst_ip, outer_fib_id=0, is_teb=0):
+ """ Create VPP loopback interface """
+ self._test = test
+ self.t_src = src_ip
+ self.t_dst = dst_ip
+ self.t_outer_fib = outer_fib_id
+ self.t_is_teb = is_teb
+
+ def add_vpp_config(self):
+ s = socket.inet_pton(socket.AF_INET, self.t_src)
+ d = socket.inet_pton(socket.AF_INET, self.t_dst)
+ r = self.test.vapi.gre_tunnel_add_del(s, d,
+ outer_fib_id=self.t_outer_fib,
+ is_teb=self.t_is_teb)
+ self._sw_if_index = r.sw_if_index
+ self.post_init_setup()
+
+ def remove_vpp_config(self):
+ s = socket.inet_pton(socket.AF_INET, self.t_src)
+ d = socket.inet_pton(socket.AF_INET, self.t_dst)
+ self.unconfig()
+ r = self.test.vapi.gre_tunnel_add_del(s, d,
+ outer_fib_id=self.t_outer_fib,
+ is_add=0)
diff --git a/test/vpp_interface.py b/test/vpp_interface.py
index 30ef8ae7a0a..511cf4bc2dd 100644
--- a/test/vpp_interface.py
+++ b/test/vpp_interface.py
@@ -176,6 +176,19 @@ class VppInterface(object):
addr_len = 24
self.test.vapi.sw_interface_add_del_address(
self.sw_if_index, addr, addr_len)
+ self.has_ip4_config = True
+
+ def unconfig_ip4(self):
+ """Remove IPv4 address on the VPP interface"""
+ try:
+ if (self.has_ip4_config):
+ self.test.vapi.sw_interface_add_del_address(
+ self.sw_if_index,
+ self.local_ip4n,
+ 24, is_add=0)
+ except AttributeError:
+ self.has_ip4_config = False
+ self.has_ip4_config = False
def configure_ipv4_neighbors(self):
"""For every remote host assign neighbor's MAC to IPv4 addresses."""
@@ -190,6 +203,24 @@ class VppInterface(object):
addr_len = 64
self.test.vapi.sw_interface_add_del_address(
self.sw_if_index, addr, addr_len, is_ipv6=1)
+ self.has_ip6_config = True
+
+ def unconfig_ip6(self):
+ """Remove IPv6 address on the VPP interface"""
+ try:
+ if (self.has_ip6_config):
+ self.test.vapi.sw_interface_add_del_address(
+ self.sw_if_index,
+ self.local_ip6n,
+ 64, is_ipv6=1, is_add=0)
+ except AttributeError:
+ self.has_ip6_config = False
+ self.has_ip6_config = False
+
+ def unconfig(self):
+ """Unconfigure IPv6 and IPv4 address on the VPP interface"""
+ self.unconfig_ip4()
+ self.unconfig_ip6()
def set_table_ip4(self, table_id):
"""Set the interface in a IPv4 Table.
diff --git a/test/vpp_ip_route.py b/test/vpp_ip_route.py
new file mode 100644
index 00000000000..78e6aaa23b9
--- /dev/null
+++ b/test/vpp_ip_route.py
@@ -0,0 +1,46 @@
+"""
+ IP Routes
+
+ object abstractions for representing IP routes in VPP
+"""
+
+import socket
+
+
+class IpPath:
+
+ def __init__(self, nh_addr, nh_sw_if_index, nh_table_id=0):
+ self.nh_addr = socket.inet_pton(socket.AF_INET, nh_addr)
+ self.nh_itf = nh_sw_if_index
+ self.nh_table_id = nh_table_id
+
+
+class IpRoute:
+ """
+ IP Route
+ """
+
+ def __init__(self, test, dest_addr,
+ dest_addr_len, paths, table_id=0):
+ self._test = test
+ self.paths = paths
+ self.dest_addr = socket.inet_pton(socket.AF_INET, dest_addr)
+ self.dest_addr_len = dest_addr_len
+ self.table_id = table_id
+
+ def add_vpp_config(self):
+ for path in self.paths:
+ self._test.vapi.ip_add_del_route(self.dest_addr,
+ self.dest_addr_len,
+ path.nh_addr,
+ path.nh_itf,
+ table_id=self.table_id)
+
+ def remove_vpp_config(self):
+ for path in self.paths:
+ self._test.vapi.ip_add_del_route(self.dest_addr,
+ self.dest_addr_len,
+ path.nh_addr,
+ path.nh_itf,
+ table_id=self.table_id,
+ is_add=0)
diff --git a/test/vpp_papi_provider.py b/test/vpp_papi_provider.py
index 2148e94b2a8..23a108d9ca2 100644
--- a/test/vpp_papi_provider.py
+++ b/test/vpp_papi_provider.py
@@ -18,6 +18,9 @@ if do_import:
MPLS_IETF_MAX_LABEL = 0xfffff
MPLS_LABEL_INVALID = MPLS_IETF_MAX_LABEL + 1
+class L2_VTR_OP:
+ L2_POP_1 = 3
+
class VppPapiProvider(object):
"""VPP-api provider using vpp-papi
@@ -230,6 +233,20 @@ class VppPapiProvider(object):
return self.api(vpp_papi.sw_interface_set_l2_xconnect,
(rx_sw_if_index, tx_sw_if_index, enable))
+ def sw_interface_set_l2_tag_rewrite(self, sw_if_index, vtr_oper, push=0, tag1=0, tag2=0):
+ """L2 interface vlan tag rewrite configure request
+ :param client_index - opaque cookie to identify the sender
+ :param context - sender context, to match reply w/ request
+ :param sw_if_index - interface the operation is applied to
+ :param vtr_op - Choose from l2_vtr_op_t enum values
+ :param push_dot1q - first pushed flag dot1q id set, else dot1ad
+ :param tag1 - Needed for any push or translate vtr op
+ :param tag2 - Needed for any push 2 or translate x-2 vtr ops
+
+ """
+ return self.api(vpp_papi.l2_interface_vlan_tag_rewrite,
+ (sw_if_index, vtr_oper, push, tag1, tag2))
+
def sw_interface_set_flags(self, sw_if_index, admin_up_down,
link_up_down=0, deleted=0):
"""
@@ -278,6 +295,13 @@ class VppPapiProvider(object):
outer_vlan,
inner_vlan))
+ def delete_subif(self, sw_if_index):
+ """Delete subinterface
+
+ :param sw_if_index:
+ """
+ return self.api(vpp_papi.delete_subif, ([sw_if_index]))
+
def create_vlan_subif(self, sw_if_index, vlan):
"""
@@ -411,3 +435,30 @@ class VppPapiProvider(object):
"""
return self.api(vpp_papi.sw_interface_span_enable_disable, (sw_if_index_from, sw_if_index_to, enable ))
+
+ def gre_tunnel_add_del(self,
+ src_address,
+ dst_address,
+ outer_fib_id=0,
+ is_teb=0,
+ is_add=1,
+ is_ip6=0):
+ """ Add a GRE tunnel
+
+ :param src_address:
+ :param dst_address:
+ :param outer_fib_id: (Default value = 0)
+ :param is_add: (Default value = 1)
+ :param is_ipv6: (Default value = 0)
+ :param is_teb: (Default value = 0)
+ """
+
+ return self.api(
+ vpp_papi.gre_add_del_tunnel,
+ (is_add,
+ is_ip6,
+ is_teb,
+ src_address,
+ dst_address,
+ outer_fib_id)
+ )
diff --git a/test/vpp_sub_interface.py b/test/vpp_sub_interface.py
index b387d27b49d..027a24b2a1d 100644
--- a/test/vpp_sub_interface.py
+++ b/test/vpp_sub_interface.py
@@ -41,6 +41,9 @@ class VppSubInterface(VppPGInterface):
def add_dot1_layer(self, pkt):
pass
+ def remove_vpp_config(self):
+ self.test.vapi.delete_subif(self._sw_if_index)
+
class VppDot1QSubint(VppSubInterface):
ef='#n1933'>1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955
#!/usr/bin/env python

import socket
import unittest
import struct
import random

from framework import VppTestCase, VppTestRunner, running_extended_tests

import scapy.compat
from scapy.layers.inet import IP, TCP, UDP, ICMP
from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror
from scapy.layers.inet6 import IPv6, ICMPv6EchoRequest, ICMPv6EchoReply, \
    ICMPv6ND_NS, ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, fragment6
from scapy.layers.inet6 import ICMPv6DestUnreach, IPerror6, IPv6ExtHdrFragment
from scapy.layers.l2 import Ether, ARP, GRE
from scapy.data import IP_PROTOS
from scapy.packet import bind_layers, Raw
from util import ppp
from ipfix import IPFIX, Set, Template, Data, IPFIXDecoder
from time import sleep
from util import ip4_range
from vpp_papi import mac_pton
from syslog_rfc5424_parser import SyslogMessage, ParseError
from syslog_rfc5424_parser.constants import SyslogFacility, SyslogSeverity
from vpp_papi_provider import SYSLOG_SEVERITY
from io import BytesIO
from vpp_papi import VppEnum
from scapy.all import bind_layers, Packet, ByteEnumField, ShortField, \
    IPField, IntField, LongField, XByteField, FlagsField, FieldLenField, \
    PacketListField


# NAT HA protocol event data
class Event(Packet):
    name = "Event"
    fields_desc = [ByteEnumField("event_type", None,
                                 {1: "add", 2: "del", 3: "refresh"}),
                   ByteEnumField("protocol", None,
                                 {0: "udp", 1: "tcp", 2: "icmp"}),
                   ShortField("flags", 0),
                   IPField("in_addr", None),
                   IPField("out_addr", None),
                   ShortField("in_port", None),
                   ShortField("out_port", None),
                   IPField("eh_addr", None),
                   IPField("ehn_addr", None),
                   ShortField("eh_port", None),
                   ShortField("ehn_port", None),
                   IntField("fib_index", None),
                   IntField("total_pkts", 0),
                   LongField("total_bytes", 0)]

    def extract_padding(self, s):
        return "", s


# NAT HA protocol header
class HANATStateSync(Packet):
    name = "HA NAT state sync"
    fields_desc = [XByteField("version", 1),
                   FlagsField("flags", 0, 8, ['ACK']),
                   FieldLenField("count", None, count_of="events"),
                   IntField("sequence_number", 1),
                   IntField("thread_index", 0),
                   PacketListField("events", [], Event,
                                   count_from=lambda pkt: pkt.count)]


class MethodHolder(VppTestCase):
    """ NAT create capture and verify method holder """

    def clear_nat44(self):
        """
        Clear NAT44 configuration.
        """
        if hasattr(self, 'pg7') and hasattr(self, 'pg8'):
            # I found no elegant way to do this
            self.vapi.ip_add_del_route(
                dst_address=self.pg7.remote_ip4n,
                dst_address_length=32,
                next_hop_address=self.pg7.remote_ip4n,
                next_hop_sw_if_index=self.pg7.sw_if_index,
                is_add=0)
            self.vapi.ip_add_del_route(
                dst_address=self.pg8.remote_ip4n,
                dst_address_length=32,
                next_hop_address=self.pg8.remote_ip4n,
                next_hop_sw_if_index=self.pg8.sw_if_index,
                is_add=0)

            for intf in [self.pg7, self.pg8]:
                self.vapi.ip_neighbor_add_del(
                    intf.sw_if_index,
                    intf.remote_mac,
                    intf.remote_ip4,
                    flags=(VppEnum.vl_api_ip_neighbor_flags_t.
                           IP_API_NEIGHBOR_FLAG_STATIC),
                    is_add=0)

            if self.pg7.has_ip4_config:
                self.pg7.unconfig_ip4()

        self.vapi.nat44_forwarding_enable_disable(0)

        interfaces = self.vapi.nat44_interface_addr_dump()
        for intf in interfaces:
            self.vapi.nat44_add_del_interface_addr(intf.sw_if_index,
                                                   twice_nat=intf.twice_nat,
                                                   is_add=0)

        self.vapi.nat_ipfix_enable_disable(enable=0,
                                           src_port=self.ipfix_src_port,
                                           domain_id=self.ipfix_domain_id)
        self.ipfix_src_port = 4739
        self.ipfix_domain_id = 1

        self.vapi.syslog_set_filter(SYSLOG_SEVERITY.EMERG)

        self.vapi.nat_ha_set_listener('0.0.0.0', 0)
        self.vapi.nat_ha_set_failover('0.0.0.0', 0)

        interfaces = self.vapi.nat44_interface_dump()
        for intf in interfaces:
            if intf.is_inside > 1:
                self.vapi.nat44_interface_add_del_feature(intf.sw_if_index,
                                                          0,
                                                          is_add=0)
            self.vapi.nat44_interface_add_del_feature(intf.sw_if_index,
                                                      intf.is_inside,
                                                      is_add=0)

        interfaces = self.vapi.nat44_interface_output_feature_dump()
        for intf in interfaces:
            self.vapi.nat44_interface_add_del_output_feature(intf.sw_if_index,
                                                             intf.is_inside,
                                                             is_add=0)

        static_mappings = self.vapi.nat44_static_mapping_dump()
        for sm in static_mappings:
            self.vapi.nat44_add_del_static_mapping(
                sm.local_ip_address,
                sm.external_ip_address,
                local_port=sm.local_port,
                external_port=sm.external_port,
                addr_only=sm.addr_only,
                vrf_id=sm.vrf_id,
                protocol=sm.protocol,
                twice_nat=sm.twice_nat,
                self_twice_nat=sm.self_twice_nat,
                out2in_only=sm.out2in_only,
                tag=sm.tag,
                external_sw_if_index=sm.external_sw_if_index,
                is_add=0)

        lb_static_mappings = self.vapi.nat44_lb_static_mapping_dump()
        for lb_sm in lb_static_mappings:
            self.vapi.nat44_add_del_lb_static_mapping(
                lb_sm.external_addr,
                lb_sm.external_port,
                lb_sm.protocol,
                twice_nat=lb_sm.twice_nat,
                self_twice_nat=lb_sm.self_twice_nat,
                out2in_only=lb_sm.out2in_only,
                tag=lb_sm.tag,
                is_add=0,
                local_num=0,
                locals=[])

        identity_mappings = self.vapi.nat44_identity_mapping_dump()
        for id_m in identity_mappings:
            self.vapi.nat44_add_del_identity_mapping(
                addr_only=id_m.addr_only,
                ip=id_m.ip_address,
                port=id_m.port,
                sw_if_index=id_m.sw_if_index,
                vrf_id=id_m.vrf_id,
                protocol=id_m.protocol,
                is_add=0)

        adresses = self.vapi.nat44_address_dump()
        for addr in adresses:
            self.vapi.nat44_add_del_address_range(addr.ip_address,
                                                  addr.ip_address,
                                                  twice_nat=addr.twice_nat,
                                                  is_add=0)

        self.vapi.nat_set_reass()
        self.vapi.nat_set_reass(is_ip6=1)
        self.verify_no_nat44_user()
        self.vapi.nat_set_timeouts()
        self.vapi.nat_set_addr_and_port_alloc_alg()
        self.vapi.nat_set_mss_clamping()

    def nat44_add_static_mapping(self, local_ip, external_ip='0.0.0.0',
                                 local_port=0, external_port=0, vrf_id=0,
                                 is_add=1, external_sw_if_index=0xFFFFFFFF,
                                 proto=0, twice_nat=0, self_twice_nat=0,
                                 out2in_only=0, tag=""):
        """
        Add/delete NAT44 static mapping

        :param local_ip: Local IP address
        :param external_ip: External IP address
        :param local_port: Local port number (Optional)
        :param external_port: External port number (Optional)
        :param vrf_id: VRF ID (Default 0)
        :param is_add: 1 if add, 0 if delete (Default add)
        :param external_sw_if_index: External interface instead of IP address
        :param proto: IP protocol (Mandatory if port specified)
        :param twice_nat: 1 if translate external host address and port
        :param self_twice_nat: 1 if translate external host address and port
                               whenever external host address equals
                               local address of internal host
        :param out2in_only: if 1 rule is matching only out2in direction
        :param tag: Opaque string tag
        """
        addr_only = 1
        if local_port and external_port:
            addr_only = 0
        l_ip = socket.inet_pton(socket.AF_INET, local_ip)
        e_ip = socket.inet_pton(socket.AF_INET, external_ip)
        self.vapi.nat44_add_del_static_mapping(
            l_ip,
            e_ip,
            external_sw_if_index,
            local_port,
            external_port,
            addr_only,
            vrf_id,
            proto,
            twice_nat,
            self_twice_nat,
            out2in_only,
            tag,
            is_add)

    def nat44_add_address(self, ip, is_add=1, vrf_id=0xFFFFFFFF, twice_nat=0):
        """
        Add/delete NAT44 address

        :param ip: IP address
        :param is_add: 1 if add, 0 if delete (Default add)
        :param twice_nat: twice NAT address for extenal hosts
        """
        nat_addr = socket.inet_pton(socket.AF_INET, ip)
        self.vapi.nat44_add_del_address_range(nat_addr, nat_addr, is_add,
                                              vrf_id=vrf_id,
                                              twice_nat=twice_nat)

    def create_stream_in(self, in_if, out_if, dst_ip=None, ttl=64):
        """
        Create packet stream for inside network

        :param in_if: Inside interface
        :param out_if: Outside interface
        :param dst_ip: Destination address
        :param ttl: TTL of generated packets
        """
        if dst_ip is None:
            dst_ip = out_if.remote_ip4

        pkts = []
        # TCP
        p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
             IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) /
             TCP(sport=self.tcp_port_in, dport=20))
        pkts.append(p)

        # UDP
        p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
             IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) /
             UDP(sport=self.udp_port_in, dport=20))
        pkts.append(p)

        # ICMP
        p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
             IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) /
             ICMP(id=self.icmp_id_in, type='echo-request'))
        pkts.append(p)

        return pkts

    def compose_ip6(self, ip4, pref, plen):
        """
        Compose IPv4-embedded IPv6 addresses

        :param ip4: IPv4 address
        :param pref: IPv6 prefix
        :param plen: IPv6 prefix length
        :returns: IPv4-embedded IPv6 addresses
        """
        pref_n = list(socket.inet_pton(socket.AF_INET6, pref))
        ip4_n = list(socket.inet_pton(socket.AF_INET, ip4))
        if plen == 32:
            pref_n[4] = ip4_n[0]
            pref_n[5] = ip4_n[1]
            pref_n[6] = ip4_n[2]
            pref_n[7] = ip4_n[3]
        elif plen == 40:
            pref_n[5] = ip4_n[0]
            pref_n[6] = ip4_n[1]
            pref_n[7] = ip4_n[2]
            pref_n[9] = ip4_n[3]
        elif plen == 48:
            pref_n[6] = ip4_n[0]
            pref_n[7] = ip4_n[1]
            pref_n[9] = ip4_n[2]
            pref_n[10] = ip4_n[3]
        elif plen == 56:
            pref_n[7] = ip4_n[0]
            pref_n[9] = ip4_n[1]
            pref_n[10] = ip4_n[2]
            pref_n[11] = ip4_n[3]
        elif plen == 64:
            pref_n[9] = ip4_n[0]
            pref_n[10] = ip4_n[1]
            pref_n[11] = ip4_n[2]
            pref_n[12] = ip4_n[3]
        elif plen == 96:
            pref_n[12] = ip4_n[0]
            pref_n[13] = ip4_n[1]
            pref_n[14] = ip4_n[2]
            pref_n[15] = ip4_n[3]
        packed_pref_n = b''.join([scapy.compat.chb(x) for x in pref_n])
        return socket.inet_ntop(socket.AF_INET6, packed_pref_n)

    def extract_ip4(self, ip6, plen):
        """
        Extract IPv4 address embedded in IPv6 addresses

        :param ip6: IPv6 address
        :param plen: IPv6 prefix length
        :returns: extracted IPv4 address
        """
        ip6_n = list(socket.inet_pton(socket.AF_INET6, ip6))
        ip4_n = [None] * 4
        if plen == 32:
            ip4_n[0] = ip6_n[4]
            ip4_n[1] = ip6_n[5]
            ip4_n[2] = ip6_n[6]
            ip4_n[3] = ip6_n[7]
        elif plen == 40:
            ip4_n[0] = ip6_n[5]
            ip4_n[1] = ip6_n[6]
            ip4_n[2] = ip6_n[7]
            ip4_n[3] = ip6_n[9]
        elif plen == 48:
            ip4_n[0] = ip6_n[6]
            ip4_n[1] = ip6_n[7]
            ip4_n[2] = ip6_n[9]
            ip4_n[3] = ip6_n[10]
        elif plen == 56:
            ip4_n[0] = ip6_n[7]
            ip4_n[1] = ip6_n[9]
            ip4_n[2] = ip6_n[10]
            ip4_n[3] = ip6_n[11]
        elif plen == 64:
            ip4_n[0] = ip6_n[9]
            ip4_n[1] = ip6_n[10]
            ip4_n[2] = ip6_n[11]
            ip4_n[3] = ip6_n[12]
        elif plen == 96:
            ip4_n[0] = ip6_n[12]
            ip4_n[1] = ip6_n[13]
            ip4_n[2] = ip6_n[14]
            ip4_n[3] = ip6_n[15]
        return socket.inet_ntop(socket.AF_INET, ''.join(ip4_n))

    def create_stream_in_ip6(self, in_if, out_if, hlim=64, pref=None, plen=0):
        """
        Create IPv6 packet stream for inside network

        :param in_if: Inside interface
        :param out_if: Outside interface
        :param ttl: Hop Limit of generated packets
        :param pref: NAT64 prefix
        :param plen: NAT64 prefix length
        """
        pkts = []
        if pref is None:
            dst = ''.join(['64:ff9b::', out_if.remote_ip4])
        else:
            dst = self.compose_ip6(out_if.remote_ip4, pref, plen)

        # TCP
        p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
             IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) /
             TCP(sport=self.tcp_port_in, dport=20))
        pkts.append(p)

        # UDP
        p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
             IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) /
             UDP(sport=self.udp_port_in, dport=20))
        pkts.append(p)

        # ICMP
        p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
             IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) /
             ICMPv6EchoRequest(id=self.icmp_id_in))
        pkts.append(p)

        return pkts

    def create_stream_out(self, out_if, dst_ip=None, ttl=64,
                          use_inside_ports=False):
        """
        Create packet stream for outside network

        :param out_if: Outside interface
        :param dst_ip: Destination IP address (Default use global NAT address)
        :param ttl: TTL of generated packets
        :param use_inside_ports: Use inside NAT ports as destination ports
               instead of outside ports
        """
        if dst_ip is None:
            dst_ip = self.nat_addr
        if not use_inside_ports:
            tcp_port = self.tcp_port_out
            udp_port = self.udp_port_out
            icmp_id = self.icmp_id_out
        else:
            tcp_port = self.tcp_port_in
            udp_port = self.udp_port_in
            icmp_id = self.icmp_id_in
        pkts = []
        # TCP
        p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
             IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
             TCP(dport=tcp_port, sport=20))
        pkts.append(p)

        # UDP
        p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
             IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
             UDP(dport=udp_port, sport=20))
        pkts.append(p)

        # ICMP
        p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
             IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
             ICMP(id=icmp_id, type='echo-reply'))
        pkts.append(p)

        return pkts

    def create_stream_out_ip6(self, out_if, src_ip, dst_ip, hl=64):
        """
        Create packet stream for outside network

        :param out_if: Outside interface
        :param dst_ip: Destination IP address (Default use global NAT address)
        :param hl: HL of generated packets
        """
        pkts = []
        # TCP
        p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
             IPv6(src=src_ip, dst=dst_ip, hlim=hl) /
             TCP(dport=self.tcp_port_out, sport=20))
        pkts.append(p)

        # UDP
        p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
             IPv6(src=src_ip, dst=dst_ip, hlim=hl) /
             UDP(dport=self.udp_port_out, sport=20))
        pkts.append(p)

        # ICMP
        p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
             IPv6(src=src_ip, dst=dst_ip, hlim=hl) /
             ICMPv6EchoReply(id=self.icmp_id_out))
        pkts.append(p)

        return pkts

    def verify_capture_out(self, capture, nat_ip=None, same_port=False,
                           dst_ip=None, is_ip6=False):
        """
        Verify captured packets on outside network

        :param capture: Captured packets
        :param nat_ip: Translated IP address (Default use global NAT address)
        :param same_port: Sorce port number is not translated (Default False)
        :param dst_ip: Destination IP address (Default do not verify)
        :param is_ip6: If L3 protocol is IPv6 (Default False)
        """
        if is_ip6:
            IP46 = IPv6
            ICMP46 = ICMPv6EchoRequest
        else:
            IP46 = IP
            ICMP46 = ICMP
        if nat_ip is None:
            nat_ip = self.nat_addr
        for packet in capture:
            try:
                if not is_ip6:
                    self.assert_packet_checksums_valid(packet)
                self.assertEqual(packet[IP46].src, nat_ip)
                if dst_ip is not None:
                    self.assertEqual(packet[IP46].dst, dst_ip)
                if packet.haslayer(TCP):
                    if same_port:
                        self.assertEqual(packet[TCP].sport, self.tcp_port_in)
                    else:
                        self.assertNotEqual(
                            packet[TCP].sport, self.tcp_port_in)
                    self.tcp_port_out = packet[TCP].sport
                    self.assert_packet_checksums_valid(packet)
                elif packet.haslayer(UDP):
                    if same_port:
                        self.assertEqual(packet[UDP].sport, self.udp_port_in)
                    else:
                        self.assertNotEqual(
                            packet[UDP].sport, self.udp_port_in)
                    self.udp_port_out = packet[UDP].sport
                else:
                    if same_port:
                        self.assertEqual(packet[ICMP46].id, self.icmp_id_in)
                    else:
                        self.assertNotEqual(packet[ICMP46].id, self.icmp_id_in)
                    self.icmp_id_out = packet[ICMP46].id
                    self.assert_packet_checksums_valid(packet)
            except:
                self.logger.error(ppp("Unexpected or invalid packet "
                                      "(outside network):", packet))
                raise

    def verify_capture_out_ip6(self, capture, nat_ip, same_port=False,
                               dst_ip=None):
        """
        Verify captured packets on outside network

        :param capture: Captured packets
        :param nat_ip: Translated IP address
        :param same_port: Sorce port number is not translated (Default False)
        :param dst_ip: Destination IP address (Default do not verify)
        """
        return self.verify_capture_out(capture, nat_ip, same_port, dst_ip,
                                       True)

    def verify_capture_in(self, capture, in_if):
        """
        Verify captured packets on inside network

        :param capture: Captured packets
        :param in_if: Inside interface
        """
        for packet in capture:
            try:
                self.assert_packet_checksums_valid(packet)
                self.assertEqual(packet[IP].dst, in_if.remote_ip4)
                if packet.haslayer(TCP):
                    self.assertEqual(packet[TCP].dport, self.tcp_port_in)
                elif packet.haslayer(UDP):
                    self.assertEqual(packet[UDP].dport, self.udp_port_in)
                else:
                    self.assertEqual(packet[ICMP].id, self.icmp_id_in)
            except:
                self.logger.error(ppp("Unexpected or invalid packet "
                                      "(inside network):", packet))
                raise

    def verify_capture_in_ip6(self, capture, src_ip, dst_ip):
        """
        Verify captured IPv6 packets on inside network

        :param capture: Captured packets
        :param src_ip: Source IP
        :param dst_ip: Destination IP address
        """
        for packet in capture:
            try:
                self.assertEqual(packet[IPv6].src, src_ip)
                self.assertEqual(packet[IPv6].dst, dst_ip)
                self.assert_packet_checksums_valid(packet)
                if packet.haslayer(TCP):
                    self.assertEqual(packet[TCP].dport, self.tcp_port_in)
                elif packet.haslayer(UDP):
                    self.assertEqual(packet[UDP].dport, self.udp_port_in)
                else:
                    self.assertEqual(packet[ICMPv6EchoReply].id,
                                     self.icmp_id_in)
            except:
                self.logger.error(ppp("Unexpected or invalid packet "
                                      "(inside network):", packet))
                raise

    def verify_capture_no_translation(self, capture, ingress_if, egress_if):
        """
        Verify captured packet that don't have to be translated

        :param capture: Captured packets
        :param ingress_if: Ingress interface
        :param egress_if: Egress interface
        """
        for packet in capture:
            try:
                self.assertEqual(packet[IP].src, ingress_if.remote_ip4)
                self.assertEqual(packet[IP].dst, egress_if.remote_ip4)
                if packet.haslayer(TCP):
                    self.assertEqual(packet[TCP].sport, self.tcp_port_in)
                elif packet.haslayer(UDP):
                    self.assertEqual(packet[UDP].sport, self.udp_port_in)
                else:
                    self.assertEqual(packet[ICMP].id, self.icmp_id_in)
            except:
                self.logger.error(ppp("Unexpected or invalid packet "
                                      "(inside network):", packet))
                raise

    def verify_capture_out_with_icmp_errors(self, capture, src_ip=None,
                                            icmp_type=11):
        """
        Verify captured packets with ICMP errors on outside network

        :param capture: Captured packets
        :param src_ip: Translated IP address or IP address of VPP
                       (Default use global NAT address)
        :param icmp_type: Type of error ICMP packet
                          we are expecting (Default 11)
        """
        if src_ip is None:
            src_ip = self.nat_addr
        for packet in capture:
            try:
                self.assertEqual(packet[IP].src, src_ip)
                self.assertEqual(packet.haslayer(ICMP), 1)
                icmp = packet[ICMP]
                self.assertEqual(icmp.type, icmp_type)
                self.assertTrue(icmp.haslayer(IPerror))
                inner_ip = icmp[IPerror]
                if inner_ip.haslayer(TCPerror):
                    self.assertEqual(inner_ip[TCPerror].dport,
                                     self.tcp_port_out)
                elif inner_ip.haslayer(UDPerror):
                    self.assertEqual(inner_ip[UDPerror].dport,
                                     self.udp_port_out)
                else:
                    self.assertEqual(inner_ip[ICMPerror].id, self.icmp_id_out)
            except:
                self.logger.error(ppp("Unexpected or invalid packet "
                                      "(outside network):", packet))
                raise

    def verify_capture_in_with_icmp_errors(self, capture, in_if, icmp_type=11):
        """
        Verify captured packets with ICMP errors on inside network

        :param capture: Captured packets
        :param in_if: Inside interface
        :param icmp_type: Type of error ICMP packet
                          we are expecting (Default 11)
        """
        for packet in capture:
            try:
                self.assertEqual(packet[IP].dst, in_if.remote_ip4)
                self.assertEqual(packet.haslayer(ICMP), 1)
                icmp = packet[ICMP]
                self.assertEqual(icmp.type, icmp_type)
                self.assertTrue(icmp.haslayer(IPerror))
                inner_ip = icmp[IPerror]
                if inner_ip.haslayer(TCPerror):
                    self.assertEqual(inner_ip[TCPerror].sport,
                                     self.tcp_port_in)
                elif inner_ip.haslayer(UDPerror):
                    self.assertEqual(inner_ip[UDPerror].sport,
                                     self.udp_port_in)
                else:
                    self.assertEqual(inner_ip[ICMPerror].id, self.icmp_id_in)
            except:
                self.logger.error(ppp("Unexpected or invalid packet "
                                      "(inside network):", packet))
                raise

    def create_stream_frag(self, src_if, dst, sport, dport, data,
                           proto=IP_PROTOS.tcp, echo_reply=False):
        """
        Create fragmented packet stream

        :param src_if: Source interface
        :param dst: Destination IPv4 address
        :param sport: Source port
        :param dport: Destination port
        :param data: Payload data
        :param proto: protocol (TCP, UDP, ICMP)
        :param echo_reply: use echo_reply if protocol is ICMP
        :returns: Fragmets
        """
        if proto == IP_PROTOS.tcp:
            p = (IP(src=src_if.remote_ip4, dst=dst) /
                 TCP(sport=sport, dport=dport) /
                 Raw(data))
            p = p.__class__(scapy.compat.raw(p))
            chksum = p[TCP].chksum
            proto_header = TCP(sport=sport, dport=dport, chksum=chksum)
        elif proto == IP_PROTOS.udp:
            proto_header = UDP(sport=sport, dport=dport)
        elif proto == IP_PROTOS.icmp:
            if not echo_reply:
                proto_header = ICMP(id=sport, type='echo-request')
            else:
                proto_header = ICMP(id=sport, type='echo-reply')
        else:
            raise Exception("Unsupported protocol")
        id = random.randint(0, 65535)
        pkts = []
        if proto == IP_PROTOS.tcp:
            raw = Raw(data[0:4])
        else:
            raw = Raw(data[0:16])
        p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
             IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) /
             proto_header /
             raw)
        pkts.append(p)
        if proto == IP_PROTOS.tcp:
            raw = Raw(data[4:20])
        else:
            raw = Raw(data[16:32])
        p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
             IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id,
                proto=proto) /
             raw)
        pkts.append(p)
        if proto == IP_PROTOS.tcp:
            raw = Raw(data[20:])
        else:
            raw = Raw(data[32:])
        p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
             IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto,
                id=id) /
             raw)
        pkts.append(p)
        return pkts

    def create_stream_frag_ip6(self, src_if, dst, sport, dport, data,
                               pref=None, plen=0, frag_size=128):
        """
        Create fragmented packet stream

        :param src_if: Source interface
        :param dst: Destination IPv4 address
        :param sport: Source TCP port
        :param dport: Destination TCP port
        :param data: Payload data
        :param pref: NAT64 prefix
        :param plen: NAT64 prefix length
        :param fragsize: size of fragments
        :returns: Fragmets
        """
        if pref is None:
            dst_ip6 = ''.join(['64:ff9b::', dst])
        else:
            dst_ip6 = self.compose_ip6(dst, pref, plen)

        p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
             IPv6(src=src_if.remote_ip6, dst=dst_ip6) /
             IPv6ExtHdrFragment(id=random.randint(0, 65535)) /
             TCP(sport=sport, dport=dport) /
             Raw(data))

        return fragment6(p, frag_size)

    def reass_frags_and_verify(self, frags, src, dst):
        """
        Reassemble and verify fragmented packet

        :param frags: Captured fragments
        :param src: Source IPv4 address to verify
        :param dst: Destination IPv4 address to verify

        :returns: Reassembled IPv4 packet
        """
        buffer = BytesIO()
        for p in frags:
            self.assertEqual(p[IP].src, src)
            self.assertEqual(p[IP].dst, dst)
            self.assert_ip_checksum_valid(p)
            buffer.seek(p[IP].frag * 8)
            buffer.write(bytes(p[IP].payload))
        ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst,
                proto=frags[0][IP].proto)
        if ip.proto == IP_PROTOS.tcp:
            p = (ip / TCP(buffer.getvalue()))
            self.assert_tcp_checksum_valid(p)
        elif ip.proto == IP_PROTOS.udp:
            p = (ip / UDP(buffer.getvalue()[:8]) /
                 Raw(buffer.getvalue()[8:]))
        elif ip.proto == IP_PROTOS.icmp:
            p = (ip / ICMP(buffer.getvalue()))
        return p

    def reass_frags_and_verify_ip6(self, frags, src, dst):
        """
        Reassemble and verify fragmented packet

        :param frags: Captured fragments
        :param src: Source IPv6 address to verify
        :param dst: Destination IPv6 address to verify

        :returns: Reassembled IPv6 packet
        """
        buffer = BytesIO()
        for p in frags:
            self.assertEqual(p[IPv6].src, src)
            self.assertEqual(p[IPv6].dst, dst)
            buffer.seek(p[IPv6ExtHdrFragment].offset * 8)
            buffer.write(bytes(p[IPv6ExtHdrFragment].payload))
        ip = IPv6(src=frags[0][IPv6].src, dst=frags[0][IPv6].dst,
                  nh=frags[0][IPv6ExtHdrFragment].nh)
        if ip.nh == IP_PROTOS.tcp:
            p = (ip / TCP(buffer.getvalue()))
        elif ip.nh == IP_PROTOS.udp:
            p = (ip / UDP(buffer.getvalue()))
        self.assert_packet_checksums_valid(p)
        return p

    def initiate_tcp_session(self, in_if, out_if):
        """
        Initiates TCP session

        :param in_if: Inside interface
        :param out_if: Outside interface
        """
        try:
            # SYN packet in->out
            p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) /
                 IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) /
                 TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                     flags="S"))
            in_if.add_stream(p)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = out_if.get_capture(1)
            p = capture[0]
            self.tcp_port_out = p[TCP].sport

            # SYN + ACK packet out->in
            p = (Ether(src=out_if.remote_mac, dst=out_if.local_mac) /
                 IP(src=out_if.remote_ip4, dst=self.nat_addr) /
                 TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                     flags="SA"))
            out_if.add_stream(p)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            in_if.get_capture(1)

            # ACK packet in->out
            p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) /
                 IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) /
                 TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                     flags="A"))
            in_if.add_stream(p)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            out_if.get_capture(1)

        except:
            self.logger.error("TCP 3 way handshake failed")
            raise

    def verify_ipfix_nat44_ses(self, data):
        """
        Verify IPFIX NAT44 session create/delete event

        :param data: Decoded IPFIX data records
        """
        nat44_ses_create_num = 0
        nat44_ses_delete_num = 0
        self.assertEqual(6, len(data))
        for record in data:
            # natEvent
            self.assertIn(scapy.compat.orb(record[230]), [4, 5])
            if scapy.compat.orb(record[230]) == 4:
                nat44_ses_create_num += 1
            else:
                nat44_ses_delete_num += 1
            # sourceIPv4Address
            self.assertEqual(self.pg0.remote_ip4n, record[8])
            # postNATSourceIPv4Address
            self.assertEqual(socket.inet_pton(socket.AF_INET, self.nat_addr),
                             record[225])
            # ingressVRFID
            self.assertEqual(struct.pack("!I", 0), record[234])
            # protocolIdentifier/sourceTransportPort/postNAPTSourceTransportPort
            if IP_PROTOS.icmp == scapy.compat.orb(record[4]):
                self.assertEqual(struct.pack("!H", self.icmp_id_in), record[7])
                self.assertEqual(struct.pack("!H", self.icmp_id_out),
                                 record[227])
            elif IP_PROTOS.tcp == scapy.compat.orb(record[4]):
                self.assertEqual(struct.pack("!H", self.tcp_port_in),
                                 record[7])
                self.assertEqual(struct.pack("!H", self.tcp_port_out),
                                 record[227])
            elif IP_PROTOS.udp == scapy.compat.orb(record[4]):
                self.assertEqual(struct.pack("!H", self.udp_port_in),
                                 record[7])
                self.assertEqual(struct.pack("!H", self.udp_port_out),
                                 record[227])
            else:
                self.fail("Invalid protocol")
        self.assertEqual(3, nat44_ses_create_num)
        self.assertEqual(3, nat44_ses_delete_num)

    def verify_ipfix_addr_exhausted(self, data):
        """
        Verify IPFIX NAT addresses event

        :param data: Decoded IPFIX data records
        """
        self.assertEqual(1, len(data))
        record = data[0]
        # natEvent
        self.assertEqual(scapy.compat.orb(record[230]), 3)
        # natPoolID
        self.assertEqual(struct.pack("!I", 0), record[283])

    def verify_ipfix_max_sessions(self, data, limit):
        """
        Verify IPFIX maximum session entries exceeded event

        :param data: Decoded IPFIX data records
        :param limit: Number of maximum session entries that can be created.
        """
        self.assertEqual(1, len(data))
        record = data[0]
        # natEvent
        self.assertEqual(scapy.compat.orb(record[230]), 13)
        # natQuotaExceededEvent
        self.assertEqual(struct.pack("I", 1), record[466])
        # maxSessionEntries
        self.assertEqual(struct.pack("I", limit), record[471])

    def verify_ipfix_max_bibs(self, data, limit):
        """
        Verify IPFIX maximum BIB entries exceeded event

        :param data: Decoded IPFIX data records
        :param limit: Number of maximum BIB entries that can be created.
        """
        self.assertEqual(1, len(data))
        record = data[0]
        # natEvent
        self.assertEqual(scapy.compat.orb(record[230]), 13)
        # natQuotaExceededEvent
        self.assertEqual(struct.pack("I", 2), record[466])
        # maxBIBEntries
        self.assertEqual(struct.pack("I", limit), record[472])

    def verify_ipfix_max_fragments_ip6(self, data, limit, src_addr):
        """
        Verify IPFIX maximum IPv6 fragments pending reassembly exceeded event

        :param data: Decoded IPFIX data records
        :param limit: Number of maximum fragments pending reassembly
        :param src_addr: IPv6 source address
        """
        self.assertEqual(1, len(data))
        record = data[0]
        # natEvent
        self.assertEqual(scapy.compat.orb(record[230]), 13)
        # natQuotaExceededEvent
        self.assertEqual(struct.pack("I", 5), record[466])
        # maxFragmentsPendingReassembly
        self.assertEqual(struct.pack("I", limit), record[475])
        # sourceIPv6Address
        self.assertEqual(src_addr, record[27])

    def verify_ipfix_max_fragments_ip4(self, data, limit, src_addr):
        """
        Verify IPFIX maximum IPv4 fragments pending reassembly exceeded event

        :param data: Decoded IPFIX data records
        :param limit: Number of maximum fragments pending reassembly
        :param src_addr: IPv4 source address
        """
        self.assertEqual(1, len(data))
        record = data[0]
        # natEvent
        self.assertEqual(scapy.compat.orb(record[230]), 13)
        # natQuotaExceededEvent
        self.assertEqual(struct.pack("I", 5), record[466])
        # maxFragmentsPendingReassembly
        self.assertEqual(struct.pack("I", limit), record[475])
        # sourceIPv4Address
        self.assertEqual(src_addr, record[8])

    def verify_ipfix_bib(self, data, is_create, src_addr):
        """
        Verify IPFIX NAT64 BIB create and delete events

        :param data: Decoded IPFIX data records
        :param is_create: Create event if nonzero value otherwise delete event
        :param src_addr: IPv6 source address
        """
        self.assertEqual(1, len(data))
        record = data[0]
        # natEvent
        if is_create:
            self.assertEqual(scapy.compat.orb(record[230]), 10)
        else:
            self.assertEqual(scapy.compat.orb(record[230]), 11)
        # sourceIPv6Address
        self.assertEqual(src_addr, record[27])
        # postNATSourceIPv4Address
        self.assertEqual(self.nat_addr_n, record[225])
        # protocolIdentifier
        self.assertEqual(IP_PROTOS.tcp, scapy.compat.orb(record[4]))
        # ingressVRFID
        self.assertEqual(struct.pack("!I", 0), record[234])
        # sourceTransportPort
        self.assertEqual(struct.pack("!H", self.tcp_port_in), record[7])
        # postNAPTSourceTransportPort
        self.assertEqual(struct.pack("!H", self.tcp_port_out), record[227])

    def verify_ipfix_nat64_ses(self, data, is_create, src_addr, dst_addr,
                               dst_port):
        """
        Verify IPFIX NAT64 session create and delete events

        :param data: Decoded IPFIX data records
        :param is_create: Create event if nonzero value otherwise delete event
        :param src_addr: IPv6 source address
        :param dst_addr: IPv4 destination address
        :param dst_port: destination TCP port
        """
        self.assertEqual(1, len(data))
        record = data[0]
        # natEvent
        if is_create:
            self.assertEqual(scapy.compat.orb(record[230]), 6)
        else:
            self.assertEqual(scapy.compat.orb(record[230]), 7)
        # sourceIPv6Address
        self.assertEqual(src_addr, record[27])
        # destinationIPv6Address
        self.assertEqual(socket.inet_pton(socket.AF_INET6,
                                          self.compose_ip6(dst_addr,
                                                           '64:ff9b::',
                                                           96)),
                         record[28])
        # postNATSourceIPv4Address
        self.assertEqual(self.nat_addr_n, record[225])
        # postNATDestinationIPv4Address
        self.assertEqual(socket.inet_pton(socket.AF_INET, dst_addr),
                         record[226])
        # protocolIdentifier
        self.assertEqual(IP_PROTOS.tcp, scapy.compat.orb(record[4]))
        # ingressVRFID
        self.assertEqual(struct.pack("!I", 0), record[234])
        # sourceTransportPort
        self.assertEqual(struct.pack("!H", self.tcp_port_in), record[7])
        # postNAPTSourceTransportPort
        self.assertEqual(struct.pack("!H", self.tcp_port_out), record[227])
        # destinationTransportPort
        self.assertEqual(struct.pack("!H", dst_port), record[11])
        # postNAPTDestinationTransportPort
        self.assertEqual(struct.pack("!H", dst_port), record[228])

    def verify_no_nat44_user(self):
        """ Verify that there is no NAT44 user """
        users = self.vapi.nat44_user_dump()
        self.assertEqual(len(users), 0)
        users = self.statistics.get_counter('/nat44/total-users')
        self.assertEqual(users[0][0], 0)
        sessions = self.statistics.get_counter('/nat44/total-sessions')
        self.assertEqual(sessions[0][0], 0)

    def verify_ipfix_max_entries_per_user(self, data, limit, src_addr):
        """
        Verify IPFIX maximum entries per user exceeded event

        :param data: Decoded IPFIX data records
        :param limit: Number of maximum entries per user
        :param src_addr: IPv4 source address
        """
        self.assertEqual(1, len(data))
        record = data[0]
        # natEvent
        self.assertEqual(scapy.compat.orb(record[230]), 13)
        # natQuotaExceededEvent
        self.assertEqual(struct.pack("I", 3), record[466])
        # maxEntriesPerUser
        self.assertEqual(struct.pack("I", limit), record[473])
        # sourceIPv4Address
        self.assertEqual(src_addr, record[8])

    def verify_syslog_apmap(self, data, is_add=True):
        message = data.decode('utf-8')
        try:
            message = SyslogMessage.parse(message)
        except ParseError as e:
            self.logger.error(e)
            raise
        else:
            self.assertEqual(message.severity, SyslogSeverity.info)
            self.assertEqual(message.appname, 'NAT')
            self.assertEqual(message.msgid, 'APMADD' if is_add else 'APMDEL')
            sd_params = message.sd.get('napmap')
            self.assertTrue(sd_params is not None)
            self.assertEqual(sd_params.get('IATYP'), 'IPv4')
            self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip4)
            self.assertEqual(sd_params.get('ISPORT'), "%d" % self.tcp_port_in)
            self.assertEqual(sd_params.get('XATYP'), 'IPv4')
            self.assertEqual(sd_params.get('XSADDR'), self.nat_addr)
            self.assertEqual(sd_params.get('XSPORT'), "%d" % self.tcp_port_out)
            self.assertEqual(sd_params.get('PROTO'), "%d" % IP_PROTOS.tcp)
            self.assertTrue(sd_params.get('SSUBIX') is not None)
            self.assertEqual(sd_params.get('SVLAN'), '0')

    def verify_syslog_sess(self, data, is_add=True, is_ip6=False):
        message = data.decode('utf-8')
        try:
            message = SyslogMessage.parse(message)
        except ParseError as e:
            self.logger.error(e)
            raise
        else:
            self.assertEqual(message.severity, SyslogSeverity.info)
            self.assertEqual(message.appname, 'NAT')
            self.assertEqual(message.msgid, 'SADD' if is_add else 'SDEL')
            sd_params = message.sd.get('nsess')
            self.assertTrue(sd_params is not None)
            if is_ip6:
                self.assertEqual(sd_params.get('IATYP'), 'IPv6')
                self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip6)
            else:
                self.assertEqual(sd_params.get('IATYP'), 'IPv4')
                self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip4)
                self.assertTrue(sd_params.get('SSUBIX') is not None)
            self.assertEqual(sd_params.get('ISPORT'), "%d" % self.tcp_port_in)
            self.assertEqual(sd_params.get('XATYP'), 'IPv4')
            self.assertEqual(sd_params.get('XSADDR'), self.nat_addr)
            self.assertEqual(sd_params.get('XSPORT'), "%d" % self.tcp_port_out)
            self.assertEqual(sd_params.get('PROTO'), "%d" % IP_PROTOS.tcp)
            self.assertEqual(sd_params.get('SVLAN'), '0')
            self.assertEqual(sd_params.get('XDADDR'), self.pg1.remote_ip4)
            self.assertEqual(sd_params.get('XDPORT'),
                             "%d" % self.tcp_external_port)

    def verify_mss_value(self, pkt, mss):
        """
        Verify TCP MSS value

        :param pkt:
        :param mss:
        """
        if not pkt.haslayer(IP) or not pkt.haslayer(TCP):
            raise TypeError("Not a TCP/IP packet")

        for option in pkt[TCP].options:
            if option[0] == 'MSS':
                self.assertEqual(option[1], mss)
                self.assert_tcp_checksum_valid(pkt)

    @staticmethod
    def proto2layer(proto):
        if proto == IP_PROTOS.tcp:
            return TCP
        elif proto == IP_PROTOS.udp:
            return UDP
        elif proto == IP_PROTOS.icmp:
            return ICMP
        else:
            raise Exception("Unsupported protocol")

    def frag_in_order(self, proto=IP_PROTOS.tcp, dont_translate=False):
        layer = self.proto2layer(proto)

        if proto == IP_PROTOS.tcp:
            data = b"A" * 4 + b"B" * 16 + b"C" * 3
        else:
            data = b"A" * 16 + b"B" * 16 + b"C" * 3
        self.port_in = random.randint(1025, 65535)

        reass = self.vapi.nat_reass_dump()
        reass_n_start = len(reass)

        # in2out
        pkts = self.create_stream_frag(self.pg0,
                                       self.pg1.remote_ip4,
                                       self.port_in,
                                       20,
                                       data,
                                       proto)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        frags = self.pg1.get_capture(len(pkts))
        if not dont_translate:
            p = self.reass_frags_and_verify(frags,
                                            self.nat_addr,
                                            self.pg1.remote_ip4)
        else:
            p = self.reass_frags_and_verify(frags,
                                            self.pg0.remote_ip4,
                                            self.pg1.remote_ip4)
        if proto != IP_PROTOS.icmp:
            if not dont_translate:
                self.assertEqual(p[layer].dport, 20)
                self.assertNotEqual(p[layer].sport, self.port_in)
            else:
                self.assertEqual(p[layer].sport, self.port_in)
        else:
            if not dont_translate:
                self.assertNotEqual(p[layer].id, self.port_in)
            else:
                self.assertEqual(p[layer].id, self.port_in)
        self.assertEqual(data, p[Raw].load)

        # out2in
        if not dont_translate:
            dst_addr = self.nat_addr
        else:
            dst_addr = self.pg0.remote_ip4
        if proto != IP_PROTOS.icmp:
            sport = 20
            dport = p[layer].sport
        else:
            sport = p[layer].id
            dport = 0
        pkts = self.create_stream_frag(self.pg1,
                                       dst_addr,
                                       sport,
                                       dport,
                                       data,
                                       proto,
                                       echo_reply=True)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        frags = self.pg0.get_capture(len(pkts))
        p = self.reass_frags_and_verify(frags,
                                        self.pg1.remote_ip4,
                                        self.pg0.remote_ip4)
        if proto != IP_PROTOS.icmp:
            self.assertEqual(p[layer].sport, 20)
            self.assertEqual(p[layer].dport, self.port_in)
        else:
            self.assertEqual(p[layer].id, self.port_in)
        self.assertEqual(data, p[Raw].load)

        reass = self.vapi.nat_reass_dump()
        reass_n_end = len(reass)

        self.assertEqual(reass_n_end - reass_n_start, 2)

    def frag_in_order_in_plus_out(self, proto=IP_PROTOS.tcp):
        layer = self.proto2layer(proto)

        if proto == IP_PROTOS.tcp:
            data = b"A" * 4 + b"B" * 16 + b"C" * 3
        else:
            data = b"A" * 16 + b"B" * 16 + b"C" * 3
        self.port_in = random.randint(1025, 65535)

        for i in range(2):
            reass = self.vapi.nat_reass_dump()
            reass_n_start = len(reass)

            # out2in
            pkts = self.create_stream_frag(self.pg0,
                                           self.server_out_addr,
                                           self.port_in,
                                           self.server_out_port,
                                           data,
                                           proto)
            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            frags = self.pg1.get_capture(len(pkts))
            p = self.reass_frags_and_verify(frags,
                                            self.pg0.remote_ip4,
                                            self.server_in_addr)
            if proto != IP_PROTOS.icmp:
                self.assertEqual(p[layer].sport, self.port_in)
                self.assertEqual(p[layer].dport, self.server_in_port)
            else:
                self.assertEqual(p[layer].id, self.port_in)
            self.assertEqual(data, p[Raw].load)

            # in2out
            if proto != IP_PROTOS.icmp:
                pkts = self.create_stream_frag(self.pg1,
                                               self.pg0.remote_ip4,
                                               self.server_in_port,
                                               p[layer].sport,
                                               data,
                                               proto)
            else:
                pkts = self.create_stream_frag(self.pg1,
                                               self.pg0.remote_ip4,
                                               p[layer].id,
                                               0,
                                               data,
                                               proto,
                                               echo_reply=True)
            self.pg1.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            frags = self.pg0.get_capture(len(pkts))
            p = self.reass_frags_and_verify(frags,
                                            self.server_out_addr,
                                            self.pg0.remote_ip4)
            if proto != IP_PROTOS.icmp:
                self.assertEqual(p[layer].sport, self.server_out_port)
                self.assertEqual(p[layer].dport, self.port_in)
            else:
                self.assertEqual(p[layer].id, self.port_in)
            self.assertEqual(data, p[Raw].load)

            reass = self.vapi.nat_reass_dump()
            reass_n_end = len(reass)

            self.assertEqual(reass_n_end - reass_n_start, 2)

    def reass_hairpinning(self, proto=IP_PROTOS.tcp):
        layer = self.proto2layer(proto)

        if proto == IP_PROTOS.tcp:
            data = b"A" * 4 + b"B" * 16 + b"C" * 3
        else:
            data = b"A" * 16 + b"B" * 16 + b"C" * 3

        # send packet from host to server
        pkts = self.create_stream_frag(self.pg0,
                                       self.nat_addr,
                                       self.host_in_port,
                                       self.server_out_port,
                                       data,
                                       proto)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        frags = self.pg0.get_capture(len(pkts))
        p = self.reass_frags_and_verify(frags,
                                        self.nat_addr,
                                        self.server.ip4)
        if proto != IP_PROTOS.icmp:
            self.assertNotEqual(p[layer].sport, self.host_in_port)
            self.assertEqual(p[layer].dport, self.server_in_port)
        else:
            self.assertNotEqual(p[layer].id, self.host_in_port)
        self.assertEqual(data, p[Raw].load)

    def frag_out_of_order(self, proto=IP_PROTOS.tcp, dont_translate=False):
        layer = self.proto2layer(proto)

        if proto == IP_PROTOS.tcp:
            data = b"A" * 4 + b"B" * 16 + b"C" * 3
        else:
            data = b"A" * 16 + b"B" * 16 + b"C" * 3
        self.port_in = random.randint(1025, 65535)

        for i in range(2):
            # in2out
            pkts = self.create_stream_frag(self.pg0,
                                           self.pg1.remote_ip4,
                                           self.port_in,
                                           20,
                                           data,
                                           proto)
            pkts.reverse()
            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            frags = self.pg1.get_capture(len(pkts))
            if not dont_translate:
                p = self.reass_frags_and_verify(frags,
                                                self.nat_addr,
                                                self.pg1.remote_ip4)
            else:
                p = self.reass_frags_and_verify(frags,
                                                self.pg0.remote_ip4,
                                                self.pg1.remote_ip4)
            if proto != IP_PROTOS.icmp:
                if not dont_translate:
                    self.assertEqual(p[layer].dport, 20)
                    self.assertNotEqual(p[layer].sport, self.port_in)
                else:
                    self.assertEqual(p[layer].sport, self.port_in)
            else:
                if not dont_translate:
                    self.assertNotEqual(p[layer].id, self.port_in)
                else:
                    self.assertEqual(p[layer].id, self.port_in)
            self.assertEqual(data, p[Raw].load)

            # out2in
            if not dont_translate:
                dst_addr = self.nat_addr
            else:
                dst_addr = self.pg0.remote_ip4
            if proto != IP_PROTOS.icmp:
                sport = 20
                dport = p[layer].sport
            else:
                sport = p[layer].id
                dport = 0
            pkts = self.create_stream_frag(self.pg1,
                                           dst_addr,
                                           sport,
                                           dport,
                                           data,
                                           proto,
                                           echo_reply=True)
            pkts.reverse()
            self.pg1.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            frags = self.pg0.get_capture(len(pkts))
            p = self.reass_frags_and_verify(frags,
                                            self.pg1.remote_ip4,
                                            self.pg0.remote_ip4)
            if proto != IP_PROTOS.icmp:
                self.assertEqual(p[layer].sport, 20)
                self.assertEqual(p[layer].dport, self.port_in)
            else:
                self.assertEqual(p[layer].id, self.port_in)
            self.assertEqual(data, p[Raw].load)

    def frag_out_of_order_in_plus_out(self, proto=IP_PROTOS.tcp):
        layer = self.proto2layer(proto)

        if proto == IP_PROTOS.tcp:
            data = b"A" * 4 + b"B" * 16 + b"C" * 3
        else:
            data = b"A" * 16 + b"B" * 16 + b"C" * 3
        self.port_in = random.randint(1025, 65535)

        for i in range(2):
            # out2in
            pkts = self.create_stream_frag(self.pg0,
                                           self.server_out_addr,
                                           self.port_in,
                                           self.server_out_port,
                                           data,
                                           proto)
            pkts.reverse()
            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            frags = self.pg1.get_capture(len(pkts))
            p = self.reass_frags_and_verify(frags,
                                            self.pg0.remote_ip4,
                                            self.server_in_addr)
            if proto != IP_PROTOS.icmp:
                self.assertEqual(p[layer].dport, self.server_in_port)
                self.assertEqual(p[layer].sport, self.port_in)
                self.assertEqual(p[layer].dport, self.server_in_port)
            else:
                self.assertEqual(p[layer].id, self.port_in)
            self.assertEqual(data, p[Raw].load)

            # in2out
            if proto != IP_PROTOS.icmp:
                pkts = self.create_stream_frag(self.pg1,
                                               self.pg0.remote_ip4,
                                               self.server_in_port,
                                               p[layer].sport,
                                               data,
                                               proto)
            else:
                pkts = self.create_stream_frag(self.pg1,
                                               self.pg0.remote_ip4,
                                               p[layer].id,
                                               0,
                                               data,
                                               proto,
                                               echo_reply=True)
            pkts.reverse()
            self.pg1.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            frags = self.pg0.get_capture(len(pkts))
            p = self.reass_frags_and_verify(frags,
                                            self.server_out_addr,
                                            self.pg0.remote_ip4)
            if proto != IP_PROTOS.icmp:
                self.assertEqual(p[layer].sport, self.server_out_port)
                self.assertEqual(p[layer].dport, self.port_in)
            else:
                self.assertEqual(p[layer].id, self.port_in)
            self.assertEqual(data, p[Raw].load)


class TestNAT44(MethodHolder):
    """ NAT44 Test Cases """

    @classmethod
    def setUpClass(cls):
        super(TestNAT44, cls).setUpClass()
        cls.vapi.cli("set log class nat level debug")

        try:
            cls.tcp_port_in = 6303
            cls.tcp_port_out = 6303
            cls.udp_port_in = 6304
            cls.udp_port_out = 6304
            cls.icmp_id_in = 6305
            cls.icmp_id_out = 6305
            cls.nat_addr = '10.0.0.3'
            cls.nat_addr_n = socket.inet_pton(socket.AF_INET, cls.nat_addr)
            cls.ipfix_src_port = 4739
            cls.ipfix_domain_id = 1
            cls.tcp_external_port = 80
            cls.udp_external_port = 69

            cls.create_pg_interfaces(range(10))
            cls.interfaces = list(cls.pg_interfaces[0:4])

            for i in cls.interfaces:
                i.admin_up()
                i.config_ip4()
                i.resolve_arp()

            cls.pg0.generate_remote_hosts(3)
            cls.pg0.configure_ipv4_neighbors()

            cls.pg1.generate_remote_hosts(1)
            cls.pg1.configure_ipv4_neighbors()

            cls.overlapping_interfaces = list(list(cls.pg_interfaces[4:7]))
            cls.vapi.ip_table_add_del(is_add=1, table_id=10)
            cls.vapi.ip_table_add_del(is_add=1, table_id=20)

            cls.pg4._local_ip4 = "172.16.255.1"
            cls.pg4._local_ip4n = socket.inet_pton(socket.AF_INET, i.local_ip4)
            cls.pg4._remote_hosts[0]._ip4 = "172.16.255.2"
            cls.pg4.set_table_ip4(10)
            cls.pg5._local_ip4 = "172.17.255.3"
            cls.pg5._local_ip4n = socket.inet_pton(socket.AF_INET, i.local_ip4)
            cls.pg5._remote_hosts[0]._ip4 = "172.17.255.4"
            cls.pg5.set_table_ip4(10)
            cls.pg6._local_ip4 = "172.16.255.1"
            cls.pg6._local_ip4n = socket.inet_pton(socket.AF_INET, i.local_ip4)
            cls.pg6._remote_hosts[0]._ip4 = "172.16.255.2"
            cls.pg6.set_table_ip4(20)
            for i in cls.overlapping_interfaces:
                i.config_ip4()
                i.admin_up()
                i.resolve_arp()

            cls.pg7.admin_up()
            cls.pg8.admin_up()

            cls.pg9.generate_remote_hosts(2)
            cls.pg9.config_ip4()
            ip_addr_n = socket.inet_pton(socket.AF_INET, "10.0.0.1")
            cls.vapi.sw_interface_add_del_address(
                sw_if_index=cls.pg9.sw_if_index, address=ip_addr_n,
                address_length=24)
            cls.pg9.admin_up()
            cls.pg9.resolve_arp()
            cls.pg9._remote_hosts[1]._ip4 = cls.pg9._remote_hosts[0]._ip4
            cls.pg4._remote_ip4 = cls.pg9._remote_hosts[0]._ip4 = "10.0.0.2"
            cls.pg9.resolve_arp()

        except Exception:
            super(TestNAT44, cls).tearDownClass()
            raise

    def test_dynamic(self):
        """ NAT44 dynamic translation test """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # in2out
        tcpn = self.statistics.get_counter(
            '/err/nat44-in2out-slowpath/TCP packets')
        udpn = self.statistics.get_counter(
            '/err/nat44-in2out-slowpath/UDP packets')
        icmpn = self.statistics.get_counter(
            '/err/nat44-in2out-slowpath/ICMP packets')
        totaln = self.statistics.get_counter(
            '/err/nat44-in2out-slowpath/good in2out packets processed')

        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)

        err = self.statistics.get_counter(
            '/err/nat44-in2out-slowpath/TCP packets')
        self.assertEqual(err - tcpn, 1)
        err = self.statistics.get_counter(
            '/err/nat44-in2out-slowpath/UDP packets')
        self.assertEqual(err - udpn, 1)
        err = self.statistics.get_counter(
            '/err/nat44-in2out-slowpath/ICMP packets')
        self.assertEqual(err - icmpn, 1)
        err = self.statistics.get_counter(
            '/err/nat44-in2out-slowpath/good in2out packets processed')
        self.assertEqual(err - totaln, 3)

        # out2in
        tcpn = self.statistics.get_counter('/err/nat44-out2in/TCP packets')
        udpn = self.statistics.get_counter('/err/nat44-out2in/UDP packets')
        icmpn = self.statistics.get_counter('/err/nat44-out2in/ICMP packets')
        totaln = self.statistics.get_counter(
            '/err/nat44-out2in/good out2in packets processed')

        pkts = self.create_stream_out(self.pg1)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

        err = self.statistics.get_counter('/err/nat44-out2in/TCP packets')
        self.assertEqual(err - tcpn, 1)
        err = self.statistics.get_counter('/err/nat44-out2in/UDP packets')
        self.assertEqual(err - udpn, 1)
        err = self.statistics.get_counter('/err/nat44-out2in/ICMP packets')
        self.assertEqual(err - icmpn, 1)
        err = self.statistics.get_counter(
            '/err/nat44-out2in/good out2in packets processed')
        self.assertEqual(err - totaln, 3)

        users = self.statistics.get_counter('/nat44/total-users')
        self.assertEqual(users[0][0], 1)
        sessions = self.statistics.get_counter('/nat44/total-sessions')
        self.assertEqual(sessions[0][0], 3)

    def test_dynamic_icmp_errors_in2out_ttl_1(self):
        """ NAT44 handling of client packets with TTL=1 """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # Client side - generate traffic
        pkts = self.create_stream_in(self.pg0, self.pg1, ttl=1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Client side - verify ICMP type 11 packets
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in_with_icmp_errors(capture, self.pg0)

    def test_dynamic_icmp_errors_out2in_ttl_1(self):
        """ NAT44 handling of server packets with TTL=1 """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # Client side - create sessions
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Server side - generate traffic
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)
        pkts = self.create_stream_out(self.pg1, ttl=1)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Server side - verify ICMP type 11 packets
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out_with_icmp_errors(capture,
                                                 src_ip=self.pg1.local_ip4)

    def test_dynamic_icmp_errors_in2out_ttl_2(self):
        """ NAT44 handling of error responses to client packets with TTL=2 """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # Client side - generate traffic
        pkts = self.create_stream_in(self.pg0, self.pg1, ttl=2)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Server side - simulate ICMP type 11 response
        capture = self.pg1.get_capture(len(pkts))
        pkts = [Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
                IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
                ICMP(type=11) / packet[IP] for packet in capture]
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Client side - verify ICMP type 11 packets
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in_with_icmp_errors(capture, self.pg0)

    def test_dynamic_icmp_errors_out2in_ttl_2(self):
        """ NAT44 handling of error responses to server packets with TTL=2 """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # Client side - create sessions
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Server side - generate traffic
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)
        pkts = self.create_stream_out(self.pg1, ttl=2)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Client side - simulate ICMP type 11 response
        capture = self.pg0.get_capture(len(pkts))
        pkts = [Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
                ICMP(type=11) / packet[IP] for packet in capture]
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Server side - verify ICMP type 11 packets
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out_with_icmp_errors(capture)

    def test_ping_out_interface_from_outside(self):
        """ Ping NAT44 out interface from outside network """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) /
             ICMP(id=self.icmp_id_out, type='echo-request'))
        pkts = [p]
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        packet = capture[0]
        try:
            self.assertEqual(packet[IP].src, self.pg1.local_ip4)
            self.assertEqual(packet[IP].dst, self.pg1.remote_ip4)
            self.assertEqual(packet[ICMP].id, self.icmp_id_in)
            self.assertEqual(packet[ICMP].type, 0)  # echo reply
        except:
            self.logger.error(ppp("Unexpected or invalid packet "
                                  "(outside network):", packet))
            raise

    def test_ping_internal_host_from_outside(self):
        """ Ping internal host from outside network """

        self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # out2in
        pkt = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
               IP(src=self.pg1.remote_ip4, dst=self.nat_addr, ttl=64) /
               ICMP(id=self.icmp_id_out, type='echo-request'))
        self.pg1.add_stream(pkt)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        self.verify_capture_in(capture, self.pg0)
        self.assert_equal(capture[0][IP].proto, IP_PROTOS.icmp)

        # in2out
        pkt = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
               IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) /
               ICMP(id=self.icmp_id_in, type='echo-reply'))
        self.pg0.add_stream(pkt)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        self.verify_capture_out(capture, same_port=True)
        self.assert_equal(capture[0][IP].proto, IP_PROTOS.icmp)

    def test_forwarding(self):
        """ NAT44 forwarding test """

        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_forwarding_enable_disable(1)

        real_ip = self.pg0.remote_ip4n
        alias_ip = self.nat_addr_n
        self.vapi.nat44_add_del_static_mapping(local_ip=real_ip,
                                               external_ip=alias_ip)

        try:
            # static mapping match

            pkts = self.create_stream_out(self.pg1)
            self.pg1.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg0.get_capture(len(pkts))
            self.verify_capture_in(capture, self.pg0)

            pkts = self.create_stream_in(self.pg0, self.pg1)
            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg1.get_capture(len(pkts))
            self.verify_capture_out(capture, same_port=True)

            # no static mapping match

            host0 = self.pg0.remote_hosts[0]
            self.pg0.remote_hosts[0] = self.pg0.remote_hosts[1]
            try:
                pkts = self.create_stream_out(self.pg1,
                                              dst_ip=self.pg0.remote_ip4,
                                              use_inside_ports=True)
                self.pg1.add_stream(pkts)
                self.pg_enable_capture(self.pg_interfaces)
                self.pg_start()
                capture = self.pg0.get_capture(len(pkts))
                self.verify_capture_in(capture, self.pg0)

                pkts = self.create_stream_in(self.pg0, self.pg1)
                self.pg0.add_stream(pkts)
                self.pg_enable_capture(self.pg_interfaces)
                self.pg_start()
                capture = self.pg1.get_capture(len(pkts))
                self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4,
                                        same_port=True)
            finally:
                self.pg0.remote_hosts[0] = host0

        finally:
            self.vapi.nat44_forwarding_enable_disable(0)
            self.vapi.nat44_add_del_static_mapping(local_ip=real_ip,
                                                   external_ip=alias_ip,
                                                   is_add=0)

    def test_static_in(self):
        """ 1:1 NAT initialized from inside network """

        nat_ip = "10.0.0.10"
        self.tcp_port_out = 6303
        self.udp_port_out = 6304
        self.icmp_id_out = 6305

        self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        sm = self.vapi.nat44_static_mapping_dump()
        self.assertEqual(len(sm), 1)
        self.assertEqual((sm[0].tag).split(b'\0', 1)[0], b'')
        self.assertEqual(sm[0].protocol, 0)
        self.assertEqual(sm[0].local_port, 0)
        self.assertEqual(sm[0].external_port, 0)

        # in2out
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip, True)

        # out2in
        pkts = self.create_stream_out(self.pg1, nat_ip)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

    def test_static_out(self):
        """ 1:1 NAT initialized from outside network """

        nat_ip = "10.0.0.20"
        self.tcp_port_out = 6303
        self.udp_port_out = 6304
        self.icmp_id_out = 6305
        tag = b"testTAG"

        self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip, tag=tag)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        sm = self.vapi.nat44_static_mapping_dump()
        self.assertEqual(len(sm), 1)
        self.assertEqual((sm[0].tag).split(b'\0', 1)[0], tag)

        # out2in
        pkts = self.create_stream_out(self.pg1, nat_ip)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

        # in2out
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip, True)

    def test_static_with_port_in(self):
        """ 1:1 NAPT initialized from inside network """

        self.tcp_port_out = 3606
        self.udp_port_out = 3607
        self.icmp_id_out = 3608

        self.nat44_add_address(self.nat_addr)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
                                      self.tcp_port_in, self.tcp_port_out,
                                      proto=IP_PROTOS.tcp)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
                                      self.udp_port_in, self.udp_port_out,
                                      proto=IP_PROTOS.udp)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
                                      self.icmp_id_in, self.icmp_id_out,
                                      proto=IP_PROTOS.icmp)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # in2out
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # out2in
        pkts = self.create_stream_out(self.pg1)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

    def test_static_with_port_out(self):
        """ 1:1 NAPT initialized from outside network """

        self.tcp_port_out = 30606
        self.udp_port_out = 30607
        self.icmp_id_out = 30608

        self.nat44_add_address(self.nat_addr)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
                                      self.tcp_port_in, self.tcp_port_out,
                                      proto=IP_PROTOS.tcp)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
                                      self.udp_port_in, self.udp_port_out,
                                      proto=IP_PROTOS.udp)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
                                      self.icmp_id_in, self.icmp_id_out,
                                      proto=IP_PROTOS.icmp)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # out2in
        pkts = self.create_stream_out(self.pg1)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

        # in2out
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)

    def test_static_vrf_aware(self):
        """ 1:1 NAT VRF awareness """

        nat_ip1 = "10.0.0.30"
        nat_ip2 = "10.0.0.40"
        self.tcp_port_out = 6303
        self.udp_port_out = 6304
        self.icmp_id_out = 6305

        self.nat44_add_static_mapping(self.pg4.remote_ip4, nat_ip1,
                                      vrf_id=10)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip2,
                                      vrf_id=10)
        self.vapi.nat44_interface_add_del_feature(self.pg3.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg4.sw_if_index)

        # inside interface VRF match NAT44 static mapping VRF
        pkts = self.create_stream_in(self.pg4, self.pg3)
        self.pg4.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip1, True)

        # inside interface VRF don't match NAT44 static mapping VRF (packets
        # are dropped)
        pkts = self.create_stream_in(self.pg0, self.pg3)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg3.assert_nothing_captured()

    def test_dynamic_to_static(self):
        """ Switch from dynamic translation to 1:1NAT """
        nat_ip = "10.0.0.10"
        self.tcp_port_out = 6303
        self.udp_port_out = 6304
        self.icmp_id_out = 6305

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # dynamic
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # 1:1NAT
        self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip)
        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n, 0)
        self.assertEqual(len(sessions), 0)
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip, True)

    def test_identity_nat(self):
        """ Identity NAT """

        self.vapi.nat44_add_del_identity_mapping(ip=self.pg0.remote_ip4n)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) /
             TCP(sport=12345, dport=56789))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg0.remote_ip4)
            self.assertEqual(ip.src, self.pg1.remote_ip4)
            self.assertEqual(tcp.dport, 56789)
            self.assertEqual(tcp.sport, 12345)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n, 0)
        self.assertEqual(len(sessions), 0)
        self.vapi.nat44_add_del_identity_mapping(ip=self.pg0.remote_ip4n,
                                                 vrf_id=1)
        identity_mappings = self.vapi.nat44_identity_mapping_dump()
        self.assertEqual(len(identity_mappings), 2)

    def test_multiple_inside_interfaces(self):
        """ NAT44 multiple non-overlapping address space inside interfaces """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg3.sw_if_index,
                                                  is_inside=0)

        # between two NAT44 inside interfaces (no translation)
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_no_translation(capture, self.pg0, self.pg1)

        # from NAT44 inside to interface without NAT44 feature (no translation)
        pkts = self.create_stream_in(self.pg0, self.pg2)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg2.get_capture(len(pkts))
        self.verify_capture_no_translation(capture, self.pg0, self.pg2)

        # in2out 1st interface
        pkts = self.create_stream_in(self.pg0, self.pg3)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # out2in 1st interface
        pkts = self.create_stream_out(self.pg3)
        self.pg3.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

        # in2out 2nd interface
        pkts = self.create_stream_in(self.pg1, self.pg3)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # out2in 2nd interface
        pkts = self.create_stream_out(self.pg3)
        self.pg3.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg1)

    def test_inside_overlapping_interfaces(self):
        """ NAT44 multiple inside interfaces with overlapping address space """

        static_nat_ip = "10.0.0.10"
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg3.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_feature(self.pg4.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg5.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg6.sw_if_index)
        self.nat44_add_static_mapping(self.pg6.remote_ip4, static_nat_ip,
                                      vrf_id=20)

        # between NAT44 inside interfaces with same VRF (no translation)
        pkts = self.create_stream_in(self.pg4, self.pg5)
        self.pg4.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg5.get_capture(len(pkts))
        self.verify_capture_no_translation(capture, self.pg4, self.pg5)

        # between NAT44 inside interfaces with different VRF (hairpinning)
        p = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) /
             IP(src=self.pg4.remote_ip4, dst=static_nat_ip) /
             TCP(sport=1234, dport=5678))
        self.pg4.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(ip.dst, self.pg6.remote_ip4)
            self.assertNotEqual(tcp.sport, 1234)
            self.assertEqual(tcp.dport, 5678)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # in2out 1st interface
        pkts = self.create_stream_in(self.pg4, self.pg3)
        self.pg4.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # out2in 1st interface
        pkts = self.create_stream_out(self.pg3)
        self.pg3.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg4.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg4)

        # in2out 2nd interface
        pkts = self.create_stream_in(self.pg5, self.pg3)
        self.pg5.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # out2in 2nd interface
        pkts = self.create_stream_out(self.pg3)
        self.pg3.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg5.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg5)

        # pg5 session dump
        addresses = self.vapi.nat44_address_dump()
        self.assertEqual(len(addresses), 1)
        sessions = self.vapi.nat44_user_session_dump(self.pg5.remote_ip4n, 10)
        self.assertEqual(len(sessions), 3)
        for session in sessions:
            self.assertFalse(session.is_static)
            self.assertEqual(session.inside_ip_address[0:4],
                             self.pg5.remote_ip4n)
            self.assertEqual(session.outside_ip_address,
                             addresses[0].ip_address)
        self.assertEqual(sessions[0].protocol, IP_PROTOS.tcp)
        self.assertEqual(sessions[1].protocol, IP_PROTOS.udp)
        self.assertEqual(sessions[2].protocol, IP_PROTOS.icmp)
        self.assertEqual(sessions[0].inside_port, self.tcp_port_in)
        self.assertEqual(sessions[1].inside_port, self.udp_port_in)
        self.assertEqual(sessions[2].inside_port, self.icmp_id_in)
        self.assertEqual(sessions[0].outside_port, self.tcp_port_out)
        self.assertEqual(sessions[1].outside_port, self.udp_port_out)
        self.assertEqual(sessions[2].outside_port, self.icmp_id_out)

        # in2out 3rd interface
        pkts = self.create_stream_in(self.pg6, self.pg3)
        self.pg6.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(len(pkts))
        self.verify_capture_out(capture, static_nat_ip, True)

        # out2in 3rd interface
        pkts = self.create_stream_out(self.pg3, static_nat_ip)
        self.pg3.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg6)

        # general user and session dump verifications
        users = self.vapi.nat44_user_dump()
        self.assertGreaterEqual(len(users), 3)
        addresses = self.vapi.nat44_address_dump()
        self.assertEqual(len(addresses), 1)
        for user in users:
            sessions = self.vapi.nat44_user_session_dump(user.ip_address,
                                                         user.vrf_id)
            for session in sessions:
                self.assertEqual(user.ip_address, session.inside_ip_address)
                self.assertTrue(session.total_bytes > session.total_pkts > 0)
                self.assertTrue(session.protocol in
                                [IP_PROTOS.tcp, IP_PROTOS.udp,
                                 IP_PROTOS.icmp])
                self.assertFalse(session.ext_host_valid)

        # pg4 session dump
        sessions = self.vapi.nat44_user_session_dump(self.pg4.remote_ip4n, 10)
        self.assertGreaterEqual(len(sessions), 4)
        for session in sessions:
            self.assertFalse(session.is_static)
            self.assertEqual(session.inside_ip_address[0:4],
                             self.pg4.remote_ip4n)
            self.assertEqual(session.outside_ip_address,
                             addresses[0].ip_address)

        # pg6 session dump
        sessions = self.vapi.nat44_user_session_dump(self.pg6.remote_ip4n, 20)
        self.assertGreaterEqual(len(sessions), 3)
        for session in sessions:
            self.assertTrue(session.is_static)
            self.assertEqual(session.inside_ip_address[0:4],
                             self.pg6.remote_ip4n)
            self.assertEqual(session.outside_ip_address,
                             socket.inet_pton(socket.AF_INET, static_nat_ip))
            self.assertTrue(session.inside_port in
                            [self.tcp_port_in, self.udp_port_in,
                             self.icmp_id_in])

    def test_hairpinning(self):
        """ NAT44 hairpinning - 1:1 NAPT """

        host = self.pg0.remote_hosts[0]
        server = self.pg0.remote_hosts[1]
        host_in_port = 1234
        host_out_port = 0
        server_in_port = 5678
        server_out_port = 8765

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        # add static mapping for server
        self.nat44_add_static_mapping(server.ip4, self.nat_addr,
                                      server_in_port, server_out_port,
                                      proto=IP_PROTOS.tcp)

        # send packet from host to server
        p = (Ether(src=host.mac, dst=self.pg0.local_mac) /
             IP(src=host.ip4, dst=self.nat_addr) /
             TCP(sport=host_in_port, dport=server_out_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(ip.dst, server.ip4)
            self.assertNotEqual(tcp.sport, host_in_port)
            self.assertEqual(tcp.dport, server_in_port)
            self.assert_packet_checksums_valid(p)
            host_out_port = tcp.sport
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # send reply from server to host
        p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
             IP(src=server.ip4, dst=self.nat_addr) /
             TCP(sport=server_in_port, dport=host_out_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(ip.dst, host.ip4)
            self.assertEqual(tcp.sport, server_out_port)
            self.assertEqual(tcp.dport, host_in_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    def test_hairpinning2(self):
        """ NAT44 hairpinning - 1:1 NAT"""

        server1_nat_ip = "10.0.0.10"
        server2_nat_ip = "10.0.0.11"
        host = self.pg0.remote_hosts[0]
        server1 = self.pg0.remote_hosts[1]
        server2 = self.pg0.remote_hosts[2]
        server_tcp_port = 22
        server_udp_port = 20

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # add static mapping for servers
        self.nat44_add_static_mapping(server1.ip4, server1_nat_ip)
        self.nat44_add_static_mapping(server2.ip4, server2_nat_ip)

        # host to server1
        pkts = []
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=host.ip4, dst=server1_nat_ip) /
             TCP(sport=self.tcp_port_in, dport=server_tcp_port))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=host.ip4, dst=server1_nat_ip) /
             UDP(sport=self.udp_port_in, dport=server_udp_port))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=host.ip4, dst=server1_nat_ip) /
             ICMP(id=self.icmp_id_in, type='echo-request'))
        pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IP].src, self.nat_addr)
                self.assertEqual(packet[IP].dst, server1.ip4)
                if packet.haslayer(TCP):
                    self.assertNotEqual(packet[TCP].sport, self.tcp_port_in)
                    self.assertEqual(packet[TCP].dport, server_tcp_port)
                    self.tcp_port_out = packet[TCP].sport
                    self.assert_packet_checksums_valid(packet)
                elif packet.haslayer(UDP):
                    self.assertNotEqual(packet[UDP].sport, self.udp_port_in)
                    self.assertEqual(packet[UDP].dport, server_udp_port)
                    self.udp_port_out = packet[UDP].sport
                else:
                    self.assertNotEqual(packet[ICMP].id, self.icmp_id_in)
                    self.icmp_id_out = packet[ICMP].id
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

        # server1 to host
        pkts = []
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=server1.ip4, dst=self.nat_addr) /
             TCP(sport=server_tcp_port, dport=self.tcp_port_out))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=server1.ip4, dst=self.nat_addr) /
             UDP(sport=server_udp_port, dport=self.udp_port_out))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=server1.ip4, dst=self.nat_addr) /
             ICMP(id=self.icmp_id_out, type='echo-reply'))
        pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IP].src, server1_nat_ip)
                self.assertEqual(packet[IP].dst, host.ip4)
                if packet.haslayer(TCP):
                    self.assertEqual(packet[TCP].dport, self.tcp_port_in)
                    self.assertEqual(packet[TCP].sport, server_tcp_port)
                    self.assert_packet_checksums_valid(packet)
                elif packet.haslayer(UDP):
                    self.assertEqual(packet[UDP].dport, self.udp_port_in)
                    self.assertEqual(packet[UDP].sport, server_udp_port)
                else:
                    self.assertEqual(packet[ICMP].id, self.icmp_id_in)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

        # server2 to server1
        pkts = []
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=server2.ip4, dst=server1_nat_ip) /
             TCP(sport=self.tcp_port_in, dport=server_tcp_port))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=server2.ip4, dst=server1_nat_ip) /
             UDP(sport=self.udp_port_in, dport=server_udp_port))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=server2.ip4, dst=server1_nat_ip) /
             ICMP(id=self.icmp_id_in, type='echo-request'))
        pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IP].src, server2_nat_ip)
                self.assertEqual(packet[IP].dst, server1.ip4)
                if packet.haslayer(TCP):
                    self.assertEqual(packet[TCP].sport, self.tcp_port_in)
                    self.assertEqual(packet[TCP].dport, server_tcp_port)
                    self.tcp_port_out = packet[TCP].sport
                    self.assert_packet_checksums_valid(packet)
                elif packet.haslayer(UDP):
                    self.assertEqual(packet[UDP].sport, self.udp_port_in)
                    self.assertEqual(packet[UDP].dport, server_udp_port)
                    self.udp_port_out = packet[UDP].sport
                else:
                    self.assertEqual(packet[ICMP].id, self.icmp_id_in)
                    self.icmp_id_out = packet[ICMP].id
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

        # server1 to server2
        pkts = []
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=server1.ip4, dst=server2_nat_ip) /
             TCP(sport=server_tcp_port, dport=self.tcp_port_out))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=server1.ip4, dst=server2_nat_ip) /
             UDP(sport=server_udp_port, dport=self.udp_port_out))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=server1.ip4, dst=server2_nat_ip) /
             ICMP(id=self.icmp_id_out, type='echo-reply'))
        pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IP].src, server1_nat_ip)
                self.assertEqual(packet[IP].dst, server2.ip4)
                if packet.haslayer(TCP):
                    self.assertEqual(packet[TCP].dport, self.tcp_port_in)
                    self.assertEqual(packet[TCP].sport, server_tcp_port)
                    self.assert_packet_checksums_valid(packet)
                elif packet.haslayer(UDP):
                    self.assertEqual(packet[UDP].dport, self.udp_port_in)
                    self.assertEqual(packet[UDP].sport, server_udp_port)
                else:
                    self.assertEqual(packet[ICMP].id, self.icmp_id_in)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

    def test_max_translations_per_user(self):
        """ MAX translations per user - recycle the least recently used """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # get maximum number of translations per user
        nat44_config = self.vapi.nat_show_config()

        # send more than maximum number of translations per user packets
        pkts_num = nat44_config.max_translations_per_user + 5
        pkts = []
        for port in range(0, pkts_num):
            p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                 IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
                 TCP(sport=1025 + port))
            pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # verify number of translated packet
        self.pg1.get_capture(pkts_num)

        users = self.vapi.nat44_user_dump()
        for user in users:
            if user.ip_address == self.pg0.remote_ip4n:
                self.assertEqual(user.nsessions,
                                 nat44_config.max_translations_per_user)
                self.assertEqual(user.nstaticsessions, 0)

        tcp_port = 22
        self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
                                      tcp_port, tcp_port,
                                      proto=IP_PROTOS.tcp)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=tcp_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)
        users = self.vapi.nat44_user_dump()
        for user in users:
            if user.ip_address == self.pg0.remote_ip4n:
                self.assertEqual(user.nsessions,
                                 nat44_config.max_translations_per_user - 1)
                self.assertEqual(user.nstaticsessions, 1)

    def test_interface_addr(self):
        """ Acquire NAT44 addresses from interface """
        self.vapi.nat44_add_del_interface_addr(self.pg7.sw_if_index)

        # no address in NAT pool
        adresses = self.vapi.nat44_address_dump()
        self.assertEqual(0, len(adresses))

        # configure interface address and check NAT address pool
        self.pg7.config_ip4()
        adresses = self.vapi.nat44_address_dump()
        self.assertEqual(1, len(adresses))
        self.assertEqual(adresses[0].ip_address[0:4], self.pg7.local_ip4n)

        # remove interface address and check NAT address pool
        self.pg7.unconfig_ip4()
        adresses = self.vapi.nat44_address_dump()
        self.assertEqual(0, len(adresses))

    def test_interface_addr_static_mapping(self):
        """ Static mapping with addresses from interface """
        tag = b"testTAG"

        self.vapi.nat44_add_del_interface_addr(self.pg7.sw_if_index)
        self.nat44_add_static_mapping(
            '1.2.3.4',
            external_sw_if_index=self.pg7.sw_if_index,
            tag=tag)

        # static mappings with external interface
        static_mappings = self.vapi.nat44_static_mapping_dump()
        self.assertEqual(1, len(static_mappings))
        self.assertEqual(self.pg7.sw_if_index,
                         static_mappings[0].external_sw_if_index)
        self.assertEqual((static_mappings[0].tag).split(b'\0', 1)[0], tag)

        # configure interface address and check static mappings
        self.pg7.config_ip4()
        static_mappings = self.vapi.nat44_static_mapping_dump()
        self.assertEqual(2, len(static_mappings))
        resolved = False
        for sm in static_mappings:
            if sm.external_sw_if_index == 0xFFFFFFFF:
                self.assertEqual(sm.external_ip_address[0:4],
                                 self.pg7.local_ip4n)
                self.assertEqual((sm.tag).split(b'\0', 1)[0], tag)
                resolved = True
        self.assertTrue(resolved)

        # remove interface address and check static mappings
        self.pg7.unconfig_ip4()
        static_mappings = self.vapi.nat44_static_mapping_dump()
        self.assertEqual(1, len(static_mappings))
        self.assertEqual(self.pg7.sw_if_index,
                         static_mappings[0].external_sw_if_index)
        self.assertEqual((static_mappings[0].tag).split(b'\0', 1)[0], tag)

        # configure interface address again and check static mappings
        self.pg7.config_ip4()
        static_mappings = self.vapi.nat44_static_mapping_dump()
        self.assertEqual(2, len(static_mappings))
        resolved = False
        for sm in static_mappings:
            if sm.external_sw_if_index == 0xFFFFFFFF:
                self.assertEqual(sm.external_ip_address[0:4],
                                 self.pg7.local_ip4n)
                self.assertEqual((sm.tag).split(b'\0', 1)[0], tag)
                resolved = True
        self.assertTrue(resolved)

        # remove static mapping
        self.nat44_add_static_mapping(
            '1.2.3.4',
            external_sw_if_index=self.pg7.sw_if_index,
            tag=tag,
            is_add=0)
        static_mappings = self.vapi.nat44_static_mapping_dump()
        self.assertEqual(0, len(static_mappings))

    def test_interface_addr_identity_nat(self):
        """ Identity NAT with addresses from interface """

        port = 53053
        self.vapi.nat44_add_del_interface_addr(self.pg7.sw_if_index)
        self.vapi.nat44_add_del_identity_mapping(
            sw_if_index=self.pg7.sw_if_index,
            port=port,
            protocol=IP_PROTOS.tcp,
            addr_only=0)

        # identity mappings with external interface
        identity_mappings = self.vapi.nat44_identity_mapping_dump()
        self.assertEqual(1, len(identity_mappings))
        self.assertEqual(self.pg7.sw_if_index,
                         identity_mappings[0].sw_if_index)

        # configure interface address and check identity mappings
        self.pg7.config_ip4()
        identity_mappings = self.vapi.nat44_identity_mapping_dump()
        resolved = False
        self.assertEqual(2, len(identity_mappings))
        for sm in identity_mappings:
            if sm.sw_if_index == 0xFFFFFFFF:
                self.assertEqual(identity_mappings[0].ip_address,
                                 self.pg7.local_ip4n)
                self.assertEqual(port, identity_mappings[0].port)
                self.assertEqual(IP_PROTOS.tcp, identity_mappings[0].protocol)
                resolved = True
        self.assertTrue(resolved)

        # remove interface address and check identity mappings
        self.pg7.unconfig_ip4()
        identity_mappings = self.vapi.nat44_identity_mapping_dump()
        self.assertEqual(1, len(identity_mappings))
        self.assertEqual(self.pg7.sw_if_index,
                         identity_mappings[0].sw_if_index)

    def test_ipfix_nat44_sess(self):
        """ IPFIX logging NAT44 session created/delted """
        self.ipfix_domain_id = 10
        self.ipfix_src_port = 20202
        colector_port = 30303
        bind_layers(UDP, IPFIX, dport=30303)
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4n,
                                     src_address=self.pg3.local_ip4n,
                                     path_mtu=512,
                                     template_interval=10,
                                     collector_port=colector_port)
        self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
                                           src_port=self.ipfix_src_port)

        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)
        self.nat44_add_address(self.nat_addr, is_add=0)
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        capture = self.pg3.get_capture(9)
        ipfix = IPFIXDecoder()
        # first load template
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            self.assertEqual(p[IP].src, self.pg3.local_ip4)
            self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
            self.assertEqual(p[UDP].sport, self.ipfix_src_port)
            self.assertEqual(p[UDP].dport, colector_port)
            self.assertEqual(p[IPFIX].observationDomainID,
                             self.ipfix_domain_id)
            if p.haslayer(Template):
                ipfix.add_template(p.getlayer(Template))
        # verify events in data set
        for p in capture:
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                self.verify_ipfix_nat44_ses(data)

    def test_ipfix_addr_exhausted(self):
        """ IPFIX logging NAT addresses exhausted """
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4n,
                                     src_address=self.pg3.local_ip4n,
                                     path_mtu=512,
                                     template_interval=10)
        self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
                                           src_port=self.ipfix_src_port)

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=3025))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.assert_nothing_captured()
        sleep(1)
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        capture = self.pg3.get_capture(9)
        ipfix = IPFIXDecoder()
        # first load template
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            self.assertEqual(p[IP].src, self.pg3.local_ip4)
            self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
            self.assertEqual(p[UDP].sport, self.ipfix_src_port)
            self.assertEqual(p[UDP].dport, 4739)
            self.assertEqual(p[IPFIX].observationDomainID,
                             self.ipfix_domain_id)
            if p.haslayer(Template):
                ipfix.add_template(p.getlayer(Template))
        # verify events in data set
        for p in capture:
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                self.verify_ipfix_addr_exhausted(data)

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_ipfix_max_sessions(self):
        """ IPFIX logging maximum session entries exceeded """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        nat44_config = self.vapi.nat_show_config()
        max_sessions = 10 * nat44_config.translation_buckets

        pkts = []
        for i in range(0, max_sessions):
            src = "10.10.%u.%u" % ((i & 0xFF00) >> 8, i & 0xFF)
            p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                 IP(src=src, dst=self.pg1.remote_ip4) /
                 TCP(sport=1025))
            pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        self.pg1.get_capture(max_sessions)
        self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4n,
                                     src_address=self.pg3.local_ip4n,
                                     path_mtu=512,
                                     template_interval=10)
        self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
                                           src_port=self.ipfix_src_port)

        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=1025))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.assert_nothing_captured()
        sleep(1)
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        capture = self.pg3.get_capture(9)
        ipfix = IPFIXDecoder()
        # first load template
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            self.assertEqual(p[IP].src, self.pg3.local_ip4)
            self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
            self.assertEqual(p[UDP].sport, self.ipfix_src_port)
            self.assertEqual(p[UDP].dport, 4739)
            self.assertEqual(p[IPFIX].observationDomainID,
                             self.ipfix_domain_id)
            if p.haslayer(Template):
                ipfix.add_template(p.getlayer(Template))
        # verify events in data set
        for p in capture:
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                self.verify_ipfix_max_sessions(data, max_sessions)

    def test_syslog_apmap(self):
        """ Test syslog address and port mapping creation and deletion """
        self.vapi.syslog_set_filter(SYSLOG_SEVERITY.INFO)
        self.vapi.syslog_set_sender(self.pg3.local_ip4n, self.pg3.remote_ip4n)
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=20))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        self.tcp_port_out = capture[0][TCP].sport
        capture = self.pg3.get_capture(1)
        self.verify_syslog_apmap(capture[0][Raw].load)

        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.nat44_add_address(self.nat_addr, is_add=0)
        capture = self.pg3.get_capture(1)
        self.verify_syslog_apmap(capture[0][Raw].load, False)

    def test_pool_addr_fib(self):
        """ NAT44 add pool addresses to FIB """
        static_addr = '10.0.0.10'
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, static_addr)

        # NAT44 address
        p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
             ARP(op=ARP.who_has, pdst=self.nat_addr,
                 psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        self.assertTrue(capture[0].haslayer(ARP))
        self.assertTrue(capture[0][ARP].op, ARP.is_at)

        # 1:1 NAT address
        p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
             ARP(op=ARP.who_has, pdst=static_addr,
                 psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        self.assertTrue(capture[0].haslayer(ARP))
        self.assertTrue(capture[0][ARP].op, ARP.is_at)

        # send ARP to non-NAT44 interface
        p = (Ether(src=self.pg2.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
             ARP(op=ARP.who_has, pdst=self.nat_addr,
                 psrc=self.pg2.remote_ip4, hwsrc=self.pg2.remote_mac))
        self.pg2.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.assert_nothing_captured()

        # remove addresses and verify
        self.nat44_add_address(self.nat_addr, is_add=0)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, static_addr,
                                      is_add=0)

        p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
             ARP(op=ARP.who_has, pdst=self.nat_addr,
                 psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.assert_nothing_captured()

        p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
             ARP(op=ARP.who_has, pdst=static_addr,
                 psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.assert_nothing_captured()

    def test_vrf_mode(self):
        """ NAT44 tenant VRF aware address pool mode """

        vrf_id1 = 1
        vrf_id2 = 2
        nat_ip1 = "10.0.0.10"
        nat_ip2 = "10.0.0.11"

        self.pg0.unconfig_ip4()
        self.pg1.unconfig_ip4()
        self.vapi.ip_table_add_del(is_add=1, table_id=vrf_id1)
        self.vapi.ip_table_add_del(is_add=1, table_id=vrf_id2)
        self.pg0.set_table_ip4(vrf_id1)
        self.pg1.set_table_ip4(vrf_id2)
        self.pg0.config_ip4()
        self.pg1.config_ip4()
        self.pg0.resolve_arp()
        self.pg1.resolve_arp()

        self.nat44_add_address(nat_ip1, vrf_id=vrf_id1)
        self.nat44_add_address(nat_ip2, vrf_id=vrf_id2)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg2.sw_if_index,
                                                  is_inside=0)

        try:
            # first VRF
            pkts = self.create_stream_in(self.pg0, self.pg2)
            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg2.get_capture(len(pkts))
            self.verify_capture_out(capture, nat_ip1)

            # second VRF
            pkts = self.create_stream_in(self.pg1, self.pg2)
            self.pg1.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg2.get_capture(len(pkts))
            self.verify_capture_out(capture, nat_ip2)

        finally:
            self.pg0.unconfig_ip4()
            self.pg1.unconfig_ip4()
            self.pg0.set_table_ip4(0)
            self.pg1.set_table_ip4(0)
            self.pg0.config_ip4()
            self.pg1.config_ip4()
            self.pg0.resolve_arp()
            self.pg1.resolve_arp()
            self.vapi.ip_table_add_del(is_add=0, table_id=vrf_id1)
            self.vapi.ip_table_add_del(is_add=0, table_id=vrf_id2)

    def test_vrf_feature_independent(self):
        """ NAT44 tenant VRF independent address pool mode """

        nat_ip1 = "10.0.0.10"
        nat_ip2 = "10.0.0.11"

        self.nat44_add_address(nat_ip1)
        self.nat44_add_address(nat_ip2, vrf_id=99)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg2.sw_if_index,
                                                  is_inside=0)

        # first VRF
        pkts = self.create_stream_in(self.pg0, self.pg2)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg2.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip1)

        # second VRF
        pkts = self.create_stream_in(self.pg1, self.pg2)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg2.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip1)

    def test_dynamic_ipless_interfaces(self):
        """ NAT44 interfaces without configured IP address """

        self.vapi.ip_neighbor_add_del(
            self.pg7.sw_if_index,
            self.pg7.remote_mac,
            self.pg7.remote_ip4,
            flags=(VppEnum.vl_api_ip_neighbor_flags_t.
                   IP_API_NEIGHBOR_FLAG_STATIC))
        self.vapi.ip_neighbor_add_del(
            self.pg8.sw_if_index,
            self.pg8.remote_mac,
            self.pg8.remote_ip4,
            flags=(VppEnum.vl_api_ip_neighbor_flags_t.
                   IP_API_NEIGHBOR_FLAG_STATIC))

        self.vapi.ip_add_del_route(dst_address=self.pg7.remote_ip4n,
                                   dst_address_length=32,
                                   next_hop_address=self.pg7.remote_ip4n,
                                   next_hop_sw_if_index=self.pg7.sw_if_index)
        self.vapi.ip_add_del_route(dst_address=self.pg8.remote_ip4n,
                                   dst_address_length=32,
                                   next_hop_address=self.pg8.remote_ip4n,
                                   next_hop_sw_if_index=self.pg8.sw_if_index)

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg7.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg8.sw_if_index,
                                                  is_inside=0)

        # in2out
        pkts = self.create_stream_in(self.pg7, self.pg8)
        self.pg7.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg8.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # out2in
        pkts = self.create_stream_out(self.pg8, self.nat_addr)
        self.pg8.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg7.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg7)

    def test_static_ipless_interfaces(self):
        """ NAT44 interfaces without configured IP address - 1:1 NAT """

        self.vapi.ip_neighbor_add_del(
            self.pg7.sw_if_index,
            self.pg7.remote_mac,
            self.pg7.remote_ip4,
            flags=(VppEnum.vl_api_ip_neighbor_flags_t.
                   IP_API_NEIGHBOR_FLAG_STATIC))
        self.vapi.ip_neighbor_add_del(
            self.pg8.sw_if_index,
            self.pg8.remote_mac,
            self.pg8.remote_ip4,
            flags=(VppEnum.vl_api_ip_neighbor_flags_t.
                   IP_API_NEIGHBOR_FLAG_STATIC))

        self.vapi.ip_add_del_route(dst_address=self.pg7.remote_ip4n,
                                   dst_address_length=32,
                                   next_hop_address=self.pg7.remote_ip4n,
                                   next_hop_sw_if_index=self.pg7.sw_if_index)
        self.vapi.ip_add_del_route(dst_address=self.pg8.remote_ip4n,
                                   dst_address_length=32,
                                   next_hop_address=self.pg8.remote_ip4n,
                                   next_hop_sw_if_index=self.pg8.sw_if_index)

        self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg7.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg8.sw_if_index,
                                                  is_inside=0)

        # out2in
        pkts = self.create_stream_out(self.pg8)
        self.pg8.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg7.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg7)

        # in2out
        pkts = self.create_stream_in(self.pg7, self.pg8)
        self.pg7.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg8.get_capture(len(pkts))
        self.verify_capture_out(capture, self.nat_addr, True)

    def test_static_with_port_ipless_interfaces(self):
        """ NAT44 interfaces without configured IP address - 1:1 NAPT """

        self.tcp_port_out = 30606
        self.udp_port_out = 30607
        self.icmp_id_out = 30608

        self.vapi.ip_neighbor_add_del(
            self.pg7.sw_if_index,
            self.pg7.remote_mac,
            self.pg7.remote_ip4,
            flags=(VppEnum.vl_api_ip_neighbor_flags_t.
                   IP_API_NEIGHBOR_FLAG_STATIC))
        self.vapi.ip_neighbor_add_del(
            self.pg8.sw_if_index,
            self.pg8.remote_mac,
            self.pg8.remote_ip4,
            flags=(VppEnum.vl_api_ip_neighbor_flags_t.
                   IP_API_NEIGHBOR_FLAG_STATIC))

        self.vapi.ip_add_del_route(dst_address=self.pg7.remote_ip4n,
                                   dst_address_length=32,
                                   next_hop_address=self.pg7.remote_ip4n,
                                   next_hop_sw_if_index=self.pg7.sw_if_index)
        self.vapi.ip_add_del_route(dst_address=self.pg8.remote_ip4n,
                                   dst_address_length=32,
                                   next_hop_address=self.pg8.remote_ip4n,
                                   next_hop_sw_if_index=self.pg8.sw_if_index)

        self.nat44_add_address(self.nat_addr)
        self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr,
                                      self.tcp_port_in, self.tcp_port_out,
                                      proto=IP_PROTOS.tcp)
        self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr,
                                      self.udp_port_in, self.udp_port_out,
                                      proto=IP_PROTOS.udp)
        self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr,
                                      self.icmp_id_in, self.icmp_id_out,
                                      proto=IP_PROTOS.icmp)
        self.vapi.nat44_interface_add_del_feature(self.pg7.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg8.sw_if_index,
                                                  is_inside=0)

        # out2in
        pkts = self.create_stream_out(self.pg8)
        self.pg8.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg7.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg7)

        # in2out
        pkts = self.create_stream_in(self.pg7, self.pg8)
        self.pg7.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg8.get_capture(len(pkts))
        self.verify_capture_out(capture)

    def test_static_unknown_proto(self):
        """ 1:1 NAT translate packet with unknown protocol """
        nat_ip = "10.0.0.10"
        self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # in2out
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             GRE() /
             IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg1.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IP].src, nat_ip)
            self.assertEqual(packet[IP].dst, self.pg1.remote_ip4)
            self.assertEqual(packet.haslayer(GRE), 1)
            self.assert_packet_checksums_valid(packet)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

        # out2in
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IP(src=self.pg1.remote_ip4, dst=nat_ip) /
             GRE() /
             IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IP].src, self.pg1.remote_ip4)
            self.assertEqual(packet[IP].dst, self.pg0.remote_ip4)
            self.assertEqual(packet.haslayer(GRE), 1)
            self.assert_packet_checksums_valid(packet)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

    def test_hairpinning_static_unknown_proto(self):
        """ 1:1 NAT translate packet with unknown protocol - hairpinning """

        host = self.pg0.remote_hosts[0]
        server = self.pg0.remote_hosts[1]

        host_nat_ip = "10.0.0.10"
        server_nat_ip = "10.0.0.11"

        self.nat44_add_static_mapping(host.ip4, host_nat_ip)
        self.nat44_add_static_mapping(server.ip4, server_nat_ip)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # host to server
        p = (Ether(dst=self.pg0.local_mac, src=host.mac) /
             IP(src=host.ip4, dst=server_nat_ip) /
             GRE() /
             IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IP].src, host_nat_ip)
            self.assertEqual(packet[IP].dst, server.ip4)
            self.assertEqual(packet.haslayer(GRE), 1)
            self.assert_packet_checksums_valid(packet)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

        # server to host
        p = (Ether(dst=self.pg0.local_mac, src=server.mac) /
             IP(src=server.ip4, dst=host_nat_ip) /
             GRE() /
             IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IP].src, server_nat_ip)
            self.assertEqual(packet[IP].dst, host.ip4)
            self.assertEqual(packet.haslayer(GRE), 1)
            self.assert_packet_checksums_valid(packet)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

    def test_output_feature(self):
        """ NAT44 interface output feature (in2out postrouting) """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_output_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_output_feature(self.pg1.sw_if_index)
        self.vapi.nat44_interface_add_del_output_feature(self.pg3.sw_if_index,
                                                         is_inside=0)

        # in2out
        pkts = self.create_stream_in(self.pg0, self.pg3)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # out2in
        pkts = self.create_stream_out(self.pg3)
        self.pg3.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

        # from non-NAT interface to NAT inside interface
        pkts = self.create_stream_in(self.pg2, self.pg0)
        self.pg2.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_no_translation(capture, self.pg2, self.pg0)

    def test_output_feature_vrf_aware(self):
        """ NAT44 interface output feature VRF aware (in2out postrouting) """
        nat_ip_vrf10 = "10.0.0.10"
        nat_ip_vrf20 = "10.0.0.20"

        self.vapi.ip_add_del_route(dst_address=self.pg3.remote_ip4n,
                                   dst_address_length=32,
                                   next_hop_address=self.pg3.remote_ip4n,
                                   next_hop_sw_if_index=self.pg3.sw_if_index,
                                   table_id=10)
        self.vapi.ip_add_del_route(dst_address=self.pg3.remote_ip4n,
                                   dst_address_length=32,
                                   next_hop_address=self.pg3.remote_ip4n,
                                   next_hop_sw_if_index=self.pg3.sw_if_index,
                                   table_id=20)

        self.nat44_add_address(nat_ip_vrf10, vrf_id=10)
        self.nat44_add_address(nat_ip_vrf20, vrf_id=20)
        self.vapi.nat44_interface_add_del_output_feature(self.pg4.sw_if_index)
        self.vapi.nat44_interface_add_del_output_feature(self.pg6.sw_if_index)
        self.vapi.nat44_interface_add_del_output_feature(self.pg3.sw_if_index,
                                                         is_inside=0)

        # in2out VRF 10
        pkts = self.create_stream_in(self.pg4, self.pg3)
        self.pg4.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip=nat_ip_vrf10)

        # out2in VRF 10
        pkts = self.create_stream_out(self.pg3, dst_ip=nat_ip_vrf10)
        self.pg3.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg4.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg4)

        # in2out VRF 20
        pkts = self.create_stream_in(self.pg6, self.pg3)
        self.pg6.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip=nat_ip_vrf20)

        # out2in VRF 20
        pkts = self.create_stream_out(self.pg3, dst_ip=nat_ip_vrf20)
        self.pg3.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg6)

    def test_output_feature_hairpinning(self):
        """ NAT44 interface output feature hairpinning (in2out postrouting) """
        host = self.pg0.remote_hosts[0]
        server = self.pg0.remote_hosts[1]
        host_in_port = 1234
        host_out_port = 0
        server_in_port = 5678
        server_out_port = 8765

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_output_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_output_feature(self.pg1.sw_if_index,
                                                         is_inside=0)

        # add static mapping for server
        self.nat44_add_static_mapping(server.ip4, self.nat_addr,
                                      server_in_port, server_out_port,
                                      proto=IP_PROTOS.tcp)

        # send packet from host to server
        p = (Ether(src=host.mac, dst=self.pg0.local_mac) /
             IP(src=host.ip4, dst=self.nat_addr) /
             TCP(sport=host_in_port, dport=server_out_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(ip.dst, server.ip4)
            self.assertNotEqual(tcp.sport, host_in_port)
            self.assertEqual(tcp.dport, server_in_port)
            self.assert_packet_checksums_valid(p)
            host_out_port = tcp.sport
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # send reply from server to host
        p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
             IP(src=server.ip4, dst=self.nat_addr) /
             TCP(sport=server_in_port, dport=host_out_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(ip.dst, host.ip4)
            self.assertEqual(tcp.sport, server_out_port)
            self.assertEqual(tcp.dport, host_in_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    def test_one_armed_nat44(self):
        """ One armed NAT44 """
        remote_host = self.pg9.remote_hosts[0]
        local_host = self.pg9.remote_hosts[1]
        external_port = 0

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg9.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg9.sw_if_index,
                                                  is_inside=0)

        # in2out
        p = (Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac) /
             IP(src=local_host.ip4, dst=remote_host.ip4) /
             TCP(sport=12345, dport=80))
        self.pg9.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg9.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(ip.dst, remote_host.ip4)
            self.assertNotEqual(tcp.sport, 12345)
            external_port = tcp.sport
            self.assertEqual(tcp.dport, 80)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # out2in
        p = (Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac) /
             IP(src=remote_host.ip4, dst=self.nat_addr) /
             TCP(sport=80, dport=external_port))
        self.pg9.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg9.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, remote_host.ip4)
            self.assertEqual(ip.dst, local_host.ip4)
            self.assertEqual(tcp.sport, 80)
            self.assertEqual(tcp.dport, 12345)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        err = self.statistics.get_counter('/err/nat44-classify/next in2out')
        self.assertEqual(err, 1)
        err = self.statistics.get_counter('/err/nat44-classify/next out2in')
        self.assertEqual(err, 1)

    def test_del_session(self):
        """ Delete NAT44 session """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(len(pkts))

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n, 0)
        nsessions = len(sessions)

        self.vapi.nat44_del_session(sessions[0].inside_ip_address,
                                    sessions[0].inside_port,
                                    sessions[0].protocol)
        self.vapi.nat44_del_session(sessions[1].outside_ip_address,
                                    sessions[1].outside_port,
                                    sessions[1].protocol,
                                    is_in=0)

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n, 0)
        self.assertEqual(nsessions - len(sessions), 2)

        self.vapi.nat44_del_session(sessions[0].inside_ip_address,
                                    sessions[0].inside_port,
                                    sessions[0].protocol)

        self.verify_no_nat44_user()

    def test_set_get_reass(self):
        """ NAT44 set/get virtual fragmentation reassembly """
        reas_cfg1 = self.vapi.nat_get_reass()

        self.vapi.nat_set_reass(timeout=reas_cfg1.ip4_timeout + 5,
                                max_reass=reas_cfg1.ip4_max_reass * 2,
                                max_frag=reas_cfg1.ip4_max_frag * 2)

        reas_cfg2 = self.vapi.nat_get_reass()

        self.assertEqual(reas_cfg1.ip4_timeout + 5, reas_cfg2.ip4_timeout)
        self.assertEqual(reas_cfg1.ip4_max_reass * 2, reas_cfg2.ip4_max_reass)
        self.assertEqual(reas_cfg1.ip4_max_frag * 2, reas_cfg2.ip4_max_frag)

        self.vapi.nat_set_reass(drop_frag=1)
        self.assertTrue(self.vapi.nat_get_reass().ip4_drop_frag)

    def test_frag_in_order(self):
        """ NAT44 translate fragments arriving in order """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        self.frag_in_order(proto=IP_PROTOS.tcp)
        self.frag_in_order(proto=IP_PROTOS.udp)
        self.frag_in_order(proto=IP_PROTOS.icmp)

    def test_frag_forwarding(self):
        """ NAT44 forwarding fragment test """
        self.vapi.nat44_add_del_interface_addr(self.pg1.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_forwarding_enable_disable(1)

        data = b"A" * 16 + b"B" * 16 + b"C" * 3
        pkts = self.create_stream_frag(self.pg1,
                                       self.pg0.remote_ip4,
                                       4789,
                                       4789,
                                       data,
                                       proto=IP_PROTOS.udp)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        frags = self.pg0.get_capture(len(pkts))
        p = self.reass_frags_and_verify(frags,
                                        self.pg1.remote_ip4,
                                        self.pg0.remote_ip4)
        self.assertEqual(p[UDP].sport, 4789)
        self.assertEqual(p[UDP].dport, 4789)
        self.assertEqual(data, p[Raw].load)

    def test_reass_hairpinning(self):
        """ NAT44 fragments hairpinning """

        self.server = self.pg0.remote_hosts[1]
        self.host_in_port = random.randint(1025, 65535)
        self.server_in_port = random.randint(1025, 65535)
        self.server_out_port = random.randint(1025, 65535)

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        # add static mapping for server
        self.nat44_add_static_mapping(self.server.ip4, self.nat_addr,
                                      self.server_in_port,
                                      self.server_out_port,
                                      proto=IP_PROTOS.tcp)
        self.nat44_add_static_mapping(self.server.ip4, self.nat_addr,
                                      self.server_in_port,
                                      self.server_out_port,
                                      proto=IP_PROTOS.udp)
        self.nat44_add_static_mapping(self.server.ip4, self.nat_addr)

        self.reass_hairpinning(proto=IP_PROTOS.tcp)
        self.reass_hairpinning(proto=IP_PROTOS.udp)
        self.reass_hairpinning(proto=IP_PROTOS.icmp)

    def test_frag_out_of_order(self):
        """ NAT44 translate fragments arriving out of order """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        self.frag_out_of_order(proto=IP_PROTOS.tcp)
        self.frag_out_of_order(proto=IP_PROTOS.udp)
        self.frag_out_of_order(proto=IP_PROTOS.icmp)

    def test_port_restricted(self):
        """ Port restricted NAT44 (MAP-E CE) """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat_set_addr_and_port_alloc_alg(alg=1,
                                                  psid_offset=6,
                                                  psid_length=6,
                                                  psid=10)

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=4567, dport=22))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg1.remote_ip4)
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(tcp.dport, 22)
            self.assertNotEqual(tcp.sport, 4567)
            self.assertEqual((tcp.sport >> 6) & 63, 10)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    def test_port_range(self):
        """ External address port range """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat_set_addr_and_port_alloc_alg(alg=2,
                                                  start_port=1025,
                                                  end_port=1027)

        pkts = []
        for port in range(0, 5):
            p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                 IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
                 TCP(sport=1125 + port))
            pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(3)
        for p in capture:
            tcp = p[TCP]
            self.assertGreaterEqual(tcp.sport, 1025)
            self.assertLessEqual(tcp.sport, 1027)

    def test_ipfix_max_frags(self):
        """ IPFIX logging maximum fragments pending reassembly exceeded """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat_set_reass(max_frag=1)
        self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4n,
                                     src_address=self.pg3.local_ip4n,
                                     path_mtu=512,
                                     template_interval=10)
        self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
                                           src_port=self.ipfix_src_port)

        data = b"A" * 4 + b"B" * 16 + b"C" * 3
        self.tcp_port_in = random.randint(1025, 65535)
        pkts = self.create_stream_frag(self.pg0,
                                       self.pg1.remote_ip4,
                                       self.tcp_port_in,
                                       20,
                                       data)
        pkts.reverse()
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.assert_nothing_captured()
        sleep(1)
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        capture = self.pg3.get_capture(9)
        ipfix = IPFIXDecoder()
        # first load template
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            self.assertEqual(p[IP].src, self.pg3.local_ip4)
            self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
            self.assertEqual(p[UDP].sport, self.ipfix_src_port)
            self.assertEqual(p[UDP].dport, 4739)
            self.assertEqual(p[IPFIX].observationDomainID,
                             self.ipfix_domain_id)
            if p.haslayer(Template):
                ipfix.add_template(p.getlayer(Template))
        # verify events in data set
        for p in capture:
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                self.verify_ipfix_max_fragments_ip4(data, 1,
                                                    self.pg0.remote_ip4n)

    def test_multiple_outside_vrf(self):
        """ Multiple outside VRF """
        vrf_id1 = 1
        vrf_id2 = 2

        self.pg1.unconfig_ip4()
        self.pg2.unconfig_ip4()
        self.vapi.ip_table_add_del(is_add=1, table_id=vrf_id1)
        self.vapi.ip_table_add_del(is_add=1, table_id=vrf_id2)
        self.pg1.set_table_ip4(vrf_id1)
        self.pg2.set_table_ip4(vrf_id2)
        self.pg1.config_ip4()
        self.pg2.config_ip4()
        self.pg1.resolve_arp()
        self.pg2.resolve_arp()

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_feature(self.pg2.sw_if_index,
                                                  is_inside=0)

        try:
            # first VRF
            pkts = self.create_stream_in(self.pg0, self.pg1)
            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg1.get_capture(len(pkts))
            self.verify_capture_out(capture, self.nat_addr)

            pkts = self.create_stream_out(self.pg1, self.nat_addr)
            self.pg1.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg0.get_capture(len(pkts))
            self.verify_capture_in(capture, self.pg0)

            self.tcp_port_in = 60303
            self.udp_port_in = 60304
            self.icmp_id_in = 60305

            # second VRF
            pkts = self.create_stream_in(self.pg0, self.pg2)
            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg2.get_capture(len(pkts))
            self.verify_capture_out(capture, self.nat_addr)

            pkts = self.create_stream_out(self.pg2, self.nat_addr)
            self.pg2.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg0.get_capture(len(pkts))
            self.verify_capture_in(capture, self.pg0)

        finally:
            self.pg1.unconfig_ip4()
            self.pg2.unconfig_ip4()
            self.pg1.set_table_ip4(0)
            self.pg2.set_table_ip4(0)
            self.pg1.config_ip4()
            self.pg2.config_ip4()
            self.pg1.resolve_arp()
            self.pg2.resolve_arp()

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_session_timeout(self):
        """ NAT44 session timeouts """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat_set_timeouts(udp=5)

        max_sessions = 1000
        pkts = []
        for i in range(0, max_sessions):
            src = "10.10.%u.%u" % ((i & 0xFF00) >> 8, i & 0xFF)
            p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                 IP(src=src, dst=self.pg1.remote_ip4) /
                 UDP(sport=1025, dport=53))
            pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(max_sessions)

        sleep(6)

        pkts = []
        for i in range(0, max_sessions):
            src = "10.10.%u.%u" % ((i & 0xFF00) >> 8, i & 0xFF)
            p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                 IP(src=src, dst=self.pg1.remote_ip4) /
                 UDP(sport=1026, dport=53))
            pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(max_sessions)

        nsessions = 0
        users = self.vapi.nat44_user_dump()
        for user in users:
            nsessions = nsessions + user.nsessions
        self.assertLess(nsessions, 2 * max_sessions)

    def test_mss_clamping(self):
        """ TCP MSS clamping """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                 flags="S", options=[('MSS', 1400)]))

        self.vapi.nat_set_mss_clamping(enable=1, mss_value=1000)
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        # Negotiated MSS value greater than configured - changed
        self.verify_mss_value(capture[0], 1000)

        self.vapi.nat_set_mss_clamping(enable=0)
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        # MSS clamping disabled - negotiated MSS unchanged
        self.verify_mss_value(capture[0], 1400)

        self.vapi.nat_set_mss_clamping(enable=1, mss_value=1500)
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        # Negotiated MSS value smaller than configured - unchanged
        self.verify_mss_value(capture[0], 1400)

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_ha_send(self):
        """ Send HA session synchronization events (active) """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat_ha_set_listener(self.pg3.local_ip4, port=12345)
        self.vapi.nat_ha_set_failover(self.pg3.remote_ip4, port=12346)
        bind_layers(UDP, HANATStateSync, sport=12345)

        # create sessions
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)
        # active send HA events
        self.vapi.nat_ha_flush()
        stats = self.statistics.get_counter('/nat44/ha/add-event-send')
        self.assertEqual(stats[0][0], 3)
        capture = self.pg3.get_capture(1)
        p = capture[0]
        self.assert_packet_checksums_valid(p)
        try:
            ip = p[IP]
            udp = p[UDP]
            hanat = p[HANATStateSync]
        except IndexError:
            self.logger.error(ppp("Invalid packet:", p))
            raise
        else:
            self.assertEqual(ip.src, self.pg3.local_ip4)
            self.assertEqual(ip.dst, self.pg3.remote_ip4)
            self.assertEqual(udp.sport, 12345)
            self.assertEqual(udp.dport, 12346)
            self.assertEqual(hanat.version, 1)
            self.assertEqual(hanat.thread_index, 0)
            self.assertEqual(hanat.count, 3)
            seq = hanat.sequence_number
            for event in hanat.events:
                self.assertEqual(event.event_type, 1)
                self.assertEqual(event.in_addr, self.pg0.remote_ip4)
                self.assertEqual(event.out_addr, self.nat_addr)
                self.assertEqual(event.fib_index, 0)

        # ACK received events
        ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
               IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
               UDP(sport=12346, dport=12345) /
               HANATStateSync(sequence_number=seq, flags='ACK'))
        self.pg3.add_stream(ack)
        self.pg_start()
        stats = self.statistics.get_counter('/nat44/ha/ack-recv')
        self.assertEqual(stats[0][0], 1)

        # delete one session
        self.pg_enable_capture(self.pg_interfaces)
        self.vapi.nat44_del_session(self.pg0.remote_ip4n, self.tcp_port_in,
                                    IP_PROTOS.tcp)
        self.vapi.nat_ha_flush()
        stats = self.statistics.get_counter('/nat44/ha/del-event-send')
        self.assertEqual(stats[0][0], 1)
        capture = self.pg3.get_capture(1)
        p = capture[0]
        try:
            hanat = p[HANATStateSync]
        except IndexError:
            self.logger.error(ppp("Invalid packet:", p))
            raise
        else:
            self.assertGreater(hanat.sequence_number, seq)

        # do not send ACK, active retry send HA event again
        self.pg_enable_capture(self.pg_interfaces)
        sleep(12)
        stats = self.statistics.get_counter('/nat44/ha/retry-count')
        self.assertEqual(stats[0][0], 3)
        stats = self.statistics.get_counter('/nat44/ha/missed-count')
        self.assertEqual(stats[0][0], 1)
        capture = self.pg3.get_capture(3)
        for packet in capture:
            self.assertEqual(packet, p)

        # session counters refresh
        pkts = self.create_stream_out(self.pg1)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg0.get_capture(2)
        self.vapi.nat_ha_flush()
        stats = self.statistics.get_counter('/nat44/ha/refresh-event-send')
        self.assertEqual(stats[0][0], 2)
        capture = self.pg3.get_capture(1)
        p = capture[0]
        self.assert_packet_checksums_valid(p)
        try:
            ip = p[IP]
            udp = p[UDP]
            hanat = p[HANATStateSync]
        except IndexError:
            self.logger.error(ppp("Invalid packet:", p))
            raise
        else:
            self.assertEqual(ip.src, self.pg3.local_ip4)
            self.assertEqual(ip.dst, self.pg3.remote_ip4)
            self.assertEqual(udp.sport, 12345)
            self.assertEqual(udp.dport, 12346)
            self.assertEqual(hanat.version, 1)
            self.assertEqual(hanat.count, 2)
            seq = hanat.sequence_number
            for event in hanat.events:
                self.assertEqual(event.event_type, 3)
                self.assertEqual(event.out_addr, self.nat_addr)
                self.assertEqual(event.fib_index, 0)
                self.assertEqual(event.total_pkts, 2)
                self.assertGreater(event.total_bytes, 0)

        ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
               IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
               UDP(sport=12346, dport=12345) /
               HANATStateSync(sequence_number=seq, flags='ACK'))
        self.pg3.add_stream(ack)
        self.pg_start()
        stats = self.statistics.get_counter('/nat44/ha/ack-recv')
        self.assertEqual(stats[0][0], 2)

    def test_ha_recv(self):
        """ Receive HA session synchronization events (passive) """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat_ha_set_listener(self.pg3.local_ip4, port=12345)
        bind_layers(UDP, HANATStateSync, sport=12345)

        self.tcp_port_out = random.randint(1025, 65535)
        self.udp_port_out = random.randint(1025, 65535)

        # send HA session add events to failover/passive
        p = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
             IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
             UDP(sport=12346, dport=12345) /
             HANATStateSync(sequence_number=1, events=[
                 Event(event_type='add', protocol='tcp',
                       in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr,
                       in_port=self.tcp_port_in, out_port=self.tcp_port_out,
                       eh_addr=self.pg1.remote_ip4,
                       ehn_addr=self.pg1.remote_ip4,
                       eh_port=self.tcp_external_port,
                       ehn_port=self.tcp_external_port, fib_index=0),
                 Event(event_type='add', protocol='udp',
                       in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr,
                       in_port=self.udp_port_in, out_port=self.udp_port_out,
                       eh_addr=self.pg1.remote_ip4,
                       ehn_addr=self.pg1.remote_ip4,
                       eh_port=self.udp_external_port,
                       ehn_port=self.udp_external_port, fib_index=0)]))

        self.pg3.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        # receive ACK
        capture = self.pg3.get_capture(1)
        p = capture[0]
        try:
            hanat = p[HANATStateSync]
        except IndexError:
            self.logger.error(ppp("Invalid packet:", p))
            raise
        else:
            self.assertEqual(hanat.sequence_number, 1)
            self.assertEqual(hanat.flags, 'ACK')
            self.assertEqual(hanat.version, 1)
            self.assertEqual(hanat.thread_index, 0)
        stats = self.statistics.get_counter('/nat44/ha/ack-send')
        self.assertEqual(stats[0][0], 1)
        stats = self.statistics.get_counter('/nat44/ha/add-event-recv')
        self.assertEqual(stats[0][0], 2)
        users = self.statistics.get_counter('/nat44/total-users')
        self.assertEqual(users[0][0], 1)
        sessions = self.statistics.get_counter('/nat44/total-sessions')
        self.assertEqual(sessions[0][0], 2)
        users = self.vapi.nat44_user_dump()
        self.assertEqual(len(users), 1)
        self.assertEqual(users[0].ip_address, self.pg0.remote_ip4n)
        # there should be 2 sessions created by HA
        sessions = self.vapi.nat44_user_session_dump(users[0].ip_address,
                                                     users[0].vrf_id)
        self.assertEqual(len(sessions), 2)
        for session in sessions:
            self.assertEqual(session.inside_ip_address, self.pg0.remote_ip4n)
            self.assertEqual(session.outside_ip_address, self.nat_addr_n)
            self.assertIn(session.inside_port,
                          [self.tcp_port_in, self.udp_port_in])
            self.assertIn(session.outside_port,
                          [self.tcp_port_out, self.udp_port_out])
            self.assertIn(session.protocol, [IP_PROTOS.tcp, IP_PROTOS.udp])

        # send HA session delete event to failover/passive
        p = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
             IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
             UDP(sport=12346, dport=12345) /
             HANATStateSync(sequence_number=2, events=[
                 Event(event_type='del', protocol='udp',
                       in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr,
                       in_port=self.udp_port_in, out_port=self.udp_port_out,
                       eh_addr=self.pg1.remote_ip4,
                       ehn_addr=self.pg1.remote_ip4,
                       eh_port=self.udp_external_port,
                       ehn_port=self.udp_external_port, fib_index=0)]))

        self.pg3.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        # receive ACK
        capture = self.pg3.get_capture(1)
        p = capture[0]
        try:
            hanat = p[HANATStateSync]
        except IndexError:
            self.logger.error(ppp("Invalid packet:", p))
            raise
        else:
            self.assertEqual(hanat.sequence_number, 2)
            self.assertEqual(hanat.flags, 'ACK')
            self.assertEqual(hanat.version, 1)
        users = self.vapi.nat44_user_dump()
        self.assertEqual(len(users), 1)
        self.assertEqual(users[0].ip_address, self.pg0.remote_ip4n)
        # now we should have only 1 session, 1 deleted by HA
        sessions = self.vapi.nat44_user_session_dump(users[0].ip_address,
                                                     users[0].vrf_id)
        self.assertEqual(len(sessions), 1)
        stats = self.statistics.get_counter('/nat44/ha/del-event-recv')
        self.assertEqual(stats[0][0], 1)

        stats = self.statistics.get_counter('/err/nat-ha/pkts-processed')
        self.assertEqual(stats, 2)

        # send HA session refresh event to failover/passive
        p = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
             IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
             UDP(sport=12346, dport=12345) /
             HANATStateSync(sequence_number=3, events=[
                 Event(event_type='refresh', protocol='tcp',
                       in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr,
                       in_port=self.tcp_port_in, out_port=self.tcp_port_out,
                       eh_addr=self.pg1.remote_ip4,
                       ehn_addr=self.pg1.remote_ip4,
                       eh_port=self.tcp_external_port,
                       ehn_port=self.tcp_external_port, fib_index=0,
                       total_bytes=1024, total_pkts=2)]))
        self.pg3.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        # receive ACK
        capture = self.pg3.get_capture(1)
        p = capture[0]
        try:
            hanat = p[HANATStateSync]
        except IndexError:
            self.logger.error(ppp("Invalid packet:", p))
            raise
        else:
            self.assertEqual(hanat.sequence_number, 3)
            self.assertEqual(hanat.flags, 'ACK')
            self.assertEqual(hanat.version, 1)
        users = self.vapi.nat44_user_dump()
        self.assertEqual(len(users), 1)
        self.assertEqual(users[0].ip_address, self.pg0.remote_ip4n)
        sessions = self.vapi.nat44_user_session_dump(users[0].ip_address,
                                                     users[0].vrf_id)
        self.assertEqual(len(sessions), 1)
        session = sessions[0]
        self.assertEqual(session.total_bytes, 1024)
        self.assertEqual(session.total_pkts, 2)
        stats = self.statistics.get_counter('/nat44/ha/refresh-event-recv')
        self.assertEqual(stats[0][0], 1)

        stats = self.statistics.get_counter('/err/nat-ha/pkts-processed')
        self.assertEqual(stats, 3)

        # send packet to test session created by HA
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=self.tcp_external_port, dport=self.tcp_port_out))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
        except IndexError:
            self.logger.error(ppp("Invalid packet:", p))
            raise
        else:
            self.assertEqual(ip.src, self.pg1.remote_ip4)
            self.assertEqual(ip.dst, self.pg0.remote_ip4)
            self.assertEqual(tcp.sport, self.tcp_external_port)
            self.assertEqual(tcp.dport, self.tcp_port_in)

    def tearDown(self):
        super(TestNAT44, self).tearDown()
        if not self.vpp_dead:
            self.logger.info(self.vapi.cli("show nat44 addresses"))
            self.logger.info(self.vapi.cli("show nat44 interfaces"))
            self.logger.info(self.vapi.cli("show nat44 static mappings"))
            self.logger.info(self.vapi.cli("show nat44 interface address"))
            self.logger.info(self.vapi.cli("show nat44 sessions detail"))
            self.logger.info(self.vapi.cli("show nat virtual-reassembly"))
            self.logger.info(self.vapi.cli("show nat44 hash tables detail"))
            self.logger.info(self.vapi.cli("show nat timeouts"))
            self.logger.info(
                self.vapi.cli("show nat addr-port-assignment-alg"))
            self.logger.info(self.vapi.cli("show nat ha"))
            self.clear_nat44()
            self.vapi.cli("clear logging")


class TestNAT44EndpointDependent(MethodHolder):
    """ Endpoint-Dependent mapping and filtering test cases """

    @classmethod
    def setUpConstants(cls):
        super(TestNAT44EndpointDependent, cls).setUpConstants()
        cls.vpp_cmdline.extend(["nat", "{", "endpoint-dependent", "}"])

    @classmethod
    def setUpClass(cls):
        super(TestNAT44EndpointDependent, cls).setUpClass()
        cls.vapi.cli("set log class nat level debug")
        try:
            cls.tcp_port_in = 6303
            cls.tcp_port_out = 6303
            cls.udp_port_in = 6304
            cls.udp_port_out = 6304
            cls.icmp_id_in = 6305
            cls.icmp_id_out = 6305
            cls.nat_addr = '10.0.0.3'
            cls.nat_addr_n = socket.inet_pton(socket.AF_INET, cls.nat_addr)
            cls.ipfix_src_port = 4739
            cls.ipfix_domain_id = 1
            cls.tcp_external_port = 80

            cls.create_pg_interfaces(range(7))
            cls.interfaces = list(cls.pg_interfaces[0:3])

            for i in cls.interfaces:
                i.admin_up()
                i.config_ip4()
                i.resolve_arp()

            cls.pg0.generate_remote_hosts(3)
            cls.pg0.configure_ipv4_neighbors()

            cls.pg3.admin_up()

            cls.pg4.generate_remote_hosts(2)
            cls.pg4.config_ip4()
            ip_addr_n = socket.inet_pton(socket.AF_INET, "10.0.0.1")
            cls.vapi.sw_interface_add_del_address(
                sw_if_index=cls.pg4.sw_if_index, address=ip_addr_n,
                address_length=24)
            cls.pg4.admin_up()
            cls.pg4.resolve_arp()
            cls.pg4._remote_hosts[1]._ip4 = cls.pg4._remote_hosts[0]._ip4
            cls.pg4.resolve_arp()

            zero_ip4n = socket.inet_pton(socket.AF_INET, "0.0.0.0")
            cls.vapi.ip_table_add_del(is_add=1, table_id=1)

            cls.pg5._local_ip4 = "10.1.1.1"
            cls.pg5._local_ip4n = socket.inet_pton(socket.AF_INET,
                                                   cls.pg5.local_ip4)
            cls.pg5._remote_hosts[0]._ip4 = "10.1.1.2"
            cls.pg5._remote_hosts[0]._ip4n = socket.inet_pton(
                socket.AF_INET, cls.pg5.remote_ip4)
            cls.pg5.set_table_ip4(1)
            cls.pg5.config_ip4()
            cls.pg5.admin_up()
            cls.vapi.ip_add_del_route(dst_address=cls.pg5.remote_ip4n,
                                      dst_address_length=32,
                                      next_hop_address=zero_ip4n,
                                      next_hop_sw_if_index=cls.pg5.sw_if_index,
                                      table_id=1)

            cls.pg6._local_ip4 = "10.1.2.1"
            cls.pg6._local_ip4n = socket.inet_pton(socket.AF_INET,
                                                   cls.pg6.local_ip4)
            cls.pg6._remote_hosts[0]._ip4 = "10.1.2.2"
            cls.pg6._remote_hosts[0]._ip4n = socket.inet_pton(
                socket.AF_INET, cls.pg6.remote_ip4)
            cls.pg6.set_table_ip4(1)
            cls.pg6.config_ip4()
            cls.pg6.admin_up()
            cls.vapi.ip_add_del_route(dst_address=cls.pg6.remote_ip4n,
                                      dst_address_length=32,
                                      next_hop_address=zero_ip4n,
                                      next_hop_sw_if_index=cls.pg6.sw_if_index,
                                      table_id=1)

            cls.vapi.ip_add_del_route(dst_address=cls.pg6.remote_ip4n,
                                      dst_address_length=16,
                                      next_hop_address=zero_ip4n, table_id=0,
                                      next_hop_table_id=1)
            cls.vapi.ip_add_del_route(dst_address=zero_ip4n,
                                      dst_address_length=0,
                                      next_hop_address=zero_ip4n, table_id=1,
                                      next_hop_table_id=0)
            cls.vapi.ip_add_del_route(dst_address=zero_ip4n,
                                      dst_address_length=0,
                                      next_hop_address=cls.pg1.local_ip4n,
                                      next_hop_sw_if_index=cls.pg1.sw_if_index,
                                      table_id=0)

            cls.pg5.resolve_arp()
            cls.pg6.resolve_arp()

        except Exception:
            super(TestNAT44EndpointDependent, cls).tearDownClass()
            raise

    def test_frag_in_order(self):
        """ NAT44 translate fragments arriving in order """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.frag_in_order(proto=IP_PROTOS.tcp)
        self.frag_in_order(proto=IP_PROTOS.udp)
        self.frag_in_order(proto=IP_PROTOS.icmp)

    def test_frag_in_order_dont_translate(self):
        """ NAT44 don't translate fragments arriving in order """
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_forwarding_enable_disable(enable=True)
        self.frag_in_order(proto=IP_PROTOS.tcp, dont_translate=True)

    def test_frag_out_of_order(self):
        """ NAT44 translate fragments arriving out of order """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.frag_out_of_order(proto=IP_PROTOS.tcp)
        self.frag_out_of_order(proto=IP_PROTOS.udp)
        self.frag_out_of_order(proto=IP_PROTOS.icmp)

    def test_frag_out_of_order_dont_translate(self):
        """ NAT44 don't translate fragments arriving out of order """
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_forwarding_enable_disable(enable=True)
        self.frag_out_of_order(proto=IP_PROTOS.tcp, dont_translate=True)

    def test_frag_in_order_in_plus_out(self):
        """ in+out interface fragments in order """
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        self.server = self.pg1.remote_hosts[0]

        self.server_in_addr = self.server.ip4
        self.server_out_addr = '11.11.11.11'
        self.server_in_port = random.randint(1025, 65535)
        self.server_out_port = random.randint(1025, 65535)

        self.nat44_add_address(self.server_out_addr)

        # add static mappings for server
        self.nat44_add_static_mapping(self.server_in_addr,
                                      self.server_out_addr,
                                      self.server_in_port,
                                      self.server_out_port,
                                      proto=IP_PROTOS.tcp)
        self.nat44_add_static_mapping(self.server_in_addr,
                                      self.server_out_addr,
                                      self.server_in_port,
                                      self.server_out_port,
                                      proto=IP_PROTOS.udp)
        self.nat44_add_static_mapping(self.server_in_addr,
                                      self.server_out_addr,
                                      proto=IP_PROTOS.icmp)

        self.vapi.nat_set_reass(timeout=10)

        self.frag_in_order_in_plus_out(proto=IP_PROTOS.tcp)
        self.frag_in_order_in_plus_out(proto=IP_PROTOS.udp)
        self.frag_in_order_in_plus_out(proto=IP_PROTOS.icmp)

    def test_frag_out_of_order_in_plus_out(self):
        """ in+out interface fragments out of order """
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        self.server = self.pg1.remote_hosts[0]

        self.server_in_addr = self.server.ip4
        self.server_out_addr = '11.11.11.11'
        self.server_in_port = random.randint(1025, 65535)
        self.server_out_port = random.randint(1025, 65535)

        self.nat44_add_address(self.server_out_addr)

        # add static mappings for server
        self.nat44_add_static_mapping(self.server_in_addr,
                                      self.server_out_addr,
                                      self.server_in_port,
                                      self.server_out_port,
                                      proto=IP_PROTOS.tcp)
        self.nat44_add_static_mapping(self.server_in_addr,
                                      self.server_out_addr,
                                      self.server_in_port,
                                      self.server_out_port,
                                      proto=IP_PROTOS.udp)
        self.nat44_add_static_mapping(self.server_in_addr,
                                      self.server_out_addr,
                                      proto=IP_PROTOS.icmp)

        self.vapi.nat_set_reass(timeout=10)

        self.frag_out_of_order_in_plus_out(proto=IP_PROTOS.tcp)
        self.frag_out_of_order_in_plus_out(proto=IP_PROTOS.udp)
        self.frag_out_of_order_in_plus_out(proto=IP_PROTOS.icmp)

    def test_reass_hairpinning(self):
        """ NAT44 fragments hairpinning """
        self.server = self.pg0.remote_hosts[1]
        self.host_in_port = random.randint(1025, 65535)
        self.server_in_port = random.randint(1025, 65535)
        self.server_out_port = random.randint(1025, 65535)

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        # add static mapping for server
        self.nat44_add_static_mapping(self.server.ip4, self.nat_addr,
                                      self.server_in_port,
                                      self.server_out_port,
                                      proto=IP_PROTOS.tcp)
        self.nat44_add_static_mapping(self.server.ip4, self.nat_addr,
                                      self.server_in_port,
                                      self.server_out_port,
                                      proto=IP_PROTOS.udp)
        self.nat44_add_static_mapping(self.server.ip4, self.nat_addr)

        self.reass_hairpinning(proto=IP_PROTOS.tcp)
        self.reass_hairpinning(proto=IP_PROTOS.udp)
        self.reass_hairpinning(proto=IP_PROTOS.icmp)

    def test_dynamic(self):
        """ NAT44 dynamic translation test """

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        nat_config = self.vapi.nat_show_config()
        self.assertEqual(1, nat_config.endpoint_dependent)

        # in2out
        tcpn = self.statistics.get_counter(
            '/err/nat44-ed-in2out-slowpath/TCP packets')
        udpn = self.statistics.get_counter(
            '/err/nat44-ed-in2out-slowpath/UDP packets')
        icmpn = self.statistics.get_counter(
            '/err/nat44-ed-in2out-slowpath/ICMP packets')
        totaln = self.statistics.get_counter(
            '/err/nat44-ed-in2out-slowpath/good in2out packets processed')

        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)

        err = self.statistics.get_counter(
            '/err/nat44-ed-in2out-slowpath/TCP packets')
        self.assertEqual(err - tcpn, 1)
        err = self.statistics.get_counter(
            '/err/nat44-ed-in2out-slowpath/UDP packets')
        self.assertEqual(err - udpn, 1)
        err = self.statistics.get_counter(
            '/err/nat44-ed-in2out-slowpath/ICMP packets')
        self.assertEqual(err - icmpn, 1)
        err = self.statistics.get_counter(
            '/err/nat44-ed-in2out-slowpath/good in2out packets processed')
        self.assertEqual(err - totaln, 3)

        # out2in
        tcpn = self.statistics.get_counter('/err/nat44-ed-out2in/TCP packets')
        udpn = self.statistics.get_counter('/err/nat44-ed-out2in/UDP packets')
        icmpn = self.statistics.get_counter(
            '/err/nat44-ed-out2in-slowpath/ICMP packets')
        totaln = self.statistics.get_counter(
            '/err/nat44-ed-out2in/good out2in packets processed')

        pkts = self.create_stream_out(self.pg1)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

        err = self.statistics.get_counter('/err/nat44-ed-out2in/TCP packets')
        self.assertEqual(err - tcpn, 1)
        err = self.statistics.get_counter('/err/nat44-ed-out2in/UDP packets')
        self.assertEqual(err - udpn, 1)
        err = self.statistics.get_counter(
            '/err/nat44-ed-out2in-slowpath/ICMP packets')
        self.assertEqual(err - icmpn, 1)
        err = self.statistics.get_counter(
            '/err/nat44-ed-out2in/good out2in packets processed')
        self.assertEqual(err - totaln, 2)

        users = self.statistics.get_counter('/nat44/total-users')
        self.assertEqual(users[0][0], 1)
        sessions = self.statistics.get_counter('/nat44/total-sessions')
        self.assertEqual(sessions[0][0], 3)

    def test_forwarding(self):
        """ NAT44 forwarding test """

        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_forwarding_enable_disable(1)

        real_ip = self.pg0.remote_ip4n
        alias_ip = self.nat_addr_n
        self.vapi.nat44_add_del_static_mapping(local_ip=real_ip,
                                               external_ip=alias_ip)

        try:
            # in2out - static mapping match

            pkts = self.create_stream_out(self.pg1)
            self.pg1.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg0.get_capture(len(pkts))
            self.verify_capture_in(capture, self.pg0)

            pkts = self.create_stream_in(self.pg0, self.pg1)
            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg1.get_capture(len(pkts))
            self.verify_capture_out(capture, same_port=True)

            # in2out - no static mapping match

            host0 = self.pg0.remote_hosts[0]
            self.pg0.remote_hosts[0] = self.pg0.remote_hosts[1]
            try:
                pkts = self.create_stream_out(self.pg1,
                                              dst_ip=self.pg0.remote_ip4,
                                              use_inside_ports=True)
                self.pg1.add_stream(pkts)
                self.pg_enable_capture(self.pg_interfaces)
                self.pg_start()
                capture = self.pg0.get_capture(len(pkts))
                self.verify_capture_in(capture, self.pg0)

                pkts = self.create_stream_in(self.pg0, self.pg1)
                self.pg0.add_stream(pkts)
                self.pg_enable_capture(self.pg_interfaces)
                self.pg_start()
                capture = self.pg1.get_capture(len(pkts))
                self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4,
                                        same_port=True)
            finally:
                self.pg0.remote_hosts[0] = host0

            user = self.pg0.remote_hosts[1]
            sessions = self.vapi.nat44_user_session_dump(user.ip4n, 0)
            self.assertEqual(len(sessions), 3)
            self.assertTrue(sessions[0].ext_host_valid)
            self.vapi.nat44_del_session(
                sessions[0].inside_ip_address,
                sessions[0].inside_port,
                sessions[0].protocol,
                ext_host_address=sessions[0].ext_host_address,
                ext_host_port=sessions[0].ext_host_port)
            sessions = self.vapi.nat44_user_session_dump(user.ip4n, 0)
            self.assertEqual(len(sessions), 2)

        finally:
            self.vapi.nat44_forwarding_enable_disable(0)
            self.vapi.nat44_add_del_static_mapping(local_ip=real_ip,
                                                   external_ip=alias_ip,
                                                   is_add=0)

    def test_static_lb(self):
        """ NAT44 local service load balancing """
        external_addr_n = socket.inet_pton(socket.AF_INET, self.nat_addr)
        external_port = 80
        local_port = 8080
        server1 = self.pg0.remote_hosts[0]
        server2 = self.pg0.remote_hosts[1]

        locals = [{'addr': server1.ip4n,
                   'port': local_port,
                   'probability': 70,
                   'vrf_id': 0},
                  {'addr': server2.ip4n,
                   'port': local_port,
                   'probability': 30,
                   'vrf_id': 0}]

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_add_del_lb_static_mapping(external_addr_n,
                                                  external_port,
                                                  IP_PROTOS.tcp,
                                                  local_num=len(locals),
                                                  locals=locals)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # from client to service
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=12345, dport=external_port))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        server = None
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertIn(ip.dst, [server1.ip4, server2.ip4])
            if ip.dst == server1.ip4:
                server = server1
            else:
                server = server2
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service back to client
        p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
             IP(src=server.ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=local_port, dport=12345))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(tcp.sport, external_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        sessions = self.vapi.nat44_user_session_dump(server.ip4n, 0)
        self.assertEqual(len(sessions), 1)
        self.assertTrue(sessions[0].ext_host_valid)
        self.vapi.nat44_del_session(
            sessions[0].inside_ip_address,
            sessions[0].inside_port,
            sessions[0].protocol,
            ext_host_address=sessions[0].ext_host_address,
            ext_host_port=sessions[0].ext_host_port)
        sessions = self.vapi.nat44_user_session_dump(server.ip4n, 0)
        self.assertEqual(len(sessions), 0)

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_static_lb_multi_clients(self):
        """ NAT44 local service load balancing - multiple clients"""

        external_addr_n = socket.inet_pton(socket.AF_INET, self.nat_addr)
        external_port = 80
        local_port = 8080
        server1 = self.pg0.remote_hosts[0]
        server2 = self.pg0.remote_hosts[1]
        server3 = self.pg0.remote_hosts[2]

        locals = [{'addr': server1.ip4n,
                   'port': local_port,
                   'probability': 90,
                   'vrf_id': 0},
                  {'addr': server2.ip4n,
                   'port': local_port,
                   'probability': 10,
                   'vrf_id': 0}]

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_add_del_lb_static_mapping(external_addr_n,
                                                  external_port,
                                                  IP_PROTOS.tcp,
                                                  local_num=len(locals),
                                                  locals=locals)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        server1_n = 0
        server2_n = 0
        clients = ip4_range(self.pg1.remote_ip4, 10, 50)
        pkts = []
        for client in clients:
            p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
                 IP(src=client, dst=self.nat_addr) /
                 TCP(sport=12345, dport=external_port))
            pkts.append(p)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for p in capture:
            if p[IP].dst == server1.ip4:
                server1_n += 1
            else:
                server2_n += 1
        self.assertGreater(server1_n, server2_n)

        # add new back-end
        self.vapi.nat44_lb_static_mapping_add_del_local(external_addr_n,
                                                        external_port,
                                                        server3.ip4n,
                                                        local_port,
                                                        IP_PROTOS.tcp,
                                                        20)
        server1_n = 0
        server2_n = 0
        server3_n = 0
        clients = ip4_range(self.pg1.remote_ip4, 60, 110)
        pkts = []
        for client in clients:
            p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
                 IP(src=client, dst=self.nat_addr) /
                 TCP(sport=12346, dport=external_port))
            pkts.append(p)
        self.assertGreater(len(pkts), 0)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for p in capture:
            if p[IP].dst == server1.ip4:
                server1_n += 1
            elif p[IP].dst == server2.ip4:
                server2_n += 1
            else:
                server3_n += 1
        self.assertGreater(server1_n, 0)
        self.assertGreater(server2_n, 0)
        self.assertGreater(server3_n, 0)

        # remove one back-end
        self.vapi.nat44_lb_static_mapping_add_del_local(external_addr_n,
                                                        external_port,
                                                        server2.ip4n,
                                                        local_port,
                                                        IP_PROTOS.tcp,
                                                        10,
                                                        is_add=0)
        server1_n = 0
        server2_n = 0
        server3_n = 0
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for p in capture:
            if p[IP].dst == server1.ip4:
                server1_n += 1
            elif p[IP].dst == server2.ip4:
                server2_n += 1
            else:
                server3_n += 1
        self.assertGreater(server1_n, 0)
        self.assertEqual(server2_n, 0)
        self.assertGreater(server3_n, 0)

    def test_static_lb_2(self):
        """ NAT44 local service load balancing (asymmetrical rule) """
        external_addr_n = socket.inet_pton(socket.AF_INET, self.nat_addr)
        external_port = 80
        local_port = 8080
        server1 = self.pg0.remote_hosts[0]
        server2 = self.pg0.remote_hosts[1]

        locals = [{'addr': server1.ip4n,
                   'port': local_port,
                   'probability': 70,
                   'vrf_id': 0},
                  {'addr': server2.ip4n,
                   'port': local_port,
                   'probability': 30,
                   'vrf_id': 0}]

        self.vapi.nat44_forwarding_enable_disable(1)
        self.vapi.nat44_add_del_lb_static_mapping(external_addr_n,
                                                  external_port,
                                                  IP_PROTOS.tcp,
                                                  out2in_only=1,
                                                  local_num=len(locals),
                                                  locals=locals)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # from client to service
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=12345, dport=external_port))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        server = None
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertIn(ip.dst, [server1.ip4, server2.ip4])
            if ip.dst == server1.ip4:
                server = server1
            else:
                server = server2
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service back to client
        p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
             IP(src=server.ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=local_port, dport=12345))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(tcp.sport, external_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from client to server (no translation)
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=server1.ip4) /
             TCP(sport=12346, dport=local_port))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        server = None
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, server1.ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service back to client (no translation)
        p = (Ether(src=server1.mac, dst=self.pg0.local_mac) /
             IP(src=server1.ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=local_port, dport=12346))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, server1.ip4)
            self.assertEqual(tcp.sport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    def test_lb_affinity(self):
        """ NAT44 local service load balancing affinity """
        external_addr_n = socket.inet_pton(socket.AF_INET, self.nat_addr)
        external_port = 80
        local_port = 8080
        server1 = self.pg0.remote_hosts[0]
        server2 = self.pg0.remote_hosts[1]

        locals = [{'addr': server1.ip4n,
                   'port': local_port,
                   'probability': 50,
                   'vrf_id': 0},
                  {'addr': server2.ip4n,
                   'port': local_port,
                   'probability': 50,
                   'vrf_id': 0}]

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_add_del_lb_static_mapping(external_addr_n,
                                                  external_port,
                                                  IP_PROTOS.tcp,
                                                  affinity=10800,
                                                  local_num=len(locals),
                                                  locals=locals)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=1025, dport=external_port))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        backend = capture[0][IP].dst

        sessions = self.vapi.nat44_user_session_dump(
            socket.inet_pton(socket.AF_INET, backend), 0)
        self.assertEqual(len(sessions), 1)
        self.assertTrue(sessions[0].ext_host_valid)
        self.vapi.nat44_del_session(
            sessions[0].inside_ip_address,
            sessions[0].inside_port,
            sessions[0].protocol,
            ext_host_address=sessions[0].ext_host_address,
            ext_host_port=sessions[0].ext_host_port)

        pkts = []
        for port in range(1030, 1100):
            p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
                 IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
                 TCP(sport=port, dport=external_port))
            pkts.append(p)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for p in capture:
            self.assertEqual(p[IP].dst, backend)

    def test_unknown_proto(self):
        """ NAT44 translate packet with unknown protocol """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # in2out
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=20))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg1.get_capture(1)

        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             GRE() /
             IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg1.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IP].src, self.nat_addr)
            self.assertEqual(packet[IP].dst, self.pg1.remote_ip4)
            self.assertEqual(packet.haslayer(GRE), 1)
            self.assert_packet_checksums_valid(packet)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

        # out2in
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             GRE() /
             IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IP].src, self.pg1.remote_ip4)
            self.assertEqual(packet[IP].dst, self.pg0.remote_ip4)
            self.assertEqual(packet.haslayer(GRE), 1)
            self.assert_packet_checksums_valid(packet)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

    def test_hairpinning_unknown_proto(self):
        """ NAT44 translate packet with unknown protocol - hairpinning """
        host = self.pg0.remote_hosts[0]
        server = self.pg0.remote_hosts[1]
        host_in_port = 1234
        server_out_port = 8765
        server_nat_ip = "10.0.0.11"

        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # add static mapping for server
        self.nat44_add_static_mapping(server.ip4, server_nat_ip)

        # host to server
        p = (Ether(src=host.mac, dst=self.pg0.local_mac) /
             IP(src=host.ip4, dst=server_nat_ip) /
             TCP(sport=host_in_port, dport=server_out_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg0.get_capture(1)

        p = (Ether(dst=self.pg0.local_mac, src=host.mac) /
             IP(src=host.ip4, dst=server_nat_ip) /
             GRE() /
             IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IP].src, self.nat_addr)
            self.assertEqual(packet[IP].dst, server.ip4)
            self.assertEqual(packet.haslayer(GRE), 1)
            self.assert_packet_checksums_valid(packet)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

        # server to host
        p = (Ether(dst=self.pg0.local_mac, src=server.mac) /
             IP(src=server.ip4, dst=self.nat_addr) /
             GRE() /
             IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IP].src, server_nat_ip)
            self.assertEqual(packet[IP].dst, host.ip4)
            self.assertEqual(packet.haslayer(GRE), 1)
            self.assert_packet_checksums_valid(packet)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

    def test_output_feature_and_service(self):
        """ NAT44 interface output feature and services """
        external_addr = '1.2.3.4'
        external_port = 80
        local_port = 8080

        self.vapi.nat44_forwarding_enable_disable(1)
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_add_del_identity_mapping(ip=self.pg1.remote_ip4n)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, external_addr,
                                      local_port, external_port,
                                      proto=IP_PROTOS.tcp, out2in_only=1)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_output_feature(self.pg1.sw_if_index,
                                                         is_inside=0)

        # from client to service
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=external_addr) /
             TCP(sport=12345, dport=external_port))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg0.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service back to client
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=local_port, dport=12345))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, external_addr)
            self.assertEqual(tcp.sport, external_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from local network host to external network
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # from external network back to local network host
        pkts = self.create_stream_out(self.pg1)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

    def test_output_feature_and_service2(self):
        """ NAT44 interface output feature and service host direct access """
        self.vapi.nat44_forwarding_enable_disable(1)
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_output_feature(self.pg1.sw_if_index,
                                                         is_inside=0)

        # session initiaded from service host - translate
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)

        pkts = self.create_stream_out(self.pg1)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

        # session initiaded from remote host - do not translate
        self.tcp_port_in = 60303
        self.udp_port_in = 60304
        self.icmp_id_in = 60305
        pkts = self.create_stream_out(self.pg1,
                                      self.pg0.remote_ip4,
                                      use_inside_ports=True)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4,
                                same_port=True)

    def test_output_feature_and_service3(self):
        """ NAT44 interface output feature and DST NAT """
        external_addr = '1.2.3.4'
        external_port = 80
        local_port = 8080

        self.vapi.nat44_forwarding_enable_disable(1)
        self.nat44_add_address(self.nat_addr)
        self.nat44_add_static_mapping(self.pg1.remote_ip4, external_addr,
                                      local_port, external_port,
                                      proto=IP_PROTOS.tcp, out2in_only=1)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_output_feature(self.pg1.sw_if_index,
                                                         is_inside=0)

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=external_addr) /
             TCP(sport=12345, dport=external_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg0.remote_ip4)
            self.assertEqual(tcp.sport, 12345)
            self.assertEqual(ip.dst, self.pg1.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) /
             TCP(sport=local_port, dport=12345))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, external_addr)
            self.assertEqual(tcp.sport, external_port)
            self.assertEqual(ip.dst, self.pg0.remote_ip4)
            self.assertEqual(tcp.dport, 12345)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    def test_next_src_nat(self):
        """ On way back forward packet to nat44-in2out node. """
        twice_nat_addr = '10.0.1.3'
        external_port = 80
        local_port = 8080
        post_twice_nat_port = 0

        self.vapi.nat44_forwarding_enable_disable(1)
        self.nat44_add_address(twice_nat_addr, twice_nat=1)
        self.nat44_add_static_mapping(self.pg6.remote_ip4, self.pg1.remote_ip4,
                                      local_port, external_port,
                                      proto=IP_PROTOS.tcp, out2in_only=1,
                                      self_twice_nat=1, vrf_id=1)
        self.vapi.nat44_interface_add_del_feature(self.pg6.sw_if_index,
                                                  is_inside=0)

        p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
             IP(src=self.pg6.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=12345, dport=external_port))
        self.pg6.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, twice_nat_addr)
            self.assertNotEqual(tcp.sport, 12345)
            post_twice_nat_port = tcp.sport
            self.assertEqual(ip.dst, self.pg6.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
             IP(src=self.pg6.remote_ip4, dst=twice_nat_addr) /
             TCP(sport=local_port, dport=post_twice_nat_port))
        self.pg6.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg1.remote_ip4)
            self.assertEqual(tcp.sport, external_port)
            self.assertEqual(ip.dst, self.pg6.remote_ip4)
            self.assertEqual(tcp.dport, 12345)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    def twice_nat_common(self, self_twice_nat=False, same_pg=False, lb=False,
                         client_id=None):
        twice_nat_addr = '10.0.1.3'

        port_in = 8080
        if lb:
            if not same_pg:
                port_in1 = port_in
                port_in2 = port_in
            else:
                port_in1 = port_in + 1
                port_in2 = port_in + 2

        port_out = 80
        eh_port_out = 4567

        server1 = self.pg0.remote_hosts[0]
        server2 = self.pg0.remote_hosts[1]
        if lb and same_pg:
            server2 = server1
        if not lb:
            server = server1

        pg0 = self.pg0
        if same_pg:
            pg1 = self.pg0
        else:
            pg1 = self.pg1

        eh_translate = ((not self_twice_nat) or (not lb and same_pg) or
                        client_id == 1)

        self.nat44_add_address(self.nat_addr)
        self.nat44_add_address(twice_nat_addr, twice_nat=1)
        if not lb:
            self.nat44_add_static_mapping(pg0.remote_ip4, self.nat_addr,
                                          port_in, port_out,
                                          proto=IP_PROTOS.tcp,
                                          twice_nat=int(not self_twice_nat),
                                          self_twice_nat=int(self_twice_nat))
        else:
            locals = [{'addr': server1.ip4n,
                       'port': port_in1,
                       'probability': 50,
                       'vrf_id': 0},
                      {'addr': server2.ip4n,
                       'port': port_in2,
                       'probability': 50,
                       'vrf_id': 0}]
            out_addr_n = socket.inet_pton(socket.AF_INET, self.nat_addr)
            self.vapi.nat44_add_del_lb_static_mapping(out_addr_n,
                                                      port_out,
                                                      IP_PROTOS.tcp,
                                                      twice_nat=int(
                                                          not self_twice_nat),
                                                      self_twice_nat=int(
                                                          self_twice_nat),
                                                      local_num=len(locals),
                                                      locals=locals)
        self.vapi.nat44_interface_add_del_feature(pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(pg1.sw_if_index,
                                                  is_inside=0)

        if same_pg:
            if not lb:
                client = server
            else:
                assert client_id is not None
                if client_id == 1:
                    client = self.pg0.remote_hosts[0]
                elif client_id == 2:
                    client = self.pg0.remote_hosts[1]
        else:
            client = pg1.remote_hosts[0]
        p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) /
             IP(src=client.ip4, dst=self.nat_addr) /
             TCP(sport=eh_port_out, dport=port_out))
        pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            if lb:
                if ip.dst == server1.ip4:
                    server = server1
                    port_in = port_in1
                else:
                    server = server2
                    port_in = port_in2
            self.assertEqual(ip.dst, server.ip4)
            if lb and same_pg:
                self.assertIn(tcp.dport, [port_in1, port_in2])
            else:
                self.assertEqual(tcp.dport, port_in)
            if eh_translate:
                self.assertEqual(ip.src, twice_nat_addr)
                self.assertNotEqual(tcp.sport, eh_port_out)
            else:
                self.assertEqual(ip.src, client.ip4)
                self.assertEqual(tcp.sport, eh_port_out)
            eh_addr_in = ip.src
            eh_port_in = tcp.sport
            saved_port_in = tcp.dport
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        p = (Ether(src=server.mac, dst=pg0.local_mac) /
             IP(src=server.ip4, dst=eh_addr_in) /
             TCP(sport=saved_port_in, dport=eh_port_in))
        pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, client.ip4)
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(tcp.dport, eh_port_out)
            self.assertEqual(tcp.sport, port_out)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        if eh_translate:
            sessions = self.vapi.nat44_user_session_dump(server.ip4n, 0)
            self.assertEqual(len(sessions), 1)
            self.assertTrue(sessions[0].ext_host_valid)
            self.assertTrue(sessions[0].is_twicenat)
            self.vapi.nat44_del_session(
                sessions[0].inside_ip_address,
                sessions[0].inside_port,
                sessions[0].protocol,
                ext_host_address=sessions[0].ext_host_nat_address,
                ext_host_port=sessions[0].ext_host_nat_port)
            sessions = self.vapi.nat44_user_session_dump(server.ip4n, 0)
            self.assertEqual(len(sessions), 0)

    def test_twice_nat(self):
        """ Twice NAT44 """
        self.twice_nat_common()

    def test_self_twice_nat_positive(self):
        """ Self Twice NAT44 (positive test) """
        self.twice_nat_common(self_twice_nat=True, same_pg=True)

    def test_self_twice_nat_negative(self):
        """ Self Twice NAT44 (negative test) """
        self.twice_nat_common(self_twice_nat=True)

    def test_twice_nat_lb(self):
        """ Twice NAT44 local service load balancing """
        self.twice_nat_common(lb=True)

    def test_self_twice_nat_lb_positive(self):
        """ Self Twice NAT44 local service load balancing (positive test) """
        self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True,
                              client_id=1)

    def test_self_twice_nat_lb_negative(self):
        """ Self Twice NAT44 local service load balancing (negative test) """
        self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True,
                              client_id=2)

    def test_twice_nat_interface_addr(self):
        """ Acquire twice NAT44 addresses from interface """
        self.vapi.nat44_add_del_interface_addr(self.pg3.sw_if_index,
                                               twice_nat=1)

        # no address in NAT pool
        adresses = self.vapi.nat44_address_dump()
        self.assertEqual(0, len(adresses))

        # configure interface address and check NAT address pool
        self.pg3.config_ip4()
        adresses = self.vapi.nat44_address_dump()
        self.assertEqual(1, len(adresses))
        self.assertEqual(adresses[0].ip_address[0:4], self.pg3.local_ip4n)
        self.assertEqual(adresses[0].twice_nat, 1)

        # remove interface address and check NAT address pool
        self.pg3.unconfig_ip4()
        adresses = self.vapi.nat44_address_dump()
        self.assertEqual(0, len(adresses))

    def test_tcp_close(self):
        """ Close TCP session from inside network - output feature """
        self.vapi.nat44_forwarding_enable_disable(1)
        self.nat44_add_address(self.pg1.local_ip4)
        twice_nat_addr = '10.0.1.3'
        service_ip = '192.168.16.150'
        self.nat44_add_address(twice_nat_addr, twice_nat=1)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_output_feature(self.pg1.sw_if_index,
                                                         is_inside=0)
        self.nat44_add_static_mapping(self.pg0.remote_ip4,
                                      service_ip,
                                      80,
                                      80,
                                      proto=IP_PROTOS.tcp,
                                      out2in_only=1,
                                      twice_nat=1)
        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n, 0)
        start_sessnum = len(sessions)

        # SYN packet out->in
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=service_ip) /
             TCP(sport=33898, dport=80, flags="S"))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        tcp_port = p[TCP].sport

        # SYN + ACK packet in->out
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) /
             TCP(sport=80, dport=tcp_port, flags="SA"))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        # ACK packet out->in
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=service_ip) /
             TCP(sport=33898, dport=80, flags="A"))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg0.get_capture(1)

        # FIN packet in -> out
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) /
             TCP(sport=80, dport=tcp_port, flags="FA", seq=100, ack=300))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        # FIN+ACK packet out -> in
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=service_ip) /
             TCP(sport=33898, dport=80, flags="FA", seq=300, ack=101))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg0.get_capture(1)

        # ACK packet in -> out
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) /
             TCP(sport=80, dport=tcp_port, flags="A", seq=101, ack=301))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n,
                                                     0)
        self.assertEqual(len(sessions) - start_sessnum, 0)

    def test_tcp_session_close_in(self):
        """ Close TCP session from inside network """
        self.tcp_port_out = 10505
        self.nat44_add_address(self.nat_addr)
        self.nat44_add_static_mapping(self.pg0.remote_ip4,
                                      self.nat_addr,
                                      self.tcp_port_in,
                                      self.tcp_port_out,
                                      proto=IP_PROTOS.tcp,
                                      twice_nat=1)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n, 0)
        start_sessnum = len(sessions)

        self.initiate_tcp_session(self.pg0, self.pg1)

        # FIN packet in -> out
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                 flags="FA", seq=100, ack=300))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        pkts = []

        # ACK packet out -> in
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                 flags="A", seq=300, ack=101))
        pkts.append(p)

        # FIN packet out -> in
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                 flags="FA", seq=300, ack=101))
        pkts.append(p)

        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg0.get_capture(2)

        # ACK packet in -> out
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                 flags="A", seq=101, ack=301))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n,
                                                     0)
        self.assertEqual(len(sessions) - start_sessnum, 0)

    def test_tcp_session_close_out(self):
        """ Close TCP session from outside network """
        self.tcp_port_out = 10505
        self.nat44_add_address(self.nat_addr)
        self.nat44_add_static_mapping(self.pg0.remote_ip4,
                                      self.nat_addr,
                                      self.tcp_port_in,
                                      self.tcp_port_out,
                                      proto=IP_PROTOS.tcp,
                                      twice_nat=1)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n, 0)
        start_sessnum = len(sessions)

        self.initiate_tcp_session(self.pg0, self.pg1)

        # FIN packet out -> in
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                 flags="FA", seq=100, ack=300))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg0.get_capture(1)

        # FIN+ACK packet in -> out
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                 flags="FA", seq=300, ack=101))

        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        # ACK packet out -> in
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                 flags="A", seq=101, ack=301))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg0.get_capture(1)

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n,
                                                     0)
        self.assertEqual(len(sessions) - start_sessnum, 0)

    def test_tcp_session_close_simultaneous(self):
        """ Close TCP session from inside network """
        self.tcp_port_out = 10505
        self.nat44_add_address(self.nat_addr)
        self.nat44_add_static_mapping(self.pg0.remote_ip4,
                                      self.nat_addr,
                                      self.tcp_port_in,
                                      self.tcp_port_out,
                                      proto=IP_PROTOS.tcp,
                                      twice_nat=1)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n, 0)
        start_sessnum = len(sessions)

        self.initiate_tcp_session(self.pg0, self.pg1)

        # FIN packet in -> out
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                 flags="FA", seq=100, ack=300))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        # FIN packet out -> in
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                 flags="FA", seq=300, ack=100))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg0.get_capture(1)

        # ACK packet in -> out
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                 flags="A", seq=101, ack=301))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        # ACK packet out -> in
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                 flags="A", seq=301, ack=101))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg0.get_capture(1)

        sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4n,
                                                     0)
        self.assertEqual(len(sessions) - start_sessnum, 0)

    def test_one_armed_nat44_static(self):
        """ One armed NAT44 and 1:1 NAPT asymmetrical rule """
        remote_host = self.pg4.remote_hosts[0]
        local_host = self.pg4.remote_hosts[1]
        external_port = 80
        local_port = 8080
        eh_port_in = 0

        self.vapi.nat44_forwarding_enable_disable(1)
        self.nat44_add_address(self.nat_addr, twice_nat=1)
        self.nat44_add_static_mapping(local_host.ip4, self.nat_addr,
                                      local_port, external_port,
                                      proto=IP_PROTOS.tcp, out2in_only=1,
                                      twice_nat=1)
        self.vapi.nat44_interface_add_del_feature(self.pg4.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg4.sw_if_index,
                                                  is_inside=0)

        # from client to service
        p = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) /
             IP(src=remote_host.ip4, dst=self.nat_addr) /
             TCP(sport=12345, dport=external_port))
        self.pg4.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg4.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, local_host.ip4)
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(tcp.dport, local_port)
            self.assertNotEqual(tcp.sport, 12345)
            eh_port_in = tcp.sport
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service back to client
        p = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) /
             IP(src=local_host.ip4, dst=self.nat_addr) /
             TCP(sport=local_port, dport=eh_port_in))
        self.pg4.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg4.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(ip.dst, remote_host.ip4)
            self.assertEqual(tcp.sport, external_port)
            self.assertEqual(tcp.dport, 12345)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    def test_static_with_port_out2(self):
        """ 1:1 NAPT asymmetrical rule """

        external_port = 80
        local_port = 8080

        self.vapi.nat44_forwarding_enable_disable(1)
        self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
                                      local_port, external_port,
                                      proto=IP_PROTOS.tcp, out2in_only=1)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # from client to service
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=12345, dport=external_port))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg0.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # ICMP error
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             ICMP(type=11) / capture[0][IP])
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            self.assertEqual(p[IP].src, self.nat_addr)
            inner = p[IPerror]
            self.assertEqual(inner.dst, self.nat_addr)
            self.assertEqual(inner[TCPerror].dport, external_port)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service back to client
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=local_port, dport=12345))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(tcp.sport, external_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # ICMP error
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             ICMP(type=11) / capture[0][IP])
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            self.assertEqual(p[IP].dst, self.pg0.remote_ip4)
            inner = p[IPerror]
            self.assertEqual(inner.src, self.pg0.remote_ip4)
            self.assertEqual(inner[TCPerror].sport, local_port)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from client to server (no translation)
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) /
             TCP(sport=12346, dport=local_port))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg0.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service back to client (no translation)
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=local_port, dport=12346))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg0.remote_ip4)
            self.assertEqual(tcp.sport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    def test_output_feature(self):
        """ NAT44 interface output feature (in2out postrouting) """
        self.vapi.nat44_forwarding_enable_disable(1)
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_output_feature(self.pg1.sw_if_index,
                                                         is_inside=0)

        # in2out
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture)

        # out2in
        pkts = self.create_stream_out(self.pg1)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

    def test_multiple_vrf(self):
        """ Multiple VRF setup """
        external_addr = '1.2.3.4'
        external_port = 80
        local_port = 8080
        port = 0

        self.vapi.nat44_forwarding_enable_disable(1)
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_output_feature(self.pg1.sw_if_index,
                                                         is_inside=0)
        self.vapi.nat44_interface_add_del_feature(self.pg5.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg5.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat44_interface_add_del_feature(self.pg6.sw_if_index,
                                                  is_inside=0)
        self.nat44_add_static_mapping(self.pg5.remote_ip4, external_addr,
                                      local_port, external_port, vrf_id=1,
                                      proto=IP_PROTOS.tcp, out2in_only=1)
        self.nat44_add_static_mapping(
            self.pg0.remote_ip4, external_sw_if_index=self.pg0.sw_if_index,
            local_port=local_port, vrf_id=0, external_port=external_port,
            proto=IP_PROTOS.tcp, out2in_only=1)

        # from client to service (both VRF1)
        p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
             IP(src=self.pg6.remote_ip4, dst=external_addr) /
             TCP(sport=12345, dport=external_port))
        self.pg6.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg5.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg5.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service back to client (both VRF1)
        p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
             IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4) /
             TCP(sport=local_port, dport=12345))
        self.pg5.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, external_addr)
            self.assertEqual(tcp.sport, external_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # dynamic NAT from VRF1 to VRF0 (output-feature)
        p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
             IP(src=self.pg5.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=2345, dport=22))
        self.pg5.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertNotEqual(tcp.sport, 2345)
            self.assert_packet_checksums_valid(p)
            port = tcp.sport
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             TCP(sport=22, dport=port))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg5.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg5.remote_ip4)
            self.assertEqual(tcp.dport, 2345)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from client VRF1 to service VRF0
        p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
             IP(src=self.pg6.remote_ip4, dst=self.pg0.local_ip4) /
             TCP(sport=12346, dport=external_port))
        self.pg6.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg0.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service VRF0 back to client VRF1
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) /
             TCP(sport=local_port, dport=12346))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg0.local_ip4)
            self.assertEqual(tcp.sport, external_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from client VRF0 to service VRF1
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=external_addr) /
             TCP(sport=12347, dport=external_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg5.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg5.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from service VRF1 back to client VRF0
        p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
             IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4) /
             TCP(sport=local_port, dport=12347))
        self.pg5.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, external_addr)
            self.assertEqual(tcp.sport, external_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from client to server (both VRF1, no translation)
        p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
             IP(src=self.pg6.remote_ip4, dst=self.pg5.remote_ip4) /
             TCP(sport=12348, dport=local_port))
        self.pg6.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg5.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg5.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from server back to client (both VRF1, no translation)
        p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
             IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4) /
             TCP(sport=local_port, dport=12348))
        self.pg5.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg5.remote_ip4)
            self.assertEqual(tcp.sport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from client VRF1 to server VRF0 (no translation)
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) /
             TCP(sport=local_port, dport=12349))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg0.remote_ip4)
            self.assertEqual(tcp.sport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from server VRF0 back to client VRF1 (no translation)
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) /
             TCP(sport=local_port, dport=12349))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg6.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg0.remote_ip4)
            self.assertEqual(tcp.sport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from client VRF0 to server VRF1 (no translation)
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg5.remote_ip4) /
             TCP(sport=12344, dport=local_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg5.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.dst, self.pg5.remote_ip4)
            self.assertEqual(tcp.dport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # from server VRF1 back to client VRF0 (no translation)
        p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
             IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4) /
             TCP(sport=local_port, dport=12344))
        self.pg5.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg5.remote_ip4)
            self.assertEqual(tcp.sport, local_port)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_session_timeout(self):
        """ NAT44 session timeouts """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat_set_timeouts(icmp=5)

        max_sessions = 1000
        pkts = []
        for i in range(0, max_sessions):
            src = "10.10.%u.%u" % ((i & 0xFF00) >> 8, i & 0xFF)
            p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                 IP(src=src, dst=self.pg1.remote_ip4) /
                 ICMP(id=1025, type='echo-request'))
            pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(max_sessions)

        sleep(10)

        pkts = []
        for i in range(0, max_sessions):
            src = "10.11.%u.%u" % ((i & 0xFF00) >> 8, i & 0xFF)
            p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                 IP(src=src, dst=self.pg1.remote_ip4) /
                 ICMP(id=1026, type='echo-request'))
            pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(max_sessions)

        nsessions = 0
        users = self.vapi.nat44_user_dump()
        for user in users:
            nsessions = nsessions + user.nsessions
        self.assertLess(nsessions, 2 * max_sessions)

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_session_rst_timeout(self):
        """ NAT44 session RST timeouts """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.nat_set_timeouts(tcp_transitory=5)

        self.initiate_tcp_session(self.pg0, self.pg1)
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                 flags="R"))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        sleep(6)

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in + 1, dport=self.tcp_external_port + 1,
                 flags="S"))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

        nsessions = 0
        users = self.vapi.nat44_user_dump()
        self.assertEqual(len(users), 1)
        self.assertEqual(users[0].ip_address, self.pg0.remote_ip4n)
        self.assertEqual(users[0].nsessions, 1)

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_session_limit_per_user(self):
        """ Maximum sessions per user limit """
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.set_ipfix_exporter(collector_address=self.pg2.remote_ip4n,
                                     src_address=self.pg2.local_ip4n,
                                     path_mtu=512,
                                     template_interval=10)
        self.vapi.nat_set_timeouts(udp=5)

        # get maximum number of translations per user
        nat44_config = self.vapi.nat_show_config()

        pkts = []
        for port in range(0, nat44_config.max_translations_per_user):
            p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
                 IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
                 UDP(sport=1025 + port, dport=1025 + port))
            pkts.append(p)

        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))

        self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
                                           src_port=self.ipfix_src_port)

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             UDP(sport=3001, dport=3002))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.assert_nothing_captured()

        # verify IPFIX logging
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        sleep(1)
        capture = self.pg2.get_capture(10)
        ipfix = IPFIXDecoder()
        # first load template
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            if p.haslayer(Template):
                ipfix.add_template(p.getlayer(Template))
        # verify events in data set
        for p in capture:
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                self.verify_ipfix_max_entries_per_user(
                    data,
                    nat44_config.max_translations_per_user,
                    self.pg0.remote_ip4n)

        sleep(6)
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             UDP(sport=3001, dport=3002))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(1)

    def test_syslog_sess(self):
        """ Test syslog session creation and deletion """
        self.vapi.syslog_set_filter(SYSLOG_SEVERITY.INFO)
        self.vapi.syslog_set_sender(self.pg2.local_ip4n, self.pg2.remote_ip4n)
        self.nat44_add_address(self.nat_addr)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        self.tcp_port_out = capture[0][TCP].sport
        capture = self.pg2.get_capture(1)
        self.verify_syslog_sess(capture[0][Raw].load)

        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.nat44_add_address(self.nat_addr, is_add=0)
        capture = self.pg2.get_capture(1)
        self.verify_syslog_sess(capture[0][Raw].load, False)

    def tearDown(self):
        super(TestNAT44EndpointDependent, self).tearDown()
        if not self.vpp_dead:
            self.logger.info(self.vapi.cli("show nat44 addresses"))
            self.logger.info(self.vapi.cli("show nat44 interfaces"))
            self.logger.info(self.vapi.cli("show nat44 static mappings"))
            self.logger.info(self.vapi.cli("show nat44 interface address"))
            self.logger.info(self.vapi.cli("show nat44 sessions detail"))
            self.logger.info(self.vapi.cli("show nat44 hash tables detail"))
            self.logger.info(self.vapi.cli("show nat timeouts"))
            self.clear_nat44()
            self.vapi.cli("clear logging")


class TestNAT44Out2InDPO(MethodHolder):
    """ NAT44 Test Cases using out2in DPO """

    @classmethod
    def setUpConstants(cls):
        super(TestNAT44Out2InDPO, cls).setUpConstants()
        cls.vpp_cmdline.extend(["nat", "{", "out2in dpo", "}"])

    @classmethod
    def setUpClass(cls):
        super(TestNAT44Out2InDPO, cls).setUpClass()
        cls.vapi.cli("set log class nat level debug")

        try:
            cls.tcp_port_in = 6303
            cls.tcp_port_out = 6303
            cls.udp_port_in = 6304
            cls.udp_port_out = 6304
            cls.icmp_id_in = 6305
            cls.icmp_id_out = 6305
            cls.nat_addr = '10.0.0.3'
            cls.nat_addr_n = socket.inet_pton(socket.AF_INET, cls.nat_addr)
            cls.dst_ip4 = '192.168.70.1'

            cls.create_pg_interfaces(range(2))

            cls.pg0.admin_up()
            cls.pg0.config_ip4()
            cls.pg0.resolve_arp()

            cls.pg1.admin_up()
            cls.pg1.config_ip6()
            cls.pg1.resolve_ndp()

            cls.vapi.ip_add_del_route(dst_address=b'\x00' * 16,
                                      dst_address_length=0,
                                      next_hop_address=cls.pg1.remote_ip6n,
                                      next_hop_sw_if_index=cls.pg1.sw_if_index,
                                      is_ipv6=True)

        except Exception:
            super(TestNAT44Out2InDPO, cls).tearDownClass()
            raise

    def configure_xlat(self):
        self.dst_ip6_pfx = '1:2:3::'
        self.dst_ip6_pfx_n = socket.inet_pton(socket.AF_INET6,
                                              self.dst_ip6_pfx)
        self.dst_ip6_pfx_len = 96
        self.src_ip6_pfx = '4:5:6::'
        self.src_ip6_pfx_n = socket.inet_pton(socket.AF_INET6,
                                              self.src_ip6_pfx)
        self.src_ip6_pfx_len = 96
        self.vapi.map_add_domain(self.dst_ip6_pfx_n, self.dst_ip6_pfx_len,
                                 self.src_ip6_pfx_n, self.src_ip6_pfx_len,
                                 '\x00\x00\x00\x00', 0)

    @unittest.skip('Temporary disabled')
    def test_464xlat_ce(self):
        """ Test 464XLAT CE with NAT44 """

        nat_config = self.vapi.nat_show_config()
        self.assertEqual(1, nat_config.out2in_dpo)

        self.configure_xlat()

        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_add_del_address_range(self.nat_addr_n, self.nat_addr_n)

        out_src_ip6 = self.compose_ip6(self.dst_ip4, self.dst_ip6_pfx,
                                       self.dst_ip6_pfx_len)
        out_dst_ip6 = self.compose_ip6(self.nat_addr, self.src_ip6_pfx,
                                       self.src_ip6_pfx_len)

        try:
            pkts = self.create_stream_in(self.pg0, self.pg1, self.dst_ip4)
            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg1.get_capture(len(pkts))
            self.verify_capture_out_ip6(capture, nat_ip=out_dst_ip6,
                                        dst_ip=out_src_ip6)

            pkts = self.create_stream_out_ip6(self.pg1, out_src_ip6,
                                              out_dst_ip6)
            self.pg1.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            capture = self.pg0.get_capture(len(pkts))
            self.verify_capture_in(capture, self.pg0)
        finally:
            self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index,
                                                      is_add=0)
            self.vapi.nat44_add_del_address_range(self.nat_addr_n,
                                                  self.nat_addr_n, is_add=0)

    @unittest.skip('Temporary disabled')
    def test_464xlat_ce_no_nat(self):
        """ Test 464XLAT CE without NAT44 """

        self.configure_xlat()

        out_src_ip6 = self.compose_ip6(self.dst_ip4, self.dst_ip6_pfx,
                                       self.dst_ip6_pfx_len)
        out_dst_ip6 = self.compose_ip6(self.pg0.remote_ip4, self.src_ip6_pfx,
                                       self.src_ip6_pfx_len)

        pkts = self.create_stream_in(self.pg0, self.pg1, self.dst_ip4)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out_ip6(capture, dst_ip=out_src_ip6,
                                    nat_ip=out_dst_ip6, same_port=True)

        pkts = self.create_stream_out_ip6(self.pg1, out_src_ip6, out_dst_ip6)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)


class TestDeterministicNAT(MethodHolder):
    """ Deterministic NAT Test Cases """

    @classmethod
    def setUpConstants(cls):
        super(TestDeterministicNAT, cls).setUpConstants()
        cls.vpp_cmdline.extend(["nat", "{", "deterministic", "}"])

    @classmethod
    def setUpClass(cls):
        super(TestDeterministicNAT, cls).setUpClass()
        cls.vapi.cli("set log class nat level debug")

        try:
            cls.tcp_port_in = 6303
            cls.tcp_external_port = 6303
            cls.udp_port_in = 6304
            cls.udp_external_port = 6304
            cls.icmp_id_in = 6305
            cls.nat_addr = '10.0.0.3'

            cls.create_pg_interfaces(range(3))
            cls.interfaces = list(cls.pg_interfaces)

            for i in cls.interfaces:
                i.admin_up()
                i.config_ip4()
                i.resolve_arp()

            cls.pg0.generate_remote_hosts(2)
            cls.pg0.configure_ipv4_neighbors()

        except Exception:
            super(TestDeterministicNAT, cls).tearDownClass()
            raise

    def create_stream_in(self, in_if, out_if, ttl=64):
        """
        Create packet stream for inside network

        :param in_if: Inside interface
        :param out_if: Outside interface
        :param ttl: TTL of generated packets
        """
        pkts = []
        # TCP
        p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
             IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port))
        pkts.append(p)

        # UDP
        p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
             IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) /
             UDP(sport=self.udp_port_in, dport=self.udp_external_port))
        pkts.append(p)

        # ICMP
        p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
             IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) /
             ICMP(id=self.icmp_id_in, type='echo-request'))
        pkts.append(p)

        return pkts

    def create_stream_out(self, out_if, dst_ip=None, ttl=64):
        """
        Create packet stream for outside network

        :param out_if: Outside interface
        :param dst_ip: Destination IP address (Default use global NAT address)
        :param ttl: TTL of generated packets
        """
        if dst_ip is None:
            dst_ip = self.nat_addr
        pkts = []
        # TCP
        p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
             IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
             TCP(dport=self.tcp_port_out, sport=self.tcp_external_port))
        pkts.append(p)

        # UDP
        p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
             IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
             UDP(dport=self.udp_port_out, sport=self.udp_external_port))
        pkts.append(p)

        # ICMP
        p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
             IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
             ICMP(id=self.icmp_external_id, type='echo-reply'))
        pkts.append(p)

        return pkts

    def verify_capture_out(self, capture, nat_ip=None):
        """
        Verify captured packets on outside network

        :param capture: Captured packets
        :param nat_ip: Translated IP address (Default use global NAT address)
        :param same_port: Sorce port number is not translated (Default False)
        """
        if nat_ip is None:
            nat_ip = self.nat_addr
        for packet in capture:
            try:
                self.assertEqual(packet[IP].src, nat_ip)
                if packet.haslayer(TCP):
                    self.tcp_port_out = packet[TCP].sport
                elif packet.haslayer(UDP):
                    self.udp_port_out = packet[UDP].sport
                else:
                    self.icmp_external_id = packet[ICMP].id
            except:
                self.logger.error(ppp("Unexpected or invalid packet "
                                      "(outside network):", packet))
                raise

    def test_deterministic_mode(self):
        """ NAT plugin run deterministic mode """
        in_addr = '172.16.255.0'
        out_addr = '172.17.255.50'
        in_addr_t = '172.16.255.20'
        in_addr_n = socket.inet_aton(in_addr)
        out_addr_n = socket.inet_aton(out_addr)
        in_addr_t_n = socket.inet_aton(in_addr_t)
        in_plen = 24
        out_plen = 32

        nat_config = self.vapi.nat_show_config()
        self.assertEqual(1, nat_config.deterministic)

        self.vapi.nat_det_add_del_map(in_addr_n, in_plen, out_addr_n, out_plen)

        rep1 = self.vapi.nat_det_forward(in_addr_t_n)
        self.assertEqual(rep1.out_addr[:4], out_addr_n)
        rep2 = self.vapi.nat_det_reverse(out_addr_n, rep1.out_port_hi)
        self.assertEqual(rep2.in_addr[:4], in_addr_t_n)

        deterministic_mappings = self.vapi.nat_det_map_dump()
        self.assertEqual(len(deterministic_mappings), 1)
        dsm = deterministic_mappings[0]
        self.assertEqual(in_addr_n, dsm.in_addr[:4])
        self.assertEqual(in_plen, dsm.in_plen)
        self.assertEqual(out_addr_n, dsm.out_addr[:4])
        self.assertEqual(out_plen, dsm.out_plen)

        self.clear_nat_det()
        deterministic_mappings = self.vapi.nat_det_map_dump()
        self.assertEqual(len(deterministic_mappings), 0)

    def test_set_timeouts(self):
        """ Set deterministic NAT timeouts """
        timeouts_before = self.vapi.nat_get_timeouts()

        self.vapi.nat_set_timeouts(timeouts_before.udp + 10,
                                   timeouts_before.tcp_established + 10,
                                   timeouts_before.tcp_transitory + 10,
                                   timeouts_before.icmp + 10)

        timeouts_after = self.vapi.nat_get_timeouts()

        self.assertNotEqual(timeouts_before.udp, timeouts_after.udp)
        self.assertNotEqual(timeouts_before.icmp, timeouts_after.icmp)
        self.assertNotEqual(timeouts_before.tcp_established,
                            timeouts_after.tcp_established)
        self.assertNotEqual(timeouts_before.tcp_transitory,
                            timeouts_after.tcp_transitory)

    def test_det_in(self):
        """ Deterministic NAT translation test (TCP, UDP, ICMP) """

        nat_ip = "10.0.0.10"

        self.vapi.nat_det_add_del_map(self.pg0.remote_ip4n,
                                      32,
                                      socket.inet_aton(nat_ip),
                                      32)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # in2out
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip)

        # out2in
        pkts = self.create_stream_out(self.pg1, nat_ip)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in(capture, self.pg0)

        # session dump test
        sessions = self.vapi.nat_det_session_dump(self.pg0.remote_ip4n)
        self.assertEqual(len(sessions), 3)

        # TCP session
        s = sessions[0]
        self.assertEqual(s.ext_addr[:4], self.pg1.remote_ip4n)
        self.assertEqual(s.in_port, self.tcp_port_in)
        self.assertEqual(s.out_port, self.tcp_port_out)
        self.assertEqual(s.ext_port, self.tcp_external_port)

        # UDP session
        s = sessions[1]
        self.assertEqual(s.ext_addr[:4], self.pg1.remote_ip4n)
        self.assertEqual(s.in_port, self.udp_port_in)
        self.assertEqual(s.out_port, self.udp_port_out)
        self.assertEqual(s.ext_port, self.udp_external_port)

        # ICMP session
        s = sessions[2]
        self.assertEqual(s.ext_addr[:4], self.pg1.remote_ip4n)
        self.assertEqual(s.in_port, self.icmp_id_in)
        self.assertEqual(s.out_port, self.icmp_external_id)

    def test_multiple_users(self):
        """ Deterministic NAT multiple users """

        nat_ip = "10.0.0.10"
        port_in = 80
        external_port = 6303

        host0 = self.pg0.remote_hosts[0]
        host1 = self.pg0.remote_hosts[1]

        self.vapi.nat_det_add_del_map(host0.ip4n,
                                      24,
                                      socket.inet_aton(nat_ip),
                                      32)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        # host0 to out
        p = (Ether(src=host0.mac, dst=self.pg0.local_mac) /
             IP(src=host0.ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=port_in, dport=external_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, nat_ip)
            self.assertEqual(ip.dst, self.pg1.remote_ip4)
            self.assertEqual(tcp.dport, external_port)
            port_out0 = tcp.sport
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # host1 to out
        p = (Ether(src=host1.mac, dst=self.pg0.local_mac) /
             IP(src=host1.ip4, dst=self.pg1.remote_ip4) /
             TCP(sport=port_in, dport=external_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, nat_ip)
            self.assertEqual(ip.dst, self.pg1.remote_ip4)
            self.assertEqual(tcp.dport, external_port)
            port_out1 = tcp.sport
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        dms = self.vapi.nat_det_map_dump()
        self.assertEqual(1, len(dms))
        self.assertEqual(2, dms[0].ses_num)

        # out to host0
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=nat_ip) /
             TCP(sport=external_port, dport=port_out0))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg1.remote_ip4)
            self.assertEqual(ip.dst, host0.ip4)
            self.assertEqual(tcp.dport, port_in)
            self.assertEqual(tcp.sport, external_port)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # out to host1
        p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
             IP(src=self.pg1.remote_ip4, dst=nat_ip) /
             TCP(sport=external_port, dport=port_out1))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.pg1.remote_ip4)
            self.assertEqual(ip.dst, host1.ip4)
            self.assertEqual(tcp.dport, port_in)
            self.assertEqual(tcp.sport, external_port)
        except:
            self.logger.error(ppp("Unexpected or invalid packet", p))
            raise

        # session close api test
        self.vapi.nat_det_close_session_out(socket.inet_aton(nat_ip),
                                            port_out1,
                                            self.pg1.remote_ip4n,
                                            external_port)
        dms = self.vapi.nat_det_map_dump()
        self.assertEqual(dms[0].ses_num, 1)

        self.vapi.nat_det_close_session_in(host0.ip4n,
                                           port_in,
                                           self.pg1.remote_ip4n,
                                           external_port)
        dms = self.vapi.nat_det_map_dump()
        self.assertEqual(dms[0].ses_num, 0)

    def test_tcp_session_close_detection_in(self):
        """ Deterministic NAT TCP session close from inside network """
        self.vapi.nat_det_add_del_map(self.pg0.remote_ip4n,
                                      32,
                                      socket.inet_aton(self.nat_addr),
                                      32)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        self.initiate_tcp_session(self.pg0, self.pg1)

        # close the session from inside
        try:
            # FIN packet in -> out
            p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
                 IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
                 TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                     flags="F"))
            self.pg0.add_stream(p)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            self.pg1.get_capture(1)

            pkts = []

            # ACK packet out -> in
            p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
                 IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
                 TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                     flags="A"))
            pkts.append(p)

            # FIN packet out -> in
            p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
                 IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
                 TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                     flags="F"))
            pkts.append(p)

            self.pg1.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            self.pg0.get_capture(2)

            # ACK packet in -> out
            p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
                 IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
                 TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                     flags="A"))
            self.pg0.add_stream(p)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            self.pg1.get_capture(1)

            # Check if deterministic NAT44 closed the session
            dms = self.vapi.nat_det_map_dump()
            self.assertEqual(0, dms[0].ses_num)
        except:
            self.logger.error("TCP session termination failed")
            raise

    def test_tcp_session_close_detection_out(self):
        """ Deterministic NAT TCP session close from outside network """
        self.vapi.nat_det_add_del_map(self.pg0.remote_ip4n,
                                      32,
                                      socket.inet_aton(self.nat_addr),
                                      32)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        self.initiate_tcp_session(self.pg0, self.pg1)

        # close the session from outside
        try:
            # FIN packet out -> in
            p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
                 IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
                 TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                     flags="F"))
            self.pg1.add_stream(p)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            self.pg0.get_capture(1)

            pkts = []

            # ACK packet in -> out
            p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
                 IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
                 TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                     flags="A"))
            pkts.append(p)

            # ACK packet in -> out
            p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
                 IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
                 TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
                     flags="F"))
            pkts.append(p)

            self.pg0.add_stream(pkts)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            self.pg1.get_capture(2)

            # ACK packet out -> in
            p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
                 IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
                 TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
                     flags="A"))
            self.pg1.add_stream(p)
            self.pg_enable_capture(self.pg_interfaces)
            self.pg_start()
            self.pg0.get_capture(1)

            # Check if deterministic NAT44 closed the session
            dms = self.vapi.nat_det_map_dump()
            self.assertEqual(0, dms[0].ses_num)
        except:
            self.logger.error("TCP session termination failed")
            raise

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_session_timeout(self):
        """ Deterministic NAT session timeouts """
        self.vapi.nat_det_add_del_map(self.pg0.remote_ip4n,
                                      32,
                                      socket.inet_aton(self.nat_addr),
                                      32)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)

        self.initiate_tcp_session(self.pg0, self.pg1)
        self.vapi.nat_set_timeouts(5, 5, 5, 5)
        pkts = self.create_stream_in(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        sleep(15)

        dms = self.vapi.nat_det_map_dump()
        self.assertEqual(0, dms[0].ses_num)

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_session_limit_per_user(self):
        """ Deterministic NAT maximum sessions per user limit """
        self.vapi.nat_det_add_del_map(self.pg0.remote_ip4n,
                                      32,
                                      socket.inet_aton(self.nat_addr),
                                      32)
        self.vapi.nat44_interface_add_del_feature(self.pg0.sw_if_index)
        self.vapi.nat44_interface_add_del_feature(self.pg1.sw_if_index,
                                                  is_inside=0)
        self.vapi.set_ipfix_exporter(collector_address=self.pg2.remote_ip4n,
                                     src_address=self.pg2.local_ip4n,
                                     path_mtu=512,
                                     template_interval=10)
        self.vapi.nat_ipfix_enable_disable()

        pkts = []
        for port in range(1025, 2025):
            p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
                 IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
                 UDP(sport=port, dport=port))
            pkts.append(p)

        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
             UDP(sport=3001, dport=3002))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.assert_nothing_captured()

        # verify ICMP error packet
        capture = self.pg0.get_capture(1)
        p = capture[0]
        self.assertTrue(p.haslayer(ICMP))
        icmp = p[ICMP]
        self.assertEqual(icmp.type, 3)
        self.assertEqual(icmp.code, 1)
        self.assertTrue(icmp.haslayer(IPerror))
        inner_ip = icmp[IPerror]
        self.assertEqual(inner_ip[UDPerror].sport, 3001)
        self.assertEqual(inner_ip[UDPerror].dport, 3002)

        dms = self.vapi.nat_det_map_dump()

        self.assertEqual(1000, dms[0].ses_num)

        # verify IPFIX logging
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        sleep(1)
        capture = self.pg2.get_capture(2)
        ipfix = IPFIXDecoder()
        # first load template
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            if p.haslayer(Template):
                ipfix.add_template(p.getlayer(Template))
        # verify events in data set
        for p in capture:
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                self.verify_ipfix_max_entries_per_user(data,
                                                       1000,
                                                       self.pg0.remote_ip4n)

    def clear_nat_det(self):
        """
        Clear deterministic NAT configuration.
        """
        self.vapi.nat_ipfix_enable_disable(enable=0)
        self.vapi.nat_set_timeouts()
        deterministic_mappings = self.vapi.nat_det_map_dump()
        for dsm in deterministic_mappings:
            self.vapi.nat_det_add_del_map(dsm.in_addr,
                                          dsm.in_plen,
                                          dsm.out_addr,
                                          dsm.out_plen,
                                          is_add=0)

        interfaces = self.vapi.nat44_interface_dump()
        for intf in interfaces:
            self.vapi.nat44_interface_add_del_feature(intf.sw_if_index,
                                                      intf.is_inside,
                                                      is_add=0)

    def tearDown(self):
        super(TestDeterministicNAT, self).tearDown()
        if not self.vpp_dead:
            self.logger.info(self.vapi.cli("show nat44 interfaces"))
            self.logger.info(self.vapi.cli("show nat timeouts"))
            self.logger.info(
                self.vapi.cli("show nat44 deterministic mappings"))
            self.logger.info(
                self.vapi.cli("show nat44 deterministic sessions"))
            self.clear_nat_det()


class TestNAT64(MethodHolder):
    """ NAT64 Test Cases """

    @classmethod
    def setUpConstants(cls):
        super(TestNAT64, cls).setUpConstants()
        cls.vpp_cmdline.extend(["nat", "{", "nat64 bib hash buckets 128",
                                "nat64 st hash buckets 256", "}"])

    @classmethod
    def setUpClass(cls):
        super(TestNAT64, cls).setUpClass()

        try:
            cls.tcp_port_in = 6303
            cls.tcp_port_out = 6303
            cls.udp_port_in = 6304
            cls.udp_port_out = 6304
            cls.icmp_id_in = 6305
            cls.icmp_id_out = 6305
            cls.tcp_external_port = 80
            cls.nat_addr = '10.0.0.3'
            cls.nat_addr_n = socket.inet_pton(socket.AF_INET, cls.nat_addr)
            cls.vrf1_id = 10
            cls.vrf1_nat_addr = '10.0.10.3'
            cls.vrf1_nat_addr_n = socket.inet_pton(socket.AF_INET,
                                                   cls.vrf1_nat_addr)
            cls.ipfix_src_port = 4739
            cls.ipfix_domain_id = 1

            cls.create_pg_interfaces(range(6))
            cls.ip6_interfaces = list(cls.pg_interfaces[0:1])
            cls.ip6_interfaces.append(cls.pg_interfaces[2])
            cls.ip4_interfaces = list(cls.pg_interfaces[1:2])

            cls.vapi.ip_table_add_del(is_ipv6=1, is_add=1,
                                      table_id=cls.vrf1_id)

            cls.pg_interfaces[2].set_table_ip6(cls.vrf1_id)

            cls.pg0.generate_remote_hosts(2)

            for i in cls.ip6_interfaces:
                i.admin_up()
                i.config_ip6()
                i.configure_ipv6_neighbors()

            for i in cls.ip4_interfaces:
                i.admin_up()
                i.config_ip4()
                i.resolve_arp()

            cls.pg3.admin_up()
            cls.pg3.config_ip4()
            cls.pg3.resolve_arp()
            cls.pg3.config_ip6()
            cls.pg3.configure_ipv6_neighbors()

            cls.pg5.admin_up()
            cls.pg5.config_ip6()

        except Exception:
            super(TestNAT64, cls).tearDownClass()
            raise

    def test_nat64_inside_interface_handles_neighbor_advertisement(self):
        """ NAT64 inside interface handles Neighbor Advertisement """

        self.vapi.nat64_add_del_interface(self.pg5.sw_if_index)

        # Try to send ping
        ping = (Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac) /
                IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6) /
                ICMPv6EchoRequest())
        pkts = [ping]
        self.pg5.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Wait for Neighbor Solicitation
        capture = self.pg5.get_capture(len(pkts))
        packet = capture[0]
        try:
            self.assertEqual(packet[IPv6].src, self.pg5.local_ip6)
            self.assertEqual(packet.haslayer(ICMPv6ND_NS), 1)
            tgt = packet[ICMPv6ND_NS].tgt
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

        # Send Neighbor Advertisement
        p = (Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac) /
             IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6) /
             ICMPv6ND_NA(tgt=tgt) /
             ICMPv6NDOptDstLLAddr(lladdr=self.pg5.remote_mac))
        pkts = [p]
        self.pg5.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Try to send ping again
        pkts = [ping]
        self.pg5.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Wait for ping reply
        capture = self.pg5.get_capture(len(pkts))
        packet = capture[0]
        try:
            self.assertEqual(packet[IPv6].src, self.pg5.local_ip6)
            self.assertEqual(packet[IPv6].dst, self.pg5.remote_ip6)
            self.assertEqual(packet.haslayer(ICMPv6EchoReply), 1)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

    def test_pool(self):
        """ Add/delete address to NAT64 pool """
        nat_addr = socket.inet_pton(socket.AF_INET, '1.2.3.4')

        self.vapi.nat64_add_del_pool_addr_range(nat_addr, nat_addr)

        addresses = self.vapi.nat64_pool_addr_dump()
        self.assertEqual(len(addresses), 1)
        self.assertEqual(addresses[0].address, nat_addr)

        self.vapi.nat64_add_del_pool_addr_range(nat_addr, nat_addr, is_add=0)

        addresses = self.vapi.nat64_pool_addr_dump()
        self.assertEqual(len(addresses), 0)

    def test_interface(self):
        """ Enable/disable NAT64 feature on the interface """
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        interfaces = self.vapi.nat64_interface_dump()
        self.assertEqual(len(interfaces), 2)
        pg0_found = False
        pg1_found = False
        for intf in interfaces:
            if intf.sw_if_index == self.pg0.sw_if_index:
                self.assertEqual(intf.is_inside, 1)
                pg0_found = True
            elif intf.sw_if_index == self.pg1.sw_if_index:
                self.assertEqual(intf.is_inside, 0)
                pg1_found = True
        self.assertTrue(pg0_found)
        self.assertTrue(pg1_found)

        features = self.vapi.cli("show interface features pg0")
        self.assertIn('nat64-in2out', features)
        features = self.vapi.cli("show interface features pg1")
        self.assertIn('nat64-out2in', features)

        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index, is_add=0)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_add=0)

        interfaces = self.vapi.nat64_interface_dump()
        self.assertEqual(len(interfaces), 0)

    def test_static_bib(self):
        """ Add/delete static BIB entry """
        in_addr = socket.inet_pton(socket.AF_INET6,
                                   '2001:db8:85a3::8a2e:370:7334')
        out_addr = socket.inet_pton(socket.AF_INET, '10.1.1.3')
        in_port = 1234
        out_port = 5678
        proto = IP_PROTOS.tcp

        self.vapi.nat64_add_del_static_bib(in_addr,
                                           out_addr,
                                           in_port,
                                           out_port,
                                           proto)
        bib = self.vapi.nat64_bib_dump(IP_PROTOS.tcp)
        static_bib_num = 0
        for bibe in bib:
            if bibe.is_static:
                static_bib_num += 1
                self.assertEqual(bibe.i_addr, in_addr)
                self.assertEqual(bibe.o_addr, out_addr)
                self.assertEqual(bibe.i_port, in_port)
                self.assertEqual(bibe.o_port, out_port)
        self.assertEqual(static_bib_num, 1)
        bibs = self.statistics.get_counter('/nat64/total-bibs')
        self.assertEqual(bibs[0][0], 1)

        self.vapi.nat64_add_del_static_bib(in_addr,
                                           out_addr,
                                           in_port,
                                           out_port,
                                           proto,
                                           is_add=0)
        bib = self.vapi.nat64_bib_dump(IP_PROTOS.tcp)
        static_bib_num = 0
        for bibe in bib:
            if bibe.is_static:
                static_bib_num += 1
        self.assertEqual(static_bib_num, 0)
        bibs = self.statistics.get_counter('/nat64/total-bibs')
        self.assertEqual(bibs[0][0], 0)

    def test_set_timeouts(self):
        """ Set NAT64 timeouts """
        # verify default values
        timeouts = self.vapi.nat_get_timeouts()
        self.assertEqual(timeouts.udp, 300)
        self.assertEqual(timeouts.icmp, 60)
        self.assertEqual(timeouts.tcp_transitory, 240)
        self.assertEqual(timeouts.tcp_established, 7440)

        # set and verify custom values
        self.vapi.nat_set_timeouts(udp=200, icmp=30, tcp_transitory=250,
                                   tcp_established=7450)
        timeouts = self.vapi.nat_get_timeouts()
        self.assertEqual(timeouts.udp, 200)
        self.assertEqual(timeouts.icmp, 30)
        self.assertEqual(timeouts.tcp_transitory, 250)
        self.assertEqual(timeouts.tcp_established, 7450)

    def test_dynamic(self):
        """ NAT64 dynamic translation test """
        self.tcp_port_in = 6303
        self.udp_port_in = 6304
        self.icmp_id_in = 6305

        ses_num_start = self.nat64_get_ses_num()

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        # in2out
        tcpn = self.statistics.get_counter('/err/nat64-in2out/TCP packets')
        udpn = self.statistics.get_counter('/err/nat64-in2out/UDP packets')
        icmpn = self.statistics.get_counter('/err/nat64-in2out/ICMP packets')
        totaln = self.statistics.get_counter(
            '/err/nat64-in2out/good in2out packets processed')

        pkts = self.create_stream_in_ip6(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip=self.nat_addr,
                                dst_ip=self.pg1.remote_ip4)

        err = self.statistics.get_counter('/err/nat64-in2out/TCP packets')
        self.assertEqual(err - tcpn, 1)
        err = self.statistics.get_counter('/err/nat64-in2out/UDP packets')
        self.assertEqual(err - udpn, 1)
        err = self.statistics.get_counter('/err/nat64-in2out/ICMP packets')
        self.assertEqual(err - icmpn, 1)
        err = self.statistics.get_counter(
            '/err/nat64-in2out/good in2out packets processed')
        self.assertEqual(err - totaln, 3)

        # out2in
        tcpn = self.statistics.get_counter('/err/nat64-out2in/TCP packets')
        udpn = self.statistics.get_counter('/err/nat64-out2in/UDP packets')
        icmpn = self.statistics.get_counter('/err/nat64-out2in/ICMP packets')
        totaln = self.statistics.get_counter(
            '/err/nat64-out2in/good out2in packets processed')

        pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        ip = IPv6(src=''.join(['64:ff9b::', self.pg1.remote_ip4]))
        self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg0.remote_ip6)

        err = self.statistics.get_counter('/err/nat64-out2in/TCP packets')
        self.assertEqual(err - tcpn, 1)
        err = self.statistics.get_counter('/err/nat64-out2in/UDP packets')
        self.assertEqual(err - udpn, 1)
        err = self.statistics.get_counter('/err/nat64-out2in/ICMP packets')
        self.assertEqual(err - icmpn, 1)
        err = self.statistics.get_counter(
            '/err/nat64-out2in/good out2in packets processed')
        self.assertEqual(err - totaln, 3)

        bibs = self.statistics.get_counter('/nat64/total-bibs')
        self.assertEqual(bibs[0][0], 3)
        sessions = self.statistics.get_counter('/nat64/total-sessions')
        self.assertEqual(sessions[0][0], 3)

        # in2out
        pkts = self.create_stream_in_ip6(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip=self.nat_addr,
                                dst_ip=self.pg1.remote_ip4)

        # out2in
        pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg0.remote_ip6)

        ses_num_end = self.nat64_get_ses_num()

        self.assertEqual(ses_num_end - ses_num_start, 3)

        # tenant with specific VRF
        self.vapi.nat64_add_del_pool_addr_range(self.vrf1_nat_addr_n,
                                                self.vrf1_nat_addr_n,
                                                vrf_id=self.vrf1_id)
        self.vapi.nat64_add_del_interface(self.pg2.sw_if_index)

        pkts = self.create_stream_in_ip6(self.pg2, self.pg1)
        self.pg2.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip=self.vrf1_nat_addr,
                                dst_ip=self.pg1.remote_ip4)

        pkts = self.create_stream_out(self.pg1, dst_ip=self.vrf1_nat_addr)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg2.get_capture(len(pkts))
        self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg2.remote_ip6)

    def test_static(self):
        """ NAT64 static translation test """
        self.tcp_port_in = 60303
        self.udp_port_in = 60304
        self.icmp_id_in = 60305
        self.tcp_port_out = 60303
        self.udp_port_out = 60304
        self.icmp_id_out = 60305

        ses_num_start = self.nat64_get_ses_num()

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        self.vapi.nat64_add_del_static_bib(self.pg0.remote_ip6n,
                                           self.nat_addr_n,
                                           self.tcp_port_in,
                                           self.tcp_port_out,
                                           IP_PROTOS.tcp)
        self.vapi.nat64_add_del_static_bib(self.pg0.remote_ip6n,
                                           self.nat_addr_n,
                                           self.udp_port_in,
                                           self.udp_port_out,
                                           IP_PROTOS.udp)
        self.vapi.nat64_add_del_static_bib(self.pg0.remote_ip6n,
                                           self.nat_addr_n,
                                           self.icmp_id_in,
                                           self.icmp_id_out,
                                           IP_PROTOS.icmp)

        # in2out
        pkts = self.create_stream_in_ip6(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip=self.nat_addr,
                                dst_ip=self.pg1.remote_ip4, same_port=True)

        # out2in
        pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        ip = IPv6(src=''.join(['64:ff9b::', self.pg1.remote_ip4]))
        self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg0.remote_ip6)

        ses_num_end = self.nat64_get_ses_num()

        self.assertEqual(ses_num_end - ses_num_start, 3)

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_session_timeout(self):
        """ NAT64 session timeout """
        self.icmp_id_in = 1234
        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)
        self.vapi.nat_set_timeouts(icmp=5, tcp_transitory=5, tcp_established=5)

        pkts = self.create_stream_in_ip6(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))

        ses_num_before_timeout = self.nat64_get_ses_num()

        sleep(15)

        # ICMP and TCP session after timeout
        ses_num_after_timeout = self.nat64_get_ses_num()
        self.assertEqual(ses_num_before_timeout - ses_num_after_timeout, 2)

    def test_icmp_error(self):
        """ NAT64 ICMP Error message translation """
        self.tcp_port_in = 6303
        self.udp_port_in = 6304
        self.icmp_id_in = 6305

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        # send some packets to create sessions
        pkts = self.create_stream_in_ip6(self.pg0, self.pg1)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture_ip4 = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture_ip4,
                                nat_ip=self.nat_addr,
                                dst_ip=self.pg1.remote_ip4)

        pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture_ip6 = self.pg0.get_capture(len(pkts))
        ip = IPv6(src=''.join(['64:ff9b::', self.pg1.remote_ip4]))
        self.verify_capture_in_ip6(capture_ip6, ip[IPv6].src,
                                   self.pg0.remote_ip6)

        # in2out
        pkts = [Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                IPv6(src=self.pg0.remote_ip6, dst=ip[IPv6].src) /
                ICMPv6DestUnreach(code=1) /
                packet[IPv6] for packet in capture_ip6]
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IP].src, self.nat_addr)
                self.assertEqual(packet[IP].dst, self.pg1.remote_ip4)
                self.assertEqual(packet[ICMP].type, 3)
                self.assertEqual(packet[ICMP].code, 13)
                inner = packet[IPerror]
                self.assertEqual(inner.src, self.pg1.remote_ip4)
                self.assertEqual(inner.dst, self.nat_addr)
                self.assert_packet_checksums_valid(packet)
                if inner.haslayer(TCPerror):
                    self.assertEqual(inner[TCPerror].dport, self.tcp_port_out)
                elif inner.haslayer(UDPerror):
                    self.assertEqual(inner[UDPerror].dport, self.udp_port_out)
                else:
                    self.assertEqual(inner[ICMPerror].id, self.icmp_id_out)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

        # out2in
        pkts = [Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
                IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
                ICMP(type=3, code=13) /
                packet[IP] for packet in capture_ip4]
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IPv6].src, ip.src)
                self.assertEqual(packet[IPv6].dst, self.pg0.remote_ip6)
                icmp = packet[ICMPv6DestUnreach]
                self.assertEqual(icmp.code, 1)
                inner = icmp[IPerror6]
                self.assertEqual(inner.src, self.pg0.remote_ip6)
                self.assertEqual(inner.dst, ip.src)
                self.assert_icmpv6_checksum_valid(packet)
                if inner.haslayer(TCPerror):
                    self.assertEqual(inner[TCPerror].sport, self.tcp_port_in)
                elif inner.haslayer(UDPerror):
                    self.assertEqual(inner[UDPerror].sport, self.udp_port_in)
                else:
                    self.assertEqual(inner[ICMPv6EchoRequest].id,
                                     self.icmp_id_in)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

    def test_hairpinning(self):
        """ NAT64 hairpinning """

        client = self.pg0.remote_hosts[0]
        server = self.pg0.remote_hosts[1]
        server_tcp_in_port = 22
        server_tcp_out_port = 4022
        server_udp_in_port = 23
        server_udp_out_port = 4023
        client_tcp_in_port = 1234
        client_udp_in_port = 1235
        client_tcp_out_port = 0
        client_udp_out_port = 0
        ip = IPv6(src=''.join(['64:ff9b::', self.nat_addr]))
        nat_addr_ip6 = ip.src

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        self.vapi.nat64_add_del_static_bib(server.ip6n,
                                           self.nat_addr_n,
                                           server_tcp_in_port,
                                           server_tcp_out_port,
                                           IP_PROTOS.tcp)
        self.vapi.nat64_add_del_static_bib(server.ip6n,
                                           self.nat_addr_n,
                                           server_udp_in_port,
                                           server_udp_out_port,
                                           IP_PROTOS.udp)

        # client to server
        pkts = []
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=client.ip6, dst=nat_addr_ip6) /
             TCP(sport=client_tcp_in_port, dport=server_tcp_out_port))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=client.ip6, dst=nat_addr_ip6) /
             UDP(sport=client_udp_in_port, dport=server_udp_out_port))
        pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IPv6].src, nat_addr_ip6)
                self.assertEqual(packet[IPv6].dst, server.ip6)
                self.assert_packet_checksums_valid(packet)
                if packet.haslayer(TCP):
                    self.assertNotEqual(packet[TCP].sport, client_tcp_in_port)
                    self.assertEqual(packet[TCP].dport, server_tcp_in_port)
                    client_tcp_out_port = packet[TCP].sport
                else:
                    self.assertNotEqual(packet[UDP].sport, client_udp_in_port)
                    self.assertEqual(packet[UDP].dport, server_udp_in_port)
                    client_udp_out_port = packet[UDP].sport
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

        # server to client
        pkts = []
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=server.ip6, dst=nat_addr_ip6) /
             TCP(sport=server_tcp_in_port, dport=client_tcp_out_port))
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=server.ip6, dst=nat_addr_ip6) /
             UDP(sport=server_udp_in_port, dport=client_udp_out_port))
        pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IPv6].src, nat_addr_ip6)
                self.assertEqual(packet[IPv6].dst, client.ip6)
                self.assert_packet_checksums_valid(packet)
                if packet.haslayer(TCP):
                    self.assertEqual(packet[TCP].sport, server_tcp_out_port)
                    self.assertEqual(packet[TCP].dport, client_tcp_in_port)
                else:
                    self.assertEqual(packet[UDP].sport, server_udp_out_port)
                    self.assertEqual(packet[UDP].dport, client_udp_in_port)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

        # ICMP error
        pkts = []
        pkts = [Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                IPv6(src=client.ip6, dst=nat_addr_ip6) /
                ICMPv6DestUnreach(code=1) /
                packet[IPv6] for packet in capture]
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IPv6].src, nat_addr_ip6)
                self.assertEqual(packet[IPv6].dst, server.ip6)
                icmp = packet[ICMPv6DestUnreach]
                self.assertEqual(icmp.code, 1)
                inner = icmp[IPerror6]
                self.assertEqual(inner.src, server.ip6)
                self.assertEqual(inner.dst, nat_addr_ip6)
                self.assert_packet_checksums_valid(packet)
                if inner.haslayer(TCPerror):
                    self.assertEqual(inner[TCPerror].sport, server_tcp_in_port)
                    self.assertEqual(inner[TCPerror].dport,
                                     client_tcp_out_port)
                else:
                    self.assertEqual(inner[UDPerror].sport, server_udp_in_port)
                    self.assertEqual(inner[UDPerror].dport,
                                     client_udp_out_port)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

    def test_prefix(self):
        """ NAT64 Network-Specific Prefix """

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)
        self.vapi.nat64_add_del_pool_addr_range(self.vrf1_nat_addr_n,
                                                self.vrf1_nat_addr_n,
                                                vrf_id=self.vrf1_id)
        self.vapi.nat64_add_del_interface(self.pg2.sw_if_index)

        # Add global prefix
        global_pref64 = "2001:db8::"
        global_pref64_n = socket.inet_pton(socket.AF_INET6, global_pref64)
        global_pref64_len = 32
        self.vapi.nat64_add_del_prefix(global_pref64_n, global_pref64_len)

        prefix = self.vapi.nat64_prefix_dump()
        self.assertEqual(len(prefix), 1)
        self.assertEqual(prefix[0].prefix, global_pref64_n)
        self.assertEqual(prefix[0].prefix_len, global_pref64_len)
        self.assertEqual(prefix[0].vrf_id, 0)

        # Add tenant specific prefix
        vrf1_pref64 = "2001:db8:122:300::"
        vrf1_pref64_n = socket.inet_pton(socket.AF_INET6, vrf1_pref64)
        vrf1_pref64_len = 56
        self.vapi.nat64_add_del_prefix(vrf1_pref64_n,
                                       vrf1_pref64_len,
                                       vrf_id=self.vrf1_id)
        prefix = self.vapi.nat64_prefix_dump()
        self.assertEqual(len(prefix), 2)

        # Global prefix
        pkts = self.create_stream_in_ip6(self.pg0,
                                         self.pg1,
                                         pref=global_pref64,
                                         plen=global_pref64_len)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip=self.nat_addr,
                                dst_ip=self.pg1.remote_ip4)

        pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        dst_ip = self.compose_ip6(self.pg1.remote_ip4,
                                  global_pref64,
                                  global_pref64_len)
        self.verify_capture_in_ip6(capture, dst_ip, self.pg0.remote_ip6)

        # Tenant specific prefix
        pkts = self.create_stream_in_ip6(self.pg2,
                                         self.pg1,
                                         pref=vrf1_pref64,
                                         plen=vrf1_pref64_len)
        self.pg2.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        self.verify_capture_out(capture, nat_ip=self.vrf1_nat_addr,
                                dst_ip=self.pg1.remote_ip4)

        pkts = self.create_stream_out(self.pg1, dst_ip=self.vrf1_nat_addr)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg2.get_capture(len(pkts))
        dst_ip = self.compose_ip6(self.pg1.remote_ip4,
                                  vrf1_pref64,
                                  vrf1_pref64_len)
        self.verify_capture_in_ip6(capture, dst_ip, self.pg2.remote_ip6)

    def test_unknown_proto(self):
        """ NAT64 translate packet with unknown protocol """

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)
        remote_ip6 = self.compose_ip6(self.pg1.remote_ip4, '64:ff9b::', 96)

        # in2out
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=remote_ip6) /
             TCP(sport=self.tcp_port_in, dport=20))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg1.get_capture(1)

        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=remote_ip6, nh=47) /
             GRE() /
             IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg1.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IP].src, self.nat_addr)
            self.assertEqual(packet[IP].dst, self.pg1.remote_ip4)
            self.assertEqual(packet.haslayer(GRE), 1)
            self.assert_packet_checksums_valid(packet)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

        # out2in
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
             GRE() /
             IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IPv6].src, remote_ip6)
            self.assertEqual(packet[IPv6].dst, self.pg0.remote_ip6)
            self.assertEqual(packet[IPv6].nh, 47)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

    def test_hairpinning_unknown_proto(self):
        """ NAT64 translate packet with unknown protocol - hairpinning """

        client = self.pg0.remote_hosts[0]
        server = self.pg0.remote_hosts[1]
        server_tcp_in_port = 22
        server_tcp_out_port = 4022
        client_tcp_in_port = 1234
        client_tcp_out_port = 1235
        server_nat_ip = "10.0.0.100"
        client_nat_ip = "10.0.0.110"
        server_nat_ip_n = socket.inet_pton(socket.AF_INET, server_nat_ip)
        client_nat_ip_n = socket.inet_pton(socket.AF_INET, client_nat_ip)
        server_nat_ip6 = self.compose_ip6(server_nat_ip, '64:ff9b::', 96)
        client_nat_ip6 = self.compose_ip6(client_nat_ip, '64:ff9b::', 96)

        self.vapi.nat64_add_del_pool_addr_range(server_nat_ip_n,
                                                client_nat_ip_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        self.vapi.nat64_add_del_static_bib(server.ip6n,
                                           server_nat_ip_n,
                                           server_tcp_in_port,
                                           server_tcp_out_port,
                                           IP_PROTOS.tcp)

        self.vapi.nat64_add_del_static_bib(server.ip6n,
                                           server_nat_ip_n,
                                           0,
                                           0,
                                           IP_PROTOS.gre)

        self.vapi.nat64_add_del_static_bib(client.ip6n,
                                           client_nat_ip_n,
                                           client_tcp_in_port,
                                           client_tcp_out_port,
                                           IP_PROTOS.tcp)

        # client to server
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=client.ip6, dst=server_nat_ip6) /
             TCP(sport=client_tcp_in_port, dport=server_tcp_out_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)

        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=client.ip6, dst=server_nat_ip6, nh=IP_PROTOS.gre) /
             GRE() /
             IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IPv6].src, client_nat_ip6)
            self.assertEqual(packet[IPv6].dst, server.ip6)
            self.assertEqual(packet[IPv6].nh, IP_PROTOS.gre)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

        # server to client
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=server.ip6, dst=client_nat_ip6, nh=IP_PROTOS.gre) /
             GRE() /
             IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) /
             TCP(sport=1234, dport=1234))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg0.get_capture(1)
        packet = p[0]
        try:
            self.assertEqual(packet[IPv6].src, server_nat_ip6)
            self.assertEqual(packet[IPv6].dst, client.ip6)
            self.assertEqual(packet[IPv6].nh, IP_PROTOS.gre)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

    def test_one_armed_nat64(self):
        """ One armed NAT64 """
        external_port = 0
        remote_host_ip6 = self.compose_ip6(self.pg3.remote_ip4,
                                           '64:ff9b::',
                                           96)

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg3.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg3.sw_if_index, is_inside=0)

        # in2out
        p = (Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac) /
             IPv6(src=self.pg3.remote_ip6, dst=remote_host_ip6) /
             TCP(sport=12345, dport=80))
        self.pg3.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(1)
        p = capture[0]
        try:
            ip = p[IP]
            tcp = p[TCP]
            self.assertEqual(ip.src, self.nat_addr)
            self.assertEqual(ip.dst, self.pg3.remote_ip4)
            self.assertNotEqual(tcp.sport, 12345)
            external_port = tcp.sport
            self.assertEqual(tcp.dport, 80)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

        # out2in
        p = (Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac) /
             IP(src=self.pg3.remote_ip4, dst=self.nat_addr) /
             TCP(sport=80, dport=external_port))
        self.pg3.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg3.get_capture(1)
        p = capture[0]
        try:
            ip = p[IPv6]
            tcp = p[TCP]
            self.assertEqual(ip.src, remote_host_ip6)
            self.assertEqual(ip.dst, self.pg3.remote_ip6)
            self.assertEqual(tcp.sport, 80)
            self.assertEqual(tcp.dport, 12345)
            self.assert_packet_checksums_valid(p)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", p))
            raise

    def test_frag_in_order(self):
        """ NAT64 translate fragments arriving in order """
        self.tcp_port_in = random.randint(1025, 65535)

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        reass = self.vapi.nat_reass_dump()
        reass_n_start = len(reass)

        # in2out
        data = b'a' * 200
        pkts = self.create_stream_frag_ip6(self.pg0, self.pg1.remote_ip4,
                                           self.tcp_port_in, 20, data)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        frags = self.pg1.get_capture(len(pkts))
        p = self.reass_frags_and_verify(frags,
                                        self.nat_addr,
                                        self.pg1.remote_ip4)
        self.assertEqual(p[TCP].dport, 20)
        self.assertNotEqual(p[TCP].sport, self.tcp_port_in)
        self.tcp_port_out = p[TCP].sport
        self.assertEqual(data, p[Raw].load)

        # out2in
        data = b"A" * 4 + b"b" * 16 + b"C" * 3
        pkts = self.create_stream_frag(self.pg1,
                                       self.nat_addr,
                                       20,
                                       self.tcp_port_out,
                                       data)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        frags = self.pg0.get_capture(len(pkts))
        src = self.compose_ip6(self.pg1.remote_ip4, '64:ff9b::', 96)
        p = self.reass_frags_and_verify_ip6(frags, src, self.pg0.remote_ip6)
        self.assertEqual(p[TCP].sport, 20)
        self.assertEqual(p[TCP].dport, self.tcp_port_in)
        self.assertEqual(data, p[Raw].load)

        reass = self.vapi.nat_reass_dump()
        reass_n_end = len(reass)

        self.assertEqual(reass_n_end - reass_n_start, 2)

    def test_reass_hairpinning(self):
        """ NAT64 fragments hairpinning """
        data = 'a' * 200
        server = self.pg0.remote_hosts[1]
        server_in_port = random.randint(1025, 65535)
        server_out_port = random.randint(1025, 65535)
        client_in_port = random.randint(1025, 65535)
        ip = IPv6(src=''.join(['64:ff9b::', self.nat_addr]))
        nat_addr_ip6 = ip.src

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        # add static BIB entry for server
        self.vapi.nat64_add_del_static_bib(server.ip6n,
                                           self.nat_addr_n,
                                           server_in_port,
                                           server_out_port,
                                           IP_PROTOS.tcp)

        # send packet from host to server
        pkts = self.create_stream_frag_ip6(self.pg0,
                                           self.nat_addr,
                                           client_in_port,
                                           server_out_port,
                                           data)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        frags = self.pg0.get_capture(len(pkts))
        p = self.reass_frags_and_verify_ip6(frags, nat_addr_ip6, server.ip6)
        self.assertNotEqual(p[TCP].sport, client_in_port)
        self.assertEqual(p[TCP].dport, server_in_port)
        self.assertEqual(data, p[Raw].load)

    def test_frag_out_of_order(self):
        """ NAT64 translate fragments arriving out of order """
        self.tcp_port_in = random.randint(1025, 65535)

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        # in2out
        data = b'a' * 200
        pkts = self.create_stream_frag_ip6(self.pg0, self.pg1.remote_ip4,
                                           self.tcp_port_in, 20, data)
        pkts.reverse()
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        frags = self.pg1.get_capture(len(pkts))
        p = self.reass_frags_and_verify(frags,
                                        self.nat_addr,
                                        self.pg1.remote_ip4)
        self.assertEqual(p[TCP].dport, 20)
        self.assertNotEqual(p[TCP].sport, self.tcp_port_in)
        self.tcp_port_out = p[TCP].sport
        self.assertEqual(data, p[Raw].load)

        # out2in
        data = b"A" * 4 + b"B" * 16 + b"C" * 3
        pkts = self.create_stream_frag(self.pg1,
                                       self.nat_addr,
                                       20,
                                       self.tcp_port_out,
                                       data)
        pkts.reverse()
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        frags = self.pg0.get_capture(len(pkts))
        src = self.compose_ip6(self.pg1.remote_ip4, '64:ff9b::', 96)
        p = self.reass_frags_and_verify_ip6(frags, src, self.pg0.remote_ip6)
        self.assertEqual(p[TCP].sport, 20)
        self.assertEqual(p[TCP].dport, self.tcp_port_in)
        self.assertEqual(data, p[Raw].load)

    def test_interface_addr(self):
        """ Acquire NAT64 pool addresses from interface """
        self.vapi.nat64_add_del_interface_addr(self.pg4.sw_if_index)

        # no address in NAT64 pool
        adresses = self.vapi.nat44_address_dump()
        self.assertEqual(0, len(adresses))

        # configure interface address and check NAT64 address pool
        self.pg4.config_ip4()
        addresses = self.vapi.nat64_pool_addr_dump()
        self.assertEqual(len(addresses), 1)
        self.assertEqual(addresses[0].address, self.pg4.local_ip4n)

        # remove interface address and check NAT64 address pool
        self.pg4.unconfig_ip4()
        addresses = self.vapi.nat64_pool_addr_dump()
        self.assertEqual(0, len(adresses))

    @unittest.skipUnless(running_extended_tests, "part of extended tests")
    def test_ipfix_max_bibs_sessions(self):
        """ IPFIX logging maximum session and BIB entries exceeded """
        max_bibs = 1280
        max_sessions = 2560
        remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4,
                                           '64:ff9b::',
                                           96)

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)

        pkts = []
        src = ""
        for i in range(0, max_bibs):
            src = "fd01:aa::%x" % (i)
            p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
                 IPv6(src=src, dst=remote_host_ip6) /
                 TCP(sport=12345, dport=80))
            pkts.append(p)
            p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
                 IPv6(src=src, dst=remote_host_ip6) /
                 TCP(sport=12345, dport=22))
            pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.get_capture(max_sessions)

        self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4n,
                                     src_address=self.pg3.local_ip4n,
                                     path_mtu=512,
                                     template_interval=10)
        self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
                                           src_port=self.ipfix_src_port)

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IPv6(src=src, dst=remote_host_ip6) /
             TCP(sport=12345, dport=25))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.assert_nothing_captured()
        sleep(1)
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        capture = self.pg3.get_capture(9)
        ipfix = IPFIXDecoder()
        # first load template
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            self.assertEqual(p[IP].src, self.pg3.local_ip4)
            self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
            self.assertEqual(p[UDP].sport, self.ipfix_src_port)
            self.assertEqual(p[UDP].dport, 4739)
            self.assertEqual(p[IPFIX].observationDomainID,
                             self.ipfix_domain_id)
            if p.haslayer(Template):
                ipfix.add_template(p.getlayer(Template))
        # verify events in data set
        for p in capture:
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                self.verify_ipfix_max_sessions(data, max_sessions)

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) /
             TCP(sport=12345, dport=80))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.assert_nothing_captured()
        sleep(1)
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        capture = self.pg3.get_capture(1)
        # verify events in data set
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            self.assertEqual(p[IP].src, self.pg3.local_ip4)
            self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
            self.assertEqual(p[UDP].sport, self.ipfix_src_port)
            self.assertEqual(p[UDP].dport, 4739)
            self.assertEqual(p[IPFIX].observationDomainID,
                             self.ipfix_domain_id)
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                self.verify_ipfix_max_bibs(data, max_bibs)

    def test_ipfix_max_frags(self):
        """ IPFIX logging maximum fragments pending reassembly exceeded """
        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)
        self.vapi.nat_set_reass(max_frag=1, is_ip6=1)
        self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4n,
                                     src_address=self.pg3.local_ip4n,
                                     path_mtu=512,
                                     template_interval=10)
        self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
                                           src_port=self.ipfix_src_port)

        data = b'a' * 200
        pkts = self.create_stream_frag_ip6(self.pg0, self.pg1.remote_ip4,
                                           self.tcp_port_in, 20, data)
        pkts.reverse()
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.pg1.assert_nothing_captured()
        sleep(1)
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        capture = self.pg3.get_capture(9)
        ipfix = IPFIXDecoder()
        # first load template
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            self.assertEqual(p[IP].src, self.pg3.local_ip4)
            self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
            self.assertEqual(p[UDP].sport, self.ipfix_src_port)
            self.assertEqual(p[UDP].dport, 4739)
            self.assertEqual(p[IPFIX].observationDomainID,
                             self.ipfix_domain_id)
            if p.haslayer(Template):
                ipfix.add_template(p.getlayer(Template))
        # verify events in data set
        for p in capture:
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                self.verify_ipfix_max_fragments_ip6(data, 1,
                                                    self.pg0.remote_ip6n)

    def test_ipfix_bib_ses(self):
        """ IPFIX logging NAT64 BIB/session create and delete events """
        self.tcp_port_in = random.randint(1025, 65535)
        remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4,
                                           '64:ff9b::',
                                           96)

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)
        self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4n,
                                     src_address=self.pg3.local_ip4n,
                                     path_mtu=512,
                                     template_interval=10)
        self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
                                           src_port=self.ipfix_src_port)

        # Create
        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) /
             TCP(sport=self.tcp_port_in, dport=25))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg1.get_capture(1)
        self.tcp_port_out = p[0][TCP].sport
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        capture = self.pg3.get_capture(10)
        ipfix = IPFIXDecoder()
        # first load template
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            self.assertEqual(p[IP].src, self.pg3.local_ip4)
            self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
            self.assertEqual(p[UDP].sport, self.ipfix_src_port)
            self.assertEqual(p[UDP].dport, 4739)
            self.assertEqual(p[IPFIX].observationDomainID,
                             self.ipfix_domain_id)
            if p.haslayer(Template):
                ipfix.add_template(p.getlayer(Template))
        # verify events in data set
        for p in capture:
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                if scapy.compat.orb(data[0][230]) == 10:
                    self.verify_ipfix_bib(data, 1, self.pg0.remote_ip6n)
                elif scapy.compat.orb(data[0][230]) == 6:
                    self.verify_ipfix_nat64_ses(data,
                                                1,
                                                self.pg0.remote_ip6n,
                                                self.pg1.remote_ip4,
                                                25)
                else:
                    self.logger.error(ppp("Unexpected or invalid packet: ", p))

        # Delete
        self.pg_enable_capture(self.pg_interfaces)
        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n,
                                                is_add=0)
        self.vapi.cli("ipfix flush")  # FIXME this should be an API call
        capture = self.pg3.get_capture(2)
        # verify events in data set
        for p in capture:
            self.assertTrue(p.haslayer(IPFIX))
            self.assertEqual(p[IP].src, self.pg3.local_ip4)
            self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
            self.assertEqual(p[UDP].sport, self.ipfix_src_port)
            self.assertEqual(p[UDP].dport, 4739)
            self.assertEqual(p[IPFIX].observationDomainID,
                             self.ipfix_domain_id)
            if p.haslayer(Data):
                data = ipfix.decode_data_set(p.getlayer(Set))
                if scapy.compat.orb(data[0][230]) == 11:
                    self.verify_ipfix_bib(data, 0, self.pg0.remote_ip6n)
                elif scapy.compat.orb(data[0][230]) == 7:
                    self.verify_ipfix_nat64_ses(data,
                                                0,
                                                self.pg0.remote_ip6n,
                                                self.pg1.remote_ip4,
                                                25)
                else:
                    self.logger.error(ppp("Unexpected or invalid packet: ", p))

    def test_syslog_sess(self):
        """ Test syslog session creation and deletion """
        self.tcp_port_in = random.randint(1025, 65535)
        remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4,
                                           '64:ff9b::',
                                           96)

        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n)
        self.vapi.nat64_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat64_add_del_interface(self.pg1.sw_if_index, is_inside=0)
        self.vapi.syslog_set_filter(SYSLOG_SEVERITY.INFO)
        self.vapi.syslog_set_sender(self.pg3.local_ip4n, self.pg3.remote_ip4n)

        p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) /
             TCP(sport=self.tcp_port_in, dport=self.tcp_external_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        p = self.pg1.get_capture(1)
        self.tcp_port_out = p[0][TCP].sport
        capture = self.pg3.get_capture(1)
        self.verify_syslog_sess(capture[0][Raw].load, is_ip6=True)

        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        self.vapi.nat64_add_del_pool_addr_range(self.nat_addr_n,
                                                self.nat_addr_n,
                                                is_add=0)
        capture = self.pg3.get_capture(1)
        self.verify_syslog_sess(capture[0][Raw].load, False, True)

    def nat64_get_ses_num(self):
        """
        Return number of active NAT64 sessions.
        """
        st = self.vapi.nat64_st_dump()
        return len(st)

    def clear_nat64(self):
        """
        Clear NAT64 configuration.
        """
        self.vapi.nat_ipfix_enable_disable(enable=0,
                                           src_port=self.ipfix_src_port,
                                           domain_id=self.ipfix_domain_id)
        self.ipfix_src_port = 4739
        self.ipfix_domain_id = 1

        self.vapi.syslog_set_filter(SYSLOG_SEVERITY.EMERG)

        self.vapi.nat_set_timeouts()

        interfaces = self.vapi.nat64_interface_dump()
        for intf in interfaces:
            if intf.is_inside > 1:
                self.vapi.nat64_add_del_interface(intf.sw_if_index,
                                                  0,
                                                  is_add=0)
            self.vapi.nat64_add_del_interface(intf.sw_if_index,
                                              intf.is_inside,
                                              is_add=0)

        bib = self.vapi.nat64_bib_dump(255)
        for bibe in bib:
            if bibe.is_static:
                self.vapi.nat64_add_del_static_bib(bibe.i_addr,
                                                   bibe.o_addr,
                                                   bibe.i_port,
                                                   bibe.o_port,
                                                   bibe.proto,
                                                   bibe.vrf_id,
                                                   is_add=0)

        adresses = self.vapi.nat64_pool_addr_dump()
        for addr in adresses:
            self.vapi.nat64_add_del_pool_addr_range(addr.address,
                                                    addr.address,
                                                    vrf_id=addr.vrf_id,
                                                    is_add=0)

        prefixes = self.vapi.nat64_prefix_dump()
        for prefix in prefixes:
            self.vapi.nat64_add_del_prefix(prefix.prefix,
                                           prefix.prefix_len,
                                           vrf_id=prefix.vrf_id,
                                           is_add=0)

        bibs = self.statistics.get_counter('/nat64/total-bibs')
        self.assertEqual(bibs[0][0], 0)
        sessions = self.statistics.get_counter('/nat64/total-sessions')
        self.assertEqual(sessions[0][0], 0)

    def tearDown(self):
        super(TestNAT64, self).tearDown()
        if not self.vpp_dead:
            self.logger.info(self.vapi.cli("show nat64 pool"))
            self.logger.info(self.vapi.cli("show nat64 interfaces"))
            self.logger.info(self.vapi.cli("show nat64 prefix"))
            self.logger.info(self.vapi.cli("show nat64 bib all"))
            self.logger.info(self.vapi.cli("show nat64 session table all"))
            self.logger.info(self.vapi.cli("show nat virtual-reassembly"))
            self.clear_nat64()


class TestDSlite(MethodHolder):
    """ DS-Lite Test Cases """

    @classmethod
    def setUpClass(cls):
        super(TestDSlite, cls).setUpClass()

        try:
            cls.nat_addr = '10.0.0.3'
            cls.nat_addr_n = socket.inet_pton(socket.AF_INET, cls.nat_addr)

            cls.create_pg_interfaces(range(3))
            cls.pg0.admin_up()
            cls.pg0.config_ip4()
            cls.pg0.resolve_arp()
            cls.pg1.admin_up()
            cls.pg1.config_ip6()
            cls.pg1.generate_remote_hosts(2)
            cls.pg1.configure_ipv6_neighbors()
            cls.pg2.admin_up()
            cls.pg2.config_ip4()
            cls.pg2.resolve_arp()

        except Exception:
            super(TestDSlite, cls).tearDownClass()
            raise

    def verify_syslog_apmadd(self, data, isaddr, isport, xsaddr, xsport,
                             sv6enc, proto):
        message = data.decode('utf-8')
        try:
            message = SyslogMessage.parse(message)
        except ParseError as e:
            self.logger.error(e)
        else:
            self.assertEqual(message.severity, SyslogSeverity.info)
            self.assertEqual(message.appname, 'NAT')
            self.assertEqual(message.msgid, 'APMADD')
            sd_params = message.sd.get('napmap')
            self.assertTrue(sd_params is not None)
            self.assertEqual(sd_params.get('IATYP'), 'IPv4')
            self.assertEqual(sd_params.get('ISADDR'), isaddr)
            self.assertEqual(sd_params.get('ISPORT'), "%d" % isport)
            self.assertEqual(sd_params.get('XATYP'), 'IPv4')
            self.assertEqual(sd_params.get('XSADDR'), xsaddr)
            self.assertEqual(sd_params.get('XSPORT'), "%d" % xsport)
            self.assertEqual(sd_params.get('PROTO'), "%d" % proto)
            self.assertTrue(sd_params.get('SSUBIX') is not None)
            self.assertEqual(sd_params.get('SV6ENC'), sv6enc)

    def test_dslite(self):
        """ Test DS-Lite """
        nat_config = self.vapi.nat_show_config()
        self.assertEqual(0, nat_config.dslite_ce)

        self.vapi.dslite_add_del_pool_addr_range(self.nat_addr_n,
                                                 self.nat_addr_n)
        aftr_ip4 = '192.0.0.1'
        aftr_ip4_n = socket.inet_pton(socket.AF_INET, aftr_ip4)
        aftr_ip6 = '2001:db8:85a3::8a2e:370:1'
        aftr_ip6_n = socket.inet_pton(socket.AF_INET6, aftr_ip6)
        self.vapi.dslite_set_aftr_addr(aftr_ip6_n, aftr_ip4_n)
        self.vapi.syslog_set_sender(self.pg2.local_ip4n, self.pg2.remote_ip4n)

        # UDP
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[0].ip6) /
             IP(dst=self.pg0.remote_ip4, src='192.168.1.1') /
             UDP(sport=20000, dport=10000))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        capture = capture[0]
        self.assertFalse(capture.haslayer(IPv6))
        self.assertEqual(capture[IP].src, self.nat_addr)
        self.assertEqual(capture[IP].dst, self.pg0.remote_ip4)
        self.assertNotEqual(capture[UDP].sport, 20000)
        self.assertEqual(capture[UDP].dport, 10000)
        self.assert_packet_checksums_valid(capture)
        out_port = capture[UDP].sport
        capture = self.pg2.get_capture(1)
        self.verify_syslog_apmadd(capture[0][Raw].load, '192.168.1.1',
                                  20000, self.nat_addr, out_port,
                                  self.pg1.remote_hosts[0].ip6, IP_PROTOS.udp)

        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(dst=self.nat_addr, src=self.pg0.remote_ip4) /
             UDP(sport=10000, dport=out_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        capture = capture[0]
        self.assertEqual(capture[IPv6].src, aftr_ip6)
        self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[0].ip6)
        self.assertEqual(capture[IP].src, self.pg0.remote_ip4)
        self.assertEqual(capture[IP].dst, '192.168.1.1')
        self.assertEqual(capture[UDP].sport, 10000)
        self.assertEqual(capture[UDP].dport, 20000)
        self.assert_packet_checksums_valid(capture)

        # TCP
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6) /
             IP(dst=self.pg0.remote_ip4, src='192.168.1.1') /
             TCP(sport=20001, dport=10001))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        capture = capture[0]
        self.assertFalse(capture.haslayer(IPv6))
        self.assertEqual(capture[IP].src, self.nat_addr)
        self.assertEqual(capture[IP].dst, self.pg0.remote_ip4)
        self.assertNotEqual(capture[TCP].sport, 20001)
        self.assertEqual(capture[TCP].dport, 10001)
        self.assert_packet_checksums_valid(capture)
        out_port = capture[TCP].sport

        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(dst=self.nat_addr, src=self.pg0.remote_ip4) /
             TCP(sport=10001, dport=out_port))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        capture = capture[0]
        self.assertEqual(capture[IPv6].src, aftr_ip6)
        self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[1].ip6)
        self.assertEqual(capture[IP].src, self.pg0.remote_ip4)
        self.assertEqual(capture[IP].dst, '192.168.1.1')
        self.assertEqual(capture[TCP].sport, 10001)
        self.assertEqual(capture[TCP].dport, 20001)
        self.assert_packet_checksums_valid(capture)

        # ICMP
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6) /
             IP(dst=self.pg0.remote_ip4, src='192.168.1.1') /
             ICMP(id=4000, type='echo-request'))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        capture = capture[0]
        self.assertFalse(capture.haslayer(IPv6))
        self.assertEqual(capture[IP].src, self.nat_addr)
        self.assertEqual(capture[IP].dst, self.pg0.remote_ip4)
        self.assertNotEqual(capture[ICMP].id, 4000)
        self.assert_packet_checksums_valid(capture)
        out_id = capture[ICMP].id

        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(dst=self.nat_addr, src=self.pg0.remote_ip4) /
             ICMP(id=out_id, type='echo-reply'))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        capture = capture[0]
        self.assertEqual(capture[IPv6].src, aftr_ip6)
        self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[1].ip6)
        self.assertEqual(capture[IP].src, self.pg0.remote_ip4)
        self.assertEqual(capture[IP].dst, '192.168.1.1')
        self.assertEqual(capture[ICMP].id, 4000)
        self.assert_packet_checksums_valid(capture)

        # ping DS-Lite AFTR tunnel endpoint address
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(src=self.pg1.remote_hosts[1].ip6, dst=aftr_ip6) /
             ICMPv6EchoRequest())
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        capture = capture[0]
        self.assertEqual(capture[IPv6].src, aftr_ip6)
        self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[1].ip6)
        self.assertTrue(capture.haslayer(ICMPv6EchoReply))

        b4s = self.statistics.get_counter('/dslite/total-b4s')
        self.assertEqual(b4s[0][0], 2)
        sessions = self.statistics.get_counter('/dslite/total-sessions')
        self.assertEqual(sessions[0][0], 3)

    def tearDown(self):
        super(TestDSlite, self).tearDown()
        if not self.vpp_dead:
            self.logger.info(self.vapi.cli("show dslite pool"))
            self.logger.info(
                self.vapi.cli("show dslite aftr-tunnel-endpoint-address"))
            self.logger.info(self.vapi.cli("show dslite sessions"))


class TestDSliteCE(MethodHolder):
    """ DS-Lite CE Test Cases """

    @classmethod
    def setUpConstants(cls):
        super(TestDSliteCE, cls).setUpConstants()
        cls.vpp_cmdline.extend(["nat", "{", "dslite ce", "}"])

    @classmethod
    def setUpClass(cls):
        super(TestDSliteCE, cls).setUpClass()

        try:
            cls.create_pg_interfaces(range(2))
            cls.pg0.admin_up()
            cls.pg0.config_ip4()
            cls.pg0.resolve_arp()
            cls.pg1.admin_up()
            cls.pg1.config_ip6()
            cls.pg1.generate_remote_hosts(1)
            cls.pg1.configure_ipv6_neighbors()

        except Exception:
            super(TestDSliteCE, cls).tearDownClass()
            raise

    def test_dslite_ce(self):
        """ Test DS-Lite CE """

        nat_config = self.vapi.nat_show_config()
        self.assertEqual(1, nat_config.dslite_ce)

        b4_ip4 = '192.0.0.2'
        b4_ip4_n = socket.inet_pton(socket.AF_INET, b4_ip4)
        b4_ip6 = '2001:db8:62aa::375e:f4c1:1'
        b4_ip6_n = socket.inet_pton(socket.AF_INET6, b4_ip6)
        self.vapi.dslite_set_b4_addr(b4_ip6_n, b4_ip4_n)

        aftr_ip4 = '192.0.0.1'
        aftr_ip4_n = socket.inet_pton(socket.AF_INET, aftr_ip4)
        aftr_ip6 = '2001:db8:85a3::8a2e:370:1'
        aftr_ip6_n = socket.inet_pton(socket.AF_INET6, aftr_ip6)
        self.vapi.dslite_set_aftr_addr(aftr_ip6_n, aftr_ip4_n)

        self.vapi.ip_add_del_route(dst_address=aftr_ip6_n,
                                   dst_address_length=128,
                                   next_hop_address=self.pg1.remote_ip6n,
                                   next_hop_sw_if_index=self.pg1.sw_if_index,
                                   is_ipv6=1)

        # UDP encapsulation
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IP(dst=self.pg1.remote_ip4, src=self.pg0.remote_ip4) /
             UDP(sport=10000, dport=20000))
        self.pg0.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        capture = capture[0]
        self.assertEqual(capture[IPv6].src, b4_ip6)
        self.assertEqual(capture[IPv6].dst, aftr_ip6)
        self.assertEqual(capture[IP].src, self.pg0.remote_ip4)
        self.assertEqual(capture[IP].dst, self.pg1.remote_ip4)
        self.assertEqual(capture[UDP].sport, 10000)
        self.assertEqual(capture[UDP].dport, 20000)
        self.assert_packet_checksums_valid(capture)

        # UDP decapsulation
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(dst=b4_ip6, src=aftr_ip6) /
             IP(dst=self.pg0.remote_ip4, src=self.pg1.remote_ip4) /
             UDP(sport=20000, dport=10000))
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(1)
        capture = capture[0]
        self.assertFalse(capture.haslayer(IPv6))
        self.assertEqual(capture[IP].src, self.pg1.remote_ip4)
        self.assertEqual(capture[IP].dst, self.pg0.remote_ip4)
        self.assertEqual(capture[UDP].sport, 20000)
        self.assertEqual(capture[UDP].dport, 10000)
        self.assert_packet_checksums_valid(capture)

        # ping DS-Lite B4 tunnel endpoint address
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(src=self.pg1.remote_hosts[0].ip6, dst=b4_ip6) /
             ICMPv6EchoRequest())
        self.pg1.add_stream(p)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        capture = capture[0]
        self.assertEqual(capture[IPv6].src, b4_ip6)
        self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[0].ip6)
        self.assertTrue(capture.haslayer(ICMPv6EchoReply))

    def tearDown(self):
        super(TestDSliteCE, self).tearDown()
        if not self.vpp_dead:
            self.logger.info(
                self.vapi.cli("show dslite aftr-tunnel-endpoint-address"))
            self.logger.info(
                self.vapi.cli("show dslite b4-tunnel-endpoint-address"))


class TestNAT66(MethodHolder):
    """ NAT66 Test Cases """

    @classmethod
    def setUpClass(cls):
        super(TestNAT66, cls).setUpClass()

        try:
            cls.nat_addr = 'fd01:ff::2'
            cls.nat_addr_n = socket.inet_pton(socket.AF_INET6, cls.nat_addr)

            cls.create_pg_interfaces(range(2))
            cls.interfaces = list(cls.pg_interfaces)

            for i in cls.interfaces:
                i.admin_up()
                i.config_ip6()
                i.configure_ipv6_neighbors()

        except Exception:
            super(TestNAT66, cls).tearDownClass()
            raise

    def test_static(self):
        """ 1:1 NAT66 test """
        self.vapi.nat66_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat66_add_del_interface(self.pg1.sw_if_index, is_inside=0)
        self.vapi.nat66_add_del_static_mapping(self.pg0.remote_ip6n,
                                               self.nat_addr_n)

        # in2out
        pkts = []
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
             TCP())
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
             UDP())
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
             ICMPv6EchoRequest())
        pkts.append(p)
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
             GRE() / IP() / TCP())
        pkts.append(p)
        self.pg0.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IPv6].src, self.nat_addr)
                self.assertEqual(packet[IPv6].dst, self.pg1.remote_ip6)
                self.assert_packet_checksums_valid(packet)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

        # out2in
        pkts = []
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) /
             TCP())
        pkts.append(p)
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) /
             UDP())
        pkts.append(p)
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) /
             ICMPv6EchoReply())
        pkts.append(p)
        p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
             IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) /
             GRE() / IP() / TCP())
        pkts.append(p)
        self.pg1.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg0.get_capture(len(pkts))
        for packet in capture:
            try:
                self.assertEqual(packet[IPv6].src, self.pg1.remote_ip6)
                self.assertEqual(packet[IPv6].dst, self.pg0.remote_ip6)
                self.assert_packet_checksums_valid(packet)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise

        sm = self.vapi.nat66_static_mapping_dump()
        self.assertEqual(len(sm), 1)
        self.assertEqual(sm[0].total_pkts, 8)

    def test_check_no_translate(self):
        """ NAT66 translate only when egress interface is outside interface """
        self.vapi.nat66_add_del_interface(self.pg0.sw_if_index)
        self.vapi.nat66_add_del_interface(self.pg1.sw_if_index)
        self.vapi.nat66_add_del_static_mapping(self.pg0.remote_ip6n,
                                               self.nat_addr_n)

        # in2out
        p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
             IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
             UDP())
        self.pg0.add_stream([p])
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        capture = self.pg1.get_capture(1)
        packet = capture[0]
        try:
            self.assertEqual(packet[IPv6].src, self.pg0.remote_ip6)
            self.assertEqual(packet[IPv6].dst, self.pg1.remote_ip6)
        except:
            self.logger.error(ppp("Unexpected or invalid packet:", packet))
            raise

    def clear_nat66(self):
        """
        Clear NAT66 configuration.
        """
        interfaces = self.vapi.nat66_interface_dump()
        for intf in interfaces:
            self.vapi.nat66_add_del_interface(intf.sw_if_index,
                                              intf.is_inside,
                                              is_add=0)

        static_mappings = self.vapi.nat66_static_mapping_dump()
        for sm in static_mappings:
            self.vapi.nat66_add_del_static_mapping(sm.local_ip_address,
                                                   sm.external_ip_address,
                                                   sm.vrf_id,
                                                   is_add=0)

    def tearDown(self):
        super(TestNAT66, self).tearDown()
        if not self.vpp_dead:
            self.logger.info(self.vapi.cli("show nat66 interfaces"))
            self.logger.info(self.vapi.cli("show nat66 static mappings"))
            self.clear_nat66()


if __name__ == '__main__':
    unittest.main(testRunner=VppTestRunner)