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