Add output.xml with only INFO logging leve
[csit.git] / resources / libraries / python / PacketVerifier.py
1 # Copyright (c) 2018 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   Example end.
65 """
66
67 import os
68 import select
69
70 from scapy.config import conf
71 from scapy.all import ETH_P_IP, ETH_P_IPV6, ETH_P_ALL, ETH_P_ARP
72 from scapy.layers.inet6 import IPv6
73 from scapy.layers.l2 import Ether, ARP
74
75 # Enable libpcap's L2listen
76 conf.use_pcap = True
77 import scapy.arch.pcapdnet  # pylint: disable=C0413, unused-import
78
79 __all__ = ['RxQueue', 'TxQueue', 'Interface', 'create_gratuitous_arp_request',
80            'auto_pad', 'checksum_equal']
81
82 # TODO: http://stackoverflow.com/questions/320232/
83 # ensuring-subprocesses-are-dead-on-exiting-python-program
84
85
86 class PacketVerifier(object):
87     """Base class for TX and RX queue objects for packet verifier."""
88     def __init__(self, interface_name):
89         os.system('sudo echo 1 > /proc/sys/net/ipv6/conf/{0}/disable_ipv6'
90                   .format(interface_name))
91         os.system('sudo ip link set {0} up promisc on'.format(interface_name))
92         self._ifname = interface_name
93
94
95 def extract_one_packet(buf):
96     """Extract one packet from the incoming buf buffer.
97
98     Takes string as input and looks for first whole packet in it.
99     If it finds one, it returns substring from the buf parameter.
100
101     :param buf: String representation of incoming packet buffer.
102     :type buf: str
103     :returns: String representation of first packet in buf.
104     :rtype: str
105     """
106     pkt_len = 0
107
108     if len(buf) < 60:
109         return None
110
111     try:
112         ether_type = Ether(buf[0:14]).type
113     except AttributeError:
114         raise RuntimeError(
115             'No EtherType in packet {0}'.format(buf.__repr__()))
116
117     if ether_type == ETH_P_IP:
118         # 14 is Ethernet fame header size.
119         # 4 bytes is just enough to look for length in ip header.
120         # ip total length contains just the IP packet length so add the Ether
121         #     header.
122         pkt_len = Ether(buf[0:14+4]).len + 14
123         if len(buf) < 60:
124             return None
125     elif ether_type == ETH_P_IPV6:
126         if not Ether(buf[0:14+6]).haslayer(IPv6):
127             raise RuntimeError(
128                 'Invalid IPv6 packet {0}'.format(buf.__repr__()))
129         # ... to add to the above, 40 bytes is the length of IPV6 header.
130         #   The ipv6.len only contains length of the payload and not the header
131         pkt_len = Ether(buf)['IPv6'].plen + 14 + 40
132         if len(buf) < 60:
133             return None
134     elif ether_type == ETH_P_ARP:
135         pkt = Ether(buf[:20])
136         if not pkt.haslayer(ARP):
137             raise RuntimeError('Incomplete ARP packet')
138         # len(eth) + arp(2 hw addr type + 2 proto addr type
139         #                + 1b len + 1b len + 2b operation)
140
141         pkt_len = 14 + 8
142         pkt_len += 2 * pkt.getlayer(ARP).hwlen
143         pkt_len += 2 * pkt.getlayer(ARP).plen
144
145         del pkt
146     elif ether_type == 32821:  # RARP (Reverse ARP)
147         pkt = Ether(buf[:20])
148         pkt.type = ETH_P_ARP  # Change to ARP so it works with scapy
149         pkt = Ether(str(pkt))
150         if not pkt.haslayer(ARP):
151             pkt.show()
152             raise RuntimeError('Incomplete RARP packet')
153
154         # len(eth) + arp(2 hw addr type + 2 proto addr type
155         #                + 1b len + 1b len + 2b operation)
156         pkt_len = 14 + 8
157         pkt_len += 2 * pkt.getlayer(ARP).hwlen
158         pkt_len += 2 * pkt.getlayer(ARP).plen
159
160         del pkt
161     else:
162         raise RuntimeError('Unknown protocol {0}'.format(ether_type))
163
164     if pkt_len < 60:
165         pkt_len = 60
166
167     if len(buf) < pkt_len:
168         return None
169
170     return buf[0:pkt_len]
171
172
173 def packet_reader(interface_name, queue):
174     """Sub-process routine that reads packets and puts them to queue.
175
176     This function is meant to be run in separate subprocess and is in tight
177     loop reading raw packets from interface passed as parameter.
178
179     :param interface_name: Name of interface to read packets from.
180     :param queue: Queue in which this function will push incoming packets.
181     :type interface_name: str
182     :type queue: multiprocessing.Queue
183     """
184     sock = conf.L2listen(iface=interface_name, type=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         self._sock = conf.L2listen(iface=interface_name, type=ETH_P_ALL)
203
204     def recv(self, timeout=3, ignore=None, verbose=True):
205         """Read next received packet.
206
207         Returns scapy's Ether() object created from next packet in the queue.
208         Queue is being filled in parallel in subprocess. If no packet
209         arrives in given timeout queue.Empty exception will be risen.
210
211         :param timeout: How many seconds to wait for next packet.
212         :param ignore: List of packets that should be ignored.
213         :param verbose: Used to suppress detailed logging of received packets.
214         :type timeout: int
215         :type ignore: list
216         :type verbose: bool
217
218         :returns: Ether() initialized object from packet data.
219         :rtype: scapy.Ether
220         """
221         ignore_list = list()
222         if ignore is not None:
223             for ig_pkt in ignore:
224                 # Auto pad all packets in ignore list
225                 ignore_list.append(auto_pad(ig_pkt))
226         while True:
227             (rlist, _, _) = select.select([self._sock], [], [], timeout)
228             if self._sock not in rlist:
229                 return None
230
231             pkt = self._sock.recv(0x7fff)
232             pkt_pad = auto_pad(pkt)
233             print 'Received packet on {0} of len {1}'\
234                 .format(self._ifname, len(pkt))
235             if verbose:
236                 pkt.show2()  # pylint: disable=no-member
237                 print
238             if pkt_pad in ignore_list:
239                 ignore_list.remove(pkt_pad)
240                 print 'Received packet ignored.'
241                 continue
242             else:
243                 return pkt
244
245
246 class TxQueue(PacketVerifier):
247     """Transmission queue object.
248
249     This object is used to send packets over RAW socket on a interface.
250
251     :param interface_name: Which interface to send packets from.
252     :type interface_name: str
253     """
254     def __init__(self, interface_name):
255         PacketVerifier.__init__(self, interface_name)
256         self._sock = conf.L2socket(iface=interface_name, type=ETH_P_ALL)
257
258     def send(self, pkt, verbose=True):
259         """Send packet out of the bound interface.
260
261         :param pkt: Packet to send.
262         :param verbose: Used to supress detailed logging of sent packets.
263         :type pkt: string or scapy Packet derivative.
264         :type verbose: bool
265         """
266         print 'Sending packet out of {0} of len {1}'.format(self._ifname,
267                                                             len(pkt))
268         if verbose:
269             Ether(str(pkt)).show2()
270             print
271
272         pkt = auto_pad(str(pkt))
273         self._sock.send(pkt)
274
275
276 class Interface(object):
277     """Class for network interfaces. Contains methods for sending and receiving
278      packets."""
279     def __init__(self, if_name):
280         """Initialize the interface class.
281
282         :param if_name: Name of the interface.
283         :type if_name: str
284         """
285         self.if_name = if_name
286         self.sent_packets = []
287         self.rxq = RxQueue(if_name)
288         self.txq = TxQueue(if_name)
289
290     def send_pkt(self, pkt):
291         """Send the provided packet out the interface."""
292         self.sent_packets.append(pkt)
293         self.txq.send(pkt)
294
295     def recv_pkt(self, timeout=3):
296         """Read one packet from the interface's receive queue.
297
298         :param timeout: Timeout value in seconds.
299         :type timeout: int
300         :returns: Ether() initialized object from packet data.
301         :rtype: scapy.Ether
302         """
303         return self.rxq.recv(timeout, self.sent_packets)
304
305
306 def create_gratuitous_arp_request(src_mac, src_ip):
307     """Creates scapy representation of gratuitous ARP request."""
308     return (Ether(src=src_mac, dst='ff:ff:ff:ff:ff:ff') /
309             ARP(psrc=src_ip, hwsrc=src_mac, pdst=src_ip))
310
311
312 def auto_pad(packet):
313     """Pads zeroes at the end of the packet if the total len < 60 bytes."""
314     padded = str(packet)
315     if len(padded) < 60:
316         padded += ('\0' * (60 - len(padded)))
317     return padded
318
319
320 def checksum_equal(chksum1, chksum2):
321     """Compares two checksums in one's complement notation.
322
323     Checksums to be compared are calculated as 16 bit one's complement of the
324     one's complement sum of 16 bit words of some buffer.
325     In one's complement notation 0x0000 (positive zero) and 0xFFFF
326     (negative zero) are equivalent.
327
328     :param chksum1: First checksum.
329     :param chksum2: Second checksum.
330     :type chksum1: uint16
331     :type chksum2: uint16
332
333     :returns: True if checksums are equivalent, False otherwise.
334     :rtype: boolean
335     """
336     if chksum1 == 0xFFFF:
337         chksum1 = 0
338     if chksum2 == 0xFFFF:
339         chksum2 = 0
340     return chksum1 == chksum2