1#!/usr/bin/env python3
2
3import socket
4
5import scapy.compat
6from scapy.layers.l2 import Ether
7from scapy.layers.inet import ICMP, IP, TCP, UDP
8from scapy.layers.ipsec import SecurityAssociation, ESP
9
10from util import ppp, ppc
11from template_ipsec import TemplateIpsec
12from vpp_ipsec import VppIpsecSA, VppIpsecSpd, VppIpsecSpdEntry,\
13        VppIpsecSpdItfBinding
14from vpp_ip_route import VppIpRoute, VppRoutePath
15from vpp_ip import DpoProto
16from vpp_papi import VppEnum
17
18
19class IPSecNATTestCase(TemplateIpsec):
20    """ IPSec/NAT
21    TUNNEL MODE:
22
23
24     public network  |   private network
25     ---   encrypt  ---   plain   ---
26    |pg0| <------- |VPP| <------ |pg1|
27     ---            ---           ---
28
29     ---   decrypt  ---   plain   ---
30    |pg0| -------> |VPP| ------> |pg1|
31     ---            ---           ---
32    """
33
34    tcp_port_in = 6303
35    tcp_port_out = 6303
36    udp_port_in = 6304
37    udp_port_out = 6304
38    icmp_id_in = 6305
39    icmp_id_out = 6305
40
41    @classmethod
42    def setUpClass(cls):
43        super(IPSecNATTestCase, cls).setUpClass()
44
45    @classmethod
46    def tearDownClass(cls):
47        super(IPSecNATTestCase, cls).tearDownClass()
48
49    def setUp(self):
50        super(IPSecNATTestCase, self).setUp()
51        self.tun_if = self.pg0
52
53        self.tun_spd = VppIpsecSpd(self, self.tun_spd_id)
54        self.tun_spd.add_vpp_config()
55        VppIpsecSpdItfBinding(self, self.tun_spd,
56                              self.tun_if).add_vpp_config()
57
58        p = self.ipv4_params
59        self.config_esp_tun(p)
60        self.logger.info(self.vapi.ppcli("show ipsec all"))
61
62        d = DpoProto.DPO_PROTO_IP6 if p.is_ipv6 else DpoProto.DPO_PROTO_IP4
63        VppIpRoute(self,  p.remote_tun_if_host, p.addr_len,
64                   [VppRoutePath(self.tun_if.remote_addr[p.addr_type],
65                                 0xffffffff,
66                                 proto=d)]).add_vpp_config()
67
68    def tearDown(self):
69        super(IPSecNATTestCase, self).tearDown()
70
71    def create_stream_plain(self, src_mac, dst_mac, src_ip, dst_ip):
72        return [
73            # TCP
74            Ether(src=src_mac, dst=dst_mac) /
75            IP(src=src_ip, dst=dst_ip) /
76            TCP(sport=self.tcp_port_in, dport=20),
77            # UDP
78            Ether(src=src_mac, dst=dst_mac) /
79            IP(src=src_ip, dst=dst_ip) /
80            UDP(sport=self.udp_port_in, dport=20),
81            # ICMP
82            Ether(src=src_mac, dst=dst_mac) /
83            IP(src=src_ip, dst=dst_ip) /
84            ICMP(id=self.icmp_id_in, type='echo-request')
85        ]
86
87    def create_stream_encrypted(self, src_mac, dst_mac, src_ip, dst_ip, sa):
88        return [
89            # TCP
90            Ether(src=src_mac, dst=dst_mac) /
91            sa.encrypt(IP(src=src_ip, dst=dst_ip) /
92                       TCP(dport=self.tcp_port_out, sport=20)),
93            # UDP
94            Ether(src=src_mac, dst=dst_mac) /
95            sa.encrypt(IP(src=src_ip, dst=dst_ip) /
96                       UDP(dport=self.udp_port_out, sport=20)),
97            # ICMP
98            Ether(src=src_mac, dst=dst_mac) /
99            sa.encrypt(IP(src=src_ip, dst=dst_ip) /
100                       ICMP(id=self.icmp_id_out, type='echo-request'))
101        ]
102
103    def verify_capture_plain(self, capture):
104        for packet in capture:
105            try:
106                self.assert_packet_checksums_valid(packet)
107                self.assert_equal(packet[IP].src, self.tun_if.remote_ip4,
108                                  "decrypted packet source address")
109                self.assert_equal(packet[IP].dst, self.pg1.remote_ip4,
110                                  "decrypted packet destination address")
111                if packet.haslayer(TCP):
112                    self.assertFalse(
113                        packet.haslayer(UDP),
114                        "unexpected UDP header in decrypted packet")
115                    self.assert_equal(packet[TCP].dport, self.tcp_port_in,
116                                      "decrypted packet TCP destination port")
117                elif packet.haslayer(UDP):
118                    if packet[UDP].payload:
119                        self.assertFalse(
120                            packet[UDP][1].haslayer(UDP),
121                            "unexpected UDP header in decrypted packet")
122                    self.assert_equal(packet[UDP].dport, self.udp_port_in,
123                                      "decrypted packet UDP destination port")
124                else:
125                    self.assertFalse(
126                        packet.haslayer(UDP),
127                        "unexpected UDP header in decrypted packet")
128                    self.assert_equal(packet[ICMP].id, self.icmp_id_in,
129                                      "decrypted packet ICMP ID")
130            except Exception:
131                self.logger.error(
132                    ppp("Unexpected or invalid plain packet:", packet))
133                raise
134
135    def verify_capture_encrypted(self, capture, sa):
136        for packet in capture:
137            try:
138                copy = packet.__class__(scapy.compat.raw(packet))
139                del copy[UDP].len
140                copy = packet.__class__(scapy.compat.raw(copy))
141                self.assert_equal(packet[UDP].len, copy[UDP].len,
142                                  "UDP header length")
143                self.assert_packet_checksums_valid(packet)
144                self.assertIn(ESP, packet[IP])
145                decrypt_pkt = sa.decrypt(packet[IP])
146                self.assert_packet_checksums_valid(decrypt_pkt)
147                self.assert_equal(decrypt_pkt[IP].src, self.pg1.remote_ip4,
148                                  "encrypted packet source address")
149                self.assert_equal(decrypt_pkt[IP].dst, self.tun_if.remote_ip4,
150                                  "encrypted packet destination address")
151            except Exception:
152                self.logger.error(
153                    ppp("Unexpected or invalid encrypted packet:", packet))
154                raise
155
156    def config_esp_tun(self, params):
157        addr_type = params.addr_type
158        scapy_tun_sa_id = params.scapy_tun_sa_id
159        scapy_tun_spi = params.scapy_tun_spi
160        vpp_tun_sa_id = params.vpp_tun_sa_id
161        vpp_tun_spi = params.vpp_tun_spi
162        auth_algo_vpp_id = params.auth_algo_vpp_id
163        auth_key = params.auth_key
164        crypt_algo_vpp_id = params.crypt_algo_vpp_id
165        crypt_key = params.crypt_key
166        addr_any = params.addr_any
167        addr_bcast = params.addr_bcast
168        flags = (VppEnum.vl_api_ipsec_sad_flags_t.
169                 IPSEC_API_SAD_FLAG_UDP_ENCAP)
170        e = VppEnum.vl_api_ipsec_spd_action_t
171
172        VppIpsecSA(self, scapy_tun_sa_id, scapy_tun_spi,
173                   auth_algo_vpp_id, auth_key,
174                   crypt_algo_vpp_id, crypt_key,
175                   self.vpp_esp_protocol,
176                   self.pg1.remote_addr[addr_type],
177                   self.tun_if.remote_addr[addr_type],
178                   flags=flags).add_vpp_config()
179        VppIpsecSA(self, vpp_tun_sa_id, vpp_tun_spi,
180                   auth_algo_vpp_id, auth_key,
181                   crypt_algo_vpp_id, crypt_key,
182                   self.vpp_esp_protocol,
183                   self.tun_if.remote_addr[addr_type],
184                   self.pg1.remote_addr[addr_type],
185                   flags=flags).add_vpp_config()
186
187        VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
188                         addr_any, addr_bcast,
189                         addr_any, addr_bcast,
190                         socket.IPPROTO_ESP).add_vpp_config()
191        VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
192                         addr_any, addr_bcast,
193                         addr_any, addr_bcast,
194                         socket.IPPROTO_ESP,
195                         is_outbound=0).add_vpp_config()
196        VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
197                         addr_any, addr_bcast,
198                         addr_any, addr_bcast,
199                         socket.IPPROTO_UDP,
200                         remote_port_start=4500,
201                         remote_port_stop=4500).add_vpp_config()
202        VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
203                         addr_any, addr_bcast,
204                         addr_any, addr_bcast,
205                         socket.IPPROTO_UDP,
206                         remote_port_start=4500,
207                         remote_port_stop=4500,
208                         is_outbound=0).add_vpp_config()
209        VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id,
210                         self.tun_if.remote_addr[addr_type],
211                         self.tun_if.remote_addr[addr_type],
212                         self.pg1.remote_addr[addr_type],
213                         self.pg1.remote_addr[addr_type],
214                         0, priority=10,
215                         policy=e.IPSEC_API_SPD_ACTION_PROTECT,
216                         is_outbound=0).add_vpp_config()
217        VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
218                         self.pg1.remote_addr[addr_type],
219                         self.pg1.remote_addr[addr_type],
220                         self.tun_if.remote_addr[addr_type],
221                         self.tun_if.remote_addr[addr_type],
222                         0, policy=e.IPSEC_API_SPD_ACTION_PROTECT,
223                         priority=10).add_vpp_config()
224
225    def test_ipsec_nat_tun(self):
226        """ IPSec/NAT tunnel test case """
227        p = self.ipv4_params
228        scapy_tun_sa = SecurityAssociation(ESP, spi=p.scapy_tun_spi,
229                                           crypt_algo=p.crypt_algo,
230                                           crypt_key=p.crypt_key,
231                                           auth_algo=p.auth_algo,
232                                           auth_key=p.auth_key,
233                                           tunnel_header=IP(
234                                               src=self.pg1.remote_ip4,
235                                               dst=self.tun_if.remote_ip4),
236                                           nat_t_header=UDP(
237                                               sport=4500,
238                                               dport=4500))
239        # in2out - from private network to public
240        pkts = self.create_stream_plain(
241            self.pg1.remote_mac, self.pg1.local_mac,
242            self.pg1.remote_ip4, self.tun_if.remote_ip4)
243        self.pg1.add_stream(pkts)
244        self.pg_enable_capture(self.pg_interfaces)
245        self.pg_start()
246        capture = self.tun_if.get_capture(len(pkts))
247        self.verify_capture_encrypted(capture, scapy_tun_sa)
248
249        vpp_tun_sa = SecurityAssociation(ESP,
250                                         spi=p.vpp_tun_spi,
251                                         crypt_algo=p.crypt_algo,
252                                         crypt_key=p.crypt_key,
253                                         auth_algo=p.auth_algo,
254                                         auth_key=p.auth_key,
255                                         tunnel_header=IP(
256                                             src=self.tun_if.remote_ip4,
257                                             dst=self.pg1.remote_ip4),
258                                         nat_t_header=UDP(
259                                             sport=4500,
260                                             dport=4500))
261
262        # out2in - from public network to private
263        pkts = self.create_stream_encrypted(
264            self.tun_if.remote_mac, self.tun_if.local_mac,
265            self.tun_if.remote_ip4, self.pg1.remote_ip4, vpp_tun_sa)
266        self.logger.info(ppc("Sending packets:", pkts))
267        self.tun_if.add_stream(pkts)
268        self.pg_enable_capture(self.pg_interfaces)
269        self.pg_start()
270        capture = self.pg1.get_capture(len(pkts))
271        self.verify_capture_plain(capture)
272