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