Skip to content

Commit cce4838

Browse files
committed
fix(link): ARP family rebuilds InARP/DRARP, any Ethernet hlen, and a ptype/plen mismatch
- InARP and DRARP pass schema=/data= on their class statements, so they use the ARP schema instead of falling back to Raw (#1204). - PAT_MAC_ADDR accepts any number of colon/dash-separated octets, so a parsed Ethernet header with hlen other than 6 (including 0) rebuilds through its explicit hlen; make() without hlen still requires a 6-octet MAC for htype Ethernet (#1205). - The protocol address is decoded as IPv4/IPv6 only when ptype and its length agree (4/16); otherwise it is kept as hex, and make() packs it as raw octets when plen disagrees with ptype (#1206). New tests/protocols/link/test_arp_roundtrip_unit.py covers ARP, InARP, RARP and DRARP; it fails without the fix. Closes #1204 Closes #1205 Closes #1206
1 parent 630f0a5 commit cce4838

3 files changed

Lines changed: 207 additions & 23 deletions

File tree

‎pcapkit/protocols/application/rarp.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def __index__(cls) -> 'Enum_EtherType': # pylint: disable=invalid-index-returne
9494
return Enum_EtherType.Reverse_Address_Resolution_Protocol # type: ignore[return-value]
9595

9696

97-
class DRARP(RARP):
97+
class DRARP(RARP, schema=Schema_ARP, data=Data_ARP):
9898
"""This class implements Dynamic Reverse Address Resolution Protocol.
9999
100100
Inherits RARP's bases unchanged, so ``layer == 'Application'`` here too --

‎pcapkit/protocols/link/arp.py‎

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,8 @@
7272
# check Python version
7373
py38 = ((version_info := sys.version_info).major >= 3 and version_info.minor >= 8)
7474

75-
# Ethernet address pattern
76-
PAT_MAC_ADDR = re.compile(rb'(?i)(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}')
75+
# Ethernet address pattern, of any number of octets (``hlen`` is not fixed at 6)
76+
PAT_MAC_ADDR = re.compile(rb'(?i)(?:[0-9a-f]{2}(?:[:-][0-9a-f]{2})*)?')
7777

7878

7979
class ARP(Link[Data_ARP, Schema_ARP],
@@ -238,8 +238,8 @@ def make(self, *,
238238
ptype_default: Default value of protocol type.
239239
ptype_namespace: Namespace of protocol type.
240240
ptype_reversed: Reversed flag of protocol type.
241-
hlen: Hardware address length; derived from the packed ``sha`` if
242-
not given.
241+
hlen: Hardware address length; if not given, ``6`` when ``htype``
242+
is Ethernet, otherwise derived from the packed ``sha``.
243243
plen: Protocol address length; derived from the packed ``spa`` if
244244
not given.
245245
oper: Operation.
@@ -258,7 +258,9 @@ def make(self, *,
258258
259259
Raises:
260260
ProtocolError: If a packed hardware address is not ``hlen`` octets
261-
long, or a packed protocol address is not ``plen`` octets long.
261+
long (with ``hlen`` not given and ``htype`` Ethernet, not 6
262+
octets long), or a packed protocol address is not ``plen``
263+
octets long.
262264
263265
"""
264266
_htype = self._make_index(htype, htype_default, namespace=htype_namespace,
@@ -269,11 +271,15 @@ def make(self, *,
269271
reversed=oper_reversed, pack=False)
270272

271273
_sha = self._make_addr_resolve(sha, _htype)
272-
_spa = self._make_proto_resolve(spa, _ptype)
274+
_spa = self._make_proto_resolve(spa, _ptype, plen)
273275
_tha = self._make_addr_resolve(tha, _htype)
274-
_tpa = self._make_proto_resolve(tpa, _ptype)
276+
_tpa = self._make_proto_resolve(tpa, _ptype, plen)
275277

276-
_hlen = len(_sha) if hlen is None else hlen
278+
# an Ethernet MAC is 6 octets unless the caller says otherwise
279+
if hlen is None:
280+
_hlen = 6 if _htype == Enum_Hardware.Ethernet else len(_sha)
281+
else:
282+
_hlen = hlen
277283
_plen = len(_spa) if plen is None else plen
278284
for name, addr, size in (('sha', _sha, _hlen), ('tha', _tha, _hlen),
279285
('spa', _spa, _plen), ('tpa', _tpa, _plen)):
@@ -371,16 +377,16 @@ def _read_proto_resolve(self, addr: 'bytes', ptype: 'int') -> 'str | IPv4Address
371377
ptype: Protocol type.
372378
373379
Returns:
374-
Protocol address. If ``ptype`` is ``0x0800`` (IPv4), an
375-
:class:`~ipaddress.IPv4Address`; if ``0x86dd`` (IPv6), an
376-
:class:`~ipaddress.IPv6Address`; otherwise, the address as a hex
377-
:data:`str`.
380+
Protocol address. If ``ptype`` is ``0x0800`` (IPv4) and ``addr`` is
381+
4 octets, an :class:`~ipaddress.IPv4Address`; if ``0x86dd`` (IPv6)
382+
and 16 octets, an :class:`~ipaddress.IPv6Address`; otherwise, the
383+
address as a hex :data:`str`.
378384
379385
"""
380-
if ptype == Enum_EtherType.Internet_Protocol_version_4: # IPv4
381-
return ipaddress.ip_address(addr)
382-
if ptype == Enum_EtherType.Internet_Protocol_version_6: # IPv6
383-
return ipaddress.ip_address(addr)
386+
if ptype == Enum_EtherType.Internet_Protocol_version_4 and len(addr) == 4: # IPv4
387+
return ipaddress.IPv4Address(addr)
388+
if ptype == Enum_EtherType.Internet_Protocol_version_6 and len(addr) == 16: # IPv6
389+
return ipaddress.IPv6Address(addr)
384390
return addr.hex()
385391

386392
def _make_addr_resolve(self, addr: 'str | bytes', htype: 'int') -> 'bytes':
@@ -393,7 +399,8 @@ def _make_addr_resolve(self, addr: 'str | bytes', htype: 'int') -> 'bytes':
393399
Returns:
394400
Hardware address packed as raw octets. If ``htype`` is ``1``, i.e.
395401
MAC address, the ``:``- or ``-``-separated *hex* encoded MAC address
396-
is validated and packed as 6 octets; otherwise, a :data:`str` is
402+
is validated and packed, one octet per group (an empty string packs
403+
as no octets); otherwise, a :data:`str` is
397404
taken as the *hex* encoded address that :meth:`_read_addr_resolve`
398405
returns, and :obj:`bytes` are returned as given.
399406
@@ -415,16 +422,19 @@ def _make_addr_resolve(self, addr: 'str | bytes', htype: 'int') -> 'bytes':
415422
raise ProtocolError(f'Invalid hardware address: {addr!r}') from None
416423
return addr
417424

418-
def _make_proto_resolve(self, addr: 'IPv4Address | IPv6Address | str | bytes', ptype: 'int') -> 'bytes':
425+
def _make_proto_resolve(self, addr: 'IPv4Address | IPv6Address | str | bytes', ptype: 'int',
426+
plen: 'Optional[int]' = None) -> 'bytes':
419427
"""Resolve protocol address according to protocol.
420428
421429
Arguments:
422430
addr: Protocol address.
423431
ptype: Protocol type.
432+
plen: Protocol address length, if given.
424433
425434
Returns:
426435
Packed protocol address. If ``ptype`` is ``0x0800`` (IPv4) or
427-
``0x86dd`` (IPv6), the address is validated and packed to 4 or 16
436+
``0x86dd`` (IPv6), and ``plen`` is either not given or 4 or 16
437+
respectively, the address is validated and packed to 4 or 16
428438
octets; otherwise, a :data:`str` is taken as the *hex* encoded
429439
address that :meth:`_read_proto_resolve` returns, an
430440
:class:`~ipaddress.IPv4Address`/:class:`~ipaddress.IPv6Address` is
@@ -455,10 +465,10 @@ def _make_proto_resolve(self, addr: 'IPv4Address | IPv6Address | str | bytes', p
455465
:exc:`AttributeError`, bool or not.
456466
457467
"""
458-
if ptype == Enum_EtherType.Internet_Protocol_version_4:
468+
if ptype == Enum_EtherType.Internet_Protocol_version_4 and plen in (None, 4):
459469
return cast('IPv4Address', parse_ip_address(
460470
addr, f'{self.__class__.__name__}: invalid protocol address', version=4)).packed
461-
if ptype == Enum_EtherType.Internet_Protocol_version_6:
471+
if ptype == Enum_EtherType.Internet_Protocol_version_6 and plen in (None, 16):
462472
return cast('IPv6Address', parse_ip_address(
463473
addr, f'{self.__class__.__name__}: invalid protocol address', version=6)).packed
464474

@@ -473,7 +483,7 @@ def _make_proto_resolve(self, addr: 'IPv4Address | IPv6Address | str | bytes', p
473483
return addr
474484

475485

476-
class InARP(ARP):
486+
class InARP(ARP, schema=Schema_ARP, data=Data_ARP):
477487
"""This class implements Inverse Address Resolution Protocol."""
478488

479489
##########################################################################
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
# -*- coding: utf-8 -*-
2+
"""ARP, InARP, RARP and DRARP rebuild every header they parse byte for byte.
3+
4+
GitHub issues:
5+
6+
* #1204: :class:`~pcapkit.protocols.link.arp.InARP` and
7+
:class:`~pcapkit.protocols.application.rarp.DRARP` did not pass
8+
``schema=``/``data=``, so they fell back to the ``Raw`` schema and could not
9+
parse any input.
10+
* #1205: an Ethernet hardware address whose ``hlen`` is not 6 was read as
11+
colon-joined hex, but :meth:`ARP._make_addr_resolve
12+
<pcapkit.protocols.link.arp.ARP._make_addr_resolve>` accepted only a
13+
6-octet MAC.
14+
* #1206: the protocol address was decoded as IPv4 or IPv6 by its length alone,
15+
ignoring ``ptype``/``plen``, so a mismatched pair either decoded as the other
16+
version or raised a bare :exc:`ValueError`.
17+
18+
Every case builds its own octets in memory and reads no capture.
19+
20+
The classes are imported inside each test, after
21+
:func:`~tests._support.reimport_once_per_class`, not at module load (c.f.
22+
``tests/protocols/link/test_ethernet_mac_roundtrip_unit.py``).
23+
24+
"""
25+
26+
import importlib
27+
import unittest
28+
29+
from tests._support import reimport_once_per_class
30+
31+
#: ``(module, class)`` for every ARP-family class.
32+
CLASSES = (
33+
('pcapkit.protocols.link.arp', 'ARP'),
34+
('pcapkit.protocols.link.arp', 'InARP'),
35+
('pcapkit.protocols.application.rarp', 'RARP'),
36+
('pcapkit.protocols.application.rarp', 'DRARP'),
37+
)
38+
39+
40+
def _header(ptype: str, hlen: int, plen: int, oper: str) -> bytes:
41+
"""Ethernet-htype header with distinct, non-zero addresses."""
42+
return bytes.fromhex('0001' + ptype + f'{hlen:02x}{plen:02x}' + oper
43+
+ '01' * hlen + 'a1' * plen + '02' * hlen + 'b2' * plen)
44+
45+
46+
class TestARPRoundTrip(unittest.TestCase):
47+
"""Parse, then ``from_data``, reproduces the original octets."""
48+
49+
def setUp(self) -> None:
50+
reimport_once_per_class(self)
51+
52+
def _cls(self, module: str, name: str) -> type:
53+
return getattr(importlib.import_module(module), name)
54+
55+
def assertRoundTrips(self, cls: type, data: bytes) -> None:
56+
parsed = cls(data)
57+
self.assertEqual(cls.from_data(parsed.info).data, data)
58+
59+
def test_subclasses_use_arp_schema(self) -> None:
60+
"""#1204: InARP and DRARP inherit ARP's schema and data classes."""
61+
from pcapkit.protocols.data.link.arp import ARP as Data_ARP
62+
from pcapkit.protocols.schema.link.arp import ARP as Schema_ARP
63+
64+
for module, name in CLASSES:
65+
with self.subTest(cls=name):
66+
cls = self._cls(module, name)
67+
self.assertIs(cls.__schema__, Schema_ARP)
68+
self.assertIs(cls.__data__, Data_ARP)
69+
70+
def test_subclasses_round_trip(self) -> None:
71+
"""#1204: the issue's repro parses and rebuilds for InARP and DRARP."""
72+
for module, name, oper in (('pcapkit.protocols.link.arp', 'InARP', '0008'),
73+
('pcapkit.protocols.application.rarp', 'DRARP', '0005')):
74+
with self.subTest(cls=name):
75+
cls = self._cls(module, name)
76+
data = bytes.fromhex('000108000604' + oper + '001122334455' '0a000001'
77+
'66778899aabb' '0a000002')
78+
parsed = cls(data)
79+
self.assertEqual(str(parsed.info.spa), '10.0.0.1')
80+
self.assertRoundTrips(cls, data)
81+
82+
def test_ethernet_hlen_other_than_six(self) -> None:
83+
"""#1205: any Ethernet ``hlen`` that parses also rebuilds."""
84+
for module, name in CLASSES:
85+
for hlen in (0, 1, 8, 20):
86+
with self.subTest(cls=name, hlen=hlen):
87+
cls = self._cls(module, name)
88+
self.assertRoundTrips(cls, _header('0800', hlen, 4, '0001'))
89+
90+
def test_ethernet_issue_repro_round_trips(self) -> None:
91+
"""#1205: the issue's parsed hlen-8 and hlen-0 headers rebuild."""
92+
from pcapkit.protocols.link.arp import ARP
93+
94+
for hlen, data in (
95+
(8, bytes.fromhex('0001080008040001' + '01' * 8 + '0a000001' + '02' * 8 + '0a000002')),
96+
(0, bytes.fromhex('0001080000040001' '0a000001' '0a000002')),
97+
):
98+
with self.subTest(hlen=hlen):
99+
parsed = ARP(data)
100+
self.assertEqual(parsed.info.hlen, hlen)
101+
self.assertRoundTrips(ARP, data)
102+
103+
def test_ethernet_make_without_hlen_requires_six_octets(self) -> None:
104+
"""#1205: with ``htype`` Ethernet and no ``hlen``, a MAC is 6 octets."""
105+
from pcapkit.utilities.exceptions import ProtocolError
106+
107+
for module, name in CLASSES:
108+
cls = self._cls(module, name)
109+
for addr in ('00:11:22:33:44', '', '00:11:22:33:44:55:66'):
110+
with self.subTest(cls=name, addr=addr):
111+
with self.assertRaises(ProtocolError):
112+
cls(htype=1, sha=addr, tha=addr, spa='10.0.0.1', tpa='10.0.0.2')
113+
with self.subTest(cls=name, addr='six octets'):
114+
proto = cls(htype=1, sha='00:11:22:33:44:55', tha='66:77:88:99:aa:bb',
115+
spa='10.0.0.1', tpa='10.0.0.2')
116+
self.assertEqual(proto.info.hlen, 6)
117+
118+
def test_make_accepts_any_octets_with_explicit_hlen_or_other_htype(self) -> None:
119+
"""#1205: an explicit ``hlen``, or a non-Ethernet ``htype``, takes any count."""
120+
from pcapkit.const.arp.hardware import Hardware
121+
122+
for module, name in CLASSES:
123+
cls = self._cls(module, name)
124+
for hlen, addr in ((5, '00:11:22:33:44'), (0, ''), (8, '01:01:01:01:01:01:01:01')):
125+
with self.subTest(cls=name, hlen=hlen):
126+
proto = cls(htype=1, hlen=hlen, sha=addr, tha=addr,
127+
spa='10.0.0.1', tpa='10.0.0.2')
128+
self.assertEqual(proto.info.hlen, hlen)
129+
self.assertEqual(proto.info.sha, addr)
130+
with self.subTest(cls=name, htype='Fibre_Channel'):
131+
proto = cls(htype=Hardware.Fibre_Channel, sha='aabbcc', tha='ddeeff',
132+
spa='10.0.0.1', tpa='10.0.0.2')
133+
self.assertEqual(proto.info.hlen, 3)
134+
135+
def test_ethernet_mac_still_validated(self) -> None:
136+
"""#1205: a malformed MAC string is still rejected."""
137+
from pcapkit.const.arp.hardware import Hardware
138+
from pcapkit.protocols.link.arp import ARP
139+
from pcapkit.utilities.exceptions import ProtocolError
140+
141+
arp = object.__new__(ARP)
142+
self.assertEqual(arp._make_addr_resolve('01:02:03:04:05:06:07:08', Hardware.Ethernet),
143+
bytes.fromhex('0102030405060708'))
144+
self.assertEqual(arp._make_addr_resolve('', Hardware.Ethernet), b'')
145+
for addr in ('not-a-mac', '0102', '01:2', '01:02:', ':01'):
146+
with self.subTest(addr=addr):
147+
with self.assertRaises(ProtocolError):
148+
arp._make_addr_resolve(addr, Hardware.Ethernet)
149+
150+
def test_protocol_address_follows_ptype_and_plen(self) -> None:
151+
"""#1206: IP decoding requires ``ptype`` and ``plen`` to agree."""
152+
import ipaddress
153+
154+
cases = (
155+
('0800', 4, ipaddress.IPv4Address),
156+
('86dd', 16, ipaddress.IPv6Address),
157+
('0800', 16, str),
158+
('0800', 5, str),
159+
('0800', 0, str),
160+
('86dd', 4, str),
161+
)
162+
for module, name in CLASSES:
163+
for ptype, plen, kind in cases:
164+
with self.subTest(cls=name, ptype=ptype, plen=plen):
165+
cls = self._cls(module, name)
166+
data = _header(ptype, 6, plen, '0001')
167+
parsed = cls(data)
168+
self.assertIsInstance(parsed.info.spa, kind)
169+
self.assertIsInstance(parsed.info.tpa, kind)
170+
self.assertRoundTrips(cls, data)
171+
172+
173+
if __name__ == '__main__':
174+
unittest.main()

0 commit comments

Comments
 (0)