pax_global_header00006660000000000000000000000064135067401000014506gustar00rootroot0000000000000052 comment=0c582095b35a2849dfbffba11cf530a7ea875a86 pcapy-0.11.5/000077500000000000000000000000001350674010000127065ustar00rootroot00000000000000pcapy-0.11.5/.gitignore000066400000000000000000000000561350674010000146770ustar00rootroot00000000000000*.py[co] *.so *.pyd *.egg-info /build/ /dist/ pcapy-0.11.5/ChangeLog000066400000000000000000000050511350674010000144610ustar00rootroot000000000000002018-06-17 Alberto Solino * Version 0.11.4 tagged with the following changes * bpfobject support get_bpf method (by @palaviv) * Monitor mode support & missing methods fix (by @gpotter2) * Documentation update (@gpotter2) 2018-03-26 Alberto Solino * Version 0.11.2 tagged with the following substantial changes (since version 0.11.11): * Exporting pcap_get_selectable_fd as getfd (by @geekhckr) * Add a close method & context manager to Reader (by @segevfiner) 2017-01-16 Martin Balao * Version 0.11.1 tagged with the following changes (since version 0.10.10): * AppVeyor integration (continuous integration service) * @takluyver contribution * Close method for Pcap Dumper * @JinBlack contribution * Pcap stats added * @duggan contribution 2015-05-19 Andres Blanco * Added sendpacket support by default 2010-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.11.5/LICENSE000066400000000000000000000050471350674010000137210ustar00rootroot00000000000000Licencing --------- 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 (https://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.11.5/MANIFEST.in000066400000000000000000000002041350674010000144400ustar00rootroot00000000000000include MANIFEST.in include LICENSE include ChangeLog include pcapy.xml include pcapy.html include *.h recursive-include win32 *.cc pcapy-0.11.5/README000066400000000000000000000051011350674010000135630ustar00rootroot00000000000000This file is an extract from the the online documentation at https://www.coresecurity.com/corelabs-research/open-source-tools/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 https://www.coresecurity.com/corelabs-research/open-source-tools/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 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. pcapy-0.11.5/README.md000066400000000000000000000052051350674010000141670ustar00rootroot00000000000000## What is Pcapy? ## [![Build status](https://ci.appveyor.com/api/projects/status/pi4bqe4kgubgr37x?svg=true)](https://ci.appveyor.com/project/CoreSecurity/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 https://github.com/CoreSecurity/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? ### [Documentation](https://rawgit.com/CoreSecurity/pcapy/master/pcapy.html) ### ### 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 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. For windows please refer to this [link] (https://github.com/CoreSecurity/pcapy/wiki/Compiling-Pcapy-on-Windows). ## 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`. pcapy-0.11.5/appveyor.yml000066400000000000000000000032711350674010000153010ustar00rootroot00000000000000environment: global: # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the # /E:ON and /V:ON options are not enabled in the batch script intepreter # See: http://stackoverflow.com/a/13751649/163740 WITH_COMPILER: "cmd /E:ON /V:ON /C .\\appveyor\\run_with_compiler.cmd" DISTRIBUTIONS: "bdist_wheel" matrix: - PYTHON: "C:\\Python27" PYTHON_VERSION: "2.7.11" PYTHON_ARCH: "32" - PYTHON: "C:\\Python34" PYTHON_VERSION: "3.4.3" PYTHON_ARCH: "32" - PYTHON: "C:\\Python35" PYTHON_VERSION: "3.5.0" PYTHON_ARCH: "32" - PYTHON: "C:\\Python27-x64" PYTHON_VERSION: "2.7.11" PYTHON_ARCH: "64" - PYTHON: "C:\\Python34-x64" PYTHON_VERSION: "3.4.3" PYTHON_ARCH: "64" - PYTHON: "C:\\Python35-x64" PYTHON_VERSION: "3.5.0" PYTHON_ARCH: "64" init: - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%" install: - cinst winpcap - "powershell appveyor\\install.ps1" - "set HOME=%APPVEYOR_BUILD_FOLDER%" - "set WPDPACK_BASE=%APPVEYOR_BUILD_FOLDER%\\WpdPack" - "%PYTHON%/python -m pip install -U pip" # Upgrade pip - "%WITH_COMPILER% %PYTHON%/python setup.py build" - "%WITH_COMPILER% %PYTHON%/python setup.py %DISTRIBUTIONS%" - ps: "ls dist" # Install the wheel to test it - "%PYTHON%/python -m pip install --ignore-installed --pre --no-index --find-links dist/ pcapy" # Appveyor's build step is specific to .NET projects, so we build in the # install step instead. build: off test_script: - "cd tests" - "%PYTHON%/python pcapytests.py" # Move back to the project folder - "cd .." artifacts: - path: dist\* pcapy-0.11.5/appveyor/000077500000000000000000000000001350674010000145535ustar00rootroot00000000000000pcapy-0.11.5/appveyor/install.ps1000066400000000000000000000020601350674010000166440ustar00rootroot00000000000000function InstallPackage ($python_home, $pkg) { $pip_path = $python_home + "/Scripts/pip.exe" & $pip_path install $pkg } function DownloadWinpcapDev () { $webclient = New-Object System.Net.WebClient $download_url = "https://www.winpcap.org/install/bin/WpdPack_4_1_2.zip" $filename = "WpdPack_4_1_2.zip" $basedir = $pwd.Path + "\" $filepath = $basedir + $filename if (Test-Path $filepath) { Write-Host "Reusing" $filepath return $filepath } # Download and retry up to 5 times in case of network transient errors. Write-Host "Downloading" $filename "from" $download_url $retry_attempts = 3 for($i=0; $i -lt $retry_attempts; $i++){ try { $webclient.DownloadFile($download_url, $filepath) break } Catch [Exception]{ Start-Sleep 1 } } Write-Host "File saved at" $filepath & 7z x $filename } function main () { InstallPackage $env:PYTHON wheel & DownloadWinpcapDev } main pcapy-0.11.5/appveyor/run_with_compiler.cmd000066400000000000000000000065761350674010000210070ustar00rootroot00000000000000:: To build extensions for 64 bit Python 3, we need to configure environment :: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of: :: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1) :: :: To build extensions for 64 bit Python 2, we need to configure environment :: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of: :: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0) :: :: 32 bit builds, and 64-bit builds for 3.5 and beyond, do not require specific :: environment configurations. :: :: Note: this script needs to be run with the /E:ON and /V:ON flags for the :: cmd interpreter, at least for (SDK v7.0) :: :: More details at: :: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows :: http://stackoverflow.com/a/13751649/163740 :: :: Author: Olivier Grisel :: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/ :: :: Notes about batch files for Python people: :: :: Quotes in values are literally part of the values: :: SET FOO="bar" :: FOO is now five characters long: " b a r " :: If you don't want quotes, don't include them on the right-hand side. :: :: The CALL lines at the end of this file look redundant, but if you move them :: outside of the IF clauses, they do not run properly in the SET_SDK_64==Y :: case, I don't know why. @ECHO OFF SET COMMAND_TO_RUN=%* SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows SET WIN_WDK=c:\Program Files (x86)\Windows Kits\10\Include\wdf :: Extract the major and minor versions, and allow for the minor version to be :: more than 9. This requires the version number to have two dots in it. SET MAJOR_PYTHON_VERSION=%PYTHON_VERSION:~0,1% IF "%PYTHON_VERSION:~3,1%" == "." ( SET MINOR_PYTHON_VERSION=%PYTHON_VERSION:~2,1% ) ELSE ( SET MINOR_PYTHON_VERSION=%PYTHON_VERSION:~2,2% ) :: Based on the Python version, determine what SDK version to use, and whether :: to set the SDK for 64-bit. IF %MAJOR_PYTHON_VERSION% == 2 ( SET WINDOWS_SDK_VERSION="v7.0" SET SET_SDK_64=Y ) ELSE ( IF %MAJOR_PYTHON_VERSION% == 3 ( SET WINDOWS_SDK_VERSION="v7.1" IF %MINOR_PYTHON_VERSION% LEQ 4 ( SET SET_SDK_64=Y ) ELSE ( SET SET_SDK_64=N IF EXIST "%WIN_WDK%" ( :: See: https://connect.microsoft.com/VisualStudio/feedback/details/1610302/ REN "%WIN_WDK%" 0wdf ) ) ) ELSE ( ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%" EXIT 1 ) ) IF %PYTHON_ARCH% == 64 ( IF %SET_SDK_64% == Y ( ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture SET DISTUTILS_USE_SDK=1 SET MSSdk=1 "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION% "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release ECHO Executing: %COMMAND_TO_RUN% call %COMMAND_TO_RUN% || EXIT 1 ) ELSE ( ECHO Using default MSVC build environment for 64 bit architecture ECHO Executing: %COMMAND_TO_RUN% call %COMMAND_TO_RUN% || EXIT 1 ) ) ELSE ( ECHO Using default MSVC build environment for 32 bit architecture ECHO Executing: %COMMAND_TO_RUN% call %COMMAND_TO_RUN% || EXIT 1 ) pcapy-0.11.5/bpfobj.cc000066400000000000000000000162671350674010000144730ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #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); } PyObject* BPFError; // BPFProgram methods static PyObject* p_filter(register bpfobject* bpf, PyObject* args); static PyObject* p_get_bpf(register bpfobject* bpf, PyObject* args); static PyObject* p_new_bpfobject(PyTypeObject *type, PyObject* args, PyObject *kwags); 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"}, {"get_bpf", (PyCFunction) p_get_bpf, METH_NOARGS, "return packet-matching code as decimal numbers"}, {NULL, NULL} /* sentinel */ }; static PyObject* bpfprog_getattr(bpfobject* pp, char* name) { #if PY_MAJOR_VERSION >= 3 PyObject *nameobj = PyUnicode_FromString(name); PyObject *attr = PyObject_GenericGetAttr((PyObject *)pp, nameobj); Py_DECREF(nameobj); return attr; #else return Py_FindMethod(bpf_methods, (PyObject*)pp, name); #endif } PyTypeObject BPFProgramType = { #if PY_MAJOR_VERSION >= 3 PyVarObject_HEAD_INIT(&PyType_Type, 0) "BPFProgram", /* tp_name */ sizeof(bpfobject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)bpfprog_dealloc, /* tp_dealloc */ 0, /* tp_print */ (getattrfunc)bpfprog_getattr, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "BPF Program Wrapper", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ bpf_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ p_new_bpfobject /* tp_new */ #else PyObject_HEAD_INIT(NULL) 0, "BPFProgram", 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*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "BPF Program Wrapper", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ bpf_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ p_new_bpfobject /* tp_new */ #endif }; PyObject* new_bpfobject(const struct bpf_program &bpfprog) { if (PyType_Ready(&BPFProgramType) < 0) return NULL; bpfobject *bpf; bpf = PyObject_New(bpfobject, &BPFProgramType); if (bpf == NULL) { PyErr_SetString(BPFError, "Failed to create object"); return NULL; } bpf->bpf = bpfprog; return (PyObject*)bpf; } static PyObject* p_new_bpfobject(PyTypeObject *type, PyObject *args, PyObject *kwds) { char *filter_string; int linktype = 1; // DLT_EN10MB if (!PyArg_ParseTuple(args, "s|i", &filter_string, &linktype)){ return NULL; } struct bpf_program bpfprog; if (pcap_compile_nopcap((1<<16), linktype, &bpfprog, filter_string, 0, 0)){ PyErr_SetString(BPFError, "Couldn't compile BPF program"); return NULL; } return new_bpfobject(bpfprog); } static PyObject* p_filter(register bpfobject* bpf, PyObject* args) { int status; u_char* packet; unsigned int len; if (Py_TYPE(bpf) != &BPFProgramType) { PyErr_SetString(BPFError, "Not a bpfprogram object"); return NULL; } #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTuple(args,"y#:filter",&packet, &len)){ return NULL; } #else if (!PyArg_ParseTuple(args,"s#:filter",&packet, &len)){ return NULL; } #endif status = bpf_filter(bpf->bpf.bf_insns, packet, len, len); return Py_BuildValue("i", status); } static PyObject* p_get_bpf(register bpfobject* bpf, PyObject* args) { struct bpf_insn *insn; int i; int n = bpf->bpf.bf_len; PyObject* list; PyObject* instruction; insn = bpf->bpf.bf_insns; if (Py_TYPE(bpf) != &BPFProgramType) { PyErr_SetString(BPFError, "Not a bpfprogram object"); return NULL; } list = PyList_New(n); if (!list) { return NULL; } for (i = 0; i < n; ++insn, ++i) { instruction = Py_BuildValue("IIII", insn->code, insn->jt, insn->jf, insn->k); if (!instruction) { Py_DECREF(list); return NULL; } PyList_SET_ITEM(list, i, instruction); } return list; } pcapy-0.11.5/bpfobj.h000066400000000000000000000006671350674010000143320ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #ifndef __bpfobj__ #define __bpfobj__ PyObject* new_bpfobject(const struct bpf_program &bpf); extern PyObject* BPFError; extern PyTypeObject BPFProgramType; extern PyTypeObject Pcaptype; #endif // __bpfobj__ pcapy-0.11.5/pcap_pkthdr.cc000066400000000000000000000120231350674010000155120ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #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) { #if PY_MAJOR_VERSION >= 3 PyObject *nameobj = PyUnicode_FromString(name); PyObject *attr = PyObject_GenericGetAttr((PyObject *)pp, nameobj); Py_DECREF(nameobj); return attr; #else return Py_FindMethod(p_methods, (PyObject*)pp, name); #endif } PyTypeObject Pkthdr_type = { #if PY_MAJOR_VERSION >= 3 PyVarObject_HEAD_INIT(&PyType_Type, 0) "Pkthdr", /* tp_name */ sizeof(pkthdr), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)pcap_dealloc, /* tp_dealloc */ 0, /* tp_print */ (getattrfunc)pcap_getattr, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ NULL, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ p_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ #else 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*/ #endif }; PyObject* new_pcap_pkthdr(const struct pcap_pkthdr* hdr) { if (PyType_Ready(&Pkthdr_type) < 0) return NULL; 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 (Py_TYPE(pp) != &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 (Py_TYPE(pp) != &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 (Py_TYPE(pp) != &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 (Py_TYPE(pyhdr) != &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; } /* vim: set tabstop=2 shiftwidth=2 expandtab: */ pcapy-0.11.5/pcap_pkthdr.h000066400000000000000000000007351350674010000153630ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #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.11.5/pcapdumper.cc000066400000000000000000000117741350674010000153670ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #include #include #include "pcapdumper.h" #include "pcap_pkthdr.h" #include "pcapy.h" // internal pcapdumper typedef struct { PyObject_HEAD pcap_dumper_t *dumper; } pcapdumper; static bool validate_pcapdumper(register const pcapdumper* pp); // 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) { #if PY_MAJOR_VERSION >= 3 PyObject *nameobj = PyUnicode_FromString(name); PyObject *attr = PyObject_GenericGetAttr((PyObject *)pp, nameobj); Py_DECREF(nameobj); return attr; #else return Py_FindMethod(p_methods, (PyObject*)pp, name); #endif } PyTypeObject Pdumpertype = { #if PY_MAJOR_VERSION >= 3 PyVarObject_HEAD_INIT(&PyType_Type, 0) "Dumper", /* tp_name */ sizeof(pcapdumper), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)pcap_dealloc, /* tp_dealloc */ 0, /* tp_print */ (getattrfunc)pcap_getattr, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ NULL, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ p_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ #else 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 */ #endif }; PyObject* new_pcapdumper(pcap_dumper_t *dumper) { if (PyType_Ready(&Pdumpertype) < 0) return NULL; 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(validate_pcapdumper(pp) == false){ return NULL; } #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTuple(args,"Oy#",&pyhdr,&data,&len)){ return NULL; } #else if (!PyArg_ParseTuple(args,"Os#",&pyhdr,&data,&len)){ return NULL; } #endif struct pcap_pkthdr hdr; if (-1 == pkthdr_to_native(pyhdr, &hdr)) return NULL; if (pp->dumper == NULL){ PyErr_SetString(PcapError, "Dumper is already closed."); return NULL; } pcap_dump((u_char *)pp->dumper, &hdr, data); Py_INCREF(Py_None); return Py_None; } // PdumperClose static PyObject* p_close(register pcapdumper* pp, PyObject* args) { if(validate_pcapdumper(pp) == false){ return NULL; } if ( pp->dumper ) pcap_dump_close(pp->dumper); pp->dumper = NULL; Py_INCREF(Py_None); return Py_None; } static bool validate_pcapdumper(register const pcapdumper* pp){ if (pp == NULL || Py_TYPE(pp) != &Pdumpertype) { PyErr_SetString(PcapError, "Not a pcapdumper object"); return false; } return true; } pcapy-0.11.5/pcapdumper.h000066400000000000000000000005771350674010000152300ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #ifndef __pcapdumper__ #define __pcapdumper__ PyObject* new_pcapdumper(pcap_dumper_t *dumper); extern PyTypeObject Pdumpertype; #endif // __pcapdumper__ pcapy-0.11.5/pcapobj.cc000066400000000000000000000475401350674010000146450ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #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 PyObject* p_close(register pcapobject* pp, PyObject*) { if ( pp->pcap ) pcap_close(pp->pcap); pp->pcap = NULL; Py_RETURN_NONE; } static void pcap_dealloc(register pcapobject* pp) { p_close(pp, NULL); PyObject_Del(pp); } static PyObject * err_closed(void) { PyErr_SetString(PyExc_ValueError, "pcap is closed"); return NULL; } // 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_setdirection(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); static PyObject* p_sendpacket(register pcapobject* pp, PyObject* args); static PyObject* p_stats( register pcapobject* pp, PyObject*); static PyObject* p__enter__( register pcapobject* pp, PyObject*); static PyObject* p_getfd(register pcapobject* pp, PyObject* args); static PyObject* p_set_snaplen(register pcapobject* pp, PyObject* args); static PyObject* p_set_promisc(register pcapobject* pp, PyObject* args); static PyObject* p_set_timeout(register pcapobject* pp, PyObject* args); static PyObject* p_set_buffer_size(register pcapobject* pp, PyObject* args); static PyObject* p_set_rfmon(register pcapobject* pp, PyObject* args); static PyObject* p_activate(register pcapobject* pp, PyObject* args); 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"}, {"setdirection", (PyCFunction) p_setdirection, METH_VARARGS, "set the direction for which packets will be captured"}, {"dump_open", (PyCFunction) p_dump_open, METH_VARARGS, "creates a dumper object"}, {"sendpacket", (PyCFunction) p_sendpacket, METH_VARARGS, "sends a packet through the interface"}, {"stats", (PyCFunction) p_stats, METH_NOARGS, "returns capture statistics"}, {"close", (PyCFunction) p_close, METH_NOARGS, "close the capture"}, {"set_snaplen", (PyCFunction)p_set_snaplen, METH_VARARGS, "set the snapshot length for a not-yet-activated capture handle"}, {"set_promisc", (PyCFunction)p_set_promisc, METH_VARARGS, "set promiscuous mode for a not-yet-activated capture handle"}, {"set_timeout", (PyCFunction)p_set_timeout, METH_VARARGS, "set the read timeout for a not-yet-activated capture handle"}, {"set_buffer_size", (PyCFunction)p_set_buffer_size, METH_VARARGS, "set the buffer size for a not-yet-activated capture handle"}, {"activate", (PyCFunction)p_activate, METH_NOARGS, "activate a capture handle created using create()"}, {"__enter__", (PyCFunction) p__enter__, METH_NOARGS, NULL}, {"__exit__", (PyCFunction) p_close, METH_VARARGS, NULL}, #ifndef WIN32 {"getfd", (PyCFunction) p_getfd, METH_VARARGS, "get selectable pcap fd"}, {"set_rfmon", (PyCFunction)p_set_rfmon, METH_VARARGS, "set monitor mode for a not-yet-activated capture handle"}, /* Available on Npcap, not on Winpcap. */ #endif {NULL, NULL} /* sentinel */ }; static PyObject* pcap_getattr(pcapobject* pp, char* name) { #if PY_MAJOR_VERSION >= 3 PyObject *nameobj = PyUnicode_FromString(name); PyObject *attr = PyObject_GenericGetAttr((PyObject *)pp, nameobj); Py_DECREF(nameobj); return attr; #else return Py_FindMethod(p_methods, (PyObject*)pp, name); #endif } PyTypeObject Pcaptype = { #if PY_MAJOR_VERSION >= 3 PyVarObject_HEAD_INIT(&PyType_Type, 0) "Reader", /* tp_name */ sizeof(pcapobject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)pcap_dealloc, /* tp_dealloc */ 0, /* tp_print */ (getattrfunc)pcap_getattr, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ NULL, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ p_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ #else 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*/ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ NULL, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ p_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ #endif }; PyObject* new_pcapobject(pcap_t *pcap, bpf_u_int32 net, bpf_u_int32 mask) { if (PyType_Ready(&Pcaptype) < 0) return NULL; 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 (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); 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 (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); 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 (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); 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 = NULL; const unsigned char *buf = (const unsigned char*)""; int err_code = 1; if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); // allow threads as this might block Py_BEGIN_ALLOW_THREADS; err_code = pcap_next_ex(pp->pcap, &hdr, &buf); Py_END_ALLOW_THREADS; if(err_code == -1) { PyErr_SetString(PcapError, pcap_geterr(pp->pcap)); return NULL; } PyObject *pkthdr; int _caplen = 0; if (err_code == 1) { pkthdr = new_pcap_pkthdr(hdr); _caplen = hdr->caplen; } else { pkthdr = Py_None; Py_INCREF(pkthdr); _caplen = 0; } if (pkthdr) { PyObject *ret = NULL; #if PY_MAJOR_VERSION >= 3 /* return bytes */ ret = Py_BuildValue("(Oy#)", pkthdr, buf, _caplen); #else ret = Py_BuildValue("(Os#)", pkthdr, buf, _caplen); #endif 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); #if PY_MAJOR_VERSION >= 3 /* pass bytes */ arglist = Py_BuildValue("Oy#", hdr, packetdata, *len); #else arglist = Py_BuildValue("Os#", hdr, packetdata, *len); #endif 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 (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); 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_stats(register pcapobject* pp, PyObject*) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); struct pcap_stat stats; if (-1 == pcap_stats(pp->pcap, &stats)) { PyErr_SetString(PcapError, pcap_geterr(pp->pcap)); return NULL; } return Py_BuildValue("III", stats.ps_recv, stats.ps_drop, stats.ps_ifdrop); } static PyObject* p__enter__( register pcapobject* pp, PyObject*) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); Py_INCREF(pp); return (PyObject*)pp; } static PyObject* p_dump_open(register pcapobject* pp, PyObject* args) { char *filename; pcap_dumper_t *ret; if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); 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 (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); 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 (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); int type = pcap_datalink(pp->pcap); return Py_BuildValue("i", type); } static PyObject* p_setdirection(register pcapobject* pp, PyObject* args) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); pcap_direction_t direction; if (!PyArg_ParseTuple(args, "i", &direction)) return NULL; int ret = pcap_setdirection(pp->pcap, direction); if (-1 == ret) { PyErr_SetString(PcapError, "Failed setting direction"); return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject* p_setnonblock(register pcapobject* pp, PyObject* args) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); 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 (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); 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); } static PyObject* p_set_snaplen(register pcapobject* pp, PyObject* args) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); int snaplen; if (!PyArg_ParseTuple(args, "i", &snaplen)) return NULL; int ret = pcap_set_snaplen(pp->pcap, snaplen); return Py_BuildValue("i", ret); } static PyObject* p_set_promisc(register pcapobject* pp, PyObject* args) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); int promisc; if (!PyArg_ParseTuple(args, "i", &promisc)) return NULL; int ret = pcap_set_promisc(pp->pcap, promisc); return Py_BuildValue("i", ret); } static PyObject* p_set_timeout(register pcapobject* pp, PyObject* args) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); int to_ms; if (!PyArg_ParseTuple(args, "i", &to_ms)) return NULL; int ret = pcap_set_timeout(pp->pcap, to_ms); return Py_BuildValue("i", ret); } static PyObject* p_set_buffer_size(register pcapobject* pp, PyObject* args) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); int buffer_size; if (!PyArg_ParseTuple(args, "i", &buffer_size)) return NULL; int ret = pcap_set_buffer_size(pp->pcap, buffer_size); return Py_BuildValue("i", ret); } static PyObject* p_set_rfmon(register pcapobject* pp, PyObject* args) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); int rfmon; if (!PyArg_ParseTuple(args, "i", &rfmon)) return NULL; int ret = pcap_set_rfmon(pp->pcap, rfmon); return Py_BuildValue("i", ret); } static PyObject* p_activate(register pcapobject* pp, PyObject*) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); int ret = pcap_activate(pp->pcap); return Py_BuildValue("i", ret); } static PyObject* p_sendpacket(register pcapobject* pp, PyObject* args) { int status; unsigned char* str; unsigned int length; if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); #if PY_MAJOR_VERSION >= 3 /* accept bytes */ if (!PyArg_ParseTuple(args,"y#", &str, &length)) { return NULL; } #else if (!PyArg_ParseTuple(args,"s#", &str, &length)) { return NULL; } #endif 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; } #ifndef WIN32 static PyObject* p_getfd(register pcapobject* pp, PyObject* args) { if (Py_TYPE(pp) != &Pcaptype) { PyErr_SetString(PcapError, "Not a pcap object"); return NULL; } if (!pp->pcap) return err_closed(); int fd = pcap_get_selectable_fd(pp->pcap); return Py_BuildValue("i", fd); } #endif pcapy-0.11.5/pcapobj.h000066400000000000000000000006211350674010000144740ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #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.11.5/pcapy.cc000066400000000000000000000346451350674010000143450ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #include #include #ifdef WIN32 #include // IPHelper API for luid/guid conversions #endif #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) { #ifdef WIN32 /* If we are on windows, then display LUID's like "Local Area Connection" * instead of GUID's like "\Device\NPF_{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}". */ char *luid = get_windows_interface_friendly_name(cursor->name); PyList_Append(list, Py_BuildValue("s", luid)); free(luid); #else PyList_Append(list, Py_BuildValue("s", cursor->name)); #endif 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; #ifdef WIN32 /* If we are on windows, then device is an LUID like "Local Area Connection". * pcap on Windows needs a GUID like "\Device\NPF_{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}". */ device = luid_to_guid(device); #endif 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); #ifdef WIN32 free(device); #endif if(!pt) { PyErr_SetString(PcapError, errbuff); return NULL; } #ifdef WIN32 //According to the doc // pcap_setmintocopy() changes the minimum amount of data in the kernel buffer that causes a read from the application to return (unless the timeout expires) // [...] pcap_open_live() sets a default mintocopy value of 16000 bytes. //It is a better practice to set it to 0, so that we are transparent about what we receive pcap_setmintocopy(pt, 0); #endif return new_pcapobject( pt, net, mask ); } static PyObject* pcap_create(PyObject *self, PyObject *args) { char errbuff[PCAP_ERRBUF_SIZE]; char * device; bpf_u_int32 net, mask; if (!PyArg_ParseTuple(args, "s:pcap_create", &device)) return NULL; int status = pcap_lookupnet(device, &net, &mask, errbuff); if (status) { net = 0; mask = 0; } pcap_t* pt; pt = pcap_create(device, errbuff); if (!pt) { PyErr_SetString(PcapError, errbuff); return NULL; } #ifdef WIN32 //Same than in open_live 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"}, {"create", pcap_create, METH_VARARGS, "create(device) is used to create a packet capture handle to look at packets on the network."}, {NULL, NULL} }; #if PY_MAJOR_VERSION >= 3 PyDoc_STRVAR(pcap_doc, "A wrapper for the Packet Capture (PCAP) library"); static struct PyModuleDef pcapy_module = { PyModuleDef_HEAD_INIT, "pcapy", /* m_name */ pcap_doc, /* m_doc */ -1, /* m_size */ pcap_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #else static char *pcap_doc = "\nA wrapper for the Packet Capture (PCAP) library\n"; #endif //PY_MAJOR_VERSION >= 3 #if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit_pcapy(void) #else void initpcapy(void) #endif //PY_MAJOR_VERSION >= 3 { PyObject *m, *d; #if PY_MAJOR_VERSION < 3 Pcaptype.ob_type = &PyType_Type; Pkthdr_type.ob_type = &PyType_Type; Pdumpertype.ob_type = &PyType_Type; #endif #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&pcapy_module); #else m = Py_InitModule3("pcapy", pcap_methods, pcap_doc); #endif if (PyType_Ready(&BPFProgramType) < 0) { #if PY_MAJOR_VERSION >= 3 return NULL; #else return; #endif //PY_MAJOR_VERSION >= 3 } PyModule_AddObject(m, "BPFProgram", (PyObject *) &BPFProgramType); /* 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); /* Direct from pcap's net/pcap.h.*/ PyModule_AddIntConstant(m, "PCAP_D_INOUT", 0); PyModule_AddIntConstant(m, "PCAP_D_IN", 1); PyModule_AddIntConstant(m, "PCAP_D_OUT", 2); d = PyModule_GetDict(m); PcapError = PyErr_NewException("pcapy.PcapError", NULL, NULL ); BPFError = PyErr_NewException("pcapy.BPFError", NULL, NULL ); if( PcapError ) { PyDict_SetItemString( d, "PcapError", PcapError ); } if ( BPFError ) { PyDict_SetItemString( d, "BPFError", BPFError ); } #if PY_MAJOR_VERSION >= 3 return m; #endif //PY_MAJOR_VERSION >= 3 } /* vim: set tabstop=2 shiftwidth=2 expandtab: */ #ifdef WIN32 /* All of the following code takes care of LUID/GUID conversions. * Copied from Wireshark. */ static BOOL gethexdigit(const char *p) { if(*p >= '0' && *p <= '9'){ return *p - '0'; }else if(*p >= 'A' && *p <= 'F'){ return *p - 'A' + 0xA; }else if(*p >= 'a' && *p <= 'f'){ return *p - 'a' + 0xa; }else{ return -1; /* Not a hex digit */ } } static BOOL get8hexdigits(const char *p, DWORD *d) { int digit; DWORD val; int i; val = 0; for(i = 0; i < 8; i++){ digit = gethexdigit(p++); if(digit == -1){ return FALSE; /* Not a hex digit */ } val = (val << 4) | digit; } *d = val; return TRUE; } static BOOL get4hexdigits(const char *p, WORD *w) { int digit; WORD val; int i; val = 0; for(i = 0; i < 4; i++){ digit = gethexdigit(p++); if(digit == -1){ return FALSE; /* Not a hex digit */ } val = (val << 4) | digit; } *w = val; return TRUE; } static BOOL parse_as_guid(const char *guid_text, GUID *guid) { int i; int digit1, digit2; if(*guid_text != '{'){ return FALSE; /* Nope, not enclosed in {} */ } guid_text++; /* There must be 8 hex digits; if so, they go into guid->Data1 */ if(!get8hexdigits(guid_text, &guid->Data1)){ return FALSE; /* nope, not 8 hex digits */ } guid_text += 8; /* Now there must be a hyphen */ if(*guid_text != '-'){ return FALSE; /* Nope */ } guid_text++; /* There must be 4 hex digits; if so, they go into guid->Data2 */ if(!get4hexdigits(guid_text, &guid->Data2)){ return FALSE; /* nope, not 4 hex digits */ } guid_text += 4; /* Now there must be a hyphen */ if(*guid_text != '-'){ return FALSE; /* Nope */ } guid_text++; /* There must be 4 hex digits; if so, they go into guid->Data3 */ if(!get4hexdigits(guid_text, &guid->Data3)){ return FALSE; /* nope, not 4 hex digits */ } guid_text += 4; /* Now there must be a hyphen */ if(*guid_text != '-'){ return FALSE; /* Nope */ } guid_text++; /* * There must be 4 hex digits; if so, they go into the first 2 bytes * of guid->Data4. */ for(i = 0; i < 2; i++){ digit1 = gethexdigit(guid_text); if(digit1 == -1){ return FALSE; /* Not a hex digit */ } guid_text++; digit2 = gethexdigit(guid_text); if(digit2 == -1){ return FALSE; /* Not a hex digit */ } guid_text++; guid->Data4[i] = (digit1 << 4)|(digit2); } /* Now there must be a hyphen */ if(*guid_text != '-'){ return FALSE; /* Nope */ } guid_text++; /* * There must be 12 hex digits; if so,t hey go into the next 6 bytes * of guid->Data4. */ for(i = 0; i < 6; i++){ digit1 = gethexdigit(guid_text); if(digit1 == -1){ return FALSE; /* Not a hex digit */ } guid_text++; digit2 = gethexdigit(guid_text); if(digit2 == -1){ return FALSE; /* Not a hex digit */ } guid_text++; guid->Data4[i+2] = (digit1 << 4)|(digit2); } /* Now there must be a closing } */ if(*guid_text != '}'){ return FALSE; /* Nope */ } guid_text++; /* And that must be the end of the string */ if(*guid_text != '\0'){ return FALSE; /* Nope */ } return TRUE; } static char* luid_to_guid(char *luid) { 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; char* cursor_luid; char *ret_guid = NULL; while(cursor) { cursor_luid = get_windows_interface_friendly_name(cursor->name); if (!strcmp(cursor_luid, luid)) { ret_guid = strdup(cursor->name); goto done; } free(cursor_luid); cursor = cursor->next; } done: pcap_freealldevs(devs); return ret_guid; } static char* guid_to_luid(GUID *guid) { BOOL status; int size; char *name; WCHAR wName[128 + 1]; HMODULE hIPHlpApi = LoadLibrary(TEXT("iphlpapi.dll")); typedef HRESULT (WINAPI *ProcAddr_nhGINFG) ( GUID *InterfaceGuid, PCWSTR InterfaceAlias, DWORD *LengthAddress, wchar_t *a4, wchar_t *a5); ProcAddr_nhGINFG Proc_nhGetInterfaceNameFromGuid = NULL; Proc_nhGetInterfaceNameFromGuid = (ProcAddr_nhGINFG) GetProcAddress(hIPHlpApi, "NhGetInterfaceNameFromGuid"); if (Proc_nhGetInterfaceNameFromGuid!= NULL) { wchar_t *p4=NULL, *p5=NULL; DWORD NameSize; /* testing of nhGetInterfaceNameFromGuid indicates the unpublished API function expects the 3rd parameter * to be the available space in bytes (as compared to wchar's) available in the second parameter buffer * to receive the friendly name (in unicode format) including the space for the nul termination.*/ NameSize = sizeof(wName); /* do the guid->friendlyname lookup */ status = ( 0 == Proc_nhGetInterfaceNameFromGuid(guid, wName, &NameSize, p4, p5) ); } /* we have finished with iphlpapi.dll - release it */ FreeLibrary(hIPHlpApi); if(FALSE == status){ /* failed to get the friendly name, nothing further to do */ return NULL; } /* Get the required buffer size, and then convert the string * from UTF-16 to UTF-8. */ size=WideCharToMultiByte(CP_UTF8, 0, wName, -1, NULL, 0, NULL, NULL); name=(char *) malloc(size); if (name == NULL){ return NULL; } size=WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, size, NULL, NULL); if(size==0){ /* bytes written == 0, indicating some form of error*/ free(name); return NULL; } return name; } char * get_windows_interface_friendly_name(const char *interface_devicename) { const char* guid_text; GUID guid; /* Extract the guid text from the interface device name */ if(strncmp("\\Device\\NPF_", interface_devicename, 12)==0){ guid_text=interface_devicename+12; /* skip over the '\Device\NPF_' prefix, assume the rest is the guid text */ }else{ guid_text=interface_devicename; } if (!parse_as_guid(guid_text, &guid)){ return strdup(interface_devicename); /* not a GUID, so no friendly name */ } /* guid okay, get the interface friendly name associated with the guid */ return guid_to_luid(&guid); } #endifpcapy-0.11.5/pcapy.h000066400000000000000000000012551350674010000141760ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #ifndef __PCAPY_H__ #ifndef Py_TYPE // python3 compatible #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #endif extern "C" { #ifdef WIN32 __declspec(dllexport) char *get_windows_interface_friendly_name(const char *interface_devicename); static char* luid_to_guid(char *luid); #endif #if PY_MAJOR_VERSION >= 3 PyObject * PyInit_pcapy(void); #else void initpcapy(void); #endif } // exception object extern PyObject* PcapError; #endif // __PCAPY_H__ pcapy-0.11.5/pcapy.html000066400000000000000000001751341350674010000147230ustar00rootroot00000000000000 Part I. Pcapy Reference

Part I. Pcapy Reference

CORE SECURITY TECHNOLOGIES

Revision History
Revision Revision: 16Date: 2018-06-04Author: jkohen
2018 updated

Table of Contents

I. Pcapy Module Reference
open_live — Obtain a packet capture descriptor to look at packets on the network
open_offline — Obtain a packet capture descriptor to look at packets on a savefile
lookupdev — Return a network device suitable for use with open_live
findalldevs — Obtain the list of available network devices
compile — Compile a BPF filter
create — Creates a non-activated packet capture handle to look at packets on the network
II. Reader Object Reference
dispatch — Collect and process packets
next — Collect the next packet
stats — get capture statistics
setfilter — Specify a filter
getfd — get a file descriptor on which a select() can be done for a live capture
set_snaplen — Set the snapshot length for a not-yet-activated capture handle
set_promisc — Set promiscuous mode for a not-yet-activated capture handle
set_timeout — Set the read timeout for a not-yet-activated capture handle
set_buffer_size — Set the buffer size for a not-yet-activated capture handle capture handle
activate — Activate a capture handle
getnet — Get the associated network number and mask
datalink — Obtain the link layer type
getnonblock / setnonblock — Manipulate the non-blocking flag
dump_open — Create a Dumper object
close — Close a Reader
III. Dumper Object Reference
dump — Dump a packet to a savefile
close — Close a Dumper
IV. Pkthdr Object Reference
getts — Obtain packet header information
V. Bpf Object Reference
filter — Test a packet against a compiled filter
Bibliography

Pcapy Module Reference


Table of Contents

open_live — Obtain a packet capture descriptor to look at packets on the network
open_offline — Obtain a packet capture descriptor to look at packets on a savefile
lookupdev — Return a network device suitable for use with open_live
findalldevs — Obtain the list of available network devices
compile — Compile a BPF filter
create — Creates a non-activated packet capture handle to look at packets on the network

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.


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.


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.


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.)


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.


