Skip to content

Commit 8e87770

Browse files
committed
fix(engines): write real PCAP traces for dpkt and scapy (#1507)
- toolkit/dpkt, toolkit/scapy: tcp_traceflow reports a FrameRecord, the engine's packet2dict mapping as before, carrying the captured octets, the PCAP record header and the exact time_epoch that only the PCAP trace dumper reads. - engines/dpkt: the PCAP and PCAP-NG readers yield a Timestamp (float) or, for a nanosecond PCAP, a DecimalTimestamp: the value dpkt yields, carrying the exact timestamp, the resolution and the original length. Under a dpkt without the reader internals this relies on, it reads with dpkt's own loop and warns. - engines/scapy: captures are read through PcapReader subclasses that stamp each packet with its PCAP or PCAP-NG interface resolution, and close once. - foundation/traceflow/data: new FrameRecord, a dict with packet, frame_info and time_epoch attributes, picklable with every protocol. - foundation/extraction, interface/misc: dpkt and scapy leave the trace_format='pcap' -> JSON fallback; #1508's Gap(1507) keeps pypcapfile. Traced PCAP files are byte-identical to the default engine's at both trace resolutions, and JSON, plist and tree output byte-identical to main's.
1 parent f96368b commit 8e87770

12 files changed

Lines changed: 912 additions & 153 deletions

File tree

‎pcapkit/foundation/engines/dpkt.py‎

Lines changed: 83 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,11 @@ def _read_packet(self, buf: 'bytes', block_type: 'int',
134134
little: Whether the enclosing section is little-endian.
135135
136136
Returns:
137-
Timestamp in seconds since the UNIX epoch, and the packet data.
137+
Timestamp in seconds since the UNIX epoch, and the packet data. The
138+
timestamp is a :class:`~pcapkit.toolkit.dpkt.Timestamp`: the
139+
:obj:`float` this reader always yielded, which also carries the exact
140+
value, the interface's resolution and the packet's original length,
141+
for the PCAP frame record of the packet (:issue:`1507`).
138142
139143
Raises:
140144
FormatError: If the section describes no interface of the ID the
@@ -143,6 +147,8 @@ def _read_packet(self, buf: 'bytes', block_type: 'int',
143147
"""
144148
import dpkt # isort:skip
145149

150+
from pcapkit.toolkit.dpkt import Timestamp # isort:skip
151+
146152
if block_type == Enum_BlockType.Enhanced_Packet_Block:
147153
tag = 'EPB'
148154
pkt = (dpkt.pcapng.EnhancedPacketBlockLE(buf) if little
@@ -168,7 +174,81 @@ def _read_packet(self, buf: 'bytes', block_type: 'int',
168174
timestamp = decimal.Decimal(ticks) / resolution + offset
169175

170176
self._linktype = interface.linktype
171-
return float(timestamp), pkt.pkt_data
177+
return (Timestamp(float(timestamp), timestamp, resolution, pkt.pkt_len), # pylint: disable=no-member
178+
pkt.pkt_data)
179+
180+
181+
def _pcap_reader() -> 'Type[PCAPReader]':
182+
"""A :class:`dpkt.pcap.Reader` that keeps each record's original length.
183+
184+
:class:`dpkt.pcap.Reader` parses every record header and then yields only
185+
``(timestamp, octets)``, so the record's original length and the file's
186+
resolution are lost by the time a PCAP frame record of the packet is built
187+
(:issue:`1507`). This subclass yields the same timestamp, as a
188+
:class:`~pcapkit.toolkit.dpkt.Timestamp` or, for a nanosecond file, a
189+
:class:`~pcapkit.toolkit.dpkt.DecimalTimestamp`, which carries the two.
190+
191+
Built when called, so that importing this module does not import `DPKT`_,
192+
and so that it always subclasses the :class:`dpkt.pcap.Reader` of the moment.
193+
194+
Warns:
195+
DPKTWarning: If this `DPKT`_'s reader lacks the attributes the loop reads
196+
-- they are private, and ``dpkt`` is not pinned. The reader then runs
197+
unchanged, and a traced PCAP record's original length is its captured
198+
length.
199+
200+
Returns:
201+
The reader type.
202+
203+
.. _DPKT: https://dpkt.readthedocs.io
204+
205+
"""
206+
import dpkt # isort:skip
207+
208+
from pcapkit.toolkit.dpkt import DecimalTimestamp, Timestamp # isort:skip
209+
210+
#: Attributes of :class:`dpkt.pcap.Reader` the loop below reads, as of dpkt 1.9.8.
211+
private = ('_Reader__f', '_Reader__ph', '_divisor')
212+
213+
class _Reader(dpkt.pcap.Reader): # type: ignore[name-defined,misc]
214+
def __init__(self, fileobj: 'IO[bytes]') -> 'None':
215+
super().__init__(fileobj)
216+
missing = [name for name in private if not hasattr(self, name)]
217+
#: Whether to read with :meth:`dpkt.pcap.Reader.__iter__` unchanged.
218+
self._upstream = bool(missing)
219+
if missing:
220+
warn(f"dpkt {getattr(dpkt, '__version__', '(unknown version)')}: "
221+
f"'dpkt.pcap.Reader' has no {', '.join(repr(name) for name in missing)}; "
222+
"reading PCAP records without their original length, so a traced "
223+
'PCAP record gives its captured length instead', DPKTWarning,
224+
stacklevel=stacklevel())
225+
226+
# NOTE: the loop is :meth:`dpkt.pcap.Reader.__iter__`'s, over the stream
227+
# and the record header type that method reads them through. A generator,
228+
# so ``dpkt.pcap.Reader.__init__`` calling it runs none of it before
229+
# :attr:`_upstream` is set.
230+
def __iter__(self) -> 'Iterator[tuple[float, bytes]]':
231+
if self._upstream:
232+
yield from super().__iter__()
233+
return
234+
235+
file, header = self._Reader__f, self._Reader__ph # pylint: disable=no-member
236+
nanosecond = isinstance(self._divisor, decimal.Decimal)
237+
resolution = 1_000_000_000 if nanosecond else 1_000_000
238+
while True:
239+
buf = file.read(header.__hdr_len__)
240+
if not buf:
241+
break
242+
hdr = header(buf)
243+
buf = file.read(hdr.caplen)
244+
value = hdr.tv_sec + (hdr.tv_usec / self._divisor)
245+
if nanosecond:
246+
yield DecimalTimestamp(value, resolution, hdr.len), buf
247+
else:
248+
exact = decimal.Decimal(hdr.tv_sec) + decimal.Decimal(hdr.tv_usec) / resolution
249+
yield Timestamp(value, exact, resolution, hdr.len), buf
250+
251+
return _Reader
172252

173253

174254
class DPKT(EngineBase['DPKTPacket']):
@@ -276,7 +356,7 @@ def run(self) -> 'None':
276356

277357
if ext.magic_number in PCAP.MAGIC_NUMBER:
278358
logger.debug('dpkt: reading %s as PCAP', ext._ifnm)
279-
reader = dpkt.pcap.Reader(ext._ifile)
359+
reader = _pcap_reader()(ext._ifile)
280360
elif ext.magic_number in PCAPNG.MAGIC_NUMBER:
281361
logger.debug('dpkt: reading %s as PCAP-NG', ext._ifnm)
282362
reader = PCAPNGReader(ext._ifile)

‎pcapkit/foundation/engines/scapy.py‎

Lines changed: 76 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,79 @@
4747
__all__ = ['Scapy']
4848

4949
if TYPE_CHECKING:
50-
from typing import Iterator
50+
from typing import Any, Iterator, Type
5151

5252
from scapy.packet import Packet as ScapyPacket
53+
from scapy.utils import PcapReader
5354

5455
from pcapkit.foundation.extraction import Extractor
5556

5657
#: logging.Logger: Module-level logger, a child of the package-wide
5758
#: :data:`pcapkit.utilities.logging.logger`.
5859
logger = get_logger(__name__)
5960

61+
def _reader_type() -> 'Type[PcapReader]':
62+
"""A :class:`scapy.utils.PcapReader` that stamps each packet with its resolution.
63+
64+
`Scapy`_'s readers convert a record's timestamp to a :class:`~decimal.Decimal`
65+
and drop the resolution it was counted in, and an exact count of microseconds
66+
comes out with the same digits whether the capture counted microseconds or
67+
nanoseconds. The PCAP frame record of a packet needs that resolution, so these
68+
subclasses attach it with :func:`pcapkit.toolkit.scapy.attach_resolution`:
69+
from the global header of a PCAP, and from the interface of each PCAP-NG
70+
packet block, which :meth:`~scapy.utils.RawPcapNgReader._read_block` is the
71+
last place to see.
72+
73+
Built when called, so that importing this module does not import `Scapy`_,
74+
and so that it always subclasses the :class:`scapy.utils.PcapReader` of the
75+
moment.
76+
77+
Returns:
78+
A reader type, which opens a PCAP-NG file as its PCAP-NG alternative.
79+
80+
.. _Scapy: https://scapy.net
81+
82+
"""
83+
from scapy.utils import PcapNgReader, PcapReader # isort:skip
84+
85+
from pcapkit.toolkit.scapy import attach_resolution # isort:skip
86+
87+
class _Closing:
88+
# ``sniff`` closes the reader at the end of the file, and the engine closes
89+
# it again in case ``sniff`` raised first; only the first close is real,
90+
# since closing a gzip reader twice raises
91+
_closed = False
92+
93+
def close(self) -> 'None':
94+
if not self._closed:
95+
self._closed = True
96+
super().close() # type: ignore[misc]
97+
98+
class _PcapReader(_Closing, PcapReader):
99+
def read_packet(self, *args: 'Any', **kwargs: 'Any') -> 'ScapyPacket':
100+
packet = super().read_packet(*args, **kwargs)
101+
attach_resolution(packet, 1_000_000_000 if self.nano else 1_000_000)
102+
return packet
103+
104+
class _PcapNgReader(_Closing, PcapNgReader):
105+
# the metaclass makes this ``_PcapReader``'s alternative in turn
106+
alternative = _PcapReader
107+
108+
_resolution = 1_000_000
109+
110+
def _read_block(self, *args: 'Any', **kwargs: 'Any') -> 'Any':
111+
block = super()._read_block(*args, **kwargs)
112+
if block is not None:
113+
self._resolution = block[1].tsresol
114+
return block
115+
116+
def read_packet(self, *args: 'Any', **kwargs: 'Any') -> 'ScapyPacket':
117+
packet = super().read_packet(*args, **kwargs)
118+
attach_resolution(packet, self._resolution)
119+
return packet
120+
121+
return _PcapReader
122+
60123

61124
class Scapy(EngineBase['ScapyPacket']):
62125
"""Scapy engine support.
@@ -179,7 +242,18 @@ def run(self) -> 'None':
179242

180243
# extract & analyse file
181244
logger.debug('scapy: sniffing %s', ext._ifnm)
182-
self._extmp = iter(self._expkg.sniff(offline=ext._ifnm))
245+
# NOTE: the reader is opened here rather than by ``sniff(offline=...)`` so
246+
# that every packet carries its capture's timestamp resolution, which
247+
# Scapy's own readers discard (#1507). Labelled with the file name, as
248+
# ``offline=`` labels it, so ``Packet.sniffed_on`` is unchanged. ``sniff``
249+
# closes it at the end of the file, as it closes the reader ``offline=``
250+
# opens; it is closed here as well in case ``sniff`` raised first, which
251+
# the reader takes as a no-op once closed.
252+
reader = _reader_type()(ext._ifnm)
253+
try:
254+
self._extmp = iter(self._expkg.sniff(opened_socket={reader: ext._ifnm}))
255+
finally:
256+
reader.close()
183257

184258
def read_frame(self) -> 'ScapyPacket':
185259
"""Read frames with Scapy engine.

‎pcapkit/foundation/extraction.py‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1431,13 +1431,12 @@ def __init__(self,
14311431
# <pcapkit.foundation.traceflow.traceflow.TraceFlowBase.__init__>`
14321432
# itself substitutes ``'pcap'`` for ``None``.
14331433
#
1434-
# DPKT and Scapy belong on this list too: their adapters build the frame
1435-
# with ``packet2dict`` exactly as the other two do, so both crash the
1436-
# same way. The guard is written from what the adapters produce, not
1437-
# from which engines are seen to crash, because an engine that
1438-
# dissects nothing never feeds the tracer and so hides the defect
1439-
# rather than avoiding it (#406).
1440-
if (self._exnam in ('dpkt', 'scapy', 'pyshark', 'pypcapfile')
1434+
# The guard is written from what the adapters produce, not from which
1435+
# engines are seen to crash, because an engine that dissects nothing
1436+
# never feeds the tracer and so hides the defect rather than avoiding
1437+
# it (#406). DPKT and Scapy are off the list because their adapters
1438+
# build a PCAP frame record from the captured octets (#1507).
1439+
if (self._exnam in ('pyshark', 'pypcapfile')
14411440
and trace_format in ('pcap', 'cap', None)):
14421441
warn(f"'Extractor(engine={self._exnam})' does not support 'trace_format={trace_format}'; "
14431442
"using 'trace_format=\"json\"' instead", FormatWarning, stacklevel=stacklevel())

‎pcapkit/foundation/traceflow/data/data.py‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,16 @@
55

66
from pcapkit.corekit.infoclass import Info, info_final
77

8-
__all__ = ['TraceFlowData', 'Deferred', 'DeferredPacket']
8+
__all__ = ['TraceFlowData', 'Deferred', 'DeferredPacket', 'FrameRecord']
99

1010
if TYPE_CHECKING:
11+
from decimal import Decimal
1112
from typing import Any, Optional
1213

1314
from pcapkit.foundation.reassembly.data.tcp import Datagram as TCP_Datagram
1415
from pcapkit.foundation.reassembly.tcp import TCP as TCP_Reassembly
1516
from pcapkit.foundation.traceflow.data.tcp import Index as TCP_Index
17+
from pcapkit.protocols.data.misc.pcap.frame import FrameInfo as Data_FrameInfo
1618

1719

1820
class Deferred:
@@ -141,6 +143,68 @@ def to_dict(self) -> 'dict[str, Any]':
141143
return super().to_dict() # type: ignore[misc] # pylint: disable=no-member
142144

143145

146+
class FrameRecord(dict):
147+
"""A frame as a third-party engine's flow tracing adapter reports it.
148+
149+
The mapping is the engine's own dissection of the frame, exactly as before, so
150+
every trace format that takes a mapping writes it unchanged. Beside it, as
151+
attributes the mapping does not show, it carries what the PCAP trace dumper
152+
reads of a frame -- :meth:`PCAPIO._append_value
153+
<pcapkit.dumpkit.pcap.PCAPIO._append_value>` takes ``packet``,
154+
``frame_info`` and ``time_epoch`` -- so ``trace_format='pcap'`` writes the
155+
frame's record too (:issue:`1507`).
156+
157+
Args:
158+
mapping: The engine's dissection of the frame.
159+
packet: The frame's captured octets.
160+
frame_info: The frame's PCAP record header.
161+
time_epoch: The frame's exact UNIX timestamp.
162+
163+
"""
164+
165+
__slots__ = ('packet', 'frame_info', 'time_epoch')
166+
167+
#: The frame's captured octets.
168+
packet: 'bytes'
169+
#: The frame's PCAP record header, with the fraction in the capture's own
170+
#: resolution.
171+
frame_info: 'Data_FrameInfo'
172+
#: The frame's exact UNIX timestamp, from which
173+
#: :meth:`PCAPIO._make_timestamp <pcapkit.dumpkit.pcap.PCAPIO._make_timestamp>`
174+
#: tells which resolution ``frame_info.ts_usec`` is in. A
175+
#: :class:`~decimal.Decimal`, since only that settles it exactly.
176+
time_epoch: 'Decimal'
177+
178+
def __init__(self, mapping: 'dict[str, Any]', *, packet: 'bytes',
179+
frame_info: 'Data_FrameInfo', time_epoch: 'Decimal') -> 'None':
180+
super().__init__(mapping)
181+
self.packet = packet
182+
self.frame_info = frame_info
183+
self.time_epoch = time_epoch
184+
185+
def __reduce__(self) -> 'tuple[Any, ...]':
186+
# NOTE: spelled out because a ``dict`` subclass with ``__slots__`` cannot
187+
# be pickled with protocol 0 or 1 otherwise
188+
return _frame_record, (dict(self), self.packet, self.frame_info, self.time_epoch)
189+
190+
191+
def _frame_record(mapping: 'dict[str, Any]', packet: 'bytes',
192+
frame_info: 'Data_FrameInfo', time_epoch: 'Decimal') -> 'FrameRecord':
193+
"""Rebuild a pickled :class:`FrameRecord`.
194+
195+
Args:
196+
mapping: The engine's dissection of the frame.
197+
packet: The frame's captured octets.
198+
frame_info: The frame's PCAP record header.
199+
time_epoch: The frame's exact UNIX timestamp.
200+
201+
Returns:
202+
The frame record.
203+
204+
"""
205+
return FrameRecord(mapping, packet=packet, frame_info=frame_info, time_epoch=time_epoch)
206+
207+
144208
@info_final
145209
class TraceFlowData(Info):
146210
"""Data storage for flow tracing."""

‎pcapkit/interface/misc.py‎

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from pcapkit.foundation.extraction import Extractor
2222
from pcapkit.foundation.reassembly.tcp import TCP as TCP_Reassembly
2323
from pcapkit.utilities.exceptions import stacklevel
24-
from pcapkit.utilities.warnings import EngineWarning, FormatWarning, warn
24+
from pcapkit.utilities.warnings import EngineWarning, warn
2525

2626
if TYPE_CHECKING:
2727
from typing import Any, Callable, Optional
@@ -115,30 +115,6 @@ def follow_tcp_stream(fin: 'Optional[str]' = None, verbose: 'bool' = False,
115115
EngineWarning, stacklevel=stacklevel())
116116
engine = None
117117

118-
# NOTE: the DPKT and Scapy engines hand their frames to the flow tracer as plain
119-
# :obj:`dict`\\ s, which the PCAP trace dumper cannot re-serialise -- it reaches
120-
# for ``frame.packet`` and dies with ``AttributeError: 'dict' object has no
121-
# attribute 'packet'`` (#399). The tracer defaults an unset ``format`` to
122-
# ``'pcap'``, so following a stream through either engine would crash *during
123-
# extraction*, before the reassembly below ever runs.
124-
#
125-
# :class:`Extractor <pcapkit.foundation.extraction.Extractor>` guards both
126-
# engines itself, so this is not what keeps the extraction alive -- it is
127-
# what keeps it *quiet*. The two guards choose the same replacement format and so
128-
# produce byte-identical traces; they differ only in when they complain. The
129-
# Extractor warns for every substitution it makes, including the one nobody asked
130-
# for, whereas here an unset ``format`` is not a request and is upgraded silently,
131-
# and only an explicit but unusable one draws a warning -- with a message naming
132-
# the engine's limitation rather than the ``trace_format=`` argument this function
133-
# does not expose. Removing this therefore would not change any trace file, but it
134-
# would make ``follow_tcp_stream(engine='dpkt')`` warn about a default the caller
135-
# never chose.
136-
if engine is not None and engine.lower() in ('dpkt', 'scapy') and format in ('pcap', 'cap', None):
137-
if format is not None:
138-
warn(f"extraction engine {engine} cannot write '{format}' trace files; "
139-
"using 'json' instead", FormatWarning, stacklevel=stacklevel())
140-
format = 'json'
141-
142118
extraction = Extractor(fin=fin, fout=None, format=None, auto=True, extension=extension,
143119
store=True, files=False, nofile=True, verbose=verbose, engine=engine,
144120
layer=None, protocol=None, ip=False, ipv4=False, ipv6=False, tcp=True,

0 commit comments

Comments
 (0)