pax_global_header00006660000000000000000000000064123555065270014524gustar00rootroot0000000000000052 comment=7288503090d95397da25b9e0e19c7f4ce93d174a python-ipfix-0.9.7/000077500000000000000000000000001235550652700141775ustar00rootroot00000000000000python-ipfix-0.9.7/.gitignore000066400000000000000000000005321235550652700161670ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 MANIFEST # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Sphinx tempfiles sphinx/_build python-ipfix-0.9.7/CHANGES.txt000066400000000000000000000020371235550652700160120ustar00rootroot00000000000000v0.9, 2013-07-01 -- Initial release. v0.9.1, 2013-07-02 -- Add missing license headers and LICENSE.txt for GNU LGPL. v0.9.2, 2013-07-02 -- Fix packaging script errors. v0.9.3, 2013-07-09 -- Fix tuple decode bug, add (undocumented) vis submodule, add TCP mode to ipfix2csv. v0.9.4, 2013-08-12 -- Fix timestamp decode issues (force all timestamps to UTC), add (pre-alpha quality) netflow9 read-only support, update to latest IANA Information Element registry. v0.9.5, 2014-03-01 -- Various bugfixes (fix timestamps for real), IANA updates, some API changes, enhancements to (pre-alpha quality) netflow9 support and to support usage with numpy. v0.9.6, 2014-06-06 -- Test coverage improvements, consolidation of scripts, bugfixes (export time, reduced-length encoding), update to latest IANA Information Element registry. v0.9.7, 2014-07-04 -- Bugfix (export time and sequence number reversed)python-ipfix-0.9.7/LICENSE.txt000066400000000000000000000167431235550652700160350ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. python-ipfix-0.9.7/MANIFEST.in000066400000000000000000000000521235550652700157320ustar00rootroot00000000000000include *.txt recursive-include docs *.txtpython-ipfix-0.9.7/README.md000066400000000000000000000005631235550652700154620ustar00rootroot00000000000000python-ipfix ============ IPFIX implementation for Python 3.3. This module provides a Python interface to IPFIX message streams, and provides tools for building IPFIX Exporting and Collecting Processes. It handles message framing and deframing, encoding and decoding IPFIX data records using templates, and a bridge between IPFIX ADTs and appopriate Python data types. python-ipfix-0.9.7/README.txt000066400000000000000000000005631235550652700157010ustar00rootroot00000000000000python-ipfix ============ IPFIX implementation for Python 3.3. This module provides a Python interface to IPFIX message streams, and provides tools for building IPFIX Exporting and Collecting Processes. It handles message framing and deframing, encoding and decoding IPFIX data records using templates, and a bridge between IPFIX ADTs and appopriate Python data types. python-ipfix-0.9.7/collector_test.py000077500000000000000000000017351235550652700176070ustar00rootroot00000000000000#!/usr/bin/env python3 import socketserver import ipfix.reader import ipfix.ie import argparse ap = argparse.ArgumentParser(description="Dump IPFIX files collected over TCP") ap.add_argument('--spec', metavar='specfile', help='iespec file to read') args = ap.parse_args() ipfix.ie.use_iana_default() ipfix.ie.use_5103_default() if args.spec: ipfix.ie.use_specfile(args.spec) class CollectorDictHandler(socketserver.StreamRequestHandler): def handle(self): reccount = 0 print ("connection from "+str(self.client_address)) r = ipfix.reader.from_stream(self.rfile) for rec in r.records_as_dict(): print("--- record %u in message %u from %s---" % (reccount, r.msgcount, str(self.client_address))) reccount += 1 for key in rec: print(" %30s => %s" % (key, str(rec[key]))) ss = socketserver.TCPServer(("", 4739), CollectorDictHandler) ss.serve_forever()python-ipfix-0.9.7/docs/000077500000000000000000000000001235550652700151275ustar00rootroot00000000000000python-ipfix-0.9.7/docs/ipfix.txt000066400000000000000000001052131235550652700170110ustar00rootroot00000000000000 python-ipfix ************ IPFIX implementation for Python 3.3. This module provides a Python interface to IPFIX message streams, and provides tools for building IPFIX Exporting and Collecting Processes. It handles message framing and deframing, encoding and decoding IPFIX data records using templates, and a bridge between IPFIX ADTs and appropriate Python data types. Before using any of the functions of this module, it is necessary to populate the information model with Information Elements. "ipfix.ie.use_iana_default()" populates the default IANA IPFIX Information Element Registry shipped with the module; this is the current registry as of release time. "ipfix.ie.use_5103_default()" populates the reverse counterpart IEs as in **RFC 5103**. The module also supports the definition of enterprise-specific Information Elements via "ipfix.ie.for_spec()" and "ipfix.ie.use_specfile()"; see "ipfix.ie" for more. For reading and writing of records to IPFIX message streams with automatic message boundary management, see the "ipfix.reader" and "ipfix.writer" modules, respectively. For manual reading and writing of messages, see "ipfix.message". In any case, exporters will need to define templates; see "ipfix.template". This module is copyright 2013 Brian Trammell. It is made available under the terms of the GNU Lesser General Public License, or, at your option, any later version. Reference documentation for each module is found in the subsections below. module ipfix.types ================== Implementation of IPFIX abstract data types (ADT) and mappings to Python types. Maps each IPFIX ADT to the corresponding Python type, as below: +-------------------------+---------------+ | IPFIX Type | Python Type | +=========================+===============+ | octetArray | bytes | +-------------------------+---------------+ | unsigned8 | int | +-------------------------+---------------+ | unsigned16 | int | +-------------------------+---------------+ | unsigned32 | int | +-------------------------+---------------+ | unsigned64 | int | +-------------------------+---------------+ | signed8 | int | +-------------------------+---------------+ | signed16 | int | +-------------------------+---------------+ | signed32 | int | +-------------------------+---------------+ | signed64 | int | +-------------------------+---------------+ | float32 | float | +-------------------------+---------------+ | float64 | float | +-------------------------+---------------+ | boolean | bool | +-------------------------+---------------+ | macAddress | bytes | +-------------------------+---------------+ | string | str | +-------------------------+---------------+ | dateTimeSeconds | datetime | +-------------------------+---------------+ | dateTimeMilliseconds | datetime | +-------------------------+---------------+ | dateTimeMicroseconds | datetime | +-------------------------+---------------+ | dateTimeNanoseconds | datetime | +-------------------------+---------------+ | ipv4Address | ipaddress | +-------------------------+---------------+ | ipv6Address | ipaddress | +-------------------------+---------------+ Though client code generally will not use this module directly, it defines how each IPFIX abstract data type will be represented in Python, and the concrete IPFIX representation of each type. Type methods operate on buffers, as used internally by the "ipfix.message.MessageBuffer" class, so we'll create one to illustrate encoding and decoding: >>> import ipfix.types >>> buf = memoryview(bytearray(16)) Each of the encoding methods returns the offset into the buffer of the first byte after the encoded value; since we're always encoding to the beginning of the buffer in this example, this is equivalent to the length. We use this to bound the encoded value on subsequent decode. Integers are represented by the python int type: >>> unsigned32 = ipfix.types.for_name("unsigned32") >>> length = unsigned32.encode_single_value_to(42, buf, 0) >>> buf[0:length].tolist() [0, 0, 0, 42] >>> unsigned32.decode_single_value_from(buf, 0, length) 42 ...floats by the float type, with the usual caveats about precision: >>> float32 = ipfix.types.for_name("float32") >>> length = float32.encode_single_value_to(42.03579, buf, 0) >>> buf[0:length].tolist() [66, 40, 36, 166] >>> float32.decode_single_value_from(buf, 0, length) 42.035789489746094 ...strings by the str type, encoded as UTF-8: >>> string = ipfix.types.for_name("string") >>> length = string.encode_single_value_to("Grüezi", buf, 0) >>> buf[0:length].tolist() [71, 114, 195, 188, 101, 122, 105] >>> string.decode_single_value_from(buf, 0, length) 'Grüezi' ...addresses as the IPv4Address and IPv6Address types in the ipaddress module: >>> from ipaddress import ip_address >>> ipv4Address = ipfix.types.for_name("ipv4Address") >>> length = ipv4Address.encode_single_value_to(ip_address("198.51.100.27"), buf, 0) >>> buf[0:length].tolist() [198, 51, 100, 27] >>> ipv4Address.decode_single_value_from(buf, 0, length) IPv4Address('198.51.100.27') >>> ipv6Address = ipfix.types.for_name("ipv6Address") >>> length = ipv6Address.encode_single_value_to(ip_address("2001:db8::c0:ffee"), buf, 0) >>> buf[0:length].tolist() [32, 1, 13, 184, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 255, 238] >>> ipv6Address.decode_single_value_from(buf, 0, length) IPv6Address('2001:db8::c0:ffee') ...and the timestamps of various precision as a python datetime, encoded as per RFC5101bis: >>> from datetime import datetime >>> dtfmt_in = "%Y-%m-%d %H:%M:%S.%f %z" >>> dtfmt_out = "%Y-%m-%d %H:%M:%S.%f" >>> dt = datetime.strptime("2013-06-21 14:00:03.456789 +0000", dtfmt_in) dateTimeSeconds truncates microseconds: >>> dateTimeSeconds = ipfix.types.for_name("dateTimeSeconds") >>> length = dateTimeSeconds.encode_single_value_to(dt, buf, 0) >>> buf[0:length].tolist() [81, 196, 92, 99] >>> dateTimeSeconds.decode_single_value_from(buf, 0, length).strftime(dtfmt_out) '2013-06-21 14:00:03.000000' dateTimeMilliseconds truncates microseconds to the nearest millisecond: >>> dateTimeMilliseconds = ipfix.types.for_name("dateTimeMilliseconds") >>> length = dateTimeMilliseconds.encode_single_value_to(dt, buf, 0) >>> buf[0:length].tolist() [0, 0, 1, 63, 103, 8, 228, 128] >>> dateTimeMilliseconds.decode_single_value_from(buf, 0, length).strftime(dtfmt_out) '2013-06-21 14:00:03.456000' dateTimeMicroseconds exports microseconds fully in NTP format: >>> dateTimeMicroseconds = ipfix.types.for_name("dateTimeMicroseconds") >>> length = dateTimeMicroseconds.encode_single_value_to(dt, buf, 0) >>> buf[0:length].tolist() [81, 196, 92, 99, 116, 240, 32, 0] >>> dateTimeMicroseconds.decode_single_value_from(buf, 0, length).strftime(dtfmt_out) '2013-06-21 14:00:03.456789' dateTimeNanoseconds is also supported, but is identical to dateTimeMicroseconds, as the datetime class in Python only supports microsecond-level timing. class class ipfix.types.IpfixType(name, num, valenc, valdec) Abstract interface for all IPFIX types. Used internally. exception exception ipfix.types.IpfixTypeError(*args) Raised when attempting to do an unsupported operation on a type class class ipfix.types.OctetArrayType(name, num, valenc=, valdec=) Type encoded by byte array packing. Used internally. class class ipfix.types.StructType(name, num, stel, valenc=, valdec=) Type encoded by struct packing. Used internally. ipfix.types.decode_varlen(buf, offset) Decode a IPFIX varlen encoded length; used internally by template ipfix.types.encode_varlen(buf, offset, length) Encode a IPFIX varlen encoded length; used internally by template ipfix.types.for_name(name) Return an IPFIX type for a given type name Parameters: **name** -- the name of the type to look up Returns: IpfixType -- type instance for that name Raises : IpfixTypeError module ipfix.ie =============== IESpec-based interface to IPFIX information elements, and interface to use the default IPFIX IANA Information Model An IESpec is a string representation of an IPFIX information element, including all the information required to define it, as documented in Section 9 of http://tools.ietf.org/html/draft-ietf-ipfix-ie-doctors. It has the format: name(pen/num)[size] To specify a new Information Element, a complete IESpec must be passed to for_spec(): >>> import ipfix.ie >>> e = ipfix.ie.for_spec("myNewInformationElement(35566/1)") >>> e InformationElement('myNewInformationElement', 35566, 1, ipfix.types.for_name('string'), 65535) The string representation of an InformationElement is its IESpec: >>> str(e) 'myNewInformationElement(35566/1)[65535]' To get an Information Element already specified, an incomplete specification can be passed; a name or number is enough: >>> ipfix.ie.use_iana_default() >>> str(ipfix.ie.for_spec("octetDeltaCount")) 'octetDeltaCount(0/1)[8]' >>> str(ipfix.ie.for_spec("(2)")) 'packetDeltaCount(0/2)[8]' Reduced-length encoding and fixed-length sequence types are supported by the for_length method; this is used internally by templates. >>> str(e.for_length(32)) 'myNewInformationElement(35566/1)[32]' Most client code will only need the "use_iana_default()", "use_5103_default()", and "use_specfile()" functions; client code using tuple interfaces will need "spec_list()" as well. class class ipfix.ie.InformationElement(name, pen, num, ietype, length) An IPFIX Information Element (IE). This is essentially a five-tuple of name, element number (num), a private enterprise number (pen; 0 if it is an IANA registered IE), a type, and a length. InformationElement instances should be obtained using the "for_spec()" or "for_template_entry()" functions. for_length(length) Get an instance of this IE for the specified length. Used to support reduced-length encoding (RLE). Parameters: **length** -- length of the new IE Returns: this IE if length matches, or a new IE for the length Raises : ValueError class class ipfix.ie.InformationElementList(iterable=None) A hashable ordered list of Information Elements. Used internally by templates, and to specify the order of tuples to the tuple append and iterator interfaces. Get an instance by calling "spec_list()" ipfix.ie.clear_infomodel() Reset the cache of known Information Elements. ipfix.ie.for_spec(spec) Get an IE from the cache of known IEs, or create a new IE if not found, given an IESpec. Parameters: **spec** -- IEspec, as in draft-ietf-ipfix-ie-doctors, of the form name(pen/num)[size]; some fields may be omitted unless creating a new IE in the cache. Returns: an IE for the name Raises : ValueError ipfix.ie.for_template_entry(pen, num, length) Get an IE from the cache of known IEs, or create a new IE if not found, given a private enterprise number, element number, and length. Used internally by Templates. Parameters: * **pen** -- private enterprise number, or 0 for an IANA IE * **num** -- IE number (Element ID) * **length** -- length of the IE in bytes Returns: an IE for the given pen, num, and length. If the IE has not been previously added to the cache of known IEs, the IE will be named _ipfix_pen_num, and have octetArray as a type. ipfix.ie.parse_spec(spec) Parse an IESpec into name, pen, number, typename, and length fields ipfix.ie.spec_list(specs) Given a list or iterable of IESpecs, return a hashable list of IEs. Pass this as the ielist argument to the tuple export and iterator functions. Parameters: **specs** -- list of IESpecs Returns: a new Information Element List, suitable for use with the tuple export and iterator functions in "message" Raises : ValueError ipfix.ie.use_5103_default() Load the module internal list of RFC 5103 reverse IEs for IANA registered IEs into the cache of known IEs. Normally, biflow-aware client code should call this just after use_iana_default(). ipfix.ie.use_iana_default() Load the module internal list of IANA registered IEs into the cache of known IEs. Normally, client code should call this before using any other part of this module. ipfix.ie.use_specfile(filename) Load a file listing IESpecs into the cache of known IEs Parameters: **filename** -- name of file containing IESpecs to open Raises : ValueError module ipfix.template ===================== Representation of IPFIX templates. Provides template-based packing and unpacking of data in IPFIX messages. For reading, templates are handled internally. For writing, use "from_ielist()" to create a template. See "ipfix.message" for examples. exception exception ipfix.template.IpfixDecodeError(*args) Raised when decoding a malformed IPFIX message exception exception ipfix.template.IpfixEncodeError(*args) Raised on internal encoding errors, or if message MTU is too small class class ipfix.template.Template(tid=0, iterable=None) An IPFIX Template. A template is an ordered list of IPFIX Information Elements with an ID. append(ie) Append an IE to this Template count() Count IEs in this template decode_from(buf, offset, packplan=None) Decodes a record into a tuple containing values in template order decode_iedict_from(buf, offset, recinf=None) Decodes a record from a buffer into a dict keyed by IE decode_namedict_from(buf, offset, recinf=None) Decodes a record from a buffer into a dict keyed by IE name. decode_tuple_from(buf, offset, recinf=None) Decodes a record from a buffer into a tuple, ordered as the IEs in the InformationElementList given as recinf. encode_iedict_to(buf, offset, rec, recinf=None) Encodes a record from a dict containing values keyed by IE encode_namedict_to(buf, offset, rec, recinf=None) Encodes a record from a dict containing values keyed by IE name encode_template_to(buf, offset, setid) Encodes the template to a buffer. Encodes as a Template if setid is TEMPLATE_SET_ID, as an Options Template if setid is OPTIONS_SET_ID. encode_to(buf, offset, vals, packplan=None) Encodes a record from a tuple containing values in template order encode_tuple_to(buf, offset, rec, recinf=None) Encodes a record from a tuple containing values ordered as the IEs in the InformationElementList given as recinf. If recinf is not given, assumes the tuple contains all IEs in the template in template order. finalize() Compile a default packing plan. Called after append()ing all IEs. fixlen_count() Count of fixed-length IEs in this template before the first variable-length IE; this is the size of the portion of the template which can be encoded/decoded efficiently. packplan_for_ielist(*args, **kwds) Given a list of IEs, devise and cache a packing plan. Used by the tuple interfaces. class class ipfix.template.TemplatePackingPlan(tmpl, indices) Plan to pack/unpack a specific set of indices for a template. Used internally by Templates for efficient encoding and decoding. ipfix.template.decode_template_from(buf, offset, setid) Decodes a template from a buffer. Decodes as a Template if setid is TEMPLATE_SET_ID, as an Options Template if setid is OPTIONS_SET_ID. ipfix.template.from_ielist(tid, ielist) Create a template from a template ID and an information element list (itself available from "ipfix.ie.spec_list()"). Parameters: * **tid** -- Template ID, must be between 256 and 65535. * **ielist** -- List of Information Elements for the Template, see "ipfix.ie.spec_list()". Returns: A new Template, ready to use for writing to a Message module ipfix.message ==================== Provides the MessageBuffer class for encoding and decoding IPFIX Messages. This interface allows direct control over Messages; for reading or writing records automatically from/to streams, see "ipfix.reader" and "ipfix.writer", respectively. To create a message buffer: >>> import ipfix.message >>> msg = ipfix.message.MessageBuffer() >>> msg To prepare the buffer to write records: >>> msg.begin_export(8304) >>> msg Note that the buffer grows to contain the message header. To write records to the buffer, first you'll need a template: >>> import ipfix.ie >>> ipfix.ie.use_iana_default() >>> import ipfix.template >>> tmpl = ipfix.template.from_ielist(256, ... ipfix.ie.spec_list(("flowStartMilliseconds", ... "sourceIPv4Address", ... "destinationIPv4Address", ... "packetDeltaCount"))) >>> tmpl