Name

create — Creates a non-activated packet capture handle to look at packets on the network

Synopsis

Reader create (device); 
string device ;
 

DESCRIPTION

create is used to create a packet capture handle to look at packets on the network. The returned handle must be activated with activate() before packets can be captured with it; options for the capture, such as promiscuous mode, can be set on the handle before activating it.

Reader Object Reference


Table of Contents

dispatch — Collect and process packets
next — Collect the next packet
stats — get capture statistics
setfilter — Specify a filter
getfd — get a file descriptor on which a select() can be done for a live capture
set_snaplen — Set the snapshot length for a not-yet-activated capture handle
set_promisc — Set promiscuous mode for a not-yet-activated capture handle
set_timeout — Set the read timeout for a not-yet-activated capture handle
set_buffer_size — Set the buffer size for a not-yet-activated capture handle capture handle
activate — Activate a capture handle
getnet — Get the associated network number and mask
datalink — Obtain the link layer type
getnonblock / setnonblock — Manipulate the non-blocking flag
dump_open — Create a Dumper object
close — Close a Reader

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.


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.


Name

stats — get capture statistics

Synopsis

(int32, int32, int32) stats (); 
 

DESCRIPTION

stats returns statistics on the current capture as a tuple (recv, drop, ifdrop)


Name

