pcapy-0.10.8/0000777000000000000000000000000011435267005012661 5ustar rootroot00000000000000pcapy-0.10.8/bpfobj.cc0000666000000000000000000000425011350775776014452 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: bpfobj.cc 44 2009-02-05 14:09:28Z gera $ */ #include #include #include "bpfobj.h" #include "pcapy.h" // internal bpfobject typedef struct { PyObject_HEAD struct bpf_program bpf; } bpfobject; // BPFProgramType static void bpfprog_dealloc(register bpfobject* bpf) { #ifndef WIN32 // XXX: is this missing from winpcap 2.3? pcap_freecode(&bpf->bpf); #endif PyObject_Del(bpf); } // BPFProgram methods static PyObject* p_filter(register bpfobject* bpf, PyObject* args); static PyMethodDef bpf_methods[] = { {"filter", (PyCFunction) p_filter, METH_VARARGS, "filter(packet) applies the filter to the packet, returns 0 if there's no match"}, {NULL, NULL} /* sentinel */ }; static PyObject* bpfprog_getattr(bpfobject* pp, char* name) { return Py_FindMethod(bpf_methods, (PyObject*)pp, name); } PyTypeObject BPFProgramtype = { PyObject_HEAD_INIT(NULL) 0, "Bpf", sizeof(bpfobject), 0, /* methods */ (destructor)bpfprog_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)bpfprog_getattr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ }; PyObject* new_bpfobject(const struct bpf_program &bpfprog) { bpfobject *bpf; bpf = PyObject_New(bpfobject, &BPFProgramtype); if (bpf == NULL) return NULL; bpf->bpf = bpfprog; return (PyObject*)bpf; } static PyObject* p_filter(register bpfobject* bpf, PyObject* args) { int status; u_char* packet; unsigned int len; if (bpf->ob_type != &BPFProgramtype) { PyErr_SetString(PcapError, "Not a bpfprogram object"); return NULL; } if (!PyArg_ParseTuple(args,"s#:filter",&packet, &len)) return NULL; status = bpf_filter(bpf->bpf.bf_insns, packet, len, len); return Py_BuildValue("i", status); } pcapy-0.10.8/bpfobj.h0000666000000000000000000000067311077456503014307 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: bpfobj.h 24 2003-10-24 18:49:33Z jkohen $ */ #ifndef __bpfobj__ #define __bpfobj__ PyObject* new_bpfobject(const struct bpf_program &bpf); extern PyTypeObject Pcaptype; #endif // __bpfobj__ pcapy-0.10.8/ChangeLog0000666000000000000000000000305111435266267014443 0ustar rootroot000000000000002010-08-25 Ezequiel Gutesman * removed check for pcap_sendpacket function 2010-07-30 Ezequiel Gutesman * pcapy.cc: fixed bug in initpcapy, Pkthdr_type.ob_type and Pdumpertype.ob_type were not set. See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=589956 (reported by Piotr Lewandowski) 2007-03-27 Max Caceres * pcapobj.cc: wrapped pcap_sendpacket for sending packets in all platforms. 2005-12-09 Max Caceres * pcapy.cc: open_live doesn't raise an exception anymore when network/netmask information is not available (i.e. when sniffing on devices without an assigned IP address). Reported by Scott Raynel. 2005-09-14 Max Caceres * pcapobj.cc: fixed bug where exceptions thrown inside a callback where not handled properly. Fix relies on fairly new pcap_breakloop function. * pcapy.cc: in Windows uses findalldevs() packaged with new Winpcap 3.1 2005-08-15 Max Caceres * pcapy.cc: fixed bug where getnet() and getmask() always returned 0.0.0.0 (reported by Jeff Connelly) 2005-07-28 Max Caceres * pcapobj.cc: fixed a memory leak in PythonCallback (reported by fraca7 _at_ free.fr). 2004-01-05 Javier Kohen * setup.py: force linking with G++ when using GCC, to avoid a missing symbol in some setups. 2003-11-28 Javier Kohen * dcerpc_v4.py: Fixed self.bind variable having the same name than a method. pcapy-0.10.8/LICENSE0000666000000000000000000000514111077456503013674 0ustar rootroot00000000000000Licencing --------- We provide this software under a slightly modified version of the Apache Software License. The only changes to the document were the replacement of "Apache" with "Pcapy" and "Apache Software Foundation" with "CORE Security Technologies". Feel free to compare the resulting document to the official Apache license. The `Apache Software License' is an Open Source Initiative Approved License. The Apache Software License, Version 1.1 Modifications by CORE Security Technologies (see above) Copyright (c) 2000 The Apache Software Foundation. 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. 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes software developed by CORE Security Technologies (http://www.coresecurity.com/)." Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The names "Pcapy" and "CORE Security Technologies" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact oss@coresecurity.com. 5. Products derived from this software may not be called "Pcapy", nor may "Pcapy" appear in their name, without prior written permission of CORE Security Technologies. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 THE APACHE SOFTWARE FOUNDATION OR ITS 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. pcapy-0.10.8/MANIFEST.in0000666000000000000000000000021311077456503014420 0ustar rootroot00000000000000include MANIFEST.in include LICENSE include ChangeLog include pcapy.xml include pcapy.html include *.h recursive-include win32 *.cc pcapy-0.10.8/pcapdumper.cc0000666000000000000000000000442510602472250015330 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: pcapdumper.cc,v 1.3 2003/10/23 20:00:53 jkohen Exp $ */ #include #include #include "pcapdumper.h" #include "pcap_pkthdr.h" #include "pcapy.h" // internal pcapdumper typedef struct { PyObject_HEAD pcap_dumper_t *dumper; } pcapdumper; // Pdumpertype static void pcap_dealloc(register pcapdumper* pp) { if ( pp->dumper ) pcap_dump_close(pp->dumper); pp->dumper = NULL; PyObject_Del(pp); } // pcap methods //static PyObject* p_close(register pcapdumper* pp, PyObject* args); static PyObject* p_dump(register pcapdumper* pp, PyObject* args); static PyMethodDef p_methods[] = { // {"close", (PyCFunction) p_close, METH_VARARGS, "loops packet dispatching"}, {"dump", (PyCFunction) p_dump, METH_VARARGS, "dump a packet to the file"}, {NULL, NULL} /* sentinel */ }; static PyObject* pcap_getattr(pcapdumper* pp, char* name) { return Py_FindMethod(p_methods, (PyObject*)pp, name); } PyTypeObject Pdumpertype = { PyObject_HEAD_INIT(NULL) 0, "Dumper", sizeof(pcapdumper), 0, /* methods */ (destructor)pcap_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)pcap_getattr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ }; PyObject* new_pcapdumper(pcap_dumper_t *dumper) { pcapdumper *pp; pp = PyObject_New(pcapdumper, &Pdumpertype); if (pp == NULL) return NULL; pp->dumper = dumper; return (PyObject*)pp; } static PyObject* p_dump(register pcapdumper* pp, PyObject* args) { PyObject *pyhdr; u_char *data; int len; if (pp->ob_type != &Pdumpertype) { PyErr_SetString(PcapError, "Not a pcapdumper object"); return NULL; } if (!PyArg_ParseTuple(args,"Os#",&pyhdr,&data,&len)) return NULL; struct pcap_pkthdr hdr; if (-1 == pkthdr_to_native(pyhdr, &hdr)) return NULL; pcap_dump((u_char *)pp->dumper, &hdr, data); Py_INCREF(Py_None); return Py_None; } pcapy-0.10.8/pcapdumper.h0000666000000000000000000000071710602472250015172 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: pcapdumper.h,v 1.2 2003/10/23 20:00:53 jkohen Exp $ */ #ifndef __pcapdumper__ #define __pcapdumper__ PyObject* new_pcapdumper(pcap_dumper_t *dumper); extern PyTypeObject Pdumpertype; #endif // __pcapdumper__ pcapy-0.10.8/pcapobj.cc0000666000000000000000000002454711350776063014627 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: pcapobj.cc 45 2009-02-05 14:11:33Z gera $ */ #include #include #include "pcapobj.h" #include "pcapy.h" #include "pcapdumper.h" #include "pcap_pkthdr.h" #ifdef WIN32 #include #else #include #endif // internal pcapobject typedef struct { PyObject_HEAD pcap_t *pcap; bpf_u_int32 net; bpf_u_int32 mask; } pcapobject; // PcapType static void pcap_dealloc(register pcapobject* pp) { if ( pp->pcap ) pcap_close(pp->pcap); pp->pcap = NULL; PyObject_Del(pp); } // pcap methods static PyObject* p_getnet(register pcapobject* pp, PyObject* args); static PyObject* p_getmask(register pcapobject* pp, PyObject* args); static PyObject* p_setfilter( register pcapobject* pp, PyObject* args ); static PyObject* p_next(register pcapobject* pp, PyObject*); static PyObject* p_dispatch(register pcapobject* pp, PyObject* args); static PyObject* p_loop(register pcapobject* pp, PyObject* args); static PyObject* p_datalink(register pcapobject* pp, PyObject* args); static PyObject* p_setnonblock(register pcapobject* pp, PyObject* args); static PyObject* p_getnonblock(register pcapobject* pp, PyObject* args); static PyObject* p_dump_open(register pcapobject* pp, PyObject* args); #ifdef HAVE_PCAP_SENDPACKET static PyObject* p_sendpacket(register pcapobject* pp, PyObject* args); #endif static PyMethodDef p_methods[] = { {"loop", (PyCFunction) p_loop, METH_VARARGS, "loops packet dispatching"}, {"dispatch", (PyCFunction) p_dispatch, METH_VARARGS, "dispatchs packets"}, {"next", (PyCFunction) p_next, METH_NOARGS, "returns next packet"}, {"setfilter", (PyCFunction) p_setfilter, METH_VARARGS, "compiles and sets a BPF capture filter"}, {"getnet", (PyCFunction) p_getnet, METH_VARARGS, "returns the network address for the device"}, {"getmask", (PyCFunction) p_getmask, METH_VARARGS, "returns the netmask for the device"}, {"datalink", (PyCFunction) p_datalink, METH_VARARGS, "returns the link layer type"}, {"getnonblock", (PyCFunction) p_getnonblock, METH_VARARGS, "returns the current `non-blocking' state"}, {"setnonblock", (PyCFunction) p_setnonblock, METH_VARARGS, "puts into `non-blocking' mode, or take it out, depending on the argument"}, {"dump_open", (PyCFunction) p_dump_open, METH_VARARGS, "creates a dumper object"}, #ifdef HAVE_PCAP_SENDPACKET {"sendpacket", (PyCFunction) p_sendpacket, METH_VARARGS, "sends a packet through the interface"}, #endif {NULL, NULL} /* sentinel */ }; static PyObject* pcap_getattr(pcapobject* pp, char* name) { return Py_FindMethod(p_methods, (PyObject*)pp, name); } PyTypeObject Pcaptype = { PyObject_HEAD_INIT(NULL) 0, "Reader", sizeof(pcapobject), 0, /* methods */ (destructor)pcap_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)pcap_getattr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ }; PyObject* new_pcapobject(pcap_t *pcap, bpf_u_int32 net, bpf_u_int32 mask) { pcapobject *pp; pp = PyObject_New(pcapobject, &Pcaptype); if (pp == NULL) return NULL; pp->pcap = pcap; pp->net = net; pp->mask = mask; return (PyObject*)pp; } static void ntos(char* dst, unsigned int n, int ip) { ip = htonl(ip); snprintf(dst, n, "%i.%i.%i.%i", ((ip >> 24) & 0xFF), ((ip >> 16) & 0xFF), ((ip >> 8) & 0xFF), (ip & 0xFF)); } static PyObject* p_getnet(register pcapobject* pp, PyObject* args) { if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } char ip_str[20]; ntos(ip_str, sizeof(ip_str), pp->net); return Py_BuildValue("s", ip_str); } static PyObject* p_getmask(register pcapobject* pp, PyObject* args) { if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } char ip_str[20]; ntos(ip_str, sizeof(ip_str), pp->mask); return Py_BuildValue("s", ip_str); } static PyObject* p_setfilter(register pcapobject* pp, PyObject* args) { struct bpf_program bpfprog; int status; char* str; if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!PyArg_ParseTuple(args,"s:setfilter",&str)) return NULL; status = pcap_compile(pp->pcap, &bpfprog, str, 1, pp->mask); if (status) { PyErr_SetString(PcapError, pcap_geterr(pp->pcap)); return NULL; } status = pcap_setfilter(pp->pcap, &bpfprog); if (status) { PyErr_SetString(PcapError, pcap_geterr(pp->pcap)); return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject* p_next(register pcapobject* pp, PyObject*) { struct pcap_pkthdr hdr; const unsigned char *buf; if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } // allow threads as this might block Py_BEGIN_ALLOW_THREADS; buf = pcap_next(pp->pcap, &hdr); Py_END_ALLOW_THREADS; if(!buf) { PyErr_SetString(PcapError, pcap_geterr(pp->pcap)); return NULL; } PyObject *pkthdr = new_pcap_pkthdr(&hdr); if (pkthdr) { PyObject *ret = NULL; ret = Py_BuildValue("(Os#)", pkthdr, buf, hdr.caplen); Py_DECREF(pkthdr); return ret; } PyErr_SetString(PcapError, "Can't build pkthdr"); return NULL; } struct PcapCallbackContext { PcapCallbackContext(pcap_t* p, PyObject* f, PyThreadState* ts) : ppcap_t(p), pyfunc(f), thread_state(ts) { Py_INCREF(pyfunc); } ~PcapCallbackContext() { Py_DECREF(pyfunc); } pcap_t* ppcap_t; PyObject *pyfunc; PyThreadState *thread_state; }; static void PythonCallBack(u_char *user, const struct pcap_pkthdr *header, const u_char *packetdata) { PyObject *arglist, *result; unsigned int *len; PcapCallbackContext *pctx; len = (unsigned int *)&header->caplen; pctx = (PcapCallbackContext *)user; PyEval_RestoreThread(pctx->thread_state); PyObject *hdr = new_pcap_pkthdr(header); arglist = Py_BuildValue("Os#", hdr, packetdata, *len); result = PyEval_CallObject(pctx->pyfunc,arglist); Py_XDECREF(arglist); if (result) Py_DECREF(result); Py_DECREF(hdr); if (!result) pcap_breakloop(pctx->ppcap_t); PyEval_SaveThread(); } static PyObject* p_dispatch(register pcapobject* pp, PyObject* args) { int cant, ret; PyObject *PyFunc; if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if(!PyArg_ParseTuple(args,"iO:dispatch",&cant,&PyFunc)) return NULL; PcapCallbackContext ctx(pp->pcap, PyFunc, PyThreadState_Get()); PyEval_SaveThread(); ret = pcap_dispatch(pp->pcap, cant, PythonCallBack, (u_char*)&ctx); PyEval_RestoreThread(ctx.thread_state); if(ret<0) { if (ret!=-2) /* pcap error, pcap_breakloop was not called so error is not set */ PyErr_SetString(PcapError, pcap_geterr(pp->pcap)); return NULL; } return Py_BuildValue("i", ret); } static PyObject* p_dump_open(register pcapobject* pp, PyObject* args) { char *filename; pcap_dumper_t *ret; if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if(!PyArg_ParseTuple(args,"s",&filename)) return NULL; ret = pcap_dump_open(pp->pcap, filename); if (ret==NULL) { PyErr_SetString(PcapError, pcap_geterr(pp->pcap)); return NULL; } return new_pcapdumper(ret); } static PyObject* p_loop(register pcapobject* pp, PyObject* args) { int cant, ret; PyObject *PyFunc; if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if(!PyArg_ParseTuple(args,"iO:loop",&cant,&PyFunc)) return NULL; PcapCallbackContext ctx(pp->pcap, PyFunc, PyThreadState_Get()); PyEval_SaveThread(); ret = pcap_loop(pp->pcap, cant, PythonCallBack, (u_char*)&ctx); PyEval_RestoreThread(ctx.thread_state); if(ret<0) { if (ret!=-2) /* pcap error, pcap_breakloop was not called so error is not set */ PyErr_SetString(PcapError, pcap_geterr(pp->pcap)); return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject* p_datalink(register pcapobject* pp, PyObject* args) { if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } int type = pcap_datalink(pp->pcap); return Py_BuildValue("i", type); } static PyObject* p_setnonblock(register pcapobject* pp, PyObject* args) { if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } int state; if (!PyArg_ParseTuple(args, "i", &state)) return NULL; char errbuf[PCAP_ERRBUF_SIZE]; int ret = pcap_setnonblock(pp->pcap, state, errbuf); if (-1 == ret) { PyErr_SetString(PcapError, errbuf); return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject* p_getnonblock(register pcapobject* pp, PyObject* args) { if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } char errbuf[PCAP_ERRBUF_SIZE]; int state = pcap_getnonblock(pp->pcap, errbuf); if (-1 == state) { PyErr_SetString(PcapError, errbuf); return NULL; } return Py_BuildValue("i", state); } #ifdef HAVE_PCAP_SENDPACKET static PyObject* p_sendpacket(register pcapobject* pp, PyObject* args) { int status; unsigned char* str; unsigned int length; if (pp->ob_type != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!PyArg_ParseTuple(args,"s#", &str, &length)) return NULL; status = pcap_sendpacket(pp->pcap, str, length); if (status) { PyErr_SetString(PcapError, pcap_geterr(pp->pcap)); return NULL; } Py_INCREF(Py_None); return Py_None; } #endif pcapy-0.10.8/pcapobj.h0000666000000000000000000000073610602472250014451 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: pcapobj.h,v 1.3 2003/10/23 20:00:53 jkohen Exp $ */ #ifndef __pcapobj__ #define __pcapobj__ PyObject* new_pcapobject(pcap_t *pcap, bpf_u_int32 net=0, bpf_u_int32 mask=0); extern PyTypeObject Pcaptype; #endif // __pcapobj__ pcapy-0.10.8/pcapy.cc0000666000000000000000000001203611435257432014311 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: pcapy.cc 46 2010-08-25 18:06:31Z gutes $ */ #include #include #include "pcapy.h" #include "pcapobj.h" #include "bpfobj.h" #include "pcapdumper.h" #include "pcap_pkthdr.h" PyObject *PcapError; // module methods static PyObject* lookupdev(PyObject* self, PyObject* args) { char errbuff[PCAP_ERRBUF_SIZE]; char* dev; dev = pcap_lookupdev(errbuff); if(!dev) { PyErr_SetString(PcapError, errbuff); return NULL; } return Py_BuildValue("u", dev); } static PyObject* findalldevs(PyObject *self, PyObject *args) { char errbuff[PCAP_ERRBUF_SIZE]; pcap_if_t *devs; int status = pcap_findalldevs(&devs, errbuff); if(status) { PyErr_SetString(PcapError, errbuff); return NULL; } if(devs==NULL) { PyErr_SetString(PcapError, "No valid interfaces to open"); return NULL; } pcap_if_t *cursor = devs; PyObject* list = PyList_New(0); while(cursor) { PyList_Append(list, Py_BuildValue("s", cursor->name)); cursor = cursor->next; } pcap_freealldevs(devs); return list; } static PyObject* open_live(PyObject *self, PyObject *args) { char errbuff[PCAP_ERRBUF_SIZE]; char * device; int snaplen; int promisc; int to_ms; bpf_u_int32 net, mask; if(!PyArg_ParseTuple(args,"siii:open_live",&device,&snaplen,&promisc,&to_ms)) return NULL; int status = pcap_lookupnet(device, &net, &mask, errbuff); if(status) { net = 0; mask = 0; } pcap_t* pt; pt = pcap_open_live(device, snaplen, promisc!=0, to_ms, errbuff); if(!pt) { PyErr_SetString(PcapError, errbuff); return NULL; } #ifdef WIN32 pcap_setmintocopy(pt, 0); #endif return new_pcapobject( pt, net, mask ); } static PyObject* open_offline(PyObject *self, PyObject *args) { char errbuff[PCAP_ERRBUF_SIZE]; char * filename; if(!PyArg_ParseTuple(args,"s",&filename)) return NULL; pcap_t* pt; pt = pcap_open_offline(filename, errbuff); if(!pt) { PyErr_SetString(PcapError, errbuff); return NULL; } #ifdef WIN32 pcap_setmintocopy(pt, 0); #endif return new_pcapobject( pt ); } static PyObject* bpf_compile(PyObject* self, PyObject* args) { int linktype; int snaplen; char *filter; int optimize; unsigned int netmask; if(!PyArg_ParseTuple(args, "iisiI:compile", &linktype, &snaplen, &filter, &optimize, &netmask)) return NULL; pcap_t *pp; pp = pcap_open_dead(linktype, snaplen); if(pp == NULL) return NULL; struct bpf_program bpf; int status = pcap_compile(pp, &bpf, filter, optimize, netmask); pcap_close(pp); if(status) { PyErr_SetString(PcapError, pcap_geterr(pp)); return NULL; } return new_bpfobject( bpf ); } static PyMethodDef pcap_methods[] = { {"open_live", open_live, METH_VARARGS, "open_live(device, snaplen, promisc, to_ms) opens a pcap device"}, {"open_offline", open_offline, METH_VARARGS, "open_offline(filename) opens a pcap formated file"}, {"lookupdev", lookupdev, METH_VARARGS, "lookupdev() looks up a pcap device"}, {"findalldevs", findalldevs, METH_VARARGS, "findalldevs() lists all available interfaces"}, {"compile", bpf_compile, METH_VARARGS, "compile(linktype, snaplen, filter, optimize, netmask) creates a bpfprogram object"}, {NULL, NULL} }; static char *pcap_doc = "\nA wrapper for the Packet Capture (PCAP) library\n"; void initpcapy(void) { PyObject *m, *d; Pcaptype.ob_type = &PyType_Type; Pkthdr_type.ob_type = &PyType_Type; Pdumpertype.ob_type = &PyType_Type; m = Py_InitModule3("pcapy", pcap_methods, pcap_doc); /* Direct from pcap's net/bpf.h. */ PyModule_AddIntConstant(m, "DLT_NULL", 0); PyModule_AddIntConstant(m, "DLT_EN10MB", 1); PyModule_AddIntConstant(m, "DLT_IEEE802", 6); PyModule_AddIntConstant(m, "DLT_ARCNET", 7); PyModule_AddIntConstant(m, "DLT_SLIP", 8); PyModule_AddIntConstant(m, "DLT_PPP", 9); PyModule_AddIntConstant(m, "DLT_FDDI", 10); PyModule_AddIntConstant(m, "DLT_ATM_RFC1483", 11); PyModule_AddIntConstant(m, "DLT_RAW", 12); PyModule_AddIntConstant(m, "DLT_PPP_SERIAL", 50); PyModule_AddIntConstant(m, "DLT_PPP_ETHER", 51); PyModule_AddIntConstant(m, "DLT_C_HDLC", 104); PyModule_AddIntConstant(m, "DLT_IEEE802_11", 105); PyModule_AddIntConstant(m, "DLT_LOOP", 108); PyModule_AddIntConstant(m, "DLT_LINUX_SLL", 113); PyModule_AddIntConstant(m, "DLT_LTALK", 114); d = PyModule_GetDict(m); PcapError = PyErr_NewException("pcapy.PcapError", NULL, NULL ); if( PcapError ) PyDict_SetItemString( d, "PcapError", PcapError ); } pcapy-0.10.8/pcapy.h0000666000000000000000000000073610602472250014147 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: pcapy.h,v 1.2 2003/10/23 20:00:53 jkohen Exp $ */ #ifndef __PCAPY_H__ extern "C" { #ifdef WIN32 __declspec(dllexport) #endif void initpcapy(void); } // exception object extern PyObject* PcapError; #endif // __PCAPY_H__ pcapy-0.10.8/pcapy.html0000666000000000000000000007315310602472250014667 0ustar rootroot00000000000000Part I. Pcapy Reference

