blob: e21fdb810260d285940ff6e32ca7b765de4a9ae8 [file] [log] [blame]
Klement Sekeraacb9b8e2017-02-14 02:55:31 +01001""" test framework utilities """
2
Paul Vinciguerra3bce8eb2018-11-24 21:46:05 -08003import abc
Paul Vinciguerra2f156312020-05-02 22:34:40 -04004import ipaddress
Paul Vinciguerra9beabd82019-12-01 22:24:28 -05005import logging
Matej Klotton0178d522016-11-04 11:11:44 +01006import socket
Paul Vinciguerrae8fece82019-02-28 15:34:00 -08007from socket import AF_INET6
Klement Sekera7bb873a2016-11-18 07:38:42 +01008import sys
juraj.linkes40dd73b2018-09-21 13:55:16 +02009import os.path
Klement Sekera7bb873a2016-11-18 07:38:42 +010010
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -070011import scapy.compat
Andrew Yourtchenko92dc12a2017-09-07 13:22:24 +020012from scapy.layers.l2 import Ether
Klement Sekera75e7d132017-09-20 08:26:30 +020013from scapy.layers.inet import IP
14from scapy.layers.inet6 import IPv6, IPv6ExtHdrFragment, IPv6ExtHdrRouting,\
15 IPv6ExtHdrHopByHop
Paul Vinciguerrae8fece82019-02-28 15:34:00 -080016from scapy.packet import Raw
Klement Sekera611864f2018-09-26 11:19:00 +020017from scapy.utils import hexdump
Paul Vinciguerrae8fece82019-02-28 15:34:00 -080018from scapy.utils6 import in6_mactoifaceid
19
Ole Troan7f991832018-12-06 17:35:12 +010020from io import BytesIO
Ole Troan8006c6a2018-12-17 12:02:26 +010021from vpp_papi import mac_pton
Andrew Yourtchenko92dc12a2017-09-07 13:22:24 +020022
Paul Vinciguerra9beabd82019-12-01 22:24:28 -050023# Set up an empty logger for the testcase that can be overridden as necessary
24null_logger = logging.getLogger('VppTestCase.util')
25null_logger.addHandler(logging.NullHandler())
26
Klement Sekera7bb873a2016-11-18 07:38:42 +010027
28def ppp(headline, packet):
29 """ Return string containing the output of scapy packet.show() call. """
Paul Vinciguerrab951ad82019-01-08 21:36:39 -080030 return '%s\n%s\n\n%s\n' % (headline,
31 hexdump(packet, dump=True),
32 packet.show(dump=True))
Klement Sekera7bb873a2016-11-18 07:38:42 +010033
Damjan Marionf56b77a2016-10-03 19:44:57 +020034
Klement Sekera9225dee2016-12-12 08:36:58 +010035def ppc(headline, capture, limit=10):
36 """ Return string containing ppp() printout for a capture.
37
38 :param headline: printed as first line of output
39 :param capture: packets to print
40 :param limit: limit the print to # of packets
41 """
42 if not capture:
43 return headline
Klement Sekeradab231a2016-12-21 08:50:14 +010044 tail = ""
Klement Sekera9225dee2016-12-12 08:36:58 +010045 if limit < len(capture):
Klement Sekeradab231a2016-12-21 08:50:14 +010046 tail = "\nPrint limit reached, %s out of %s packets printed" % (
Klement Sekera75e7d132017-09-20 08:26:30 +020047 limit, len(capture))
Klement Sekeradab231a2016-12-21 08:50:14 +010048 body = "".join([ppp("Packet #%s:" % count, p)
49 for count, p in zip(range(0, limit), capture)])
50 return "%s\n%s%s" % (headline, body, tail)
Klement Sekera9225dee2016-12-12 08:36:58 +010051
52
Eyal Barid81da8c2017-01-11 13:39:54 +020053def ip4_range(ip4, s, e):
54 tmp = ip4.rsplit('.', 1)[0]
55 return ("%s.%d" % (tmp, i) for i in range(s, e))
56
57
Paul Vinciguerra2f156312020-05-02 22:34:40 -040058def mcast_ip_to_mac(ip):
59 ip = ipaddress.ip_address(ip)
60 if not ip.is_multicast:
61 raise ValueError("Must be multicast address.")
62 ip_as_int = int(ip)
63 if ip.version == 4:
64 mcast_mac = "01:00:5e:%02x:%02x:%02x" % ((ip_as_int >> 16) & 0x7f,
65 (ip_as_int >> 8) & 0xff,
66 ip_as_int & 0xff)
67 else:
68 mcast_mac = "33:33:%02x:%02x:%02x:%02x" % ((ip_as_int >> 24) & 0xff,
69 (ip_as_int >> 16) & 0xff,
70 (ip_as_int >> 8) & 0xff,
71 ip_as_int & 0xff)
72 return mcast_mac
Eyal Barid81da8c2017-01-11 13:39:54 +020073
74
Paul Vinciguerrae8fece82019-02-28 15:34:00 -080075# wrapper around scapy library function.
Neale Ranns2a3ea492017-04-19 05:24:40 -070076def mk_ll_addr(mac):
Ole Troan6ed154f2019-10-15 19:31:55 +020077 euid = in6_mactoifaceid(str(mac))
Neale Ranns2a3ea492017-04-19 05:24:40 -070078 addr = "fe80::" + euid
79 return addr
80
81
Juraj Sloboda4b9669d2018-01-15 10:39:21 +010082def ip6_normalize(ip6):
83 return socket.inet_ntop(socket.AF_INET6,
84 socket.inet_pton(socket.AF_INET6, ip6))
85
86
juraj.linkes40dd73b2018-09-21 13:55:16 +020087def get_core_path(tempdir):
88 return "%s/%s" % (tempdir, get_core_pattern())
89
90
91def is_core_present(tempdir):
92 return os.path.isfile(get_core_path(tempdir))
93
94
95def get_core_pattern():
Andrew Yourtchenko57612eb2018-03-28 15:32:10 +020096 with open("/proc/sys/kernel/core_pattern", "r") as f:
juraj.linkes40dd73b2018-09-21 13:55:16 +020097 corefmt = f.read().strip()
98 return corefmt
99
100
101def check_core_path(logger, core_path):
102 corefmt = get_core_pattern()
103 if corefmt.startswith("|"):
104 logger.error(
105 "WARNING: redirecting the core dump through a"
106 " filter may result in truncated dumps.")
107 logger.error(
108 " You may want to check the filter settings"
109 " or uninstall it and edit the"
110 " /proc/sys/kernel/core_pattern accordingly.")
111 logger.error(
112 " current core pattern is: %s" % corefmt)
Andrew Yourtchenko57612eb2018-03-28 15:32:10 +0200113
114
Paul Vinciguerrae061dad2020-12-04 14:57:51 -0500115class NumericConstant:
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200116
117 desc_dict = {}
118
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200119 def __init__(self, value):
120 self._value = value
121
122 def __int__(self):
123 return self._value
124
125 def __long__(self):
126 return self._value
127
128 def __str__(self):
129 if self._value in self.desc_dict:
130 return self.desc_dict[self._value]
131 return ""
132
133
Paul Vinciguerrae061dad2020-12-04 14:57:51 -0500134class Host:
Matej Klotton0178d522016-11-04 11:11:44 +0100135 """ Generic test host "connected" to VPPs interface. """
Damjan Marionf56b77a2016-10-03 19:44:57 +0200136
Klement Sekeraf62ae122016-10-11 11:47:09 +0200137 @property
138 def mac(self):
139 """ MAC address """
140 return self._mac
Damjan Marionf56b77a2016-10-03 19:44:57 +0200141
Klement Sekeraf62ae122016-10-11 11:47:09 +0200142 @property
Eyal Baric86e5922017-07-02 18:33:16 +0300143 def bin_mac(self):
144 """ MAC address """
Ole Troan8006c6a2018-12-17 12:02:26 +0100145 return mac_pton(self._mac)
Eyal Baric86e5922017-07-02 18:33:16 +0300146
147 @property
Klement Sekeraf62ae122016-10-11 11:47:09 +0200148 def ip4(self):
Klement Sekera46a87ad2017-01-02 08:22:23 +0100149 """ IPv4 address - string """
Klement Sekeraf62ae122016-10-11 11:47:09 +0200150 return self._ip4
Damjan Marionf56b77a2016-10-03 19:44:57 +0200151
Klement Sekeraf62ae122016-10-11 11:47:09 +0200152 @property
Matej Klotton0178d522016-11-04 11:11:44 +0100153 def ip4n(self):
Klement Sekera46a87ad2017-01-02 08:22:23 +0100154 """ IPv4 address of remote host - raw, suitable as API parameter."""
Matej Klotton0178d522016-11-04 11:11:44 +0100155 return socket.inet_pton(socket.AF_INET, self._ip4)
156
157 @property
Klement Sekeraf62ae122016-10-11 11:47:09 +0200158 def ip6(self):
Klement Sekera46a87ad2017-01-02 08:22:23 +0100159 """ IPv6 address - string """
Klement Sekeraf62ae122016-10-11 11:47:09 +0200160 return self._ip6
Damjan Marionf56b77a2016-10-03 19:44:57 +0200161
Klement Sekera46a87ad2017-01-02 08:22:23 +0100162 @property
163 def ip6n(self):
164 """ IPv6 address of remote host - raw, suitable as API parameter."""
165 return socket.inet_pton(socket.AF_INET6, self._ip6)
166
Neale Ranns2a3ea492017-04-19 05:24:40 -0700167 @property
168 def ip6_ll(self):
169 """ IPv6 link-local address - string """
170 return self._ip6_ll
171
172 @property
173 def ip6n_ll(self):
174 """ IPv6 link-local address of remote host -
175 raw, suitable as API parameter."""
176 return socket.inet_pton(socket.AF_INET6, self._ip6_ll)
177
Eyal Baric86e5922017-07-02 18:33:16 +0300178 def __eq__(self, other):
179 if isinstance(other, Host):
180 return (self.mac == other.mac and
181 self.ip4 == other.ip4 and
182 self.ip6 == other.ip6 and
183 self.ip6_ll == other.ip6_ll)
184 else:
185 return False
186
187 def __ne__(self, other):
188 return not self.__eq__(other)
189
190 def __repr__(self):
191 return "Host { mac:%s ip4:%s ip6:%s ip6_ll:%s }" % (self.mac,
192 self.ip4,
193 self.ip6,
194 self.ip6_ll)
195
196 def __hash__(self):
197 return hash(self.__repr__())
198
Neale Ranns2a3ea492017-04-19 05:24:40 -0700199 def __init__(self, mac=None, ip4=None, ip6=None, ip6_ll=None):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200200 self._mac = mac
201 self._ip4 = ip4
202 self._ip6 = ip6
Neale Ranns2a3ea492017-04-19 05:24:40 -0700203 self._ip6_ll = ip6_ll
Filip Tehlar770e89e2017-01-31 10:39:16 +0100204
205
Andrew Yourtchenko92dc12a2017-09-07 13:22:24 +0200206class L4_Conn():
207 """ L4 'connection' tied to two VPP interfaces """
Klement Sekera75e7d132017-09-20 08:26:30 +0200208
Andrew Yourtchenko92dc12a2017-09-07 13:22:24 +0200209 def __init__(self, testcase, if1, if2, af, l4proto, port1, port2):
210 self.testcase = testcase
211 self.ifs = [None, None]
212 self.ifs[0] = if1
213 self.ifs[1] = if2
214 self.address_family = af
215 self.l4proto = l4proto
216 self.ports = [None, None]
217 self.ports[0] = port1
218 self.ports[1] = port2
219 self
220
221 def pkt(self, side, l4args={}, payload="x"):
222 is_ip6 = 1 if self.address_family == AF_INET6 else 0
223 s0 = side
Klement Sekera75e7d132017-09-20 08:26:30 +0200224 s1 = 1 - side
Andrew Yourtchenko92dc12a2017-09-07 13:22:24 +0200225 src_if = self.ifs[s0]
226 dst_if = self.ifs[s1]
227 layer_3 = [IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4),
228 IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6)]
229 merged_l4args = {'sport': self.ports[s0], 'dport': self.ports[s1]}
230 merged_l4args.update(l4args)
231 p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
232 layer_3[is_ip6] /
233 self.l4proto(**merged_l4args) /
234 Raw(payload))
235 return p
236
237 def send(self, side, flags=None, payload=""):
238 l4args = {}
239 if flags is not None:
240 l4args['flags'] = flags
241 self.ifs[side].add_stream(self.pkt(side,
242 l4args=l4args, payload=payload))
Klement Sekera75e7d132017-09-20 08:26:30 +0200243 self.ifs[1 - side].enable_capture()
Andrew Yourtchenko92dc12a2017-09-07 13:22:24 +0200244 self.testcase.pg_start()
245
246 def recv(self, side):
247 p = self.ifs[side].wait_for_packet(1)
248 return p
249
250 def send_through(self, side, flags=None, payload=""):
251 self.send(side, flags, payload)
Klement Sekera75e7d132017-09-20 08:26:30 +0200252 p = self.recv(1 - side)
Andrew Yourtchenko92dc12a2017-09-07 13:22:24 +0200253 return p
254
255 def send_pingpong(self, side, flags1=None, flags2=None):
256 p1 = self.send_through(side, flags1)
Klement Sekera75e7d132017-09-20 08:26:30 +0200257 p2 = self.send_through(1 - side, flags2)
Andrew Yourtchenko92dc12a2017-09-07 13:22:24 +0200258 return [p1, p2]
259
260
261class L4_CONN_SIDE:
262 L4_CONN_SIDE_ZERO = 0
263 L4_CONN_SIDE_ONE = 1
Klement Sekera75e7d132017-09-20 08:26:30 +0200264
265
Paul Vinciguerra9beabd82019-12-01 22:24:28 -0500266def fragment_rfc791(packet, fragsize, logger=null_logger):
Klement Sekera75e7d132017-09-20 08:26:30 +0200267 """
268 Fragment an IPv4 packet per RFC 791
269 :param packet: packet to fragment
270 :param fragsize: size at which to fragment
271 :note: IP options are not supported
272 :returns: list of fragments
273 """
Klement Sekera75e7d132017-09-20 08:26:30 +0200274 logger.debug(ppp("Fragmenting packet:", packet))
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -0700275 packet = packet.__class__(scapy.compat.raw(packet)) # recalc. all values
Klement Sekera75e7d132017-09-20 08:26:30 +0200276 if len(packet[IP].options) > 0:
277 raise Exception("Not implemented")
278 if len(packet) <= fragsize:
279 return [packet]
280
281 pre_ip_len = len(packet) - len(packet[IP])
282 ip_header_len = packet[IP].ihl * 4
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -0700283 hex_packet = scapy.compat.raw(packet)
Klement Sekera75e7d132017-09-20 08:26:30 +0200284 hex_headers = hex_packet[:(pre_ip_len + ip_header_len)]
285 hex_payload = hex_packet[(pre_ip_len + ip_header_len):]
286
287 pkts = []
288 ihl = packet[IP].ihl
289 otl = len(packet[IP])
snaramre3030bea2019-10-17 16:39:03 +0000290 nfb = int((fragsize - pre_ip_len - ihl * 4) / 8)
Klement Sekera75e7d132017-09-20 08:26:30 +0200291 fo = packet[IP].frag
292
293 p = packet.__class__(hex_headers + hex_payload[:nfb * 8])
294 p[IP].flags = "MF"
295 p[IP].frag = fo
296 p[IP].len = ihl * 4 + nfb * 8
297 del p[IP].chksum
298 pkts.append(p)
299
300 p = packet.__class__(hex_headers + hex_payload[nfb * 8:])
301 p[IP].len = otl - nfb * 8
302 p[IP].frag = fo + nfb
303 del p[IP].chksum
304
Paul Vinciguerra9beabd82019-12-01 22:24:28 -0500305 more_fragments = fragment_rfc791(p, fragsize, logger)
Klement Sekera75e7d132017-09-20 08:26:30 +0200306 pkts.extend(more_fragments)
307
308 return pkts
309
310
Paul Vinciguerra9beabd82019-12-01 22:24:28 -0500311def fragment_rfc8200(packet, identification, fragsize, logger=null_logger):
Klement Sekera75e7d132017-09-20 08:26:30 +0200312 """
313 Fragment an IPv6 packet per RFC 8200
314 :param packet: packet to fragment
315 :param fragsize: size at which to fragment
316 :note: IP options are not supported
317 :returns: list of fragments
318 """
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -0700319 packet = packet.__class__(scapy.compat.raw(packet)) # recalc. all values
Klement Sekera75e7d132017-09-20 08:26:30 +0200320 if len(packet) <= fragsize:
321 return [packet]
322 logger.debug(ppp("Fragmenting packet:", packet))
323 pkts = []
324 counter = 0
325 routing_hdr = None
326 hop_by_hop_hdr = None
327 upper_layer = None
328 seen_ipv6 = False
329 ipv6_nr = -1
330 l = packet.getlayer(counter)
331 while l is not None:
332 if l.__class__ is IPv6:
333 if seen_ipv6:
334 # ignore 2nd IPv6 header and everything below..
335 break
336 ipv6_nr = counter
337 seen_ipv6 = True
338 elif l.__class__ is IPv6ExtHdrFragment:
339 raise Exception("Already fragmented")
340 elif l.__class__ is IPv6ExtHdrRouting:
341 routing_hdr = counter
342 elif l.__class__ is IPv6ExtHdrHopByHop:
343 hop_by_hop_hdr = counter
344 elif seen_ipv6 and not upper_layer and \
345 not l.__class__.__name__.startswith('IPv6ExtHdr'):
346 upper_layer = counter
347 counter = counter + 1
348 l = packet.getlayer(counter)
349
350 logger.debug(
351 "Layers seen: IPv6(#%s), Routing(#%s), HopByHop(#%s), upper(#%s)" %
352 (ipv6_nr, routing_hdr, hop_by_hop_hdr, upper_layer))
353
354 if upper_layer is None:
355 raise Exception("Upper layer header not found in IPv6 packet")
356
357 last_per_fragment_hdr = ipv6_nr
358 if routing_hdr is None:
359 if hop_by_hop_hdr is not None:
360 last_per_fragment_hdr = hop_by_hop_hdr
361 else:
362 last_per_fragment_hdr = routing_hdr
363 logger.debug("Last per-fragment hdr is #%s" % (last_per_fragment_hdr))
364
365 per_fragment_headers = packet.copy()
366 per_fragment_headers[last_per_fragment_hdr].remove_payload()
367 logger.debug(ppp("Per-fragment headers:", per_fragment_headers))
368
369 ext_and_upper_layer = packet.getlayer(last_per_fragment_hdr)[1]
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -0700370 hex_payload = scapy.compat.raw(ext_and_upper_layer)
Klement Sekera75e7d132017-09-20 08:26:30 +0200371 logger.debug("Payload length is %s" % len(hex_payload))
372 logger.debug(ppp("Ext and upper layer:", ext_and_upper_layer))
373
374 fragment_ext_hdr = IPv6ExtHdrFragment()
375 logger.debug(ppp("Fragment header:", fragment_ext_hdr))
376
Neale Ranns14046982019-07-29 14:49:52 +0000377 len_ext_and_upper_layer_payload = len(ext_and_upper_layer.payload)
378 if not len_ext_and_upper_layer_payload and \
379 hasattr(ext_and_upper_layer, "data"):
380 len_ext_and_upper_layer_payload = len(ext_and_upper_layer.data)
381
Klement Sekera75e7d132017-09-20 08:26:30 +0200382 if len(per_fragment_headers) + len(fragment_ext_hdr) +\
Neale Ranns14046982019-07-29 14:49:52 +0000383 len(ext_and_upper_layer) - len_ext_and_upper_layer_payload\
Klement Sekera75e7d132017-09-20 08:26:30 +0200384 > fragsize:
385 raise Exception("Cannot fragment this packet - MTU too small "
386 "(%s, %s, %s, %s, %s)" % (
387 len(per_fragment_headers), len(fragment_ext_hdr),
388 len(ext_and_upper_layer),
Neale Ranns14046982019-07-29 14:49:52 +0000389 len_ext_and_upper_layer_payload, fragsize))
Klement Sekera75e7d132017-09-20 08:26:30 +0200390
391 orig_nh = packet[IPv6].nh
392 p = per_fragment_headers
393 del p[IPv6].plen
394 del p[IPv6].nh
395 p = p / fragment_ext_hdr
396 del p[IPv6ExtHdrFragment].nh
snaramre3030bea2019-10-17 16:39:03 +0000397 first_payload_len_nfb = int((fragsize - len(p)) / 8)
Klement Sekera75e7d132017-09-20 08:26:30 +0200398 p = p / Raw(hex_payload[:first_payload_len_nfb * 8])
399 del p[IPv6].plen
400 p[IPv6ExtHdrFragment].nh = orig_nh
401 p[IPv6ExtHdrFragment].id = identification
402 p[IPv6ExtHdrFragment].offset = 0
403 p[IPv6ExtHdrFragment].m = 1
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -0700404 p = p.__class__(scapy.compat.raw(p))
Klement Sekera75e7d132017-09-20 08:26:30 +0200405 logger.debug(ppp("Fragment %s:" % len(pkts), p))
406 pkts.append(p)
407 offset = first_payload_len_nfb * 8
408 logger.debug("Offset after first fragment: %s" % offset)
409 while len(hex_payload) > offset:
410 p = per_fragment_headers
411 del p[IPv6].plen
412 del p[IPv6].nh
413 p = p / fragment_ext_hdr
414 del p[IPv6ExtHdrFragment].nh
snaramre3030bea2019-10-17 16:39:03 +0000415 l_nfb = int((fragsize - len(p)) / 8)
Klement Sekera75e7d132017-09-20 08:26:30 +0200416 p = p / Raw(hex_payload[offset:offset + l_nfb * 8])
417 p[IPv6ExtHdrFragment].nh = orig_nh
418 p[IPv6ExtHdrFragment].id = identification
snaramre3030bea2019-10-17 16:39:03 +0000419 p[IPv6ExtHdrFragment].offset = int(offset / 8)
Klement Sekera75e7d132017-09-20 08:26:30 +0200420 p[IPv6ExtHdrFragment].m = 1
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -0700421 p = p.__class__(scapy.compat.raw(p))
Klement Sekera75e7d132017-09-20 08:26:30 +0200422 logger.debug(ppp("Fragment %s:" % len(pkts), p))
423 pkts.append(p)
424 offset = offset + l_nfb * 8
425
426 pkts[-1][IPv6ExtHdrFragment].m = 0 # reset more-flags in last fragment
427
428 return pkts
Ole Troan7f991832018-12-06 17:35:12 +0100429
430
431def reassemble4_core(listoffragments, return_ip):
432 buffer = BytesIO()
433 first = listoffragments[0]
434 buffer.seek(20)
435 for pkt in listoffragments:
436 buffer.seek(pkt[IP].frag*8)
437 buffer.write(bytes(pkt[IP].payload))
438 first.len = len(buffer.getvalue()) + 20
439 first.flags = 0
440 del(first.chksum)
441 if return_ip:
442 header = bytes(first[IP])[:20]
443 return first[IP].__class__(header + buffer.getvalue())
444 else:
445 header = bytes(first[Ether])[:34]
446 return first[Ether].__class__(header + buffer.getvalue())
447
448
449def reassemble4_ether(listoffragments):
450 return reassemble4_core(listoffragments, False)
451
452
453def reassemble4(listoffragments):
454 return reassemble4_core(listoffragments, True)