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