Skip to content

Commit e115868

Browse files
committed
fix(ipv4,tcp)!: a header length declared past the data zero-fills on rebuild; TS make() rejects string address keys (#1402, #1404)
- IPv4.read() and TCP.read() raise ProtocolError when ihl / Data Offset declares more header than the data holds, so the parent keeps the octets as a Raw payload and rebuilds them byte for byte (#1404). - IPv4._make_opt_ts() converts timestamp address keys with parse_ip_address(version=4) instead of int(), so a dotted-quad string works like an IPv4Address and a bool raises FieldValueError (#1402). - Tests that pinned the zero-filling parse now pin the refusal, and keep #431's end-of-option-list loop pinned at the schema level. Closes #1402 Closes #1404
1 parent b9660b4 commit e115868

6 files changed

Lines changed: 259 additions & 44 deletions

File tree

‎pcapkit/protocols/internet/ipv4.py‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
from pcapkit.const.ipv4.tos_thr import ToSThroughput as Enum_ToSThroughput
5757
from pcapkit.const.ipv4.ts_flag import TSFlag as Enum_TSFlag
5858
from pcapkit.const.reg.transtype import TransType as Enum_TransType
59+
from pcapkit.corekit.fields.ipaddress import parse_ip_address
5960
from pcapkit.corekit.multidict import OrderedMultiDict
6061
from pcapkit.protocols.data.internet.ipv4 import EOOLOption as Data_EOOLOption
6162
from pcapkit.protocols.data.internet.ipv4 import ESECOption as Data_ESECOption
@@ -283,6 +284,10 @@ def read(self, length: 'Optional[int]' = None, *, # pylint: disable=unused-argu
283284
Returns:
284285
Parsed packet data.
285286
287+
Raises:
288+
ProtocolError: If the version is not 4, or if ``ihl`` declares
289+
more header than the data holds.
290+
286291
"""
287292
if length is None:
288293
length = len(self)
@@ -316,6 +321,13 @@ def read(self, length: 'Optional[int]' = None, *, # pylint: disable=unused-argu
316321
dst=schema.dst,
317322
)
318323

324+
# NOTE: An ``ihl`` declaring more header than was captured leaves the
325+
# missing octets to read as zeros, which ``from_data`` then rebuilds;
326+
# rejecting it keeps the octets as captured inside the parent (:issue:`1404`).
327+
if len(self) < ipv4.hdr_len:
328+
raise ProtocolError(f'{self.alias}: header length {ipv4.hdr_len} runs past the end of '
329+
f'the data ({len(self)} octets)')
330+
319331
_optl = ipv4.hdr_len - 20
320332
if _optl:
321333
options = self._read_ipv4_options(_optl)
@@ -1606,7 +1618,7 @@ def _make_opt_lsr(self, kind: 'Enum_OptionNumber', option: 'Optional[Data_LSROpt
16061618
def _make_opt_ts(self, kind: 'Enum_OptionNumber', option: 'Optional[Data_TSOption]' = None, *,
16071619
counts: 'int' = 5,
16081620
overflow: 'int' = 0,
1609-
timestamp: 'Optional[list[int | timedelta] | dict[IPv4Address, int | timedelta]]' = None,
1621+
timestamp: 'Optional[list[int | timedelta] | dict[IPv4Address | str | int, int | timedelta]]' = None,
16101622
remaining: 'Optional[list[int]]' = None,
16111623
**kwargs: 'Any') -> 'Schema_TSOption':
16121624
"""Make IPv4 Timestamp (``TS``) option.
@@ -1615,14 +1627,21 @@ def _make_opt_ts(self, kind: 'Enum_OptionNumber', option: 'Optional[Data_TSOptio
16151627
kind: option type code
16161628
option: option data
16171629
counts: maximum number of timestamps to record
1618-
timestamp: list of timestamps, i.e. the slots before the pointer
1630+
timestamp: list of timestamps, i.e. the slots before the pointer, or
1631+
a mapping of the addresses to their timestamps; an address may
1632+
be anything :func:`~pcapkit.corekit.fields.ipaddress.parse_ip_address`
1633+
accepts for IPv4
16191634
remaining: raw 32-bit words for the slots at or beyond the pointer;
16201635
the slots left over up to ``counts`` are zero
16211636
**kwargs: arbitrary keyword arguments
16221637
16231638
Returns:
16241639
Constructed option schema.
16251640
1641+
Raises:
1642+
FieldValueError: If an address is a :obj:`bool` or is not a valid
1643+
IPv4 address.
1644+
16261645
"""
16271646
if option is not None:
16281647
ts_list = [] # type: list[int]
@@ -1638,7 +1657,8 @@ def _make_opt_ts(self, kind: 'Enum_OptionNumber', option: 'Optional[Data_TSOptio
16381657
ts_list.append(ts)
16391658
else:
16401659
for ip, ts in option.timestamp.items(True):
1641-
ts_list.append(int(ip))
1660+
ts_list.append(int(parse_ip_address(ip, f'{self.alias}: [OptNo {kind}] timestamp address',
1661+
version=4)))
16421662
if not isinstance(ts, int):
16431663
ts = ts // datetime.timedelta(milliseconds=1)
16441664
if ts.bit_length() > 31:
@@ -1676,12 +1696,13 @@ def _make_opt_ts(self, kind: 'Enum_OptionNumber', option: 'Optional[Data_TSOptio
16761696
counts = min(4, counts) # 4 is the maximum number of timestamps
16771697
length = 4 + counts * 8
16781698

1679-
for index, (ip, ts) in enumerate(timestamp.items()):
1699+
for index, (addr, ts) in enumerate(timestamp.items()):
16801700
if index >= counts:
16811701
warn(f'{self.alias}: [OptNo {kind}] too many timestamps: {len(timestamp)}', ProtocolWarning)
16821702
break
16831703

1684-
ts_list.append(int(ip))
1704+
ts_list.append(int(parse_ip_address(addr, f'{self.alias}: [OptNo {kind}] timestamp address',
1705+
version=4)))
16851706
if not isinstance(ts, int):
16861707
ts = ts // datetime.timedelta(milliseconds=1)
16871708
if ts.bit_length() > 31:

‎pcapkit/protocols/transport/tcp.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,10 @@ def read(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_TCP':
459459
Returns:
460460
Parsed packet data.
461461
462+
Raises:
463+
ProtocolError: If the Data Offset declares more header than the
464+
data holds.
465+
462466
"""
463467
if length is None:
464468
length = len(self)
@@ -508,6 +512,13 @@ def read(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_TCP':
508512
'connection': self._flags,
509513
})
510514

515+
# NOTE: A Data Offset declaring more header than was captured leaves the
516+
# missing octets to read as zeros, which ``from_data`` then rebuilds;
517+
# rejecting it keeps the octets as captured inside the parent (:issue:`1404`).
518+
if len(self) < tcp.hdr_len:
519+
raise ProtocolError(f'{self.alias}: header length {tcp.hdr_len} runs past the end of '
520+
f'the data ({len(self)} octets)')
521+
511522
_optl = tcp.hdr_len - 20
512523
if _optl:
513524
# NOTE: the octets after an End of Option List option are kept as

‎tests/protocols/internet/test_ipv4_unit.py‎

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1981,38 +1981,44 @@ def test_ipv4_schema_helpers_and_post_process_branches(self) -> None:
19811981
self.assertEqual(tuple(unknown.timestamp), (1,))
19821982
warn.assert_called_once()
19831983

1984-
def test_an_option_area_longer_than_the_datagram_still_parses(self) -> None:
1985-
"""An ``ihl`` promising more options than are there is tolerated.
1984+
def test_an_option_area_longer_than_the_datagram_is_refused(self) -> None:
1985+
"""An ``ihl`` promising more options than are there is refused. C.f. #431, #1404.
19861986
19871987
The header below sets ``ihl`` to 10 -- a 20-octet option area -- and stops
1988-
after the fixed 20 octets, so there are no option octets at all. Reading
1989-
past them yields ``b''``, which decodes the option number as 0, and 0 is
1990-
IPv4's end-of-option-list, so the option loop breaks there and reports the
1991-
whole area as padding. That is how a datagram cut short by the snapshot
1992-
length parses at all, and it is why :meth:`OptionField.unpack
1988+
after the fixed 20 octets, so there are no option octets at all. Read by
1989+
the schema, the option area yields ``b''``, which decodes the option
1990+
number as 0, and 0 is IPv4's end-of-option-list, so the option loop breaks
1991+
there. That is why :meth:`OptionField.unpack
19931992
<pcapkit.corekit.fields.collections.OptionField.unpack>` checks each
19941993
option's progress *after* its end-of-option-list break rather than before:
19951994
checking first turns every such header into an error. C.f. #431.
19961995
1996+
:class:`~pcapkit.protocols.internet.ipv4.IPv4` itself refuses the header
1997+
with :exc:`~pcapkit.utilities.exceptions.ProtocolError`, since the 20
1998+
missing octets would otherwise be rebuilt as zeros (#1404).
1999+
19972000
"""
19982001
from pcapkit.const.ipv4.option_number import OptionNumber
19992002
from pcapkit.protocols.internet.ipv4 import IPv4
2003+
from pcapkit.protocols.schema.internet.ipv4 import IPv4 as Schema_IPv4
2004+
from pcapkit.utilities.exceptions import ProtocolError
20002005
from tests._support import time_limit
20012006

20022007
raw = bytes.fromhex('4a00001800010000400600000a0000010a000002')
20032008
with time_limit():
2004-
proto = IPv4(raw, len(raw))
2005-
2006-
self.assertEqual(proto.info.hdr_len, 40)
2009+
schema = Schema_IPv4.unpack(raw)
20072010
self.assertEqual(
2008-
[(code, opt.length) for code, opt in proto.info.options.items(multi=True)],
2011+
[(opt.type, opt.length) for opt in schema.options],
20092012
[(OptionNumber.EOOL, 1)],
20102013
)
20112014

2015+
with self.assertRaisesRegex(ProtocolError, 'header length 40 runs past the end of the data'):
2016+
IPv4(raw, len(raw))
2017+
20122018
def test_a_truncated_option_still_parses_its_declared_length(self) -> None:
20132019
"""A capture cut short mid-option is refused alone, and kept as captured in a frame. C.f. #431, #572, #1325.
20142020
2015-
:meth:`test_an_option_area_longer_than_the_datagram_still_parses` above
2021+
:meth:`test_an_option_area_longer_than_the_datagram_is_refused` above
20162022
pins the *empty*-tail half of the #431 accommodation: an option area
20172023
that runs out before it starts. This is the other half -- an option
20182024
that *does* start, declares more data than the capture holds, and runs
@@ -2021,12 +2027,13 @@ def test_a_truncated_option_still_parses_its_declared_length(self) -> None:
20212027
The header below sets ``ihl`` to 9 -- 16 declared octets of options --
20222028
for an unassigned option (code 31) declaring ``length=12``, with only
20232029
6 of its 10 data octets behind it. Those 4 missing octets used to be
2024-
read as zeros and rebuilt as if captured. :meth:`OptionField.unpack
2025-
<pcapkit.corekit.fields.collections.OptionField.unpack>` now refuses
2026-
the option with :exc:`~pcapkit.utilities.exceptions.ProtocolError`
2027-
instead (#1325). Inside a frame the datagram is kept as the octets
2028-
captured, a :class:`~pcapkit.protocols.misc.raw.Raw` payload carrying
2029-
that error, and rebuilds byte for byte.
2030+
read as zeros and rebuilt as if captured. The datagram is now refused
2031+
with :exc:`~pcapkit.utilities.exceptions.ProtocolError` instead -- by
2032+
the header-length check (#1404), ahead of :meth:`OptionField.unpack
2033+
<pcapkit.corekit.fields.collections.OptionField.unpack>`'s own (#1325).
2034+
Inside a frame the datagram is kept as the octets captured, a
2035+
:class:`~pcapkit.protocols.misc.raw.Raw` payload carrying that error,
2036+
and rebuilds byte for byte.
20302037
20312038
"""
20322039
from pcapkit.const.ipv4.option_number import OptionNumber

‎tests/protocols/test_declared_length_overrun_unit.py‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@
1414
the parent rebuilds byte for byte.
1515
1616
An option that begins at the end of the data reads nothing at all, and is still
17-
left to the end-of-option-list handling an over-long option area relies on.
17+
left to the end-of-option-list handling an over-long option area relies on. An
18+
IPv4 or TCP header declaring an option area past the data is rejected before its
19+
options are read (GitHub issue #1404), and its parent likewise keeps it as
20+
captured.
1821
1922
Every case builds its own octets in memory and reads no capture.
2023
@@ -158,16 +161,25 @@ def test_an_overrunning_layer_is_kept_as_captured_by_its_parent(self) -> None:
158161
self.assertEqual(parsed.payload.data, OVERRUNS[case][2])
159162
self.assertEqual(protocol.from_data(parsed.info).data, frame)
160163

161-
def test_an_option_area_declared_past_the_data_still_ends_at_eool(self) -> None:
164+
def test_an_option_area_declared_past_the_data_is_kept_as_captured(self) -> None:
162165
from pcapkit.protocols.internet.ipv4 import IPv4
166+
from pcapkit.protocols.link.ethernet import Ethernet
167+
from pcapkit.protocols.misc.raw import Raw
168+
from pcapkit.utilities.exceptions import ProtocolError
163169

164-
# ``ihl`` declares 20 octets of options with none present: the first
165-
# option begins at the end of the data, so it is end-of-option-list.
170+
# ``ihl`` declares 20 octets of options with none present: reading the
171+
# option area would zero-fill all 20 of them on rebuild (issue #1404).
166172
data = bytes.fromhex('4a00001800010000400600000a0000010a000002')
173+
with self.assertRaisesRegex(ProtocolError, 'runs past the end of the data'):
174+
IPv4(data, len(data))
175+
176+
frame = bytes.fromhex('0123456789ab fedcba987654 0800') + data
167177
with warnings.catch_warnings():
168178
warnings.simplefilter('ignore')
169-
parsed = IPv4(data, len(data))
170-
self.assertEqual(parsed.info.src.compressed, '10.0.0.1')
179+
parsed = Ethernet(frame, len(frame))
180+
self.assertIsInstance(parsed.payload, Raw)
181+
self.assertEqual(parsed.payload.data, data)
182+
self.assertEqual(Ethernet.from_data(parsed.info).data, frame)
171183

172184

173185
if __name__ == '__main__':
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
# -*- coding: utf-8 -*-
2+
"""A header length declared past the data, and TS address keys given as strings.
3+
4+
GitHub issue #1404: an IPv4 ``ihl`` or a TCP Data Offset declaring more header
5+
than the data holds read the missing octets as zeros, and ``from_data`` rebuilt
6+
them -- 34 octets in and 38 out for an Ethernet frame whose IPv4 ``ihl`` is 6
7+
with only 20 header octets present. Such a header now raises
8+
:exc:`~pcapkit.utilities.exceptions.ProtocolError`, so its parent keeps the
9+
octets as a :class:`~pcapkit.protocols.misc.raw.Raw` payload and rebuilds them
10+
byte for byte.
11+
12+
GitHub issue #1402: ``IPv4.make()`` called :func:`int` on each key of a TS
13+
option's ``timestamp`` mapping, so a dotted-quad string key raised a bare
14+
:exc:`ValueError`. The keys are now converted as addresses, and a :obj:`bool`
15+
key is rejected with :exc:`~pcapkit.utilities.exceptions.FieldValueError`.
16+
17+
Every case builds its own octets in memory and reads no capture.
18+
19+
"""
20+
21+
import struct
22+
import unittest
23+
import warnings
24+
25+
from tests._support import reimport_once_per_class
26+
27+
_ETH = bytes.fromhex('0123456789ab fedcba987654 0800')
28+
29+
30+
def _ipv4(ihl: int, proto: int, body: bytes) -> bytes:
31+
"""An IPv4 header declaring ``ihl``, followed by ``body``."""
32+
return (bytes([0x40 | ihl, 0]) + struct.pack('>H', 20 + len(body))
33+
+ bytes.fromhex('00010000 40') + bytes([proto]) + bytes(2)
34+
+ bytes.fromhex('0a000001 0a000002') + body)
35+
36+
37+
def _tcp(offset: int, opts: bytes = b'') -> bytes:
38+
"""A TCP header declaring ``offset``, followed by ``opts``."""
39+
return struct.pack('>HHIIBBHHH', 1, 2, 0, 0, offset << 4, 0x10, 0, 0, 0) + opts
40+
41+
42+
#: Layers whose declared header length runs past the data: (module, class, octets).
43+
SHORT = {
44+
# issue #1404: options declared, none present
45+
'IPv4 ihl=6, 20 octets': ('pcapkit.protocols.internet.ipv4', 'IPv4', _ipv4(6, 253, b'')),
46+
'IPv4 ihl=7, 24 octets': ('pcapkit.protocols.internet.ipv4', 'IPv4', _ipv4(7, 253, bytes.fromhex('01010101'))),
47+
'TCP offset=6, 20 octets': ('pcapkit.protocols.transport.tcp', 'TCP', _tcp(6)),
48+
'TCP offset=10, 28 octets': ('pcapkit.protocols.transport.tcp', 'TCP', _tcp(10, bytes.fromhex('0101010101010101'))),
49+
}
50+
51+
#: Each short layer inside its parent: (parent module, parent class, frame).
52+
IN_PARENT = {
53+
'IPv4 ihl=6, 20 octets': ('pcapkit.protocols.link.ethernet', 'Ethernet', _ETH + SHORT['IPv4 ihl=6, 20 octets'][2]),
54+
'IPv4 ihl=7, 24 octets': ('pcapkit.protocols.link.ethernet', 'Ethernet', _ETH + SHORT['IPv4 ihl=7, 24 octets'][2]),
55+
'TCP offset=6, 20 octets': ('pcapkit.protocols.internet.ipv4', 'IPv4',
56+
_ipv4(5, 6, SHORT['TCP offset=6, 20 octets'][2])),
57+
'TCP offset=10, 28 octets': ('pcapkit.protocols.internet.ipv4', 'IPv4',
58+
_ipv4(5, 6, SHORT['TCP offset=10, 28 octets'][2])),
59+
}
60+
61+
62+
class TestHeaderLengthOverrun(unittest.TestCase):
63+
"""Pin the rejection of a header length running past the end of its data."""
64+
65+
def setUp(self) -> None:
66+
reimport_once_per_class(self)
67+
68+
@staticmethod
69+
def _protocol(module: str, name: str) -> type:
70+
import importlib
71+
72+
return getattr(importlib.import_module(module), name)
73+
74+
def test_a_short_header_raises_protocol_error(self) -> None:
75+
from pcapkit.utilities.exceptions import ProtocolError
76+
77+
for case, (module, name, data) in SHORT.items():
78+
with self.subTest(case=case):
79+
protocol = self._protocol(module, name)
80+
with warnings.catch_warnings():
81+
warnings.simplefilter('ignore')
82+
with self.assertRaisesRegex(ProtocolError, 'header length .* runs past the end of the data'):
83+
protocol(data, len(data))
84+
85+
def test_a_short_header_is_kept_as_captured_by_its_parent(self) -> None:
86+
from pcapkit.protocols.misc.raw import Raw
87+
88+
for case, (module, name, frame) in IN_PARENT.items():
89+
with self.subTest(case=case):
90+
protocol = self._protocol(module, name)
91+
with warnings.catch_warnings():
92+
warnings.simplefilter('ignore')
93+
parsed = protocol(frame, len(frame))
94+
self.assertIsInstance(parsed.payload, Raw)
95+
self.assertEqual(parsed.payload.data, SHORT[case][2])
96+
self.assertEqual(protocol.from_data(parsed.info).data, frame)
97+
98+
def test_a_complete_header_still_rebuilds_byte_for_byte(self) -> None:
99+
# the same option areas, every declared octet present
100+
for module, name, data in (('pcapkit.protocols.internet.ipv4', 'IPv4', _ipv4(6, 253, bytes(4))),
101+
('pcapkit.protocols.transport.tcp', 'TCP', _tcp(6, bytes(4)))):
102+
with self.subTest(name=name):
103+
protocol = self._protocol(module, name)
104+
parsed = protocol(data, len(data))
105+
self.assertEqual(protocol.from_data(parsed.info).data, data)
106+
107+
108+
class TestTimestampAddressKeys(unittest.TestCase):
109+
"""Pin the conversion of a TS option's address keys on ``make()``."""
110+
111+
def setUp(self) -> None:
112+
reimport_once_per_class(self)
113+
114+
def _make(self, key: object) -> bytes:
115+
from datetime import timedelta
116+
117+
from pcapkit.const.ipv4.option_number import OptionNumber
118+
from pcapkit.protocols.internet.ipv4 import IPv4
119+
120+
return IPv4(options=[(OptionNumber.TS, {'timestamp': {key: timedelta(milliseconds=1)}})],
121+
protocol=253).data
122+
123+
def test_a_string_key_builds_like_an_address_key(self) -> None:
124+
from ipaddress import IPv4Address
125+
126+
from pcapkit.protocols.internet.ipv4 import IPv4
127+
128+
expected = self._make(IPv4Address('1.2.3.4'))
129+
data = self._make('1.2.3.4')
130+
self.assertEqual(data, expected)
131+
self.assertEqual(data[20:32], bytes.fromhex('44240d01 01020304 00000001'))
132+
self.assertEqual(IPv4(data, len(data)).data, data)
133+
134+
def test_a_string_key_in_parsed_data_rebuilds(self) -> None:
135+
from datetime import timedelta
136+
from ipaddress import IPv4Address
137+
138+
from pcapkit.corekit.multidict import OrderedMultiDict
139+
from pcapkit.protocols.internet.ipv4 import IPv4
140+
141+
data = self._make(IPv4Address('1.2.3.4'))
142+
parsed = IPv4(data, len(data))
143+
option = next(iter(parsed.info.options.values()))
144+
option.__update__(timestamp=OrderedMultiDict([('1.2.3.4', timedelta(milliseconds=1))]))
145+
self.assertEqual(IPv4.from_data(parsed.info).data, data)
146+
147+
def test_a_bool_key_raises_field_value_error(self) -> None:
148+
from pcapkit.utilities.exceptions import FieldValueError
149+
150+
with self.assertRaisesRegex(FieldValueError, 'timestamp address: must not be a bool'):
151+
self._make(True)
152+
153+
def test_an_invalid_key_raises_field_value_error(self) -> None:
154+
from pcapkit.utilities.exceptions import FieldValueError
155+
156+
with self.assertRaisesRegex(FieldValueError, 'timestamp address'):
157+
self._make('1.2.3')
158+
159+
160+
if __name__ == '__main__':
161+
unittest.main()

0 commit comments

Comments
 (0)