Skip to content

Commit a4cf408

Browse files
committed
fix(protocols): reject a jumbogram RFC 2675 calls an error (#1687)
RFC 2675 section 3 lists four errors a receiver must detect. The default engine dissected each as a jumbogram, or warned and went on. - schema/internet/ipv6.py: jumbogram_error() names the error, if any: a Payload Length of 0 with a Hop-by-Hop header and no Jumbo Payload option; a non-zero Payload Length with the option; a Jumbo Payload Length below 65,536; the option with a Fragment header (asked of the caller's walk). - IPv6.read raises ProtocolError for the first three, and the extension header walk for the fourth, as IPv4.read rejects a bad version, so behind a link layer the frame stops at IPv6 and rebuilds as captured. - IPv6.make with no payload_length writes 0 when the payload's leading Hop-by-Hop header carries a Jumbo Payload option, so a genuine Jumbo Payload Length builds a jumbogram the parser accepts. - examples/generators/options.py: HOPOPT's Jumbo Payload frame, one of those errors, is a genuine jumbogram, Jumbo Payload Length 65,536 filled out by a UDP datagram, in a capture whose snaplen does not cut it. - tests: each error on IPv6, behind Ethernet and at extraction; make->parse of a jumbogram; the generator's jumbogram; adapter-test rows on now-invalid jumbograms dropped.
1 parent 9808d51 commit a4cf408

13 files changed

Lines changed: 777 additions & 89 deletions

‎examples/generators/options.py‎

Lines changed: 84 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@
2727
than a packet assembled by :mod:`scapy` from its own protocol model. That is the
2828
point: the octets under test are the library's own output, so a capture is a
2929
record of what this version of ``pcapkit`` builds, and re-parsing it exercises
30-
``_read_*`` against ``_make_*``.
30+
``_read_*`` against ``_make_*``. The one frame with more in it is HOPOPT's Jumbo
31+
Payload case, a genuine jumbogram -- see :func:`_jumbogram_datagram`.
3132
3233
Only the codes that construct *successfully* can appear in a capture -- there
3334
are no octets for the ones that do not. A failing case in a captured family
@@ -152,6 +153,18 @@
152153
#: Destination address for every generated IPv6 envelope.
153154
DST_IP6 = '2001:db8::2'
154155

156+
#: Jumbo Payload Length of the ``hopopt-option/Jumbo_Payload`` case: the least
157+
#: a jumbogram may carry, one more than the 16-bit Payload Length holds
158+
#: (:rfc:`2675#section-2`). See :func:`_jumbogram_datagram`.
159+
JUMBO_LEN = 0x10000
160+
#: Snapshot length of a capture whose frames all fit in it: scapy's default,
161+
#: which keeps every capture but a jumbogram's as it always was.
162+
SNAPLEN = 0xFFFF
163+
#: Snapshot length of a capture holding a longer frame: libpcap's
164+
#: ``MAXIMUM_SNAPLEN``. A libpcap reader cuts a record to the file's snaplen, so
165+
#: a jumbogram under :data:`SNAPLEN` would reach it truncated.
166+
JUMBO_SNAPLEN = 262144
167+
155168
#: Seconds a single case may take before :func:`roundtrip` gives up on it and
156169
#: records ``'TIMEOUT'``, before :data:`TIMEOUT_SCALE_ENV` stretches it. A working
157170
#: case takes low single-digit milliseconds, so this is headroom for a stalled
@@ -575,7 +588,8 @@ def _ipv6_option_overrides() -> 'dict[Any, dict[str, Any]]':
575588
from pcapkit.const.ipv6.option import Option as Enum_Option
576589

577590
# HOPOPT and IPv6-Opts key on the same enumeration and behave identically
578-
# on every code, so one table serves both.
591+
# on every code, so one table serves both; ``_hopopt_overrides`` adds the
592+
# one value that matters only in a Hop-by-Hop Options header.
579593
return {
580594
# The nonce is sized to its bit length rounded up to whole octets, at
581595
# least one, so the default ``nonce=0`` is a one-octet zero. A
@@ -586,6 +600,17 @@ def _ipv6_option_overrides() -> 'dict[Any, dict[str, Any]]':
586600
}
587601

588602

603+
def _hopopt_overrides() -> 'dict[Any, dict[str, Any]]':
604+
from pcapkit.const.ipv6.option import Option as Enum_Option
605+
606+
# A Jumbo Payload option in the Hop-by-Hop Options header after an IPv6
607+
# header makes the packet a jumbogram, and one whose Jumbo Payload Length is
608+
# not above 65,535 is an error (RFC 2675 section 3) the default engine
609+
# rejects (#1687). So the option carries a legal length, and ``_frame``
610+
# builds the jumbogram around it. In IPv6-Opts the option is just an option.
611+
return {**_ipv6_option_overrides(), Enum_Option.Jumbo_Payload: {'len': JUMBO_LEN}}
612+
613+
589614
def _hopopt_base() -> 'dict[str, Any]':
590615
from pcapkit.const.reg.transtype import TransType
591616
return {'next': TransType.UDP, 'payload': b''}
@@ -1588,7 +1613,7 @@ def _pcapng_secrets_build(code: 'Any', kwargs: 'dict[str, Any]') -> 'Any':
15881613
Family('ipv4-option', _ipv4_registry, _ipv4_overrides,
15891614
_ipv4_build, _ipv4_parse, _ipv4_extract, _ipv4_rebuild,
15901615
capture='options-ipv4.pcap', envelope='ethernet-ipv4'),
1591-
Family('hopopt-option', _hopopt_registry, _ipv6_option_overrides,
1616+
Family('hopopt-option', _hopopt_registry, _hopopt_overrides,
15921617
_hopopt_build, _hopopt_parse, _ipv6_extract, _hopopt_rebuild,
15931618
capture='options-ipv6.pcap', envelope='ipv6', proto=0),
15941619
Family('ipv6-opts-option', _ipv6_opts_registry, _ipv6_option_overrides,
@@ -1880,6 +1905,47 @@ def outcomes(families: 'Optional[tuple[Family, ...]]' = None,
18801905
yield roundtrip(case, deadline)
18811906

18821907

1908+
def _jumbogram_datagram(octets: 'bytes', jumbo: 'int') -> 'bytes':
1909+
"""The UDP datagram that makes a jumbogram up to its Jumbo Payload Length.
1910+
1911+
With a Payload Length of 0 it is the Jumbo Payload Length that says where
1912+
the packet ends, so the octets after the Hop-by-Hop Options header have to
1913+
fill it, or the frame is a jumbogram cut short. The header names UDP as its
1914+
next header, as :func:`_hopopt_base` has every HOPOPT case do, so they are a
1915+
datagram of zeros to the Discard port [:rfc:`863`], with the checksum
1916+
:rfc:`8200#section-8.1` has a receiver verify. Its length fits UDP's Length
1917+
field, which :rfc:`2675#section-4` therefore leaves as is.
1918+
1919+
Args:
1920+
octets: The Hop-by-Hop Options header, as :func:`roundtrip` built it.
1921+
jumbo: Its Jumbo Payload Length.
1922+
1923+
Returns:
1924+
The datagram, ``jumbo - len(octets)`` octets long.
1925+
1926+
Raises:
1927+
ValueError: If the header does not name UDP, or the octets it leaves
1928+
are not the length of a UDP datagram.
1929+
1930+
"""
1931+
import ipaddress
1932+
1933+
from scapy.utils import checksum # pylint: disable=no-name-in-module
1934+
1935+
size = jumbo - len(octets)
1936+
if octets[0] != 17 or not 8 <= size <= 0xFFFF:
1937+
raise ValueError(f'cannot fill a {jumbo}-octet jumbogram after a {len(octets)}-octet '
1938+
f'header naming next header {octets[0]} with a UDP datagram')
1939+
1940+
head = (50000).to_bytes(2, 'big') + (9).to_bytes(2, 'big') + size.to_bytes(2, 'big')
1941+
data = bytes(size - 8)
1942+
pseudo = (ipaddress.IPv6Address(SRC_IP6).packed + ipaddress.IPv6Address(DST_IP6).packed
1943+
+ size.to_bytes(4, 'big') + bytes(3) + bytes([17]))
1944+
# A computed checksum of zero goes out as all ones, since zero means none.
1945+
value = checksum(pseudo + head + bytes(2) + data) or 0xFFFF
1946+
return head + value.to_bytes(2, 'big') + data
1947+
1948+
18831949
def _frame(family: 'Family', octets: 'bytes', index: 'int') -> 'Any':
18841950
"""Wrap constructed octets in the envelope that makes them decodable.
18851951
@@ -1911,8 +1977,18 @@ def _frame(family: 'Family', octets: 'bytes', index: 'int') -> 'Any':
19111977
frame = link / IP(src=SRC_IP, dst=DST_IP, proto=family.proto,
19121978
id=index, ttl=64) / Raw(octets)
19131979
elif family.envelope == 'ipv6':
1914-
frame = link / IPv6(src=SRC_IP6, dst=DST_IP6, nh=family.proto,
1915-
hlim=64) / Raw(octets)
1980+
from pcapkit.protocols.schema.internet.ipv6 import jumbo_payload_length
1981+
1982+
# A Jumbo Payload option where it makes the packet a jumbogram gets a
1983+
# genuine one: a Payload Length of 0 (RFC 2675 section 3, #1687), and
1984+
# octets to make up the Jumbo Payload Length.
1985+
jumbo = None if family.proto is None else jumbo_payload_length(family.proto, octets)
1986+
if jumbo is None:
1987+
frame = link / IPv6(src=SRC_IP6, dst=DST_IP6, nh=family.proto,
1988+
hlim=64) / Raw(octets)
1989+
else:
1990+
frame = link / IPv6(src=SRC_IP6, dst=DST_IP6, nh=family.proto, hlim=64,
1991+
plen=0) / Raw(octets + _jumbogram_datagram(octets, jumbo))
19161992
elif family.envelope == 'tcp':
19171993
frame = (link / IP(src=SRC_IP, dst=DST_IP, id=index, ttl=64)
19181994
/ TCP(sport=50000, dport=80, flags='A', seq=1, ack=1)
@@ -1973,7 +2049,9 @@ def generate(dest: 'pathlib.Path | None' = None) -> 'list[pathlib.Path]':
19732049
written = [] # type: list[pathlib.Path]
19742050
for name in sorted(buckets):
19752051
path = dest / name
1976-
wrpcap(str(path), buckets[name])
2052+
frames = buckets[name]
2053+
snaplen = SNAPLEN if max(len(frame) for frame in frames) <= SNAPLEN else JUMBO_SNAPLEN
2054+
wrpcap(str(path), frames, snaplen=snaplen)
19772055
written.append(path)
19782056

19792057
total = sum(len(frames) for frames in buckets.values())

‎pcapkit/protocols/internet/ipv6.py‎

Lines changed: 38 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,9 @@
3939
from pcapkit.protocols.internet.ip import IP
4040
from pcapkit.protocols.protocol import FRAME_LAYER_LIMIT, _frame_depth
4141
from pcapkit.protocols.schema.internet.ipv6 import IPv6 as Schema_IPv6
42-
from pcapkit.protocols.schema.internet.ipv6 import jumbo_payload_length
42+
from pcapkit.protocols.schema.internet.ipv6 import jumbo_payload_length, jumbogram_error
4343
from pcapkit.utilities.decorators import beholder
44-
from pcapkit.utilities.exceptions import stacklevel
45-
from pcapkit.utilities.warnings import ProtocolWarning, warn
44+
from pcapkit.utilities.exceptions import ProtocolError
4645

4746
if TYPE_CHECKING:
4847
from enum import IntEnum as StdlibEnum
@@ -197,11 +196,26 @@ def read(self, length: 'Optional[int]' = None, *,
197196
Returns:
198197
Parsed packet data.
199198
199+
Raises:
200+
ProtocolError: If the packet is one of the errors
201+
:rfc:`2675#section-3` has a receiver detect (see
202+
:func:`~pcapkit.protocols.schema.internet.ipv6.jumbogram_error`).
203+
200204
"""
201205
if length is None:
202206
length = len(self)
203207
schema = self.__header__
204208

209+
# NOTE: A receiver treats each of these as an error (:issue:`1687`), so
210+
# the frame stops here, c.f. :meth:`IPv4.read
211+
# <pcapkit.protocols.internet.ipv4.IPv4.read>`. A Fragment header beside
212+
# the Jumbo Payload option is caught on the walk, see
213+
# :meth:`_decode_next_layer`.
214+
rest = schema.get_payload() + schema.trailer
215+
error = jumbogram_error(schema.length, schema.next, rest)
216+
if error is not None:
217+
raise ProtocolError(f'{self.alias}: {error}')
218+
205219
ipv6 = Data_IPv6.from_dict({
206220
'version': schema.hextet['version'],
207221
'class': schema.hextet['class'],
@@ -224,19 +238,9 @@ def read(self, length: 'Optional[int]' = None, *,
224238
# NOTE: A jumbogram's extent is its Jumbo Payload Length, not the zero
225239
# Payload Length, c.f. :meth:`Schema_IPv6.post_process
226240
# <pcapkit.protocols.schema.internet.ipv6.IPv6.post_process>`
227-
# (:issue:`1434`). :rfc:`2675#section-2` makes a Jumbo Payload option
228-
# beside a non-zero Payload Length an error; such a packet is still
229-
# kept as captured, with the Payload Length deciding its extent, since
230-
# that is what the receiver had to go by.
231-
extent = schema.length
232-
jumbo = jumbo_payload_length(schema.next, schema.get_payload() + schema.trailer)
233-
if jumbo is not None:
234-
if schema.length == 0:
235-
extent = jumbo
236-
else:
237-
warn(f'{self.alias}: Jumbo Payload option with non-zero Payload Length '
238-
f'{schema.length}; ignoring the Jumbo Payload Length {jumbo}',
239-
ProtocolWarning, stacklevel=stacklevel())
241+
# (:issue:`1434`); the check above leaves a zero one beside it.
242+
jumbo = jumbo_payload_length(schema.next, rest)
243+
extent = schema.length if jumbo is None else jumbo
240244

241245
# update packet info
242246
if __packet__ is None:
@@ -276,7 +280,8 @@ def make(self,
276280
dst: Destination IP address.
277281
payload_length: Length of the payload, extension headers included;
278282
computed from the payload when omitted, and zero (a jumbogram)
279-
if that exceeds 65,535 octets.
283+
if that exceeds 65,535 octets or the payload starts with a
284+
Hop-by-Hop Options header carrying a Jumbo Payload option.
280285
payload: Payload data.
281286
trailer: Octets after the packet, outside the Payload Length, such
282287
as link-layer padding; written as is.
@@ -294,12 +299,13 @@ def make(self,
294299
# length the sender declared instead of the one that was recorded
295300
# (:issue:`1155`). Computed from the octets at hand otherwise, which is
296301
# what a plain ``IPv6(payload=...)`` wants -- or zero for a payload too
297-
# long for the field, i.e. a jumbogram, whose length the caller carries
298-
# in a Jumbo Payload option of ``payload``'s Hop-by-Hop Options header
299-
# (:rfc:`2675#section-2`).
302+
# long for the field, or one whose Hop-by-Hop Options header carries a
303+
# Jumbo Payload option, i.e. a jumbogram, whose length the caller gives
304+
# there (:rfc:`2675#section-2`); its Payload Length must be zero
305+
# (:issue:`1687`).
300306
if payload_length is None:
301307
payload_length = len(payload)
302-
if payload_length > 0xFFFF:
308+
if payload_length > 0xFFFF or jumbo_payload_length(next_val, bytes(payload)) is not None:
303309
payload_length = 0
304310

305311
return Schema_IPv6(
@@ -526,6 +532,11 @@ def _decode_next_layer(self, ipv6: 'Data_IPv6', proto: 'Optional[int]' = None,
526532
Returns:
527533
Current protocol with next layer extracted.
528534
535+
Raises:
536+
ProtocolError: If the walk reaches a Fragment header in a packet
537+
carrying a Jumbo Payload option, an error by
538+
:rfc:`2675#section-3` (:issue:`1687`).
539+
529540
"""
530541
#: Extension headers.
531542
self._exthdr = OrderedMultiDict() # type: OrderedMultiDict[Enum_ExtensionHeader, ProtocolBase] # pylint: disable=attribute-defined-outside-init
@@ -634,6 +645,12 @@ def _decode_next_layer(self, ipv6: 'Data_IPv6', proto: 'Optional[int]' = None,
634645
# reassembly, so ``fragment``, ``hdr_len`` and ``raw_len`` keep
635646
# that split however far the walk goes on.
636647
if split is None:
648+
# NOTE: Nor may a jumbogram carry one (:issue:`1687`), so the
649+
# frame stops here as for the errors :meth:`read` checks;
650+
# past those, its Jumbo Payload option is in the payload.
651+
error = jumbogram_error(ipv6.payload, ipv6.next, self.__header__.get_payload(), lambda: True)
652+
if error is not None:
653+
raise ProtocolError(f'{self.alias}: {error}')
637654
split = (hdr_len, raw_len)
638655
ipv6.__update__({
639656
'fragment': self._read_packet(header=hdr_len, payload=raw_len),

‎pcapkit/protocols/schema/internet/ipv6.py‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
if TYPE_CHECKING:
1919
from ipaddress import IPv6Address
20-
from typing import Any, Optional
20+
from typing import Any, Callable, Optional
2121

2222
from pcapkit.protocols.protocol import ProtocolBase
2323

@@ -143,3 +143,44 @@ def jumbo_payload_length(next: 'int', data: 'bytes') -> 'Optional[int]': # pyli
143143
return int.from_bytes(data[ptr + 2:ptr + 6], 'big', signed=False)
144144
ptr += 2 + size
145145
return None
146+
147+
148+
def jumbogram_error(length: 'int', next: 'int', data: 'bytes', # pylint: disable=redefined-builtin
149+
fragment: 'Optional[Callable[[], bool]]' = None) -> 'Optional[str]':
150+
"""Name the error :rfc:`2675#section-3` has a receiver detect in an IPv6 packet, if any.
151+
152+
The four errors that section lists for a node that understands the Jumbo
153+
Payload option, each a packet the default engine rejects (:issue:`1687`):
154+
155+
* a Payload Length of zero, a Next Header of Hop-by-Hop Options, and no
156+
Jumbo Payload option;
157+
* a non-zero Payload Length and a Jumbo Payload option;
158+
* a Jumbo Payload option whose Jumbo Payload Length is below 65,536;
159+
* a Jumbo Payload option and a Fragment header.
160+
161+
The option counts only where :func:`jumbo_payload_length` finds it.
162+
163+
Args:
164+
length: Payload Length of the IPv6 header.
165+
next: Next Header of the IPv6 header.
166+
data: Octets following the IPv6 header, as captured.
167+
fragment: Tells whether the extension header chain, as the default
168+
engine walks it, has a Fragment header; called only for a packet
169+
carrying the option, so a caller walks the chain only for those.
170+
171+
Returns:
172+
The error, or :data:`None` if the packet makes none of them.
173+
174+
"""
175+
jumbo = jumbo_payload_length(next, data)
176+
if jumbo is None:
177+
if not length and next == Enum_TransType.HOPOPT:
178+
return 'Payload Length 0 and a Hop-by-Hop Options header with no Jumbo Payload option'
179+
return None
180+
if length:
181+
return f'Jumbo Payload option with a non-zero Payload Length {length}'
182+
if jumbo <= 0xFFFF:
183+
return f'Jumbo Payload Length {jumbo}, not greater than 65,535'
184+
if fragment is not None and fragment():
185+
return 'Jumbo Payload option with a Fragment header'
186+
return None

‎tests/protocols/internet/test_internet_edge_roundtrip_unit.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,9 @@ def hip_param(code: int, body: bytes) -> bytes:
248248
REJECTED = {
249249
'ipv4/version-6': Reject('ProtocolError', '[IPv4] invalid version: 6'),
250250
'ipv4/ihl-4': Reject('ProtocolError', 'resolved to a negative length'),
251+
# a Jumbo Payload option beside a non-zero Payload Length, an RFC 2675 error (#1687)
252+
'hopopt/jumbo-payload-0/in-ipv6': Reject('ProtocolError', 'Jumbo Payload option with a non-zero Payload '
253+
'Length 8'),
251254
}
252255

253256
KNOWN_FAILURES = () # type: tuple[edge.Gap, ...]

0 commit comments

Comments
 (0)