Skip to content

Commit ab543c4

Browse files
committed
fix(protocols): dissect LINKTYPE_RAW by version nibble; add the BSD loopback layer for LINKTYPE_NULL/LOOP (#1502, #1574)
- Frame and PCAPNG dispatch LINKTYPE_RAW (101) data as IPV4 or IPV6 by the version nibble of its first octet (_dispatch_linktype), unless RAW itself is registered; any other version stays Raw. - New Loopback link layer (protocols/link, schema/link, data/link): a 4-octet address family, big-endian under LINKTYPE_LOOP (108) and inferred under LINKTYPE_NULL (0) (family_byteorder). The byte order is kept in info and read back by from_data, so a rebuild returns the same info. 2 goes to IPv4 and 24/28/30 to IPv6 through its own __proto__. Registered for NULL and LOOP in both tables, exported, and documented. - dpkt engine: RAW by version nibble; NULL/LOOP through a dpkt Loopback, cached per base/IP/IP6 class and link type, that reads the family as pcapkit does and names its ip/ip6 payload. - Delete Gap(1502): all four labels now agree, many_interfaces.pcapng's two NULL frames included (36 datagrams in default, scapy and dpkt). - Dispatch generator pins the new entries and walks Loopback.__proto__. - New tests for RAW, Loopback (7 families x 2 byte orders x 3 link-type hints, info-exact from_data, PCAP and PCAP-NG) and the dpkt engine. Closes #1502 Closes #1574
1 parent 589414e commit ab543c4

31 files changed

Lines changed: 1195 additions & 32 deletions

‎docs/source/ext.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ The protocol classes :mod:`pcapkit` ships:
3030
+ + +-----------------------+-------------------------------------------------------------+
3131
| | L2TP Family | :class:`pcapkit.protocols.link.l2tpv2.L2TPv2` |
3232
+ +----------------+-----------------------+-------------------------------------------------------------+
33+
| | :class:`pcapkit.protocols.link.loopback.Loopback` |
34+
+ +----------------+-----------------------+-------------------------------------------------------------+
3335
| | | :class:`pcapkit.protocols.link.vlan.VLAN` |
3436
+ + +-----------------------+-------------------------------------------------------------+
3537
| | VLAN Family | :class:`pcapkit.protocols.link.c_tag.C_Tag` |

‎docs/source/pcapkit/protocols/index.rst‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ from given information. The class hierarchy of :mod:`pcapkit.protocols`:
2727
A{{ProtocolMeta}} -.->|metaclass| B(ProtocolBase)
2828

2929
subgraph link [Link Layer]
30-
Link --> Ethernet & L2TP & VLAN & ARP
30+
Link --> Ethernet & L2TP & Loopback & VLAN & ARP
3131

3232
subgraph arp [ARP Family]
3333
ARP --> InARP
@@ -108,6 +108,7 @@ from given information. The class hierarchy of :mod:`pcapkit.protocols`:
108108
click Ethernet "/pcapkit/protocols/link/ethernet.html#pcapkit.protocols.link.ethernet.Ethernet"
109109
click L2TP "/pcapkit/protocols/link/l2tp.html#pcapkit.protocols.link.l2tp.L2TP"
110110
click L2TPv2 "/pcapkit/protocols/link/l2tpv2.html#pcapkit.protocols.link.l2tpv2.L2TPv2"
111+
click Loopback "/pcapkit/protocols/link/loopback.html#pcapkit.protocols.link.loopback.Loopback"
111112
click VLAN "/pcapkit/protocols/link/vlan.html#pcapkit.protocols.link.vlan.VLAN"
112113
click C_Tag "/pcapkit/protocols/link/c_tag.html#pcapkit.protocols.link.c_tag.C_Tag"
113114
click S_Tag "/pcapkit/protocols/link/s_tag.html#pcapkit.protocols.link.s_tag.S_Tag"

‎docs/source/pcapkit/protocols/link/index.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ link layer, with detailed implementation and methods.
1616
arp
1717
l2tp
1818
l2tpv2
19+
loopback
1920
vlan
2021
c_tag
2122
s_tag
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
BSD Loopback Encapsulation
2+
==========================
3+
4+
.. module:: pcapkit.protocols.link.loopback
5+
6+
:mod:`pcapkit.protocols.link.loopback` contains
7+
:class:`~pcapkit.protocols.link.loopback.Loopback`
8+
only, which implements extractor for the BSD loopback
9+
encapsulation [*]_ of ``LINKTYPE_NULL`` and ``LINKTYPE_LOOP``,
10+
whose structure is described as below:
11+
12+
.. table::
13+
14+
====== ===== =================== ===================================
15+
Octets Bits Name Description
16+
====== ===== =================== ===================================
17+
0 0 ``loopback.family`` Address Family (Internet Layer)
18+
====== ===== =================== ===================================
19+
20+
The address family is in the byte order of the capturing host for
21+
``LINKTYPE_NULL``, which no capture format records, so it is inferred from the
22+
octets; for ``LINKTYPE_LOOP`` it is always in network byte order. Either way it
23+
is kept as ``loopback.byteorder``.
24+
25+
.. autoclass:: pcapkit.protocols.link.loopback.Loopback
26+
:no-members:
27+
:show-inheritance:
28+
29+
.. autoproperty:: name
30+
.. autoproperty:: length
31+
.. autoproperty:: protocol
32+
33+
.. automethod:: read
34+
.. automethod:: make
35+
36+
.. automethod:: _make_data
37+
38+
.. automethod:: __index__
39+
40+
.. autoattribute:: __proto__
41+
:no-value:
42+
43+
.. autofunction:: pcapkit.protocols.link.loopback.family_byteorder
44+
45+
Header Schemas
46+
--------------
47+
48+
.. module:: pcapkit.protocols.schema.link.loopback
49+
50+
.. autoclass:: pcapkit.protocols.schema.link.loopback.Loopback
51+
:members:
52+
:show-inheritance:
53+
54+
Data Models
55+
-----------
56+
57+
.. module:: pcapkit.protocols.data.link.loopback
58+
59+
.. autoclass:: pcapkit.protocols.data.link.loopback.Loopback
60+
:members:
61+
:show-inheritance:
62+
63+
.. rubric:: Footnotes
64+
65+
.. [*] https://www.tcpdump.org/linktypes/LINKTYPE_NULL.html

‎docs/source/pcapkit/protocols/misc/pcap.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ whose structure is described as below:
114114
.. automethod:: make
115115

116116
.. automethod:: _make_data
117+
.. automethod:: _dispatch_linktype
117118

118119
.. autoattribute:: __proto__
119120
:no-value:

‎docs/source/pcapkit/protocols/misc/pcapng.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ which implements extractor for PCAP-NG file format [*]_.
3838
.. automethod:: index
3939

4040
.. automethod:: _decode_next_layer
41+
.. automethod:: _dispatch_linktype
4142

4243
.. automethod:: _get_payload
4344
.. automethod:: _make_data

‎examples/generators/dispatch.py‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# -*- coding: utf-8 -*-
2-
"""Enumerate the seven ``__proto__`` dispatch registries, and probe every entry.
2+
"""Enumerate the eight ``__proto__`` dispatch registries, and probe every entry.
33
44
:file:`pcapkit/foundation/registry/protocols.py` documents the registries that
55
decide *which* :class:`~pcapkit.protocols.protocol.Protocol` subclass parses the
@@ -274,6 +274,12 @@ def _ethernet(ethertype: 'int', payload: 'bytes') -> 'bytes':
274274
return bytes(Ethernet(type=ethertype, payload=payload))
275275

276276

277+
def _loopback(family: 'int', payload: 'bytes', byteorder: 'str' = 'little') -> 'bytes':
278+
"""A BSD loopback header carrying ``payload``."""
279+
from pcapkit.protocols.link.loopback import Loopback
280+
return bytes(Loopback(family=family, byteorder=byteorder, payload=payload))
281+
282+
277283
###############################################################################
278284
# Link -- EtherType.
279285
###############################################################################
@@ -508,7 +514,8 @@ def _linktype_payload(code: 'Any') -> 'tuple[bytes, bool]':
508514
Returns:
509515
The record's octets, and whether they still need an Ethernet wrapper
510516
(true for :attr:`~pcapkit.const.reg.linktype.LinkType.ETHERNET`, false
511-
for the two raw-IP link types, which carry no link layer at all).
517+
for the two raw-IP link types, which carry no link layer at all, and
518+
for the two loopback link types, whose header is built here).
512519
513520
"""
514521
from pcapkit.const.reg.linktype import LinkType
@@ -519,6 +526,10 @@ def _linktype_payload(code: 'Any') -> 'tuple[bytes, bool]':
519526
return _ip4(6, _tcp(9999)), False
520527
if code == LinkType.IPV6:
521528
return _ip6(6, _tcp(9999)), False
529+
if code == LinkType.NULL: # in the capturing host's byte order (#1574)
530+
return _loopback(2, _ip4(6, _tcp(9999))), False
531+
if code == LinkType.LOOP: # in network byte order (#1574)
532+
return _loopback(2, _ip4(6, _tcp(9999)), byteorder='big'), False
522533
raise LookupError(f'linktype: no payload builder for {code!r}') # pragma: no cover
523534

524535

@@ -539,6 +550,21 @@ def _pcapng_build(code: 'Any') -> 'Any':
539550
return _extract_first(_pcapng_bytes(code, record), '.pcapng')
540551

541552

553+
###############################################################################
554+
# Loopback -- address family.
555+
###############################################################################
556+
557+
558+
def _loopback_registry() -> 'Any':
559+
from pcapkit.protocols.link.loopback import Loopback
560+
return Loopback.__proto__
561+
562+
563+
def _loopback_build(family: 'int') -> 'Any':
564+
payload = _ip4(6, _tcp(9999)) if family == 2 else _ip6(6, _tcp(9999))
565+
return _extract_first(_pcap_bytes((_loopback(family, payload),), linktype=0), '.pcap')
566+
567+
542568
###############################################################################
543569
# The families, the cases, and the probe.
544570
###############################################################################
@@ -571,7 +597,7 @@ def _internet_enum() -> 'Any':
571597

572598

573599
#: Every family this module exercises, one per ``__proto__`` table named in
574-
#: GitHub issue #496.
600+
#: GitHub issue #496, and the loopback table #1574 added.
575601
FAMILIES = (
576602
Family('link', _link_registry, _link_build, _link_enum),
577603
Family('internet', _internet_registry, _internet_build, _internet_enum),
@@ -580,6 +606,7 @@ def _internet_enum() -> 'Any':
580606
Family('sctp', _sctp_registry, _sctp_build),
581607
Family('pcap-frame', _pcap_frame_registry, _pcap_frame_build),
582608
Family('pcapng-frame', _pcapng_registry, _pcapng_build),
609+
Family('loopback', _loopback_registry, _loopback_build),
583610
)
584611

585612
#: The families keyed by label, for a caller -- :func:`probe` -- that wants
@@ -665,14 +692,24 @@ def _internet_enum() -> 'Any':
665692
('pcapkit.protocols.application.ngap', 'NGAP'),
666693

667694
# -- Frame.__proto__ (pcap LinkType) ---------------------------------------
695+
'pcap-frame/NULL': ('pcapkit.protocols.link', 'Loopback'),
668696
'pcap-frame/ETHERNET': ('pcapkit.protocols.link', 'Ethernet'),
697+
'pcap-frame/LOOP': ('pcapkit.protocols.link', 'Loopback'),
669698
'pcap-frame/IPV4': ('pcapkit.protocols.internet', 'IPv4'),
670699
'pcap-frame/IPV6': ('pcapkit.protocols.internet', 'IPv6'),
671700

672701
# -- PCAPNG.__proto__ (LinkType) --------------------------------------------
702+
'pcapng-frame/NULL': ('pcapkit.protocols.link', 'Loopback'),
673703
'pcapng-frame/ETHERNET': ('pcapkit.protocols.link', 'Ethernet'),
704+
'pcapng-frame/LOOP': ('pcapkit.protocols.link', 'Loopback'),
674705
'pcapng-frame/IPV4': ('pcapkit.protocols.internet', 'IPv4'),
675706
'pcapng-frame/IPV6': ('pcapkit.protocols.internet', 'IPv6'),
707+
708+
# -- Loopback.__proto__ (address family) ------------------------------------
709+
'loopback/2': ('pcapkit.protocols.internet.ipv4', 'IPv4'),
710+
'loopback/24': ('pcapkit.protocols.internet.ipv6', 'IPv6'),
711+
'loopback/28': ('pcapkit.protocols.internet.ipv6', 'IPv6'),
712+
'loopback/30': ('pcapkit.protocols.internet.ipv6', 'IPv6'),
676713
}
677714

678715

‎pcapkit/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@
113113
'Raw', # Raw Packet
114114

115115
'ARP', 'C_Tag', 'Ethernet', 'InARP', 'L2TP', # Link Layer
116-
'L2TPv2', 'S_Tag', 'VLAN',
116+
'L2TPv2', 'Loopback', 'S_Tag', 'VLAN',
117117

118118
'AH', 'ESP', 'IP', 'IPsec', 'IPv4', 'IPv6', 'IPX', # Internet Layer
119119
'HIP', 'HOPOPT', 'IPv6_Frag', 'IPv6_Ext', 'IPv6_Opts', 'IPv6_Route', 'MH',

‎pcapkit/all.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@
120120
'NoPayload', # No Payload
121121
'Raw', # Raw Packet
122122
'ARP', 'C_Tag', 'Ethernet', 'InARP', 'L2TP', 'L2TPv2',
123-
'S_Tag', 'VLAN', # Link Layer
123+
'Loopback', 'S_Tag', 'VLAN', # Link Layer
124124
'AH', 'ESP', 'IP', 'IPsec', 'IPv4', 'IPv6', 'IPX', # Internet Layer
125125
'HIP', 'HOPOPT', 'IPv6_Ext', 'IPv6_Frag', 'IPv6_Opts', 'IPv6_Route', 'MH',
126126
# IPv6 Extension Header

‎pcapkit/foundation/engines/dpkt.py‎

Lines changed: 68 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
1212
"""
1313
import decimal
14+
import functools
1415
from typing import TYPE_CHECKING, cast
1516

