-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathpcap.pyx
427 lines (374 loc) · 13.6 KB
/
pcap.pyx
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#
# pcap.pyx
#
# $Id$
"""packet capture library
This module provides a high level interface to packet capture systems.
All packets on the network, even those destined for other hosts, are
accessible through this mechanism.
"""
__author__ = 'Dug Song <dugsong@monkey.org>'
__copyright__ = 'Copyright (c) 2004 Dug Song'
__license__ = 'BSD license'
__url__ = 'http://monkey.org/~dugsong/pypcap/'
__version__ = '1.1'
import sys
import struct
cdef extern from "Python.h":
object PyBuffer_FromMemory(char *s, int len)
int PyObject_AsCharBuffer(object obj, char **buffer, int *buffer_len)
int PyGILState_Ensure()
void PyGILState_Release(int gil)
void Py_BEGIN_ALLOW_THREADS()
void Py_END_ALLOW_THREADS()
cdef extern from "pcap.h":
struct bpf_insn:
int __xxx
struct bpf_program:
bpf_insn *bf_insns
struct bpf_timeval:
unsigned int tv_sec
unsigned int tv_usec
struct pcap_stat:
unsigned int ps_recv
unsigned int ps_drop
unsigned int ps_ifdrop
struct pcap_pkthdr:
bpf_timeval ts
unsigned int caplen
ctypedef struct pcap_t:
int __xxx
ctypedef struct pcap_if_t # hack for win32
ctypedef struct pcap_if_t:
pcap_if_t *next
char *name
ctypedef void (*pcap_handler)(void *arg, pcap_pkthdr *hdr, char *pkt)
cdef extern from "pcap.h":
pcap_t *pcap_open_live(char *device, int snaplen, int promisc,
int to_ms, char *errbuf)
pcap_t *pcap_open_offline(char *fname, char *errbuf)
int pcap_compile(pcap_t *p, bpf_program *fp, char *str, int optimize,
unsigned int netmask)
int pcap_setfilter(pcap_t *p, bpf_program *fp)
void pcap_freecode(bpf_program *fp)
int pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback,
unsigned char *arg)
unsigned char *pcap_next(pcap_t *p, pcap_pkthdr *hdr)
int pcap_datalink(pcap_t *p)
int pcap_snapshot(pcap_t *p)
int pcap_stats(pcap_t *p, pcap_stat *ps)
char *pcap_geterr(pcap_t *p)
void pcap_close(pcap_t *p)
int bpf_filter(bpf_insn *insns, char *buf, int len, int caplen)
int pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
void pcap_freealldevs(pcap_if_t *alldevs)
int pcap_lookupnet(char *device,
unsigned int *netp,
unsigned int *maskp,
char *errbuf)
int pcap_sendpacket(pcap_t *p, char *buf, int size)
cdef extern from "pcap_ex.h":
# XXX - hrr, sync with libdnet and libevent
int pcap_ex_immediate(pcap_t *p)
char *pcap_ex_name(char *name)
char *pcap_ex_lookupdev(char *ebuf)
int pcap_ex_fileno(pcap_t *p)
void pcap_ex_setup(pcap_t *p)
void pcap_ex_setnonblock(pcap_t *p, int nonblock, char *ebuf)
int pcap_ex_getnonblock(pcap_t *p, char *ebuf)
int pcap_ex_next(pcap_t *p, pcap_pkthdr **hdr, char **pkt)
int pcap_ex_compile_nopcap(int snaplen, int dlt,
bpf_program *fp, char *str,
int optimize, unsigned int netmask)
cdef extern from *:
char *strdup(char *src)
void free(void *ptr)
cdef struct pcap_handler_ctx:
void *callback
void *args
int got_exc
cdef void __pcap_handler(void *arg, pcap_pkthdr *hdr, char *pkt):
cdef pcap_handler_ctx *ctx
cdef int gil
ctx = <pcap_handler_ctx *>arg
gil = PyGILState_Ensure()
try:
(<object>ctx.callback)(hdr.ts.tv_sec + (hdr.ts.tv_usec/1000000.0),
PyBuffer_FromMemory(pkt, hdr.caplen),
*(<object>ctx.args))
except:
ctx.got_exc = 1
PyGILState_Release(gil)
DLT_NULL = 0
DLT_EN10MB = 1
DLT_EN3MB = 2
DLT_AX25 = 3
DLT_PRONET = 4
DLT_CHAOS = 5
DLT_IEEE802 = 6
DLT_ARCNET = 7
DLT_SLIP = 8
DLT_PPP = 9
DLT_FDDI = 10
# XXX - Linux
DLT_LINUX_SLL = 113
# XXX - OpenBSD
DLT_PFLOG = 117
DLT_PFSYNC = 18
if sys.platform.find('openbsd') != -1:
DLT_LOOP = 12
DLT_RAW = 14
else:
DLT_LOOP = 108
DLT_RAW = 12
dltoff = { DLT_NULL:4, DLT_EN10MB:14, DLT_IEEE802:22, DLT_ARCNET:6,
DLT_SLIP:16, DLT_PPP:4, DLT_FDDI:21, DLT_PFLOG:48, DLT_PFSYNC:4,
DLT_LOOP:4, DLT_RAW:0, DLT_LINUX_SLL:16 }
cdef class bpf:
"""bpf(filter, dlt=DLT_RAW) -> BPF filter object"""
cdef bpf_program fcode
def __init__(self, char *filter, dlt=DLT_RAW):
if pcap_ex_compile_nopcap(65535, dlt, &self.fcode, filter, 1, 0) < 0:
raise IOError, 'bad filter'
def filter(self, buf):
"""Return boolean match for buf against our filter."""
cdef char *p
cdef int n
if PyObject_AsCharBuffer(buf, &p, &n) < 0:
raise TypeError
if bpf_filter(self.fcode.bf_insns, p, n, n) == 0:
return False
return True
def __dealloc__(self):
pcap_freecode(&self.fcode)
cdef class pcap:
"""pcap(name=None, snaplen=65535, promisc=True, timeout_ms=None, immediate=False) -> packet capture object
Open a handle to a packet capture descriptor.
Keyword arguments:
name -- name of a network interface or dumpfile to open,
or None to open the first available up interface
snaplen -- maximum number of bytes to capture for each packet
promisc -- boolean to specify promiscuous mode sniffing
timeout_ms -- requests for the next packet will return None if the timeout
(in milliseconds) is reached and no packets were received
(Default: no timeout)
immediate -- disable buffering, if possible
"""
cdef pcap_t *__pcap
cdef char *__name
cdef char *__filter
cdef char __ebuf[256]
cdef int __dloff
def __init__(self, name=None, snaplen=65535, promisc=True,
timeout_ms=0, immediate=False):
global dltoff
cdef char *p
if not name:
p = pcap_ex_lookupdev(self.__ebuf)
if p == NULL:
raise OSError, self.__ebuf
else:
p = name
self.__pcap = pcap_open_offline(p, self.__ebuf)
if not self.__pcap:
self.__pcap = pcap_open_live(pcap_ex_name(p), snaplen, promisc,
timeout_ms, self.__ebuf)
if not self.__pcap:
raise OSError, self.__ebuf
self.__name = strdup(p)
self.__filter = strdup("")
try: self.__dloff = dltoff[pcap_datalink(self.__pcap)]
except KeyError: pass
if immediate and pcap_ex_immediate(self.__pcap) < 0:
raise OSError, "couldn't enable immediate mode"
property name:
"""Network interface or dumpfile name."""
def __get__(self):
return self.__name
property snaplen:
"""Maximum number of bytes to capture for each packet."""
def __get__(self):
return pcap_snapshot(self.__pcap)
property dloff:
"""Datalink offset (length of layer-2 frame header)."""
def __get__(self):
return self.__dloff
property filter:
"""Current packet capture filter."""
def __get__(self):
return self.__filter
property fd:
"""File descriptor (or Win32 HANDLE) for capture handle."""
def __get__(self):
return pcap_ex_fileno(self.__pcap)
def fileno(self):
"""Return file descriptor (or Win32 HANDLE) for capture handle."""
return pcap_ex_fileno(self.__pcap)
def setfilter(self, value, optimize=1):
"""Set BPF-format packet capture filter."""
cdef bpf_program fcode
free(self.__filter)
self.__filter = strdup(value)
if pcap_compile(self.__pcap, &fcode, self.__filter, optimize, 0) < 0:
raise OSError, pcap_geterr(self.__pcap)
if pcap_setfilter(self.__pcap, &fcode) < 0:
raise OSError, pcap_geterr(self.__pcap)
pcap_freecode(&fcode)
def setnonblock(self, nonblock=True):
"""Set non-blocking capture mode."""
pcap_ex_setnonblock(self.__pcap, nonblock, self.__ebuf)
def getnonblock(self):
"""Return non-blocking capture mode as boolean."""
ret = pcap_ex_getnonblock(self.__pcap, self.__ebuf)
if ret < 0:
raise OSError, self.__ebuf
elif ret:
return True
return False
def datalink(self):
"""Return datalink type (DLT_* values)."""
return pcap_datalink(self.__pcap)
def __add_pkts(self, ts, pkt, pkts):
pkts.append((ts, pkt))
def readpkts(self):
"""Return a list of (timestamp, packet) tuples received in one buffer."""
pkts = []
self.dispatch(-1, self.__add_pkts, pkts)
return pkts
def dispatch(self, cnt, callback, *args):
"""Collect and process packets with a user callback,
return the number of packets processed, or 0 for a savefile.
Arguments:
cnt -- number of packets to process;
or 0 to process all packets until an error occurs,
EOF is reached, or the read times out;
or -1 to process all packets received in one buffer
callback -- function with (timestamp, pkt, *args) prototype
*args -- optional arguments passed to callback on execution
"""
cdef pcap_handler_ctx ctx
cdef int n
ctx.callback = <void *>callback
ctx.args = <void *>args
ctx.got_exc = 0
n = pcap_dispatch(self.__pcap, cnt, __pcap_handler,
<unsigned char *>&ctx)
if ctx.got_exc:
exc = sys.exc_info()
raise exc[0], exc[1], exc[2]
return n
def loop(self, cnt, callback, *args):
"""Processing packets with a user callback during a loop.
The loop can be exited when cnt value is reached
or with an exception, including KeyboardInterrupt.
Arguments:
cnt -- number of packets to process;
0 or -1 to process all packets until an error occurs,
EOF is reached;
callback -- function with (timestamp, pkt, *args) prototype
*args -- optional arguments passed to callback on execution
"""
cdef pcap_pkthdr *hdr
cdef char *pkt
cdef int n
cdef int i
i = 1
pcap_ex_setup(self.__pcap)
while 1:
Py_BEGIN_ALLOW_THREADS
n = pcap_ex_next(self.__pcap, &hdr, &pkt)
Py_END_ALLOW_THREADS
if n == 1:
callback(hdr.ts.tv_sec + (hdr.ts.tv_usec / 1000000.0),
PyBuffer_FromMemory(pkt, hdr.caplen), *args)
elif n == 0:
break
elif n == -1:
raise KeyboardInterrupt
elif n == -2:
break
if i == cnt:
break
i = i + 1
def sendpacket(self, buf):
"""Send a raw network packet on the interface."""
ret = pcap_sendpacket(self.__pcap, buf, len(buf))
if ret == -1:
raise OSError, pcap_geterr(self.__pcap)
return len(buf)
def geterr(self):
"""Return the last error message associated with this handle."""
return pcap_geterr(self.__pcap)
def stats(self):
"""Return a 3-tuple of the total number of packets received,
dropped, and dropped by the interface."""
cdef pcap_stat pstat
if pcap_stats(self.__pcap, &pstat) < 0:
raise OSError, pcap_geterr(self.__pcap)
return (pstat.ps_recv, pstat.ps_drop, pstat.ps_ifdrop)
def __iter__(self):
pcap_ex_setup(self.__pcap)
return self
def __next__(self):
cdef pcap_pkthdr *hdr
cdef char *pkt
cdef int n
while 1:
Py_BEGIN_ALLOW_THREADS
n = pcap_ex_next(self.__pcap, &hdr, &pkt)
Py_END_ALLOW_THREADS
if n == 1:
return (hdr.ts.tv_sec + (hdr.ts.tv_usec / 1000000.0),
PyBuffer_FromMemory(pkt, hdr.caplen))
elif n == 0:
return None
elif n == -1:
raise KeyboardInterrupt
elif n == -2:
raise StopIteration
def __dealloc__(self):
if self.__name:
free(self.__name)
if self.__filter:
free(self.__filter)
if self.__pcap:
pcap_close(self.__pcap)
def ex_name(char *foo):
return pcap_ex_name(foo)
def lookupdev():
"""Return the name of a network device suitable for sniffing."""
cdef char *p, ebuf[256]
p = pcap_ex_lookupdev(ebuf)
if p == NULL:
raise OSError, ebuf
return p
def findalldevs():
"""Return a list of capture devices."""
cdef pcap_if_t *devs, *curr
cdef char ebuf[256]
status = pcap_findalldevs(&devs, ebuf)
if status:
raise OSError(ebuf)
retval = []
if not devs:
return retval
curr = devs
while 1:
retval.append(curr.name)
if not curr.next:
break
curr = curr.next
pcap_freealldevs(devs)
return retval
def lookupnet(char *dev):
"""
Return the address and the netmask of a given device
as network-byteorder integers.
"""
cdef unsigned int netp
cdef unsigned int maskp
cdef char ebuf[256]
status = pcap_lookupnet(dev, &netp, &maskp, ebuf)
if status:
raise OSError(ebuf)
return struct.pack('I', netp), struct.pack('I', maskp)