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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
14 """PacketVerifier module.
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"
27 >>> pkt_send = Ether(src=src_mac, dst=dst_mac) /
28 ... IP(src=src_ip, dst=dst_ip) /
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()
38 dst = aa:bb:cc:dd:ee:ff
39 src = 52:54:00:ca:5d:0b
62 load = 'RT\x00\xca]\x0b\xaa\xbb\xcc\xdd\xee\xff\x08\x06\x00\x01\x08\x00'
68 from scapy.config import conf
69 from scapy.all import ETH_P_IP, ETH_P_IPV6, ETH_P_ALL, ETH_P_ARP
70 from scapy.layers.inet6 import IPv6
71 from scapy.layers.l2 import Ether, ARP
73 # Enable libpcap's L2listen
75 import scapy.arch.pcapdnet # pylint: disable=C0413, unused-import
77 __all__ = ['RxQueue', 'TxQueue', 'Interface', 'create_gratuitous_arp_request',
78 'auto_pad', 'checksum_equal']
80 # TODO: http://stackoverflow.com/questions/320232/
81 # ensuring-subprocesses-are-dead-on-exiting-python-program
84 class PacketVerifier(object):
85 """Base class for TX and RX queue objects for packet verifier."""
86 def __init__(self, interface_name):
87 os.system('sudo echo 1 > /proc/sys/net/ipv6/conf/{0}/disable_ipv6'
88 .format(interface_name))
89 os.system('sudo ip link set {0} up promisc on'.format(interface_name))
90 self._ifname = interface_name
93 def extract_one_packet(buf):
94 """Extract one packet from the incoming buf buffer.
96 Takes string as input and looks for first whole packet in it.
97 If it finds one, it returns substring from the buf parameter.
99 :param buf: String representation of incoming packet buffer.
101 :returns: String representation of first packet in buf.
110 ether_type = Ether(buf[0:14]).type
111 except AttributeError:
113 'No EtherType in packet {0}'.format(buf.__repr__()))
115 if ether_type == ETH_P_IP:
116 # 14 is Ethernet fame header size.
117 # 4 bytes is just enough to look for length in ip header.
118 # ip total length contains just the IP packet length so add the Ether
120 pkt_len = Ether(buf[0:14+4]).len + 14
123 elif ether_type == ETH_P_IPV6:
124 if not Ether(buf[0:14+6]).haslayer(IPv6):
126 'Invalid IPv6 packet {0}'.format(buf.__repr__()))
127 # ... to add to the above, 40 bytes is the length of IPV6 header.
128 # The ipv6.len only contains length of the payload and not the header
129 pkt_len = Ether(buf)['IPv6'].plen + 14 + 40
132 elif ether_type == ETH_P_ARP:
133 pkt = Ether(buf[:20])
134 if not pkt.haslayer(ARP):
135 raise RuntimeError('Incomplete ARP packet')
136 # len(eth) + arp(2 hw addr type + 2 proto addr type
137 # + 1b len + 1b len + 2b operation)
140 pkt_len += 2 * pkt.getlayer(ARP).hwlen
141 pkt_len += 2 * pkt.getlayer(ARP).plen
144 elif ether_type == 32821: # RARP (Reverse ARP)
145 pkt = Ether(buf[:20])
146 pkt.type = ETH_P_ARP # Change to ARP so it works with scapy
147 pkt = Ether(str(pkt))
148 if not pkt.haslayer(ARP):
150 raise RuntimeError('Incomplete RARP packet')
152 # len(eth) + arp(2 hw addr type + 2 proto addr type
153 # + 1b len + 1b len + 2b operation)
155 pkt_len += 2 * pkt.getlayer(ARP).hwlen
156 pkt_len += 2 * pkt.getlayer(ARP).plen
160 raise RuntimeError('Unknown protocol {0}'.format(ether_type))
165 if len(buf) < pkt_len:
168 return buf[0:pkt_len]
171 def packet_reader(interface_name, queue):
172 """Sub-process routine that reads packets and puts them to queue.
174 This function is meant to be run in separate subprocess and is in tight
175 loop reading raw packets from interface passed as parameter.
177 :param interface_name: Name of interface to read packets from.
178 :param queue: Queue in which this function will push incoming packets.
179 :type interface_name: str
180 :type queue: multiprocessing.Queue
183 sock = conf.L2listen(iface=interface_name, type=ETH_P_ALL)
186 pkt = sock.recv(0x7fff)
190 class RxQueue(PacketVerifier):
191 """Receive queue object.
193 This object creates raw socket, reads packets from it and provides
194 function to access them.
196 :param interface_name: Which interface to bind to.
197 :type interface_name: str
199 def __init__(self, interface_name):
200 PacketVerifier.__init__(self, interface_name)
201 self._sock = conf.L2listen(iface=interface_name, type=ETH_P_ALL)
203 def recv(self, timeout=3, ignore=None, verbose=True):
204 """Read next received packet.
206 Returns scapy's Ether() object created from next packet in the queue.
207 Queue is being filled in parallel in subprocess. If no packet
208 arrives in given timeout queue.Empty exception will be risen.
210 :param timeout: How many seconds to wait for next packet.
211 :param ignore: List of packets that should be ignored.
212 :param verbose: Used to suppress detailed logging of received packets.
217 :returns: Ether() initialized object from packet data.
221 if ignore is not None:
222 for ig_pkt in ignore:
223 # Auto pad all packets in ignore list
224 ignore_list.append(auto_pad(ig_pkt))
226 (rlist, _, _) = select.select([self._sock], [], [], timeout)
227 if self._sock not in rlist:
230 pkt = self._sock.recv(0x7fff)
231 pkt_pad = auto_pad(pkt)
232 print 'Received packet on {0} of len {1}'\
233 .format(self._ifname, len(pkt))
235 pkt.show2() # pylint: disable=no-member
237 if pkt_pad in ignore_list:
238 ignore_list.remove(pkt_pad)
239 print 'Received packet ignored.'
245 class TxQueue(PacketVerifier):
246 """Transmission queue object.
248 This object is used to send packets over RAW socket on a interface.
250 :param interface_name: Which interface to send packets from.
251 :type interface_name: str
253 def __init__(self, interface_name):
254 PacketVerifier.__init__(self, interface_name)
255 self._sock = conf.L2socket(iface=interface_name, type=ETH_P_ALL)
257 def send(self, pkt, verbose=True):
258 """Send packet out of the bound interface.
260 :param pkt: Packet to send.
261 :param verbose: Used to supress detailed logging of sent packets.
262 :type pkt: string or scapy Packet derivative.
265 print 'Sending packet out of {0} of len {1}'.format(self._ifname,
268 Ether(str(pkt)).show2()
271 pkt = auto_pad(str(pkt))
275 class Interface(object):
276 """Class for network interfaces. Contains methods for sending and receiving
278 def __init__(self, if_name):
279 """Initialize the interface class.
281 :param if_name: Name of the interface.
284 self.if_name = if_name
285 self.sent_packets = []
286 self.rxq = RxQueue(if_name)
287 self.txq = TxQueue(if_name)
289 def send_pkt(self, pkt):
290 """Send the provided packet out the interface."""
291 self.sent_packets.append(pkt)
294 def recv_pkt(self, timeout=3):
295 """Read one packet from the interface's receive queue.
297 :param timeout: Timeout value in seconds.
299 :returns: Ether() initialized object from packet data.
302 return self.rxq.recv(timeout, self.sent_packets)
305 def create_gratuitous_arp_request(src_mac, src_ip):
306 """Creates scapy representation of gratuitous ARP request."""
307 return (Ether(src=src_mac, dst='ff:ff:ff:ff:ff:ff') /
308 ARP(psrc=src_ip, hwsrc=src_mac, pdst=src_ip))
311 def auto_pad(packet):
312 """Pads zeroes at the end of the packet if the total len < 60 bytes."""
315 padded += ('\0' * (60 - len(padded)))
319 def checksum_equal(chksum1, chksum2):
320 """Compares two checksums in one's complement notation.
322 Checksums to be compared are calculated as 16 bit one's complement of the
323 one's complement sum of 16 bit words of some buffer.
324 In one's complement notation 0x0000 (positive zero) and 0xFFFF
325 (negative zero) are equivalent.
327 :param chksum1: First checksum.
328 :param chksum2: Second checksum.
329 :type chksum1: uint16
330 :type chksum2: uint16
332 :returns: True if checksums are equivalent, False otherwise.
335 if chksum1 == 0xFFFF:
337 if chksum2 == 0xFFFF:
339 return chksum1 == chksum2