setfilter — Specify a filter

Synopsis

setfilter (filter); 
string filter ;
 

DESCRIPTION

setfilter is used to specify a filter for this object.


Name

getfd — get a file descriptor on which a select() can be done for a live capture

Synopsis

int getfd (filter); 
string filter ;
 

DESCRIPTION

getfd returns, on UNIX, a file descriptor number for a file descriptor on which one can do a select(), poll(), epoll_wait(), kevent(), or other such call to wait for it to be possible to read packets without blocking, if such a descriptor exists, or -1, if no such descriptor exists.


Name

set_snaplen — Set the snapshot length for a not-yet-activated capture handle

Synopsis

int set_snaplen (snaplen); 
int snaplen ;
 

DESCRIPTION

set_snaplen sets the snapshot length to be used on a capture handle when the handle is activated to snaplen. set_snaplen returns 0 on success or PCAP_ERROR_ACTIVATED if called on a capture handle that has been activated.


Name

set_promisc — Set promiscuous mode for a not-yet-activated capture handle

Synopsis

int set_promisc (promisc); 
int promisc ;
 

DESCRIPTION

set_promisc sets whether promiscuous mode should be set on a capture handle when the handle is activated. If promisc is non-zero, promiscuous mode will be set, otherwise it will not be set. set_promisc returns 0 on success or PCAP_ERROR_ACTIVATED if called on a capture handle that has been activated.


