Skip to content

Commit f0e0802

Browse files
committed
fix(engines): dpkt float timestamps, Simple Packet Blocks and raw-IP tracing (#1501, #1520, #1548)
- The dpkt reassembly and flow-tracing adapters passed the reader's timestamp straight through, so a nanosecond PCAP gave reassembly and the flow tracer a Decimal where every other engine gives a float, and flow labels were spelled with nine places. They now hand on float(timestamp), as the default and scapy toolkits do; the PCAP frame record is still built from the exact timestamp attached to the frame, so traces stay byte-exact. - PCAPNGReader skipped Simple Packet Blocks, dropping their packets and renumbering every later frame. It now parses an SPB with pcapkit's own PCAPNG against interface 0, dates it at the epoch as the default engine does, and keeps the block's original length. The engine docs no longer say that dpkt drops them. - On a raw-IP link type (228, 229) dpkt reads a frame as a bare IP or IP6, which names no ip or ip6 layer, so all four adapters returned None and nothing was reassembled or traced. They now take such a packet as its own network layer. - Deletes the Gap(1501) and Gap(1520) rows from the engine-agreement table, and the labels=False workaround from the nanosecond PCAP trace test.
1 parent cf6e78a commit f0e0802

7 files changed

Lines changed: 323 additions & 69 deletions

File tree

‎docs/source/pcapkit/foundation/engines/3rdparty.rst‎

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -64,26 +64,6 @@ support, as is used by :class:`pcapkit.foundation.extraction.Extractor`.
6464

6565
.. _DPKT: https://dpkt.readthedocs.io
6666

67-
.. important::
68-
69-
On PCAP-NG, `DPKT`_ yields **Enhanced Packet Blocks and (obsolete) Packet
70-
Blocks only**. ``dpkt.pcapng.Reader.__iter__`` skips every other block type
71-
without a warning (``# just ignore other blocks``, as of ``dpkt`` 1.9.8), and
72-
:class:`~pcapkit.foundation.engines.dpkt.PCAPNGReader`, which this engine
73-
reads PCAP-NG with, keeps that block set. It includes the **Simple Packet
74-
Block**, which carries a packet just as an Enhanced Packet Block does. Such packets are silently missing from this
75-
engine's output, and the frames after them are numbered as if they had never
76-
been captured.
77-
78-
Reading :file:`examples/captures/test.pcapng` -- four Enhanced Packet Blocks
79-
and one Simple Packet Block, across two sections -- this engine gives four
80-
frames where the default engine and
81-
:class:`~pcapkit.foundation.engines.scapy.Scapy` give five; the missing one is
82-
frame 4, the Simple Packet Block. The second Section Header Block is not the
83-
cause: the Enhanced Packet Block after it is read. This is a limitation of
84-
`DPKT`_, not of :mod:`pcapkit`, so read a capture that may contain Simple
85-
Packet Blocks with the default engine instead.
86-
8767
.. note::
8868

8969
``dpkt.pcapng.Reader`` reads only the **first** Interface Description Block
@@ -93,6 +73,12 @@ support, as is used by :class:`pcapkit.foundation.extraction.Extractor`.
9373
resolves each packet's link type, ``if_tsresol`` and ``if_tsoffset`` from
9474
the interface it names, in its own section (:issue:`1379`).
9575

76+
``dpkt.pcapng.Reader`` also skips Simple Packet Blocks, which `DPKT`_ has no
77+
type for; :class:`~pcapkit.foundation.engines.dpkt.PCAPNGReader` reads them
78+
through :mod:`pcapkit`'s own :class:`~pcapkit.protocols.misc.pcapng.PCAPNG`
79+
and, since the block carries no timestamp, dates them 0, as the default
80+
engine does (:issue:`1520`).
81+
9682
.. autoclass:: pcapkit.foundation.engines.dpkt.DPKT
9783
:no-members:
9884
:show-inheritance:

‎pcapkit/foundation/engines/dpkt.py‎

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,11 @@
3232

3333
from pcapkit.foundation.engines.pcapng import Context
3434
from pcapkit.foundation.extraction import Extractor
35+
from pcapkit.protocols.data.misc.pcapng import IF_TSResolOption as Data_IF_TSResolOption
3536
from pcapkit.protocols.data.misc.pcapng import \
3637
InterfaceDescriptionBlock as Data_InterfaceDescriptionBlock
3738
from pcapkit.protocols.data.misc.pcapng import SectionHeaderBlock as Data_SectionHeaderBlock
39+
from pcapkit.protocols.data.misc.pcapng import SimplePacketBlock as Data_SimplePacketBlock
3840

3941
Reader = Union[PCAPReader, 'PCAPNGReader']
4042

@@ -55,8 +57,11 @@ class PCAPNGReader:
5557
``if_tsresol`` and ``if_tsoffset`` from the interface it names. Packet
5658
blocks are still decoded by `DPKT`_.
5759
58-
As :class:`dpkt.pcapng.Reader` does, it yields Enhanced Packet Blocks and
59-
(obsolete) Packet Blocks only, and skips every other block.
60+
It yields Enhanced Packet Blocks, (obsolete) Packet Blocks and Simple Packet
61+
Blocks, and skips every other block. :class:`dpkt.pcapng.Reader` skips the
62+
Simple Packet Block too, and `DPKT`_ has no type for one, so that block is
63+
parsed with :class:`~pcapkit.protocols.misc.pcapng.PCAPNG` as well
64+
(:issue:`1520`).
6065
6166
.. _DPKT: https://dpkt.readthedocs.io
6267
@@ -123,6 +128,8 @@ def _read(self) -> 'Iterator[tuple[float, bytes]]':
123128
self._ctx.interfaces.append(cast('Data_InterfaceDescriptionBlock', idb.info))
124129
elif block_type in (Enum_BlockType.Enhanced_Packet_Block, Enum_BlockType.Packet_Block):
125130
yield self._read_packet(buf, block_type, byteorder == 'little')
131+
elif block_type == Enum_BlockType.Simple_Packet_Block:
132+
yield self._read_simple(buf)
126133

127134
def _read_packet(self, buf: 'bytes', block_type: 'int',
128135
little: 'bool') -> 'tuple[float, bytes]':
@@ -177,6 +184,46 @@ def _read_packet(self, buf: 'bytes', block_type: 'int',
177184
return (Timestamp(float(timestamp), timestamp, resolution, pkt.pkt_len), # pylint: disable=no-member
178185
pkt.pkt_data)
179186

187+
def _read_simple(self, buf: 'bytes') -> 'tuple[float, bytes]':
188+
"""Decode a Simple Packet Block, against the section's first interface.
189+
190+
`DPKT`_ has no type for this block, so it is parsed by
191+
:class:`~pcapkit.protocols.misc.pcapng.PCAPNG`, as for the default
192+
engine: the packet data is ``min(original_len, snaplen)`` octets, with
193+
the snaplen of interface 0.
194+
195+
Args:
196+
buf: Whole block, as read from the file.
197+
198+
Returns:
199+
Timestamp and packet data, as :meth:`_read_packet` returns them. A
200+
Simple Packet Block carries no timestamp, so the packet is dated at
201+
the UNIX epoch, as the default engine dates it; the original length
202+
is the block's own.
203+
204+
Raises:
205+
FormatError: If the section describes no interface. A Simple Packet
206+
Block names none, so it refers to the first (Section 4.4 of the
207+
PCAP-NG specification).
208+
209+
"""
210+
from pcapkit.protocols.misc.pcapng import PCAPNG as P_PCAPNG
211+
from pcapkit.toolkit.dpkt import Timestamp # isort:skip
212+
213+
if not self._ctx.interfaces:
214+
raise FormatError('PCAP-NG: [SPB] section has no interface description block')
215+
interface = self._ctx.interfaces[0]
216+
block = P_PCAPNG(buf, num=0, sct=self._sect, ctx=self._ctx)
217+
spb = cast('Data_SimplePacketBlock', block.info)
218+
219+
tsresol = cast('Optional[Data_IF_TSResolOption]',
220+
interface.options.get(Enum_OptionType.if_tsresol))
221+
resolution = 1_000_000 if tsresol is None else tsresol.resolution
222+
223+
self._linktype = interface.linktype
224+
return (Timestamp(0.0, decimal.Decimal(0), resolution, spb.original_len),
225+
bytes(spb.packet))
226+
180227

181228
def _pcap_reader() -> 'Type[PCAPReader]':
182229
"""A :class:`dpkt.pcap.Reader` that keeps each record's original length.
@@ -258,10 +305,9 @@ class DPKT(EngineBase['DPKTPacket']):
258305
:class:`dpkt.pcapng.Reader`, so each packet takes the link type and the
259306
timestamp resolution and offset of the interface it was captured on.
260307
261-
Like `DPKT`_'s reader, it yields Enhanced Packet Blocks and (obsolete)
262-
Packet Blocks only, and skips every other block without a warning -- the
263-
Simple Packet Block included. A packet carried in a Simple Packet Block is
264-
therefore missing from this engine's output; the default engine reads it.
308+
It reads every packet block the default engine reads -- the Enhanced, the
309+
Simple and the (obsolete) Packet Block -- and skips every other block
310+
without a warning. `DPKT`_'s own reader skips the Simple Packet Block too.
265311
266312
.. _DPKT: https://dpkt.readthedocs.io
267313

‎pcapkit/toolkit/dpkt.py‎

Lines changed: 49 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,9 @@ class RecordTimestamp:
8181
resolution and its original length would be lost between the reader and
8282
:func:`packet2frame`. The engine's readers yield a :class:`Timestamp` or a
8383
:class:`DecimalTimestamp` instead, which *is* the value `DPKT`_ yields --
84-
so reassembly and flow labels see exactly what they did before -- and also
85-
carries those three.
84+
so a stored frame's timestamp is exactly what it was before -- and also
85+
carries those three. Reassembly and flow tracing are handed a plain
86+
:obj:`float` of it, as by every other engine (:issue:`1501`).
8687
8788
.. _DPKT: https://dpkt.readthedocs.io
8889
@@ -395,6 +396,30 @@ def _layer2bytes(packet: 'Packet', layer: 'Packet') -> 'tuple[bytes, bool]':
395396
return packet2bytes(layer), False
396397

397398

399+
def _network(packet: 'Packet') -> 'Optional[IP | IP6]':
400+
"""Fetch the network layer of a DPKT packet.
401+
402+
Args:
403+
packet: DPKT packet, i.e. the outermost layer.
404+
405+
Returns:
406+
The packet itself if it is an IPv4 or IPv6 packet, as `DPKT`_ reads every
407+
frame of a raw-IP link type (:issue:`1548`); otherwise the IPv4 or IPv6
408+
payload of its link layer, which `DPKT`_ names ``ip`` or ``ip6`` -- a
409+
bare IP packet names neither -- or :data:`None` if it has none.
410+
411+
.. _DPKT: https://dpkt.readthedocs.io
412+
413+
"""
414+
import dpkt # isort:skip
415+
416+
if isinstance(packet, (dpkt.ip.IP, dpkt.ip6.IP6)):
417+
return packet
418+
if hasattr(packet, 'ip'):
419+
return cast('IP', packet.ip)
420+
return getattr(packet, 'ip6', None)
421+
422+
398423
def ipv6_hdr_len(ipv6: 'IP6') -> 'int':
399424
"""Calculate length of headers before IPv6 Fragment header.
400425
@@ -482,7 +507,9 @@ def ipv4_reassembly(packet: 'Packet', timestamp: 'float', *,
482507
than on the packet, so it is passed in -- as :func:`tcp_traceflow`
483508
does. A caller holding only a frame can read it back with
484509
:func:`packet2timestamp`, which is where
485-
:class:`~pcapkit.foundation.engines.dpkt.DPKT` leaves it.
510+
:class:`~pcapkit.foundation.engines.dpkt.DPKT` leaves it. Handed on
511+
as a :obj:`float`, as every engine's adapters do, though `DPKT`_ reads
512+
a nanosecond PCAP's as a :class:`~decimal.Decimal` (:issue:`1501`).
486513
count: Packet index. If not provided, default to ``-1``.
487514
488515
Returns:
@@ -507,7 +534,9 @@ def ipv4_reassembly(packet: 'Packet', timestamp: 'float', *,
507534
:class:`pcapkit.foundation.reassembly.ipv4.IPv4`
508535
509536
"""
510-
ipv4 = getattr(packet, 'ip', None) # type: Optional[IP]
537+
network = _network(packet)
538+
# an IPv6 layer is the one with extension headers, as in ``_wire_hdr_len``
539+
ipv4 = None if hasattr(network, 'extension_hdrs') else network
511540
if ipv4 is not None:
512541
if ipv4.df: # dismiss not fragmented packet
513542
return None
@@ -537,7 +566,7 @@ def ipv4_reassembly(packet: 'Packet', timestamp: 'float', *,
537566
tl=ipv4.len, # total length, header includes
538567
header=wire[:ihl], # raw bytes type header
539568
payload=bytearray(wire[ihl:]), # raw bytearray type payload
540-
timestamp=timestamp, # capture timestamp
569+
timestamp=float(timestamp), # capture timestamp
541570
)
542571
return data
543572
return None
@@ -551,6 +580,7 @@ def ipv6_reassembly(packet: 'Packet', timestamp: 'float', *,
551580
packet: DPKT packet.
552581
timestamp: Capture timestamp of the packet, which drives the reassembly
553582
timeout; :func:`packet2timestamp` reads it back off a stored frame.
583+
Handed on as a :obj:`float`, as for :func:`ipv4_reassembly`.
554584
count: Packet index. If not provided, default to ``-1``.
555585
556586
Returns:
@@ -575,7 +605,8 @@ def ipv6_reassembly(packet: 'Packet', timestamp: 'float', *,
575605
:class:`pcapkit.foundation.reassembly.ipv6.IPv6`
576606
577607
"""
578-
ipv6 = getattr(packet, 'ip6', None) # type: Optional[IP6]
608+
network = _network(packet)
609+
ipv6 = cast('IP6', network) if hasattr(network, 'extension_hdrs') else None
579610
if ipv6 is not None:
580611
ipv6_frag = ipv6.extension_hdrs.get(44) # type: Optional[IP6FragmentHeader]
581612
if ipv6_frag is None: # dismiss not fragmented packet
@@ -618,7 +649,7 @@ def ipv6_reassembly(packet: 'Packet', timestamp: 'float', *,
618649
tl=hdr_len + len(payload), # total length, header includes
619650
header=wire[:hdr_len], # raw bytes type header before IPv6-Frag
620651
payload=bytearray(payload), # raw bytearray type payload after IPv6-Frag
621-
timestamp=timestamp, # capture timestamp
652+
timestamp=float(timestamp), # capture timestamp
622653
)
623654
return data
624655
return None
@@ -632,6 +663,7 @@ def tcp_reassembly(packet: 'Packet', timestamp: 'float', *,
632663
packet: DPKT packet.
633664
timestamp: Capture timestamp of the packet, which drives the reassembly
634665
timeout; :func:`packet2timestamp` reads it back off a stored frame.
666+
Handed on as a :obj:`float`, as for :func:`ipv4_reassembly`.
635667
count: Packet index. If not provided, default to ``-1``.
636668
637669
Returns:
@@ -655,11 +687,8 @@ def tcp_reassembly(packet: 'Packet', timestamp: 'float', *,
655687
:class:`pcapkit.foundation.reassembly.tcp.TCP`
656688
657689
"""
658-
if hasattr(packet, 'ip'):
659-
ip = cast('IP', packet.ip)
660-
elif hasattr(packet, 'ip6'):
661-
ip = cast('IP6', packet.ip6)
662-
else:
690+
ip = _network(packet)
691+
if ip is None:
663692
return None
664693

665694
tcp = getattr(ip, 'tcp', None) # type: Optional[TCP]
@@ -688,7 +717,7 @@ def tcp_reassembly(packet: 'Packet', timestamp: 'float', *,
688717
first=tcp.seq, # first sequence number of payload
689718
last=tcp.seq + raw_len - 1, # last sequence number of payload
690719
len=raw_len, # payload length, header excludes
691-
timestamp=timestamp, # capture timestamp
720+
timestamp=float(timestamp), # capture timestamp
692721
)
693722
return data
694723
return None
@@ -700,7 +729,10 @@ def tcp_traceflow(packet: 'Packet', timestamp: 'float', *,
700729
701730
Args:
702731
packet: DPKT packet.
703-
timestamp: Timestamp of the packet.
732+
timestamp: Timestamp of the packet, handed on as a :obj:`float`, as for
733+
:func:`ipv4_reassembly`. The PCAP frame record is built from the
734+
exact timestamp attached by :func:`attach_timestamp`, if any; see
735+
:func:`packet2frame`.
704736
data_link: Data link layer protocol (from global header).
705737
count: Packet index. If not provided, default to ``-1``.
706738
@@ -725,11 +757,8 @@ def tcp_traceflow(packet: 'Packet', timestamp: 'float', *,
725757
:class:`pcapkit.foundation.traceflow.tcp.TCP`
726758
727759
"""
728-
if hasattr(packet, 'ip'):
729-
ip = cast('IP', packet.ip)
730-
elif hasattr(packet, 'ip6'):
731-
ip = cast('IP6', packet.ip6)
732-
else:
760+
ip = _network(packet)
761+
if ip is None:
733762
return None
734763

735764
tcp = getattr(ip, 'tcp', None) # type: Optional[TCP]
@@ -750,7 +779,7 @@ def tcp_traceflow(packet: 'Packet', timestamp: 'float', *,
750779
dst=ipaddress.ip_address(ip.dst), # destination IP
751780
srcport=tcp.sport, # TCP source port
752781
dstport=tcp.dport, # TCP destination port
753-
timestamp=timestamp, # timestamp
782+
timestamp=float(timestamp), # timestamp
754783
seq=tcp.seq, # TCP sequence number
755784
ack=tcp.ack, # TCP acknowledgement number
756785
header=wire[:tcp.off * 4], # raw bytes type header

0 commit comments

Comments
 (0)