59ea2db5a30e68c1845d5fed59839504e9f416ca
[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, Packet
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/ensuring-subprocesses-are-dead-on-exiting-python-program
78
79
80 class PacketVerifier(object):
81     """Base class for TX and RX queue objects for packet verifier."""
82     def __init__(self, interface_name):
83         os.system('sudo echo 1 > /proc/sys/net/ipv6/conf/{0}/disable_ipv6'
84                   .format(interface_name))
85         os.system('sudo ip link set {0} up promisc on'.format(interface_name))
86         self._sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
87                                    ETH_P_ALL)
88         self._sock.bind((interface_name, ETH_P_ALL))
89         self._ifname = interface_name
90
91
92 def extract_one_packet(buf):
93     """Extract one packet from the incoming buf buffer.
94
95     Takes string as input and looks for first whole packet in it.
96     If it finds one, it returns substring from the buf parameter.
97
98     :param buf: String representation of incoming packet buffer.
99     :type buf: str
100     :return: String representation of first packet in buf.
101     :rtype: str
102     """
103     pkt_len = 0
104
105     if len(buf) < 60:
106         return None
107
108     # print
109     # print buf.__repr__()
110     # print Ether(buf).__repr__()
111     # print len(Ether(buf))
112     # print
113     try:
114         ether_type = Ether(buf[0:14]).type
115     except AttributeError:
116         raise RuntimeError(
117             'No EtherType in packet {0}'.format(buf.__repr__()))
118
119     if ether_type == ETH_P_IP:
120         # 14 is Ethernet fame header size.
121         # 4 bytes is just enough to look for length in ip header.
122         # ip total length contains just the IP packet length so add the Ether
123         #     header.
124         pkt_len = Ether(buf[0:14+4]).len + 14
125         if len(buf) < 60:
126             return None
127     elif ether_type == ETH_P_IPV6:
128         if not Ether(buf[0:14+6]).haslayer(IPv6):
129             raise RuntimeError(
130                 'Invalid IPv6 packet {0}'.format(buf.__repr__()))
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)['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('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(str(pkt))
152         if not pkt.haslayer(ARP):
153             pkt.show()
154             raise RuntimeError('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('Unknown protocol {0}'.format(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     :return: None
186     """
187     sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, ETH_P_ALL)
188     sock.bind((interface_name, ETH_P_ALL))
189
190     while True:
191         pkt = sock.recv(0x7fff)
192         queue.put(pkt)
193
194
195 class RxQueue(PacketVerifier):
196     """Receive queue object.
197
198     This object creates raw socket, reads packets from it and provides
199     function to access them.
200
201     :param interface_name: Which interface to bind to.
202     :type interface_name: str
203     """
204     def __init__(self, interface_name):
205         PacketVerifier.__init__(self, interface_name)
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         :return: Ether() initialized object from packet data.
222         :rtype: scapy.Ether
223         """
224         (rlist, _, _) = select.select([self._sock], [], [], timeout)
225         if self._sock not in rlist:
226             return None
227
228         pkt = self._sock.recv(0x7fff)
229         pkt_pad = auto_pad(pkt)
230         print 'Received packet on {0} of len {1}'.format(self._ifname, len(pkt))
231         if verbose:
232             Ether(pkt).show2()
233             print
234
235         if ignore is not None:
236             for i, ig_pkt in enumerate(ignore):
237                 # Auto pad all packets in ignore list
238                 ignore[i] = auto_pad(ig_pkt)
239             for ig_pkt in ignore:
240                 if ig_pkt == pkt_pad:
241                     # Found the packet in ignore list, get another one
242                     # TODO: subtract timeout - time_spent in here
243                     ignore.remove(ig_pkt)
244                     return self.recv(timeout, ignore, verbose)
245
246         return Ether(pkt)
247
248
249 class TxQueue(PacketVerifier):
250     """Transmission queue object.
251
252     This object is used to send packets over RAW socket on a interface.
253
254     :param interface_name: Which interface to send packets from.
255     :type interface_name: str
256     """
257     def __init__(self, interface_name):
258         PacketVerifier.__init__(self, interface_name)
259
260     def send(self, pkt, verbose=True):
261         """Send packet out of the bound interface.
262
263         :param pkt: Packet to send.
264         :param verbose: Used to supress detailed logging of sent packets.
265         :type pkt: string or scapy Packet derivative.
266         :type verbose: bool
267         """
268         print 'Sending packet out of {0} of len {1}'.format(self._ifname,
269                                                             len(pkt))
270         if verbose:
271             Ether(str(pkt)).show2()
272             print
273
274         pkt = auto_pad(str(pkt))
275         self._sock.send(pkt)
276
277
278 class Interface(object):
279     def __init__(self, if_name):
280         self.if_name = if_name
281         self.sent_packets = []
282         self.rxq = RxQueue(if_name)
283         self.txq = TxQueue(if_name)
284
285     def send_pkt(self, pkt):
286         self.sent_packets.append(pkt)
287         self.txq.send(pkt)
288
289     def recv_pkt(self, timeout=3):
290         return self.rxq.recv(timeout, self.sent_packets)
291
292
293 def create_gratuitous_arp_request(src_mac, src_ip):
294     """Creates scapy representation of gratuitous ARP request."""
295     return (Ether(src=src_mac, dst='ff:ff:ff:ff:ff:ff') /
296             ARP(psrc=src_ip, hwsrc=src_mac, pdst=src_ip))
297
298
299 def auto_pad(packet):
300     """Pads zeroes at the end of the packet if the total len < 60 bytes."""
301     padded = str(packet)
302     if len(padded) < 60:
303         padded += ('\0' * (60 - len(padded)))
304     return padded
305
306
307 def checksum_equal(chksum1, chksum2):
308     """Compares two checksums in one's complement notation.
309
310     Checksums to be compared are calculated as 16 bit one's complement of the
311     one's complement sum of 16 bit words of some buffer.
312     In one's complement notation 0x0000 (positive zero) and 0xFFFF
313     (negative zero) are equivalent.
314
315     :param chksum1: First checksum.
316     :param chksum2: Second checksum.
317     :type chksum1: uint16
318     :type chksum2: uint16
319
320     :return: True if checksums are equivalent, False otherwise.
321     :rtype: boolean
322     """
323     if chksum1 == 0xFFFF:
324         chksum1 = 0
325     if chksum2 == 0xFFFF:
326         chksum2 = 0
327     return chksum1 == chksum2