Name

set_timeout — Set the read timeout for a not-yet-activated capture handle

Synopsis

int set_timeout (timeout); 
int timeout ;
 

DESCRIPTION

set_timeout sets the read timeout that will be used on a capture handle when the handle is activated to to_ms, which is in units of milliseconds. set_timeout returns 0 on success or PCAP_ERROR_ACTIVATED if called on a capture handle that has been activated.


Name

set_buffer_size — Set the buffer size for a not-yet-activated capture handle capture handle

Synopsis

int set_buffer_size (buffer_size); 
int buffer_size ;
 

DESCRIPTION

set_buffer_size sets the buffer size that will be used on a capture handle when the handle is activated to buffer_size, which is in units of bytes. set_buffer_size returns 0 on success or PCAP_ERROR_ACTIVATED if called on a capture handle that has been activated.


Name

activate — Activate a capture handle

Synopsis

int activate (); 
 

DESCRIPTION

activate is used to activate a packet capture handle to look at packets on the network, with the options that were set on the handle being in effect. activate returns 0 on success without warnings, a non-zero positive value on success with warnings, and a negative value on error. A non-zero return value indicates what warning or error condition occurred. has been activated. See https://www.tcpdump.org/manpages/pcap_activate.3pcap.html for all possible return values.


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.


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.


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.


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.


