Skip to content

Commit e5f3af3

Browse files
authored
fix(toolkit): dpkt and scapy find TCP in IPv4 where the default engine does (#1606, #1617) (#1624)
- dpkt and scapy step over an AH or IPv6 extension header carried directly in IPv4 (protocols 0, 43, 44, 51, 60, 135, 139) by the default engine's own rules, via pypcapfile's _past_extension_headers, bounded at EXTENSION_HEADER_LIMIT; the TCP segment or IP-in-IP tunnel behind them is decoded from the captured octets. Behind such a header, TCP is read only as the default TCP parser accepts it. - dpkt keeps a tunnel it raises anything decoding undecoded, as its engine keeps such a frame raw, rather than ending the extraction. - dpkt's packet2dict and packet2chain treat only a packet-like payload as a layer; a str payload, such as VRRP's '', is leaf data and ends the chain. - scapy's carrier walk now runs top-down and stops at a later IPv4 fragment, which scapy still dissects IPv6 and AH in. - Drop the #1606 gap row from the #1604 chain-limit agreement test.
1 parent bbcabf1 commit e5f3af3

4 files changed

Lines changed: 589 additions & 43 deletions

File tree

‎pcapkit/toolkit/dpkt.py‎

Lines changed: 141 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@
2323
from pcapkit.foundation.traceflow.data.data import FrameRecord
2424
from pcapkit.foundation.traceflow.data.tcp import Packet as TF_TCP_Packet
2525
from pcapkit.protocols.data.misc.pcap.frame import FrameInfo as Data_FrameInfo
26-
from pcapkit.toolkit.pypcapfile import _default_accepts
26+
from pcapkit.toolkit.pypcapfile import (IPV4_EXTENSION_HEADERS, TCP_MIN_HEADER_LEN,
27+
_default_accepts, _past_extension_headers)
2728
from pcapkit.utilities.exceptions import ProtocolError, UnsupportedCall
2829

2930
if TYPE_CHECKING:
@@ -462,6 +463,112 @@ def _ipv4_accepted(ipv4: 'IP') -> 'bool':
462463
return _default_accepts('IPv4', ipv4.pack_hdr() + bytes(ipv4.opts))
463464

464465

466+
def _past_ipv4_extension_headers(packet: 'Packet', ipv4: 'IP') -> 'Optional[tuple[int, bytes]]':
467+
"""Step over the headers at the head of a DPKT IPv4 packet's payload that the default engine reads past.
468+
469+
Args:
470+
packet: DPKT packet ``ipv4`` is a layer of, whose octets
471+
:func:`_layer2bytes` slices.
472+
ipv4: DPKT IPv4 packet, whose protocol is one of the
473+
:data:`~pcapkit.toolkit.pypcapfile.IPV4_EXTENSION_HEADERS`.
474+
475+
Returns:
476+
The protocol number after the last of those headers and the octets from
477+
its header on, as far as the Total Length goes -- a Total Length of
478+
``0``, which TCP segmentation offload leaves, runs to the end of the
479+
frame -- or :data:`None` if the default engine reads no upper-layer
480+
header there: ``ipv4`` is a later fragment, whose data is a slice of the
481+
datagram's payload (:rfc:`791#section-3.2`), or it leaves one of the
482+
headers undissected, which
483+
:func:`~pcapkit.toolkit.pypcapfile._past_extension_headers` decides by
484+
the default engine's own rules, up to
485+
:data:`~pcapkit.protocols.internet.internet.EXTENSION_HEADER_LIMIT`
486+
headers in a row (:issue:`1604`).
487+
488+
Note:
489+
The default engine dispatches an IPv4 packet's protocol through the
490+
registry IPv6 uses, so it reads an AH or IPv6 extension header there
491+
and what its Next Header names. `DPKT`_ decodes protocol 0 as IPv4 and
492+
an AH as :class:`dpkt.ah.AH`, and keeps the rest as octets, so the
493+
octets are read instead (:issue:`1606`).
494+
495+
.. _DPKT: https://dpkt.readthedocs.io
496+
497+
"""
498+
if ipv4.offset:
499+
return None
500+
wire, _ = _layer2bytes(packet, ipv4)
501+
ihl = ipv4.hl * 4
502+
return _past_extension_headers(ipv4.p, wire[ihl:max(ipv4.len, ihl)] if ipv4.len else wire[ihl:])
503+
504+
505+
def _decode_tcp(segment: 'bytes') -> 'Optional[TCP]':
506+
"""Decode a TCP segment the default engine reads behind an AH or IPv6 extension header in IPv4.
507+
508+
Args:
509+
segment: Raw octets from the TCP header on, as far as the IPv4 packet
510+
carrying it goes (see :func:`_past_ipv4_extension_headers`).
511+
512+
Returns:
513+
The segment, with ``segment`` attached by :func:`attach_buffer` so that
514+
its header is the captured one; or :data:`None` if the default engine
515+
reads no TCP there: fewer than :data:`TCP_MIN_HEADER_LEN
516+
<pcapkit.toolkit.pypcapfile.TCP_MIN_HEADER_LEN>` octets, a Data Offset
517+
counting fewer or more than were captured, or options its TCP parser
518+
rejects (see :func:`~pcapkit.toolkit.pypcapfile._default_accepts`).
519+
520+
Note:
521+
Directly over IP, the default engine reads a TCP header its parser
522+
rejects out of the raw octets left behind
523+
(:func:`pcapkit.toolkit.pcap.tcp_segment`), but behind another header
524+
it does not, so the parser's answer stands here, as for the pypcapfile
525+
engine.
526+
527+
"""
528+
import dpkt # isort:skip
529+
530+
hdr_len = (segment[12] >> 4) * 4 if len(segment) >= TCP_MIN_HEADER_LEN else 0
531+
if hdr_len < TCP_MIN_HEADER_LEN or hdr_len > len(segment):
532+
return None
533+
if hdr_len > TCP_MIN_HEADER_LEN and not _default_accepts('TCP', segment[:hdr_len]):
534+
return None
535+
tcp = dpkt.tcp.TCP(segment)
536+
attach_buffer(tcp, segment)
537+
return tcp
538+
539+
540+
def _decode_ip(protocol: 'int', data: 'bytes') -> 'Optional[IP | IP6]':
541+
"""Decode an IP packet the default engine reads behind an AH or IPv6 extension header in IPv4.
542+
543+
Args:
544+
protocol: The IP-in-IP protocol number, one of the :data:`IP_TUNNELS`.
545+
data: Raw octets from the IP header on, as far as the IPv4 packet
546+
carrying it goes (see :func:`_past_ipv4_extension_headers`).
547+
548+
Returns:
549+
The packet as `DPKT`_ decodes one in a tunnel, with ``data`` attached by
550+
:func:`attach_buffer`, so that :func:`_layer2bytes` slices its layers
551+
out of the captured octets; or :data:`None` if decoding it raises
552+
anything at all, as :class:`~pcapkit.foundation.engines.dpkt.DPKT` then
553+
keeps a frame raw. `DPKT`_ raises more than its own
554+
:exc:`~dpkt.dpkt.UnpackError`: dpkt 1.9.8 reads ``frag_off`` from
555+
whatever header follows an IPv6 Fragment header, so one followed by
556+
another extension header raises :exc:`AttributeError` (:issue:`1351`).
557+
558+
.. _DPKT: https://dpkt.readthedocs.io
559+
560+
"""
561+
import dpkt # isort:skip
562+
563+
klass = dpkt.ip.IP if protocol == Enum_TransType.IPv4 else dpkt.ip6.IP6
564+
try:
565+
ip = klass(data)
566+
except Exception: # as the DPKT engine does, for a whole frame
567+
return None
568+
attach_buffer(ip, data)
569+
return ip
570+
571+
465572
def _tcp_carrier(packet: 'Packet') -> 'tuple[Optional[IP | IP6], Optional[TCP]]':
466573
"""Fetch the IP layer of a DPKT packet that carries its TCP segment, and the segment.
467574
@@ -476,14 +583,20 @@ def _tcp_carrier(packet: 'Packet') -> 'tuple[Optional[IP | IP6], Optional[TCP]]'
476583
rejects the header of an IPv4 packet on the way (see
477584
:func:`_ipv4_accepted`). A tunnel is a packet whose protocol, or for
478585
IPv6 the next header after its extension headers, is one of the
479-
:data:`IP_TUNNELS`.
586+
:data:`IP_TUNNELS`. An IPv4 packet whose protocol names an AH or IPv6
587+
extension header carries what the default engine reads past them (see
588+
:func:`_past_ipv4_extension_headers`), a tunnel or a TCP segment, which
589+
are decoded from the captured octets (see :func:`_decode_ip` and
590+
:func:`_decode_tcp`).
480591
481592
Note:
482593
`DPKT`_ decodes an IPv4 or IPv6 packet inside another (:rfc:`2003`,
483594
:rfc:`2473`, :rfc:`4213`) as its ``data``. The TCP endpoints are the
484595
innermost packet's addresses, as for the default engine
485596
(:func:`pcapkit.toolkit.pcap.tcp_segment`); the outer ones are the
486-
tunnel's (:issue:`1581`).
597+
tunnel's (:issue:`1581`). A segment found behind an extension header is
598+
no layer of ``packet``, so it carries its own octets, which
599+
:func:`_layer2bytes` then hands back (:issue:`1606`).
487600
488601
.. _DPKT: https://dpkt.readthedocs.io
489602
@@ -493,16 +606,28 @@ def _tcp_carrier(packet: 'Packet') -> 'tuple[Optional[IP | IP6], Optional[TCP]]'
493606
ip = _network(packet)
494607
if ip is None:
495608
return None, None
609+
root = packet # the packet ``ip`` is a layer of
496610
while True:
497-
if isinstance(ip, dpkt.ip.IP) and not _ipv4_accepted(ip):
498-
return None, None
611+
if isinstance(ip, dpkt.ip.IP):
612+
if not _ipv4_accepted(ip):
613+
return None, None
614+
if ip.p in IPV4_EXTENSION_HEADERS:
615+
upper = _past_ipv4_extension_headers(root, ip)
616+
if upper is not None and upper[0] == Enum_TransType.TCP:
617+
return ip, _decode_tcp(upper[1])
618+
if upper is None or upper[0] not in IP_TUNNELS or (inner := _decode_ip(*upper)) is None:
619+
return ip, None
620+
root = ip = inner
621+
continue
499622
if getattr(ip, 'p', None) not in IP_TUNNELS or not isinstance(ip.data, (dpkt.ip.IP, dpkt.ip6.IP6)):
500623
break
501624
ip = ip.data
502625

503626
tcp = getattr(ip, 'tcp', None) # type: Optional[TCP]
504627
if tcp is None and type(getattr(ip, 'data', None)).__name__ == 'TCP':
505628
tcp = cast('TCP', ip.data)
629+
if tcp is not None and root is not packet:
630+
attach_buffer(tcp, _layer2bytes(root, tcp)[0])
506631
return ip, tcp
507632

508633

@@ -542,12 +667,13 @@ def packet2chain(packet: 'Packet') -> 'str':
542667
packet: DPKT packet.
543668
544669
Returns:
545-
Colon (``:``) separated list of protocol chain.
670+
Colon (``:``) separated list of protocol chain. It ends at the first
671+
payload that is no layer, as in :func:`packet2dict`, e.g. VRRP's ``''``.
546672
547673
"""
548674
chain = [type(packet).__name__]
549675
payload = packet.data
550-
while not isinstance(payload, bytes):
676+
while hasattr(payload, '__hdr_fields__'):
551677
chain.append(type(payload).__name__)
552678
payload = payload.data
553679
return ':'.join(chain)
@@ -563,15 +689,21 @@ def packet2dict(packet: 'Packet', timestamp: 'float', *,
563689
data_link: Data link type.
564690
565691
Returns:
566-
Dict[str, Any]: A :obj:`dict` mapping of packet data.
692+
Dict[str, Any]: A :obj:`dict` mapping of packet data. A layer's payload
693+
is mapped as a layer of its own only where it is one, i.e. has the
694+
header fields a :class:`dpkt.dpkt.Packet` has; any other is leaf data.
695+
`DPKT`_ leaves some undecoded payloads as a :obj:`str` rather than as
696+
:obj:`bytes`, e.g. ``''`` for VRRP's.
697+
698+
.. _DPKT: https://dpkt.readthedocs.io
567699
568700
"""
569701
def wrapper(packet: 'Packet') -> 'dict[str, Any]':
570702
dict_ = {} # type: dict[str, Any]
571703
for field in packet.__hdr_fields__:
572704
dict_[field] = getattr(packet, field, None)
573705
payload = packet.data
574-
if not isinstance(payload, bytes):
706+
if hasattr(payload, '__hdr_fields__'):
575707
dict_[type(payload).__name__] = wrapper(payload)
576708
return dict_
577709

‎pcapkit/toolkit/scapy.py‎

Lines changed: 100 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,9 @@
4747
from pcapkit.foundation.traceflow.data.tcp import Packet as TF_TCP_Packet
4848
from pcapkit.protocols.data.misc.pcap.frame import FrameInfo as Data_FrameInfo
4949
from pcapkit.protocols.schema.internet.ipv6 import jumbo_payload_length
50-
from pcapkit.toolkit.pypcapfile import _default_accepts
50+
from pcapkit.toolkit.pypcapfile import (IP_TUNNELS, IPV4_EXTENSION_HEADERS, IPV4_HEADER_LEN,
51+
IPV6_HEADER_LEN, TCP_MIN_HEADER_LEN, _default_accepts,
52+
_past_extension_headers)
5153
from pcapkit.utilities.compat import ModuleNotFoundError # pylint: disable=redefined-builtin
5254
from pcapkit.utilities.exceptions import MissingKeyError, ModuleNotFound, stacklevel
5355
from pcapkit.utilities.warnings import ScapyWarning, warn
@@ -332,17 +334,62 @@ def _ipv4_accepted(ipv4: 'IP') -> 'bool':
332334
return _default_accepts('IPv4', octets[:max((octets[0] & 0x0F) * 4, 20)])
333335

334336

335-
def _carrier(layer: 'Packet') -> 'IP | IPv6 | None':
336-
"""Fetch the IP layer that carries ``layer``.
337+
def _tcp_behind_extension_headers(segment: 'bytes') -> 'tuple[bytes, bytes] | None':
338+
"""Split a TCP segment the default engine reads behind an AH or IPv6 extension header in IPv4.
337339
338340
Args:
339-
layer: A layer of a dissected Scapy packet.
341+
segment: Raw octets from the TCP header on, as far as the IPv4 layer
342+
carrying it goes (see :func:`_tcp_carrier`).
343+
344+
Returns:
345+
The header, as many octets as the Data Offset counts, and the payload
346+
after it; or :data:`None` if the default engine reads no TCP there:
347+
fewer than :data:`TCP_MIN_HEADER_LEN
348+
<pcapkit.toolkit.pypcapfile.TCP_MIN_HEADER_LEN>` octets, a Data Offset
349+
counting fewer or more than were captured, or options its TCP parser
350+
rejects (see :func:`~pcapkit.toolkit.pypcapfile._default_accepts`).
351+
352+
Note:
353+
Directly over IP, the default engine reads a TCP header its parser
354+
rejects out of the raw octets left behind
355+
(:func:`pcapkit.toolkit.pcap.tcp_segment`), but behind another header
356+
it does not, so the parser's answer stands here, as for the pypcapfile
357+
engine.
358+
359+
"""
360+
hdr_len = (segment[12] >> 4) * 4 if len(segment) >= TCP_MIN_HEADER_LEN else 0
361+
if hdr_len < TCP_MIN_HEADER_LEN or hdr_len > len(segment):
362+
return None
363+
if hdr_len > TCP_MIN_HEADER_LEN and not _default_accepts('TCP', segment[:hdr_len]):
364+
return None
365+
return segment[:hdr_len], segment[hdr_len:]
366+
367+
368+
def _tcp_carrier(packet: 'Packet') -> 'tuple[IP | IPv6, TCP, bytes, bytes] | None':
369+
"""Fetch the TCP segment of a Scapy packet, and the IP layer that carries it.
370+
371+
Args:
372+
packet: Scapy packet.
340373
341374
Returns:
342375
The nearest :class:`~scapy.layers.inet.IP` or
343-
:class:`~scapy.layers.inet6.IPv6` layer above ``layer``, or
344-
:data:`None` if there is none, or the default engine rejects the
345-
header of an IPv4 layer above it (see :func:`_ipv4_accepted`).
376+
:class:`~scapy.layers.inet6.IPv6` layer above the packet's TCP layer,
377+
that layer, and the segment's header and payload (see
378+
:func:`_tcp_segment`); or :data:`None` if there is no such IP layer, or
379+
the default engine reads no TCP there: an IPv4 layer above it has a
380+
header that engine rejects (see :func:`_ipv4_accepted`), or is a later
381+
fragment, whose data is a slice of the datagram's payload with no
382+
upper-layer header in it (:rfc:`791#section-3.2`, :issue:`1617`).
383+
384+
An IPv4 layer whose protocol names an AH or IPv6 extension header
385+
carries what the default engine reads past those headers, by its own
386+
rules and up to
387+
:data:`~pcapkit.protocols.internet.internet.EXTENSION_HEADER_LIMIT` of
388+
them in a row (see
389+
:func:`~pcapkit.toolkit.pypcapfile._past_extension_headers`): a tunnel,
390+
walked on as above, or a TCP segment (see
391+
:func:`_tcp_behind_extension_headers`), each dissected from the
392+
octets (:issue:`1606`).
346393
347394
Note:
348395
The nearest is the innermost IP layer of an IP-in-IP tunnel
@@ -351,22 +398,51 @@ def _carrier(layer: 'Packet') -> 'IP | IPv6 | None':
351398
(:func:`pcapkit.toolkit.pcap.tcp_segment`). ``packet['IP']`` finds the
352399
outermost IPv4 layer instead, which is the tunnel's, or with IPv4
353400
carried in IPv6 the inner one (:issue:`1581`). The extension header
354-
layers `Scapy`_ dissects between an IP layer and its payload are not
401+
layers `Scapy`_ dissects between an IPv6 layer and its payload are not
355402
IP layers, so are stepped over.
356403
404+
Inside IPv4, `Scapy`_ dissects an AH alone of those headers, and behind
405+
one only IPv6 and, for a Next Header of ``0``, IPv4, so the default
406+
engine's rules are applied to the octets instead. It also dissects IPv6
407+
and AH inside a later fragment, binding neither to a zero fragment
408+
offset as it binds TCP.
409+
357410
"""
358-
from scapy.layers.inet import IP
411+
from scapy.layers.inet import IP, TCP, IPerror
359412
from scapy.layers.inet6 import IPv6
413+
from scapy.packet import NoPayload
360414

415+
tcp = cast('TCP | None', packet.getlayer('TCP'))
361416
carrier = None # type: IP | IPv6 | None
362-
above = layer.underlayer
363-
while above is not None:
364-
if isinstance(above, IP) and not _ipv4_accepted(above):
417+
layer = packet # type: Packet
418+
while layer is not tcp:
419+
if isinstance(layer, NoPayload):
365420
return None
366-
if carrier is None and isinstance(above, (IP, IPv6)):
367-
carrier = above
368-
above = above.underlayer
369-
return carrier
421+
if isinstance(layer, IP):
422+
if not _ipv4_accepted(layer) or layer.frag:
423+
return None
424+
carrier = layer
425+
# not the datagram an ICMP error quotes, which the default engine does not dissect
426+
if layer.proto in IPV4_EXTENSION_HEADERS and not isinstance(layer, IPerror):
427+
upper = _past_extension_headers(layer.proto, _within_datagrams(layer.payload))
428+
if upper is not None and upper[0] == Enum_TransType.TCP:
429+
segment = _tcp_behind_extension_headers(upper[1])
430+
return None if segment is None else (carrier, TCP(upper[1]), *segment)
431+
if upper is None or upper[0] not in IP_TUNNELS:
432+
return None
433+
version, data = IP_TUNNELS[upper[0]], upper[1]
434+
if len(data) < (IPV4_HEADER_LEN if version == 4 else IPV6_HEADER_LEN):
435+
return None
436+
layer = IP(data) if version == 4 else IPv6(data)
437+
tcp = cast('TCP | None', layer.getlayer('TCP'))
438+
continue
439+
elif isinstance(layer, IPv6):
440+
carrier = layer
441+
layer = layer.payload
442+
443+
if carrier is None or (segment := _tcp_segment(tcp)) is None:
444+
return None
445+
return carrier, tcp, *segment
370446

371447

372448
def ipv4_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'IP_Packet[IPv4Address] | None':
@@ -512,20 +588,19 @@ def tcp_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'TCP_Packet | None
512588
* If the ``packet`` can be used for TCP reassembly. A packet can be reassembled
513589
if it contains TCP layer (:class:`scapy.layers.inet.TCP`) whose fixed header
514590
lies inside its datagram, and whose Data Offset counts at least that header,
515-
behind no IPv4 header the default engine rejects. It is keyed by the IP layer
516-
that carries it -- in an IP-in-IP tunnel, the innermost (see :func:`_carrier`).
591+
behind no IPv4 header the default engine rejects and in no later IPv4 fragment,
592+
or a TCP segment the default engine reads behind an AH or IPv6 extension header
593+
in IPv4. It is keyed by the IP layer that carries it -- in an IP-in-IP tunnel,
594+
the innermost (see :func:`_tcp_carrier`).
517595
* If the ``packet`` can be reassembled, then the :obj:`dict` mapping of data for TCP
518596
reassembly (:term:`reasm.tcp.packet`) will be returned; otherwise, returns :data:`None`.
519597
520598
See Also:
521599
:class:`pcapkit.foundation.reassembly.tcp.TCP`
522600
523601
"""
524-
if 'TCP' in packet:
525-
tcp = cast('TCP', packet['TCP'])
526-
if (ip := _carrier(tcp)) is None or (segment := _tcp_segment(tcp)) is None:
527-
return None
528-
header, payload = segment
602+
if (found := _tcp_carrier(packet)) is not None:
603+
ip, tcp, header, payload = found
529604

530605
raw_len = len(payload) # payload length, header excludes
531606
data = TCP_Packet(
@@ -572,11 +647,8 @@ def tcp_traceflow(packet: 'Packet', *, count: 'int' = -1) -> 'TF_TCP_Packet | No
572647
:class:`pcapkit.foundation.traceflow.tcp.TCP`
573648
574649
"""
575-
if 'TCP' in packet:
576-
tcp = cast('TCP', packet['TCP'])
577-
if (ip := _carrier(tcp)) is None or (segment := _tcp_segment(tcp)) is None:
578-
return None
579-
header, payload = segment
650+
if (found := _tcp_carrier(packet)) is not None:
651+
ip, tcp, header, payload = found
580652

581653
# NOTE: the link type of the interface the packet was read from, which
582654
# :class:`~pcapkit.foundation.engines.scapy.Scapy` attaches with

0 commit comments

Comments
 (0)