From cf828ab27230895304fba77294271b6f9b7a5196 Mon Sep 17 00:00:00 2001 From: Brian Trammell Date: Sat, 21 Nov 2026 10:12:02 -0700 Subject: [PATCH 1/2] v1.0.0: Session separation, UDP helpers, aware UTC + NTP Era 1, repeated IEs, typing, fuzz tests, and migration guide --- CHANGES.txt | 12 ++ README.md | 55 +++++++-- ipfix/__init__.py | 6 +- ipfix/cli.py | 25 +++- ipfix/message.py | 97 ++++++++++------ ipfix/py.typed | 0 ipfix/reader.py | 84 ++++++++++++-- ipfix/session.py | 187 ++++++++++++++++++++++++++++++ ipfix/template.py | 61 +++++++++- ipfix/testutils.py | 4 +- ipfix/types.py | 61 +++++----- ipfix/writer.py | 175 +++++++++++++++++++++------- pyproject.toml | 5 +- sphinx/conf.py | 4 +- tests/test_fuzz.py | 66 +++++++++++ tests/test_reader_writer.py | 4 +- tests/test_session_udp.py | 202 +++++++++++++++++++++++++++++++++ tests/test_template_message.py | 4 +- tests/test_types.py | 32 ++++-- tests/test_v9pdu.py | 10 +- 20 files changed, 943 insertions(+), 151 deletions(-) create mode 100644 ipfix/py.typed create mode 100644 ipfix/session.py create mode 100644 tests/test_fuzz.py create mode 100644 tests/test_session_udp.py diff --git a/CHANGES.txt b/CHANGES.txt index 1ed9e16..b5b23a2 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -35,3 +35,15 @@ v0.10.0, 2026-11-20 -- Modernize packaging (pyproject.toml, Python 3.11+, drop accept timezone-aware datetimes on encode while eliminating Python 3.12+ deprecation warnings; expand pytest test suite. + +v1.0.0, 2026-11-21 -- Separate IPFIX session state into ipfix.session.Session + (templates, UDP template lifetimes, sequence checking); + add DatagramReader, DatagramWriter (with UDP MTU default + and RFC 7011 periodic template refresh), and UDP collect + support in ipfix2csv; switch decoded datetimes and + get_export_time() to timezone-aware UTC (breaking) with + RFC 5905 NTP Era 1 (2036) rollover handling; support + repeated IEs in templates; add PEP 484 type annotations + with py.typed and Hypothesis fuzz tests; add 0.x -> 1.0 + migration guide in README.md. + diff --git a/README.md b/README.md index db056fe..7606706 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,10 @@ IPFIX (RFC 7011) implementation for Python 3.11+. -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. +This package provides a Python interface to IPFIX message streams and UDP +datagrams, tools for building IPFIX Exporting and Collecting Processes, a +bridge between IPFIX abstract data types (ADTs) and native Python data types, +and a read-only NetFlow v9 PDU decoder. ## Installation @@ -39,8 +38,50 @@ msg.add_template(tmpl) msg.export_ensure_set(256) ``` -Command-line utilities `ipfix2csv` and `ipfixstat` are installed as console -scripts. +For UDP collectors and exporters, use `ipfix.session.Session` with +`ipfix.reader.DatagramReader` and `ipfix.writer.DatagramWriter` so template +state, UDP template lifetimes, and periodic template refreshes are managed +automatically across datagrams. + +Command-line utilities `ipfix2csv` (supporting files, TCP, and UDP) and +`ipfixstat` are installed as console scripts. + +## Migrating from 0.x to 1.0 + +`v1.0.0` completes the modernization started in `v0.10.0` with a small set of +intentional breaking changes: + +1. **Timezone-aware UTC `datetime` returns:** + All decoded `dateTime*` Information Elements, `MessageBuffer.get_export_time()`, + `ipfix.ie.InformationElement.parse()` for datetime types, and + `ipfix.v9pdu.TimeAdapter` now return **timezone-aware UTC** `datetime` + objects (`tzinfo=datetime.timezone.utc`) instead of naive `datetime`s. + - Encoding (`export_*`) continues to accept both timezone-aware (converted + to UTC) and naive (assumed UTC) `datetime` objects. + - If your code compares or subtracts decoded timestamps against naive + `datetime`s, update your reference timestamps to use `tzinfo=datetime.UTC` + (or `datetime.now(datetime.UTC)`). + - `dateTimeMicroseconds` and `dateTimeNanoseconds` now handle RFC 5905 NTP + Era 1 rollover (February 7, 2036). +2. **Separated `Session` state & UDP helpers:** + Templates, UDP template lifetimes, and sequence numbers now live in + `ipfix.session.Session`. `MessageBuffer()` continues to create an internal + default `Session` (and exposes `.templates` and `.sequences` properties) for + backwards compatibility, so existing TCP/file code works unchanged. UDP + collectors and exporters should migrate to `DatagramReader` / + `DatagramWriter` (or pass a shared `Session` to `MessageBuffer(session=...)`). +3. **Repeated IEs in a single template:** + If a template contains multiple occurrences of the same IE name (RFC 7011 §8), + `namedict_iterator()` now returns a `list` of values under that key instead + of silently overwriting earlier occurrences. Templates with unique IE names + are unaffected. +4. **Fixed-length `string` encoding (introduced in `0.10.0`):** + Encoding a UTF-8 string whose byte length exceeds a fixed-length `string[N]` + field now raises `ValueError` instead of silently truncating mid-codepoint, + and trailing `\x00` padding is stripped on decode. +5. **Python 3.11+ only:** + Python 2.7 compatibility (`ipfix.compat`) and `vis-package` have been + removed. ## Development diff --git a/ipfix/__init__.py b/ipfix/__init__.py index ce0c781..20522aa 100644 --- a/ipfix/__init__.py +++ b/ipfix/__init__.py @@ -51,8 +51,8 @@ """ -from . import ie, message, template, types +from . import ie, message, session, template, types -__version__ = "0.10.0" +__version__ = "1.0.0" -__all__ = ["types", "ie", "template", "message", "__version__"] +__all__ = ["types", "ie", "template", "session", "message", "__version__"] diff --git a/ipfix/cli.py b/ipfix/cli.py index 8b071e9..bf3fd64 100644 --- a/ipfix/cli.py +++ b/ipfix/cli.py @@ -118,9 +118,32 @@ def handle(self): with socketserver.TCPServer((args.bind, args.port), TcpCsvHandler) as ss: ss.serve_forever() + elif args.collect == "udp": + sys.stderr.write( + f"starting UDP CP on {args.bind}:{args.port}; Ctrl-C to stop\n" + ) + sys.stderr.flush() + cols = ie.spec_list(args.ienames) + dg_reader = reader.DatagramReader() + csv_writer = csv.writer(sys.stdout, dialect="unix") + csv_writer.writerow([e.name for e in cols]) + sys.stdout.flush() + + class UdpCsvHandler(socketserver.DatagramRequestHandler): + def handle(self): + for rec in dg_reader.tuple_iterator( + self.packet, cols, peer=self.client_address + ): + csv_writer.writerow( + [col.unparse(val) for val, col in zip(rec, cols, strict=True)] + ) + sys.stdout.flush() + + with socketserver.UDPServer((args.bind, args.port), UdpCsvHandler) as ss: + ss.serve_forever() elif args.collect: raise ValueError( - f"Unsupported transport {args.collect}; must be 'tcp' in this revision" + f"Unsupported transport {args.collect}; must be 'tcp' or 'udp'" ) elif args.file: with _open_input(args.file, args.gzip, args.bzip2) as f: diff --git a/ipfix/message.py b/ipfix/message.py index b302cc4..7990926 100644 --- a/ipfix/message.py +++ b/ipfix/message.py @@ -151,9 +151,9 @@ ... print("{}: {}".format(key, value)) ... >>> 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))] +[('destinationIPv4Address', IPv4Address('10.5.6.7')), ('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, tzinfo=datetime.timezone.utc)), ('packetDeltaCount', 27), ('sourceIPv4Address', IPv4Address('10.1.2.3'))] +[('destinationIPv4Address', IPv4Address('10.12.13.14')), ('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, 2, tzinfo=datetime.timezone.utc)), ('packetDeltaCount', 33), ('sourceIPv4Address', IPv4Address('10.8.9.11'))] +[('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, 4, tzinfo=datetime.timezone.utc))] myNewInformationElement: Grüezi, Y'all The tuple interface for reading messages is designed for applications with a @@ -167,8 +167,8 @@ >>> for rec in msg.tuple_iterator(ielist): ... print(rec) ... -(datetime.datetime(2013, 6, 21, 14, 0), 27) -(datetime.datetime(2013, 6, 21, 14, 0, 2), 33) +(datetime.datetime(2013, 6, 21, 14, 0, tzinfo=datetime.timezone.utc), 27) +(datetime.datetime(2013, 6, 21, 14, 0, 2, tzinfo=datetime.timezone.utc), 33) 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. @@ -188,6 +188,7 @@ from warnings import warn from . import template, types +from .session import Session from .template import IpfixDecodeError, IpfixEncodeError _sethdr_st = struct.Struct("!HH") @@ -214,8 +215,14 @@ class MessageBuffer: Implements a buffer for reading or writing IPFIX messages. """ - def __init__(self, buf_sz=65536): - """Create a new MessageBuffer instance.""" + def __init__(self, buf_sz: int = 65536, session: Session | None = None) -> None: + """Create a new MessageBuffer instance. + + :param buf_sz: Internal buffer size in bytes (default 65536). + :param session: Optional :class:`ipfix.session.Session` holding + template and sequence state. If omitted, a private + default :class:`Session` is created. + """ self.mbuf = memoryview(bytearray(buf_sz)) self.length = 0 self.sequence = None @@ -223,11 +230,10 @@ def __init__(self, buf_sz=65536): self.odid = 0 self.streamid = 0 - self.templates = {} - self.accepted_tids = set() - self.sequences = {} + self.session: Session = session if session is not None else Session() + self.accepted_tids: set[tuple[int, int]] = set() - self.setlist = [] + self.setlist: list[tuple[int, int, int]] = [] self.auto_export_time = True self.cursetoff = 0 @@ -243,6 +249,16 @@ def __init__(self, buf_sz=65536): self.ignored_data_set_hook = None self.message_header_hook = None + @property + def templates(self) -> dict[tuple[int, int], template.Template]: + """Active templates dictionary (delegated to :attr:`session`).""" + return self.session.templates + + @property + def sequences(self) -> dict[tuple[int, int], int]: + """Sequence numbers dictionary (delegated to :attr:`session`).""" + return self.session.sequences + def __repr__(self): if self.cursetid: addinf = f" (writing set {self.cursetid})" @@ -281,8 +297,7 @@ def set_export_time(self, dt=None): self.auto_export_time = False def _increment_sequence(self): - key = (self.odid, self.streamid) - self.sequences[key] = (self.sequences.get(key, 0) + 1) & 0xFFFFFFFF + self.session.increment_sequence(self.odid, self.streamid, 1) def _scan_setlist(self): # We've read a message. Discard all export state. @@ -343,6 +358,9 @@ def read_message(self, stream): ) self.mbuf[_msghdr_st.size : self.length] = msgbody + # verify sequence number against session state + self.session.check_sequence(self.odid, self.streamid, self.sequence) + # call the message header hook if self.message_header_hook: self.message_header_hook(self) @@ -366,18 +384,13 @@ def from_bytes(self, 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) + for removed_tid in self.session.withdraw_all_templates( + self.odid, setid=setid + ): + self.accepted_tids.discard((self.odid, removed_tid)) else: - key = (self.odid, tid) - self.templates.pop(key, None) - self.accepted_tids.discard(key) + self.session.delete_template(self.odid, tid) + self.accepted_tids.discard((self.odid, tid)) def record_iterator( self, @@ -432,7 +445,7 @@ def record_iterator( if tmpl.count() == 0: self._handle_template_withdrawal(setid, tmpl.tid) else: - self.templates[(self.odid, tmpl.tid)] = tmpl + self.session.add_template(self.odid, tmpl) if tmplaccept_fn(tmpl): self.accepted_tids.add((self.odid, tmpl.tid)) else: @@ -445,14 +458,18 @@ def record_iterator( warn("skipping illegal set id " + str(setid), stacklevel=2) else: try: - tmpl = self.templates[(self.odid, setid)] + tmpl = self.session.get_template(self.odid, setid) except KeyError: + self.accepted_tids.discard((self.odid, setid)) if self.unknown_data_set_hook: self.unknown_data_set_hook( self, self.mbuf[offset - _sethdr_st.size : setend] ) continue + if (self.odid, setid) not in self.accepted_tids and tmplaccept_fn(tmpl): + self.accepted_tids.add((self.odid, setid)) + if (self.odid, setid) in self.accepted_tids: if tmpl.minlength <= 0: raise IpfixDecodeError( @@ -494,8 +511,17 @@ def tuple_iterator(self, ielist): listing IEs to return as a tuple :returns: a tuple iterator for tuples as in ielist order """ + # Also ensure tuple_iterator checks multiplicity for repeated IEs def tmplaccept_fn(tmpl): - return all(elem in tmpl.ies for elem in ielist) + needed: dict[tuple[int, int], int] = {} + for elem in ielist: + key = (elem.pen, elem.num) + needed[key] = needed.get(key, 0) + 1 + avail: dict[tuple[int, int], int] = {} + for elem in tmpl.ies: + key = (elem.pen, elem.num) + avail[key] = avail.get(key, 0) + 1 + return all(avail.get(k, 0) >= cnt for k, cnt in needed.items()) if ( self.last_tuple_iterator_ielist is None @@ -546,7 +572,7 @@ def write_message(self, stream): def add_template(self, tmpl, export=True): """ - Add a template to this MessageBuffer. Adding a template makes it + Add a template to this MessageBuffer's Session. Adding a template makes it available for use for exporting records; see :meth:`export_new_set`. :param tmpl: the template to add @@ -554,7 +580,7 @@ def add_template(self, tmpl, export=True): after adding it. :raises: EndOfMessage """ - self.templates[(self.odid, tmpl.tid)] = tmpl + self.session.add_template(self.odid, tmpl) if export: self.export_template(tmpl.tid) @@ -564,15 +590,16 @@ def add_template(self, tmpl, export=True): def delete_template(self, tid, export=True): """ - Delete a template by ID from this MessageBuffer. + Delete a template by ID from this MessageBuffer's Session. :param tid: ID of the template to delete :param export: if True, export a Template Withdrawal for this Template after deleting it :raises: EndOfMessage, KeyError """ - setid = self.templates[(self.odid, tid)].native_setid() - del self.templates[(self.odid, tid)] + tmpl = self.session.get_template(self.odid, tid) + setid = tmpl.native_setid() + self.session.delete_template(self.odid, tid) self.accepted_tids.discard((self.odid, tid)) if export: self._export_template_withdrawal(setid, tid) @@ -585,9 +612,7 @@ def active_template_ids(self): :returns: a template ID iterator """ - for odid, tid in self.templates: - if odid == self.odid: - yield tid + yield from self.session.active_template_ids(self.odid) def template_for_id(self, tid): """ @@ -597,7 +622,7 @@ def template_for_id(self, tid): :returns: the template :raises: KeyError """ - return self.templates[(self.odid, tid)] + return self.session.get_template(self.odid, tid) def begin_export(self, odid=None): """ diff --git a/ipfix/py.typed b/ipfix/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/ipfix/reader.py b/ipfix/reader.py index 37f30b4..a59b7ab 100644 --- a/ipfix/reader.py +++ b/ipfix/reader.py @@ -19,10 +19,16 @@ # """ -Interface to read IPFIX Messages from a stream. +Interfaces to read IPFIX Messages from streams (TCP/files) and datagrams (UDP). """ -from . import message +from __future__ import annotations + +from collections.abc import Iterator +from typing import Any + +from . import ie, message +from .session import Session class MessageStreamReader: @@ -38,12 +44,13 @@ class MessageStreamReader: When opening a stream from a file, use mode='rb'. """ - def __init__(self, stream): + def __init__(self, stream: Any, *, session: Session | None = None) -> None: self.stream = stream - self.msg = message.MessageBuffer() + self.session = session if session is not None else Session() + self.msg = message.MessageBuffer(session=self.session) self.msgcount = 0 - def namedict_iterator(self): + def namedict_iterator(self) -> Iterator[dict[str, Any]]: """ Iterate over all records in the stream, as dicts mapping IE names to values. @@ -59,7 +66,9 @@ def namedict_iterator(self): except EOFError: return - def tuple_iterator(self, ielist): + def tuple_iterator( + self, ielist: ie.InformationElementList + ) -> Iterator[tuple[Any, ...]]: """ Iterate over all records in the stream containing all the IEs in the given ielist. Records are returned as tuples in ielist order. @@ -78,11 +87,70 @@ def tuple_iterator(self, ielist): return -def from_stream(stream): +class DatagramReader: + """ + Reads IPFIX messages from UDP datagrams while maintaining per-peer + :class:`ipfix.session.Session` state (templates, template lifetimes, + and sequence numbers). + + Suitable for UDP collectors (e.g., :class:`socketserver.UDPServer` or + ``asyncio.DatagramProtocol``) where each datagram arrives independently + and templates may be sent in separate packets from data sets. + """ + + def __init__( + self, + *, + template_lifetime: float | None = 1800.0, + session: Session | None = None, + ) -> None: + self.template_lifetime = template_lifetime + self._shared_session = session + self.sessions: dict[Any, Session] = {} + self.msgcount = 0 + + def session_for_peer(self, peer: Any = None) -> Session: + """Return (creating if needed) the :class:`Session` for ``peer``.""" + if self._shared_session is not None: + return self._shared_session + sess = self.sessions.get(peer) + if sess is None: + sess = Session(template_lifetime=self.template_lifetime) + self.sessions[peer] = sess + return sess + + def read_datagram(self, data: bytes | bytearray | memoryview, peer: Any = None) -> message.MessageBuffer: + """Parse a single IPFIX UDP datagram using the peer's :class:`Session`.""" + sess = self.session_for_peer(peer) + msg = message.MessageBuffer(session=sess) + msg.from_bytes(data) + self.msgcount += 1 + return msg + + def namedict_iterator( + self, data: bytes | bytearray | memoryview, peer: Any = None + ) -> Iterator[dict[str, Any]]: + """Decode a single datagram and yield records as dicts.""" + msg = self.read_datagram(data, peer=peer) + yield from msg.namedict_iterator() + + def tuple_iterator( + self, + data: bytes | bytearray | memoryview, + ielist: ie.InformationElementList, + peer: Any = None, + ) -> Iterator[tuple[Any, ...]]: + """Decode a single datagram and yield records as tuples.""" + msg = self.read_datagram(data, peer=peer) + yield from msg.tuple_iterator(ielist) + + +def from_stream(stream: Any, *, session: Session | None = None) -> MessageStreamReader: """ Get a MessageStreamReader for a given stream. :param stream: stream to read + :param session: optional :class:`ipfix.session.Session` :return: a :class:`MessageStreamReader` wrapped around the stream. """ - return MessageStreamReader(stream) + return MessageStreamReader(stream, session=session) diff --git a/ipfix/session.py b/ipfix/session.py new file mode 100644 index 0000000..ae3cedd --- /dev/null +++ b/ipfix/session.py @@ -0,0 +1,187 @@ +# +# 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 Lesser General Public License along with +# this program. If not, see . +# + +""" +IPFIX Transport Session state management (RFC 7011 §8, §10). + +A :class:`Session` holds the stateful context shared across IPFIX messages +within a transport session: active templates (scoped by Observation Domain ID), +optional UDP template lifetimes (RFC 7011 §8.3), and per-domain sequence +numbers (RFC 7011 §3.1). + +Separating :class:`Session` from :class:`ipfix.message.MessageBuffer` allows +UDP collectors and exporters to share template and sequence state cleanly +across individual datagrams without keeping a single mutable buffer per peer. +""" + +from __future__ import annotations + +import time +from collections.abc import Callable, Iterator +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .template import Template + +SequenceGapHook = Callable[["Session", int, int, int, int], None] + + +class Session: + """ + Holds IPFIX session state: templates, template lifetimes, and sequence numbers. + + :param template_lifetime: Optional template expiration time in seconds + (recommended for UDP collectors per RFC 7011 §8.3, + e.g. ``1800.0``). ``None`` disables expiration + (appropriate for TCP/SCTP/file sessions). + :param sequence_gap_hook: Optional callback ``(session, odid, streamid, + expected_seq, received_seq)`` invoked when a + collected message header sequence number does not + match the expected sequence number. + """ + + def __init__( + self, + *, + template_lifetime: float | None = None, + sequence_gap_hook: SequenceGapHook | None = None, + ) -> None: + self.templates: dict[tuple[int, int], Template] = {} + self.template_times: dict[tuple[int, int], float] = {} + self.sequences: dict[tuple[int, int], int] = {} + self._seen_sequences: set[tuple[int, int]] = set() + self.template_lifetime: float | None = template_lifetime + self.sequence_gap_hook: SequenceGapHook | None = sequence_gap_hook + + def _is_expired(self, key: tuple[int, int], now: float) -> bool: + if self.template_lifetime is None: + return False + ts = self.template_times.get(key) + if ts is None: + return False + return (now - ts) > self.template_lifetime + + def purge_expired_templates(self, *, now: float | None = None) -> int: + """Remove all expired templates and return the count removed.""" + if self.template_lifetime is None: + return 0 + current = time.monotonic() if now is None else now + expired = [k for k in list(self.templates) if self._is_expired(k, current)] + for k in expired: + del self.templates[k] + self.template_times.pop(k, None) + return len(expired) + + def add_template( + self, odid: int, tmpl: Template, *, now: float | None = None + ) -> None: + """Register or refresh a template for an Observation Domain ID.""" + key = (odid, tmpl.tid) + self.templates[key] = tmpl + self.template_times[key] = time.monotonic() if now is None else now + + def get_template( + self, odid: int, tid: int, *, now: float | None = None + ) -> Template: + """Retrieve an active template; raises KeyError if missing or expired.""" + key = (odid, tid) + if key not in self.templates: + raise KeyError(key) + if self.template_lifetime is not None: + current = time.monotonic() if now is None else now + if self._is_expired(key, current): + del self.templates[key] + self.template_times.pop(key, None) + raise KeyError(key) + return self.templates[key] + + def delete_template(self, odid: int, tid: int) -> Template | None: + """Remove a template if present and return it (or None).""" + key = (odid, tid) + self.template_times.pop(key, None) + return self.templates.pop(key, None) + + def withdraw_all_templates( + self, odid: int, setid: int | None = None + ) -> list[int]: + """Withdraw all templates (optionally filtered by native setid) for odid.""" + removed: list[int] = [] + for k in list(self.templates): + if k[0] == odid and (setid is None or self.templates[k].native_setid() == setid): + del self.templates[k] + self.template_times.pop(k, None) + removed.append(k[1]) + return removed + + def active_template_ids( + self, odid: int, *, now: float | None = None + ) -> Iterator[int]: + """Yield active (non-expired) template IDs for the given domain.""" + if self.template_lifetime is not None: + self.purge_expired_templates(now=now) + for domain, tid in list(self.templates): + if domain == odid: + yield tid + + def current_sequence(self, odid: int, streamid: int = 0) -> int: + """Return the current sequence number for (odid, streamid).""" + return self.sequences.setdefault((odid, streamid), 0) + + def increment_sequence( + self, odid: int, streamid: int = 0, count: int = 1 + ) -> int: + """Increment and return the sequence number mod 2^32.""" + key = (odid, streamid) + val = (self.sequences.get(key, 0) + count) & 0xFFFFFFFF + self.sequences[key] = val + return val + + def check_sequence( + self, odid: int, streamid: int, received_seq: int + ) -> bool: + """ + Verify a received IPFIX message header sequence number (RFC 7011 §3.1). + + On the first message for ``(odid, streamid)``, synchronizes to + ``received_seq`` and returns ``True``. On subsequent messages, if + ``received_seq`` differs from the expected sequence number, invokes + ``sequence_gap_hook`` (if set), resynchronizes to ``received_seq``, + and returns ``False``. + """ + key = (odid, streamid) + if key not in self._seen_sequences: + self._seen_sequences.add(key) + self.sequences[key] = received_seq & 0xFFFFFFFF + return True + + expected = self.sequences.get(key, 0) + if received_seq != expected: + if self.sequence_gap_hook is not None: + self.sequence_gap_hook(self, odid, streamid, expected, received_seq) + self.sequences[key] = received_seq & 0xFFFFFFFF + return False + return True + + def reset(self) -> None: + """Clear all templates and sequence state.""" + self.templates.clear() + self.template_times.clear() + self.sequences.clear() + self._seen_sequences.clear() diff --git a/ipfix/template.py b/ipfix/template.py index aa0bf75..9ee4eaf 100644 --- a/ipfix/template.py +++ b/ipfix/template.py @@ -180,13 +180,26 @@ def finalize(self): def packplan_for_ielist(self, ielist): """ Given a list of IEs, devise and cache a packing plan. - Used by the tuple interfaces. + Used by the tuple interfaces. Supports repeated IEs in a template + by matching successive occurrences in order. """ plan = self._packplan_cache.get(ielist) if plan is None: if len(self._packplan_cache) >= 32: self._packplan_cache.clear() - plan = TemplatePackingPlan(self, [self.ies.index(elem) for elem in ielist]) + used: set[int] = set() + indices: list[int] = [] + for elem in ielist: + found = None + for idx, tmpl_ie in enumerate(self.ies): + if idx not in used and tmpl_ie == elem: + found = idx + break + if found is None: + raise ValueError(f"{elem} is not in template") + used.add(found) + indices.append(found) + plan = TemplatePackingPlan(self, indices) self._packplan_cache[ielist] = plan return plan @@ -245,9 +258,26 @@ def decode_from(self, buf, offset, packplan=None, setend=None): return (vals, offset) def decode_namedict_from(self, buf, offset, recinf=None): - """Decodes a record from a buffer into a dict keyed by IE name.""" + """ + Decodes a record from a buffer into a dict keyed by IE name. + + If an IE name appears multiple times in the template (RFC 7011 §8), + its value in the returned dict is a list of values in template order. + """ vals, offset = self.decode_from(buf, offset) - return ({elem.name: v for elem, v in zip(self.ies, vals, strict=True)}, offset) + rec = {} + multi: set[str] = set() + for elem, v in zip(self.ies, vals, strict=True): + name = elem.name + if name in rec: + if name not in multi: + rec[name] = [rec[name], v] + multi.add(name) + else: + rec[name].append(v) + else: + rec[name] = v + return (rec, offset) def decode_tuple_from(self, buf, offset, recinf=None): """ @@ -301,8 +331,27 @@ def encode_to(self, buf, offset, vals, packplan=None): return offset def encode_namedict_to(self, buf, offset, rec, recinf=None): - """Encodes a record from a dict containing values keyed by IE name.""" - return self.encode_to(buf, offset, [rec[elem.name] for elem in self.ies]) + """ + Encodes a record from a dict containing values keyed by IE name. + + If an IE name appears multiple times in the template, its dict value + must be a list or tuple providing one value per occurrence in order. + """ + counts: dict[str, int] = {} + for elem in self.ies: + counts[elem.name] = counts.get(elem.name, 0) + 1 + + seen: dict[str, int] = {} + vals = [] + for elem in self.ies: + name = elem.name + if counts[name] > 1: + idx = seen.get(name, 0) + vals.append(rec[name][idx]) + seen[name] = idx + 1 + else: + vals.append(rec[name]) + return self.encode_to(buf, offset, vals) def encode_tuple_to(self, buf, offset, rec, recinf=None): """ diff --git a/ipfix/testutils.py b/ipfix/testutils.py index f5c47c2..db19946 100644 --- a/ipfix/testutils.py +++ b/ipfix/testutils.py @@ -21,7 +21,7 @@ """Helper utilities for generating synthetic IPFIX test messages.""" import base64 -from datetime import datetime, timedelta +from datetime import UTC, datetime, timedelta from ipaddress import ip_address from . import ie, message, template @@ -104,7 +104,7 @@ def mktest_record(sequence): return { "sourceIPv4Address": ip_address(0x7F000000 + sequence), - "flowStartMilliseconds": datetime(2009, 2, 20, tzinfo=None) + "flowStartMilliseconds": datetime(2009, 2, 20, tzinfo=UTC) + timedelta(0, sequence / 1000), "testString": _test_strings[sequence % len(_test_strings)], "octetDeltaCount": sequence % 33, diff --git a/ipfix/types.py b/ipfix/types.py index 7fb36eb..2c229f9 100644 --- a/ipfix/types.py +++ b/ipfix/types.py @@ -451,60 +451,69 @@ def _encode_sec(dt): return int(dt2epoch(dt)) -def _decode_sec(epoch): - return datetime.fromtimestamp(epoch, tz=UTC).replace(tzinfo=None) +def _decode_sec(epoch: int) -> datetime: + return datetime.fromtimestamp(epoch, tz=UTC) -def _str_sec(dt): +def _str_sec(dt: datetime) -> str: return dt.strftime(ISO8601_FMT) -def _parse_sec(string): +def _parse_sec(string: str) -> datetime: dt = datetime.fromisoformat(string) - if dt.tzinfo is not None: - dt = dt.astimezone(UTC).replace(tzinfo=None) - return dt + if dt.tzinfo is None: + return dt.replace(tzinfo=UTC) + return dt.astimezone(UTC) -def _encode_msec(dt): +def _encode_msec(dt: datetime) -> int: return int(dt2epoch(dt) * 1000) -def _decode_msec(epoch): - return datetime.fromtimestamp(epoch / 1000, tz=UTC).replace(tzinfo=None) +def _decode_msec(epoch: int | float) -> datetime: + return datetime.fromtimestamp(epoch / 1000, tz=UTC) -def _str_msec(dt): +def _str_msec(dt: datetime) -> str: return f"{dt.strftime(ISO8601_FMT)}.{int(dt.microsecond / 1000):03d}" -def _parse_msec(string): +def _parse_msec(string: str) -> datetime: dt = datetime.fromisoformat(string) - if dt.tzinfo is not None: - dt = dt.astimezone(UTC).replace(tzinfo=None) - return dt + if dt.tzinfo is None: + return dt.replace(tzinfo=UTC) + return dt.astimezone(UTC) -def _encode_ntp(dt): +def _encode_ntp(dt: datetime) -> int: tsf, tsi = math.modf(dt2epoch(dt)) - return int(((int(tsi) + NTP_EPOCH_TO_UNIX_EPOCH) << 32) + (tsf * 2**32)) + # Wrap 32-bit NTP seconds modulo 2^32 for RFC 5905 Era 1 (2036+) compatibility + ntp_sec = (int(tsi) + NTP_EPOCH_TO_UNIX_EPOCH) & 0xFFFFFFFF + ntp_frac = int(tsf * 2**32) & 0xFFFFFFFF + return (ntp_sec << 32) | ntp_frac -def _decode_ntp(ntp): - tsf = ntp & (2**32 - 1) - tsi = (ntp >> 32) - NTP_EPOCH_TO_UNIX_EPOCH - return datetime.fromtimestamp(tsi + tsf / 2**32, tz=UTC).replace(tzinfo=None) +def _decode_ntp(ntp: int) -> datetime: + tsf = ntp & 0xFFFFFFFF + ntp_sec = (ntp >> 32) & 0xFFFFFFFF + # RFC 5905 / RFC 7011 §6.1.9-6.1.10 era disambiguation: + # MSB=1 (0x80000000..0xFFFFFFFF) -> Era 0 (1968-01-20 .. 2036-02-07) + # MSB=0 (0x00000000..0x7FFFFFFF) -> Era 1 (2036-02-07 .. 2104-02-26) + if ntp_sec < 0x80000000: + ntp_sec += 1 << 32 + tsi = ntp_sec - NTP_EPOCH_TO_UNIX_EPOCH + return datetime.fromtimestamp(tsi + tsf / 2**32, tz=UTC) -def _str_usec(dt): +def _str_usec(dt: datetime) -> str: return f"{dt.strftime(ISO8601_FMT)}.{dt.microsecond:06d}" -def _parse_usec(string): +def _parse_usec(string: str) -> datetime: dt = datetime.fromisoformat(string) - if dt.tzinfo is not None: - dt = dt.astimezone(UTC).replace(tzinfo=None) - return dt + if dt.tzinfo is None: + return dt.replace(tzinfo=UTC) + return dt.astimezone(UTC) def _encode_ip(ipaddr): diff --git a/ipfix/writer.py b/ipfix/writer.py index 4d2b3bf..f7059f5 100644 --- a/ipfix/writer.py +++ b/ipfix/writer.py @@ -19,10 +19,16 @@ # """ -Interface to write IPFIX Messages to a stream. +Interfaces to write IPFIX Messages to streams (TCP/files) and datagrams (UDP). """ -from . import message +from __future__ import annotations + +import time +from typing import Any + +from . import message, template +from .session import Session class MessageStreamWriter: @@ -38,68 +44,52 @@ class MessageStreamWriter: sockets. When writing a stream to a file, use mode='wb'. """ - def __init__(self, stream, mtu=65535): + def __init__( + self, stream: Any, mtu: int = 65535, *, session: Session | None = None + ) -> None: self.stream = stream - self.msg = message.MessageBuffer() + self.session = session if session is not None else Session() + self.msg = message.MessageBuffer(session=self.session) self.msg.mtu = mtu self.msgcount = 0 - self.curtid = None + self.curtid: int | None = None - def _retry_after_flush(self, fn, *args, **kwargs): + def _retry_after_flush(self, fn: Any, *args: Any, **kwargs: Any) -> Any: try: return fn(*args, **kwargs) except message.EndOfMessage: self.flush() return fn(*args, **kwargs) - def set_domain(self, odid): + def set_domain(self, odid: int) -> None: """ Sets the observation domain for subsequent messages sent with this Writer. - - :param odid: Observation domain ID to use for export. Note that - templates are scoped to observation domain, so - templates will need to be added after switching to a - new observation domain ID. """ if self.msg.export_needs_flush(): self.msg.write_message(self.stream) self.msgcount += 1 self.msg.begin_export(odid) - def add_template(self, tmpl): + def add_template(self, tmpl: template.Template) -> None: """ Add a template to this Writer. Adding a template makes it available for use for exporting records; see :meth:`set_export_template`. - - :param tmpl: the template to add """ self._retry_after_flush(message.MessageBuffer.add_template, self.msg, tmpl) - def set_export_template(self, tid): + def set_export_template(self, tid: int) -> None: """ Set the template to be used for export by subsequent calls to :meth:`export_namedict` and :meth:`export_tuple`. - - :param tid: Template ID of the Template that will be used to encode - records to the Writer. The corresponding Template must - have already been added to the Writer, see - :meth:`add_template`. """ self.curtid = tid self._retry_after_flush( message.MessageBuffer.export_ensure_set, self.msg, self.curtid ) - def export_namedict(self, rec): - """ - Export a record to the message, using the current template. - The record is a dictionary mapping IE names to values. The - dictionary must contain a value for each IE in the template. Keys in the - dictionary not in the template will be ignored. - - :param rec: the record to export, as a dictionary - """ + def export_namedict(self, rec: dict[str, Any]) -> None: + """Export a record to the message, using the current template.""" self._retry_after_flush( message.MessageBuffer.export_ensure_set, self.msg, self.curtid ) @@ -107,7 +97,7 @@ def export_namedict(self, rec): message.MessageBuffer.export_namedict, self.msg, rec ) - def export_tuple(self, rec): + def export_tuple(self, rec: tuple[Any, ...]) -> None: self._retry_after_flush( message.MessageBuffer.export_ensure_set, self.msg, self.curtid ) @@ -115,15 +105,8 @@ def export_tuple(self, rec): message.MessageBuffer.export_tuple, self.msg, rec ) - def flush(self): - """ - Export an in-progress Message immediately. - - Used internally to manage message boundaries, but - can also be used to force immediate export (e.g. to reduce delay - due to buffer dwell time), as well as to finish write operations on - a Writer before closing the underlying stream. - """ + def flush(self) -> None: + """Export an in-progress Message immediately.""" if not self.msg.export_needs_flush(): return setid = self.msg.cursetid @@ -134,13 +117,121 @@ def flush(self): self.msg.export_ensure_set(setid) -def to_stream(stream, mtu=65535): +class DatagramWriter: + """ + Writes IPFIX messages as MTU-bounded UDP datagrams with automatic + periodic template refresh (RFC 7011 §10.3.6). + + :param send_fn: Callable accepting a ``bytes`` datagram (e.g., + ``sock.send`` on a connected UDP socket, or + ``lambda b: sock.sendto(b, addr)``). + :param mtu: Maximum IPFIX message size in bytes (default ``1400`` to avoid + IP fragmentation over standard Ethernet MTUs). + :param template_refresh_interval: Seconds between automatic re-export of + active templates (default ``600.0``; + ``None`` disables periodic refresh). + :param session: Optional :class:`ipfix.session.Session`. + """ + + def __init__( + self, + send_fn: Any, + mtu: int = 1400, + *, + template_refresh_interval: float | None = 600.0, + session: Session | None = None, + ) -> None: + self.send_fn = send_fn + self.session = session if session is not None else Session() + self.msg = message.MessageBuffer(session=self.session) + self.msg.mtu = mtu + self.template_refresh_interval = template_refresh_interval + self._last_template_refresh: float | None = None + self.msgcount = 0 + self.curtid: int | None = None + + def _maybe_refresh_templates(self, *, now: float | None = None) -> None: + if self.template_refresh_interval is None: + return + current = time.monotonic() if now is None else now + if self._last_template_refresh is None: + self._last_template_refresh = current + return + if (current - self._last_template_refresh) >= self.template_refresh_interval: + self.refresh_templates(now=current) + + def refresh_templates(self, *, now: float | None = None) -> None: + """Re-export all active templates in the current domain.""" + for tid in list(self.msg.active_template_ids()): + try: + self.msg.export_template(tid) + except message.EndOfMessage: + self.flush() + self.msg.export_template(tid) + self._last_template_refresh = time.monotonic() if now is None else now + + def _retry_after_flush(self, fn: Any, *args: Any, **kwargs: Any) -> Any: + try: + return fn(*args, **kwargs) + except message.EndOfMessage: + self.flush() + return fn(*args, **kwargs) + + def set_domain(self, odid: int) -> None: + if self.msg.export_needs_flush(): + self.flush() + self.msg.begin_export(odid) + + def add_template(self, tmpl: template.Template) -> None: + self._retry_after_flush(message.MessageBuffer.add_template, self.msg, tmpl) + self._last_template_refresh = time.monotonic() + + def set_export_template(self, tid: int) -> None: + self.curtid = tid + self._retry_after_flush( + message.MessageBuffer.export_ensure_set, self.msg, self.curtid + ) + + def export_namedict(self, rec: dict[str, Any]) -> None: + self._maybe_refresh_templates() + self._retry_after_flush( + message.MessageBuffer.export_ensure_set, self.msg, self.curtid + ) + self._retry_after_flush( + message.MessageBuffer.export_namedict, self.msg, rec + ) + + def export_tuple(self, rec: tuple[Any, ...]) -> None: + self._maybe_refresh_templates() + self._retry_after_flush( + message.MessageBuffer.export_ensure_set, self.msg, self.curtid + ) + self._retry_after_flush( + message.MessageBuffer.export_tuple, self.msg, rec + ) + + def flush(self) -> None: + """Send the in-progress IPFIX message as a single UDP datagram.""" + if not self.msg.export_needs_flush(): + return + setid = self.msg.cursetid + self.send_fn(self.msg.to_bytes()) + self.msgcount += 1 + self.msg.begin_export() + if setid is not None: + self.msg.export_ensure_set(setid) + + +def to_stream( + stream: Any, mtu: int = 65535, *, session: Session | None = None +) -> MessageStreamWriter: """ Get a MessageStreamWriter for a given stream. :param stream: stream to write :param mtu: maximum message size in bytes; defaults to 65535, the largest possible IPFIX message. + :param session: optional :class:`ipfix.session.Session` :return: a :class:`MessageStreamWriter` wrapped around the stream. """ - return MessageStreamWriter(stream, mtu) + return MessageStreamWriter(stream, mtu, session=session) diff --git a/pyproject.toml b/pyproject.toml index 54d9f3c..349dff1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "ipfix" -version = "0.10.0" +version = "1.0.0" description = "IPFIX (RFC 7011) implementation for Python" readme = "README.md" license = "LGPL-3.0-or-later" @@ -14,7 +14,7 @@ authors = [ ] keywords = ["ipfix", "netflow", "rfc7011", "networking", "telemetry", "flow"] classifiers = [ - "Development Status :: 4 - Beta", + "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)", "Operating System :: OS Independent", @@ -40,6 +40,7 @@ docs = ["sphinx>=7.0"] [dependency-groups] dev = [ + "hypothesis>=6.100", "pytest>=8.0", "pytest-cov>=5.0", "ruff>=0.8", diff --git a/sphinx/conf.py b/sphinx/conf.py index 1736298..f5cc87c 100755 --- a/sphinx/conf.py +++ b/sphinx/conf.py @@ -49,9 +49,9 @@ # built documents. # # The short X.Y version. -version = '0.10' +version = '1.0' # The full version, including alpha/beta/rc tags. -release = '0.10.0' +release = '1.0.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/tests/test_fuzz.py b/tests/test_fuzz.py new file mode 100644 index 0000000..067f719 --- /dev/null +++ b/tests/test_fuzz.py @@ -0,0 +1,66 @@ +import io + +from hypothesis import given, settings +from hypothesis import strategies as st + +import ipfix.ie as ie +import ipfix.message as message +import ipfix.testutils as testutils +import ipfix.v9pdu as v9pdu +from ipfix.template import IpfixDecodeError + + +def _init_once(): + if not ie._ieForNum: + ie.use_iana_default() + + +@settings(max_examples=200, deadline=None) +@given(data=st.binary(max_size=1024)) +def test_fuzz_ipfix_arbitrary_bytes(data): + """Arbitrary bytes must never hang or raise unhandled exceptions.""" + _init_once() + before_ie_count = len(ie._ieForNum) + msg = message.MessageBuffer() + try: + msg.from_bytes(data) + list(msg.namedict_iterator()) + except (IpfixDecodeError, EOFError): + pass + assert len(ie._ieForNum) == before_ie_count + + +@settings(max_examples=200, deadline=None) +@given( + idx=st.integers(min_value=0, max_value=len(testutils._stored_test_message) - 1), + val=st.integers(min_value=0, max_value=255), + truncate=st.integers(min_value=0, max_value=len(testutils._stored_test_message)), +) +def test_fuzz_ipfix_mutated_valid_message(idx, val, truncate): + """Single-byte mutations and truncations of a valid IPFIX message stay safe.""" + _init_once() + mutated = bytearray(testutils._stored_test_message) + mutated[idx] = val + buf = bytes(mutated[:truncate]) + msg = message.MessageBuffer() + try: + msg.from_bytes(buf) + list(msg.namedict_iterator()) + except (IpfixDecodeError, EOFError): + pass + + +@settings(max_examples=200, deadline=None) +@given(data=st.binary(max_size=512)) +def test_fuzz_v9pdu_arbitrary_bytes(data): + """Arbitrary bytes fed to NetFlow v9 decoders must never hang or crash.""" + _init_once() + try: + list(v9pdu.SinglePduBuffer(data).namedict_iterator()) + except (IpfixDecodeError, EOFError): + pass + + try: + list(v9pdu.from_stream(io.BytesIO(data)).namedict_iterator()) + except (IpfixDecodeError, EOFError): + pass diff --git a/tests/test_reader_writer.py b/tests/test_reader_writer.py index 0ac0a80..54114ef 100644 --- a/tests/test_reader_writer.py +++ b/tests/test_reader_writer.py @@ -1,5 +1,5 @@ import io -from datetime import datetime +from datetime import UTC, datetime from ipaddress import ip_address import pytest @@ -35,7 +35,7 @@ def test_writer_and_reader_multimessage_roundtrip(): expected = [] for i in range(25): rec = { - "flowStartMilliseconds": datetime(2024, 1, 1, 0, 0, i), + "flowStartMilliseconds": datetime(2024, 1, 1, 0, 0, i, tzinfo=UTC), "sourceIPv4Address": ip_address(0x0A000001 + i), "packetDeltaCount": i * 10, } diff --git a/tests/test_session_udp.py b/tests/test_session_udp.py new file mode 100644 index 0000000..9f8ff1a --- /dev/null +++ b/tests/test_session_udp.py @@ -0,0 +1,202 @@ +from ipaddress import ip_address + +import pytest + +import ipfix.ie as ie +import ipfix.message as message +import ipfix.reader as reader +import ipfix.session as session +import ipfix.template as template +import ipfix.writer as writer + + +@pytest.fixture(autouse=True) +def setup_iana(): + ie.clear_infomodel() + ie.use_iana_default() + yield + ie.clear_infomodel() + + +def test_session_shared_across_message_buffers(): + """Issues #13, #27, #31: template in packet 1, data in packet 2 via shared Session.""" + tmpl = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount") + + # Packet 1: template only + exp = message.MessageBuffer() + exp.begin_export(42) + exp.add_template(tmpl, export=True) + pkt1 = exp.to_bytes() + + # Packet 2: data only (no template re-sent) + exp.begin_export(42) + exp.export_ensure_set(256) + exp.export_namedict( + {"sourceIPv4Address": ip_address("198.51.100.1"), "packetDeltaCount": 7} + ) + pkt2 = exp.to_bytes() + + # Collector uses fresh MessageBuffers sharing a single Session + sess = session.Session() + m1 = message.MessageBuffer(session=sess) + m1.from_bytes(pkt1) + assert list(m1.namedict_iterator()) == [] + + m2 = message.MessageBuffer(session=sess) + m2.from_bytes(pkt2) + assert list(m2.namedict_iterator()) == [ + {"sourceIPv4Address": ip_address("198.51.100.1"), "packetDeltaCount": 7} + ] + + +def test_session_template_expiration(): + tmpl = template.for_specs(256, "sourceIPv4Address") + sess = session.Session(template_lifetime=10.0) + sess.add_template(1, tmpl, now=100.0) + assert sess.get_template(1, 256, now=105.0) is tmpl + assert list(sess.active_template_ids(1, now=105.0)) == [256] + + # Expired after 10s + with pytest.raises(KeyError): + sess.get_template(1, 256, now=111.0) + assert list(sess.active_template_ids(1, now=111.0)) == [] + + # purge_expired_templates removes expired entries + sess.add_template(1, tmpl, now=200.0) + assert sess.purge_expired_templates(now=205.0) == 0 + assert sess.purge_expired_templates(now=215.0) == 1 + + sess.reset() + assert sess.templates == {} + + +def test_session_sequence_gap_detection(): + """Issue #5: collector-side sequence number verification.""" + gaps = [] + sess = session.Session( + sequence_gap_hook=lambda s, odid, sid, exp, got: gaps.append((odid, exp, got)) + ) + + tmpl = template.for_specs(256, "packetDeltaCount") + exp = message.MessageBuffer() + + # Message 1: seq 0, 2 records -> next expected seq is 2 + exp.begin_export(9) + exp.add_template(tmpl) + exp.export_ensure_set(256) + exp.export_namedict({"packetDeltaCount": 1}) + exp.export_namedict({"packetDeltaCount": 2}) + pkt1 = exp.to_bytes() + + # Message 2: seq 2, 1 record (in-order) -> next expected seq is 3 + exp.begin_export(9) + exp.export_ensure_set(256) + exp.export_namedict({"packetDeltaCount": 3}) + pkt2 = exp.to_bytes() + + # Message 3: dropped! + exp.begin_export(9) + exp.export_ensure_set(256) + exp.export_namedict({"packetDeltaCount": 4}) + _ = exp.to_bytes() + + # Message 4: seq 4 (gap: expected 3, got 4) + exp.begin_export(9) + exp.export_ensure_set(256) + exp.export_namedict({"packetDeltaCount": 5}) + pkt4 = exp.to_bytes() + + for pkt in (pkt1, pkt2, pkt4): + m = message.MessageBuffer(session=sess) + m.from_bytes(pkt) + list(m.namedict_iterator()) + + assert gaps == [(9, 3, 4)] + + +def test_datagram_writer_and_reader_udp_roundtrip(): + """Issues #22, #27, #31: DatagramWriter with template refresh + DatagramReader per peer.""" + sent = [] + dw = writer.DatagramWriter( + sent.append, mtu=128, template_refresh_interval=10.0 + ) + dw.set_domain(10) + tmpl = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount") + dw.add_template(tmpl) + dw.set_export_template(256) + + for i in range(15): + dw.export_namedict( + {"sourceIPv4Address": ip_address(0x0A000001 + i), "packetDeltaCount": i} + ) + # Trigger explicit template refresh + dw.refresh_templates() + dw.export_tuple((ip_address("10.0.0.99"), 99)) + dw.flush() + + assert len(sent) >= 2 + assert all(len(d) <= 128 for d in sent) + + dr = reader.DatagramReader(template_lifetime=600.0) + peer_a = ("192.0.2.10", 12345) + recs = [] + for dgram in sent: + recs.extend(dr.namedict_iterator(dgram, peer=peer_a)) + + assert len(recs) == 16 + assert recs[-1]["packetDeltaCount"] == 99 + + # Peer B has an isolated Session and shouldn't decode data-only datagram sent[1] + peer_b = ("192.0.2.20", 54321) + assert list(dr.namedict_iterator(sent[1], peer=peer_b)) == [] + + # Tuple iterator on DatagramReader + ielist = ie.spec_list(["packetDeltaCount"]) + tups = list(dr.tuple_iterator(sent[-1], ielist, peer=peer_a)) + assert (99,) in tups + + +def test_repeated_ies_in_template_issue10(): + """Issue #10: multiple occurrences of the same IE in a single template.""" + tmpl = template.for_specs( + 256, + "sourceIPv4Address", + "mplsTopLabelStackSection", + "mplsTopLabelStackSection", + "packetDeltaCount", + ) + + msg = message.MessageBuffer() + msg.begin_export(1) + msg.add_template(tmpl) + msg.export_ensure_set(256) + + rec_in = { + "sourceIPv4Address": ip_address("10.0.0.1"), + "mplsTopLabelStackSection": [b"\x00\x01\x00", b"\x00\x02\x01"], + "packetDeltaCount": 42, + } + msg.export_namedict(rec_in) + raw = msg.to_bytes() + + msg2 = message.MessageBuffer() + msg2.from_bytes(raw) + assert list(msg2.namedict_iterator()) == [rec_in] + + # Tuple iterator requesting both repeated occurrences + ielist = ie.spec_list( + ["mplsTopLabelStackSection", "mplsTopLabelStackSection", "packetDeltaCount"] + ) + assert list(msg2.tuple_iterator(ielist)) == [ + (b"\x00\x01\x00", b"\x00\x02\x01", 42) + ] + + # Requesting 3 occurrences when template only has 2 skips the template + ielist3 = ie.spec_list( + [ + "mplsTopLabelStackSection", + "mplsTopLabelStackSection", + "mplsTopLabelStackSection", + ] + ) + assert list(msg2.tuple_iterator(ielist3)) == [] diff --git a/tests/test_template_message.py b/tests/test_template_message.py index 6834bc7..340a30f 100644 --- a/tests/test_template_message.py +++ b/tests/test_template_message.py @@ -1,5 +1,5 @@ import struct -from datetime import datetime +from datetime import UTC, datetime from ipaddress import ip_address import pytest @@ -57,7 +57,7 @@ def test_varlen_first_ie_issue24(): long_name = "x" * 300 # also exercises 255-byte extended varlen encoding rec_in = { "applicationName": long_name, - "flowStartMilliseconds": datetime(2024, 1, 2, 3, 4, 5), + "flowStartMilliseconds": datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "sourceIPv4Address": ip_address("10.1.2.3"), "packetDeltaCount": 99, } diff --git a/tests/test_types.py b/tests/test_types.py index 642552e..c4d8e4f 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -23,7 +23,7 @@ class SubTypeError(types.IpfixTypeError): def test_all_builtin_types_roundtrip(): buf = memoryview(bytearray(64)) - dt = datetime(2024, 5, 6, 7, 8, 9, 123000) + dt = datetime(2024, 5, 6, 7, 8, 9, 123000, tzinfo=UTC) cases = [ ("octetArray", b"\xde\xad\xbe\xef", b"\xde\xad\xbe\xef"), @@ -42,7 +42,7 @@ def test_all_builtin_types_roundtrip(): ("boolean", False, False), ("macAddress", b"\x00\x11\x22\x33\x44\x55", b"\x00\x11\x22\x33\x44\x55"), ("string", "hello Grüezi", "hello Grüezi"), - ("dateTimeSeconds", dt, datetime(2024, 5, 6, 7, 8, 9)), + ("dateTimeSeconds", dt, datetime(2024, 5, 6, 7, 8, 9, tzinfo=UTC)), ("dateTimeMilliseconds", dt, dt), ("dateTimeMicroseconds", dt, dt), ("dateTimeNanoseconds", dt, dt), @@ -187,18 +187,18 @@ def test_datetime_aware_and_naive_encode_and_parse(): assert b_naive == b_utc == b_plus2 decoded = t.decode_single_value_from(buf, 0, t.length) - assert decoded.tzinfo is None + assert decoded.tzinfo is UTC - # ISO 8601 parse/unparse with Z and offset + # ISO 8601 parse/unparse with Z and offset (returns aware UTC in 1.0.0) assert types.for_name("dateTimeSeconds").valparse("2024-06-15T12:30:45Z") == datetime( - 2024, 6, 15, 12, 30, 45 + 2024, 6, 15, 12, 30, 45, tzinfo=UTC ) assert types.for_name("dateTimeMilliseconds").valparse( "2024-06-15 12:30:45.123+00:00" - ) == datetime(2024, 6, 15, 12, 30, 45, 123000) + ) == datetime(2024, 6, 15, 12, 30, 45, 123000, tzinfo=UTC) assert types.for_name("dateTimeMicroseconds").valparse( "2024-06-15 12:30:45.123456Z" - ) == datetime(2024, 6, 15, 12, 30, 45, 123456) + ) == datetime(2024, 6, 15, 12, 30, 45, 123456, tzinfo=UTC) assert types.for_name("dateTimeSeconds").valstr(naive) == "2024-06-15 12:30:45" assert ( types.for_name("dateTimeMilliseconds").valstr(naive) @@ -210,6 +210,24 @@ def test_datetime_aware_and_naive_encode_and_parse(): ) +def test_ntp_era1_2036_rollover(): + """RFC 5905 NTP Era 1 rollover (2036-02-07 06:28:16 UTC) round-trips cleanly.""" + buf = memoryview(bytearray(8)) + t = types.for_name("dateTimeMicroseconds") + + for dt in ( + datetime(2036, 2, 7, 6, 28, 15, 500000, tzinfo=UTC), # just before rollover + datetime(2036, 2, 7, 6, 28, 16, 0, tzinfo=UTC), # exact rollover (Era 1) + datetime(2036, 2, 7, 6, 28, 17, 123456, tzinfo=UTC), # just after rollover + datetime(2050, 1, 1, 0, 0, 0, 250000, tzinfo=UTC), # mid Era 1 + ): + end = t.encode_single_value_to(dt, buf, 0) + assert end == 8 + got = t.decode_single_value_from(buf, 0, 8) + assert got.tzinfo is UTC + assert abs((got - dt).total_seconds()) < 1e-5 + + def test_varlen_encode_decode_and_bounds(): buf = memoryview(bytearray(16)) diff --git a/tests/test_v9pdu.py b/tests/test_v9pdu.py index 1611873..86e0e5a 100644 --- a/tests/test_v9pdu.py +++ b/tests/test_v9pdu.py @@ -1,6 +1,6 @@ import io import struct -from datetime import datetime +from datetime import UTC, datetime from ipaddress import ip_address import pytest @@ -99,8 +99,8 @@ def test_time_adapter_namedict_and_tuple(): ta = v9pdu.TimeAdapter(v9pdu.SinglePduBuffer(pdu)) recs = list(ta.namedict_iterator()) assert len(recs) == 1 - assert recs[0]["flowStartMilliseconds"] == datetime(2023, 11, 14, 22, 13, 10) - assert recs[0]["flowEndMilliseconds"] == datetime(2023, 11, 14, 22, 13, 15, 500000) + assert recs[0]["flowStartMilliseconds"] == datetime(2023, 11, 14, 22, 13, 10, tzinfo=UTC) + assert recs[0]["flowEndMilliseconds"] == datetime(2023, 11, 14, 22, 13, 15, 500000, tzinfo=UTC) # Tuple iterator with sysuptime fields ta2 = v9pdu.TimeAdapter(v9pdu.SinglePduBuffer(pdu)) @@ -109,8 +109,8 @@ def test_time_adapter_namedict_and_tuple(): ) tups = list(ta2.tuple_iterator(ielist)) assert len(tups) == 1 - assert tups[0][3] == datetime(2023, 11, 14, 22, 13, 10) - assert tups[0][4] == datetime(2023, 11, 14, 22, 13, 15, 500000) + assert tups[0][3] == datetime(2023, 11, 14, 22, 13, 10, tzinfo=UTC) + assert tups[0][4] == datetime(2023, 11, 14, 22, 13, 15, 500000, tzinfo=UTC) # Tuple iterator without sysuptime fields passes through unchanged ta3 = v9pdu.TimeAdapter(v9pdu.SinglePduBuffer(pdu)) From e4af1d6c5741fefba5d7b6bee248a89627793f29 Mon Sep 17 00:00:00 2001 From: Brian Trammell Date: Sat, 21 Nov 2026 10:38:12 -0700 Subject: [PATCH 2/2] Expand v1.0.0 test coverage to 96% across core, v9pdu, UDP writer, and CLI --- tests/test_ieutils_cli.py | 21 +++++++ tests/test_session_udp.py | 44 ++++++++++++++ tests/test_template_message.py | 108 +++++++++++++++++++++++++++++++++ tests/test_v9pdu.py | 44 ++++++++++++++ 4 files changed, 217 insertions(+) diff --git a/tests/test_ieutils_cli.py b/tests/test_ieutils_cli.py index fca3ebf..dd6e884 100644 --- a/tests/test_ieutils_cli.py +++ b/tests/test_ieutils_cli.py @@ -127,3 +127,24 @@ def test_cli_ipfix2csv_and_ipfixstat(tmp_path, capsys): cli.main_ipfixstat(["-9", "-f", str(v9_file)]) v9_report = capsys.readouterr().out assert "Template 256 in domain 7" in v9_report + + # ipfixstat with missing template, template replacement, withdrawal, and --spec + spec_file = tmp_path / "extra.iespec" + spec_file.write_text("extraIE(35566/99)[4]\n", encoding="utf-8") + dset_missing_before = struct.pack("!HH 4s", 260, 8, b"\x00\x00\x00\x01") + dset_never_defined = struct.pack("!HH 4s", 299, 8, b"\x00\x00\x00\x02") + tset_v1 = struct.pack("!HH HH HH", 2, 12, 260, 1, 8, 4) + tset_v2 = struct.pack("!HH HH HH", 2, 12, 260, 1, 1, 8) + tset_wd = struct.pack("!HH HH", 2, 8, 260, 0) + body = dset_missing_before + dset_never_defined + tset_v1 + tset_v2 + tset_wd + stat_msg = struct.pack("!HHLLL", 10, 16 + len(body), 1700000000, 0, 5) + body + stat_file = tmp_path / "stats.ipfix" + stat_file.write_bytes(stat_msg) + + cli.main_ipfixstat(["-s", str(spec_file), "-f", str(stat_file)]) + stat_report = capsys.readouterr().out + assert "1 replacements" in stat_report + assert "2 missing sets total" in stat_report + assert "1 sets missing template with this ID" in stat_report + assert "Sets without templates" in stat_report + assert "ID 299 in domain 5" in stat_report diff --git a/tests/test_session_udp.py b/tests/test_session_udp.py index 9f8ff1a..30faa89 100644 --- a/tests/test_session_udp.py +++ b/tests/test_session_udp.py @@ -200,3 +200,47 @@ def test_repeated_ies_in_template_issue10(): ] ) assert list(msg2.tuple_iterator(ielist3)) == [] + + # 3 repeated occurrences in a single template exercises list append path + tmpl3 = template.for_specs( + 257, + "mplsTopLabelStackSection", + "mplsTopLabelStackSection", + "mplsTopLabelStackSection", + ) + msg3 = message.MessageBuffer() + msg3.begin_export(1) + msg3.add_template(tmpl3) + msg3.export_ensure_set(257) + rec3 = {"mplsTopLabelStackSection": [b"\x00\x01\x00", b"\x00\x02\x00", b"\x00\x03\x01"]} + msg3.export_namedict(rec3) + msg4 = message.MessageBuffer() + msg4.from_bytes(msg3.to_bytes()) + assert list(msg4.namedict_iterator()) == [rec3] + + +def test_datagram_writer_auto_refresh_and_set_domain(): + sent = [] + dw = writer.DatagramWriter(sent.append, mtu=128, template_refresh_interval=0.0) + dw.set_domain(1) + # Empty flush is a no-op + dw.flush() + assert dw.msgcount == 0 + + tmpl = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount") + dw.add_template(tmpl) + dw.set_export_template(256) + # With template_refresh_interval=0.0, export triggers automatic template refresh + dw.export_namedict( + {"sourceIPv4Address": ip_address("192.0.2.1"), "packetDeltaCount": 1} + ) + # Switching domain flushes domain 1 + dw.set_domain(2) + assert dw.msgcount >= 1 + assert len(sent) == dw.msgcount + + # DatagramReader with explicit shared Session + shared = session.Session() + dr = reader.DatagramReader(session=shared) + assert dr.session_for_peer(("1.2.3.4", 1)) is shared + assert dr.session_for_peer(("5.6.7.8", 2)) is shared diff --git a/tests/test_template_message.py b/tests/test_template_message.py index 340a30f..157b547 100644 --- a/tests/test_template_message.py +++ b/tests/test_template_message.py @@ -327,3 +327,111 @@ def test_unsigned256_in_message_roundtrip(): msg2 = message.MessageBuffer() msg2.from_bytes(raw) assert list(msg2.namedict_iterator()) == [rec] + + +def test_options_template_withdrawal_and_decode_errors(): + # Export and decode an Options Template Withdrawal via delete_template() + otmpl = template.for_specs(260, "observationDomainId", "octetDeltaCount", scopecount=1) + msg = message.MessageBuffer() + msg.begin_export(7) + msg.add_template(otmpl) + msg.delete_template(260, export=True) + raw = msg.to_bytes() + + msg2 = message.MessageBuffer() + msg2.from_bytes(raw) + assert list(msg2.namedict_iterator()) == [] + assert (7, 260) not in msg2.templates + + # Invalid Options Template Withdrawal with scopecount != 0 + bad_owithdraw = struct.pack("!HH HHH", 3, 10, 260, 0, 1) + bad_msg = struct.pack("!HHLLL", 10, 16 + len(bad_owithdraw), 0, 0, 7) + bad_owithdraw + msg3 = message.MessageBuffer() + msg3.from_bytes(bad_msg) + with pytest.raises(IpfixDecodeError): + list(msg3.namedict_iterator()) + + # Truncated template headers, IE specifiers, and bad set IDs in decode_template_from + with pytest.raises(IpfixDecodeError): + template.decode_template_from(b"\x01", 0, template.TEMPLATE_SET_ID) + with pytest.raises(IpfixDecodeError): + template.decode_template_from(b"\x01\x00\x00\x01", 0, template.OPTIONS_SET_ID) + with pytest.raises(IpfixDecodeError): + template.decode_template_from(b"\x01\x00\x00\x01", 0, 99) + with pytest.raises(IpfixDecodeError): + template.decode_template_from( + struct.pack("!HH H", 256, 1, 1), 0, template.TEMPLATE_SET_ID + ) + with pytest.raises(IpfixDecodeError): + template.decode_template_from( + struct.pack("!HH", 10, 0), 0, template.TEMPLATE_SET_ID + ) + with pytest.raises(IpfixDecodeError): + template.decode_template_from( + struct.pack("!HH HH", 10, 1, 1, 8), 0, template.TEMPLATE_SET_ID + ) + + # Bad set ID on encode_template_to and missing IE in packplan_for_ielist + with pytest.raises(IpfixEncodeError): + otmpl.encode_template_to(bytearray(32), 0, 99) + with pytest.raises(ValueError): + otmpl.packplan_for_ielist(ie.spec_list(["sourceIPv4Address"])) + + +def test_malformed_data_values_and_message_edge_cases(): + # Invalid boolean (byte 3) in fixed data record -> IpfixDecodeError + ie.for_spec("testBool(35566/50)[1]") + tset = struct.pack("!HH HH HHL", 2, 16, 256, 1, 0x8000 | 50, 1, 35566) + dset = struct.pack("!HH B", 256, 5, 3) + raw = struct.pack("!HHLLL", 10, 16 + len(tset) + len(dset), 0, 0, 1) + tset + dset + msg = message.MessageBuffer() + msg.from_bytes(raw) + with pytest.raises(IpfixDecodeError): + list(msg.namedict_iterator()) + + # Invalid UTF-8 in varlen string record -> IpfixDecodeError + tset = struct.pack("!HH HH HH", 2, 12, 257, 1, 96, 65535) + dset = struct.pack("!HH B 2s", 257, 7, 2, b"\xff\xfe") + raw = struct.pack("!HHLLL", 10, 16 + len(tset) + len(dset), 0, 0, 1) + tset + dset + msg = message.MessageBuffer() + msg.from_bytes(raw) + with pytest.raises(IpfixDecodeError): + list(msg.namedict_iterator()) + + # Truncated extended varlen prefix (0xff followed by only 1 byte) -> IpfixDecodeError + dset = struct.pack("!HH BB", 257, 6, 255, 0) + raw = struct.pack("!HHLLL", 10, 16 + len(tset) + len(dset), 0, 0, 1) + tset + dset + msg = message.MessageBuffer() + msg.from_bytes(raw) + with pytest.raises(IpfixDecodeError): + list(msg.namedict_iterator()) + + # Illegal set ID (< 256, not 2 or 3) emits UserWarning + bad_set = struct.pack("!HH 4s", 100, 8, b"\x00\x00\x00\x00") + raw = struct.pack("!HHLLL", 10, 16 + len(bad_set), 0, 0, 1) + bad_set + msg = message.MessageBuffer() + msg.from_bytes(raw) + with pytest.warns(UserWarning, match="illegal set id 100"): + assert list(msg.namedict_iterator()) == [] + + # set_export_time(None) and get_export_time() return aware UTC + msg = message.MessageBuffer() + msg.begin_export(1) + msg.set_export_time() + assert msg.get_export_time().tzinfo is UTC + + # EndOfMessage when varlen field exceeds underlying mbuf size + small = message.MessageBuffer(buf_sz=64) + small.mtu = 64 + small.begin_export(1) + small.add_template(template.for_specs(258, "applicationName")) + small.export_ensure_set(258) + with pytest.raises(message.EndOfMessage): + small.export_namedict({"applicationName": "a" * 100}) + + # EndOfMessage when export_template doesn't fit in MTU + tiny = message.MessageBuffer(buf_sz=64) + tiny.mtu = 22 + tiny.begin_export(1) + with pytest.raises(message.EndOfMessage): + tiny.add_template(template.for_specs(259, "sourceIPv4Address", "packetDeltaCount")) diff --git a/tests/test_v9pdu.py b/tests/test_v9pdu.py index 86e0e5a..2555d43 100644 --- a/tests/test_v9pdu.py +++ b/tests/test_v9pdu.py @@ -143,3 +143,47 @@ def test_v9_malformed_inputs(): bad_pen = _build_v9_pdu([_v9_template_set(256, [(0x8001, 4)])]) with pytest.raises(IpfixDecodeError): list(v9pdu.SinglePduBuffer(bad_pen).namedict_iterator()) + + # Non-zero trailing bytes in v9 template set + tbody = struct.pack("!HH HH", 256, 1, 8, 4) + b"\x01\x02" + bad_pad = _build_v9_pdu([struct.pack("!HH", 0, 4 + len(tbody)) + tbody]) + with pytest.raises(IpfixDecodeError): + list(v9pdu.SinglePduBuffer(bad_pad).namedict_iterator()) + + # Truncated v9 set header in SinglePduBuffer + with pytest.raises(IpfixDecodeError): + list(v9pdu.SinglePduBuffer(_build_v9_pdu([b"\x01\x00"])).namedict_iterator()) + + # StreamPduBuffer short PDU header, short set body, and EOF right after PDU header + with pytest.raises(IpfixDecodeError): + list(v9pdu.from_stream(io.BytesIO(b"\x00\x09\x00\x01\x00\x00")).namedict_iterator()) + with pytest.raises(IpfixDecodeError): + list( + v9pdu.from_stream( + io.BytesIO(_build_v9_pdu([struct.pack("!HH", 256, 20) + b"\x00\x00"])) + ).namedict_iterator() + ) + assert list(v9pdu.from_stream(io.BytesIO(_build_v9_pdu([]))).namedict_iterator()) == [] + + +def test_v9_hooks_and_illegal_setid(): + tset = _v9_template_set(256, [(8, 4)]) + dset = _v9_data_set(256, ip_address("10.0.0.1").packed) + unk_set = _v9_data_set(300, b"\x01\x02\x03\x04") + bad_set = struct.pack("!HH 4s", 100, 8, b"\x00\x00\x00\x00") + pdu = _build_v9_pdu([tset, dset, unk_set, bad_set], reccount=2) + + headers = [] + unknown = [] + ignored = [] + sp = v9pdu.SinglePduBuffer(pdu) + sp.message_header_hook = lambda p: headers.append(p.odid) + sp.unknown_data_set_hook = lambda p, b: unknown.append(len(b)) + sp.ignored_data_set_hook = lambda p, t, b: ignored.append((t.tid, len(b))) + # Re-parse header to exercise message_header_hook + sp._parse_pdu_header() + with pytest.warns(UserWarning, match="illegal set id 100"): + assert list(sp.tuple_iterator(ie.spec_list(["packetDeltaCount"]))) == [] + assert headers == [42] + assert unknown == [8] + assert ignored == [(256, 8)]