1617
from pcapkit.const.pcapng.block_type import BlockType as Enum_BlockType
@@ -298,6 +299,58 @@ def __iter__(self) -> 'Iterator[tuple[float, bytes]]':
298299
return _Reader
299300

300301

302+
@functools.lru_cache(maxsize=None)
303+
def _loopback_protocol(base: 'Type[DPKTPacket]', ip: 'Type[DPKTPacket]', ip6: 'Type[DPKTPacket]',
304+
linktype: 'int') -> 'Type[DPKTPacket]':
305+
"""A :class:`dpkt.loopback.Loopback` that reads as the default engine's.
306+
307+
It reads the address family in the byte order
308+
:func:`~pcapkit.protocols.link.loopback.family_byteorder` gives for
309+
``linktype`` -- network byte order for ``LINKTYPE_LOOP``, inferred for
310+
``LINKTYPE_NULL`` -- and dispatches on the same families as
311+
:class:`~pcapkit.protocols.link.loopback.Loopback`. Unlike `DPKT`_'s own, it
312+
names an IPv4 or IPv6 payload ``ip`` or ``ip6``, as
313+
:class:`dpkt.ethernet.Ethernet` does and as :mod:`pcapkit.toolkit.dpkt`
314+
looks for it, and keeps a payload of any other family as raw octets rather
315+
than parsing it as Ethernet (:issue:`1574`).
316+
317+
Args:
318+
base: :class:`dpkt.loopback.Loopback` itself.
319+
ip: :class:`dpkt.ip.IP`, the payload of family 2.
320+
ip6: :class:`dpkt.ip6.IP6`, the payload of families 24, 28 and 30.
321+
linktype: ``LINKTYPE_NULL`` or ``LINKTYPE_LOOP``.
322+
323+
Returns:
324+
The packet type, built once per argument tuple rather than once per
325+
packet. Every class it is built from is part of that key, so a reloaded
326+
`DPKT`_ module gets a class of its own instead of one holding stale
327+
classes.
328+
329+
.. _DPKT: https://dpkt.readthedocs.io
330+
331+
"""
332+
import dpkt # isort:skip
333+
334+
from pcapkit.protocols.link.loopback import family_byteorder # isort:skip
335+
336+
layers = {2: ip, 24: ip6, 28: ip6, 30: ip6}
337+
338+
class Loopback(base):
339+
"""BSD loopback encapsulation."""
340+
341+
def unpack(ext, buf: 'bytes') -> 'None':
342+
dpkt.dpkt.Packet.unpack(ext, buf)
343+
family = buf[:ext.__hdr_len__]
344+
ext.family = int.from_bytes(family, family_byteorder(family, linktype))
345+
layer = layers.get(ext.family)
346+
if layer is not None:
347+
payload = layer(buf[ext.__hdr_len__:])
348+
ext.data = payload
349+
setattr(ext, layer.__name__.lower(), payload)
350+
351+
return Loopback
352+
353+
301354
class DPKT(EngineBase['DPKTPacket']):
302355
"""DPKT engine support.
303356
@@ -434,7 +487,7 @@ def read_frame(self) -> 'DPKTPacket':
434487
# interface this packet was captured on, so ask only after reading it
435488
timestamp, pkt = cast('tuple[float, bytes]', next(reader))
436489
linktype = Enum_LinkType.get(reader.datalink())
437-
protocol = self._get_protocol(linktype)
490+
protocol = self._get_protocol(linktype, pkt)
438491
try:
439492
packet = protocol(pkt) # type: DPKTPacket
440493
except Exception as exc: # pylint: disable=broad-except
@@ -511,25 +564,36 @@ def read_frame(self) -> 'DPKTPacket':
511564
# Utilities.
512565
##########################################################################
513566

514-
def _get_protocol(self, linktype: 'Optional[Enum_LinkType]' = None) -> 'Type[DPKTPacket]':
567+
def _get_protocol(self, linktype: 'Optional[Enum_LinkType]' = None,
568+
data: 'bytes' = b'') -> 'Type[DPKTPacket]':
515569
"""Returns the protocol for parsing the current packet.
516570
517571
Args:
518572
linktype: Link type code.
573+
data: Octets of the current packet. ``LINKTYPE_RAW`` (101) carries
574+
a bare IPv4 or IPv6 datagram, and only the version nibble of
575+
its first octet tells which (:issue:`1502`).
576+
577+
Notes:
578+
``LINKTYPE_NULL`` (0) and ``LINKTYPE_LOOP`` (108) are parsed with
579+
:func:`_loopback_protocol` (:issue:`1574`).
519580
520581
"""
521582
dpkt = self._expkg
522583
reader = self._extmp
523584

524585
if linktype is None:
525586
linktype = Enum_LinkType.get(reader.datalink())
587+
version = data[0] >> 4 if data else None
526588

527589
if linktype == Enum_LinkType.ETHERNET:
528590
pkg = dpkt.ethernet.Ethernet
529-
elif linktype.value == Enum_LinkType.IPV4:
591+
elif linktype.value == Enum_LinkType.IPV4 or (linktype.value == Enum_LinkType.RAW and version == 4):
530592
pkg = dpkt.ip.IP
531-
elif linktype.value == Enum_LinkType.IPV6:
593+
elif linktype.value == Enum_LinkType.IPV6 or (linktype.value == Enum_LinkType.RAW and version == 6):
532594
pkg = dpkt.ip6.IP6
595+
elif linktype.value in (Enum_LinkType.NULL, Enum_LinkType.LOOP):
596+
pkg = _loopback_protocol(dpkt.loopback.Loopback, dpkt.ip.IP, dpkt.ip6.IP6, linktype.value)
533597
else:
534598
warn('unrecognised link layer protocol; all analysis functions ignored',
535599
DPKTWarning, stacklevel=stacklevel())

0 commit comments

Comments
 (0)