Pcapy Reference

CORE SECURITY TECHNOLOGIES

Revision History
Revision $Revision: 1.2 $$Date: 2003/10/23 17:24:27 $$Author: jkohen $
Initial revision

Pcapy Module Reference


open_live

Name

open_live — Obtain a packet capture descriptor to look at packets on the network

Synopsis

Reader open_live(device, snaplen, promisc, to_ms);
string device;
int snaplen;
int promisc;
int to_ms;

DESCRIPTION

open_live is used to obtain a packet capture descriptor to look at packets on the network. device is a string that specifies the network device to open; on Linux systems with 2.2 or later kernels, a device argument of any or NULL can be used to capture packets from all interfaces. snaplen specifies the maximum number of bytes to capture. promisc specifies if the interface is to be put into promiscuous mode. (Note that even if this parameter is false, the interface could well be in promiscuous mode for some other reason.) For now, this doesn't work on the any device; if an argument of any or NULL is supplied, the promisc flag is ignored. to_ms specifies the read timeout in milliseconds. The read timeout is used to arrange that the read not necessarily return immediately when a packet is seen, but that it wait for some amount of time to allow more packets to arrive and to read multiple packets from the OS kernel in one operation. Not all platforms support a read timeout; on platforms that don't, the read timeout is ignored.

