Skip to content

Commit 1a5126d

Browse files
committed
fix(foundation/reassembly): cap DTLS handshake message allocation at 64KiB
Prevent memory DoS from unbounded buffer allocation when a DTLS handshake fragment declares an oversized message length. A single fragment with length near the 24-bit max (16,777,215) would allocate ~16MiB on its own; now allocation is clamped to DTLS_MAX_LENGTH (65535), matching IP reassembly's precedent. Clamping applies only to the allocation; the declared length is preserved in the Fragment for round-trip fidelity. Add resource-limit test to verify no memory explosion on oversized declarations. Fixes #2468.
1 parent 679aa41 commit 1a5126d

2 files changed

Lines changed: 75 additions & 4 deletions

File tree

‎pcapkit/foundation/reassembly/dtls.py‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,25 @@
2121
from typing import TYPE_CHECKING, Generic
2222

2323
from pcapkit.foundation.reassembly.data.data import Completion
24-
from pcapkit.foundation.reassembly.data.dtls import (_AT, Buffer, BufferID, Datagram, DatagramID,
25-
Fragment, HoleDescriptor, Packet)
24+
from pcapkit.foundation.reassembly.data.dtls import (_AT, Buffer, BufferID,
25+
Datagram, DatagramID,
26+
Fragment, HoleDescriptor,
27+
Packet)
2628
from pcapkit.foundation.reassembly.reassembly import ReassemblyBase
2729

2830
if TYPE_CHECKING:
2931
from typing import Optional
3032

3133
__all__ = ['DTLS']
3234

35+
#: int: Maximum DTLS handshake message length, matching
36+
#: :data:`~pcapkit.protocols.schema.internet.ipv6.IP_MAX_LENGTH` as the
37+
#: reasonable upper bound for a single datagram. DTLS handshake messages
38+
#: over 64KiB are unrealistic and pose a memory DoS risk if allocated
39+
#: up-front; this cap prevents unbounded buffer allocation from a fragment's
40+
#: declared length field (:issue:`2468`).
41+
DTLS_MAX_LENGTH = 65535
42+
3343

3444
class DTLS(ReassemblyBase[Packet[_AT], Datagram[_AT], BufferID, Buffer], Generic[_AT]): # pylint: disable=abstract-method
3545
"""Reassembly for DTLS handshake messages.
@@ -225,11 +235,15 @@ def reassembly(self, info: 'Packet[_AT]') -> 'None':
225235
# vanishing silently (#2451 cross-review, round 3).
226236
self._dtgram.extend(self.submit(Buffer(msg={MSN: frag}, timestamp=buf.timestamp),
227237
bufid=BUFID))
228-
length = info.length
238+
# Clamp the declared length to a sane maximum to prevent memory DoS
239+
# via unbounded buffer allocation. DTLS handshake messages over 64KiB
240+
# are unrealistic; this matches IP_MAX_LENGTH as the precedent
241+
# (:issue:`2468`).
242+
length = min(info.length, DTLS_MAX_LENGTH)
229243
frag = Fragment(
230244
ind=[],
231245
msg_type=info.msg_type,
232-
length=length,
246+
length=info.length,
233247
raw=bytearray(length),
234248
hdl=([HoleDescriptor(first=0, last=length - 1)] if length else []),
235249
)

‎tests/foundation/reassembly/test_dtls_handshake_reassembly_2440_unit.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,63 @@ def test_stale_buffer_expires_as_timeout_not_partial_or_hang(self) -> None:
351351
self.assertEqual(len(stale), 1)
352352
self.assertEqual(stale[0].completed.name, 'TIMEOUT')
353353

354+
def test_oversized_declared_length_is_clamped_to_prevent_memory_dos(self) -> None:
355+
"""A fragment declaring a message length exceeding
356+
:data:`~pcapkit.foundation.reassembly.dtls.DTLS_MAX_LENGTH` must have its
357+
allocated buffer clamped to that limit, not allocate the full oversized
358+
amount and risk a memory DoS. The declared length is preserved for
359+
round-tripping, but the allocation respects the cap (:issue:`2468`)."""
360+
import resource
361+
import sys
362+
363+
from pcapkit.const.tls.handshake_type import HandshakeType
364+
from pcapkit.foundation.reassembly.dtls import DTLS_MAX_LENGTH
365+
366+
# An absurdly large declared length, near the 24-bit field's maximum:
367+
# without the cap, this fragment would allocate ~16MiB in a single
368+
# bytearray(). With the cap, only 64KiB.
369+
oversized_length = 16_000_000
370+
actual_payload = b'A' * 100
371+
bufid = ('99.0.0.1', 1, '99.0.0.2', 5684, 0)
372+
373+
engine = self._engine()
374+
375+
# Set a memory limit: 512MB soft, 1GB hard. This should be tight enough
376+
# to catch a 16MB allocation but loose enough for normal operation.
377+
try:
378+
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
379+
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 1024 * 1024 * 1024))
380+
except (AttributeError, ValueError):
381+
# RLIMIT_AS may not be available on all platforms; skip this test gracefully
382+
self.skipTest('RLIMIT_AS not available on this platform')
383+
384+
try:
385+
# This should NOT raise MemoryError or fail with ENOMEM; the allocation
386+
# must be clamped to DTLS_MAX_LENGTH, not the oversized_length.
387+
engine(self._packet(bufid, 1, HandshakeType.certificate, oversized_length,
388+
0, 0, len(actual_payload), actual_payload, 0.0))
389+
390+
# The message should still be incomplete (only 100 bytes of 16M)
391+
self.assertIsNone(engine.last)
392+
393+
finally:
394+
# Restore original limits
395+
try:
396+
resource.setrlimit(resource.RLIMIT_AS, (soft, hard))
397+
except (AttributeError, ValueError):
398+
pass
399+
400+
# Verify that a message that actually completes within the cap works fine
401+
complete_payload = b'B' * DTLS_MAX_LENGTH
402+
bufid2 = ('100.0.0.1', 1, '100.0.0.2', 5684, 0)
403+
404+
engine2 = self._engine()
405+
engine2(self._packet(bufid2, 1, HandshakeType.server_hello_done, len(complete_payload),
406+
0, 0, len(complete_payload), complete_payload, 0.0))
407+
self.assertIsNotNone(engine2.last)
408+
self.assertTrue(engine2.last.completed)
409+
self.assertEqual(engine2.last.body, complete_payload)
410+
354411

355412
class TestDTLSReadReassemblyWiring(unittest.TestCase):
356413
""":meth:`DTLS.read`'s ``reassembly``/``flow`` arguments, exercised

0 commit comments

Comments
 (0)