Fix multiple NAT translation with interface address as external
[vpp.git] / test / test_classifier.py
1 #!/usr/bin/env python
2
3 import unittest
4 import socket
5 import binascii
6 import sys
7
8 from framework import VppTestCase, VppTestRunner
9
10 from scapy.packet import Raw
11 from scapy.layers.l2 import Ether
12 from scapy.layers.inet import IP, UDP
13 from util import ppp
14
15
16 class TestClassifier(VppTestCase):
17     """ Classifier Test Case """
18
19     def setUp(self):
20         """
21         Perform test setup before test case.
22
23         **Config:**
24             - create 4 pg interfaces
25                 - untagged pg0/pg1/pg2 interface
26                     pg0 -------> pg1 (IP ACL)
27                            \
28                             ---> pg2 (MAC ACL))
29                              \
30                               -> pg3 (PBR)
31             - setup interfaces:
32                 - put it into UP state
33                 - set IPv4 addresses
34                 - resolve neighbor address using ARP
35
36         :ivar list interfaces: pg interfaces.
37         :ivar list pg_if_packet_sizes: packet sizes in test.
38         :ivar dict acl_tbl_idx: ACL table index.
39         :ivar int pbr_vrfid: VRF id for PBR test.
40         """
41         super(TestClassifier, self).setUp()
42
43         # create 4 pg interfaces
44         self.create_pg_interfaces(range(4))
45
46         # packet sizes to test
47         self.pg_if_packet_sizes = [64, 9018]
48
49         self.interfaces = list(self.pg_interfaces)
50
51         # ACL & PBR vars
52         self.acl_tbl_idx = {}
53         self.pbr_vrfid = 200
54
55         # setup all interfaces
56         for intf in self.interfaces:
57             intf.admin_up()
58             intf.config_ip4()
59             intf.resolve_arp()
60
61     def tearDown(self):
62         """Run standard test teardown and acl related log."""
63         for intf in self.interfaces:
64             intf.unconfig_ip4()
65             intf.admin_down()
66
67         super(TestClassifier, self).tearDown()
68         if not self.vpp_dead:
69             self.logger.info(self.vapi.cli("show classify table verbose"))
70             self.logger.info(self.vapi.cli("show ip fib"))
71
72     def config_pbr_fib_entry(self, intf, is_add=1):
73         """Configure fib entry to route traffic toward PBR VRF table
74
75         :param VppInterface intf: destination interface to be routed for PBR.
76
77         """
78         addr_len = 24
79         self.vapi.ip_add_del_route(intf.local_ip4n,
80                                    addr_len,
81                                    intf.remote_ip4n,
82                                    table_id=self.pbr_vrfid,
83                                    is_add=is_add)
84
85     def create_stream(self, src_if, dst_if, packet_sizes):
86         """Create input packet stream for defined interfaces.
87
88         :param VppInterface src_if: Source Interface for packet stream.
89         :param VppInterface dst_if: Destination Interface for packet stream.
90         :param list packet_sizes: packet size to test.
91         """
92         pkts = []
93         for size in packet_sizes:
94             info = self.create_packet_info(src_if, dst_if)
95             payload = self.info_to_payload(info)
96             p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
97                  IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) /
98                  UDP(sport=1234, dport=5678) /
99                  Raw(payload))
100             info.data = p.copy()
101             self.extend_packet(p, size)
102             pkts.append(p)
103         return pkts
104
105     def verify_capture(self, dst_if, capture):
106         """Verify captured input packet stream for defined interface.
107
108         :param VppInterface dst_if: Interface to verify captured packet stream.
109         :param list capture: Captured packet stream.
110         """
111         self.logger.info("Verifying capture on interface %s" % dst_if.name)
112         last_info = dict()
113         for i in self.interfaces:
114             last_info[i.sw_if_index] = None
115         dst_sw_if_index = dst_if.sw_if_index
116         for packet in capture:
117             try:
118                 ip = packet[IP]
119                 udp = packet[UDP]
120                 payload_info = self.payload_to_info(str(packet[Raw]))
121                 packet_index = payload_info.index
122                 self.assertEqual(payload_info.dst, dst_sw_if_index)
123                 self.logger.debug(
124                     "Got packet on port %s: src=%u (id=%u)" %
125                     (dst_if.name, payload_info.src, packet_index))
126                 next_info = self.get_next_packet_info_for_interface2(
127                     payload_info.src, dst_sw_if_index,
128                     last_info[payload_info.src])
129                 last_info[payload_info.src] = next_info
130                 self.assertTrue(next_info is not None)
131                 self.assertEqual(packet_index, next_info.index)
132                 saved_packet = next_info.data
133                 # Check standard fields
134                 self.assertEqual(ip.src, saved_packet[IP].src)
135                 self.assertEqual(ip.dst, saved_packet[IP].dst)
136                 self.assertEqual(udp.sport, saved_packet[UDP].sport)
137                 self.assertEqual(udp.dport, saved_packet[UDP].dport)
138             except:
139                 self.logger.error(ppp("Unexpected or invalid packet:", packet))
140                 raise
141         for i in self.interfaces:
142             remaining_packet = self.get_next_packet_info_for_interface2(
143                 i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
144             self.assertTrue(remaining_packet is None,
145                             "Interface %s: Packet expected from interface %s "
146                             "didn't arrive" % (dst_if.name, i.name))
147
148     def verify_vrf(self, vrf_id):
149         """
150         Check if the FIB table / VRF ID is configured.
151
152         :param int vrf_id: The FIB table / VRF ID to be verified.
153         :return: 1 if the FIB table / VRF ID is configured, otherwise return 0.
154         """
155         ip_fib_dump = self.vapi.ip_fib_dump()
156         vrf_count = 0
157         for ip_fib_details in ip_fib_dump:
158             if ip_fib_details[2] == vrf_id:
159                 vrf_count += 1
160         if vrf_count == 0:
161             self.logger.info("IPv4 VRF ID %d is not configured" % vrf_id)
162             return 0
163         else:
164             self.logger.info("IPv4 VRF ID %d is configured" % vrf_id)
165             return 1
166
167     @staticmethod
168     def build_ip_mask(proto='', src_ip='', dst_ip='',
169                       src_port='', dst_port=''):
170         """Build IP ACL mask data with hexstring format
171
172         :param str proto: protocol number <0-ff>
173         :param str src_ip: source ip address <0-ffffffff>
174         :param str dst_ip: destination ip address <0-ffffffff>
175         :param str src_port: source port number <0-ffff>
176         :param str dst_port: destination port number <0-ffff>
177         """
178
179         return ('{:0>20}{:0>12}{:0>8}{:0>12}{:0>4}'.format(
180             proto, src_ip, dst_ip, src_port, dst_port)).rstrip('0')
181
182     @staticmethod
183     def build_ip_match(proto='', src_ip='', dst_ip='',
184                        src_port='', dst_port=''):
185         """Build IP ACL match data with hexstring format
186
187         :param str proto: protocol number with valid option "<0-ff>"
188         :param str src_ip: source ip address with format of "x.x.x.x"
189         :param str dst_ip: destination ip address with format of "x.x.x.x"
190         :param str src_port: source port number <0-ffff>
191         :param str dst_port: destination port number <0-ffff>
192         """
193         if src_ip:
194             src_ip = socket.inet_aton(src_ip).encode('hex')
195         if dst_ip:
196             dst_ip = socket.inet_aton(dst_ip).encode('hex')
197
198         return ('{:0>20}{:0>12}{:0>8}{:0>12}{:0>4}'.format(
199             proto, src_ip, dst_ip, src_port, dst_port)).rstrip('0')
200
201     @staticmethod
202     def build_mac_mask(dst_mac='', src_mac='', ether_type=''):
203         """Build MAC ACL mask data with hexstring format
204
205         :param str dst_mac: source MAC address <0-ffffffffffff>
206         :param str src_mac: destination MAC address <0-ffffffffffff>
207         :param str ether_type: ethernet type <0-ffff>
208         """
209
210         return ('{:0>12}{:0>12}{:0>4}'.format(dst_mac, src_mac,
211                                               ether_type)).rstrip('0')
212
213     @staticmethod
214     def build_mac_match(dst_mac='', src_mac='', ether_type=''):
215         """Build MAC ACL match data with hexstring format
216
217         :param str dst_mac: source MAC address <x:x:x:x:x:x>
218         :param str src_mac: destination MAC address <x:x:x:x:x:x>
219         :param str ether_type: ethernet type <0-ffff>
220         """
221         if dst_mac:
222             dst_mac = dst_mac.replace(':', '')
223         if src_mac:
224             src_mac = src_mac.replace(':', '')
225
226         return ('{:0>12}{:0>12}{:0>4}'.format(dst_mac, src_mac,
227                                               ether_type)).rstrip('0')
228
229     def create_classify_table(self, key, mask, data_offset=0, is_add=1):
230         """Create Classify Table
231
232         :param str key: key for classify table (ex, ACL name).
233         :param str mask: mask value for interested traffic.
234         :param int match_n_vectors:
235         :param int is_add: option to configure classify table.
236             - create(1) or delete(0)
237         """
238         r = self.vapi.classify_add_del_table(
239             is_add,
240             binascii.unhexlify(mask),
241             match_n_vectors=(len(mask) - 1) // 32 + 1,
242             miss_next_index=0,
243             current_data_flag=1,
244             current_data_offset=data_offset)
245         self.assertIsNotNone(r, msg='No response msg for add_del_table')
246         self.acl_tbl_idx[key] = r.new_table_index
247
248     def create_classify_session(self, intf, table_index, match,
249                                 pbr_option=0, vrfid=0, is_add=1):
250         """Create Classify Session
251
252         :param VppInterface intf: Interface to apply classify session.
253         :param int table_index: table index to identify classify table.
254         :param str match: matched value for interested traffic.
255         :param int pbr_action: enable/disable PBR feature.
256         :param int vrfid: VRF id.
257         :param int is_add: option to configure classify session.
258             - create(1) or delete(0)
259         """
260         r = self.vapi.classify_add_del_session(
261             is_add,
262             table_index,
263             binascii.unhexlify(match),
264             opaque_index=0,
265             action=pbr_option,
266             metadata=vrfid)
267         self.assertIsNotNone(r, msg='No response msg for add_del_session')
268
269     def input_acl_set_interface(self, intf, table_index, is_add=1):
270         """Configure Input ACL interface
271
272         :param VppInterface intf: Interface to apply Input ACL feature.
273         :param int table_index: table index to identify classify table.
274         :param int is_add: option to configure classify session.
275             - enable(1) or disable(0)
276         """
277         r = self.vapi.input_acl_set_interface(
278             is_add,
279             intf.sw_if_index,
280             ip4_table_index=table_index)
281         self.assertIsNotNone(r, msg='No response msg for acl_set_interface')
282
283     def output_acl_set_interface(self, intf, table_index, is_add=1):
284         """Configure Output ACL interface
285
286         :param VppInterface intf: Interface to apply Output ACL feature.
287         :param int table_index: table index to identify classify table.
288         :param int is_add: option to configure classify session.
289             - enable(1) or disable(0)
290         """
291         r = self.vapi.output_acl_set_interface(
292             is_add,
293             intf.sw_if_index,
294             ip4_table_index=table_index)
295         self.assertIsNotNone(r, msg='No response msg for acl_set_interface')
296
297     def test_acl_ip(self):
298         """ IP ACL test
299
300         Test scenario for basic IP ACL with source IP
301             - Create IPv4 stream for pg0 -> pg1 interface.
302             - Create ACL with source IP address.
303             - Send and verify received packets on pg1 interface.
304         """
305
306         # Basic ACL testing with source IP
307         pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes)
308         self.pg0.add_stream(pkts)
309
310         self.create_classify_table('ip', self.build_ip_mask(src_ip='ffffffff'))
311         self.create_classify_session(
312             self.pg0, self.acl_tbl_idx.get('ip'),
313             self.build_ip_match(src_ip=self.pg0.remote_ip4))
314         self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get('ip'))
315
316         self.pg_enable_capture(self.pg_interfaces)
317         self.pg_start()
318
319         pkts = self.pg1.get_capture(len(pkts))
320         self.verify_capture(self.pg1, pkts)
321         self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get('ip'), 0)
322         self.pg0.assert_nothing_captured(remark="packets forwarded")
323         self.pg2.assert_nothing_captured(remark="packets forwarded")
324         self.pg3.assert_nothing_captured(remark="packets forwarded")
325
326     def test_acl_ip_out(self):
327         """ Output IP ACL test
328
329         Test scenario for basic IP ACL with source IP
330             - Create IPv4 stream for pg1 -> pg0 interface.
331             - Create ACL with source IP address.
332             - Send and verify received packets on pg0 interface.
333         """
334
335         # Basic ACL testing with source IP
336         pkts = self.create_stream(self.pg1, self.pg0, self.pg_if_packet_sizes)
337         self.pg1.add_stream(pkts)
338
339         self.create_classify_table('ip', self.build_ip_mask(src_ip='ffffffff'),
340                                    data_offset=0)
341         self.create_classify_session(
342             self.pg1, self.acl_tbl_idx.get('ip'),
343             self.build_ip_match(src_ip=self.pg1.remote_ip4))
344         self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get('ip'))
345
346         self.pg_enable_capture(self.pg_interfaces)
347         self.pg_start()
348
349         pkts = self.pg0.get_capture(len(pkts))
350         self.verify_capture(self.pg0, pkts)
351         self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get('ip'), 0)
352         self.pg1.assert_nothing_captured(remark="packets forwarded")
353         self.pg2.assert_nothing_captured(remark="packets forwarded")
354         self.pg3.assert_nothing_captured(remark="packets forwarded")
355
356     def test_acl_mac(self):
357         """ MAC ACL test
358
359         Test scenario for basic MAC ACL with source MAC
360             - Create IPv4 stream for pg0 -> pg2 interface.
361             - Create ACL with source MAC address.
362             - Send and verify received packets on pg2 interface.
363         """
364
365         # Basic ACL testing with source MAC
366         pkts = self.create_stream(self.pg0, self.pg2, self.pg_if_packet_sizes)
367         self.pg0.add_stream(pkts)
368
369         self.create_classify_table('mac',
370                                    self.build_mac_mask(src_mac='ffffffffffff'),
371                                    data_offset=-14)
372         self.create_classify_session(
373             self.pg0, self.acl_tbl_idx.get('mac'),
374             self.build_mac_match(src_mac=self.pg0.remote_mac))
375         self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get('mac'))
376
377         self.pg_enable_capture(self.pg_interfaces)
378         self.pg_start()
379
380         pkts = self.pg2.get_capture(len(pkts))
381         self.verify_capture(self.pg2, pkts)
382         self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get('mac'), 0)
383         self.pg0.assert_nothing_captured(remark="packets forwarded")
384         self.pg1.assert_nothing_captured(remark="packets forwarded")
385         self.pg3.assert_nothing_captured(remark="packets forwarded")
386
387     def test_acl_pbr(self):
388         """ IP PBR test
389
390         Test scenario for PBR with source IP
391             - Create IPv4 stream for pg0 -> pg3 interface.
392             - Configure PBR fib entry for packet forwarding.
393             - Send and verify received packets on pg3 interface.
394         """
395
396         # PBR testing with source IP
397         pkts = self.create_stream(self.pg0, self.pg3, self.pg_if_packet_sizes)
398         self.pg0.add_stream(pkts)
399
400         self.create_classify_table(
401             'pbr', self.build_ip_mask(
402                 src_ip='ffffffff'))
403         pbr_option = 1
404         # this will create the VRF/table in which we will insert the route
405         self.create_classify_session(
406             self.pg0, self.acl_tbl_idx.get('pbr'),
407             self.build_ip_match(src_ip=self.pg0.remote_ip4),
408             pbr_option, self.pbr_vrfid)
409         self.assertTrue(self.verify_vrf(self.pbr_vrfid))
410         self.config_pbr_fib_entry(self.pg3)
411         self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get('pbr'))
412
413         self.pg_enable_capture(self.pg_interfaces)
414         self.pg_start()
415
416         pkts = self.pg3.get_capture(len(pkts))
417         self.verify_capture(self.pg3, pkts)
418         self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get('pbr'), 0)
419         self.pg0.assert_nothing_captured(remark="packets forwarded")
420         self.pg1.assert_nothing_captured(remark="packets forwarded")
421         self.pg2.assert_nothing_captured(remark="packets forwarded")
422
423         # remove the classify session and the route
424         self.config_pbr_fib_entry(self.pg3, is_add=0)
425         self.create_classify_session(
426             self.pg0, self.acl_tbl_idx.get('pbr'),
427             self.build_ip_match(src_ip=self.pg0.remote_ip4),
428             pbr_option, self.pbr_vrfid, is_add=0)
429
430         # and the table should be gone.
431         self.assertFalse(self.verify_vrf(self.pbr_vrfid))
432
433 if __name__ == '__main__':
434     unittest.main(testRunner=VppTestRunner)