open_offline

Name

open_offline — Obtain a packet capture descriptor to look at packets on a savefile

Synopsis

Reader open_offline(filename);
string filename;

DESCRIPTION

open_offline is called to open a savefile for reading. filename specifies the name of the file to open. The file has the same format as those used by tcpdump(8) and tcpslice(8). The name - is a synonym for stdin.

lookupdev

Name

lookupdev — Return a network device suitable for use with open_live

Synopsis

string lookupdev();

DESCRIPTION

lookupdev returns the name of a network device suitable for use with open_live.

findalldevs

Name

findalldevs — Obtain the list of available network devices

Synopsis

string[] findalldevs();

DESCRIPTION

findalldevs constructs a list of network devices that can be opened with open_live. (Note that there may be network devices that cannot be opened with open_live, because, for example, that process might not have sufficient privileges to open them for capturing; if so, those devices will not appear on the list.)

compile

Name

compile — Compile a BPF filter

Synopsis

Bpf compile(linktype, snaplen, filter, optimize, netmask);
int linktype;
int snaplen;
string filter;
int optimize;
int32 netmask;

DESCRIPTION

compile is used to compile the filter into a filter program. snaplen specifies the maximum number of bytes to capture. optimize controls whether optimization on the resulting code is performed. netmask specifies the netmask of the local network.

