Skip to content

Commit a176c71

Browse files
authored
fix(link)!: L2TPv2 drops the reserved flag bits on rebuild, and make() drops a lone ns or nr (#1226)
1 parent 4aca920 commit a176c71

5 files changed

Lines changed: 136 additions & 6 deletions

File tree

‎pcapkit/protocols/data/link/l2tp.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,14 @@ class Flags(Data):
2929
offset: 'bool'
3030
#: Priority.
3131
prio: 'bool'
32+
#: Reserved bits 2, 3, 5 and 8-11 of the flags word, in their on-wire
33+
#: positions (i.e. masked by ``0x34F0``). :rfc:`2661` §3.1 has them "set
34+
#: to 0 on outgoing messages and ignored on incoming messages"; they are
35+
#: carried verbatim so that a rebuild reproduces the word as it arrived.
36+
reserved: 'int'
3237

3338
if TYPE_CHECKING:
34-
def __init__(self, type: 'Type', len: 'bool', seq: 'bool', offset: 'bool', prio: 'bool') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,redefined-builtin,multiple-statements
39+
def __init__(self, type: 'Type', len: 'bool', seq: 'bool', offset: 'bool', prio: 'bool', reserved: 'int') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,redefined-builtin,multiple-statements,line-too-long
3540

3641

3742
@info_final

‎pcapkit/protocols/link/l2tpv2.py‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ def read(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_L2TP':
206206
seq=bool(_flag['seq']),
207207
offset=bool(_flag['offset']),
208208
prio=bool(_flag['prio']),
209+
reserved=(_flag['reserved_1'] << 12) | (_flag['reserved_2'] << 10) | (_flag['reserved_3'] << 4),
209210
)
210211

211212
_size = schema.offset if flags.offset else 0
@@ -245,6 +246,7 @@ def make(self,
245246
type_namespace: 'Optional[dict[str, int] | dict[int, str] | Type[StdlibEnum] | Type[AenumEnum]]' = None, # pylint: disable=line-too-long
246247
type_reversed: 'bool' = False,
247248
priority: 'bool' = False,
249+
reserved: 'int' = 0,
248250
total_length: 'Optional[int]' = None,
249251
length_flag: 'Optional[bool]' = None,
250252
tunnel_id: 'int' = 0,
@@ -264,6 +266,8 @@ def make(self,
264266
type_namespace: Namespace of type.
265267
type_reversed: Reversed namespace of type.
266268
priority: Priority flag.
269+
reserved: Reserved bits of the flags word, in their on-wire
270+
positions (bits 2, 3, 5 and 8-11, i.e. within ``0x34F0``).
267271
total_length: Length of the datagram, header included, written as
268272
given; the real header-plus-payload length when :data:`None`
269273
and the Length field is present.
@@ -286,12 +290,21 @@ def make(self,
286290
287291
Raises:
288292
ProtocolError: If ``total_length`` is given with ``length_flag``
289-
set to :data:`False`.
293+
set to :data:`False`, if only one of ``ns`` and ``nr`` is
294+
given, or if ``reserved`` sets a bit outside ``0x34F0``.
290295
291296
"""
292297
type_ = self._make_index(type, type_default, namespace=type_namespace,
293298
reversed=type_reversed, pack=False)
294-
seq = ns is not None and nr is not None
299+
# NOTE: :rfc:`2661` §3.1 makes ``S`` mark the presence of *both* Ns and
300+
# Nr, so a header cannot carry one without the other. Refuse a lone
301+
# value rather than drop it, or invent the other on the wire.
302+
if (ns is None) != (nr is None):
303+
raise ProtocolError(f'{self.alias}: ns and nr must be given together')
304+
seq = ns is not None
305+
306+
if reserved & ~0x34F0:
307+
raise ProtocolError(f'{self.alias}: reserved bits outside 0x34F0: {reserved:#06x}')
295308

296309
if length_flag is None:
297310
length_flag = total_length is not None or type_ == Enum_Type.Control
@@ -312,6 +325,9 @@ def make(self,
312325
'seq': seq,
313326
'offset': offset is not None,
314327
'prio': priority,
328+
'reserved_1': (reserved >> 12) & 0b11,
329+
'reserved_2': (reserved >> 10) & 0b1,
330+
'reserved_3': (reserved >> 4) & 0b1111,
315331
'version': version,
316332
},
317333
length=total_length,
@@ -391,6 +407,7 @@ def _make_data(cls, data: 'Data_L2TP') -> 'dict[str, Any]': # type: ignore[over
391407
return {
392408
'type': data.flags.type,
393409
'priority': data.flags.prio,
410+
'reserved': data.flags.reserved,
394411
'version': data.version,
395412
# NOTE: Passed as ``total_length`` since ``length`` is the parse
396413
# length :class:`~pcapkit.protocols.protocol.ProtocolBase` takes, so

‎pcapkit/protocols/schema/link/l2tp.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ class FlagsType(TypedDict):
3333
offset: int
3434
#: Priority of L2TP packet.
3535
prio: int
36+
#: Reserved bits 2 and 3 of L2TP packet.
37+
reserved_1: int
38+
#: Reserved bit 5 of L2TP packet.
39+
reserved_2: int
40+
#: Reserved bits 8 to 11 of L2TP packet.
41+
reserved_3: int
3642
#: Version of L2TP packet.
3743
version: Literal[2]
3844

@@ -45,9 +51,12 @@ class L2TP(Schema):
4551
flags: 'FlagsType' = BitField(length=2, namespace={
4652
'type': (0, 1),
4753
'len': (1, 1),
54+
'reserved_1': (2, 2),
4855
'seq': (4, 1),
56+
'reserved_2': (5, 1),
4957
'offset': (6, 1),
5058
'prio': (7, 1),
59+
'reserved_3': (8, 4),
5160
'version': (12, 4),
5261
})
5362
#: Length of L2TP packet.
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# -*- coding: utf-8 -*-
2+
"""L2TPv2 keeps its reserved flag bits, and never drops a lone Ns or Nr.
3+
4+
GitHub issue #1207: the flags :class:`~pcapkit.corekit.fields.strings.BitField`
5+
declared no reserved subfields, so bits 2, 3, 5 and 8-11 were lost on a
6+
``from_data`` rebuild: ``200200010002ff03002145000000`` came back as
7+
``000200010002ff03002145000000``.
8+
9+
GitHub issue #1208: :meth:`~pcapkit.protocols.link.l2tpv2.L2TPv2.make` set ``S``
10+
only when both ``ns`` and ``nr`` were given, so ``L2TPv2(ns=7)`` silently wrote
11+
neither. :rfc:`2661` §3.1 has ``S`` mark the presence of both fields together,
12+
so a lone value is now refused with
13+
:class:`~pcapkit.utilities.exceptions.ProtocolError`.
14+
15+
Every case builds its own octets in memory and reads no capture.
16+
17+
:class:`L2TPv2` is imported inside each test, after
18+
:func:`~tests._support.reimport_once_per_class`, not at module load, for the
19+
reason :mod:`tests.protocols.link.test_ethernet_mac_roundtrip_unit` gives.
20+
21+
"""
22+
23+
import unittest
24+
25+
from tests._support import reimport_once_per_class
26+
27+
#: A PPP frame header and the first IPv4 octet, as the L2TPv2 payload.
28+
PAYLOAD = bytes.fromhex('ff03002145')
29+
30+
#: Each reserved bit group on its own, then all of them at once.
31+
RESERVED_MASKS = (0x2000, 0x1000, 0x0400, 0x00f0, 0x34f0)
32+
33+
34+
class TestL2TPv2RoundTrip(unittest.TestCase):
35+
"""Pin the reserved flag bits and the Ns/Nr pairing."""
36+
37+
def setUp(self) -> None:
38+
reimport_once_per_class(self)
39+
40+
def test_issue_1207_reproduction(self) -> None:
41+
from pcapkit.protocols.link.l2tpv2 import L2TPv2
42+
43+
raw = bytes.fromhex('200200010002ff03002145000000')
44+
parsed = L2TPv2(raw)
45+
self.assertEqual(parsed.info.flags.reserved, 0x2000)
46+
self.assertEqual(L2TPv2.from_data(parsed.info).data, raw)
47+
48+
def test_each_reserved_mask_round_trips(self) -> None:
49+
from pcapkit.protocols.link.l2tpv2 import L2TPv2
50+
51+
for mask in RESERVED_MASKS:
52+
raw = (mask | 0x0002).to_bytes(2, 'big') + bytes.fromhex('00010002') + PAYLOAD
53+
with self.subTest(mask=hex(mask)):
54+
parsed = L2TPv2(raw)
55+
self.assertEqual(parsed.info.flags.reserved, mask)
56+
self.assertEqual(L2TPv2.from_data(parsed.info).data, raw)
57+
58+
def test_reserved_bits_round_trip_inside_udp(self) -> None:
59+
from pcapkit.protocols.transport.udp import UDP
60+
61+
l2tp = bytes.fromhex('34f200010002') + PAYLOAD
62+
raw = (1701).to_bytes(2, 'big') * 2 + (8 + len(l2tp)).to_bytes(2, 'big') + b'\x00\x00' + l2tp
63+
parsed = UDP(raw)
64+
self.assertEqual(parsed.payload.info.flags.reserved, 0x34f0)
65+
self.assertEqual(UDP.from_data(parsed.info).data, raw)
66+
67+
def test_make_writes_reserved_and_refuses_other_bits(self) -> None:
68+
from pcapkit.protocols.link.l2tpv2 import L2TPv2
69+
from pcapkit.utilities.exceptions import ProtocolError
70+
71+
self.assertEqual(L2TPv2(type=0, reserved=0x0400).data[:2], bytes.fromhex('0402'))
72+
self.assertEqual(L2TPv2(type=0).data[:2], bytes.fromhex('0002'))
73+
for bad in (0x0001, 0x0800, 0x8000):
74+
with self.subTest(reserved=hex(bad)):
75+
with self.assertRaises(ProtocolError):
76+
L2TPv2(type=0, reserved=bad)
77+
78+
def test_issue_1208_lone_ns_or_nr_is_refused(self) -> None:
79+
from pcapkit.protocols.link.l2tpv2 import L2TPv2
80+
from pcapkit.utilities.exceptions import ProtocolError
81+
82+
for kwargs in ({'ns': 7}, {'nr': 7}, {'ns': 0}, {'nr': 0}):
83+
with self.subTest(**kwargs):
84+
with self.assertRaises(ProtocolError):
85+
L2TPv2(**kwargs)
86+
87+
def test_ns_and_nr_together_round_trip(self) -> None:
88+
from pcapkit.protocols.link.l2tpv2 import L2TPv2
89+
90+
made = L2TPv2(type=0, ns=7, nr=0)
91+
self.assertEqual(made.data, bytes.fromhex('08020000000000070000'))
92+
self.assertEqual((made.info.ns, made.info.nr), (7, 0))
93+
self.assertEqual(L2TPv2.from_data(made.info).data, made.data)
94+
95+
96+
if __name__ == '__main__':
97+
unittest.main()

‎tests/protocols/link/test_link_unit.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ def test_l2tp_index_is_unsupported_and_make_data_preserves_flags(self) -> None:
348348
from pcapkit.utilities.exceptions import UnsupportedCall
349349

350350
data = DummyData(
351-
flags=DummyData(type=True, len=True, prio=False),
351+
flags=DummyData(type=True, len=True, prio=False, reserved=0),
352352
version=2,
353353
length=32,
354354
tunnelid=3,
@@ -635,7 +635,8 @@ def test_l2tp_properties_read_and_make_variants(self) -> None:
635635
reader = object.__new__(L2TPv2)
636636
reader.__header__ = SchemaL2TP(
637637
flags={'type': Type.Control, 'len': True, 'seq': True, 'offset': True,
638-
'prio': True, 'version': 2},
638+
'prio': True, 'reserved_1': 0, 'reserved_2': 0,
639+
'reserved_3': 0, 'version': 2},
639640
length=24,
640641
tunnel_id=1,
641642
session_id=2,
@@ -658,7 +659,8 @@ def test_l2tp_properties_read_and_make_variants(self) -> None:
658659
reader_no_flags._data = b'\x00' * 14
659660
reader_no_flags.__header__ = SchemaL2TP(
660661
flags={'type': Type.Data, 'len': False, 'seq': False, 'offset': False,
661-
'prio': False, 'version': 2},
662+
'prio': False, 'reserved_1': 0, 'reserved_2': 0,
663+
'reserved_3': 0, 'version': 2},
662664
length=None,
663665
tunnel_id=5,
664666
session_id=6,

0 commit comments

Comments
 (0)