From f1e93bb3c3de7cb8b3dfbb3e93c41e444246c290 Mon Sep 17 00:00:00 2001 From: Jarry Shaw Date: Mon, 2 Nov 2026 10:29:18 -0500 Subject: [PATCH] refactor(protocols)!: range-check the transport makers and adopt the shared helpers (#2614) BREAKING CHANGE: the released TCP, UDP and SCTP makers stop wrapping. A value an integer field cannot hold raises ProtocolError naming the field, where it was written as its low bits (TCP(window=70000) packed 0x1170, seq_no=-1 packed 0xffffffff), and a fixed-size octet field of the wrong size raises where it was padded or cut. - TCP, UDP, DCCP and SCTP make() and their option, chunk, parameter and cause makers check each integer field with _make_uint, bar the two below, and each fixed-size octet field with _make_octets; a UDP Length and an SCTP chunk, parameter or cause length past 16 bits, given or computed, raises. - TCP _make_mode_timeout keeps its 15-bit-minutes limit and also refuses, by name, a timeout that is negative, a bool, or neither an int nor a timedelta, where a bare ValueError or AttributeError came out or True packed 1 second. - The Quick-Start TTL Diff keeps wrapping: RFC 4782 defines it modulo 256. - TCP _make_tcp_options, DCCP _make_dccp_options and SCTP _padding_width pad with pad_length; DCCP _make_opt_ndp_count sizes its count with _uint_size. - New test_transport_maker_range_2614_unit; the MPTCP unknown-subtype case in test_tcp_udp_unit gives a first data octet that fits its four bits. --- pcapkit/protocols/transport/dccp.py | 58 ++- pcapkit/protocols/transport/sctp.py | 163 ++++--- pcapkit/protocols/transport/tcp.py | 253 +++++++---- pcapkit/protocols/transport/udp.py | 21 +- .../protocols/transport/test_tcp_udp_unit.py | 2 +- .../test_transport_maker_range_2614_unit.py | 401 ++++++++++++++++++ 6 files changed, 735 insertions(+), 163 deletions(-) create mode 100644 tests/protocols/transport/test_transport_maker_range_2614_unit.py diff --git a/pcapkit/protocols/transport/dccp.py b/pcapkit/protocols/transport/dccp.py index b1c7b0de1d..49673d4dca 100644 --- a/pcapkit/protocols/transport/dccp.py +++ b/pcapkit/protocols/transport/dccp.py @@ -47,6 +47,7 @@ from pcapkit.const.reg.apptype import AppType as Enum_AppType from pcapkit.const.reg.apptype import TransportProtocol as Enum_TransportProtocol from pcapkit.const.reg.transtype import TransType as Enum_TransType +from pcapkit.corekit.fields.strings import pad_length from pcapkit.corekit.module import ModuleDescriptor from pcapkit.corekit.multidict import OrderedMultiDict from pcapkit.protocols.data.transport.dccp import DCCP as Data_DCCP @@ -409,16 +410,21 @@ def make(self, Raises: ProtocolError: If ``srcport`` or ``dstport`` is a :obj:`bool`, the header with its options runs past the 1020 octets a Data Offset - can give, or an option maker rejects its option. + can give, an option maker rejects its option, a numeric field + does not fit its width, ``checksum`` is not two octets, or + ``reset_data`` is not three. EnumValueError: If ``type`` is out of its 4-bit range. """ code = Enum_PacketType.get(type) type_field = { - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=3, name='reserved'), 'type': int(code), 'x': int(x), } # type: Schema_TypeField + ccval = self._make_uint(ccval, bits=4, name='ccval') + cscov = self._make_uint(cscov, bits=4, name='cscov') + seq_bits = (6 if x else 3) * 8 if options is not None: options_value, options_length = self._make_dccp_options(options) @@ -438,15 +444,15 @@ def make(self, 'ccval': ccval, 'cscov': cscov, }, - checksum=b'\x00\x00' if checksum is None else checksum, + checksum=b'\x00\x00' if checksum is None else self._make_octets(checksum, size=2, name='checksum'), type=type_field, - seq_reserved=seq_reserved, - seq=seq, - ack_reserved=ack_reserved, - ack=ack, - service_code=service_code, + seq_reserved=self._make_uint(seq_reserved, bits=8, name='seq_reserved'), + seq=self._make_uint(seq, bits=seq_bits, name='sequence number'), + ack_reserved=self._make_uint(ack_reserved, bits=(2 if x else 1) * 8, name='ack_reserved'), + ack=self._make_uint(ack, bits=seq_bits, name='acknowledgement number'), + service_code=self._make_uint(service_code, bits=32, name='service code'), reset_code=reset_code, - reset_data=reset_data, + reset_data=self._make_octets(reset_data, size=3, name='reset data'), options=options_value, payload=payload, ) @@ -598,8 +604,8 @@ def _make_dccp_options(self, options: 'list[Schema_Option | tuple[Enum_Option, d total_length = sum(len(item) if isinstance(item, bytes) else len(item.pack()) for item in options_list) - if total_length % 4: - pad_len = 4 - total_length % 4 + pad_len = pad_length(total_length, 4) + if pad_len: options_list.extend(self._make_opt_padding(Enum_Option.Padding) # type: ignore[arg-type] for _ in range(pad_len)) total_length += pad_len @@ -1207,15 +1213,15 @@ def _make_opt_ndp_count(self, code: 'Enum_Option', opt: 'Optional[Data_NDPCount] Constructed option schema. Raises: - ProtocolError: If ``count`` does not fit six octets. + ProtocolError: If ``count`` is not an unsigned integer that fits six + octets. """ if opt is not None: count, length = opt.count, opt.length else: - length = max((count.bit_length() + 7) // 8, 1) + 2 - if length > 8: - raise ProtocolError(f'{self.alias}: [Opt {code}] NDP count {count} does not fit 6 octets') + count = self._make_uint(count, bits=48, name=f'[Opt {code}] NDP count') + length = self._uint_size(count, minimum=1) + 2 return Schema_NDPCount( type=code, @@ -1317,11 +1323,14 @@ def _make_opt_timestamp(self, code: 'Enum_Option', opt: 'Optional[Data_Timestamp Returns: Constructed option schema. + Raises: + ProtocolError: If ``timestamp`` does not fit four octets. + """ if opt is not None: timestamp, length = opt.timestamp, opt.length else: - length = 6 + timestamp, length = self._make_uint(timestamp, bits=32, name=f'[Opt {code}] timestamp'), 6 return Schema_Timestamp( type=code, @@ -1346,13 +1355,20 @@ def _make_opt_timestamp_echo(self, code: 'Enum_Option', opt: 'Optional[Data_Time Returns: Constructed option schema. + Raises: + ProtocolError: If ``timestamp`` or ``elapsed`` does not fit four + octets. + """ if opt is not None: timestamp, elapsed, length = opt.timestamp, opt.elapsed, opt.length - elif elapsed is None: - length = 6 else: - length = 8 if elapsed <= 0xFFFF else 10 + timestamp = self._make_uint(timestamp, bits=32, name=f'[Opt {code}] timestamp') + if elapsed is None: + length = 6 + else: + elapsed = self._make_uint(elapsed, bits=32, name=f'[Opt {code}] elapsed') + length = 8 if elapsed <= 0xFFFF else 10 return Schema_TimestampEcho( type=code, @@ -1376,10 +1392,14 @@ def _make_opt_elapsed_time(self, code: 'Enum_Option', opt: 'Optional[Data_Elapse Returns: Constructed option schema. + Raises: + ProtocolError: If ``elapsed`` does not fit four octets. + """ if opt is not None: elapsed, length = opt.elapsed, opt.length else: + elapsed = self._make_uint(elapsed, bits=32, name=f'[Opt {code}] elapsed') length = 4 if elapsed <= 0xFFFF else 6 return Schema_ElapsedTime( diff --git a/pcapkit/protocols/transport/sctp.py b/pcapkit/protocols/transport/sctp.py index 889354669b..f3ab784fcf 100644 --- a/pcapkit/protocols/transport/sctp.py +++ b/pcapkit/protocols/transport/sctp.py @@ -35,6 +35,7 @@ from pcapkit.const.sctp.parameter import Parameter as Enum_Parameter from pcapkit.const.sctp.payload_protocol_identifier import \ PayloadProtocolIdentifier as Enum_PayloadProtocolIdentifier +from pcapkit.corekit.fields.strings import pad_length from pcapkit.corekit.module import ModuleDescriptor from pcapkit.corekit.multidict import OrderedMultiDict from pcapkit.protocols.data.transport.sctp import SCTP as Data_SCTP @@ -245,7 +246,7 @@ def _padding_width(schema: 'Schema') -> 'int': """ length = schema.__dict__.get('length') - return -length % 4 if isinstance(length, int) else 0 + return pad_length(length, 4) if isinstance(length, int) else 0 def _restore_padding(data: 'Optional[Data]', schema: 'Schema_T') -> 'Schema_T': @@ -440,6 +441,16 @@ class SCTP(Transport[Data_SCTP, Schema_SCTP], .. versionadded:: 1.5.0 + .. versionchanged:: 1.6.0 + + :meth:`make` and the chunk, parameter and error cause makers raise + :exc:`~pcapkit.utilities.exceptions.ProtocolError` for an integer field + given a value its width cannot hold, a length included, rather than + writing its low bits or raising a + :exc:`~pcapkit.utilities.exceptions.FieldValueError` or a bare + :exc:`ValueError`, and for a checksum that is not four octets, rather + than padding or cutting it (:issue:`2614`). + """ ########################################################################## @@ -700,7 +711,8 @@ def make(self, Raises: ProtocolError: If ``srcport`` or ``dstport`` is a :obj:`bool` - (:issue:`2287`). + (:issue:`2287`), ``vtag`` does not fit 32 bits, ``chksum`` is + not four octets, or a chunk maker rejects its chunk. Note: There is no ``payload`` argument: SCTP carries its user data in the @@ -716,8 +728,8 @@ def make(self, schema = Schema_SCTP( srcport=self._make_port(srcport, Enum_TransportProtocol.sctp), dstport=self._make_port(dstport, Enum_TransportProtocol.sctp), - vtag=vtag, - chksum=b'\x00\x00\x00\x00' if chksum is None else chksum, + vtag=self._make_uint(vtag, bits=32, name='verification tag'), + chksum=b'\x00\x00\x00\x00' if chksum is None else self._make_octets(chksum, size=4, name='checksum'), chunks=chunks_value, trailer=trailer, ) @@ -1918,7 +1930,7 @@ def _make_chunk_donone(self, code: 'Enum_Chunk', chunk: 'Optional[Data_UnknownCh return Schema_UnknownChunk( type=code, flags=flags, - length=len(value) + 4, + length=self._make_uint(len(value) + 4, bits=16, name=f'[Chunk {code}] length'), value=value, ) @@ -1956,7 +1968,8 @@ def _make_chunk_data(self, code: 'Enum_Chunk', chunk: 'Optional[Data_DATAChunk]' Raises: ProtocolError: If ``data`` is empty, since :rfc:`9260#section-3.3.1` - requires at least one byte of user data. + requires at least one byte of user data, or a field does not + fit its width. """ if chunk is not None: @@ -1978,17 +1991,17 @@ def _make_chunk_data(self, code: 'Enum_Chunk', chunk: 'Optional[Data_DATAChunk]' return Schema_DATAChunk( type=code, flags={ - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=4, name=f'[Chunk {code}] reserved'), 'I': int(I), 'U': int(U), 'B': int(B), 'E': int(E), }, - length=len(data) + 16, - tsn=tsn, - stream_id=stream_id, - stream_seq=stream_seq, - ppid=ppid, + length=self._make_uint(len(data) + 16, bits=16, name=f'[Chunk {code}] length'), + tsn=self._make_uint(tsn, bits=32, name=f'[Chunk {code}] tsn'), + stream_id=self._make_uint(stream_id, bits=16, name=f'[Chunk {code}] stream_id'), + stream_seq=self._make_uint(stream_seq, bits=16, name=f'[Chunk {code}] stream_seq'), + ppid=self._make_uint(ppid, bits=32, name=f'[Chunk {code}] ppid'), data=data, ) @@ -2019,7 +2032,8 @@ def _make_chunk_init(self, code: 'Enum_Chunk', chunk: 'Optional[Data_INITChunk]' Constructed chunk schema. Raises: - ProtocolError: If ``flags`` is **NOT** exactly one byte. + ProtocolError: If ``flags`` is **NOT** exactly one byte, or a field + does not fit its width. Note: The chunk flags are reserved by :rfc:`9260#section-3.3.2`, so they @@ -2047,12 +2061,12 @@ def _make_chunk_init(self, code: 'Enum_Chunk', chunk: 'Optional[Data_INITChunk]' return Schema_INITChunk( type=code, flags=flags, - length=length, - init_tag=init_tag, - a_rwnd=a_rwnd, - outbound_streams=outbound_streams, - inbound_streams=inbound_streams, - init_tsn=init_tsn, + length=self._make_uint(length, bits=16, name=f'[Chunk {code}] length'), + init_tag=self._make_uint(init_tag, bits=32, name=f'[Chunk {code}] init_tag'), + a_rwnd=self._make_uint(a_rwnd, bits=32, name=f'[Chunk {code}] a_rwnd'), + outbound_streams=self._make_uint(outbound_streams, bits=16, name=f'[Chunk {code}] outbound_streams'), + inbound_streams=self._make_uint(inbound_streams, bits=16, name=f'[Chunk {code}] inbound_streams'), + init_tsn=self._make_uint(init_tsn, bits=32, name=f'[Chunk {code}] init_tsn'), parameters=parameters_value, ) @@ -2083,7 +2097,8 @@ def _make_chunk_init_ack(self, code: 'Enum_Chunk', chunk: 'Optional[Data_INITACK Constructed chunk schema. Raises: - ProtocolError: If ``flags`` is **NOT** exactly one byte. + ProtocolError: If ``flags`` is **NOT** exactly one byte, or a field + does not fit its width. """ if chunk is not None: @@ -2107,12 +2122,12 @@ def _make_chunk_init_ack(self, code: 'Enum_Chunk', chunk: 'Optional[Data_INITACK return Schema_INITACKChunk( type=code, flags=flags, - length=length, - init_tag=init_tag, - a_rwnd=a_rwnd, - outbound_streams=outbound_streams, - inbound_streams=inbound_streams, - init_tsn=init_tsn, + length=self._make_uint(length, bits=16, name=f'[Chunk {code}] length'), + init_tag=self._make_uint(init_tag, bits=32, name=f'[Chunk {code}] init_tag'), + a_rwnd=self._make_uint(a_rwnd, bits=32, name=f'[Chunk {code}] a_rwnd'), + outbound_streams=self._make_uint(outbound_streams, bits=16, name=f'[Chunk {code}] outbound_streams'), + inbound_streams=self._make_uint(inbound_streams, bits=16, name=f'[Chunk {code}] inbound_streams'), + init_tsn=self._make_uint(init_tsn, bits=32, name=f'[Chunk {code}] init_tsn'), parameters=parameters_value, ) @@ -2140,7 +2155,9 @@ def _make_chunk_sack(self, code: 'Enum_Chunk', chunk: 'Optional[Data_SACKChunk]' Constructed chunk schema. Raises: - ProtocolError: If ``flags`` is **NOT** exactly one byte. + ProtocolError: If ``flags`` is **NOT** exactly one byte, or a + field, a gap ack block's offset or a duplicate TSN does not + fit its width. Note: The counts of gap ack blocks and duplicate TSNs are derived from the @@ -2161,19 +2178,22 @@ def _make_chunk_sack(self, code: 'Enum_Chunk', chunk: 'Optional[Data_SACKChunk]' for block in gap_blocks or []: if isinstance(block, Schema_GapAckBlock): blocks.append(block) - elif isinstance(block, Data_GapAckBlock): - blocks.append(Schema_GapAckBlock(start=block.start, end=block.end)) else: - start, end = cast('tuple[int, int]', block) - blocks.append(Schema_GapAckBlock(start=start, end=end)) - tsn_list = list(dup_tsn or []) + start, end = ((block.start, block.end) if isinstance(block, Data_GapAckBlock) + else cast('tuple[int, int]', block)) + blocks.append(Schema_GapAckBlock( + start=self._make_uint(start, bits=16, name=f'[Chunk {code}] gap block start'), + end=self._make_uint(end, bits=16, name=f'[Chunk {code}] gap block end'), + )) + tsn_list = [self._make_uint(tsn, bits=32, name=f'[Chunk {code}] dup_tsn') for tsn in dup_tsn or []] return Schema_SACKChunk( type=code, flags=flags, - length=16 + len(blocks) * 4 + len(tsn_list) * 4, - cum_tsn_ack=cum_tsn_ack, - a_rwnd=a_rwnd, + length=self._make_uint(16 + len(blocks) * 4 + len(tsn_list) * 4, bits=16, + name=f'[Chunk {code}] length'), + cum_tsn_ack=self._make_uint(cum_tsn_ack, bits=32, name=f'[Chunk {code}] cum_tsn_ack'), + a_rwnd=self._make_uint(a_rwnd, bits=32, name=f'[Chunk {code}] a_rwnd'), num_gap_blocks=len(blocks), num_dup_tsn=len(tsn_list), gap_blocks=blocks, @@ -2216,7 +2236,7 @@ def _make_chunk_heartbeat(self, code: 'Enum_Chunk', chunk: 'Optional[Data_Heartb return Schema_HeartbeatChunk( type=code, flags=flags, - length=length, + length=self._make_uint(length, bits=16, name=f'[Chunk {code}] length'), parameters=parameters_value, ) @@ -2256,7 +2276,7 @@ def _make_chunk_heartbeat_ack(self, code: 'Enum_Chunk', chunk: 'Optional[Data_He return Schema_HeartbeatACKChunk( type=code, flags=flags, - length=length, + length=self._make_uint(length, bits=16, name=f'[Chunk {code}] length'), parameters=parameters_value, ) @@ -2278,6 +2298,9 @@ def _make_chunk_abort(self, code: 'Enum_Chunk', chunk: 'Optional[Data_AbortChunk Returns: Constructed chunk schema. + Raises: + ProtocolError: If ``reserved`` does not fit 7 bits. + """ if chunk is not None: reserved = chunk.flags.reserved @@ -2294,10 +2317,10 @@ def _make_chunk_abort(self, code: 'Enum_Chunk', chunk: 'Optional[Data_AbortChunk return Schema_AbortChunk( type=code, flags={ - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=7, name=f'[Chunk {code}] reserved'), 'T': int(T), }, - length=length, + length=self._make_uint(length, bits=16, name=f'[Chunk {code}] length'), error=error_value, ) @@ -2318,7 +2341,8 @@ def _make_chunk_shutdown(self, code: 'Enum_Chunk', chunk: 'Optional[Data_Shutdow Constructed chunk schema. Raises: - ProtocolError: If ``flags`` is **NOT** exactly one byte. + ProtocolError: If ``flags`` is **NOT** exactly one byte, or + ``cum_tsn_ack`` does not fit 32 bits. """ if chunk is not None: @@ -2331,7 +2355,7 @@ def _make_chunk_shutdown(self, code: 'Enum_Chunk', chunk: 'Optional[Data_Shutdow type=code, flags=flags, length=8, - cum_tsn_ack=cum_tsn_ack, + cum_tsn_ack=self._make_uint(cum_tsn_ack, bits=32, name=f'[Chunk {code}] cum_tsn_ack'), ) def _make_chunk_shutdown_ack(self, code: 'Enum_Chunk', chunk: 'Optional[Data_ShutdownACKChunk]' = None, *, @@ -2399,7 +2423,7 @@ def _make_chunk_error(self, code: 'Enum_Chunk', chunk: 'Optional[Data_ErrorChunk return Schema_ErrorChunk( type=code, flags=flags, - length=length, + length=self._make_uint(length, bits=16, name=f'[Chunk {code}] length'), error=error_value, ) @@ -2433,7 +2457,7 @@ def _make_chunk_cookie_echo(self, code: 'Enum_Chunk', chunk: 'Optional[Data_Cook return Schema_CookieEchoChunk( type=code, flags=flags, - length=len(cookie) + 4, + length=self._make_uint(len(cookie) + 4, bits=16, name=f'[Chunk {code}] length'), cookie=cookie, ) @@ -2482,6 +2506,9 @@ def _make_chunk_shutdown_complete(self, code: 'Enum_Chunk', chunk: 'Optional[Dat Returns: Constructed chunk schema. + Raises: + ProtocolError: If ``reserved`` does not fit 7 bits. + """ if chunk is not None: reserved = chunk.flags.reserved @@ -2490,7 +2517,7 @@ def _make_chunk_shutdown_complete(self, code: 'Enum_Chunk', chunk: 'Optional[Dat return Schema_ShutdownCompleteChunk( type=code, flags={ - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=7, name=f'[Chunk {code}] reserved'), 'T': int(T), }, length=4, @@ -2841,7 +2868,7 @@ def _make_param_donone(self, code: 'Enum_Parameter', param: 'Optional[Data_Unkno return Schema_UnknownParameter( type=code, - length=len(value) + 4, + length=self._make_uint(len(value) + 4, bits=16, name=f'[Param {code}] length'), value=value, ) @@ -2865,7 +2892,7 @@ def _make_param_hbinfo(self, code: 'Enum_Parameter', param: 'Optional[Data_Heart return Schema_HeartbeatInfoParameter( type=code, - length=len(info) + 4, + length=self._make_uint(len(info) + 4, bits=16, name=f'[Param {code}] length'), info=info, ) @@ -2937,7 +2964,7 @@ def _make_param_cookie(self, code: 'Enum_Parameter', param: 'Optional[Data_State return Schema_StateCookieParameter( type=code, - length=len(cookie) + 4, + length=self._make_uint(len(cookie) + 4, bits=16, name=f'[Param {code}] length'), cookie=cookie, ) @@ -2961,7 +2988,7 @@ def _make_param_unrecognized(self, code: 'Enum_Parameter', param: 'Optional[Data return Schema_UnrecognizedParameter( type=code, - length=len(value) + 4, + length=self._make_uint(len(value) + 4, bits=16, name=f'[Param {code}] length'), value=value, ) @@ -2979,6 +3006,9 @@ def _make_param_preservative(self, code: 'Enum_Parameter', param: 'Optional[Data Returns: Constructed parameter schema. + Raises: + ProtocolError: If ``increment`` does not fit 32 bits. + """ if param is not None: increment = param.increment @@ -2986,7 +3016,7 @@ def _make_param_preservative(self, code: 'Enum_Parameter', param: 'Optional[Data return Schema_CookiePreservativeParameter( type=code, length=8, - increment=increment, + increment=self._make_uint(increment, bits=32, name=f'[Param {code}] increment'), ) def _make_param_hostname(self, code: 'Enum_Parameter', param: 'Optional[Data_HostNameAddressParameter]' = None, *, @@ -3021,7 +3051,7 @@ def _make_param_hostname(self, code: 'Enum_Parameter', param: 'Optional[Data_Hos return Schema_HostNameAddressParameter( type=code, - length=len(name) + 4, + length=self._make_uint(len(name) + 4, bits=16, name=f'[Param {code}] length'), name=name, ) @@ -3051,7 +3081,7 @@ def _make_param_addrtypes(self, code: 'Enum_Parameter', param: 'Optional[Data_Su return Schema_SupportedAddressTypesParameter( type=code, - length=len(types_value) * 2 + 4, + length=self._make_uint(len(types_value) * 2 + 4, bits=16, name=f'[Param {code}] length'), types=types_value, ) @@ -3553,7 +3583,7 @@ def _make_cause_donone(self, code: 'Enum_CauseCode', cause: 'Optional[Data_Unkno return Schema_UnknownCause( code=code, - length=len(value) + 4, + length=self._make_uint(len(value) + 4, bits=16, name=f'[Cause {code}] length'), value=value, ) @@ -3574,7 +3604,8 @@ def _make_cause_invalid_stream(self, code: 'Enum_CauseCode', cause: 'Optional[Da Constructed error cause schema. Raises: - ProtocolError: If ``reserved`` is **NOT** exactly two bytes. + ProtocolError: If ``reserved`` is **NOT** exactly two bytes, or + ``stream_id`` does not fit 16 bits. """ if cause is not None: @@ -3586,7 +3617,7 @@ def _make_cause_invalid_stream(self, code: 'Enum_CauseCode', cause: 'Optional[Da return Schema_InvalidStreamIdentifierCause( code=code, length=8, - stream_id=stream_id, + stream_id=self._make_uint(stream_id, bits=16, name=f'[Cause {code}] stream_id'), reserved=reserved, ) @@ -3621,7 +3652,7 @@ def _make_cause_missing_param(self, code: 'Enum_CauseCode', cause: 'Optional[Dat return Schema_MissingMandatoryParameterCause( code=code, - length=8 + len(types_value) * 2, + length=self._make_uint(8 + len(types_value) * 2, bits=16, name=f'[Cause {code}] length'), num=len(types_value), types=types_value, ) @@ -3640,6 +3671,9 @@ def _make_cause_stale_cookie(self, code: 'Enum_CauseCode', cause: 'Optional[Data Returns: Constructed error cause schema. + Raises: + ProtocolError: If ``staleness`` does not fit 32 bits. + """ if cause is not None: staleness = cause.staleness @@ -3647,7 +3681,7 @@ def _make_cause_stale_cookie(self, code: 'Enum_CauseCode', cause: 'Optional[Data return Schema_StaleCookieCause( code=code, length=8, - staleness=staleness, + staleness=self._make_uint(staleness, bits=32, name=f'[Cause {code}] staleness'), ) def _make_cause_out_of_resource(self, code: 'Enum_CauseCode', cause: 'Optional[Data_OutOfResourceCause]' = None, @@ -3689,7 +3723,7 @@ def _make_cause_unresolvable_addr(self, code: 'Enum_CauseCode', cause: 'Optional return Schema_UnresolvableAddressCause( code=code, - length=len(value) + 4, + length=self._make_uint(len(value) + 4, bits=16, name=f'[Cause {code}] length'), value=value, ) @@ -3714,7 +3748,7 @@ def _make_cause_unrecognized_chunk(self, code: 'Enum_CauseCode', cause: 'Optiona return Schema_UnrecognizedChunkTypeCause( code=code, - length=len(value) + 4, + length=self._make_uint(len(value) + 4, bits=16, name=f'[Cause {code}] length'), value=value, ) @@ -3757,7 +3791,7 @@ def _make_cause_unrecognized_params(self, code: 'Enum_CauseCode', cause: 'Option return Schema_UnrecognizedParametersCause( code=code, - length=len(value) + 4, + length=self._make_uint(len(value) + 4, bits=16, name=f'[Cause {code}] length'), value=value, ) @@ -3775,6 +3809,9 @@ def _make_cause_no_user_data(self, code: 'Enum_CauseCode', cause: 'Optional[Data Returns: Constructed error cause schema. + Raises: + ProtocolError: If ``tsn`` does not fit 32 bits. + """ if cause is not None: tsn = cause.tsn @@ -3782,7 +3819,7 @@ def _make_cause_no_user_data(self, code: 'Enum_CauseCode', cause: 'Optional[Data return Schema_NoUserDataCause( code=code, length=8, - tsn=tsn, + tsn=self._make_uint(tsn, bits=32, name=f'[Cause {code}] tsn'), ) def _make_cause_cookie_shutdown(self, code: 'Enum_CauseCode', cause: 'Optional[Data_CookieReceivedWhileShuttingDownCause]' = None, @@ -3824,7 +3861,7 @@ def _make_cause_restart_addr(self, code: 'Enum_CauseCode', cause: 'Optional[Data return Schema_RestartOfAnAssociationWithNewAddressesCause( code=code, - length=len(value) + 4, + length=self._make_uint(len(value) + 4, bits=16, name=f'[Cause {code}] length'), value=value, ) @@ -3848,7 +3885,7 @@ def _make_cause_user_abort(self, code: 'Enum_CauseCode', cause: 'Optional[Data_U return Schema_UserInitiatedAbortCause( code=code, - length=len(info) + 4, + length=self._make_uint(len(info) + 4, bits=16, name=f'[Cause {code}] length'), info=info, ) @@ -3872,6 +3909,6 @@ def _make_cause_protocol_violation(self, code: 'Enum_CauseCode', cause: 'Optiona return Schema_ProtocolViolationCause( code=code, - length=len(info) + 4, + length=self._make_uint(len(info) + 4, bits=16, name=f'[Cause {code}] length'), info=info, ) diff --git a/pcapkit/protocols/transport/tcp.py b/pcapkit/protocols/transport/tcp.py index e4e31f9c90..c54efefb40 100644 --- a/pcapkit/protocols/transport/tcp.py +++ b/pcapkit/protocols/transport/tcp.py @@ -51,6 +51,7 @@ from pcapkit.const.tcp.mp_tcp_option import MPTCPOption as Enum_MPTCPOption from pcapkit.const.tcp.option import Option as Enum_Option from pcapkit.corekit.fields.ipaddress import parse_ip_address +from pcapkit.corekit.fields.strings import pad_length from pcapkit.corekit.module import ModuleDescriptor from pcapkit.corekit.multidict import OrderedMultiDict from pcapkit.protocols.data.transport.tcp import CC as Data_CC @@ -342,6 +343,16 @@ class TCP(Transport[Data_TCP, Schema_TCP], :exc:`ValueError`, an :exc:`OverflowError` or a :exc:`~pcapkit.utilities.exceptions.FieldValueError`, or a rate of zero written in its place (:issue:`2617`). + * :meth:`make` and the option makers raise + :exc:`~pcapkit.utilities.exceptions.ProtocolError` for an integer + field given a value its width cannot hold, rather than writing its low + bits or raising a :exc:`~pcapkit.utilities.exceptions.FieldValueError` + or a bare :exc:`ValueError`, and for a fixed-size octet field given + the wrong number of octets, rather than padding or cutting them. A + User Timeout that is neither an :class:`int` nor a + :class:`~datetime.timedelta` raises the same, rather than an + :exc:`AttributeError`. The Quick-Start TTL Diff wraps, as + :rfc:`4782` defines it modulo 256 (:issue:`2614`). """ @@ -653,7 +664,8 @@ def make(self, Raises: ProtocolError: If ``srcport`` or ``dstport`` is a :obj:`bool` - (:issue:`2287`). + (:issue:`2287`), a numeric field does not fit its width, or + ``checksum`` is not two octets. .. versionchanged:: 1.5.0 @@ -711,17 +723,17 @@ def make(self, schema = Schema_TCP( srcport=self._make_port(srcport, Enum_TransportProtocol.tcp), dstport=self._make_port(dstport, Enum_TransportProtocol.tcp), - seq=seq_no, - ack=ack_no, + seq=self._make_uint(seq_no, bits=32, name='sequence number'), + ack=self._make_uint(ack_no, bits=32, name='acknowledgement number'), offset={ 'offset': offset, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=3, name='reserved'), 'ns': int(ns), }, flags=flags, - window=window, - checksum=b'\x00\x00' if checksum is None else checksum, - urgent=urgent, + window=self._make_uint(window, bits=16, name='window'), + checksum=b'\x00\x00' if checksum is None else self._make_octets(checksum, size=2, name='checksum'), + urgent=self._make_uint(urgent, bits=16, name='urgent pointer'), options=options_value, payload=payload, ) @@ -992,8 +1004,8 @@ def _make_tcp_options(self, options: 'list[Schema_Option | tuple[Enum_Option, di total_length += len(padding) # force alignment to 32-bit boundary - if total_length % 4: - pad_len = 4 - (total_length % 4) + pad_len = pad_length(total_length, 4) + if pad_len: total_length += pad_len if code == Enum_Option.End_of_Option_List: @@ -2389,6 +2401,9 @@ def _make_mode_mss(self, code: 'Enum_Option', opt: 'Optional[Data_MaximumSegment Returns: Constructed option schema. + Raises: + ProtocolError: If ``mss`` does not fit 16 bits. + """ if opt is not None: mss = opt.mss @@ -2396,7 +2411,7 @@ def _make_mode_mss(self, code: 'Enum_Option', opt: 'Optional[Data_MaximumSegment return Schema_MaximumSegmentSize( kind=code, length=4, - mss=mss, + mss=self._make_uint(mss, bits=16, name=f'[OptNo {code}] mss'), ) def _make_mode_ws(self, code: 'Enum_Option', opt: 'Optional[Data_WindowScale]' = None, *, @@ -2413,6 +2428,9 @@ def _make_mode_ws(self, code: 'Enum_Option', opt: 'Optional[Data_WindowScale]' = Returns: Constructed option schema. + Raises: + ProtocolError: If ``shift`` does not fit 8 bits. + """ if opt is not None: shift = opt.shift @@ -2420,7 +2438,7 @@ def _make_mode_ws(self, code: 'Enum_Option', opt: 'Optional[Data_WindowScale]' = return Schema_WindowScale( kind=code, length=3, - shift=shift, + shift=self._make_uint(shift, bits=8, name=f'[OptNo {code}] shift'), ) def _make_mode_sackpmt(self, code: 'Enum_Option', opt: 'Optional[Data_SACKPermitted]' = None, @@ -2455,21 +2473,17 @@ def _make_mode_sack(self, code: 'Enum_Option', opt: 'Optional[Data_SACK]' = None Returns: Constructed option schema. + Raises: + ProtocolError: If an edge of ``sack`` does not fit 32 bits. + """ if opt is not None: - sack_val = [Schema_SACKBlock( - left=block.left, - right=block.right, - ) for block in opt.sack] - else: - sack_val = [] + sack = [(block.left, block.right) for block in opt.sack] - if sack is not None: - for left, right in sack: - sack_val.append(Schema_SACKBlock( - left=left, - right=right, - )) + sack_val = [Schema_SACKBlock( + left=self._make_uint(left, bits=32, name=f'[OptNo {code}] left edge'), + right=self._make_uint(right, bits=32, name=f'[OptNo {code}] right edge'), + ) for left, right in sack or []] return Schema_SACK( kind=code, @@ -2491,6 +2505,9 @@ def _make_mode_echo(self, code: 'Enum_Option', opt: 'Optional[Data_Echo]' = None Returns: Constructed option schema. + Raises: + ProtocolError: If ``data`` is not four octets. + """ if opt is not None: data = opt.data @@ -2498,7 +2515,7 @@ def _make_mode_echo(self, code: 'Enum_Option', opt: 'Optional[Data_Echo]' = None return Schema_Echo( kind=code, length=6, - data=data, + data=self._make_octets(data, size=4, name=f'[OptNo {code}] data'), ) def _make_mode_echore(self, code: 'Enum_Option', opt: 'Optional[Data_EchoReply]' = None, *, @@ -2515,6 +2532,9 @@ def _make_mode_echore(self, code: 'Enum_Option', opt: 'Optional[Data_EchoReply]' Returns: Constructed option schema. + Raises: + ProtocolError: If ``data`` is not four octets. + """ if opt is not None: data = opt.data @@ -2522,7 +2542,7 @@ def _make_mode_echore(self, code: 'Enum_Option', opt: 'Optional[Data_EchoReply]' return Schema_EchoReply( kind=code, length=6, - data=data, + data=self._make_octets(data, size=4, name=f'[OptNo {code}] data'), ) def _make_mode_ts(self, code: 'Enum_Option', opt: 'Optional[Data_Timestamps]' = None, *, @@ -2541,6 +2561,9 @@ def _make_mode_ts(self, code: 'Enum_Option', opt: 'Optional[Data_Timestamps]' = Returns: Constructed option schema. + Raises: + ProtocolError: If ``tsval`` or ``tsecr`` does not fit 32 bits. + """ if opt is not None: tsval = opt.timestamp @@ -2549,8 +2572,8 @@ def _make_mode_ts(self, code: 'Enum_Option', opt: 'Optional[Data_Timestamps]' = return Schema_Timestamps( kind=code, length=10, - value=tsval, - reply=tsecr, + value=self._make_uint(tsval, bits=32, name=f'[OptNo {code}] tsval'), + reply=self._make_uint(tsecr, bits=32, name=f'[OptNo {code}] tsecr'), ) def _make_mode_poc(self, code: 'Enum_Option', opt: 'Optional[Data_PartialOrderConnectionPermitted]' = None, @@ -2589,6 +2612,9 @@ def _make_mode_pocsp(self, code: 'Enum_Option', opt: 'Optional[Data_PartialOrder Returns: Constructed option schema. + Raises: + ProtocolError: If ``reserved`` does not fit 6 bits. + """ if opt is not None: start = opt.start @@ -2601,7 +2627,7 @@ def _make_mode_pocsp(self, code: 'Enum_Option', opt: 'Optional[Data_PartialOrder profile={ 'start': start, 'end': end, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=6, name=f'[OptNo {code}] reserved'), }, ) @@ -2619,6 +2645,9 @@ def _make_mode_cc(self, code: 'Enum_Option', opt: 'Optional[Data_CC]' = None, *, Returns: Constructed option schema. + Raises: + ProtocolError: If ``count`` does not fit 32 bits. + """ if opt is not None: count = opt.cc @@ -2626,7 +2655,7 @@ def _make_mode_cc(self, code: 'Enum_Option', opt: 'Optional[Data_CC]' = None, *, return Schema_CC( kind=code, length=6, - count=count, + count=self._make_uint(count, bits=32, name=f'[OptNo {code}] count'), ) def _make_mode_ccnew(self, code: 'Enum_Option', opt: 'Optional[Data_CCNew]' = None, *, @@ -2643,6 +2672,9 @@ def _make_mode_ccnew(self, code: 'Enum_Option', opt: 'Optional[Data_CCNew]' = No Returns: Constructed option schema. + Raises: + ProtocolError: If ``count`` does not fit 32 bits. + """ if opt is not None: count = opt.cc @@ -2650,7 +2682,7 @@ def _make_mode_ccnew(self, code: 'Enum_Option', opt: 'Optional[Data_CCNew]' = No return Schema_CCNew( kind=code, length=6, - count=count, + count=self._make_uint(count, bits=32, name=f'[OptNo {code}] count'), ) def _make_mode_ccecho(self, code: 'Enum_Option', opt: 'Optional[Data_CCEcho]' = None, *, @@ -2667,6 +2699,9 @@ def _make_mode_ccecho(self, code: 'Enum_Option', opt: 'Optional[Data_CCEcho]' = Returns: Constructed option schema. + Raises: + ProtocolError: If ``count`` does not fit 32 bits. + """ if opt is not None: count = opt.cc @@ -2674,7 +2709,7 @@ def _make_mode_ccecho(self, code: 'Enum_Option', opt: 'Optional[Data_CCEcho]' = return Schema_CCEcho( kind=code, length=6, - count=count, + count=self._make_uint(count, bits=32, name=f'[OptNo {code}] count'), ) def _make_mode_chkreq(self, code: 'Enum_Option', opt: 'Optional[Data_AlternateChecksumRequest]' = None, *, @@ -2697,6 +2732,9 @@ def _make_mode_chkreq(self, code: 'Enum_Option', opt: 'Optional[Data_AlternateCh Returns: Constructed option schema. + Raises: + ProtocolError: If ``algorithm`` does not fit 8 bits. + """ if opt is not None: algorithm_val = opt.chksum @@ -2707,7 +2745,7 @@ def _make_mode_chkreq(self, code: 'Enum_Option', opt: 'Optional[Data_AlternateCh return Schema_AlternateChecksumRequest( kind=code, length=3, - algorithm=algorithm_val, + algorithm=cast('Enum_Checksum', self._make_uint(algorithm_val, bits=8, name=f'[OptNo {code}] algorithm')), ) def _make_mode_chksum(self, code: 'Enum_Option', opt: 'Optional[Data_AlternateChecksumData]' = None, *, @@ -2748,6 +2786,9 @@ def _make_mode_sig(self, code: 'Enum_Option', opt: 'Optional[Data_MD5Signature]' Returns: Constructed option schema. + Raises: + ProtocolError: If ``digest`` is not 16 octets. + """ if opt is not None: digest = opt.digest @@ -2755,7 +2796,7 @@ def _make_mode_sig(self, code: 'Enum_Option', opt: 'Optional[Data_MD5Signature]' return Schema_MD5Signature( kind=code, length=18, - digest=digest, + digest=self._make_octets(digest, size=16, name=f'[OptNo {code}] digest'), ) def _make_mode_qs(self, code: 'Enum_Option', opt: 'Optional[Data_QuickStartResponse]' = None, *, @@ -2836,14 +2877,23 @@ def _make_mode_timeout(self, code: 'Enum_Option', opt: 'Optional[Data_UserTimeou Constructed option schema. Raises: - ProtocolError: If the timeout does not fit in 15 bits of minutes. + ProtocolError: If the timeout is a :obj:`bool`, is neither an + :class:`int` nor a :class:`~datetime.timedelta`, is negative, + or does not fit in 15 bits of minutes. """ if opt is not None: - seconds = math.floor(opt.timeout.total_seconds()) + timeout = opt.timeout granularity = opt.granularity + + if isinstance(timeout, datetime.timedelta): + seconds = math.floor(timeout.total_seconds()) # type: Optional[int] + elif isinstance(timeout, int) and not isinstance(timeout, bool): + seconds = int(timeout) else: - seconds = timeout if isinstance(timeout, int) else math.floor(timeout.total_seconds()) + seconds = None + if seconds is None or seconds < 0: + raise ProtocolError(f'TCP: invalid [OptNo {code}] timeout: {timeout!r}') # NOTE: a parsed (or requested) unit that the value no longer fits in -- # e.g. a parsed seconds option edited past 15 bits, or a minutes option @@ -2884,6 +2934,10 @@ def _make_mode_ao(self, code: 'Enum_Option', opt: 'Optional[Data_Authentication] Returns: Constructed option schema. + Raises: + ProtocolError: If ``key_id`` or ``next_key_id`` does not fit 8 + bits. + """ if opt is not None: key_id = opt.key_id @@ -2893,8 +2947,8 @@ def _make_mode_ao(self, code: 'Enum_Option', opt: 'Optional[Data_Authentication] return Schema_Authentication( kind=code, length=4 + len(mac), - key_id=key_id, - next_key_id=next_key_id, + key_id=self._make_uint(key_id, bits=8, name=f'[OptNo {code}] key_id'), + next_key_id=self._make_uint(next_key_id, bits=8, name=f'[OptNo {code}] next_key_id'), mac=mac, ) @@ -2954,12 +3008,17 @@ def _make_mptcp_unknown(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_M Args: subtype: MPTCP subtype opt: option data - data: option payload data + data: option payload data, its first octet the four bits after + the subtype **kwargs: arbitrary keyword arguments Returns: Constructed option schema. + Raises: + ProtocolError: If the first octet of ``data`` does not fit four + bits. + """ if opt is not None: data = opt.data @@ -2981,7 +3040,8 @@ def _make_mptcp_unknown(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_M length=3 + len(data[1:]), test={ 'subtype': subtype.value, - 'data': data[0] & 0x0F if data else 0, + 'data': self._make_uint(data[0], bits=4, name=f'[OptNo {Enum_Option.Multipath_TCP}] ' + f'subtype {subtype} first data octet') if data else 0, }, data=data[1:], ) @@ -3025,7 +3085,8 @@ def _make_mptcp_capable(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_M Constructed option schema. Raises: - ProtocolError: If a field is given without the field before it. + ProtocolError: If a field is given without the field before it, or + does not fit its width. """ if opt is not None: @@ -3049,6 +3110,7 @@ def _make_mptcp_capable(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_M f'{self.alias}: [OptNo {Enum_Option.Multipath_TCP}] invalid {names[index]}: ' f'must be None when {names[present]} is None, not {fields[index]!r}') + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' return Schema_MPTCPCapable( kind=cast('Enum_Option', Enum_Option.Multipath_TCP), # NOTE: :rfc:`8684` section 3.1 gives MP_CAPABLE as 4, 12, 20, 22 @@ -3056,19 +3118,19 @@ def _make_mptcp_capable(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_M length=(4, 12, 20, 22, 24)[present], test={ 'subtype': subtype.value, - 'version': version, + 'version': self._make_uint(version, bits=4, name=f'{where} version'), }, flags={ 'req': flag_req, 'ext': flag_ext, 'deny_join': flag_deny_join, - 'reserved': flag_reserved, + 'reserved': self._make_uint(flag_reserved, bits=4, name=f'{where} flag_reserved'), 'hsa': flag_hsa, }, - skey=skey, - rkey=rkey, - dl_len=dl_len, - checksum=checksum, + skey=None if skey is None else self._make_uint(skey, bits=64, name=f'{where} skey'), + rkey=None if rkey is None else self._make_uint(rkey, bits=64, name=f'{where} rkey'), + dl_len=None if dl_len is None else self._make_uint(dl_len, bits=16, name=f'{where} dl_len'), + checksum=None if checksum is None else self._make_octets(checksum, size=2, name=f'{where} checksum'), ) def _make_mptcp_join(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPJoin]' = None, **kwargs: 'Any') -> 'Schema_MPTCPJoin': @@ -3117,6 +3179,9 @@ def _make_join_syn(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPJ Returns: Constructed option schema. + Raises: + ProtocolError: If a field does not fit its width. + """ if opt is not None: reserved = opt.reserved @@ -3125,17 +3190,18 @@ def _make_join_syn(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPJ token = opt.token nonce = opt.nonce + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' return Schema_MPTCPJoinSYN( kind=cast('Enum_Option', Enum_Option.Multipath_TCP), length=12, test={ 'subtype': subtype.value, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=3, name=f'{where} reserved'), 'backup': backup, }, - addr_id=addr_id, - token=token, - nonce=nonce, + addr_id=self._make_uint(addr_id, bits=8, name=f'{where} addr_id'), + token=self._make_uint(token, bits=32, name=f'{where} token'), + nonce=self._make_uint(nonce, bits=32, name=f'{where} nonce'), ) def _make_join_synack(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPJoinSYNACK]' = None, *, @@ -3160,6 +3226,10 @@ def _make_join_synack(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPT Returns: Constructed option schema. + Raises: + ProtocolError: If a field does not fit its width, or ``hmac`` is + not eight octets. + """ if opt is not None: reserved = opt.reserved @@ -3171,6 +3241,7 @@ def _make_join_synack(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPT hmac = opt.hmac nonce = opt.nonce + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' return Schema_MPTCPJoinSYNACK( kind=cast('Enum_Option', Enum_Option.Multipath_TCP), # NOTE: :rfc:`8684` section 3.2 figure 6 gives ``Length = 16`` for the @@ -3181,12 +3252,12 @@ def _make_join_synack(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPT length=16, test={ 'subtype': subtype.value, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=3, name=f'{where} reserved'), 'backup': backup, }, - addr_id=addr_id, - hmac=hmac, - nonce=nonce, + addr_id=self._make_uint(addr_id, bits=8, name=f'{where} addr_id'), + hmac=self._make_octets(hmac, size=8, name=f'{where} hmac'), + nonce=self._make_uint(nonce, bits=32, name=f'{where} nonce'), ) def _make_join_ack(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPJoinACK]' = None, *, @@ -3205,11 +3276,16 @@ def _make_join_ack(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPJ Returns: Constructed option schema. + Raises: + ProtocolError: If ``reserved`` does not fit 12 bits, or ``hmac`` is + not 20 octets. + """ if opt is not None: reserved = opt.reserved hmac = opt.hmac + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' return Schema_MPTCPJoinACK( kind=cast('Enum_Option', Enum_Option.Multipath_TCP), # NOTE: :rfc:`8684` section 3.2 figure 7 gives ``Length = 24`` for the @@ -3219,9 +3295,9 @@ def _make_join_ack(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPJ length=24, test={ 'subtype': subtype.value, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=12, name=f'{where} reserved'), }, - hmac=hmac, + hmac=self._make_octets(hmac, size=20, name=f'{where} hmac'), ) def _make_mptcp_dss(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPDSS]' = None, *, @@ -3257,8 +3333,9 @@ def _make_mptcp_dss(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCP Constructed option schema. Raises: - ProtocolError: If the mapping fields are given only in part, or a - 4-octet field is asked to hold a value wider than 32 bits. + ProtocolError: If the mapping fields are given only in part, a + 4-octet field is asked to hold a value wider than 32 bits, or a + field does not fit its width. """ if opt is not None: @@ -3272,6 +3349,13 @@ def _make_mptcp_dss(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCP dl_len = opt.dl_len checksum = opt.checksum + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' + reserved = self._make_uint(reserved, bits=7, name=f'{where} reserved') + if ack is not None: + ack = self._make_uint(ack, bits=64, name=f'{where} ack') + if dsn is not None: + dsn = self._make_uint(dsn, bits=64, name=f'{where} dsn') + flag_A = ack is not None flag_a = ack_wide if ack_wide is not None else (flag_A and cast('int', ack).bit_length() > 32) @@ -3312,9 +3396,9 @@ def _make_mptcp_dss(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCP }, ack=ack, dsn=dsn, - ssn=ssn, - dl_len=dl_len, - checksum=checksum, + ssn=None if ssn is None else self._make_uint(ssn, bits=32, name=f'{where} ssn'), + dl_len=None if dl_len is None else self._make_uint(dl_len, bits=16, name=f'{where} dl_len'), + checksum=None if checksum is None else self._make_octets(checksum, size=2, name=f'{where} checksum'), ) def _make_mptcp_addaddr(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPAddAddress]' = None, *, @@ -3343,7 +3427,7 @@ def _make_mptcp_addaddr(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_M Raises: ProtocolError: If ``hmac`` is not 8 octets, or is given together - with ``echo`` set. + with ``echo`` set, or a field does not fit its width. FieldValueError: If ``addr`` is a :obj:`bool` or not a valid IP address. @@ -3383,17 +3467,18 @@ def _make_mptcp_addaddr(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_M if opt is None and hmac is not None and (echo or len(hmac) != 8): raise ProtocolError(f'{self.alias}: [OptNo {Enum_Option.Multipath_TCP}] {subtype}: invalid HMAC') + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' return Schema_MPTCPAddAddress( kind=cast('Enum_Option', Enum_Option.Multipath_TCP), length=4 + (4 if version == 4 else 16) + (2 if port is not None else 0) + (8 if hmac is not None else 0), test={ 'subtype': subtype.value, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=3, name=f'{where} reserved'), 'echo': echo, }, - addr_id=addr_id, + addr_id=self._make_uint(addr_id, bits=8, name=f'{where} addr_id'), address=addr_val, - port=port, + port=None if port is None else self._make_uint(port, bits=16, name=f'{where} port'), hmac=hmac, ) @@ -3413,6 +3498,10 @@ def _make_mptcp_remove(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MP Returns: Constructed option schema. + Raises: + ProtocolError: If ``reserved`` does not fit 4 bits, or an address + ID 8 bits. + """ if opt is not None: reserved = opt.reserved @@ -3420,6 +3509,9 @@ def _make_mptcp_remove(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MP else: addr_id_list = addr_id if addr_id is not None else [] + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' + for item in addr_id_list: + self._make_uint(item, bits=8, name=f'{where} addr_id') return Schema_MPTCPRemoveAddress( kind=cast('Enum_Option', Enum_Option.Multipath_TCP), # NOTE: :rfc:`8684` section 3.4.2 figure 13 gives ``Length = 3 + n``, @@ -3431,7 +3523,7 @@ def _make_mptcp_remove(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MP length=3 + len(addr_id_list), test={ 'subtype': subtype.value, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=4, name=f'{where} reserved'), }, addr_id=addr_id_list, ) @@ -3454,6 +3546,10 @@ def _make_mptcp_prio(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTC Returns: Constructed option schema. + Raises: + ProtocolError: If ``reserved`` does not fit 3 bits, or ``addr_id`` + 8 bits. + """ if opt is not None: # NOTE: ``backup`` must be carried over, or reconstructing a parsed @@ -3463,6 +3559,7 @@ def _make_mptcp_prio(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTC backup = opt.backup addr_id = opt.addr_id + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' return Schema_MPTCPPriority( kind=cast('Enum_Option', Enum_Option.Multipath_TCP), # NOTE: :rfc:`8684` section 3.3.8 figure 11 gives MP_PRIO as **3** @@ -3479,10 +3576,10 @@ def _make_mptcp_prio(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTC length=3 if addr_id is None else 4, test={ 'subtype': subtype.value, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=3, name=f'{where} reserved'), 'backup': backup, }, - addr_id=addr_id, + addr_id=None if addr_id is None else self._make_uint(addr_id, bits=8, name=f'{where} addr_id'), ) def _make_mptcp_fail(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPFallback]' = None, *, @@ -3501,19 +3598,24 @@ def _make_mptcp_fail(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTC Returns: Constructed option schema. + Raises: + ProtocolError: If ``reserved`` does not fit 12 bits, or ``dsn`` 64 + bits. + """ if opt is not None: reserved = opt.reserved dsn = opt.dsn + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' return Schema_MPTCPFallback( kind=cast('Enum_Option', Enum_Option.Multipath_TCP), length=12, test={ 'subtype': subtype.value, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=12, name=f'{where} reserved'), }, - dsn=dsn, + dsn=self._make_uint(dsn, bits=64, name=f'{where} dsn'), ) def _make_mptcp_fastclose(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data_MPTCPFastclose]' = None, *, @@ -3532,19 +3634,24 @@ def _make_mptcp_fastclose(self, subtype: 'Enum_MPTCPOption', opt: 'Optional[Data Returns: Constructed option schema. + Raises: + ProtocolError: If ``reserved`` does not fit 12 bits, or ``key`` 64 + bits. + """ if opt is not None: reserved = opt.reserved key = opt.rkey + where = f'[OptNo {Enum_Option.Multipath_TCP}] {subtype.name}' return Schema_MPTCPFastclose( kind=cast('Enum_Option', Enum_Option.Multipath_TCP), length=12, test={ 'subtype': subtype.value, - 'reserved': reserved, + 'reserved': self._make_uint(reserved, bits=12, name=f'{where} reserved'), }, - key=key, + key=self._make_uint(key, bits=64, name=f'{where} key'), ) def _make_mode_fastopen(self, code: 'Enum_Option', opt: 'Optional[Data_FastOpenCookie]' = None, *, diff --git a/pcapkit/protocols/transport/udp.py b/pcapkit/protocols/transport/udp.py index 64f5992563..5b9b476b82 100644 --- a/pcapkit/protocols/transport/udp.py +++ b/pcapkit/protocols/transport/udp.py @@ -86,10 +86,14 @@ class UDP(Transport[Data_UDP, Schema_UDP], .. versionchanged:: 1.6.0 - The checksum is computed when :meth:`make` is given none, over the - ``pseudo`` it is given or by the enclosing IP layer, and verified by that - layer under :data:`~pcapkit.utilities.config.CHECKSUM_VERIFY` - (:issue:`2474`). + * The checksum is computed when :meth:`make` is given none, over the + ``pseudo`` it is given or by the enclosing IP layer, and verified by + that layer under :data:`~pcapkit.utilities.config.CHECKSUM_VERIFY` + (:issue:`2474`). + * :meth:`make` raises :exc:`~pcapkit.utilities.exceptions.ProtocolError` + for a Length past 16 bits, given or computed, and a checksum that is + not two octets, where it wrote the Length's low 16 bits and padded or + cut the checksum (:issue:`2614`). """ @@ -248,7 +252,8 @@ def make(self, computed over ``pseudo`` (:rfc:`768`), or left to an IP layer this datagram is the payload of; zero, i.e. none, otherwise. total_length: Length of the datagram, header included; computed from - the header and the payload when omitted. + the header and the payload when omitted. A jumbogram's is + given as zero (:rfc:`2675#section-4`). payload: Payload data. trailer: Octets after the datagram, outside the Length field; written as is and not counted in a computed ``total_length``. @@ -261,7 +266,8 @@ def make(self, Raises: ProtocolError: If ``srcport`` or ``dstport`` is a :obj:`bool` - (:issue:`2287`). + (:issue:`2287`), ``total_length``, given or computed, does not + fit 16 bits, or ``checksum`` is not two octets. .. versionchanged:: 1.5.0 @@ -279,12 +285,13 @@ def make(self, # what a plain ``UDP(payload=...)`` wants. if total_length is None: total_length = 8 + len(payload) + total_length = self._make_uint(total_length, bits=16, name='length') schema = Schema_UDP( srcport=self._make_port(srcport, Enum_TransportProtocol.udp), dstport=self._make_port(dstport, Enum_TransportProtocol.udp), len=total_length, - checksum=b'\x00\x00' if checksum is None else checksum, + checksum=b'\x00\x00' if checksum is None else self._make_octets(checksum, size=2, name='checksum'), payload=payload, trailer=trailer, ) diff --git a/tests/protocols/transport/test_tcp_udp_unit.py b/tests/protocols/transport/test_tcp_udp_unit.py index 7afe004994..85550f4cb6 100644 --- a/tests/protocols/transport/test_tcp_udp_unit.py +++ b/tests/protocols/transport/test_tcp_udp_unit.py @@ -896,7 +896,7 @@ def test_tcp_mptcp_constructors_cover_flag_branches(self) -> None: ) self.assertEqual( proto._make_mptcp_unknown(MPTCPOption.Reserved_for_Private_Use, - data=b'\xfa\x01').to_dict()['data'], + data=b'\x0a\x01').to_dict()['data'], b'\x01', ) self.assertIsNone(proto._make_mptcp_capable(MPTCPOption.MP_CAPABLE, diff --git a/tests/protocols/transport/test_transport_maker_range_2614_unit.py b/tests/protocols/transport/test_transport_maker_range_2614_unit.py new file mode 100644 index 0000000000..f3bcb54adc --- /dev/null +++ b/tests/protocols/transport/test_transport_maker_range_2614_unit.py @@ -0,0 +1,401 @@ +# -*- coding: utf-8 -*- +"""The TCP, UDP, DCCP and SCTP makers refuse a value its field cannot hold (#2614). + +The owner ruled on #2614 that :meth:`Protocol._make_uint +` raises on a value outside its +field rather than wrapping it, and that :meth:`Protocol._make_octets +` checks a fixed-size octet +field. So ``TCP(window=70000)`` raises ``ProtocolError: TCP: invalid window: +70000`` rather than packing ``0x1170``, and ``TCP(seq_no=-1)`` raises rather +than packing ``0xffffffff``. A bit-field given a negative value raises the +same, not the bare ``ValueError`` the field itself would, and a checksum of the +wrong size is refused, not padded or cut. + +Each refusal names the field, and each table is paired with the widest value +the field holds, packed where the RFC puts it. The one exception is the +Quick-Start TTL Diff, which RFC 4782 defines modulo 256 and so wraps. + +Every case builds its own octets, so this belongs to the unit tier. + +""" +from __future__ import annotations + +import datetime +import re +import unittest +from typing import TYPE_CHECKING + +from tests._support import reimport_once_per_class + +if TYPE_CHECKING: + from typing import Any, Callable + + +class RangeTestCase(unittest.TestCase): + """Shared assertions: the refusal is a ``ProtocolError`` naming the field.""" + + def setUp(self) -> 'None': + reimport_once_per_class(self) + + def assertRefused(self, alias: 'str', name: 'str', value: 'Any', build: 'Callable[[], Any]') -> 'None': + """``build()`` raises ``ProtocolError: : invalid : ``.""" + from pcapkit.utilities.exceptions import ProtocolError + + pattern = rf'^{alias}: invalid {re.escape(name)}: {re.escape(repr(value))}$' + with self.assertRaisesRegex(ProtocolError, pattern): + build() + + def assertWrongSize(self, alias: 'str', name: 'str', size: 'int', value: 'bytes', + build: 'Callable[[], Any]') -> 'None': + """``build()`` raises the ``ProtocolError`` of an octet field of the wrong size.""" + from pcapkit.utilities.exceptions import ProtocolError + + pattern = rf'^{alias}: invalid {re.escape(name)}: must be {size} octets, not {re.escape(repr(value))}$' + with self.assertRaisesRegex(ProtocolError, pattern): + build() + + +class TCPRangeTests(RangeTestCase): + """:rfc:`9293#section-3.1` header fields, and the option fields.""" + + def test_header_field_outside_its_width_is_refused(self) -> 'None': + from pcapkit.protocols.transport.tcp import TCP + + for keyword, name, values in (('seq_no', 'sequence number', (-1, 1 << 32, True)), + ('ack_no', 'acknowledgement number', (-1, 1 << 32)), + ('reserved', 'reserved', (-1, 8, True)), + ('window', 'window', (-1, 70000, True)), + ('urgent', 'urgent pointer', (-1, 1 << 16))): + for value in values: + with self.subTest(field=keyword, value=value): + self.assertRefused('TCP', name, value, lambda: TCP(**{keyword: value})) + + def test_checksum_of_the_wrong_size_is_refused(self) -> 'None': + from pcapkit.protocols.transport.tcp import TCP + + for value in (b'', b'\x01', b'\x01\x02\x03'): + with self.subTest(value=value): + self.assertWrongSize('TCP', 'checksum', 2, value, lambda: TCP(checksum=value)) + + def test_header_field_takes_its_widest_value(self) -> 'None': + from pcapkit.protocols.transport.tcp import TCP + + raw = TCP(seq_no=0xFFFF_FFFF, ack_no=0xFFFF_FFFF, reserved=0b111, window=0xFFFF, + checksum=b'\x12\x34', urgent=0xFFFF).data + self.assertEqual(raw[4:12], b'\xff' * 8) + self.assertEqual(raw[12] & 0b1110, 0b1110) # Data Offset, then the reserved bits, then NS + self.assertEqual(raw[14:20], b'\xff\xff\x12\x34\xff\xff') + + def test_option_field_outside_its_width_is_refused(self) -> 'None': + from pcapkit.const.tcp.option import Option + from pcapkit.protocols.transport.tcp import TCP + + for code, args, name, value in ( + (Option.Maximum_Segment_Size, {'mss': 1 << 16}, 'mss', 1 << 16), + (Option.Window_Scale, {'shift': 256}, 'shift', 256), + (Option.SACK, {'sack': [(1 << 32, 0)]}, 'left edge', 1 << 32), + (Option.SACK, {'sack': [(0, -1)]}, 'right edge', -1), + (Option.Timestamps, {'tsval': 1 << 32}, 'tsval', 1 << 32), + (Option.Timestamps, {'tsecr': -1}, 'tsecr', -1), + (Option.Partial_Order_Service_Profile, {'reserved': 64}, 'reserved', 64), + (Option.CC, {'count': 1 << 32}, 'count', 1 << 32), + (Option.CC_NEW, {'count': -1}, 'count', -1), + (Option.CC_ECHO, {'count': True}, 'count', True), + (Option.TCP_Alternate_Checksum_Request, {'algorithm': 256}, 'algorithm', 256), + (Option.TCP_Authentication_Option, {'key_id': 256}, 'key_id', 256), + (Option.TCP_Authentication_Option, {'next_key_id': -1}, 'next_key_id', -1), + ): + with self.subTest(code=code, field=name, value=value): + self.assertRefused('TCP', f'[OptNo {code}] {name}', value, + lambda: TCP(options=[(code, args)])) + + def test_user_timeout_outside_its_range_is_refused(self) -> 'None': + """A negative timeout raises by name, not a bare ``ValueError``, and ``True`` is not one second.""" + from pcapkit.const.tcp.option import Option + from pcapkit.protocols.data.transport.tcp import UserTimeout + from pcapkit.protocols.transport.tcp import TCP + + code = Option.User_Timeout_Option + for value in (-1, datetime.timedelta(seconds=-5), True, 1.5, None): + with self.subTest(timeout=value): + self.assertRefused('TCP', f'[OptNo {code}] timeout', value, + lambda: TCP(options=[(code, {'timeout': value})])) + + edited = UserTimeout(kind=code, length=4, timeout=datetime.timedelta(seconds=-1), granularity=False) + self.assertRefused('TCP', f'[OptNo {code}] timeout', edited.timeout, + lambda: object.__new__(TCP)._make_mode_timeout(code, edited)) + + def test_user_timeout_takes_its_range(self) -> 'None': + """RFC 5482 section 3: the ``G`` bit, then 15 bits of seconds or minutes.""" + from pcapkit.const.tcp.option import Option + from pcapkit.protocols.transport.tcp import TCP + + code = Option.User_Timeout_Option + for value, wire in ((0, '1c040000'), (datetime.timedelta(0), '1c040000'), + (0x7FFF * 60, '1c04ffff')): + with self.subTest(timeout=value): + self.assertEqual(TCP(options=[(code, {'timeout': value})]).data[20:24].hex(), wire) + + def test_option_octets_of_the_wrong_size_are_refused(self) -> 'None': + from pcapkit.const.tcp.option import Option + from pcapkit.protocols.transport.tcp import TCP + + for code, keyword, size, value in ((Option.Echo, 'data', 4, b'abc'), + (Option.Echo_Reply, 'data', 4, b'abcde'), + (Option.MD5_Signature_Option, 'digest', 16, bytes(15))): + with self.subTest(code=code, value=value): + self.assertWrongSize('TCP', f'[OptNo {code}] {keyword}', size, value, + lambda: TCP(options=[(code, {keyword: value})])) + + def test_mptcp_field_outside_its_width_is_refused(self) -> 'None': + from pcapkit.const.tcp.mp_tcp_option import MPTCPOption + from pcapkit.const.tcp.option import Option + from pcapkit.protocols.transport.tcp import TCP + + syn, synack, ack = {'syn': True}, {'syn': True, 'ack': True}, {'ack': True} + for flags, subtype, args, name, value in ( + ({}, MPTCPOption.MP_CAPABLE, {'version': 16}, 'version', 16), + ({}, MPTCPOption.MP_CAPABLE, {'flag_reserved': -1}, 'flag_reserved', -1), + ({}, MPTCPOption.MP_CAPABLE, {'skey': 1 << 64}, 'skey', 1 << 64), + ({}, MPTCPOption.MP_CAPABLE, {'rkey': -1}, 'rkey', -1), + ({}, MPTCPOption.MP_CAPABLE, {'dl_len': 1 << 16}, 'dl_len', 1 << 16), + (syn, MPTCPOption.MP_JOIN, {'reserved': 8}, 'reserved', 8), + (syn, MPTCPOption.MP_JOIN, {'addr_id': 256}, 'addr_id', 256), + (syn, MPTCPOption.MP_JOIN, {'token': 1 << 32}, 'token', 1 << 32), + (syn, MPTCPOption.MP_JOIN, {'nonce': -1}, 'nonce', -1), + (synack, MPTCPOption.MP_JOIN, {'addr_id': -1}, 'addr_id', -1), + (synack, MPTCPOption.MP_JOIN, {'nonce': 1 << 32}, 'nonce', 1 << 32), + (ack, MPTCPOption.MP_JOIN, {'reserved': 1 << 12}, 'reserved', 1 << 12), + ({}, MPTCPOption.DSS, {'reserved': 128}, 'reserved', 128), + ({}, MPTCPOption.DSS, {'ack': -1}, 'ack', -1), + ({}, MPTCPOption.DSS, {'dsn': 1 << 64, 'ssn': 0, 'dl_len': 0}, 'dsn', 1 << 64), + ({}, MPTCPOption.DSS, {'dsn': 0, 'ssn': 1 << 32, 'dl_len': 0}, 'ssn', 1 << 32), + ({}, MPTCPOption.DSS, {'dsn': 0, 'ssn': 0, 'dl_len': -1}, 'dl_len', -1), + ({}, MPTCPOption.ADD_ADDR, {'reserved': 8, 'hmac': bytes(8)}, 'reserved', 8), + ({}, MPTCPOption.ADD_ADDR, {'addr_id': 256}, 'addr_id', 256), + ({}, MPTCPOption.ADD_ADDR, {'port': 1 << 16}, 'port', 1 << 16), + ({}, MPTCPOption.REMOVE_ADDR, {'reserved': 16}, 'reserved', 16), + ({}, MPTCPOption.REMOVE_ADDR, {'addr_id': [1, 256]}, 'addr_id', 256), + ({}, MPTCPOption.MP_PRIO, {'reserved': -1}, 'reserved', -1), + ({}, MPTCPOption.MP_PRIO, {'addr_id': 256}, 'addr_id', 256), + ({}, MPTCPOption.MP_FAIL, {'reserved': 1 << 12}, 'reserved', 1 << 12), + ({}, MPTCPOption.MP_FAIL, {'dsn': 1 << 64}, 'dsn', 1 << 64), + ({}, MPTCPOption.MP_FASTCLOSE, {'reserved': -1}, 'reserved', -1), + ({}, MPTCPOption.MP_FASTCLOSE, {'key': -1}, 'key', -1), + ): + with self.subTest(subtype=subtype.name, flags=flags, field=name, value=value): + option = (Option.Multipath_TCP, {'subtype': subtype, **args}) + self.assertRefused('TCP', f'[OptNo {Option.Multipath_TCP}] {subtype.name} {name}', value, + lambda: TCP(options=[option], **flags)) + + def test_mptcp_octets_of_the_wrong_size_are_refused(self) -> 'None': + from pcapkit.const.tcp.mp_tcp_option import MPTCPOption + from pcapkit.const.tcp.option import Option + from pcapkit.protocols.transport.tcp import TCP + + for flags, subtype, args, name, size, value in ( + ({'syn': True, 'ack': True}, MPTCPOption.MP_JOIN, {}, 'hmac', 8, bytes(7)), + ({'ack': True}, MPTCPOption.MP_JOIN, {}, 'hmac', 20, bytes(19)), + ({}, MPTCPOption.MP_CAPABLE, {'dl_len': 0}, 'checksum', 2, b'\x01'), + ({}, MPTCPOption.DSS, {'dsn': 0, 'ssn': 0, 'dl_len': 0}, 'checksum', 2, b''), + ): + with self.subTest(subtype=subtype.name, field=name, value=value): + option = (Option.Multipath_TCP, {'subtype': subtype, name: value, **args}) + self.assertWrongSize('TCP', f'[OptNo {Option.Multipath_TCP}] {subtype.name} {name}', size, value, + lambda: TCP(options=[option], **flags)) + + def test_unknown_mptcp_subtype_keeps_its_first_octet_to_four_bits(self) -> 'None': + """The first data octet is the low nibble of the subtype octet, refused past it, not masked.""" + from pcapkit.const.tcp.mp_tcp_option import MPTCPOption + from pcapkit.const.tcp.option import Option + from pcapkit.protocols.transport.tcp import TCP + + subtype = MPTCPOption.get(14) + self.assertRefused('TCP', f'[OptNo {Option.Multipath_TCP}] subtype {subtype} first data octet', 0xFA, + lambda: TCP(options=[(Option.Multipath_TCP, {'subtype': subtype, 'data': b'\xfa'})])) + raw = TCP(options=[(Option.Multipath_TCP, {'subtype': subtype, 'data': b'\x0f\x01'})]).data + self.assertEqual(raw[20:24], bytes([30, 4, 0xEF, 0x01])) # RFC 8684 section 3: subtype, then 4 bits + + def test_option_field_takes_its_widest_value(self) -> 'None': + from pcapkit.const.tcp.mp_tcp_option import MPTCPOption + from pcapkit.const.tcp.option import Option + from pcapkit.protocols.transport.tcp import TCP + + raw = TCP(options=[(Option.Maximum_Segment_Size, {'mss': 0xFFFF}), + (Option.Timestamps, {'tsval': 0xFFFF_FFFF, 'tsecr': 0xFFFF_FFFF}), + (Option.Multipath_TCP, {'subtype': MPTCPOption.MP_FASTCLOSE, 'key': (1 << 64) - 1})]).data + self.assertEqual(raw[20:24], b'\x02\x04\xff\xff') + self.assertEqual(raw[24:34], b'\x08\x0a' + b'\xff' * 8) + self.assertEqual(raw[34:46], bytes([30, 12, MPTCPOption.MP_FASTCLOSE << 4, 0]) + b'\xff' * 8) + + def test_quick_start_ttl_diff_wraps_modulo_256(self) -> 'None': + """RFC 4782 section 4.2 defines the TTL Diff modulo 256, so it wraps and is not refused.""" + from pcapkit.const.tcp.option import Option + from pcapkit.protocols.transport.tcp import TCP + + for value, octet in ((-1, 0xFF), (256, 0x00), (255, 0xFF), (300, 0x2C)): + with self.subTest(diff=value): + raw = TCP(options=[(Option.Quick_Start_Response, {'rate': 0, 'diff': value})]).data + # Kind, Length, Resv. and Rate (both zero), then the TTL Diff octet. + self.assertEqual(raw[20:24], bytes([Option.Quick_Start_Response, 8, 0, octet])) + + +class UDPRangeTests(RangeTestCase): + """:rfc:`768` Length and Checksum.""" + + def test_length_outside_16_bits_is_refused(self) -> 'None': + from pcapkit.protocols.transport.udp import UDP + + for value in (-1, 1 << 16, True): + with self.subTest(total_length=value): + self.assertRefused('UDP', 'length', value, lambda: UDP(total_length=value)) + self.assertRefused('UDP', 'length', 1 << 16, lambda: UDP(payload=bytes(0xFFF8))) + + def test_checksum_of_the_wrong_size_is_refused(self) -> 'None': + from pcapkit.protocols.transport.udp import UDP + + for value in (b'\x01', b'\x01\x02\x03'): + with self.subTest(value=value): + self.assertWrongSize('UDP', 'checksum', 2, value, lambda: UDP(checksum=value)) + + def test_length_takes_its_widest_value_and_a_jumbogram_zero(self) -> 'None': + from pcapkit.protocols.transport.udp import UDP + + self.assertEqual(UDP(payload=bytes(0xFFF7)).data[4:6], b'\xff\xff') + self.assertEqual(UDP(total_length=0xFFFF, checksum=b'\x00\x00').data, bytes(4) + b'\xff\xff' + bytes(2)) + # A jumbogram's Length is zero (RFC 2675 section 4). + self.assertEqual(UDP(total_length=0, payload=b'x', checksum=b'\x00\x00').data[4:6], b'\x00\x00') + + +class DCCPRangeTests(RangeTestCase): + """:rfc:`4340#section-5.1` generic header, its subheaders, and the options.""" + + def test_header_field_outside_its_width_is_refused(self) -> 'None': + from pcapkit.protocols.transport.dccp import DCCP + + for args, name, value in (({'reserved': 8}, 'reserved', 8), + ({'ccval': 16}, 'ccval', 16), + ({'cscov': -1}, 'cscov', -1), + ({'seq_reserved': 256}, 'seq_reserved', 256), + ({'seq': 1 << 48}, 'sequence number', 1 << 48), + ({'x': False, 'seq': 1 << 24}, 'sequence number', 1 << 24), + ({'type': 3, 'ack_reserved': 1 << 16}, 'ack_reserved', 1 << 16), + ({'type': 3, 'x': False, 'ack_reserved': 256}, 'ack_reserved', 256), + ({'type': 3, 'ack': -1}, 'acknowledgement number', -1), + ({'service_code': 1 << 32}, 'service code', 1 << 32)): + with self.subTest(args=args): + self.assertRefused('DCCP', name, value, lambda: DCCP(**args)) + + def test_header_octets_of_the_wrong_size_are_refused(self) -> 'None': + from pcapkit.protocols.transport.dccp import DCCP + + self.assertWrongSize('DCCP', 'checksum', 2, b'\x01', lambda: DCCP(checksum=b'\x01')) + self.assertWrongSize('DCCP', 'reset data', 3, b'\x01\x02', + lambda: DCCP(type=7, reset_data=b'\x01\x02')) + + def test_option_field_outside_its_width_is_refused(self) -> 'None': + from pcapkit.const.dccp.option import Option + from pcapkit.protocols.transport.dccp import DCCP + + for code, args, name, value in ((Option.NDP_Count, {'count': -1}, 'NDP count', -1), + (Option.Timestamp, {'timestamp': 1 << 32}, 'timestamp', 1 << 32), + (Option.Timestamp_Echo, {'timestamp': -1}, 'timestamp', -1), + (Option.Timestamp_Echo, {'elapsed': 1 << 32}, 'elapsed', 1 << 32), + (Option.Elapsed_Time, {'elapsed': -1}, 'elapsed', -1)): + with self.subTest(code=code, args=args): + self.assertRefused('DCCP', f'[Opt {code}] {name}', value, + lambda: DCCP(type=3, checksum=b'\x00\x00', options=[(code, args)])) + + def test_field_takes_its_widest_value(self) -> 'None': + from pcapkit.const.dccp.option import Option + from pcapkit.protocols.transport.dccp import DCCP + + # X clear: a 24-bit Sequence Number at octet 9, then a reserved octet and a + # 24-bit Acknowledgement Number (RFC 4340 section 5.1). + raw = DCCP(type=3, x=False, seq=0xFF_FFFF, ack_reserved=0xFF, ack=0xFF_FFFF, checksum=b'\x00\x00', + options=[(Option.NDP_Count, {'count': 0xFFFF}), (Option.NDP_Count, {'count': 0})]).data + self.assertEqual(raw[9:16], b'\xff' * 7) + # The fewest octets that hold the count, and at least one (RFC 4340 section 7.7). + self.assertEqual(raw[16:23], bytes([37, 4, 0xFF, 0xFF, 37, 3, 0])) + + +class SCTPRangeTests(RangeTestCase): + """:rfc:`9260#section-3` common header, chunks, parameters and error causes.""" + + def test_header_field_outside_its_width_is_refused(self) -> 'None': + from pcapkit.protocols.transport.sctp import SCTP + + for value in (-1, 1 << 32, True): + with self.subTest(vtag=value): + self.assertRefused('SCTP', 'verification tag', value, lambda: SCTP(vtag=value)) + self.assertWrongSize('SCTP', 'checksum', 4, b'\x01\x02\x03', lambda: SCTP(chksum=b'\x01\x02\x03')) + + def test_chunk_field_outside_its_width_is_refused(self) -> 'None': + from pcapkit.const.sctp.chunk import Chunk + from pcapkit.protocols.transport.sctp import SCTP + + data = {'data': b'x'} + for code, args, name, value in ( + (Chunk.Payload_Data, {**data, 'reserved': 16}, 'reserved', 16), + (Chunk.Payload_Data, {**data, 'tsn': 1 << 32}, 'tsn', 1 << 32), + (Chunk.Payload_Data, {**data, 'stream_id': 1 << 16}, 'stream_id', 1 << 16), + (Chunk.Payload_Data, {**data, 'stream_seq': -1}, 'stream_seq', -1), + (Chunk.Payload_Data, {**data, 'ppid': 1 << 32}, 'ppid', 1 << 32), + (Chunk.Payload_Data, {'data': bytes(0xFFF0)}, 'length', 1 << 16), + (Chunk.Initiation, {'init_tag': 1 << 32}, 'init_tag', 1 << 32), + (Chunk.Initiation, {'a_rwnd': -1}, 'a_rwnd', -1), + (Chunk.Initiation, {'outbound_streams': 1 << 16}, 'outbound_streams', 1 << 16), + (Chunk.Initiation, {'inbound_streams': -1}, 'inbound_streams', -1), + (Chunk.Initiation, {'init_tsn': 1 << 32}, 'init_tsn', 1 << 32), + (Chunk.Initiation_Acknowledgement, {'init_tag': -1}, 'init_tag', -1), + (Chunk.Selective_Acknowledgement, {'cum_tsn_ack': 1 << 32}, 'cum_tsn_ack', 1 << 32), + (Chunk.Selective_Acknowledgement, {'a_rwnd': -1}, 'a_rwnd', -1), + (Chunk.Selective_Acknowledgement, {'gap_blocks': [(1 << 16, 1)]}, 'gap block start', 1 << 16), + (Chunk.Selective_Acknowledgement, {'gap_blocks': [(1, -1)]}, 'gap block end', -1), + (Chunk.Selective_Acknowledgement, {'dup_tsn': [1, 1 << 32]}, 'dup_tsn', 1 << 32), + (Chunk.Abort, {'reserved': 128}, 'reserved', 128), + (Chunk.Shutdown, {'cum_tsn_ack': -1}, 'cum_tsn_ack', -1), + (Chunk.Shutdown_Complete, {'reserved': -1}, 'reserved', -1), + (Chunk.State_Cookie, {'cookie': bytes(0xFFFC)}, 'length', 1 << 16), + ): + with self.subTest(code=code, field=name): + self.assertRefused('SCTP', f'[Chunk {code}] {name}', value, + lambda: SCTP(chunks=[(code, args)])) + + def test_parameter_and_cause_field_outside_its_width_is_refused(self) -> 'None': + from pcapkit.const.sctp.cause_code import CauseCode + from pcapkit.const.sctp.chunk import Chunk + from pcapkit.const.sctp.parameter import Parameter + from pcapkit.protocols.transport.sctp import SCTP + + for chunk, code, nested, args, name, value in ( + (Chunk.Initiation, Parameter.Cookie_Preservative, 'parameters', {'increment': 1 << 32}, + 'increment', 1 << 32), + (Chunk.Heartbeat_Request, Parameter.Heartbeat_Info, 'parameters', {'info': bytes(0xFFFC)}, + 'length', 1 << 16), + (Chunk.Operation_Error, CauseCode.Invalid_Stream_Identifier, 'error', {'stream_id': 1 << 16}, + 'stream_id', 1 << 16), + (Chunk.Operation_Error, CauseCode.Stale_Cookie, 'error', {'staleness': -1}, 'staleness', -1), + (Chunk.Abort, CauseCode.No_User_Data, 'error', {'tsn': 1 << 32}, 'tsn', 1 << 32), + (Chunk.Abort, CauseCode.User_Initiated_Abort, 'error', {'info': bytes(0xFFFC)}, 'length', 1 << 16), + ): + kind = 'Param' if nested == 'parameters' else 'Cause' + with self.subTest(code=code, field=name): + self.assertRefused('SCTP', f'[{kind} {code}] {name}', value, + lambda: SCTP(chunks=[(chunk, {nested: [(code, args)]})])) + + def test_field_takes_its_widest_value(self) -> 'None': + from pcapkit.const.sctp.chunk import Chunk + from pcapkit.protocols.transport.sctp import SCTP + + raw = SCTP(vtag=0xFFFF_FFFF, chunks=[(Chunk.Payload_Data, { + 'data': b'x', 'tsn': 0xFFFF_FFFF, 'stream_id': 0xFFFF, 'stream_seq': 0xFFFF, 'ppid': 0xFFFF_FFFF, + })]).data + self.assertEqual(raw[4:8], b'\xff' * 4) + # RFC 9260 section 3.3.1: TSN, Stream Identifier, Stream Sequence Number, then the PPID. + self.assertEqual(raw[12:16], b'\x00\x03\x00\x11') + self.assertEqual(raw[16:28], b'\xff' * 12) + + +if __name__ == '__main__': + unittest.main()