Name

close — Close a Reader

Synopsis

Reader close (); 
 

DESCRIPTION

close closes a Reader using pcap_close.

Dumper Object Reference


Table of Contents

dump — Dump a packet to a savefile
close — Close a Dumper

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.


Name

close — Close a Dumper

Synopsis

Dumper close (); 
 

DESCRIPTION

close closes a Dumper.

Pkthdr Object Reference


Table of Contents

getts — Obtain packet header information

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 — Test a packet against a compiled 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.11.5/pcapy.xml000066400000000000000000001344151350674010000145540ustar00rootroot00000000000000 ]> 2016-2018 &corest; &corest; pcap packet capture python Revision: 16 Date: 2018-06-04 Author: jkohen 2018 updated 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. create Creates a non-activated packet capture handle to look at packets on the network Reader create string device DESCRIPTION create is used to create a packet capture handle to look at packets on the network. The returned handle must be activated with activate() before packets can be captured with it; options for the capture, such as promiscuous mode, can be set on the handle before activating it. 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. stats get capture statistics (int32, int32, int32) stats DESCRIPTION stats returns statistics on the current capture as a tuple (recv, drop, ifdrop) setfilter Specify a filter setfilter string filter DESCRIPTION setfilter is used to specify a filter for this object. getfd get a file descriptor on which a select() can be done for a live capture int getfd string filter DESCRIPTION getfd returns, on UNIX, a file descriptor number for a file descriptor on which one can do a select(), poll(), epoll_wait(), kevent(), or other such call to wait for it to be possible to read packets without blocking, if such a descriptor exists, or -1, if no such descriptor exists. set_snaplen Set the snapshot length for a not-yet-activated capture handle int set_snaplen int snaplen DESCRIPTION set_snaplen sets the snapshot length to be used on a capture handle when the handle is activated to snaplen. set_snaplen returns 0 on success or PCAP_ERROR_ACTIVATED if called on a capture handle that has been activated. set_promisc Set promiscuous mode for a not-yet-activated capture handle int set_promisc int promisc DESCRIPTION set_promisc sets whether promiscuous mode should be set on a capture handle when the handle is activated. If promisc is non-zero, promiscuous mode will be set, otherwise it will not be set. set_promisc returns 0 on success or PCAP_ERROR_ACTIVATED if called on a capture handle that has been activated. set_timeout Set the read timeout for a not-yet-activated capture handle int set_timeout int timeout DESCRIPTION set_timeout sets the read timeout that will be used on a capture handle when the handle is activated to to_ms, which is in units of milliseconds. set_timeout returns 0 on success or PCAP_ERROR_ACTIVATED if called on a capture handle that has been activated. set_buffer_size Set the buffer size for a not-yet-activated capture handle capture handle int set_buffer_size int buffer_size DESCRIPTION set_buffer_size sets the buffer size that will be used on a capture handle when the handle is activated to buffer_size, which is in units of bytes. set_buffer_size returns 0 on success or PCAP_ERROR_ACTIVATED if called on a capture handle that has been activated. activate Activate a capture handle int activate DESCRIPTION activate is used to activate a packet capture handle to look at packets on the network, with the options that were set on the handle being in effect. activate returns 0 on success without warnings, a non-zero positive value on success with warnings, and a negative value on error. A non-zero return value indicates what warning or error condition occurred. has been activated. See https://www.tcpdump.org/manpages/pcap_activate.3pcap.html for all possible return values. 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. close Close a Reader Reader close DESCRIPTION close closes a Reader using pcap_close. 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. close Close a Dumper Dumper close DESCRIPTION close closes a Dumper. 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.11.5/setup.py000066400000000000000000000055561350674010000144330ustar00rootroot00000000000000import sys import os import glob from setuptools import setup, Extension PACKAGE_NAME = 'pcapy' # You might want to change these to reflect your specific configuration include_dirs = [] library_dirs = [] libraries = [] if sys.platform == 'win32': if os.environ.get('WPDPACK_BASE'): wpdpack = os.environ['WPDPACK_BASE'] include_dirs.append(os.path.join(wpdpack, 'Include')) if sys.maxsize > 2**32: # x64 Python interpreter library_dirs.append(os.path.join(wpdpack, 'Lib', 'x64')) else: # x86 Python interpreter library_dirs.append(os.path.join(wpdpack, 'Lib')) else: # WinPcap include files include_dirs.append(r'c:\wpdpack\Include') # WinPcap library files if sys.maxsize > 2**32: # x64 Python interpreter library_dirs.append(r'c:\wpdpack\Lib\x64') else: # x86 Python interpreter library_dirs.append(r'c:\wpdpack\Lib') libraries = ['wpcap', 'packet', 'ws2_32'] else: libraries = ['pcap'] # end of user configurable parameters macros = [] sources = ['pcapdumper.cc', 'bpfobj.cc', 'pcapobj.cc', 'pcap_pkthdr.cc', 'pcapy.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 compiler = g['LDSHARED'].split()[0] flags = g['LDSHARED'].split()[1:] if compiler == 'gcc': g['LDSHARED'] = ' '.join(['g++'] + flags) elif compiler == 'clang': g['LDSHARED'] = ' '.join(['clang++'] + flags) print('my_init_posix: changing LDSHARED =', repr(g['LDSHARED'])) print('to', repr(g['LDSHARED'])) sysconfig._init_posix = my_init_posix def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name=PACKAGE_NAME, version="0.11.5-dev", url="https://github.com/CoreSecurity/pcapy", author="CORE Security", author_email="oss@coresecurity.com", maintainer="CORE Security", maintainer_email="oss@coresecurity.com", platforms=["Unix", "Windows"], description="Python pcap extension", long_description=read('README'), license="Apache modified", 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']), (os.path.join('share', 'doc', PACKAGE_NAME, 'tests'), glob.glob('tests/*'))] ) pcapy-0.11.5/tests/000077500000000000000000000000001350674010000140505ustar00rootroot00000000000000pcapy-0.11.5/tests/96pings.pcap000066400000000000000000000250301350674010000162140ustar00rootroot00000000000000`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.11.5/tests/pcapytests.py000066400000000000000000000110321350674010000166160ustar00rootroot00000000000000## Copyright (c) 2014 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. ## import pcapy import sys import unittest import os class TestPcapy(unittest.TestCase): _96PINGS = '96pings.pcap' _IFACE = 'vboxnet0' def testPacketHeaderRefCount(self): """ #1: when next() creates a pkthdr it makes one extra reference """ class _Simple: pass r = pcapy.open_offline(TestPcapy._96PINGS) # get one & check its refcount self.assertEqual( sys.getrefcount(r.next()[0]), sys.getrefcount(_Simple())) def testEOFValue(self): """ #2 empty string is returned as packet body at end of file """ r = pcapy.open_offline(TestPcapy._96PINGS) # get one & check its refcount i = 0 refNone = sys.getrefcount(None) hdr, pkt = r.next() while hdr is not None: hdr, pkt = r.next() i += 1 self.assertEqual(96, i) self.assertTrue(hdr is None) self.assertEqual(pkt, b'') del hdr self.assertEqual(refNone, sys.getrefcount(None)) def testBPFFilter(self): """ #3 test offline BPFFilter """ r = pcapy.open_offline(TestPcapy._96PINGS) bpf = pcapy.BPFProgram("ip dst host 192.168.1.1") hdr, pkt = r.next() while hdr is not None: f = bpf.filter(pkt) self.assertNotEqual(f, 0) hdr, pkt = r.next() def _testLiveCapture(self): """ #4 (disabled -- requires interface info) test live capture """ r = pcapy.open_live(TestPcapy._IFACE, 60000, 1, 1500) net = r.getnet() self.assertEqual(net, '192.168.56.0') hdr, body = r.next() self.assertTrue(hdr is not None) def _testSendPacket(self): """ #5 (disabled -- requires interface info) test sendpacket """ r = pcapy.open_offline(TestPcapy._96PINGS) w = pcapy.open_live(TestPcapy._IFACE, 60000, 1, 1500) # get one & check its refcount i = 0 hdr, pkt = r.next() while hdr is not None: w.sendpacket(pkt) hdr, pkt = r.next() i += 1 def testPacketDumper(self): """ #6 test that the dumper writes correct payload """ try: r = pcapy.open_offline(TestPcapy._96PINGS) dumper = r.dump_open('tmp.pcap') hdr, body = r.next() i = 0 while hdr is not None: dumper.dump(hdr, body) i += 1 hdr, body = r.next() # make sure file closes del dumper # check that the dumper wrote a legal pcap # file with same packer data r = pcapy.open_offline(TestPcapy._96PINGS) r2 = pcapy.open_offline('tmp.pcap') h1, b1 = r.next() h2, b2 = r2.next() while h1 is not None and h2 is not None: self.assertEqual(b1, b2) h1, b1 = r.next() h2, b2 = r2.next() self.assertTrue(h1 is None) self.assertTrue(h2 is None) del r2 finally: os.unlink('tmp.pcap') def testClose(self): """ #7 Test the close method """ r = pcapy.open_offline(TestPcapy._96PINGS) hdr, body = r.next() assert hdr is not None r.close() with self.assertRaises(ValueError): r.next() def testContextManager(self): """ #8 Test the context manager support """ with pcapy.open_offline(TestPcapy._96PINGS) as r: hdr, body = r.next() assert hdr is not None with self.assertRaises(ValueError): r.next() def test_get_bpf(self): bpf = pcapy.compile(pcapy.DLT_EN10MB, 2**16, "icmp", 1, 1) code = bpf.get_bpf() # result of `tcpdump "icmp" -ddd -s 65536` on EN10MB interface expected = """6 40 0 0 12 21 0 3 2048 48 0 0 23 21 0 1 1 6 0 0 65536 6 0 0 0""" result = str(len(code)) + "\n" result += "\n".join([' '.join(map(str, inst)) for inst in code]) self.assertEqual(expected, result) suite = unittest.TestLoader().loadTestsFromTestCase(TestPcapy) result = unittest.TextTestRunner(verbosity=2).run(suite) if not result.wasSuccessful(): sys.exit(1) pcapy-0.11.5/win32/000077500000000000000000000000001350674010000136505ustar00rootroot00000000000000pcapy-0.11.5/win32/dllmain.cc000066400000000000000000000011251350674010000155760ustar00rootroot00000000000000/* * Copyright (c) 2014 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. * */ #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; }