Skip to content

Commit b7b02c0

Browse files
authored
fix(corekit): range-check ports in PortEnumField, and document NumberField's masking (#2314) (#2335)
1 parent cbf882a commit b7b02c0

3 files changed

Lines changed: 123 additions & 1 deletion

File tree

‎pcapkit/corekit/fields/numbers.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,14 @@ class NumberField(Field[int], Generic[_T]):
158158
-- see GitHub issue :issue:`545`. Omitting it, or passing the sign the
159159
class already fixes, stays legal.
160160
161+
Packing does not range-check a value: :meth:`pre_process` masks it to
162+
:attr:`bit_length` bits, so e.g. ``70000`` in a two-octet field packs
163+
as ``0x1170`` and ``-1`` as ``0xffff``, with no error or warning. This
164+
is the documented contract a parsed value's round trip relies on
165+
(:issue:`1488`). A range check belongs in the protocol's ``make`` or in
166+
a field whose values have a range of their own, such as
167+
:class:`PortEnumField` (:issue:`2314`).
168+
161169
"""
162170

163171
__length__ = None # type: Optional[int]
@@ -1065,6 +1073,20 @@ def pre_process(self, value: 'int | AppType', packet: 'dict[str, Any]') -> 'int
10651073
Returns:
10661074
Processed field value.
10671075
1076+
Raises:
1077+
FieldValueError: If ``value`` is a port outside this field's width,
1078+
i.e. ``0``-``65535`` for the two-octet TCP, UDP and SCTP
1079+
ports.
1080+
1081+
Notes:
1082+
:meth:`NumberField.pre_process` masks a value to the field's width
1083+
rather than range-checking it, so without this check a schema built
1084+
directly would write port ``70000`` as ``0x1170`` and ``-1`` as
1085+
``0xffff``. A port is a whole field with no bits to carry outside
1086+
its width, so the check costs no wire value its round trip: every
1087+
port :meth:`post_process` can return is in range. The bound is the
1088+
one :meth:`post_process` tests. See GitHub issue :issue:`2314`.
1089+
10681090
"""
10691091
# NOTE: imported here rather than at module level, as
10701092
# :mod:`pcapkit.const` itself imports :mod:`pcapkit.corekit`; and tested
@@ -1073,6 +1095,11 @@ def pre_process(self, value: 'int | AppType', packet: 'dict[str, Any]') -> 'int
10731095

10741096
if isinstance(value, AppType):
10751097
value = value.port
1098+
if isinstance(value, int) and not 0 <= value < (1 << (8 * self.length)):
1099+
raise FieldValueError(
1100+
f'Field {self.name} has invalid value: port {value!r} is outside '
1101+
f'0-{(1 << (8 * self.length)) - 1}.'
1102+
)
10761103
return super().pre_process(value, packet)
10771104

10781105
def post_process(self, value: 'int | bytes', packet: 'dict[str, Any]') -> 'AppType':

