diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4a38d0d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI + +on: + push: + branches: [master, main, "v0.*"] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.12", "3.13", "3.14"] + + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v5 + with: + python-version: ${{ matrix.python-version }} + - run: uv sync --group dev + - run: uv run ruff check ipfix tests scripts + - run: uv run pytest diff --git a/.gitignore b/.gitignore index 74d5af6..3b37697 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,11 @@ nosetests.xml # Sphinx tempfiles sphinx/_build +# Modern Python tooling +.venv/ +.pytest_cache/ +.ruff_cache/ +__pycache__/ +uv.lock + + diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6dd4abd..0000000 --- a/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -notifications: - email: false - -language: python -python: - - "2.7" - - "3.3" - - "3.4" -install: - - if [[ $TRAVIS_PYTHON_VERSION == 2* ]]; then - pip install functools32; - pip install py2-ipaddress; - pip install pytz; - fi - - pip install doctest-ignore-unicode - - pip install svgwrite - - pip install python-coveralls -script: - - nosetests -after_success: - - coveralls diff --git a/CHANGES.txt b/CHANGES.txt index bfa6acf..deffb86 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -19,4 +19,26 @@ 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) \ No newline at end of file +v0.9.7, 2014-07-04 -- Bugfix (export time and sequence number reversed) + +v0.10.0, 2026-11-22 -- Modernize packaging (pyproject.toml with PEP 639, Python + 3.11+, drop Python 2 compat and vis-package); refresh IANA + IE registry (up to ID 533; note ID 278 renamed from + connectionCountNew to newConnectionDeltaCount, and ID 263 + messageScope changed from unsigned64 to unsigned8) and + RFC 5103 reverse IEs; add unsigned256 (RFC 9740) and + arbitrary-width integer RLE; harden IPFIX and NetFlow v9 + decoders against malformed packets (setlen < 4, zero- + length templates, bounds checks, template set padding, + template withdrawals, unbounded unknown IE cache); fix + varlen-first templates, strict RLE validation and fixed- + length string parse/unparse/resizing, use_integer_ipv4, + IE hashing, accepted_tids caching, empty set emission and + delete_template atomicity, export_record error propagation, + begin_export(0), writer default domain and flush/template + bugs, reader msgcount, and v9pdu Options Templates, stream + version check, and sequence accounting; accept timezone- + aware datetimes on encode/parse/unparse while eliminating + Python 3.12+ deprecation warnings (note: + template_record_hook now also fires on template + withdrawals with tmpl.count() == 0); expand pytest suite. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index 9203697..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -include *.txt -recursive-include docs *.txt \ No newline at end of file diff --git a/README.md b/README.md index 7bfa99a..8d22bd7 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,55 @@ -python-ipfix -============ +# python-ipfix -IPFIX implementation for Python 3.3. +IPFIX (RFC 7011) implementation for Python 3.11+. -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. +This package provides a Python interface to IPFIX message streams, and tools +for building IPFIX Exporting and Collecting Processes. It handles message +framing and deframing, encoding and decoding IPFIX data records using +templates, a bridge between IPFIX abstract data types (ADTs) and native Python +data types, and a read-only NetFlow v9 PDU decoder. -It should work on Python 2.7 as well; your mileage may vary. To install on -Python 2.7, the following additional dependencies must be manually installed: +## Installation -- pip install functools32 -- pip install py2-ipaddress -- pip install pytz +```bash +pip install ipfix +``` + +Requires Python 3.11 or later, with no mandatory runtime dependencies. + +## Quick Start + +```python +import ipfix.ie +import ipfix.message +import ipfix.template + +ipfix.ie.use_iana_default() +ipfix.ie.use_5103_default() + +msg = ipfix.message.MessageBuffer() +msg.begin_export(8304) +tmpl = ipfix.template.for_specs( + 256, + "flowStartMilliseconds", + "sourceIPv4Address", + "destinationIPv4Address", + "packetDeltaCount", +) +msg.add_template(tmpl) +msg.export_ensure_set(256) +``` + +Command-line utilities `ipfix2csv` and `ipfixstat` are installed as console +scripts. + +## Development + +```bash +uv sync --group dev +uv run ruff check ipfix tests scripts +uv run pytest +``` + +## License + +GNU Lesser General Public License v3 or later (LGPLv3+). diff --git a/README.txt b/README.txt deleted file mode 100644 index cd4c37e..0000000 --- a/README.txt +++ /dev/null @@ -1,10 +0,0 @@ -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 -appopriate Python data types. diff --git a/ipfix/__init__.py b/ipfix/__init__.py index 86f0cc8..ce0c781 100644 --- a/ipfix/__init__.py +++ b/ipfix/__init__.py @@ -1,6 +1,5 @@ -# coding: utf8 # -# python-ipfix (c) 2013 Brian Trammell. +# python-ipfix (c) 2013-2026 Brian Trammell. # # Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for # its material support of this effort. @@ -19,10 +18,8 @@ # this program. If not, see . # -from __future__ import unicode_literals - """ -IPFIX implementation for Python 3.3. +IPFIX (RFC 7011) implementation for Python 3.11+. .. moduleauthor:: Brian Trammell @@ -47,14 +44,15 @@ messages, see :mod:`ipfix.message`. In any case, exporters will need to define templates; see :mod:`ipfix.template`. -This module is copyright 2013 Brian Trammell. It is made available under the -terms of the +This module is copyright 2013-2026 Brian Trammell. It is made available under +the terms of the `GNU Lesser General Public License `_, version 3 or, at your option, any later version. """ -from . import types -from . import ie -from . import template -from . import message +from . import ie, message, template, types + +__version__ = "0.10.0" + +__all__ = ["types", "ie", "template", "message", "__version__"] diff --git a/ipfix/cli.py b/ipfix/cli.py new file mode 100644 index 0000000..3d961e9 --- /dev/null +++ b/ipfix/cli.py @@ -0,0 +1,285 @@ +# +# python-ipfix (c) 2013-2026 Brian Trammell. +# +# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for +# its material support of this effort. +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU General Public License along with +# this program. If not, see . +# + +"""Command-line entry points for ipfix2csv and ipfixstat.""" + +import argparse +import bz2 +import csv +import gzip +import socketserver +import sys + +from . import ie, message, reader, v9pdu + + +def _init_ipfix(specfiles=None): + ie.use_iana_default() + ie.use_5103_default() + if specfiles: + for sf in specfiles: + ie.use_specfile(sf) + + +def _open_input(filename, use_gzip=False, use_bzip2=False): + if use_bzip2: + return bz2.open(filename, mode="rb") + if use_gzip: + return gzip.open(filename, mode="rb") + return open(filename, mode="rb") + + +def stream_to_csv(instream, ienames, outstream=None, reader_fn=reader.from_stream): + """Read an IPFIX or NetFlow v9 stream and write selected IEs as CSV.""" + if outstream is None: + outstream = sys.stdout + cols = ie.spec_list(ienames) + r = reader_fn(instream) + w = csv.writer(outstream, dialect="unix") + w.writerow([e.name for e in cols]) + for rec in r.tuple_iterator(cols): + w.writerow([col.unparse(val) for val, col in zip(rec, cols, strict=True)]) + + +def main_ipfix2csv(argv=None): + parser = argparse.ArgumentParser( + description="Convert an IPFIX file or stream to CSV" + ) + parser.add_argument("ienames", metavar="ie", nargs="+", help="column(s) by IE name") + parser.add_argument( + "--spec", "-s", metavar="specfile", action="append", + help="file to load additional IESpecs from", + ) + parser.add_argument( + "--file", "-f", metavar="file", nargs="?", + help="IPFIX file to read (default stdin)", + ) + comp_group = parser.add_mutually_exclusive_group() + comp_group.add_argument( + "--gzip", "-z", action="store_true", + help="Decompress gzip-compressed IPFIX file", + ) + comp_group.add_argument( + "--bzip2", "-j", action="store_true", + help="Decompress bz2-compressed IPFIX file", + ) + parser.add_argument( + "--netflow9", "-9", action="store_true", + help="Decode as NetFlow version 9 instead of IPFIX (with --file or stdin only)", + ) + parser.add_argument( + "--collect", "-c", metavar="transport", nargs="?", + help="run CP on specified transport", + ) + parser.add_argument( + "--bind", "-b", metavar="bind", nargs="?", default="", + help="address to bind to as CP (default all)", + ) + parser.add_argument( + "--port", "-p", metavar="port", nargs="?", type=int, default=4739, + help="port to bind to as CP (default 4739)", + ) + args = parser.parse_args(argv) + + if args.file is None and (args.bzip2 or args.gzip): + raise ValueError("Decompression only supported from file input") + + _init_ipfix(args.spec) + reader_fn = v9pdu.from_stream if args.netflow9 else reader.from_stream + + if args.netflow9 and args.collect: + raise ValueError("NetFlow9 only supported from files or stdin") + + if args.collect == "tcp": + sys.stderr.write( + f"starting TCP CP on {args.bind}:{args.port}; Ctrl-C to stop\n" + ) + sys.stderr.flush() + + class TcpCsvHandler(socketserver.StreamRequestHandler): + def handle(self): + sys.stderr.write(f"connection from {self.client_address}\n") + stream_to_csv(self.rfile, args.ienames) + + with socketserver.TCPServer((args.bind, args.port), TcpCsvHandler) as ss: + ss.serve_forever() + elif args.collect: + raise ValueError( + f"Unsupported transport {args.collect}; must be 'tcp' in this revision" + ) + elif args.file: + with _open_input(args.file, args.gzip, args.bzip2) as f: + stream_to_csv(f, args.ienames, reader_fn=reader_fn) + else: + stream_to_csv(sys.stdin.buffer, args.ienames, reader_fn=reader_fn) + + +class TemplateStatsSession: + """Collect template and dataset statistics over an IPFIX or NetFlow v9 stream.""" + + def __init__(self, instream, netflow9=False): + self._netflow9 = netflow9 + self.templates = {} + self.template_count = {} + self.template_replcount = {} + self.template_setcount = {} + self.template_bytecount = {} + self.missing_setcount = {} + self.missing_bytecount = {} + + if netflow9: + self.r = v9pdu.from_stream(instream) + self.r.template_record_hook = self.handle_template_record + self.r.ignored_data_set_hook = self.handle_data_set + self.r.unknown_data_set_hook = self.handle_unknown_set + else: + self.r = reader.from_stream(instream) + self.r.msg.template_record_hook = self.handle_template_record + self.r.msg.ignored_data_set_hook = self.handle_data_set + self.r.msg.unknown_data_set_hook = self.handle_unknown_set + + def handle_template_record(self, msg, tmpl): + if tmpl.count() == 0: + return + tkey = (msg.odid, tmpl.tid) + if tkey in self.templates: + self.template_count[tkey] += 1 + if not self.templates[tkey].identical_to(tmpl): + self.template_replcount[tkey] += 1 + self.templates[tkey] = tmpl + else: + self.templates[tkey] = tmpl + self.template_count[tkey] = 1 + self.template_replcount[tkey] = 0 + self.template_setcount[tkey] = 0 + self.template_bytecount[tkey] = 0 + + def handle_data_set(self, msg, tmpl, setbuf): + tkey = (msg.odid, tmpl.tid) + self.template_setcount[tkey] += 1 + self.template_bytecount[tkey] += len(setbuf) + + def handle_unknown_set(self, msg, setbuf): + setid, setlen = message._sethdr_st.unpack_from(setbuf) + tkey = (msg.odid, setid) + self.missing_setcount[tkey] = self.missing_setcount.get(tkey, 0) + 1 + self.missing_bytecount[tkey] = self.missing_bytecount.get(tkey, 0) + setlen + + def run(self): + if self._netflow9: + for _ in self.r.record_iterator(tmplaccept_fn=lambda _tmpl: False): + pass + else: + try: + while True: + self.r.msg.read_message(self.r.stream) + self.r.msgcount += 1 + for _ in self.r.msg.record_iterator(tmplaccept_fn=lambda _tmpl: False): + pass + except EOFError: + return + + def print_report(self, outstream=None): + if outstream is None: + outstream = sys.stdout + missing_setcount = self.missing_setcount.copy() + + total_tsets = sum(self.template_count.values()) + total_dsets = sum(self.template_setcount.values()) + total_repl = sum(self.template_replcount.values()) + total_miss = sum(self.missing_setcount.values()) + + outstream.write( + f"#\n# {len(self.templates)} templates, {total_tsets} template sets, " + f"{total_dsets} decodable sets, {total_repl} replacements, " + f"{total_miss} missing sets total\n" + ) + + for tkey in sorted(self.templates.keys()): + odid, _ = tkey + tmpl = self.templates[tkey] + kind = "Options Template" if tmpl.scopecount else "Template" + outstream.write( + f"#\n# {kind} {tmpl.tid} in domain {odid} ({len(tmpl.ies)} IEs)\n#\n" + ) + for i, elem in enumerate(tmpl.ies): + addl = "{scope}" if i < tmpl.scopecount else "" + outstream.write(f"{elem}{addl}\n") + outstream.write( + f"# {self.template_count[tkey]} instances " + f"{self.template_replcount[tkey]} replacements " + f"{self.template_setcount[tkey]} sets " + f"{self.template_bytecount[tkey]} bytes \n" + ) + if tkey in missing_setcount: + outstream.write( + f"# {missing_setcount[tkey]} sets missing template with this ID\n" + ) + del missing_setcount[tkey] + + if missing_setcount: + outstream.write("#\n# Sets without templates\n") + for tkey, count in missing_setcount.items(): + outstream.write( + f"# {count} sets missing template with ID {tkey[1]} in domain {tkey[0]}\n" + ) + + +def main_ipfixstat(argv=None): + parser = argparse.ArgumentParser( + description="Dump statistics about templates and data sets in an IPFIX file" + ) + parser.add_argument( + "--spec", "-s", metavar="specfile", action="append", + help="file to load additional IESpecs from", + ) + parser.add_argument( + "--file", "-f", metavar="file", nargs="?", + help="IPFIX file to read (default stdin)", + ) + comp_group = parser.add_mutually_exclusive_group() + comp_group.add_argument( + "--gzip", "-z", action="store_true", + help="Decompress gzip-compressed IPFIX file", + ) + comp_group.add_argument( + "--bzip2", "-j", action="store_true", + help="Decompress bz2-compressed IPFIX file", + ) + parser.add_argument( + "--netflow9", "-9", action="store_true", + help="Decode as NetFlow version 9 instead of IPFIX", + ) + args = parser.parse_args(argv) + + if args.file is None and (args.bzip2 or args.gzip): + raise ValueError("Decompression only supported from file input") + + _init_ipfix(args.spec) + + if args.file: + with _open_input(args.file, args.gzip, args.bzip2) as f: + tss = TemplateStatsSession(f, args.netflow9) + tss.run() + else: + tss = TemplateStatsSession(sys.stdin.buffer, args.netflow9) + tss.run() + + tss.print_report() diff --git a/ipfix/compat.py b/ipfix/compat.py deleted file mode 100644 index bca0dd3..0000000 --- a/ipfix/compat.py +++ /dev/null @@ -1,75 +0,0 @@ -try: - # Python 3 imports - from datetime import timezone - import urllib.request as urlreq - from functools import lru_cache - - # These will succeed in Python 2, but we won't get here due to - # ImportError from the previous lines. - izip = zip - xrange = range - ifilter = filter - from functools import reduce -except ImportError: - import pytz as timezone - import urllib2 as urlreq - from functools32 import lru_cache - - from itertools import izip, ifilter - xrange = xrange - reduce = reduce - -def _get_memoryview_buffer(bufsize): - return memoryview(bytearray(bufsize)) - - -def _get_fake_memoryview_buffer(bufsize): - return _FakeMemoryView(bufsize) - - -class _FakeMemoryView(bytearray): - """ - Python 2.7.8 has a bug that prevents struct.pack_into from - working with a memoryview: http://bugs.python.org/issue22113 - - This class just acts like a memoryview from the perspective - of the rest of the library (though it lacks the performance benefits). - It can and should go away if this bug gets fixed in a later 2.7 version. - """ - - def __getitem__(self, key): - _slice = bytearray.__getitem__(self, key) - return _FakeMemoryView(_slice) - - def tobytes(self): - return self - - def tolist(self): - return list(self) - -try: - length = 10 - mv = memoryview(bytearray(length)) - mv[0:length] = bytearray([0] * length) - import struct - struct.pack_into("!HLL", mv, 0, 42, 17, 21) - - # if slice assignment succeeded, no bug. - get_buffer = _get_memoryview_buffer -except TypeError: - # slice assignment bug exists. - # return a bytearray with the few extra methods that - # the MessageBuffer wants. Less efficient, but not broken. - get_buffer = _get_fake_memoryview_buffer - - -def _datetime_to_timestamp_by_duration(datetime_): - # from python3 docs - dur = (datetime_ - datetime.datetime(1970, 1, 1, tzinfo=timezone.utc)) - return dur.total_seconds() - -import datetime -if hasattr(datetime.datetime, 'timestamp'): - datetime_to_timestamp = getattr(datetime.datetime, 'timestamp') -else: - datetime_to_timestamp = _datetime_to_timestamp_by_duration diff --git a/ipfix/iana.iespec b/ipfix/iana.iespec index ba268bd..d21596c 100644 --- a/ipfix/iana.iespec +++ b/ipfix/iana.iespec @@ -231,7 +231,7 @@ exportSctpStreamId(259)[2] maxExportSeconds(260)[4] maxFlowEndSeconds(261)[4] messageMD5Checksum(262)[65535] -messageScope(263)[8] +messageScope(263)[1] minExportSeconds(264)[4] minFlowStartSeconds(265)[4] opaqueOctets(266)[65535] @@ -246,7 +246,7 @@ collectorCertificate(274)[65535] exporterCertificate(275)[65535] dataRecordsReliability(276)[1] observationPointType(277)[1] -connectionCountNew(278)[4] +newConnectionDeltaCount(278)[4] connectionSumDurationSeconds(279)[8] connectionTransactionId(280)[8] postNATSourceIPv6Address(281)[16] @@ -396,4 +396,87 @@ layer2OctetTotalSumOfSquares(429)[8] layer2FrameDeltaCount(430)[8] layer2FrameTotalCount(431)[8] pseudoWireDestinationIPv4Address(432)[4] -ignoredLayer2FrameTotalCount(433)[8] \ No newline at end of file +ignoredLayer2FrameTotalCount(433)[8] +mibObjectValueInteger(434)[4] +mibObjectValueOctetString(435)[65535] +mibObjectValueOID(436)[65535] +mibObjectValueBits(437)[65535] +mibObjectValueIPAddress(438)[4] +mibObjectValueCounter(439)[8] +mibObjectValueGauge(440)[4] +mibObjectValueTimeTicks(441)[4] +mibObjectValueUnsigned(442)[4] +mibObjectIdentifier(445)[65535] +mibSubIdentifier(446)[4] +mibIndexIndicator(447)[8] +mibCaptureTimeSemantics(448)[1] +mibContextEngineID(449)[65535] +mibContextName(450)[65535] +mibObjectName(451)[65535] +mibObjectDescription(452)[65535] +mibObjectSyntax(453)[65535] +mibModuleName(454)[65535] +mobileIMSI(455)[65535] +mobileMSISDN(456)[65535] +httpStatusCode(457)[2] +sourceTransportPortsLimit(458)[2] +httpRequestMethod(459)[65535] +httpRequestHost(460)[65535] +httpRequestTarget(461)[65535] +httpMessageVersion(462)[65535] +natInstanceID(463)[4] +internalAddressRealm(464)[65535] +externalAddressRealm(465)[65535] +natQuotaExceededEvent(466)[4] +natThresholdEvent(467)[4] +httpUserAgent(468)[65535] +httpContentType(469)[65535] +httpReasonPhrase(470)[65535] +maxSessionEntries(471)[4] +maxBIBEntries(472)[4] +maxEntriesPerUser(473)[4] +maxSubscribers(474)[4] +maxFragmentsPendingReassembly(475)[4] +addressPoolHighThreshold(476)[4] +addressPoolLowThreshold(477)[4] +addressPortMappingHighThreshold(478)[4] +addressPortMappingLowThreshold(479)[4] +addressPortMappingPerUserHighThreshold(480)[4] +globalAddressMappingHighThreshold(481)[4] +vpnIdentifier(482)[65535] +bgpCommunity(483)[4] +bgpExtendedCommunity(486)[65535] +bgpLargeCommunity(489)[65535] +srhFlagsIPv6(492)[1] +srhTagIPv6(493)[2] +srhSegmentIPv6(494)[16] +srhActiveSegmentIPv6(495)[16] +srhSegmentIPv6ListSection(497)[65535] +srhSegmentsIPv6Left(498)[1] +srhIPv6Section(499)[65535] +srhIPv6ActiveSegmentType(500)[1] +srhSegmentIPv6LocatorLength(501)[1] +srhSegmentIPv6EndpointBehavior(502)[2] +transportChecksum(503)[2] +icmpHeaderPacketSection(504)[65535] +gtpuFlags(505)[1] +gtpuMsgType(506)[1] +gtpuTEid(507)[4] +gtpuSequenceNum(508)[2] +gtpuQFI(509)[1] +gtpuPduType(510)[1] +ipv6ExtensionHeaderType(513)[1] +ipv6ExtensionHeaderCount(514)[1] +ipv6ExtensionHeadersFull(515)[32] +ipv6ExtensionHeadersLimit(517)[1] +ipv6ExtensionHeadersChainLength(518)[4] +tcpOptionsFull(520)[32] +tcpSharedOptionExID16(521)[2] +tcpSharedOptionExID32(522)[4] +udpSafeOptions(525)[32] +udpUnsafeOptions(526)[8] +udpExID(527)[2] +pathDelayMeanDeltaMicroseconds(530)[4] +pathDelayMinDeltaMicroseconds(531)[4] +pathDelayMaxDeltaMicroseconds(532)[4] +pathDelaySumDeltaMicroseconds(533)[8] diff --git a/ipfix/ie.py b/ipfix/ie.py index 1757460..fcbf0d8 100644 --- a/ipfix/ie.py +++ b/ipfix/ie.py @@ -1,5 +1,5 @@ # -# python-ipfix (c) 2013 Brian Trammell. +# python-ipfix (c) 2013-2026 Brian Trammell. # # Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for # its material support of this effort. @@ -20,12 +20,11 @@ """ IESpec-based interface to IPFIX information elements, -and interface to use the default IPFIX IANA Information Model +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: +Section 10.1 of RFC 7013. It has the format: name(pen/num)[size] @@ -34,7 +33,7 @@ >>> import ipfix.ie >>> e = ipfix.ie.for_spec("myNewInformationElement(35566/1)") ->>> e #doctest: +IGNORE_UNICODE +>>> e InformationElement('myNewInformationElement', 35566, 1, ipfix.types.for_name('string'), 65535) The string representation of an InformationElement is its IESpec: @@ -64,40 +63,39 @@ >>> ipfix.ie.for_spec("sourceIPv4Address").parse("192.0.2.19") IPv4Address('192.0.2.19') >>> from datetime import datetime ->>> ipfix.ie.for_spec("flowEndMilliseconds").unparse(datetime(2013,6,21,14)) #doctest: +IGNORE_UNICODE +>>> ipfix.ie.for_spec("flowEndMilliseconds").unparse(datetime(2013, 6, 21, 14)) '2013-06-21 14:00:00.000' - Most client code will only need the :func:`use_iana_default`, :func:`use_5103_default`, and :func:`use_specfile` functions; client code using tuple interfaces will need :func:`spec_list` as well. """ -from __future__ import with_statement, unicode_literals + +import importlib.resources import re -import os.path -from . import types, compat -from .compat import reduce from functools import total_ordering -import operator -from io import open -_iespec_re = re.compile('^([^\s\[\<\(]+)?(\(((\d+)\/)?(\d+)\))?' - '(\<(\S+)\>)?(\[(\S+)\])?') +from . import types + +_iespec_re = re.compile( + r"^([^\s\[\<\(]+)?(\(((\d+)\/)?(\d+)\))?" + r"(\<(\S+)\>)?(\[(\S+)\])?" +) # Internal information element registry _ieForName = {} _ieForNum = {} + def _register_ie(ie): _ieForName[ie.name] = ie _ieForNum[(ie.pen, ie.num)] = ie - return ie @total_ordering -class InformationElement(object): +class InformationElement: """ An IPFIX Information Element (IE). This is essentially a five-tuple of name, element number (num), a private enterprise number (pen; 0 if it @@ -105,51 +103,57 @@ class InformationElement(object): Information Elements may also have value string and parser functions, for representing the values as strings; if not set, these default to + the type's valstr/valparse functions. InformationElement instances should be obtained using the :func:`for_spec` or :func:`for_template_entry` functions. """ - def __init__(self, name, pen, num, ietype=types._roottypes[0], length=None, valstr=None, valparse=None): - if name: - self.name = name - else: - self.name = "_ipfix_%u_%u" % (pen, num) - - if length: - self.length = length - else: - self.length = ietype.length - + def __init__( + self, + name, + pen, + num, + ietype=types._roottypes[0], + length=None, + valstr=None, + valparse=None, + ): + self.name = name if name else f"_ipfix_{pen}_{num}" + self.length = length if length else ietype.length self.pen = pen self.num = num self.type = ietype.for_length(self.length) - self.valparse = valparse self.valstr = valstr def __eq__(self, other): """ Determine if an IE is equal to another IE. - Two IEs are considered equal if they share a PEN, number, and length. - + Two IEs are considered equal if they share a PEN and element number + (regardless of reduced-size encoding length). """ - return ((self.pen, self.num) == (other.pen, other.num)) + if not isinstance(other, InformationElement): + return NotImplemented + return (self.pen, self.num) == (other.pen, other.num) def __lt__(self, other): - return ((self.pen, self.num) < (other.pen, other.num)) + if not isinstance(other, InformationElement): + return NotImplemented + return (self.pen, self.num) < (other.pen, other.num) def __repr__(self): - return "InformationElement(%s, %s, %s, %s, %s)" % (repr(self.name), - repr(self.pen), repr(self.num), repr(self.type), - repr(self.length)) + return ( + f"InformationElement({self.name!r}, {self.pen!r}, {self.num!r}, " + f"{self.type!r}, {self.length!r})" + ) def __str__(self): - return "%s(%u/%u)%s[%u]" % (self.name, self.pen, self.num, str(self.type), self.length) + return f"{self.name}({self.pen}/{self.num}){self.type}[{self.length}]" def __hash__(self): - return ((self.num << 16) + self.length) ^ self.pen + return hash((self.pen, self.num)) def for_length(self, length): """ @@ -160,11 +164,17 @@ def for_length(self, length): :returns: this IE if length matches, or a new IE for the length :raises: ValueError """ - if not length or length == self.length: return self - else: - return self.__class__(self.name, self.pen, self.num, self.type, length) + return self.__class__( + self.name, + self.pen, + self.num, + self.type, + length, + valstr=self.valstr, + valparse=self.valparse, + ) def unparse(self, v): """ @@ -172,15 +182,13 @@ def unparse(self, v): for this Information Element. Uses the default string conversion for the IE's type if not overridden at IE creation time. - :param v: value to unparse using this IEs's string conversion + :param v: value to unparse using this IE's string conversion :returns: string representation of v :raises: ValueError if v is not a valid value for this IE """ - if self.valstr: return self.valstr(v) - else: - return self.type.valstr(v) + return self.type.valstr(v) def parse(self, s): """ @@ -188,27 +196,28 @@ def parse(self, s): for this Information Element. Uses the default string conversion for the IE's type if not overridden at IE creation time. - :param s: string to parse using this IEs's string conversion + :param s: string to parse using this IE's string conversion :returns: value for given string - :raises: ValueError is not a valid string representation for this IE + :raises: ValueError if s is not a valid string representation for this IE """ if self.valparse: return self.valparse(s) - else: - return self.type.valparse(s) + return self.type.valparse(s) @total_ordering -class InformationElementList(object): +class InformationElementList: """ 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 :func:`spec_list` + instance by calling :func:`spec_list`. """ - def __init__(self, iterable = None): + + def __init__(self, iterable=None): self.inner = [] + self.hashcache = None if iterable: for x in iterable: @@ -218,21 +227,24 @@ def __iter__(self): return iter(self.inner) def __eq__(self, other): + if not isinstance(other, InformationElementList): + return NotImplemented return self.inner == other.inner def __lt__(self, other): + if not isinstance(other, InformationElementList): + return NotImplemented return self.inner < other.inner def __repr__(self): - return "InformationElementList(" + ",".join((repr(x) for x in self.inner)) + ")" + return "InformationElementList(" + ",".join(repr(x) for x in self.inner) + ")" def __str__(self): - return "\n".join((str(x) for x in self.inner)) + return "\n".join(str(x) for x in self.inner) def __hash__(self): - if not self.hashcache: - self.hashcache = reduce(operator.xor, (hash(x) for x in self.inner)) - + if self.hashcache is None: + self.hashcache = hash(tuple(self.inner)) return self.hashcache def __len__(self): @@ -248,83 +260,72 @@ def append(self, ie): self.inner.append(ie) self.hashcache = None -def parse_spec(spec): - """Parse an IESpec into name, pen, number, typename, and length fields""" - (name, pen, num, typename, length) = _iespec_re.match(spec).group(1,4,5,7,9) - - if pen: - pen = int(pen) - else: - pen = 0 - if num: - num = int(num) - else: - num = 0 - - if length: - length = int(length) - else: - length = 0 +def parse_spec(spec): + """Parse an IESpec into name, pen, number, typename, and length fields.""" + match = _iespec_re.match(spec) + name, pen, num, typename, length = match.group(1, 4, 5, 7, 9) + pen = int(pen) if pen else 0 + num = int(num) if num else 0 + length = int(length) if length else 0 if not typename: typename = False return (name, pen, num, typename, length) + def for_spec(spec): """ Get an IE from the cache of known IEs, or create a new IE if not found, given an IESpec. - :param spec: IEspec, as in draft-ietf-ipfix-ie-doctors, of the + :param spec: IESpec, as in RFC 7013, 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 - - """ - (name, pen, num, typename, length) = parse_spec(spec) + name, pen, num, typename, length = parse_spec(spec) if not name and not pen and not num and not typename and not length: - raise ValueError("unrecognized IE spec "+spec) + raise ValueError("unrecognized IE spec " + spec) if name and not pen and not num and name in _ieForName: - # lookup in name registry return _ieForName[name].for_length(length) if num and (pen, num) in _ieForNum: - # lookup in number registry return _ieForNum[(pen, num)].for_length(length) # try to create new registered IE if not typename: - raise ValueError("IE "+str(spec)+ - " unknown; use a full IEspec to create a new IE.") + raise ValueError(f"IE {spec} unknown; use a full IEspec to create a new IE.") ietype = types.for_name(typename) - return _register_ie(InformationElement(name, pen, num, ietype, length)) + def 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, + Get an IE from the cache of known IEs, or create an unregistered + octetArray IE if not found, given a private enterprise number, element number, and length. Used internally by Templates. + Unknown IEs are intentionally NOT registered into the global cache + to prevent unbounded memory growth from untrusted network templates. + :param pen: private enterprise number, or 0 for an IANA IE :param num: IE number (Element ID) :param 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. - + been previously added to the cache of known IEs, the IE will be + named _ipfix_pen_num, and have octetArray as a type. """ - if ((pen, num) in _ieForNum): + if (pen, num) in _ieForNum: return _ieForNum[(pen, num)].for_length(length) - return _register_ie(InformationElement(None, pen, num, types.for_name("octetArray"), length)) + return InformationElement(None, pen, num, types.for_name("octetArray"), length) + def spec_list(specs): """ @@ -336,63 +337,57 @@ def spec_list(specs): :returns: a new Information Element List, suitable for use with the tuple export and iterator functions in :mod:`message` :raises: ValueError - """ return InformationElementList(for_spec(spec) for spec in specs) + def clear_infomodel(): """Reset the cache of known Information Elements.""" _ieForName.clear() _ieForNum.clear() + def dump_infomodel(): - return sorted([_ieForNum[x] for x in _ieForNum]) + return sorted(_ieForNum.values()) + + +def _load_spec_stream(stream): + for line in stream: + line = line.strip() + if line and not line.startswith("#"): + for_spec(line) + def use_specfile(filename): """ - Load a file listing IESpecs into the cache of known IEs + Load a file listing IESpecs into the cache of known IEs. - :param filename: name of file containing IESpecs to open + :param filename: path-like object or filename containing IESpecs to open :raises: ValueError - """ - with open(filename) as f: - for line in f: - for_spec(line) + with open(filename, encoding="utf-8") as f: + _load_spec_stream(f) + + +def _use_package_specfile(name): + resource = importlib.resources.files("ipfix").joinpath(name) + with resource.open("r", encoding="utf-8") as f: + _load_spec_stream(f) + def 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. - """ - use_specfile(os.path.join(os.path.dirname(__file__), "iana.iespec")) + _use_package_specfile("iana.iespec") + def 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(). - """ - use_specfile(os.path.join(os.path.dirname(__file__), "rfc5103.iespec")) - -def test_ie_internals(): - # Tests for full statement coverage of the ipfix.ie module - # (not already covered in doctest or elsewhere) - la = InformationElementList([InformationElement(None, 35566, 9999, length=1)]) - lb = InformationElementList([InformationElement(None, 35566, 9999, length=4)]) - lc = InformationElementList([InformationElement(None, 35566, 9998)]) - - assert la[0].name == "_ipfix_35566_9999" - assert la == lb - assert la > lc - - try: - for_spec("not a spec") - assert False - except ValueError as e: - pass - - assert for_template_entry(35566,9999,4) == InformationElement(None, 35566, 9999, length=4) + _use_package_specfile("rfc5103.iespec") diff --git a/ipfix/ieutils.py b/ipfix/ieutils.py index e5da51f..e4c775e 100644 --- a/ipfix/ieutils.py +++ b/ipfix/ieutils.py @@ -1,5 +1,5 @@ # -# python-ipfix (c) 2013 Brian Trammell. +# python-ipfix (c) 2013-2026 Brian Trammell. # # Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for # its material support of this effort. @@ -18,56 +18,113 @@ # this program. If not, see . # -from __future__ import with_statement +""" +Utilities for generating IESpec files from the IANA IPFIX Information Elements +registry (CSV or XML) and deriving RFC 5103 reverse Information Elements. +""" + +import csv +import io +import urllib.request as urlreq import xml.etree.ElementTree as etree -from warnings import warn -from . import types, ie, compat -from .compat import urlreq -from io import open +from . import ie, types + +IANA_CSV_URI = "https://www.iana.org/assignments/ipfix/ipfix-information-elements.csv" +IANA_XML_URI = "https://www.iana.org/assignments/ipfix/ipfix.xml" + +# RFC 5103 §6.1: Information Elements that are not reversible (flow-key directional +# identifiers, scope identifiers, etc.) +_NON_REVERSIBLE_SUBSTRINGS = ("Source", "Destination", "source", "destination") +_NON_REVERSIBLE_NAMES = frozenset({"messageScope"}) + + +def is_reversible_ie(name): + """Return True if an IANA IE name is eligible for an RFC 5103 reverse counterpart.""" + if name in _NON_REVERSIBLE_NAMES: + return False + return not any(tok in name for tok in _NON_REVERSIBLE_SUBSTRINGS) + -def iana_xml_to_iespec(uri = "http://www.iana.org/assignments/ipfix/ipfix.xml"): +def parse_iana_csv(csv_file): + """Parse an open text file/stream of the IANA IPFIX IE CSV into IESpec strings.""" iespecs = [] + reader = csv.DictReader(csv_file) + for row in reader: + name = (row.get("Name") or "").strip() + typename = (row.get("Abstract Data Type") or "").strip() + num = (row.get("ElementID") or "").strip() + if not (name and typename and num.isdigit()): + continue + try: + ietype = types.for_name(typename) + except types.IpfixTypeError: + # Skip types not yet implemented (e.g. RFC 6313 structured data) + continue + iespecs.append(f"{name}({int(num)})<{ietype.name}>[{ietype.length}]") + return iespecs + - nsmap = { "iana" : "http://www.iana.org/assignments" } +def iana_csv_to_iespec(uri=IANA_CSV_URI): + """Fetch the IANA IPFIX IE CSV over HTTPS and return a list of IESpec strings.""" + with urlreq.urlopen(uri) as res: + text = io.TextIOWrapper(res, encoding="utf-8") + return parse_iana_csv(text) - res = urlreq.urlopen(uri) - root = etree.parse(res).getroot() - for recelem in root.iterfind("iana:registry[@id='ipfix-information-elements']/iana:record", nsmap): - (name, typename, num) = (None, None, None) - for fieldelem in recelem.iter(): - if fieldelem.tag[-4:] == "name": - name = fieldelem.text - elif fieldelem.tag[-8:] == "dataType": - typename = fieldelem.text - elif fieldelem.tag[-9:] == "elementId": - num = fieldelem.text +def parse_iana_xml(xml_file): + """Parse an open binary/text file of the IANA IPFIX XML into IESpec strings.""" + iespecs = [] + ns = "http://www.iana.org/assignments" + nsmap = {"iana": ns} + tag_name = f"{{{ns}}}name" + tag_datatype = f"{{{ns}}}dataType" + tag_element_id = f"{{{ns}}}elementId" + root = etree.parse(xml_file).getroot() + for recelem in root.iterfind( + "iana:registry[@id='ipfix-information-elements']/iana:record", nsmap + ): + name = typename = num = None + for fieldelem in recelem: + if fieldelem.tag == tag_name: + name = (fieldelem.text or "").strip() + elif fieldelem.tag == tag_datatype: + typename = (fieldelem.text or "").strip() + elif fieldelem.tag == tag_element_id: + num = (fieldelem.text or "").strip() - if name and typename and num: + if name and typename and num and num.isdigit(): try: ietype = types.for_name(typename) - iespecs.append("%s(%u)<%s>[%u]" % (name, int(num), ietype.name, ietype.length)) - except: - pass + except types.IpfixTypeError: + continue + iespecs.append(f"{name}({int(num)})<{ietype.name}>[{ietype.length}]") return iespecs +def iana_xml_to_iespec(uri=IANA_XML_URI): + """Fetch the IANA IPFIX XML over HTTPS and return a list of IESpec strings.""" + with urlreq.urlopen(uri) as res: + return parse_iana_xml(res) + + def reverse_iespec(iespec): - (name, pen, num, typename, length) = ie.parse_spec(iespec) - revname = "reverse" + name[0].capitalize() + name[1:] + """Generate the RFC 5103 reverse counterpart IESpec for a given IESpec.""" + name, pen, num, typename, length = ie.parse_spec(iespec) + revname = "reverse" + name[0].upper() + name[1:] if pen: num |= 0x4000 else: pen = 29305 - return "%s(%u/%u)<%s>[%u]" % (revname, pen, num, typename, length) + return f"{revname}({pen}/{num})<{typename}>[{length}]" def write_specfile(filename, iespecs): - with open(filename, "w") as f: + """Write a sequence of IESpec strings to a file, one per line.""" + with open(filename, "w", encoding="utf-8") as f: for spec in iespecs: f.write(spec) f.write("\n") diff --git a/ipfix/message.py b/ipfix/message.py index 0af2fad..56d75fe 100644 --- a/ipfix/message.py +++ b/ipfix/message.py @@ -1,6 +1,5 @@ -# coding: utf8 # -# python-ipfix (c) 2013 Brian Trammell. +# python-ipfix (c) 2013-2026 Brian Trammell. # # Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for # its material support of this effort. @@ -28,7 +27,6 @@ To create a message buffer: ->>> from __future__ import unicode_literals >>> import ipfix.message >>> msg = ipfix.message.MessageBuffer() >>> msg @@ -96,7 +94,7 @@ Variable-length information elements will be encoded using the native length of the passed value: ->>> ipfix.ie.for_spec("myNewInformationElement(35566/1)") #doctest: +IGNORE_UNICODE +>>> ipfix.ie.for_spec("myNewInformationElement(35566/1)") InformationElement('myNewInformationElement', 35566, 1, ipfix.types.for_name('string'), 65535) >>> tmpl = ipfix.template.from_ielist(257, ... ipfix.ie.spec_list(("flowStartMilliseconds", @@ -152,7 +150,7 @@ ... for key, value in unicode_recs: ... print("{}: {}".format(key, value)) ... ->>> print_msg(msg) #doctest: +IGNORE_UNICODE +>>> print_msg(msg) [('destinationIPv4Address', IPv4Address('10.5.6.7')), ('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0)), ('packetDeltaCount', 27), ('sourceIPv4Address', IPv4Address('10.1.2.3'))] [('destinationIPv4Address', IPv4Address('10.12.13.14')), ('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, 2)), ('packetDeltaCount', 33), ('sourceIPv4Address', IPv4Address('10.8.9.11'))] [('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, 4))] @@ -172,7 +170,7 @@ (datetime.datetime(2013, 6, 21, 14, 0), 27) (datetime.datetime(2013, 6, 21, 14, 0, 2), 33) -Notice that the variable-length record written to the message are not returned +Notice that the variable-length record written to the message is not returned by this iterator, since that record doesn't include a packetDeltaCount IE. The record is, however, still there: @@ -184,41 +182,64 @@ """ -from __future__ import unicode_literals -from . import template, types, compat -from .template import IpfixEncodeError, IpfixDecodeError -from .compat import timezone, ifilter, reduce - import io -import operator import struct -from datetime import datetime +from datetime import UTC, datetime from warnings import warn +from . import template, types +from .template import EndOfMessage, IpfixDecodeError, IpfixEncodeError + _sethdr_st = struct.Struct("!HH") _msghdr_st = struct.Struct("!HHLLL") -class EndOfMessage(Exception): - """ - Exception raised when a write operation on a Message - fails because there is not enough space in the message. - - """ - def __init__(self, *args): - super(self.__class__, self).__init__(args) def accept_all_templates(tmpl): return True -class MessageBuffer(object): + +def _is_zero_padding(buf, start, end): + return all(b == 0 for b in buf[start:end]) + + +def _iter_template_set_records(buf, offset, setend, setid, *, v9=False): + setview = buf[:setend] + label = "v9 template set" if v9 else "template set" + while offset < setend: + rem = setend - offset + # RFC 7011 §3.3.1: alignment padding at end of Template Set + if rem < template._tmplhdr_st.size: + if _is_zero_padding(buf, offset, setend): + break + raise IpfixDecodeError(f"Non-zero trailing bytes ({rem}) in {label}") + if ( + buf[offset] == 0 + and buf[offset + 1] == 0 + and _is_zero_padding(buf, offset, setend) + ): + break + + tmpl, offset = template.decode_template_from( + setview, offset, setid, setend=setend + ) + yield tmpl + + +def _recache_all_accepted_tids(templates, accepted_tids, tmplaccept_fn): + accepted_tids.clear() + for key, tmpl in templates.items(): + if tmplaccept_fn(tmpl): + accepted_tids.add(key) + + +class MessageBuffer: """ Implements a buffer for reading or writing IPFIX messages. - """ + def __init__(self, buf_sz=65536): """Create a new MessageBuffer instance.""" - - self.mbuf = compat.get_buffer(bytearray(buf_sz)) + self.mbuf = memoryview(bytearray(buf_sz)) self.length = 0 self.sequence = None self.export_epoch = None @@ -237,8 +258,9 @@ def __init__(self, buf_sz=65536): self.curtmpl = None self.last_tuple_iterator_ielist = None + self._accepted_cache_key = None - self.mtu = 65535 + self.mtu = min(65535, buf_sz) self.template_record_hook = None self.unknown_data_set_hook = None @@ -247,27 +269,25 @@ def __init__(self, buf_sz=65536): def __repr__(self): if self.cursetid: - addinf = " (writing set "+str(self.cursetid)+")" + addinf = f" (writing set {self.cursetid})" elif self.setlist: - addinf = " (deframed "+str(len(self.setlist))+" sets)" + addinf = f" (deframed {len(self.setlist)} sets)" elif self.length: addinf = " (writing)" else: addinf = "" - return "" + return f"" def get_export_time(self): """ Return the export time of this message. When reading, returns the export time as read from the message header. When writing, this is the argument of the last call to :meth:`set_export_time`, or, if - :attr:auto_export_time is True, the time of the last message + :attr:`auto_export_time` is True, the time of the last message export. :returns: export time of the last message read/written. - """ return types._decode_sec(self.export_epoch) @@ -277,17 +297,16 @@ def set_export_time(self, dt=None): :meth:`write_message` or :meth:`to_bytes`. Disables automatic export time updates. By default, sets the export time to the current time. - :param dt: export time to set, as a datetime - + :param dt: export time to set, as a datetime (aware or naive UTC) """ - if not dt: - dt = datetime.utcnow() + if dt is None: + dt = datetime.now(UTC) self.export_epoch = types._encode_sec(dt) self.auto_export_time = False def _increment_sequence(self): - self.sequences.setdefault((self.odid, self.streamid), 0) - self.sequences[(self.odid, self.streamid)] += 1 + key = (self.odid, self.streamid) + self.sequences[key] = (self.sequences.get(key, 0) + 1) & 0xFFFFFFFF def _scan_setlist(self): # We've read a message. Discard all export state. @@ -299,54 +318,55 @@ def _scan_setlist(self): self.setlist = [] offset = _msghdr_st.size - while (offset < self.length): - (setid, setlen) = _sethdr_st.unpack_from(self.mbuf, offset) + while offset < self.length: + if offset + _sethdr_st.size > self.length: + raise IpfixDecodeError("Truncated set header at end of message") + setid, setlen = _sethdr_st.unpack_from(self.mbuf, offset) + if setlen < _sethdr_st.size: + raise IpfixDecodeError(f"Illegal set length {setlen} (must be >= 4)") if offset + setlen > self.length: raise IpfixDecodeError("Set too long for message") self.setlist.append((offset, setid, setlen)) offset += setlen def read_message(self, stream): - """Read a IPFIX message from a stream. + """Read an IPFIX message from a stream. This populates message header fields and the internal setlist. Call for each new message before iterating over records when reading from a stream. :param stream: stream to read from - :raises: IpfixDecodeError - + :raises: IpfixDecodeError, EOFError """ - # deframe and parse message header msghdr = stream.read(_msghdr_st.size) - if (len(msghdr) == 0): + if len(msghdr) == 0: raise EOFError() - elif (len(msghdr) < _msghdr_st.size): - raise IpfixDecodeError("Short read in message header ("+ - str(len(msghdr)) +")") + if len(msghdr) < _msghdr_st.size: + raise IpfixDecodeError(f"Short read in message header ({len(msghdr)})") - self.mbuf[0:_msghdr_st.size] = msghdr - (version, self.length, self.export_epoch, self.sequence, self.odid) = \ - _msghdr_st.unpack_from(self.mbuf, 0) + self.mbuf[0 : _msghdr_st.size] = msghdr + (version, self.length, self.export_epoch, self.sequence, self.odid) = ( + _msghdr_st.unpack_from(self.mbuf, 0) + ) # verify version and length if version != 10: - raise IpfixDecodeError("Illegal or unsupported version " + - str(version)) + raise IpfixDecodeError(f"Illegal or unsupported version {version}") - if self.length < 20: - raise IpfixDecodeError("Illegal message length" + - str(self.length)) + if self.length < 20 or self.length > len(self.mbuf): + raise IpfixDecodeError(f"Illegal message length {self.length}") # read the rest of the message into the buffer - msgbody = stream.read(self.length-_msghdr_st.size) - if len(msgbody) < self.length - _msghdr_st.size: - raise IpfixDecodeError("Short read in message body (got "+ - str(len(msgbody))+", expected "+ - str(self.length - _msghdr_st.size)+")") - self.mbuf[_msghdr_st.size:self.length] = msgbody - + bodylen = self.length - _msghdr_st.size + msgbody = stream.read(bodylen) + if len(msgbody) < bodylen: + raise IpfixDecodeError( + f"Short read in message body (got {len(msgbody)}, expected {bodylen})" + ) + self.mbuf[_msghdr_st.size : self.length] = msgbody + # call the message header hook if self.message_header_hook: self.message_header_hook(self) @@ -354,24 +374,92 @@ def read_message(self, stream): # populate setlist self._scan_setlist() - def from_bytes(self, str_): + def from_bytes(self, data): """ - Read an IPFIX message from a byte array. + Read an IPFIX message from a bytes-like object. This populates message header fields and the internal setlist. Call for each new message before iterating over records when reading from a byte array. - :param bytes: a byte array containing a complete IPFIX message. + :param data: a bytes-like object containing a complete IPFIX message. :raises: IpfixDecodeError - """ - return self.read_message(io.BytesIO(str_)) - - def record_iterator(self, - decode_fn=template.Template.decode_namedict_from, - tmplaccept_fn=accept_all_templates, - recinf=None): + return self.read_message(io.BytesIO(data)) + + def _handle_template_withdrawal(self, setid, tid): + if tid == setid: + # All-Templates Withdrawal (RFC 7011 §8.1) + to_delete = [ + k + for k, t in self.templates.items() + if k[0] == self.odid and t.native_setid() == setid + ] + for k in to_delete: + del self.templates[k] + self.accepted_tids.discard(k) + else: + key = (self.odid, tid) + self.templates.pop(key, None) + self.accepted_tids.discard(key) + + def _iter_records(self, decode_fn, tmplaccept_fn, recinf): + for offset, setid, setlen in self.setlist: + setend = offset + setlen + setview = self.mbuf[:setend] + offset += _sethdr_st.size # skip set header in decode + if setid in (template.TEMPLATE_SET_ID, template.OPTIONS_SET_ID): + for tmpl in _iter_template_set_records( + self.mbuf, offset, setend, setid, v9=False + ): + if tmpl.count() == 0: + self._handle_template_withdrawal(setid, tmpl.tid) + else: + key = (self.odid, tmpl.tid) + self.templates[key] = tmpl + if tmplaccept_fn(tmpl): + self.accepted_tids.add(key) + else: + self.accepted_tids.discard(key) + + if self.template_record_hook: + self.template_record_hook(self, tmpl) + + elif setid < 256: + warn("skipping illegal set id " + str(setid), stacklevel=2) + else: + key = (self.odid, setid) + try: + tmpl = self.templates[key] + except KeyError: + if self.unknown_data_set_hook: + self.unknown_data_set_hook( + self, self.mbuf[offset - _sethdr_st.size : setend] + ) + continue + + if key in self.accepted_tids: + if tmpl.minlength <= 0: + raise IpfixDecodeError( + f"Template {tmpl.tid} has zero minimum record length" + ) + while offset + tmpl.minlength <= setend: + rec, offset = decode_fn( + tmpl, setview, offset, recinf=recinf + ) + yield rec + self._increment_sequence() + elif self.ignored_data_set_hook: + self.ignored_data_set_hook( + self, tmpl, self.mbuf[offset - _sethdr_st.size : setend] + ) + + def record_iterator( + self, + decode_fn=template.Template.decode_namedict_from, + tmplaccept_fn=accept_all_templates, + recinf=None, + ): """ Low-level interface to record iteration. @@ -379,7 +467,7 @@ def record_iterator(self, :meth:`read_message()` or :meth:`from_bytes()`. Automatically handles templates in set order. By default, iterates over each record in the stream as a dictionary mapping IE name to value - (i.e., the same as :meth:`namedict_iterator`) + (i.e., the same as :meth:`namedict_iterator`). :param decode_fn: Function used to decode a record; must be an (unbound) "decode" instance method of the @@ -391,46 +479,17 @@ def record_iterator(self, will be skipped. :param recinf: Record information opaquely passed to decode function :returns: an iterator over records decoded by decode_fn. - """ - for (offset, setid, setlen) in self.setlist: - setend = offset + setlen - offset += _sethdr_st.size # skip set header in decode - if setid == template.TEMPLATE_SET_ID or\ - setid == template.OPTIONS_SET_ID: - while offset < setend: - (tmpl, offset) = template.decode_template_from( - self.mbuf, offset, setid) - # FIXME handle withdrawal - self.templates[(self.odid, tmpl.tid)] = tmpl - if tmplaccept_fn(tmpl): - self.accepted_tids.add((self.odid, tmpl.tid)) - else: - self.accepted_tids.discard((self.odid, tmpl.tid)) + if tmplaccept_fn is accept_all_templates: + if self._accepted_cache_key != "all": + self._recache_accepted_tids(accept_all_templates) + self._accepted_cache_key = "all" + self.last_tuple_iterator_ielist = None + else: + self._recache_accepted_tids(tmplaccept_fn) + self._accepted_cache_key = None - if self.template_record_hook: - self.template_record_hook(self, tmpl) - - elif setid < 256: - warn("skipping illegal set id "+str(setid)) - else: - try: - tmpl = self.templates[(self.odid, setid)] - if (self.odid, setid) in self.accepted_tids: - while offset + tmpl.minlength <= setend: - (rec, offset) = decode_fn(tmpl, self.mbuf, offset, - recinf = recinf) - yield rec - self._increment_sequence() - elif self.ignored_data_set_hook: - # not in accepted tids - ignored data set - self.ignored_data_set_hook(self, tmpl, - self.mbuf[offset-_sethdr_st.size:setend]) - except KeyError as e: - if self.unknown_data_set_hook: - # KeyError on template lookup - unknown data set - self.unknown_data_set_hook(self, - self.mbuf[offset-_sethdr_st.size:setend]) + return self._iter_records(decode_fn, tmplaccept_fn, recinf) def namedict_iterator(self): """ @@ -438,18 +497,17 @@ def namedict_iterator(self): to values. :returns: a name dictionary iterator - """ - - return self.record_iterator( - decode_fn = template.Template.decode_namedict_from) + if self._accepted_cache_key != "all": + self._recache_accepted_tids(accept_all_templates) + self._accepted_cache_key = "all" + self.last_tuple_iterator_ielist = None + return self._iter_records( + template.Template.decode_namedict_from, accept_all_templates, None + ) def _recache_accepted_tids(self, tmplaccept_fn): - for tid in self.active_template_ids(): - if tmplaccept_fn(self.templates[(self.odid, tid)]): - self.accepted_tids.add((self.odid, tid)) - else: - self.accepted_tids.discard((self.odid, tid)) + _recache_all_accepted_tids(self.templates, self.accepted_tids, tmplaccept_fn) def tuple_iterator(self, ielist): """ @@ -459,46 +517,47 @@ def tuple_iterator(self, ielist): :param ielist: an instance of :class:`ipfix.ie.InformationElementList` listing IEs to return as a tuple :returns: a tuple iterator for tuples as in ielist order - """ + def tmplaccept_fn(tmpl): + return all(elem in tmpl.ies for elem in ielist) - tmplaccept_fn = lambda tmpl: \ - reduce(operator.__and__, - (ie in tmpl.ies for ie in ielist)) - - if ((not self.last_tuple_iterator_ielist) or - (ielist is not self.last_tuple_iterator_ielist)): - self._recache_accepted_tids(tmplaccept_fn) + cache_key = tuple(ielist) + if self._accepted_cache_key != cache_key: + self._recache_accepted_tids(tmplaccept_fn) + self._accepted_cache_key = cache_key self.last_tuple_iterator_ielist = ielist - return self.record_iterator( - decode_fn = template.Template.decode_tuple_from, - tmplaccept_fn = tmplaccept_fn, - recinf = ielist) + return self._iter_records( + template.Template.decode_tuple_from, tmplaccept_fn, ielist + ) def to_bytes(self): """ - Convert this MessageBuffer to a byte array, suitable for writing + Convert this MessageBuffer to a bytes object, suitable for writing to a binary file, socket, or datagram. Finalizes the message by - rewriting the message header with current length, and export time. - - :returns: message as a byte array + rewriting the message header with current length and export time. + :returns: message as bytes """ - # Close final set self._export_close_set() # Update export time if necessary if self.auto_export_time: - dt = datetime.utcnow().replace(tzinfo=timezone.utc) - self.export_epoch = int(compat.datetime_to_timestamp(dt)) + self.export_epoch = int(datetime.now(UTC).timestamp()) # Update message header in buffer - _msghdr_st.pack_into(self.mbuf, 0, 10, self.length, - self.export_epoch, self.sequence, self.odid) - - return self.mbuf[0:self.length].tobytes() + _msghdr_st.pack_into( + self.mbuf, + 0, + 10, + self.length, + self.export_epoch, + self.sequence, + self.odid, + ) + + return self.mbuf[0 : self.length].tobytes() def write_message(self, stream): """ @@ -517,6 +576,7 @@ def add_template(self, tmpl, export=True): :raises: EndOfMessage """ self.templates[(self.odid, tmpl.tid)] = tmpl + self._accepted_cache_key = None if export: self.export_template(tmpl.tid) @@ -530,14 +590,17 @@ def delete_template(self, tid, export=True): :param tid: ID of the template to delete :param export: if True, export a Template Withdrawal for this - Template after deleting it - :raises: EndOfMessage - + Template before deleting it + :raises: EndOfMessage, KeyError """ - setid = self.templates[self.odid, tid].native_setid() - del(self.templates[self.odid, tid]) + key = (self.odid, tid) + setid = self.templates[key].native_setid() if export: - self.export_template_withdrawal(setid, tid) + self._export_template_withdrawal(setid, tid) + elif self.cursetid == tid: + self._export_close_set() + del self.templates[key] + self.accepted_tids.discard(key) def active_template_ids(self): """ @@ -546,10 +609,10 @@ def active_template_ids(self): multiple Messages. :returns: a template ID iterator - """ - for tk in ifilter(lambda k: k[0] == self.odid, self.templates): - yield tk[1] + for odid, tid in self.templates: + if odid == self.odid: + yield tid def template_for_id(self, tid): """ @@ -558,7 +621,6 @@ def template_for_id(self, tid): :param tid: template ID to get :returns: the template :raises: KeyError - """ return self.templates[(self.odid, tid)] @@ -573,29 +635,28 @@ def begin_export(self, odid=None): templates will need to be added after switching to a new observation domain ID. :raises: IpfixEncodeError - """ # We're exporting. Clear setlist from any previously read message. self.setlist = [] - # Set sequence number - self.sequences.setdefault((self.odid, self.streamid), 0) # FIXME why do we need this? - self.sequence = self.sequences[(self.odid, self.streamid)] - - # set new domain if necessary - if odid: + # Set new domain before looking up sequence number + if odid is not None: self.odid = odid + # Set sequence number for current domain/stream + self.sequence = self.sequences.setdefault((self.odid, self.streamid), 0) + # reset message and zero header self.length = _msghdr_st.size self.cursetoff = self.length - self.mbuf[0:_msghdr_st.size] = bytearray([0] * _msghdr_st.size) + self.mbuf[0 : _msghdr_st.size] = bytes(_msghdr_st.size) if self.mtu <= self.length: - raise IpfixEncodeError("MTU too small: "+str(self.mtu)) + raise IpfixEncodeError("MTU too small: " + str(self.mtu)) # no current set self.cursetid = None + self.curtmpl = None def export_new_set(self, setid): """ @@ -605,19 +666,19 @@ def export_new_set(self, setid): :param setid: Set ID of the new Set; corresponds to the Template ID of the Template that will be used to encode records into the - Set. The require Template must have already been added + Set. The required Template must have already been added to the MessageBuffer, see :meth:`add_template`. :raises: IpfixEncodeError, EndOfMessage - """ # close current set if any self._export_close_set() if setid >= 256: # make sure we have a template for the set - if not ((self.odid, setid) in self.templates): - raise IpfixEncodeError("can't start set without template id " + - str(setid)) + if (self.odid, setid) not in self.templates: + raise IpfixEncodeError( + "can't start set without template id " + str(setid) + ) # make sure we have room to export at least one record tmpl = self.templates[(self.odid, setid)] @@ -625,6 +686,8 @@ def export_new_set(self, setid): raise EndOfMessage() else: # special Set ID. no template + if self.length + _sethdr_st.size > self.mtu: + raise EndOfMessage() tmpl = None # set up new set @@ -637,14 +700,13 @@ def export_new_set(self, setid): def export_ensure_set(self, setid): """ Ensure that the current set for export has the given Set ID. - Starts a new set if not using :meth:`export_new_set` + Starts a new set if not using :meth:`export_new_set`. :param setid: Set ID of the new Set; corresponds to the Template ID of the Template that will be used to encode records into the - Set. The require Template must have already been added + Set. The required Template must have already been added to the MessageBuffer, see :meth:`add_template`. :raises: IpfixEncodeError, EndOfMessage - """ if self.cursetid != setid: self.export_new_set(setid) @@ -652,20 +714,32 @@ def export_ensure_set(self, setid): def export_needs_flush(self): """ True if content has been written to this MessageBuffer since the - last call to :meth:`begin_export` - + last call to :meth:`begin_export`. """ - # FIXME we don't prewrite a set, do we? - if self.length <= _msghdr_st.size + _sethdr_st.size: - return False - else: - return True + return self.length > _msghdr_st.size + _sethdr_st.size def _export_close_set(self): - if self.cursetid: - _sethdr_st.pack_into(self.mbuf, self.cursetoff, - self.cursetid, self.length - self.cursetoff) + if self.cursetid is not None: + if self.length == self.cursetoff + _sethdr_st.size: + self.length = self.cursetoff + else: + _sethdr_st.pack_into( + self.mbuf, + self.cursetoff, + self.cursetid, + self.length - self.cursetoff, + ) self.cursetid = None + self.curtmpl = None + + def _effective_length_for_set(self, setid): + if ( + self.cursetid is not None + and self.cursetid != setid + and self.length == self.cursetoff + _sethdr_st.size + ): + return self.cursetoff + return self.length def export_template(self, tid): """ @@ -674,31 +748,41 @@ def export_template(self, tid): :param tid: ID of template to export; must have been added to this message previously with :meth:`add_template`. :raises: EndOfMessage, KeyError - """ - tmpl = self.templates[(self.odid, tid)] + setid = tmpl.native_setid() + hdrlen = ( + template._otmplhdr_st.size + if setid == template.OPTIONS_SET_ID + else template._tmplhdr_st.size + ) + sethdr_needed = 0 if self.cursetid == setid else _sethdr_st.size + base_len = self._effective_length_for_set(setid) + + if base_len + sethdr_needed + hdrlen + tmpl.enclength > self.mtu: + raise EndOfMessage() - self.export_ensure_set(tmpl.native_setid()) - - if self.length + tmpl.enclength > self.mtu: - raise EndOfMessage - - self.length = tmpl.encode_template_to(self.mbuf, self.length, - tmpl.native_setid()) + self.export_ensure_set(setid) + self.length = tmpl.encode_template_to(self.mbuf, self.length, setid) def _export_template_withdrawal(self, setid, tid): - self.export_ensure_set(setid) + sethdr_needed = 0 if self.cursetid == setid else _sethdr_st.size + base_len = self._effective_length_for_set(setid) - if self.length + template.withdrawal_length(setid) > self.mtu: - raise EndOfMessage + if base_len + sethdr_needed + template.withdrawal_length(setid) > self.mtu: + raise EndOfMessage() - self.length = template.encode_withdrawal_to(self.mbuf, self.length, - setid, tid) + self.export_ensure_set(setid) + self.length = template.encode_withdrawal_to( + self.mbuf, self.length, setid, tid + ) - def export_record(self, rec, - encode_fn=template.Template.encode_namedict_to, - recinf = None): + def export_record( + self, + rec, + encode_fn=template.Template.encode_namedict_to, + recinf=None, + ): """ Low-level interface to record export. @@ -711,17 +795,20 @@ def export_record(self, rec, :param encode_fn: Function used to encode a record; must be an (unbound) "encode" instance method of the :class:`ipfix.template.Template` class. - :param recinf: Record information opaquely passed to decode function - :raises: EndOfMessage - + :param recinf: Record information opaquely passed to encode function + :raises: EndOfMessage, IpfixEncodeError """ + if self.curtmpl is None: + raise IpfixEncodeError("no active data set for record export") savelength = self.length try: - self.length = encode_fn(self.curtmpl, self.mbuf, self.length, rec, recinf) - except struct.error: # out of bounds on the underlying mbuf + self.length = encode_fn( + self.curtmpl, self.mbuf, self.length, rec, recinf + ) + except Exception: self.length = savelength - raise EndOfMessage() + raise # check for mtu overrun if self.length > self.mtu: @@ -739,7 +826,6 @@ def export_namedict(self, rec): :param rec: the record to export, as a dictionary :raises: EndOfMessage - """ self.export_record(rec, template.Template.encode_namedict_to) @@ -750,6 +836,5 @@ def export_tuple(self, rec): :param rec: the record to export, as a tuple in template order. :raises: EndOfMessage - """ self.export_record(rec, template.Template.encode_tuple_to) diff --git a/ipfix/reader.py b/ipfix/reader.py index 7dcaae4..c855344 100644 --- a/ipfix/reader.py +++ b/ipfix/reader.py @@ -1,5 +1,5 @@ # -# python-ipfix (c) 2013 Brian Trammell. +# python-ipfix (c) 2013-2026 Brian Trammell. # # Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for # its material support of this effort. @@ -20,12 +20,12 @@ """ Interface to read IPFIX Messages from a stream. - """ from . import message -class MessageStreamReader(object): + +class MessageStreamReader: """ Reads records from a stream of IPFIX messages. @@ -34,10 +34,10 @@ class MessageStreamReader(object): until the end of the stream. Use :func:`from_stream` to get an instance. Suitable for reading from IPFIX files (see :rfc:`5655`) as well as from - UDP or TCP sockets with :class:`socketserver.StreamRequestHandler`. + TCP sockets with :class:`socketserver.StreamRequestHandler`. When opening a stream from a file, use mode='rb'. - """ + def __init__(self, stream): self.stream = stream self.msg = message.MessageBuffer() @@ -49,14 +49,12 @@ def namedict_iterator(self): to values. :returns: a name dictionary iterator - """ try: - while(True): + while True: self.msg.read_message(self.stream) - for name in self.msg.namedict_iterator(): - yield name - self.msgcount += 1 + self.msgcount += 1 + yield from self.msg.namedict_iterator() except EOFError: return @@ -67,23 +65,22 @@ def tuple_iterator(self, ielist): :param ielist: an instance of :class:`ipfix.ie.InformationElementList` listing IEs to return as a tuple - :returns: a tuple iterator for tuples in ielist order + :returns: a tuple iterator for tuples as in ielist order """ try: - while(True): + while True: self.msg.read_message(self.stream) - for tuple_ in self.msg.tuple_iterator(ielist): - yield tuple_ - self.msgcount += 1 + self.msgcount += 1 + yield from self.msg.tuple_iterator(ielist) except EOFError: return + def from_stream(stream): """ - Get a MessageStreamReader for a given stream + Get a MessageStreamReader for a given stream. :param stream: stream to read :return: a :class:`MessageStreamReader` wrapped around the stream. - """ return MessageStreamReader(stream) diff --git a/ipfix/rfc5103.iespec b/ipfix/rfc5103.iespec index e272559..06318e4 100644 --- a/ipfix/rfc5103.iespec +++ b/ipfix/rfc5103.iespec @@ -5,9 +5,6 @@ reverseProtocolIdentifier(29305/4)[1] reverseIpClassOfService(29305/5)[1] reverseTcpControlBits(29305/6)[2] reverseIngressInterface(29305/10)[4] -reverseDestinationTransportPort(29305/11)[2] -reverseDestinationIPv4Address(29305/12)[4] -reverseDestinationIPv4PrefixLength(29305/13)[1] reverseEgressInterface(29305/14)[4] reverseIpNextHopIPv4Address(29305/15)[4] reverseBgpNextHopIPv4Address(29305/18)[4] @@ -220,7 +217,7 @@ reverseCollectorCertificate(29305/274)[65535] reverseExporterCertificate(29305/275)[65535] reverseDataRecordsReliability(29305/276)[1] reverseObservationPointType(29305/277)[1] -reverseConnectionCountNew(29305/278)[4] +reverseNewConnectionDeltaCount(29305/278)[4] reverseConnectionSumDurationSeconds(29305/279)[8] reverseConnectionTransactionId(29305/280)[8] reverseNatPoolId(29305/283)[4] @@ -359,5 +356,86 @@ reverseLayer2OctetDeltaSumOfSquares(29305/428)[8] reverseLayer2OctetTotalSumOfSquares(29305/429)[8] reverseLayer2FrameDeltaCount(29305/430)[8] reverseLayer2FrameTotalCount(29305/431)[8] -reversePseudoWireDestinationIPv4Address(29305/432)[4] -reverseIgnoredLayer2FrameTotalCount(29305/433)[8] \ No newline at end of file +reverseIgnoredLayer2FrameTotalCount(29305/433)[8] +reverseMibObjectValueInteger(29305/434)[4] +reverseMibObjectValueOctetString(29305/435)[65535] +reverseMibObjectValueOID(29305/436)[65535] +reverseMibObjectValueBits(29305/437)[65535] +reverseMibObjectValueIPAddress(29305/438)[4] +reverseMibObjectValueCounter(29305/439)[8] +reverseMibObjectValueGauge(29305/440)[4] +reverseMibObjectValueTimeTicks(29305/441)[4] +reverseMibObjectValueUnsigned(29305/442)[4] +reverseMibObjectIdentifier(29305/445)[65535] +reverseMibSubIdentifier(29305/446)[4] +reverseMibIndexIndicator(29305/447)[8] +reverseMibCaptureTimeSemantics(29305/448)[1] +reverseMibContextEngineID(29305/449)[65535] +reverseMibContextName(29305/450)[65535] +reverseMibObjectName(29305/451)[65535] +reverseMibObjectDescription(29305/452)[65535] +reverseMibObjectSyntax(29305/453)[65535] +reverseMibModuleName(29305/454)[65535] +reverseMobileIMSI(29305/455)[65535] +reverseMobileMSISDN(29305/456)[65535] +reverseHttpStatusCode(29305/457)[2] +reverseHttpRequestMethod(29305/459)[65535] +reverseHttpRequestHost(29305/460)[65535] +reverseHttpRequestTarget(29305/461)[65535] +reverseHttpMessageVersion(29305/462)[65535] +reverseNatInstanceID(29305/463)[4] +reverseInternalAddressRealm(29305/464)[65535] +reverseExternalAddressRealm(29305/465)[65535] +reverseNatQuotaExceededEvent(29305/466)[4] +reverseNatThresholdEvent(29305/467)[4] +reverseHttpUserAgent(29305/468)[65535] +reverseHttpContentType(29305/469)[65535] +reverseHttpReasonPhrase(29305/470)[65535] +reverseMaxSessionEntries(29305/471)[4] +reverseMaxBIBEntries(29305/472)[4] +reverseMaxEntriesPerUser(29305/473)[4] +reverseMaxSubscribers(29305/474)[4] +reverseMaxFragmentsPendingReassembly(29305/475)[4] +reverseAddressPoolHighThreshold(29305/476)[4] +reverseAddressPoolLowThreshold(29305/477)[4] +reverseAddressPortMappingHighThreshold(29305/478)[4] +reverseAddressPortMappingLowThreshold(29305/479)[4] +reverseAddressPortMappingPerUserHighThreshold(29305/480)[4] +reverseGlobalAddressMappingHighThreshold(29305/481)[4] +reverseVpnIdentifier(29305/482)[65535] +reverseBgpCommunity(29305/483)[4] +reverseBgpExtendedCommunity(29305/486)[65535] +reverseBgpLargeCommunity(29305/489)[65535] +reverseSrhFlagsIPv6(29305/492)[1] +reverseSrhTagIPv6(29305/493)[2] +reverseSrhSegmentIPv6(29305/494)[16] +reverseSrhActiveSegmentIPv6(29305/495)[16] +reverseSrhSegmentIPv6ListSection(29305/497)[65535] +reverseSrhSegmentsIPv6Left(29305/498)[1] +reverseSrhIPv6Section(29305/499)[65535] +reverseSrhIPv6ActiveSegmentType(29305/500)[1] +reverseSrhSegmentIPv6LocatorLength(29305/501)[1] +reverseSrhSegmentIPv6EndpointBehavior(29305/502)[2] +reverseTransportChecksum(29305/503)[2] +reverseIcmpHeaderPacketSection(29305/504)[65535] +reverseGtpuFlags(29305/505)[1] +reverseGtpuMsgType(29305/506)[1] +reverseGtpuTEid(29305/507)[4] +reverseGtpuSequenceNum(29305/508)[2] +reverseGtpuQFI(29305/509)[1] +reverseGtpuPduType(29305/510)[1] +reverseIpv6ExtensionHeaderType(29305/513)[1] +reverseIpv6ExtensionHeaderCount(29305/514)[1] +reverseIpv6ExtensionHeadersFull(29305/515)[32] +reverseIpv6ExtensionHeadersLimit(29305/517)[1] +reverseIpv6ExtensionHeadersChainLength(29305/518)[4] +reverseTcpOptionsFull(29305/520)[32] +reverseTcpSharedOptionExID16(29305/521)[2] +reverseTcpSharedOptionExID32(29305/522)[4] +reverseUdpSafeOptions(29305/525)[32] +reverseUdpUnsafeOptions(29305/526)[8] +reverseUdpExID(29305/527)[2] +reversePathDelayMeanDeltaMicroseconds(29305/530)[4] +reversePathDelayMinDeltaMicroseconds(29305/531)[4] +reversePathDelayMaxDeltaMicroseconds(29305/532)[4] +reversePathDelaySumDeltaMicroseconds(29305/533)[8] diff --git a/ipfix/template.py b/ipfix/template.py index 1203e55..9155345 100644 --- a/ipfix/template.py +++ b/ipfix/template.py @@ -1,5 +1,5 @@ # -# python-ipfix (c) 2013 Brian Trammell. +# python-ipfix (c) 2013-2026 Brian Trammell. # # Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for # its material support of this effort. @@ -28,27 +28,55 @@ See :mod:`ipfix.message` for examples. """ -from . import ie, types, compat -from .compat import izip, xrange, lru_cache import struct +from . import ie, types + # Builtin exceptions class IpfixEncodeError(Exception): """Raised on internal encoding errors, or if message MTU is too small""" - def __init__(self, *args): - super(self.__class__, self).__init__(args) + class IpfixDecodeError(Exception): """Raised when decoding a malformed IPFIX message""" - def __init__(self, *args): - super(self.__class__, self).__init__(args) + + +class EndOfMessage(Exception): + """ + Exception raised when a write operation on a Message + fails because there is not enough space in the message. + """ + # constants for v9 V9_TEMPLATE_SET_ID = 0 V9_OPTIONS_SET_ID = 1 +_V9_SCOPE_NAMES = { + 1: "v9ScopeSystem", + 2: "v9ScopeInterface", + 3: "v9ScopeLineCard", + 4: "v9ScopeCache", + 5: "v9ScopeTemplate", +} + + +class _V9ScopeIE(ie.InformationElement): + """NetFlow v9 Options Template scope field (distinct namespace from IANA IEs).""" + + def __eq__(self, other): + if isinstance(other, _V9ScopeIE): + return self.num == other.num + if isinstance(other, ie.InformationElement): + return False + return NotImplemented + + def __hash__(self): + return hash(("v9scope", self.num)) + + # constants TEMPLATE_SET_ID = 2 OPTIONS_SET_ID = 3 @@ -59,16 +87,19 @@ def __init__(self, *args): _iespec_st = struct.Struct("!HH") _iepen_st = struct.Struct("!L") -class TemplatePackingPlan(object): + +class TemplatePackingPlan: """ Plan to pack/unpack a specific set of indices for a template. Used internally by Templates for efficient encoding and decoding. """ + def __init__(self, tmpl, indices): self.tmpl = tmpl self.indices = indices - self.ranks = sorted(xrange(len(indices)), key=indices.__getitem__) + self.index_set = frozenset(indices) + self.ranks = sorted(range(len(indices)), key=indices.__getitem__) self.valenc = [] self.valdec = [] @@ -76,7 +107,7 @@ def __init__(self, tmpl, indices): for i, t in enumerate(e.type for e in tmpl.ies): if i >= tmpl.fixlen_count(): break - if i in indices: + if i in self.index_set: packstring += t.stel self.valenc.append(t.valenc) self.valdec.append(t.valdec) @@ -86,20 +117,26 @@ def __init__(self, tmpl, indices): self.st = struct.Struct(packstring) def __repr__(self): - return "" + return ( + f"" + ) -class Template(object): + +class Template: """ An IPFIX Template. A template is an ordered list of IPFIX Information Elements with an ID. """ - def __init__(self, tid = 0, iterable = None): - if tid < 256 or tid > 65535: - raise ValueError("bad template ID "+str(tid)) + + def __init__(self, tid=0, iterable=None, *, _allow_withdrawal_tid=False): + if _allow_withdrawal_tid: + if not (tid in (TEMPLATE_SET_ID, OPTIONS_SET_ID) or 256 <= tid <= 65535): + raise ValueError("bad template ID " + str(tid)) + elif tid < 256 or tid > 65535: + raise ValueError("bad template ID " + str(tid)) self.tid = tid self.minlength = 0 @@ -107,6 +144,7 @@ def __init__(self, tid = 0, iterable = None): self.scopecount = 0 self.varlenslice = None self.packplan = None + self._packplan_cache = {} self.ies = [] if iterable: @@ -116,38 +154,45 @@ def __init__(self, tid = 0, iterable = None): self.append(elem) def __repr__(self): - return "