1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
|
# -*- coding: utf-8 -*-
"""
pcapy clone in pure python
This module aims to support exactly the same interface as pcapy,
so that it can be used as a drop-in replacement. This means the module
does not and probably will never support live captures. Offline file
support should match the original though.
"""
# Copyright 2010 Stanisław Pitucha. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are
# permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list
# of conditions and the following disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY Stanisław Pitucha ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are those of the
# authors and should not be interpreted as representing official policies, either expressed
# or implied, of Stanisław Pitucha.
import struct
DLT_NULL = 0
DLT_EN10MB = 1
DLT_IEEE802 = 6
DLT_ARCNET = 7
DLT_SLIP = 8
DLT_PPP = 9
DLT_FDDI = 10
DLT_ATM_RFC1483 = 11
DLT_RAW = 12
DLT_PPP_SERIAL = 50
DLT_PPP_ETHER = 51
DLT_C_HDLC = 104
DLT_IEEE802_11 = 105
DLT_LOOP = 108
DLT_LINUX_SLL = 113
DLT_LTALK = 114
class PcapError(Exception):
""" General Pcap module exception class """
pass
def fixup_identical_short(short):
""" noop for "fixing" big/little endian """
return short
def fixup_identical_long(long_int):
""" noop for "fixing" big/little endian """
return long_int
def fixup_swapped_short(short):
""" swap bytes in a 16b short """
return ((short&0xff) << 8) | ((short&0xff00) >> 8)
def fixup_swapped_long(long_int):
""" swap swapped shorts in a 32b int """
bottom = fixup_swapped_short(long_int & 0xffff)
top = fixup_swapped_short((long_int >> 16) & 0xffff)
return ((bottom << 16) & 0xffff0000) | top
fixup_sets = {
b"\xd4\xc3\xb2\xa1": (fixup_identical_short, fixup_identical_long),
b"\xa1\xb2\xc3\xd4": (fixup_swapped_short, fixup_swapped_long),
}
def open_offline(filename):
""" opens the pcap file indicated by `filename` and returns a Reader object """
if filename == "-":
import sys
source = sys.stdin
else:
try:
source = open(filename, "rb")
except IOError as error:
if error.args[0] == 21:
raise PcapError("error reading dump file: %s" % (error.args[1]))
else:
raise PcapError("%s: %s" % (filename, error.args[1]))
return Reader(source)
def open_live(_device, _snaplen, _promisc, _to_ms):
raise NotImplementedError("This function is only available in pcapy")
def lookupdev():
raise NotImplementedError("This function is only available in pcapy")
def findalldevs():
raise NotImplementedError("This function is only available in pcapy")
def compile(_linktype, _snaplen, _filter, _optimize, _netmask):
raise NotImplementedError("not implemented yet")
class Reader(object):
"""
An interface for reading an open pcap file.
This object can either read a single packet via `next()`, a series
via `loop()` or `dispatch()`, or by iterating over the object.
"""
__GLOBAL_HEADER_LEN = 24
__PACKET_HEADER_LEN = 16
def __init__(self, source):
""" creates a Reader instance from an open file object """
self.__source = source
header = self.__source.read(self.__GLOBAL_HEADER_LEN)
if len(header) < self.__GLOBAL_HEADER_LEN:
raise PcapError(
"truncated dump file; tried to read %i file header bytes, only got %i" %
(self.__GLOBAL_HEADER_LEN, len(header)))
hdr_values = struct.unpack("IHHIIII", header)
if header[:4] in fixup_sets:
self.fixup_short, self.fixup_long = fixup_sets[header[:4]]
else:
raise PcapError("bad dump file format")
self.version_major, self.version_minor = [self.fixup_short(x)
for x in hdr_values[1:3]]
self.thiszone, self.sigfigs, self.snaplen, self.network = [self.fixup_long(x)
for x in hdr_values[3:]]
self.last_good_position = self.__GLOBAL_HEADER_LEN
def __loop_and_count(self, maxcant, callback):
"""
reads up to `maxcant` packets and runs callback for each of them
returns the number of packets processed
"""
i = 0
while True:
if i >= maxcant and maxcant > -1:
break
hdr, data = self.next()
if hdr is None:
break
else:
callback(hdr, data)
i += 1
return i
def dispatch(self, maxcant, callback):
"""
reads up to `maxcant` packets and runs callback for each of them
returns the number of packets processed or 0 if no limit was specified
"""
i = self.__loop_and_count(maxcant, callback)
if maxcant > -1:
return i
else:
return 0
def loop(self, maxcant, callback):
"""
reads up to `maxcant` packets and runs callback for each of them
does not return a value
"""
self.__loop_and_count(maxcant, callback)
def __iter__(self):
return self
def next(self):
""" reads the next packet from file and returns a (Pkthdr, data) tuple """
header = self.__source.read(self.__PACKET_HEADER_LEN)
if len(header) == 0:
return (None, '')
if len(header) < self.__PACKET_HEADER_LEN:
raise PcapError(
"truncated dump file; tried to read %i header bytes, only got %i" %
(self.__PACKET_HEADER_LEN, len(header)))
hdr_values = struct.unpack("IIII", header)
ts_sec, ts_usec, incl_len, orig_len = [self.fixup_long(x) for x in hdr_values]
data = self.__source.read(incl_len)
if len(data) < incl_len:
raise PcapError(
"truncated dump file; tried to read %i captured bytes, only got %i" %
(incl_len, len(data)))
pkthdr = Pkthdr(ts_sec, ts_usec, incl_len, orig_len)
return (pkthdr, data)
def getnet(self):
raise NotImplementedError("This function is only available in pcapy")
def getmask(self):
raise NotImplementedError("This function is only available in pcapy")
def datalink(self):
""" returns the datalink type used in the current file """
return self.network
def getnonblock(self):
"""
shows whether the operations are nonblocking, which is always 0 for files
"""
return 0
def setnonblock(self, state):
""" this has no effect on savefiles, so is not implemented in pure-pcapy """
pass
def dump_open(self, filename):
"""
create a new dumper object which inherits the network and snaplen information
from the original reader
"""
return Dumper(filename, self.snaplen, self.network)
class Dumper(object):
"""
Interface for pcap files, which can be used for creating new files.
Although this is accessible only through `Reader.dump_open()` in the
original pcapy, there's no good reason for that limitation and this object
can be used directly. It implements some sanity checking before the packet
is written to the file.
Files created this way are always stored using the native byte order.
"""
def __init__(self, filename, snaplen, network):
""" creates a new dumper object which can be used for writing pcap files """
self.store = open(filename, "wb")
self.store.write(struct.pack("IHHIIII", 0xa1b2c3d4, 2, 4, 0, 0,
snaplen, network))
self.store.flush() # have to flush, since there's no close
def dump(self, header, data):
""" writes a new header and packet to the file, then forces a file flush """
if not isinstance(header, Pkthdr):
raise PcapError("not a proper Pkthdr")
if type(data) != bytes:
raise PcapError("can dump only bytes")
if header.getcaplen() != len(data):
raise PcapError("capture length not equal to length of data")
fields = list(header.getts()) + [header.getcaplen(), header.getlen()]
self.store.write(struct.pack("IIII", *fields))
self.store.write(data)
self.store.flush()
class Pkthdr(object):
"""
Packet header, as used in the pcap files before each data segment.
This class is a simple data wrapper.
"""
def __init__(self, ts_sec, ts_usec, incl_len, orig_len):
self.ts = (ts_sec, ts_usec)
self.incl_len = incl_len
self.orig_len = orig_len
def getts(self):
""" returns a (seconds, microseconds) tuple for the capture time"""
return self.ts
def getcaplen(self):
""" returns the captured length of the packet """
return self.incl_len
def getlen(self):
""" returns the original length of the packet """
return self.orig_len
class Bpf(object):
def __init__(self):
raise NotImplementedError("not implemented yet")
def filter(self, packet):
raise NotImplementedError("not implemented yet")
|