Reader Object Reference


dispatch

Name

dispatch, loop — Collect and process packets

Synopsis

int dispatch(maxcant, (* callback));
int maxcant;
void (* callback) (Pkthdr, string);

int loop(maxcant, (* callback));
int maxcant;
void (* callback) (Pkthdr, string);

DESCRIPTION

dispatch is used to collect and process packets. maxcant specifies the maximum number of packets to process before returning. This is not a minimum number; when reading a live capture, only one bufferful of packets is read at a time, so fewer than maxcant packets may be processed. A cnt of -1 processes all the packets received in one buffer when reading a live capture, or all the packets in the file when reading a savefile. callback specifies a routine to be called with two arguments: a Pkthdr instance describing the data passed and the data itself.

The number of packets read is returned. 0 is returned if no packets were read from a live capture (if, for example, they were discarded because they didn't pass the packet filter, or if, on platforms that support a read timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is in non–blocking mode and no packets were available to be read) or if no more packets are available in a savefile.

Note

When reading a live capture, dispatch will not necessarily return when the read times out; on some platforms, the read timeout isn't supported, and, on other platforms, the timer doesn't start until at least one packet arrives. This means that the read timeout should not be used in, for example, an interactive application, to allow the packet capture loop to poll for user input periodically, as there's no guarantee that dispatch will return after the timeout expires.

loop is similar to dispatch except it keeps reading packets until maxcant packets are processed or an error occurs. It does not return when live read timeouts occur. Rather, specifying a non–zero read timeout to open_live and then calling dispatch allows the reception and processing of any packets that arrive when the timeout occurs. A negative maxcant causes loop to loop forever (or at least until an error occurs). 0 is returned if maxcant is exhausted.

next

Name

next — Collect the next packet

Synopsis

(Pkthdr, string) next();

DESCRIPTION

next reads the next packet (by calling dispatch with a maxcant of 1) and returns a tuple (header, data) where header is a Pkthdr instance describing the data passed and data is the data itself.

setfilter

Name

setfilter — Specify a filter

Synopsis

setfilter(filter);
string filter;

DESCRIPTION

setfilter is used to specify a filter for this object.

getnet

Name

getnet, getmask — Get the associated network number and mask

Synopsis

int32 getnet();

int32 getmask();

DESCRIPTION

getnet and getmask are used to determine the network number and mask associated with the network device attached to this Reader.

datalink

Name

datalink — Obtain the link layer type

Synopsis

int datalink();

DESCRIPTION

datalink returns the link layer type; link layer types it can return include:

DLT_NULL

BSD loopback encapsulation; the link layer header is a 4–byte field, in host byte order, containing a PF_ value from socket.h for the network–layer protocol of the packet.

Note

“host byte order” is the byte order of the machine on which the packets are captured, and the PF_ values are for the OS of the machine on which the packets are captured; if a live capture is being done, “host byte order” is the byte order of the machine capturing the packets, and the PF_ values are those of the OS of the machine capturing the packets, but if a savefile is being read, the byte order and PF_ values are not necessarily those of the machine reading the capture file.

DLT_EN10MB

Ethernet (10Mb, 100Mb, 1000Mb, and up)

DLT_IEEE802

IEEE 802.5 Token Ring

DLT_ARCNET

ARCNET

DLT_SLIP

SLIP; the link layer header contains, in order:

  • a 1–byte flag, which is 0 for packets received by the machine and 1 for packets sent by the machine.

  • a 1–byte field, the upper 4 bits of which indicate the type of packet, as per RFC 1144:

    • 0x40; an unmodified IP datagram (TYPE_IP)

    • 0x70; an uncompressed–TCP/IP datagram (UNCOMPRESSED_TCP), with that byte being the first byte of the raw IP header on the wire, containing the connection number in the protocol field

    • 0x80; a compressed–TCP/IP datagram (COMPRESSED_TCP), with that byte being the first byte of the compressed TCP/IP datagram header

  • for UNCOMPRESSED_TCP, the rest of the modified IP header, and for COMPRESSED_TCP, the compressed TCP/IP datagram header

for a total of 16 bytes; the uncompressed IP datagram follows the header.

DLT_PPP

PPP; if the first 2 bytes are 0xff and 0x03, it's PPP in HDLC–like framing, with the PPP header following those two bytes, otherwise it's PPP without framing, and the packet begins with the PPP header.

DLT_FDDI

FDDI

DLT_ATM_RFC1483

RFC 1483 LLC/SNAP–encapsulated ATM; the packet begins with an IEEE 802.2 LLC header.

DLT_RAW

Raw IP; the packet begins with an IP header.

DLT_PPP_SERIAL

PPP in HDLC–like framing, as per RFC 1662, or Cisco PPP with HDLC framing, as per section 4.3.1 of RFC 1547; the first byte will be 0xFF for PPP in HDLC–like framing, and will be 0x0F or 0x8F for Cisco PPP with HDLC framing.

DLT_PPP_ETHER

PPPoE; the packet begins with a PPPoE header, as per RFC 2516.

DLT_C_HDLC

Cisco PPP with HDLC framing, as per section 4.3.1 of RFC 1547.

DLT_IEEE802_11

IEEE 802.11 wireless LAN.

DLT_LOOP

OpenBSD loopback encapsulation; the link layer header is a 4–byte field, in network byte order, containing a PF_ value from OpenBSD's socket.h for the network–layer protocol of the packet.

Note

Note that, if a savefile is being read, those PF_ values are not necessarily those of the machine reading the capture file.

DLT_LINUX_SLL

Linux cooked capture encapsulation; the link layer header contains, in order:

  • a 2–byte "packet type", in network byte order, which is one of:

    • 0; packet was sent to us by somebody else.

    • 1; packet was broadcast by somebody else.

    • 2; packet was multicast, but not broadcast, by somebody else.

    • 3; packet was sent by somebody else to somebody else.

    • 4; packet was sent by us.

  • a 2–byte field, in network byte order, containing a Linux ARPHRD_ value for the link layer device type.

  • a 2–byte field, in network byte order, containing the length of the link layer address of the sender of the packet (which could be 0).

  • an 8–byte field containing that number of bytes of the link layer header (if there are more than 8 bytes, only the first 8 are present).

  • a 2–byte field containing an Ethernet protocol type, in network byte order, or containing 1 for Novell 802.3 frames without an 802.2 LLC header or 4 for frames beginning with an 802.2 LLC header.

DLT_LTALK

Apple LocalTalk; the packet begins with an AppleTalk LLAP header.

getnonblock

Name

getnonblock, setnonblock — Manipulate the non–blocking flag

Synopsis

int getnonblock();

setnonblock(state);
int state;

DESCRIPTION

getnonblock returns the current non–blocking state of the capture descriptor; it always returns 0 on savefiles.

DESCRIPTION

setnonblock puts a capture descriptor, opened with open_live, into non–blocking mode, or takes it out of non–blocking mode, depending on whether the state argument is non–zero or zero. It has no effect on savefiles. In non–blocking mode, an attempt to read from the capture descriptor with dispatch will, if no packets are currently available to be read, return 0 immediately rather than blocking waiting for packets to arrive. loop and next will not work in non–blocking mode.

dump_open

Name

dump_open — Create a Dumper object

Synopsis

Dumper dump_open(filename);
string filename;

DESCRIPTION

dump_open is called to open a savefile for writing and associate it to a newly created Dumper instance. The name - is a synonym for stdout. filename specifies the name of the file to open.

Dumper Object Reference


Table of Contents

dump

dump

Name

dump — Dump a packet to a savefile

Synopsis

dump(header, data);
Pkthdr header;
string data;

DESCRIPTION

dump outputs a packet to the savefile opened with dump_open from type Reader.

Pkthdr Object Reference


Table of Contents

getts

getts

Name

getts, getcaplen, getlen — Obtain packet header information

Synopsis

(long, long) getts();

long getcaplen();

long getlen();

DESCRIPTION

getts, getcaplen and getlen return the timestamp, capture length and total length fields of the packet header, respectively.

Timestamp is a tuple with two elements: the number of seconds since the Epoch, and the amount of microseconds past the current second. The capture length is the number of bytes of the packet that are available from the capture. Finally, total length gives the length of the packet, in bytes (which might be more than the number of bytes available from the capture, if the length of the packet is larger than the maximum number of bytes to capture).

Bpf Object Reference


Table of Contents

filter

filter

Name

filter — Test a packet against a compiled filter

Synopsis

int filter(packet);
string packet;

DESCRIPTION

filter tests a packet against a compiled filter as returned by pcapy's compile. If the packet is allowed to pass through -1 is returned, otherwise filter returns 0.

Bibliography

Sources

Portions of this work based on pcap(3) by the Lawrence Berkeley National Laboratory, University of California, Berkeley, CA. .

pcapy-0.10.8/pcapy.xml0000666000000000000000000007231711100421201014504 0ustar rootroot00000000000000 ]> 2003 &corest; &corest; pcap packet capture python $Revision: 15 $ $Date: 2003-10-23 14:24:27 -0300 (Jue, 23 Oct 2003) $ $Author: jkohen $ Initial revision Pcapy Reference Pcapy Module Reference open_live Obtain a packet capture descriptor to look at packets on the network Reader open_live string device int snaplen int promisc int to_ms DESCRIPTION open_live is used to obtain a packet capture descriptor to look at packets on the network. device is a string that specifies the network device to open; on Linux systems with 2.2 or later kernels, a device argument of any or NULL can be used to capture packets from all interfaces. snaplen specifies the maximum number of bytes to capture. promisc specifies if the interface is to be put into promiscuous mode. (Note that even if this parameter is false, the interface could well be in promiscuous mode for some other reason.) For now, this doesn't work on the any device; if an argument of any or NULL is supplied, the promisc flag is ignored. to_ms specifies the read timeout in milliseconds. The read timeout is used to arrange that the read not necessarily return immediately when a packet is seen, but that it wait for some amount of time to allow more packets to arrive and to read multiple packets from the OS kernel in one operation. Not all platforms support a read timeout; on platforms that don't, the read timeout is ignored. open_offline Obtain a packet capture descriptor to look at packets on a savefile Reader open_offline string filename DESCRIPTION open_offline is called to open a savefile for reading. filename specifies the name of the file to open. The file has the same format as those used by tcpdump 8 and tcpslice 8. The name - is a synonym for stdin. lookupdev Return a network device suitable for use with open_live string lookupdev DESCRIPTION lookupdev returns the name of a network device suitable for use with open_live. findalldevs Obtain the list of available network devices string[] findalldevs DESCRIPTION findalldevs constructs a list of network devices that can be opened with open_live. (Note that there may be network devices that cannot be opened with open_live, because, for example, that process might not have sufficient privileges to open them for capturing; if so, those devices will not appear on the list.) compile Compile a BPF filter Bpf compile int linktype int snaplen string filter int optimize int32 netmask DESCRIPTION compile is used to compile the filter into a filter program. snaplen specifies the maximum number of bytes to capture. optimize controls whether optimization on the resulting code is performed. netmask specifies the netmask of the local network. Reader Object Reference dispatch loop Collect and process packets int dispatch int maxcant void (* callback) Pkthdr, string int loop int maxcant void (* callback) Pkthdr, string DESCRIPTION dispatch is used to collect and process packets. maxcant specifies the maximum number of packets to process before returning. This is not a minimum number; when reading a live capture, only one bufferful of packets is read at a time, so fewer than maxcant packets may be processed. A cnt of -1 processes all the packets received in one buffer when reading a live capture, or all the packets in the file when reading a savefile. callback specifies a routine to be called with two arguments: a Pkthdr instance describing the data passed and the data itself. The number of packets read is returned. 0 is returned if no packets were read from a live capture (if, for example, they were discarded because they didn't pass the packet filter, or if, on platforms that support a read timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is in non–blocking mode and no packets were available to be read) or if no more packets are available in a savefile. When reading a live capture, dispatch will not necessarily return when the read times out; on some platforms, the read timeout isn't supported, and, on other platforms, the timer doesn't start until at least one packet arrives. This means that the read timeout should not be used in, for example, an interactive application, to allow the packet capture loop to poll for user input periodically, as there's no guarantee that dispatch will return after the timeout expires. loop is similar to dispatch except it keeps reading packets until maxcant packets are processed or an error occurs. It does not return when live read timeouts occur. Rather, specifying a non–zero read timeout to open_live and then calling dispatch allows the reception and processing of any packets that arrive when the timeout occurs. A negative maxcant causes loop to loop forever (or at least until an error occurs). 0 is returned if maxcant is exhausted. next Collect the next packet (Pkthdr, string) next DESCRIPTION next reads the next packet (by calling dispatch with a maxcant of 1) and returns a tuple (header, data) where header is a Pkthdr instance describing the data passed and data is the data itself. setfilter Specify a filter setfilter string filter DESCRIPTION setfilter is used to specify a filter for this object. getnet getmask Get the associated network number and mask int32 getnet int32 getmask DESCRIPTION getnet and getmask are used to determine the network number and mask associated with the network device attached to this Reader. datalink Obtain the link layer type int datalink DESCRIPTION datalink returns the link layer type; link layer types it can return include: DLT_NULL BSD loopback encapsulation; the link layer header is a 4–byte field, in host byte order, containing a PF_ value from socket.h for the network–layer protocol of the packet. host byte order is the byte order of the machine on which the packets are captured, and the PF_ values are for the OS of the machine on which the packets are captured; if a live capture is being done, host byte order is the byte order of the machine capturing the packets, and the PF_ values are those of the OS of the machine capturing the packets, but if a savefile is being read, the byte order and PF_ values are not necessarily those of the machine reading the capture file. DLT_EN10MB Ethernet (10Mb, 100Mb, 1000Mb, and up) DLT_IEEE802 IEEE 802.5 Token Ring DLT_ARCNET ARCNET DLT_SLIP SLIP; the link layer header contains, in order: a 1–byte flag, which is 0 for packets received by the machine and 1 for packets sent by the machine. a 1–byte field, the upper 4 bits of which indicate the type of packet, as per RFC 1144: 0x40; an unmodified IP datagram (TYPE_IP) 0x70; an uncompressed–TCP/IP datagram (UNCOMPRESSED_TCP), with that byte being the first byte of the raw IP header on the wire, containing the connection number in the protocol field 0x80; a compressed–TCP/IP datagram (COMPRESSED_TCP), with that byte being the first byte of the compressed TCP/IP datagram header for UNCOMPRESSED_TCP, the rest of the modified IP header, and for COMPRESSED_TCP, the compressed TCP/IP datagram header for a total of 16 bytes; the uncompressed IP datagram follows the header. DLT_PPP PPP; if the first 2 bytes are 0xff and 0x03, it's PPP in HDLC–like framing, with the PPP header following those two bytes, otherwise it's PPP without framing, and the packet begins with the PPP header. DLT_FDDI FDDI DLT_ATM_RFC1483 RFC 1483 LLC/SNAP–encapsulated ATM; the packet begins with an IEEE 802.2 LLC header. DLT_RAW Raw IP; the packet begins with an IP header. DLT_PPP_SERIAL PPP in HDLC–like framing, as per RFC 1662, or Cisco PPP with HDLC framing, as per section §4.3.1 of RFC 1547; the first byte will be 0xFF for PPP in HDLC–like framing, and will be 0x0F or 0x8F for Cisco PPP with HDLC framing. DLT_PPP_ETHER PPPoE; the packet begins with a PPPoE header, as per RFC 2516. DLT_C_HDLC Cisco PPP with HDLC framing, as per section § 4.3.1 of RFC 1547. DLT_IEEE802_11 IEEE 802.11 wireless LAN. DLT_LOOP OpenBSD loopback encapsulation; the link layer header is a 4–byte field, in network byte order, containing a PF_ value from OpenBSD's socket.h for the network–layer protocol of the packet. Note that, if a savefile is being read, those PF_ values are not necessarily those of the machine reading the capture file. DLT_LINUX_SLL Linux cooked capture encapsulation; the link layer header contains, in order: a 2–byte "packet type", in network byte order, which is one of: 0; packet was sent to us by somebody else. 1; packet was broadcast by somebody else. 2; packet was multicast, but not broadcast, by somebody else. 3; packet was sent by somebody else to somebody else. 4; packet was sent by us. a 2–byte field, in network byte order, containing a Linux ARPHRD_ value for the link layer device type. a 2–byte field, in network byte order, containing the length of the link layer address of the sender of the packet (which could be 0). an 8–byte field containing that number of bytes of the link layer header (if there are more than 8 bytes, only the first 8 are present). a 2–byte field containing an Ethernet protocol type, in network byte order, or containing 1 for Novell 802.3 frames without an 802.2 LLC header or 4 for frames beginning with an 802.2 LLC header. DLT_LTALK Apple LocalTalk; the packet begins with an AppleTalk LLAP header. getnonblock setnonblock Manipulate the non–blocking flag int getnonblock setnonblock int state DESCRIPTION getnonblock returns the current non–blocking state of the capture descriptor; it always returns 0 on savefiles. DESCRIPTION setnonblock puts a capture descriptor, opened with open_live, into non–blocking mode, or takes it out of non–blocking mode, depending on whether the state argument is non–zero or zero. It has no effect on savefiles. In non–blocking mode, an attempt to read from the capture descriptor with dispatch will, if no packets are currently available to be read, return 0 immediately rather than blocking waiting for packets to arrive. loop and next will not work in non–blocking mode. dump_open Create a Dumper object Dumper dump_open string filename DESCRIPTION dump_open is called to open a savefile for writing and associate it to a newly created Dumper instance. The name - is a synonym for stdout. filename specifies the name of the file to open. Dumper Object Reference dump Dump a packet to a savefile dump Pkthdr header string data DESCRIPTION dump outputs a packet to the savefile opened with dump_open from type Reader. Pkthdr Object Reference getts getcaplen getlen Obtain packet header information (long, long) getts long getcaplen long getlen DESCRIPTION getts, getcaplen and getlen return the timestamp, capture length and total length fields of the packet header, respectively. Timestamp is a tuple with two elements: the number of seconds since the Epoch, and the amount of microseconds past the current second. The capture length is the number of bytes of the packet that are available from the capture. Finally, total length gives the length of the packet, in bytes (which might be more than the number of bytes available from the capture, if the length of the packet is larger than the maximum number of bytes to capture). Bpf Object Reference filter Test a packet against a compiled filter int filter string packet DESCRIPTION filter tests a packet against a compiled filter as returned by pcapy's compile. If the packet is allowed to pass through -1 is returned, otherwise filter returns 0. Bibliography Sources Portions of this work based on pcap 3 by the Lawrence Berkeley National Laboratory, University of California, Berkeley, CA. pcapy-0.10.8/pcap_pkthdr.cc0000666000000000000000000000605611100421126015457 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: pcap_pkthdr.cc 21 2003-10-23 20:00:54Z jkohen $ */ #include #include #include "pcapy.h" #include "pcap_pkthdr.h" #ifdef WIN32 #include #else #include #endif // internal pcapobject typedef struct { PyObject_HEAD struct timeval ts; bpf_u_int32 caplen; bpf_u_int32 len; } pkthdr; // Pkthdr_Type static void pcap_dealloc(register pkthdr* pp) { PyObject_Del(pp); } // pcap methods static PyObject* p_getts(register pkthdr* pp, PyObject* args); static PyObject* p_getcaplen(register pkthdr* pp, PyObject* args); static PyObject* p_getlen(register pkthdr* pp, PyObject* args); static PyMethodDef p_methods[] = { {"getts", (PyCFunction) p_getts, METH_VARARGS, "get timestamp tuple (seconds, microseconds) since the Epoch"}, {"getcaplen", (PyCFunction) p_getcaplen, METH_VARARGS, "returns the length of portion present"}, {"getlen", (PyCFunction) p_getlen, METH_VARARGS, "returns the length of the packet (off wire)"}, {NULL, NULL} /* sentinel */ }; static PyObject* pcap_getattr(pkthdr* pp, char* name) { return Py_FindMethod(p_methods, (PyObject*)pp, name); } PyTypeObject Pkthdr_type = { PyObject_HEAD_INIT(NULL) 0, "Pkthdr", sizeof(pkthdr), 0, /* methods */ (destructor)pcap_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)pcap_getattr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ }; PyObject* new_pcap_pkthdr(const struct pcap_pkthdr* hdr) { pkthdr *pp; pp = PyObject_New(pkthdr, &Pkthdr_type); if (pp == NULL) return NULL; pp->ts = hdr->ts; pp->caplen = hdr->caplen; pp->len = hdr->len; return (PyObject*)pp; } static PyObject* p_getts(register pkthdr* pp, PyObject* args) { if (pp->ob_type != &Pkthdr_type) { PyErr_SetString(PcapError, "Not a pkthdr object"); return NULL; } return Py_BuildValue("(ll)", pp->ts.tv_sec, pp->ts.tv_usec); } static PyObject* p_getcaplen(register pkthdr* pp, PyObject* args) { if (pp->ob_type != &Pkthdr_type) { PyErr_SetString(PcapError, "Not a pkthdr object"); return NULL; } return Py_BuildValue("l", pp->caplen); } static PyObject* p_getlen(register pkthdr* pp, PyObject* args) { if (pp->ob_type != &Pkthdr_type) { PyErr_SetString(PcapError, "Not a pkthdr object"); return NULL; } return Py_BuildValue("l", pp->len); } int pkthdr_to_native(PyObject *pyhdr, struct pcap_pkthdr *hdr) { if (pyhdr->ob_type != &Pkthdr_type) { PyErr_SetString(PcapError, "Not a pkthdr object"); return -1; } pkthdr *pp = (pkthdr *) pyhdr; hdr->ts = pp->ts; hdr->caplen = pp->caplen; hdr->len = pp->len; return 0; } pcapy-0.10.8/pcap_pkthdr.h0000666000000000000000000000106110602472250015322 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * $Id: pcap_pkthdr.h,v 1.2 2003/10/23 20:00:53 jkohen Exp $ */ #ifndef __pcap_pkthdr__ #define __pcap_pkthdr__ #include PyObject* new_pcap_pkthdr(const struct pcap_pkthdr* hdr); int pkthdr_to_native(PyObject *pyhdr, struct pcap_pkthdr *hdr); extern PyTypeObject Pkthdr_type; #endif // __pcap_pkthdr__ pcapy-0.10.8/PKG-INFO0000666000000000000000000000042411435267005013756 0ustar rootroot00000000000000Metadata-Version: 1.0 Name: pcapy Version: 0.10.8 Summary: Python pcap extension Home-page: http://oss.coresecurity.com/projects/pcapy.html Author: Core Security Technologies Author-email: oss@coresecurity.com License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN pcapy-0.10.8/README0000666000000000000000000000520311077456503013546 0ustar rootroot00000000000000This file is an extract from the the online documentation at http://oss.coresecurity.com/pcapy/. What is Pcapy? ============== Pcapy is a Python extension module that enables software written in Python to access the routines from the pcap packet capture library. From libpcap's documentation: "Libpcap is a system-independent interface for user-level packet capture. Libpcap provides a portable framework for low-level network monitoring. Applications include network statistics collection, security monitoring, network debugging, etc." What makes pcapy different from the others? ------------------------------------------- * works with Python threads. * works both in UNIX with libpcap and Windows with WinPcap. * provides a simpler Object Oriented API. Getting Pcapy ============= Current and past releases are available from http://oss.coresecurity.com/pcapy/. Setup ===== Quick start ----------- Grab the latest stable release, unpack it and run 'python setup.py install' from the directory where you placed it. Isn't that easy? Requirements ------------ * A Python interpreter. Versions 2.1.3 and newer are known to work. * A C++ compiler. GCC G++ 2.95, as well as Microsoft Visual Studio 6.0, are known to work. * Libpcap 0.7.2 or newer. Windows user are best to check WinPcap 3.0 or newer. * A recent release of Pcapy. Compiling the source and installing ----------------------------------- As this extension is written in C++ it needs to be compiled for the host system before it can be accessed from Python. Fortunately this process has been made easy by the setup.py script. In order to compile and install the source execute the following command from the directory where the pcapy's distribution has been unpacked: 'python setup.py install'. This will install the extension into the default Python's modules path; note that you might need special permissions to write there. For more information on what commands and options are available from setup.py, run 'python setup.py --help-commands'. This extension has been tested under Linux and Windows 2000 systems and is known to work there, but it ought to work out-of-the-box on any system where Python and libpcap are available. Licensing ========= This software is provided under under a slightly modified version of the Apache Software License. See the accompanying LICENSE file for more information. Contact Us ========== Whether you want to report a bug, send a patch or give some suggestions on this package, drop us a few lines at oss@coresecurity.com. $Id: README 31 2003-10-27 17:45:51Z jkohen $ pcapy-0.10.8/setup.py0000666000000000000000000000410411435266267014403 0ustar rootroot00000000000000# $Id: setup.py 47 2010-08-25 19:07:28Z aweil $ import sys, os from distutils.core import setup, Extension import distutils.ccompiler import distutils.errors PACKAGE_NAME = 'pcapy' # You might want to change these to reflect your specific configuration include_dirs = [] library_dirs = [] libraries = [] if sys.platform =='win32': # WinPcap include files include_dirs.append(r'c:\devel\oss\wpdpack\Include') # WinPcap library files library_dirs.append(r'c:\devel\oss\wpdpack\Lib') libraries = ['wpcap', 'packet', 'ws2_32'] else: libraries = ['pcap'] # end of user configurable parameters macros = [] sources = ['pcapdumper.cc', 'bpfobj.cc', 'pcapy.cc', 'pcapobj.cc', 'pcap_pkthdr.cc', ] if sys.platform == 'win32': sources.append(os.path.join('win32', 'dllmain.cc')) macros.append(('WIN32', '1')) # HACK replace linker gcc with g++ from distutils import sysconfig save_init_posix = sysconfig._init_posix def my_init_posix(): save_init_posix() g = sysconfig._config_vars if g['LDSHARED'][:3]=='gcc': print 'my_init_posix: changing LDSHARED =',`g['LDSHARED']`, g['LDSHARED'] = 'g++'+g['LDSHARED'][3:] print 'to',`g['LDSHARED']` sysconfig._init_posix = my_init_posix setup(name = PACKAGE_NAME, version = "0.10.8", url = "http://oss.coresecurity.com/projects/pcapy.html", author = "Maximiliano Caceres", author_email = "oss@coresecurity.com", maintainer = "Core Security Technologies", maintainer_email = "oss@coresecurity.com", description = "Python pcap extension", ext_modules = [Extension( name = PACKAGE_NAME, sources = sources, define_macros = macros, include_dirs = include_dirs, library_dirs = library_dirs, libraries = libraries)], scripts = ['tests/pcapytests.py', 'tests/96pings.pcap'], data_files = [(os.path.join('share', 'doc', PACKAGE_NAME), ['README', 'LICENSE', 'pcapy.html'])], ) pcapy-0.10.8/tests/0000777000000000000000000000000011435267005014023 5ustar rootroot00000000000000pcapy-0.10.8/tests/96pings.pcap0000666000000000000000000002503011077513165016172 0ustar rootroot00000000000000`Hcؾ`b$+]ET@eQHcT  !"#$%&'()*+,-./012345Hd`b$+]ET@ePHd~  !"#$%&'()*+,-./012345He`b$+]ET@eKHeq  !"#$%&'()*+,-./012345Hf`b$+]ET@eEHf]  !"#$%&'()*+,-./012345Hg`b$+]ET@eDHgy  !"#$%&'()*+,-./012345Hh`b$+]ET@eCHh  !"#$%&'()*+,-./012345Hi`b$+]ET@eBxHi  !"#$%&'()*+,-./012345Hjq`b$+]ET@eTHj  !"#$%&'()*+,-./012345Hkܦ`b$+]ET@eMHkE  !"#$%&'()*+,-./012345Hlݳ`b$+]ET@eL HlT  !"#$%&'()*+,-./012345Hm޻`b$+]ET@eK Hm\  !"#$%&'()*+,-./012345Hn`b$+]ET4@eI Hn|  !"#$%&'()*+,-./012345Ho`b$+]ETW@eHe Ho  !"#$%&'()*+,-./012345Hp`b$+]ET\@eG^ Hp  !"#$%&'()*+,-./012345Hq `b$+]ET]@eFSHq  !"#$%&'()*+,-./012345Hr`b$+]ET^@eDbHr  !"#$%&'()*+,-./012345Hsz`b$+]ET`@eBHs  !"#$%&'()*+,-./012345Ht`b$+]ETb@eAHt(  !"#$%&'()*+,-./012345Hu`b$+]ETc@e@Hu-  !"#$%&'()*+,-./012345Hv`b$+]ETe@e?Hv5  !"#$%&'()*+,-./012345Hw{`b$+]ETf@esHw{{  !"#$%&'()*+,-./012345Hx|`b$+]ETg@elHx|  !"#$%&'()*+,-./012345Hy~`b$+]ETi@eDHy}  !"#$%&'()*+,-./012345Hz~`b$+]ETl@eHz~a  !"#$%&'()*+,-./012345H{`b$+]ETm@eH{[  !"#$%&'()*+,-./012345H| `b$+]ETs@e$H|  !"#$%&'()*+,-./012345H}?`b$+]ETw@{exH}T  !"#$%&'()*+,-./012345H~`b$+]ETx@ze4eH~z  !"#$%&'()*+,-./012345H>`b$+]ETy@ye.H  !"#$%&'()*+,-./012345H`b$+]ETz@xe'2H  !"#$%&'()*+,-./012345H `b$+]ET@se H   !"#$%&'()*+,-./012345H `b$+]ET@qe4H   !"#$%&'()*+,-./012345H`b$+]ET@pe H  !"#$%&'()*+,-./012345H#`b$+]ET@oe!H  !"#$%&'()*+,-./012345HR`b$+]ET@le"H  !"#$%&'()*+,-./012345HO`b$+]ET@ke#H  !"#$%&'()*+,-./012345HV`b$+]ET@je$H  !"#$%&'()*+,-./012345HV`b$+]ET@ge%H  !"#$%&'()*+,-./012345HY`b$+]ET@ee&H  !"#$%&'()*+,-./012345HX`b$+]ET@ce'H  !"#$%&'()*+,-./012345Hd`b$+]ET@be(H  !"#$%&'()*+,-./012345Hg`b$+]ET@_e)H   !"#$%&'()*+,-./012345H_`b$+]ET@\e*H  !"#$%&'()*+,-./012345H[`b$+]ET@Te)+H[  !"#$%&'()*+,-./012345H]`b$+]ET@SeJ,H]r  !"#$%&'()*+,-./012345Hp`b$+]ET@Qei-HpQ  !"#$%&'()*+,-./012345Hq`b$+]ET@OeW.Hqa  !"#$%&'()*+,-./012345Hr`b$+]ET@Ne[/Hr[  !"#$%&'()*+,-./012345Hs`b$+]ET@LeN0Hsf  !"#$%&'()*+,-./012345Ht`b$+]ET@KeA1Htq  !"#$%&'()*+,-./012345H~`b$+]ET@Dey2H~7  !"#$%&'()*+,-./012345HB`b$+]ET@@e3H  !"#$%&'()*+,-./012345Hi`b$+]ET@1e4H  !"#$%&'()*+,-./012345H`b$+]ET@)e5H  !"#$%&'()*+,-./012345H`b$+]ET@ e6H  !"#$%&'()*+,-./012345H`b$+]ET@e7H  !"#$%&'()*+,-./012345H:`b$+]ET @e8H  !"#$%&'()*+,-./012345HL`b$+]ET/@e}9H  !"#$%&'()*+,-./012345Hd`b$+]ET<@e|:H  !"#$%&'()*+,-./012345H`b$+]ET>@ek;H  !"#$%&'()*+,-./012345H"`b$+]ETB@ejHW  !"#$%&'()*+,-./012345HY`b$+]ETZ@e<?HYX  !"#$%&'()*+,-./012345H[d`b$+]ETm@eΌ@H[  !"#$%&'()*+,-./012345H\h`b$+]ETn@e͉AH\  !"#$%&'()*+,-./012345Ha`b$+]ETo@e0BHa^  !"#$%&'()*+,-./012345Hb`b$+]ETy@ye#CHbi  !"#$%&'()*+,-./012345He`b$+]ET@feDHez  !"#$%&'()*+,-./012345Hf`b$+]ET@YeEHf  !"#$%&'()*+,-./012345Ho`b$+]ET@Be<FHoJ  !"#$%&'()*+,-./012345Hp`b$+]ET@7eGHpo  !"#$%&'()*+,-./012345Hq`b$+]ET@1eHHq  !"#$%&'()*+,-./012345Hr`b$+]ET@,eIHrx  !"#$%&'()*+,-./012345Ht`b$+]ET@+eJHta  !"#$%&'()*+,-./012345Hw`b$+]ET@"eKHw  !"#$%&'()*+,-./012345HyQ`b$+]ET@eLHx  !"#$%&'()*+,-./012345H]`b$+]ET@e|MH  !"#$%&'()*+,-./012345H`b$+]ET@ eMNH)  !"#$%&'()*+,-./012345H`b$+]ET@e2OHB  !"#$%&'()*+,-./012345H5`b$+]ET@ePH  !"#$%&'()*+,-./012345H\`b$+]ET@evQH  !"#$%&'()*+,-./012345Hk`b$+]ET@egRH  !"#$%&'()*+,-./012345H`b$+]ET@eSH  !"#$%&'()*+,-./012345H<`b$+]ET@eTH  !"#$%&'()*+,-./012345HI`b$+]ET @eUH  !"#$%&'()*+,-./012345HK`b$+]ET@eyVH  !"#$%&'()*+,-./012345H`b$+]ET@eWH  !"#$%&'()*+,-./012345H`b$+]ET!@eXH  !"#$%&'()*+,-./012345H6`b$+]ET.@eYH  !"#$%&'()*+,-./012345HU`b$+]ET8@emZH  !"#$%&'()*+,-./012345H``b$+]ET:@eZ[H  !"#$%&'()*+,-./012345H^`b$+]ET=@e\\H  !"#$%&'()*+,-./012345Hk`b$+]ET?@ex"]H6  !"#$%&'()*+,-./012345HD`b$+]ETB@ewr^H  !"#$%&'()*+,-./012345H>`b$+]ETC@evs_H  !"#$%&'()*+,-./012345pcapy-0.10.8/tests/pcapytests.py0000666000000000000000000000301111136153240016560 0ustar rootroot00000000000000## Copyright (c) 2003 CORE Security Technologies ## ## This software is provided under under a slightly modified version ## of the Apache Software License. See the accompanying LICENSE file ## for more information. ## ## $Id: test.py 21 2003-10-23 20:00:54Z jkohen $ import pcapy import sys import unittest class TestPcapy(unittest.TestCase): _96PINGS = '96pings.pcap' def testPacketHeaderRefCount(self): """#1:when next() creates a pkthdr it make one extra reference""" class _Simple: pass #r = pcapy.open_live("en1", 65000, 0, 1000) r = pcapy.open_offline(TestPcapy._96PINGS) #get one & check its refcount self.assertEqual( sys.getrefcount(r.next()[0]), sys.getrefcount(_Simple()) ) def testEOFValue(self): """#1:when next() creates a pkthdr it make one extra reference""" class _Simple: pass #r = pcapy.open_live("en1", 65000, 0, 1000) r = pcapy.open_offline(TestPcapy._96PINGS) #get one & check its refcount i=0 refNone = sys.getrefcount(None) s = r.next() while not s[0] is None: s = r.next() i+=1 self.assertEqual( 96, i ) self.assertEqual( s[0], None ) self.assertEqual( s[1], '' ) del s self.assertEqual( refNone, sys.getrefcount(None) ) suite = unittest.TestLoader().loadTestsFromTestCase(TestPcapy) suite = unittest.TestLoader().loadTestsFromTestCase(TestPcapy) unittest.TextTestRunner(verbosity=2).run(suite) pcapy-0.10.8/win32/0000777000000000000000000000000011435267005013623 5ustar rootroot00000000000000pcapy-0.10.8/win32/dllmain.cc0000666000000000000000000000125011077456503015555 0ustar rootroot00000000000000/* * Copyright (c) 2003 CORE Security Technologies * * This software is provided under under a slightly modified version * of the Apache Software License. See the accompanying LICENSE file * for more information. * * Win32 DLL entry point. * * $Id: dllmain.cc 21 2003-10-23 20:00:54Z jkohen $ */ #include BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }