Skip to content

Commit fc407c3

Browse files
authored
fix(transport): rebuild an SCTP packet cut short of its envelope's length (#2673) (#2679)
A capture cut short leaves the IPv4 Total Length or IPv6 Payload Length past the SCTP octets present. The SCTP schema sized its chunk area by that length, so Schema.unpack recorded the cut on chunks while ChunkListField handed the octets after the last whole chunk to trailer: from_data(info) dropped them, and bytes(schema) counted them again. Parsing SCTP on its own was unaffected. - SCTP.unpack in the schema module reads no further than the octets present, as SCTP has no length field. ChunkListField and ListField are unchanged. - With no octet after the last whole chunk, as for a cut inside its padding, the short read stays on chunks, where Schema.unpack records it. - SCTP.make takes no new keyword: SCTP has no length to pass through. - Tests: cuts at every offset through IPv4, IPv6 and a declared length, of packets of several chunks with parameters and causes; the schema on bytes and on a stream; whole packets and own-length cuts as controls; and an IPv4-carried case in the short-read sweep. SCTP, maker-range, schema, sweep, option, doc-claim, member-order and RFC modules pass; captures parse identically to main.
1 parent cf979c3 commit fc407c3

4 files changed

Lines changed: 310 additions & 10 deletions

File tree

‎pcapkit/protocols/schema/transport/sctp.py‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"""header schema for stream control transmission protocol"""
44

55
import io
6-
from typing import TYPE_CHECKING
6+
from typing import TYPE_CHECKING, cast
77

88
from pcapkit.const.reg.apptype import AppType as Enum_AppType
99
from pcapkit.const.reg.apptype import TransportProtocol as Enum_TransportProtocol
@@ -49,7 +49,9 @@
4949

5050
if TYPE_CHECKING:
5151
from ipaddress import IPv4Address, IPv6Address
52-
from typing import IO, Any, Callable
52+
from typing import IO, Any, Callable, Optional
53+
54+
from typing_extensions import Self
5355

5456
from pcapkit.protocols.protocol import ProtocolBase
5557

@@ -895,7 +897,9 @@ class ChunkListField(OptionField):
895897
cannot be told apart from a chunk cut short. They are not parsed but
896898
reported as option padding, which :meth:`Schema.unpack
897899
<pcapkit.protocols.schema.schema.Schema.unpack>` hands back to the stream for
898-
:attr:`SCTP.trailer` to keep as captured (:issue:`1468`).
900+
:attr:`SCTP.trailer` to keep as captured (:issue:`1468`). The area reaches no
901+
further than the octets present, as :meth:`SCTP.unpack` sizes it
902+
(:issue:`2673`).
899903
900904
"""
901905

@@ -962,6 +966,49 @@ class SCTP(Schema):
962966
#: and :attr:`IPv4.trailer <pcapkit.protocols.schema.internet.ipv4.IPv4.trailer>`.
963967
trailer: 'bytes' = PayloadField(default=b'')
964968

969+
@classmethod
970+
def unpack(cls, data: 'bytes | IO[bytes]', # type: ignore[override]
971+
length: 'Optional[int]' = None, packet: 'Optional[dict[str, Any]]' = None) -> 'Self':
972+
"""Unpack :obj:`bytes` into :class:`SCTP`, no further than the octets present.
973+
974+
Args:
975+
data: Packed data.
976+
length: Length of data, as the enclosing layer declares it.
977+
packet: Unpacked data.
978+
979+
Returns:
980+
Unpacked data as :class:`SCTP`.
981+
982+
SCTP has no packet length field (:rfc:`9260#section-3`), so a ``length``
983+
past the octets present, as an IPv4 Total Length the capture cut short of
984+
declares, is cut to them. Sized past them, :attr:`chunks` would record the
985+
data as ending inside it while :class:`ChunkListField` hands the octets
986+
after the last whole chunk to :attr:`trailer`, so :meth:`Schema.pack
987+
<pcapkit.protocols.schema.schema.Schema.pack>` would drop them and
988+
``bytes(schema)`` count them twice (:issue:`2673`).
989+
990+
When no octet follows the last whole chunk, which the capture may have cut
991+
inside its padding, the data does end inside :attr:`chunks`, so the cut is
992+
recorded there as :meth:`Schema.unpack
993+
<pcapkit.protocols.schema.schema.Schema.unpack>` records a short read, and
994+
packing writes back only the octets read.
995+
996+
"""
997+
cut = False
998+
if length is not None:
999+
if isinstance(data, bytes):
1000+
present = len(data)
1001+
else:
1002+
start = data.tell()
1003+
present = data.seek(0, io.SEEK_END) - start
1004+
data.seek(start, io.SEEK_SET)
1005+
cut, length = length > present, min(length, present)
1006+
1007+
schema = cast('Self', super().unpack(data, length, packet)) # type: ignore[call-arg,misc]
1008+
if cut and not schema.__buffer__['trailer'] and '__short_read__' not in schema.__dict__:
1009+
schema.__dict__['__short_read__'] = ('chunks', len(schema.__buffer__['chunks']))
1010+
return schema
1011+
9651012
if TYPE_CHECKING:
9661013
def __init__(self, srcport: 'Enum_AppType | int', dstport: 'Enum_AppType | int',
9671014
vtag: 'int', chksum: 'bytes',

‎pcapkit/protocols/transport/sctp.py‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -443,13 +443,18 @@ class SCTP(Transport[Data_SCTP, Schema_SCTP],
443443
444444
.. versionchanged:: 1.6.0
445445
446-
:meth:`make` and the chunk, parameter and error cause makers raise
447-
:exc:`~pcapkit.utilities.exceptions.ProtocolError` for an integer field
448-
given a value its width cannot hold, a length included, rather than
449-
writing its low bits or raising a
450-
:exc:`~pcapkit.utilities.exceptions.FieldValueError` or a bare
451-
:exc:`ValueError`, and for a checksum that is not four octets, rather
452-
than padding or cutting it (:issue:`2614`).
446+
* :meth:`make` and the chunk, parameter and error cause makers raise
447+
:exc:`~pcapkit.utilities.exceptions.ProtocolError` for an integer field
448+
given a value its width cannot hold, a length included, rather than
449+
writing its low bits or raising a
450+
:exc:`~pcapkit.utilities.exceptions.FieldValueError` or a bare
451+
:exc:`ValueError`, and for a checksum that is not four octets, rather
452+
than padding or cutting it (:issue:`2614`).
453+
* A packet the capture cut short of the length an enclosing layer
454+
declares, such as an IPv4 Total Length, rebuilds through
455+
:meth:`~pcapkit.protocols.transport.transport.Transport.from_data` as
456+
captured, where it lost the octets after its last whole chunk
457+
(:issue:`2673`).
453458
454459
"""
455460