‎pcapkit/protocols/schema/schema.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,19 @@ def __new__(cls, name: 'str', bases: 'tuple[type, ...]', attrs: 'dict[str, Any]'
370370

371371

372372
class Schema(Mapping[str, _VT], Generic[_VT], metaclass=SchemaMeta):
373-
"""Schema for protocol headers."""
373+
"""Schema for protocol headers.
374+
375+
Note:
376+
Building a schema directly does not range-check its field values. A
377+
:class:`~pcapkit.corekit.fields.numbers.NumberField` masks an
378+
out-of-range integer to its width on packing, so e.g. ``70000`` in a
379+
two-octet field packs as ``0x1170``. The range checks live in each
380+
protocol's :meth:`~pcapkit.protocols.protocol.Protocol.make`, and in a
381+
field whose values have a range of their own, such as
382+
:class:`~pcapkit.corekit.fields.numbers.PortEnumField`. See GitHub issue
383+
:issue:`2314`.
384+
385+
"""
374386

375387
if TYPE_CHECKING:
376388
#: Mapping of name conflicts with builtin methods (original names to
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# -*- coding: utf-8 -*-
2+
"""A TCP or UDP schema built directly rejects a port outside ``0``-``65535``.
3+
4+
GitHub issue #2314. :meth:`~pcapkit.corekit.fields.numbers.NumberField.pre_process`
5+
masks a value to the field's width, which is the documented schema contract
6+
(#1488), so ``Schema_UDP(srcport=70000, ...)`` packed ``0x1170`` with no error.
7+
The owner ruled that the masking stays and that the ports get their range check
8+
from :class:`~pcapkit.corekit.fields.numbers.PortEnumField`, the field the
9+
schemas carry them on. These tests pin that an out-of-range port is rejected on
10+
both ports of both schemas, and that the boundary ports still close byte-exact.
11+
12+
"""
13+
import unittest
14+
from typing import TYPE_CHECKING
15+
16+
from tests._support import reimport_once_per_class
17+
18+
if TYPE_CHECKING:
19+
from typing import Any
20+
21+
#: Test tier (#1958): a hand-picked round trip over the ``int`` boundaries of a
22+
#: two-octet field.
23+
__tier__ = 'ALL'
24+
25+
#: Ports the issue measured masking, one past each end and well past the top.
26+
OUT_OF_RANGE = (-1, 65536, 70000)
27+
28+
#: The two ends of a two-octet port.
29+
BOUNDARIES = (0, 65535)
30+
31+
32+
class SchemaPortRangeTests(unittest.TestCase):
33+
"""Out-of-range ports, and the boundary round trip, on the TCP and UDP schemas."""
34+
35+
def setUp(self) -> None:
36+
reimport_once_per_class(self)
37+
38+
@staticmethod
39+
def _udp(**ports: 'int') -> 'Any':
40+
from pcapkit.protocols.schema.transport.udp import UDP
41+
42+
values = {'srcport': 1024, 'dstport': 53, 'len': 8, 'checksum': b'\x00\x00', 'payload': b''}
43+
values.update(ports)
44+
return UDP(**values)
45+
46+
@staticmethod
47+
def _tcp(**ports: 'int') -> 'Any':
48+
from pcapkit.protocols.schema.transport.tcp import TCP
49+
50+
flags = dict.fromkeys(('cwr', 'ece', 'urg', 'ack', 'psh', 'rst', 'syn', 'fin'), 0)
51+
values = {'srcport': 1024, 'dstport': 80, 'seq': 0, 'ack': 0,
52+
'offset': {'offset': 5, 'reserved': 0, 'ns': 0}, 'flags': flags,
53+
'window': 0, 'checksum': b'\x00\x00', 'urgent': 0, 'options': [], 'payload': b''}
54+
values.update(ports)
55+
return TCP(**values)
56+
57+
def test_an_out_of_range_port_is_rejected_on_packing(self) -> None:
58+
from pcapkit.utilities.exceptions import FieldValueError
59+
60+
for name, build in (('UDP', self._udp), ('TCP', self._tcp)):
61+
for field in ('srcport', 'dstport'):
62+
for port in OUT_OF_RANGE:
63+
with self.subTest(schema=name, field=field, port=port):
64+
with self.assertRaisesRegex(FieldValueError, rf'port {port} is outside 0-65535'):
65+
build(**{field: port}).pack()
66+
67+
def test_the_boundary_ports_round_trip_byte_exact(self) -> None:
68+
from pcapkit.protocols.schema.transport.tcp import TCP
69+
from pcapkit.protocols.schema.transport.udp import UDP
70+
71+
for name, schema, build in (('UDP', UDP, self._udp), ('TCP', TCP, self._tcp)):
72+
for srcport in BOUNDARIES:
73+
for dstport in BOUNDARIES:
74+
with self.subTest(schema=name, srcport=srcport, dstport=dstport):
75+
octets = build(srcport=srcport, dstport=dstport).pack()
76+
self.assertEqual(octets[:4], srcport.to_bytes(2, 'big') + dstport.to_bytes(2, 'big'))
77+
parsed = schema.unpack(octets)
78+
self.assertEqual((parsed.srcport.port, parsed.dstport.port), (srcport, dstport))
79+
self.assertEqual(parsed.pack(), octets)
80+
81+
82+
if __name__ == '__main__':
83+
unittest.main()

0 commit comments

Comments
 (0)