VIRL test: Replace IP probe for VXLAN test
[csit.git] / resources / libraries / python / PacketVerifier.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """PacketVerifier module.
15
16     :Example:
17
18     >>> from scapy.all import *
19     >>> from PacketVerifier import *
20     >>> rxq = RxQueue('eth1')
21     >>> txq = TxQueue('eth1')
22     >>> src_mac = "AA:BB:CC:DD:EE:FF"
23     >>> dst_mac = "52:54:00:ca:5d:0b"
24     >>> src_ip = "11.11.11.10"
25     >>> dst_ip = "11.11.11.11"
26     >>> sent_packets = []
27     >>> pkt_send = Ether(src=src_mac, dst=dst_mac) /
28     ... IP(src=src_ip, dst=dst_ip) /
29     ... ICMP()
30     >>> sent_packets.append(pkt_send)
31     >>> txq.send(pkt_send)
32     >>> pkt_send = Ether(src=src_mac, dst=dst_mac) /
33     ... ARP(hwsrc=src_mac, psrc=src_ip, hwdst=dst_mac, pdst=dst_ip, op=2)
34     >>> sent_packets.append(pkt_send)
35     >>> txq.send(pkt_send)
36     >>> rxq.recv(100, sent_packets).show()
37     ###[ Ethernet ]###
38       dst       = aa:bb:cc:dd:ee:ff
39       src       = 52:54:00:ca:5d:0b
40       type      = 0x800
41     ###[ IP ]###
42       version   = 4L
43       ihl       = 5L
44       tos       = 0x0
45       len       = 28
46       id        = 43183
47       flags     =
48       frag      = 0L
49       ttl       = 64
50       proto     = icmp
51       chksum    = 0xa607
52       src       = 11.11.11.11
53       dst       = 11.11.11.10
54       options
55     ###[ ICMP ]###
56       type      = echo-reply
57       code      = 0
58       chksum    = 0xffff
59       id        = 0x0
60       seq       = 0x0
61     ###[ Padding ]###
62       load = 'RT\x00\xca]\x0b\xaa\xbb\xcc\xdd\xee\xff\x08\x06\x00\x01\x08\x00'
63 """
64
65
66 import os
67 import socket
68 import select
69
70 from scapy.all import ETH_P_IP, ETH_P_IPV6, ETH_P_ALL, ETH_P_ARP
71 from scapy.all import Ether, ARP
72 from scapy.layers.inet6 import IPv6
73
74 __all__ = ['RxQueue', 'TxQueue', 'Interface', 'create_gratuitous_arp_request',
75            'auto_pad', 'checksum_equal']
76
77 # TODO: http://stackoverflow.com/questions/320232/
78 # ensuring-subprocesses-are-dead-on-exiting-python-program
79
80
81 class PacketVerifier(object):
82     """Base class for TX and RX queue objects for packet verifier."""
83     def __init__(self, interface_name):
84         os.system('sudo echo 1 > /proc/sys/net/ipv6/conf/{0}/disable_ipv6'
85                   .format(interface_name))
86         os.system('sudo ip link set {0} up promisc on'.format(interface_name))
87         self._sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
88                                    ETH_P_ALL)
89         self._sock.bind((interface_name, ETH_P_ALL))
90         self._ifname = interface_name
91
92
93 def extract_one_packet(buf):
94     """Extract one packet from the incoming buf buffer.
95
96     Takes string as input and looks for first whole packet in it.
97     If it finds one, it returns substring from the buf parameter.
98
99     :param buf: String representation of incoming packet buffer.
100     :type buf: str
101     :returns: String representation of first packet in buf.
102     :rtype: str
103     """
104     pkt_len = 0
105
106     if len(buf) < 60:
107         return None
108
109     try:
110         ether_type = Ether(buf[0:14]).type
111     except AttributeError:
112         raise RuntimeError(
113             'No EtherType in packet {0}'.format(buf.__repr__()))
114
115     if ether_type == ETH_P_IP:
116         # 14 is Ethernet fame header size.
117         # 4 bytes is just enough to look for length in ip header.
118         # ip total length contains just the IP packet length so add the Ether
119         #     header.
120         pkt_len = Ether(buf[0:14+4]).len + 14
121         if len(buf) < 60:
122             return None
123     elif ether_type == ETH_P_IPV6:
124         if not Ether(buf[0:14+6]).haslayer(IPv6):
125             raise RuntimeError(
126                 'Invalid IPv6 packet {0}'.format(buf.__repr__()))
127         # ... to add to the above, 40 bytes is the length of IPV6 header.
128         #   The ipv6.len only contains length of the payload and not the header
129         pkt_len = Ether(buf)['IPv6'].plen + 14 + 40
130         if len(buf) < 60:
131             return None
132     elif ether_type == ETH_P_ARP:
133         pkt = Ether(buf[:20])
134         if not pkt.haslayer(ARP):
135             raise RuntimeError('Incomplete ARP packet')
136         # len(eth) + arp(2 hw addr type + 2 proto addr type
137         #                + 1b len + 1b len + 2b operation)
138
139         pkt_len = 14 + 8
140         pkt_len += 2 * pkt.getlayer(ARP).hwlen
141         pkt_len += 2 * pkt.getlayer(ARP).plen
142
143         del pkt
144     elif ether_type == 32821:  # RARP (Reverse ARP)
145         pkt = Ether(buf[:20])
146         pkt.type = ETH_P_ARP  # Change to ARP so it works with scapy
147         pkt = Ether(str(pkt))
148         if not pkt.haslayer(ARP):
149             pkt.show()
150             raise RuntimeError('Incomplete RARP packet')
151
152         # len(eth) + arp(2 hw addr type + 2 proto addr type
153         #                + 1b len + 1b len + 2b operation)
154         pkt_len = 14 + 8
155         pkt_len += 2 * pkt.getlayer(ARP).hwlen
156         pkt_len += 2 * pkt.getlayer(ARP).plen
157
158         del pkt
159     else:
160         raise RuntimeError('Unknown protocol {0}'.format(ether_type))
161
162     if pkt_len < 60:
163         pkt_len = 60
164
165     if len(buf) < pkt_len:
166         return None
167
168     return buf[0:pkt_len]
169
170
171 def packet_reader(interface_name, queue):
172     """Sub-process routine that reads packets and puts them to queue.
173
174     This function is meant to be run in separate subprocess and is in tight
175     loop reading raw packets from interface passed as parameter.
176
177     :param interface_name: Name of interface to read packets from.
178     :param queue: Queue in which this function will push incoming packets.
179     :type interface_name: str
180     :type queue: multiprocessing.Queue
181     :returns: None
182     """
183     sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, ETH_P_ALL)
184     sock.bind((interface_name, ETH_P_ALL))
185
186     while True:
187         pkt = sock.recv(0x7fff)
188         queue.put(pkt)
189
190
191 class RxQueue(PacketVerifier):
192     """Receive queue object.
193
194     This object creates raw socket, reads packets from it and provides
195     function to access them.
196
197     :param interface_name: Which interface to bind to.
198     :type interface_name: str
199     """
200     def __init__(self, interface_name):
201         PacketVerifier.__init__(self, interface_name)
202
203     def recv(self, timeout=3, ignore=None, verbose=True):
204         """Read next received packet.
205
206         Returns scapy's Ether() object created from next packet in the queue.
207         Queue is being filled in parallel in subprocess. If no packet
208         arrives in given timeout queue.Empty exception will be risen.
209
210         :param timeout: How many seconds to wait for next packet.
211         :param ignore: List of packets that should be ignored.
212         :param verbose: Used to suppress detailed logging of received packets.
213         :type timeout: int
214         :type ignore: list
215         :type verbose: bool
216
217         :returns: Ether() initialized object from packet data.
218         :rtype: scapy.Ether
219         """
220         (rlist, _, _) = select.select([self._sock], [], [], timeout)
221         if self._sock not in rlist:
222             return None
223
224         pkt = self._sock.recv(0x7fff)
225         pkt_pad = auto_pad(pkt)
226         print'Received packet on {0} of len {1}'.format(self._ifname, len(pkt))
227         if verbose:
228             Ether(pkt).show2()
229             print
230
231         if ignore is not None:
232             for i, ig_pkt in enumerate(ignore):
233                 # Auto pad all packets in ignore list
234                 ignore[i] = auto_pad(ig_pkt)
235             for ig_pkt in ignore:
236                 if ig_pkt == pkt_pad:
237                     # Found the packet in ignore list, get another one
238                     # TODO: subtract timeout - time_spent in here
239                     ignore.remove(ig_pkt)
240                     return self.recv(timeout, ignore, verbose)
241
242         return Ether(pkt)
243
244
245 class TxQueue(PacketVerifier):
246     """Transmission queue object.
247
248     This object is used to send packets over RAW socket on a interface.
249
250     :param interface_name: Which interface to send packets from.
251     :type interface_name: str
252     """
253     def __init__(self, interface_name):
254         PacketVerifier.__init__(self, interface_name)
255
256     def send(self, pkt, verbose=True):
257         """Send packet out of the bound interface.
258
259         :param pkt: Packet to send.
260         :param verbose: Used to supress detailed logging of sent packets.
261         :type pkt: string or scapy Packet derivative.
262         :type verbose: bool
263         """
264         print 'Sending packet out of {0} of len {1}'.format(self._ifname,
265                                                             len(pkt))
266         if verbose:
267             Ether(str(pkt)).show2()
268             print
269
270         pkt = auto_pad(str(pkt))
271         self._sock.send(pkt)
272
273
274 class Interface(object):
275     """Class for network interfaces. Contains methods for sending and receiving
276      packets."""
277     def __init__(self, if_name):
278         """Initialize the interface class.
279
280         :param if_name: Name of the interface.
281         :type if_name: str
282         """
283         self.if_name = if_name
284         self.sent_packets = []
285         self.rxq = RxQueue(if_name)
286         self.txq = TxQueue(if_name)
287
288     def send_pkt(self, pkt):
289         """Send the provided packet out the interface."""
290         self.sent_packets.append(pkt)
291         self.txq.send(pkt)
292
293     def recv_pkt(self, timeout=3):
294         """Read one packet from the interface's receive queue.
295
296         :param timeout: Timeout value in seconds.
297         :type timeout: int
298         :returns: Ether() initialized object from packet data.
299         :rtype: scapy.Ether
300         """
301         return self.rxq.recv(timeout, self.sent_packets)
302
303
304 def create_gratuitous_arp_request(src_mac, src_ip):
305     """Creates scapy representation of gratuitous ARP request."""
306     return (Ether(src=src_mac, dst='ff:ff:ff:ff:ff:ff') /
307             ARP(psrc=src_ip, hwsrc=src_mac, pdst=src_ip))
308
309
310 def auto_pad(packet):
311     """Pads zeroes at the end of the packet if the total len < 60 bytes."""
312     padded = str(packet)
313     if len(padded) < 60:
314         padded += ('\0' * (60 - len(padded)))
315     return padded
316
317
318 def checksum_equal(chksum1, chksum2):
319     """Compares two checksums in one's complement notation.
320
321     Checksums to be compared are calculated as 16 bit one's complement of the
322     one's complement sum of 16 bit words of some buffer.
323     In one's complement notation 0x0000 (positive zero) and 0xFFFF
324     (negative zero) are equivalent.
325
326     :param chksum1: First checksum.
327     :param chksum2: Second checksum.
328     :type chksum1: uint16
329     :type chksum2: uint16
330
331     :returns: True if checksums are equivalent, False otherwise.
332     :rtype: boolean
333     """
334     if chksum1 == 0xFFFF:
335         chksum1 = 0
336     if chksum2 == 0xFFFF:
337         chksum2 = 0
338     return chksum1 == chksum2