‎tests/protocols/test_short_read_roundtrip_unit.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,11 @@ def _ipv6(code: int, body: bytes) -> bytes:
107107
'9c40138906008f3a0100000000000001123456782004010268656c6c6f')),
108108
('sctp', 'transport.sctp:SCTP', {}, bytes.fromhex(
109109
'13881389deadbeef000000000003001400000001000100020000000061626364')),
110+
# #2673: a COOKIE ACK, then an INIT with an IPv4 Address parameter, in an IPv4
111+
# datagram declaring all of it, so a cut leaves its length past the data
112+
('sctp-ipv4', 'internet.ipv4:IPv4', {}, bytes.fromhex(
113+
'450000401234000040847bcfc0000201c6336402' '13881389deadbeef00000000' '0b000004'
114+
'0100001c000000010000ffff0001000100000001' '00050008c0000202')),
110115
('ftp', 'application.ftp:FTP', {}, b'XYZW arg\r\n'),
111116
('http1', 'application.httpv1:HTTPv1', {}, b'GET / HTTP/1.1\r\n\r\n'),
112117
# an HTTP/2 SETTINGS frame of three settings, to TCP port 80 (#2659)
Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
# -*- coding: utf-8 -*-
2+
"""An SCTP packet cut short of the length its envelope declares rebuilds as captured (#2673).
3+
4+
SCTP has no length field, so a capture cut short leaves the IPv4 Total Length or IPv6
5+
Payload Length declaring more than the octets present. The SCTP schema sized its chunk
6+
area by that declared length, so ``Schema.unpack`` recorded the data as ending inside
7+
``chunks`` while ``ChunkListField`` handed the octets after the last whole chunk to
8+
``trailer``. Packing then cut the chunks back and dropped the trailer: 13 octets in, 12
9+
out. ``bytes(schema)`` counted the trailer's octets twice as well.
10+
11+
Every case builds its own octets.
12+
13+
"""
14+
15+
import io
16+
import struct
17+
import unittest
18+
import warnings
19+
20+
from tests._support import reimport_once_per_class
21+
from tests.foundation import _roundtrip as wire
22+
23+
#: Test tier (#1958): a sweep that cuts each packet at every offset.
24+
__tier__ = 'LATEST'
25+
26+
27+
def _tlv(code: int, value: bytes) -> bytes:
28+
"""A parameter or error cause, its Length excluding the padding (RFC 9260, section 3.2.1)."""
29+
body = struct.pack('!HH', code, 4 + len(value)) + value
30+
return body + bytes(-len(body) % 4)
31+
32+
33+
def _chunk(code: int, flags: int, value: bytes) -> bytes:
34+
"""A chunk, its Length excluding the padding (RFC 9260, section 3.2)."""
35+
body = struct.pack('!BBH', code, flags, 4 + len(value)) + value
36+
return body + bytes(-len(body) % 4)
37+
38+
39+
def _packet(*chunks: bytes) -> bytes:
40+
"""An SCTP packet from port 5000 to 5001 carrying ``chunks``, with its CRC32c."""
41+
from pcapkit.protocols.transport.sctp import SCTP
42+
43+
raw = struct.pack('!HHI', 5000, 5001, 0x11223344) + bytes(4) + b''.join(chunks)
44+
return raw[:8] + SCTP.calculate_checksum(raw) + raw[12:]
45+
46+
47+
#: INIT fixed part (RFC 9260, section 3.3.2): initiate tag, a_rwnd, outbound and
48+
#: inbound streams, initial TSN.
49+
INIT_HEAD = struct.pack('!IIHHI', 0xaabbccdd, 65536, 10, 10, 1)
50+
#: INIT ACK fixed part, laid out as INIT's (RFC 9260, section 3.3.3).
51+
INIT_ACK_HEAD = struct.pack('!IIHHI', 1, 2, 3, 4, 5)
52+
#: DATA chunk TSN, stream identifier, stream sequence number and PPID (RFC 9260,
53+
#: section 3.3.1).
54+
DATA_HEAD = struct.pack('!IHHI', 7, 1, 2, 0)
55+
56+
57+
def _shapes() -> 'dict[str, tuple[bytes, list[int]]]':
58+
"""Packets of several chunks, each with parameters or causes, and their chunk types."""
59+
return {
60+
# INIT with IPv4 Address (5), Supported Address Types (12), Host Name Address
61+
# (11) and Cookie Preservative (9); DATA (0) of five octets; HEARTBEAT (4)
62+
# with Heartbeat Info (1)
63+
'init-data-heartbeat': (_packet(
64+
_chunk(1, 0, INIT_HEAD + _tlv(5, bytes.fromhex('c0000201')) + _tlv(12, b'\x00\x05')
65+
+ _tlv(11, b'localhost\x00') + _tlv(9, struct.pack('!I', 1000))),
66+
_chunk(0, 0x03, DATA_HEAD + b'abcde'),
67+
_chunk(4, 0, _tlv(1, b'xyz'))), [1, 0, 4]),
68+
# SACK (3) with two gap ack blocks and a duplicate TSN; ERROR (9) with Stale
69+
# Cookie (3) and Unrecognized Chunk Type (6); ABORT (6) with Invalid Stream
70+
# Identifier (1), Missing Mandatory Parameter (2) and User-Initiated Abort (12)
71+
'sack-error-abort': (_packet(
72+
_chunk(3, 0, struct.pack('!IIHHHHHHI', 9, 4096, 2, 1, 1, 2, 4, 5, 8)),
73+
_chunk(9, 0, _tlv(3, struct.pack('!I', 500)) + _tlv(6, b'ab')),
74+
_chunk(6, 0x01, _tlv(1, b'\x00\x02\x00\x00') + _tlv(2, struct.pack('!IHH', 2, 5, 6))
75+
+ _tlv(12, b'bye'))), [3, 9, 6]),
76+
# INIT ACK with State Cookie (7), Unrecognized Parameter (8) and IPv6 Address
77+
# (6); COOKIE ECHO (10); SHUTDOWN (7)
78+
'init-ack-cookie-shutdown': (_packet(
79+
_chunk(2, 0, INIT_ACK_HEAD + _tlv(7, b'\x01\x02\x03\x04\x05')
80+
+ _tlv(8, _tlv(0x8001, b'\x09' * 4)) + _tlv(6, bytes(15) + b'\x01')),
81+
_chunk(10, 0, b'cookie'),
82+
_chunk(7, 0, struct.pack('!I', 77))), [2, 10, 7]),
83+
# one DATA chunk of three octets, as the option-coverage capture carries
84+
'data': (_packet(_chunk(0, 0x03, DATA_HEAD + b'\x01\x02\x03')), [0]),
85+
}
86+
87+
88+
class SCTPCutTests(unittest.TestCase):
89+
"""SCTP packets cut at every offset, through an envelope and on their own."""
90+
91+
def setUp(self) -> None:
92+
reimport_once_per_class(self)
93+
catcher = warnings.catch_warnings()
94+
catcher.__enter__()
95+
self.addCleanup(catcher.__exit__, None, None, None)
96+
# a cut header warns that its length runs past the data, which is the point
97+
warnings.simplefilter('ignore')
98+
99+
def assert_rebuilds(self, sctp: 'object', raw: bytes) -> None:
100+
"""``sctp`` holds ``raw`` and rebuilds it three ways."""
101+
from pcapkit.protocols.transport.sctp import SCTP
102+
103+
assert isinstance(sctp, SCTP)
104+
self.assertEqual(sctp.data, raw)
105+
self.assertEqual(bytes(sctp.__header__), raw)
106+
self.assertEqual(SCTP.from_data(sctp.info).data, raw)
107+
self.assertEqual(SCTP.from_data(sctp.info.to_dict()).data, raw)
108+
109+
def test_cut_through_ipv4_at_every_offset(self) -> None:
110+
from pcapkit.protocols.internet.ipv4 import IPv4
111+
from pcapkit.protocols.transport.sctp import SCTP
112+
113+
for name, (whole, _) in _shapes().items():
114+
packet = wire.ipv4(whole, proto=132)
115+
for keep in range(12, len(whole) + 1):
116+
raw = packet[:20 + keep]
117+
with self.subTest(case=name, keep=keep):
118+
ipv4 = IPv4(raw, len(raw))
119+
self.assertIsInstance(ipv4.payload, SCTP)
120+
self.assert_rebuilds(ipv4.payload, whole[:keep])
121+
self.assertEqual(IPv4.from_data(ipv4.info).data, raw)
122+
self.assertEqual(IPv4.from_data(ipv4.info.to_dict()).data, raw)
123+
124+
def test_cut_through_ipv6_at_every_offset(self) -> None:
125+
from pcapkit.protocols.internet.ipv6 import IPv6
126+
from pcapkit.protocols.transport.sctp import SCTP
127+
128+
for name, (whole, _) in _shapes().items():
129+
packet = wire.ipv6(whole, nxt=132)
130+
for keep in range(12, len(whole) + 1):
131+
raw = packet[:40 + keep]
132+
with self.subTest(case=name, keep=keep):
133+
ipv6 = IPv6(raw, len(raw))
134+
self.assertIsInstance(ipv6.payload, SCTP)
135+
self.assert_rebuilds(ipv6.payload, whole[:keep])
136+
self.assertEqual(IPv6.from_data(ipv6.info).data, raw)
137+
self.assertEqual(IPv6.from_data(ipv6.info.to_dict()).data, raw)
138+
139+
def test_cut_with_the_whole_length_declared(self) -> None:
140+
# the envelope's case, with no envelope: the length given exceeds the data
141+
from pcapkit.protocols.transport.sctp import SCTP
142+
143+
for name, (whole, _) in _shapes().items():
144+
for keep in range(12, len(whole) + 1):
145+
raw = whole[:keep]
146+
with self.subTest(case=name, keep=keep):
147+
self.assert_rebuilds(SCTP(raw, len(whole)), raw)
148+
self.assert_rebuilds(SCTP(io.BytesIO(raw), len(whole)), raw)
149+
150+
def test_cut_with_its_own_length_is_the_control(self) -> None:
151+
from pcapkit.protocols.transport.sctp import SCTP
152+
153+
for name, (whole, _) in _shapes().items():
154+
for keep in range(12, len(whole) + 1):
155+
raw = whole[:keep]
156+
with self.subTest(case=name, keep=keep):
157+
self.assert_rebuilds(SCTP(raw, len(raw)), raw)
158+
159+
def test_a_chunk_cut_short_is_the_trailer(self) -> None:
160+
# ten octets into the DATA chunk, after the whole INIT
161+
from pcapkit.const.sctp.chunk import Chunk
162+
from pcapkit.protocols.internet.ipv4 import IPv4
163+
164+
whole, _ = _shapes()['init-data-heartbeat']
165+
init = 4 + len(INIT_HEAD) + 8 + 8 + 16 + 8
166+
raw = wire.ipv4(whole, proto=132)[:20 + 12 + init + 10]
167+
sctp = IPv4(raw, len(raw)).payload
168+
169+
self.assertNotIn('__short_read__', sctp.info)
170+
self.assertEqual(sctp.info.trailer, whole[12 + init:12 + init + 10])
171+
self.assertEqual(list(sctp.info.chunks), [Chunk.Initiation])
172+
chunk = sctp.info.chunks[Chunk.Initiation]
173+
# RFC 9260, section 3.3.2: the INIT Length counts every parameter, and the
174+
# parameter Lengths exclude their padding (section 3.2.1)
175+
self.assertEqual(chunk.length, init)
176+
self.assertEqual([param.length for param in chunk.parameters.values()], [8, 6, 14, 8])
177+
178+
def test_a_cut_inside_the_last_padding_is_a_short_read(self) -> None:
179+
# one of the DATA chunk's three padding octets, ahead of the HEARTBEAT
180+
from pcapkit.const.sctp.chunk import Chunk
181+
from pcapkit.protocols.internet.ipv4 import IPv4
182+
183+
whole, _ = _shapes()['init-data-heartbeat']
184+
init = 4 + len(INIT_HEAD) + 8 + 8 + 16 + 8
185+
data = 4 + len(DATA_HEAD) + 5
186+
raw = wire.ipv4(whole, proto=132)[:20 + 12 + init + data + 1]
187+
sctp = IPv4(raw, len(raw)).payload
188+
189+
self.assertEqual(sctp.info['__short_read__'], ('chunks', init + data + 1))
190+
self.assertNotIn('trailer', sctp.info)
191+
self.assertEqual(list(sctp.info.chunks), [Chunk.Initiation, Chunk.Payload_Data])
192+
self.assertEqual(sctp.info.chunks[Chunk.Payload_Data].length, data)
193+
self.assertEqual(sctp.info.chunks[Chunk.Payload_Data].padding, b'\x00')
194+
self.assert_rebuilds(sctp, whole[:12 + init + data + 1])
195+
196+
def test_schema_reads_no_further_than_the_octets_present(self) -> None:
197+
from pcapkit.protocols.schema.transport.sctp import SCTP
198+
199+
for name, (whole, _) in _shapes().items():
200+
for keep in range(12, len(whole) + 1):
201+
raw = whole[:keep]
202+
with self.subTest(case=name, keep=keep):
203+
schema = SCTP.unpack(raw, len(whole))
204+
self.assertEqual(bytes(schema), raw)
205+
self.assertEqual(schema.pack(), raw)
206+
207+
# a stream read from the middle, with the octets ahead left alone
208+
stream = io.BytesIO(b'\xff' * 3 + raw)
209+
stream.seek(3)
210+
schema = SCTP.unpack(stream, len(whole))
211+
self.assertEqual(stream.tell(), 3 + keep)
212+
self.assertEqual(bytes(schema), raw)
213+
self.assertEqual(schema.pack(), raw)
214+
215+
def test_schema_given_no_length_past_the_data_is_the_control(self) -> None:
216+
from pcapkit.protocols.schema.transport.sctp import SCTP
217+
218+
for name, (whole, _) in _shapes().items():
219+
for given in (len(whole), None):
220+
with self.subTest(case=name, length=given):
221+
data = whole + b'\xee' * 4 if given is not None else whole
222+
schema = SCTP.unpack(data, given)
223+
self.assertEqual(schema.trailer, b'')
224+
self.assertNotIn('__short_read__', schema.__dict__)
225+
self.assertEqual(schema.pack(), whole)
226+
227+
def test_whole_packets_are_the_control(self) -> None:
228+
from pcapkit.protocols.internet.ipv4 import IPv4
229+
from pcapkit.protocols.transport.sctp import SCTP
230+
231+
for name, (whole, types) in _shapes().items():
232+
for via, sctp in (('IPv4', IPv4(wire.ipv4(whole, proto=132)).payload),
233+
('SCTP', SCTP(whole, len(whole)))):
234+
with self.subTest(case=name, via=via):
235+
self.assertNotIn('__short_read__', sctp.info)
236+
self.assertNotIn('trailer', sctp.info)
237+
self.assertTrue(sctp.checksum_valid)
238+
self.assertEqual([int(code) for code in sctp.info.chunks], types)
239+
self.assert_rebuilds(sctp, whole)
240+
241+
242+
if __name__ == '__main__':
243+
unittest.main()

0 commit comments

Comments
 (0)