54f719fa9add6821504eebda84242e8674b2d8e6
[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     >>> rxq._proc.terminate()
64 """
65
66
67 import socket
68 import os
69 import time
70 from multiprocessing import Queue, Process
71 from scapy.all import ETH_P_IP, ETH_P_IPV6, ETH_P_ALL, ETH_P_ARP
72 from scapy.all import Ether, ARP, Packet
73 from scapy.layers.inet6 import IPv6
74
75 __all__ = ['RxQueue', 'TxQueue', 'Interface', 'create_gratuitous_arp_request',
76            'auto_pad']
77
78 # TODO: http://stackoverflow.com/questions/320232/ensuring-subprocesses-are-dead-on-exiting-python-program
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
90
91 def extract_one_packet(buf):
92     """Extract one packet from the incoming buf buffer.
93
94     Takes string as input and looks for first whole packet in it.
95     If it finds one, it returns substring from the buf parameter.
96
97     :param buf: string representation of incoming packet buffer.
98     :type buf: string
99     :return: String representation of first packet in buf.
100     :rtype: string
101     """
102     pkt_len = 0
103
104     if len(buf) < 60:
105         return None
106
107     # print
108     # print buf.__repr__()
109     # print Ether(buf).__repr__()
110     # print len(Ether(buf))
111     # print
112     try:
113         ether_type = Ether(buf[0:14]).type
114     except AttributeError:
115         raise RuntimeError(
116             'No EtherType in packet {0}'.format(buf.__repr__()))
117
118     if ether_type == ETH_P_IP:
119         # 14 is Ethernet fame header size.
120         # 4 bytes is just enough to look for length in ip header.
121         # ip total length contains just the IP packet length so add the Ether
122         #     header.
123         pkt_len = Ether(buf[0:14+4]).len + 14
124         if len(buf) < 60:
125             return None
126     elif ether_type == ETH_P_IPV6:
127         if not Ether(buf[0:14+6]).haslayer(IPv6):
128             raise RuntimeError(
129                 'Invalid IPv6 packet {0}'.format(buf.__repr__()))
130         # ... to add to the above, 40 bytes is the length of IPV6 header.
131         #   The ipv6.len only contains length of the payload and not the header
132         pkt_len = Ether(buf)['IPv6'].plen + 14 + 40
133         if len(buf) < 60:
134             return None
135     elif ether_type == ETH_P_ARP:
136         pkt = Ether(buf[:20])
137         if not pkt.haslayer(ARP):
138             raise RuntimeError('Incomplete ARP packet')
139         # len(eth) + arp(2 hw addr type + 2 proto addr type
140         #                + 1b len + 1b len + 2b operation)
141
142         pkt_len = 14 + 8
143         pkt_len += 2 * pkt.getlayer(ARP).hwlen
144         pkt_len += 2 * pkt.getlayer(ARP).plen
145
146         del pkt
147     elif ether_type == 32821:  # RARP (Reverse ARP)
148         pkt = Ether(buf[:20])
149         pkt.type = ETH_P_ARP  # Change to ARP so it works with scapy
150         pkt = Ether(str(pkt))
151         if not pkt.haslayer(ARP):
152             pkt.show()
153             raise RuntimeError('Incomplete RARP packet')
154
155         # len(eth) + arp(2 hw addr type + 2 proto addr type
156         #                + 1b len + 1b len + 2b operation)
157         pkt_len = 14 + 8
158         pkt_len += 2 * pkt.getlayer(ARP).hwlen
159         pkt_len += 2 * pkt.getlayer(ARP).plen
160
161         del pkt
162     else:
163         raise RuntimeError('Unknown protocol {0}'.format(ether_type))
164
165     if pkt_len < 60:
166         pkt_len = 60
167
168     if len(buf) < pkt_len:
169         return None
170
171     return buf[0:pkt_len]
172
173
174 def packet_reader(interface_name, queue):
175     """Sub-process routine that reads packets and puts them to queue.
176
177     This function is meant to be run in separate subprocess and is in tight
178     loop reading raw packets from interface passed as parameter.
179
180     :param interace_name: Name of interface to read packets from.
181     :param queue: Queue in which this function will push incoming packets.
182     :type interface_name: string
183     :type queue: multiprocessing.Queue
184     :return: None
185     """
186     sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, ETH_P_ALL)
187     sock.bind((interface_name, ETH_P_ALL))
188
189     buf = ""
190     while True:
191         recvd = sock.recv(1514)
192         buf = buf + recvd
193
194         pkt = extract_one_packet(buf)
195         while pkt is not None:
196             if pkt is None:
197                 break
198             queue.put(pkt)
199             buf = buf[len(pkt):]
200             pkt = extract_one_packet(buf)
201
202
203 class RxQueue(PacketVerifier):
204     """Receive queue object.
205
206     This object creates raw socket, reads packets from it and provides
207     function to access them.
208
209     :param interface_name: Which interface to bind to.
210     :type interface_name: string
211     """
212
213     def __init__(self, interface_name):
214         PacketVerifier.__init__(self, interface_name)
215
216         self._queue = Queue()
217         self._proc = Process(target=packet_reader, args=(interface_name,
218                                                          self._queue))
219         self._proc.daemon = True
220         self._proc.start()
221         time.sleep(2)
222
223     def recv(self, timeout=3, ignore=None):
224         """Read next received packet.
225
226         Returns scapy's Ether() object created from next packet in the queue.
227         Queue is being filled in parallel in subprocess. If no packet
228         arrives in given timeout queue.Empty exception will be risen.
229
230         :param timeout: How many seconds to wait for next packet.
231         :type timeout: int
232
233         :return: Ether() initialized object from packet data.
234         :rtype: scapy.Ether
235         """
236
237         pkt = self._queue.get(True, timeout=timeout)
238
239         if ignore is not None:
240             for i, ig_pkt in enumerate(ignore):
241                 # Auto pad all packets in ignore list
242                 ignore[i] = auto_pad(ig_pkt)
243             for ig_pkt in ignore:
244                 if ig_pkt == pkt:
245                     # Found the packet in ignore list, get another one
246                     # TODO: subtract timeout - time_spent in here
247                     ignore.remove(ig_pkt)
248                     return self.recv(timeout, ignore)
249
250         return Ether(pkt)
251
252
253 class TxQueue(PacketVerifier):
254     """Transmission queue object.
255
256     This object is used to send packets over RAW socket on a interface.
257
258     :param interface_name: Which interface to send packets from.
259     :type interface_name: string
260     """
261     def __init__(self, interface_name):
262         PacketVerifier.__init__(self, interface_name)
263
264     def send(self, pkt):
265         """Send packet out of the bound interface.
266
267         :param pkt: Packet to send.
268         :type pkt: string or scapy Packet derivative.
269         """
270         if isinstance(pkt, Packet):
271             pkt = str(pkt)
272         pkt = auto_pad(pkt)
273         self._sock.send(pkt)
274
275
276 class Interface(object):
277     def __init__(self, if_name):
278         self.if_name = if_name
279         self.sent_packets = []
280         self.txq = TxQueue(if_name)
281         self.rxq = RxQueue(if_name)
282
283     def send_pkt(self, pkt):
284         self.sent_packets.append(pkt)
285         self.txq.send(pkt)
286
287     def recv_pkt(self, timeout=3):
288         return self.rxq.recv(timeout, self.sent_packets)
289
290     def close(self):
291         self.rxq._proc.terminate()
292
293
294 def create_gratuitous_arp_request(src_mac, src_ip):
295     """Creates scapy representation of gratuitous ARP request"""
296     return (Ether(src=src_mac, dst='ff:ff:ff:ff:ff:ff') /
297             ARP(psrc=src_ip, hwsrc=src_mac, pdst=src_ip))
298
299
300 def auto_pad(packet):
301     """Pads zeroes at the end of the packet if the total len < 60 bytes."""
302     padded = str(packet)
303     if len(padded) < 60:
304         padded += ('\0' * (60 - len(padded)))
305     return padded
306