Source code for pcapkit.protocols.link.gre.protocol

# -*- coding: utf-8 -*-
"""GRE - Generic Routing Encapsulation
=========================================

.. module:: pcapkit.protocols.link.gre.protocol

:mod:`pcapkit.protocols.link.gre.protocol` contains
:class:`~pcapkit.protocols.link.gre.protocol.GRE` only, which implements the extractor
for the Generic Routing Encapsulation base header [:rfc:`2784`] plus the
optional Key and Sequence Number extensions [:rfc:`2890`]. It is reached
through IP protocol number 47 behind any layer sharing
:attr:`Internet.__proto__ <pcapkit.protocols.internet.internet.Internet.__proto__>`,
IPv4 and IPv6 among them, and on a
``LINKTYPE_LINUX_SLL``/``LINKTYPE_LINUX_SLL2`` capture whose ``arphrd_type``
is ``ARPHRD_IPGRE`` or ``ARPHRD_IP6GRE``; see
:attr:`LinuxSLL.__proto__ <pcapkit.protocols.link.linux_sll.protocol.LinuxSLL.__proto__>`.
The two names differ only in the tunnel's outer IP version; the GRE framing is
the same.

Structure, the base header plus every optional field (:rfc:`2784` section
2.1, :rfc:`2890` section 2):

.. code-block:: text

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |C| |K|S| Reserved0       | Ver |         Protocol Type         |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |      Checksum (optional)      |       Reserved1 (optional)    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                         Key (optional)                        |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                 Sequence Number (optional)                    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

``C`` gates the Checksum/Reserved1 pair, ``K`` gates the Key field and ``S``
gates the Sequence Number field, each independently, so the header is 4, 8,
12 or 16 octets. ``Ver`` is :rfc:`2784`'s 3-bit Version Number, which MUST be
``0``. The Protocol Type field is an EtherType selecting the payload, resolved
through :attr:`Link.__proto__ <pcapkit.protocols.link.link.Link.__proto__>` as
:class:`~pcapkit.protocols.link.vlan.protocol.VLAN` resolves its ``type`` field,
so this class keeps no registry of its own.

Scope
-----

Only the framing above is dissected. The Key and Sequence Number fields are
recorded but not interpreted: their meaning is a matter for the tunnel
endpoints. The Checksum, when ``C`` is set, covers the header and the payload
with no pseudo-header (:rfc:`2784#section-2.5`);
:meth:`~pcapkit.protocols.link.gre.protocol.GRE.read` verifies it and
:meth:`~pcapkit.protocols.link.gre.protocol.GRE.make` computes it
(:issue:`2618`). RFC 2637's Enhanced GRE (version 1, used by PPTP) has an
incompatible layout -- a Key field split into Payload Length and Call ID, and
an optional Acknowledgment Number -- so :meth:`read` refuses any nonzero
version rather than misreading it as RFC 2784/2890 GRE.

.. versionadded:: 1.6.0

"""
from typing import TYPE_CHECKING

from pcapkit.const.reg.ethertype import EtherType as Enum_EtherType
from pcapkit.const.reg.transtype import TransType as Enum_TransType
from pcapkit.protocols.link.gre.data import GRE as Data_GRE
from pcapkit.protocols.link.gre.schema import GRE as Schema_GRE
from pcapkit.protocols.link.link import Link
from pcapkit.utilities import config
from pcapkit.utilities.exceptions import ProtocolError

if TYPE_CHECKING:
    from typing import Any, Optional

    from typing_extensions import Literal

    from pcapkit.protocols.protocol import ProtocolBase
    from pcapkit.protocols.schema import Schema

__all__ = ['GRE']


[docs] class GRE(Link[Data_GRE, Schema_GRE], schema=Schema_GRE, data=Data_GRE): """This class implements Generic Routing Encapsulation (GRE). The Protocol Type field is dispatched as an EtherType through :attr:`Link.__proto__ <pcapkit.protocols.link.link.Link.__proto__>`, exactly as :class:`~pcapkit.protocols.link.vlan.protocol.VLAN` resolves its own ``type`` field -- so, unlike :class:`~pcapkit.protocols.link.frad.protocol.FRAD`, this class declares no registry of its own. The checksum, present when ``C`` is set, is verified on read under :data:`~pcapkit.utilities.config.CHECKSUM_VERIFY`, and computed by :meth:`make` when ``checksum_present`` asks for one without giving it. Neither this header nor the Linux cooked-capture header before it states a length, so the message runs to the end of its frame. A frame the capture cut short, holding fewer octets than its original length, reads as :attr:`~pcapkit.corekit.checksum.internet.ChecksumStatus.TRUNCATED`, as :data:`~pcapkit.utilities.contextvars.frame_length` tells it (:issue:`2653`), and so does a header the data ends inside (:issue:`2689`). The header records such a cut, so the message rebuilt on its own reads as cut too (:issue:`2711`). """ ########################################################################## # Properties. ########################################################################## @property def name(self) -> 'Literal["Generic Routing Encapsulation"]': """Name of current protocol.""" return 'Generic Routing Encapsulation' @property def alias(self) -> 'Literal["GRE"]': """Acronym of corresponding protocol.""" return 'GRE' @property def length(self) -> 'int': """Header length of current protocol.""" return self._info.len @property def protocol(self) -> 'Enum_EtherType': """Name of next layer protocol.""" return self._info.protocol_type ########################################################################## # Methods. ##########################################################################
[docs] @classmethod def id(cls) -> 'tuple[Literal["GRE"]]': """Index ID of the protocol.""" return ('GRE',)
[docs] def read(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_GRE': # pylint: disable=unused-argument """Read Generic Routing Encapsulation (GRE) frame. Structure of a GRE frame, with every optional field present; see the module docstring for the full diagram: .. code-block:: text 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |C| |K|S| Reserved0 | Ver | Protocol Type | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Args: length: Length of packet data. **kwargs: Arbitrary keyword arguments. Returns: Parsed packet data. Raises: ProtocolError: If the Version Number is not ``0`` -- see the module docstring's *Scope* section. """ if length is None: length = len(self) schema = self.__header__ flags = schema.flags if flags['version']: raise ProtocolError(f'{self.alias}: invalid version: {flags["version"]}') _hdr_len = 4 _checksum = None # type: Optional[int] _reserved1 = None # type: Optional[int] if flags['checksum_present']: _checksum = schema.checksum _reserved1 = schema.reserved1 _hdr_len += 4 _key = None # type: Optional[int] if flags['key_present']: _key = schema.key _hdr_len += 4 _sequence_number = None # type: Optional[int] if flags['sequence_present']: _sequence_number = schema.sequence_number _hdr_len += 4 gre = Data_GRE( checksum_present=bool(flags['checksum_present']), key_present=bool(flags['key_present']), sequence_present=bool(flags['sequence_present']), reserved=(flags['reserved_1'] << 14) | (flags['reserved_2'] << 3), version=flags['version'], protocol_type=schema.protocol_type, checksum=_checksum, reserved1=_reserved1, key=_key, sequence_number=_sequence_number, len=_hdr_len, ) # NOTE: The checksum covers the header and the payload, with no # pseudo-header (RFC 2784 section 2.5); with C clear there is none. if config.CHECKSUM_VERIFY: from pcapkit.corekit.checksum.internet import ( # isort: skip # pylint: disable=import-outside-toplevel ChecksumStatus, verify_message) if _checksum is None: status = ChecksumStatus.NOT_COMPUTED elif '__short_read__' in schema.__dict__: # NOTE: The checksum covers the whole message, so a header the data # ends inside leaves part of what it covers uncaptured (#2689). status = ChecksumStatus.TRUNCATED else: # NOTE: Behind LinuxSLL the message runs to the end of its frame, so # verify_message covers what the capture cut off too (#2653). status = verify_message(self.alias, self._data, _checksum.to_bytes(2, 'big'), length=length) gre.__update__([ ('checksum_status', status), ]) return self._decode_next_layer(gre, schema.protocol_type, length - _hdr_len)
[docs] def make(self, *, checksum: 'Optional[int]' = None, reserved1: 'Optional[int]' = None, checksum_present: 'Optional[bool]' = None, key: 'Optional[int]' = None, sequence_number: 'Optional[int]' = None, reserved: 'int' = 0, version: 'Literal[0]' = 0, protocol_type: 'Enum_EtherType | int' = Enum_EtherType.Internet_Protocol_version_4, payload: 'bytes | ProtocolBase | Schema' = b'', **kwargs: 'Any') -> 'Schema_GRE': """Make (construct) packet data. The presence of each optional field is inferred from whether its value is given, as :meth:`L2TPv2.make <pcapkit.protocols.link.l2tpv2.protocol.L2TPv2.make>` infers ``S`` from whether ``ns``/``nr`` are given: passing ``checksum`` sets ``C``, ``key`` sets ``K``, and ``sequence_number`` sets ``S``. ``C`` can be set without a ``checksum`` too, through ``checksum_present``, as L2TPv2's ``length_flag`` sets ``L`` without a length. Args: checksum: Checksum; setting this also sets ``C``. If :data:`None` with ``C`` set, computed over the header and ``payload`` (:rfc:`2784#section-2.5`) when :data:`~pcapkit.utilities.config.CHECKSUM_COMPUTE` is on, zero when it is off. reserved1: Reserved1; only meaningful, and only accepted, when ``C`` is set. Defaults to ``0`` when ``C`` is set and this is not. checksum_present: Whether ``C`` is set, and the Checksum and Reserved1 fields present. When :data:`None`, ``C`` is set if ``checksum`` is given. key: Key, :rfc:`2890`; setting this also sets ``K``. sequence_number: Sequence Number, :rfc:`2890`; setting this also sets ``S``. reserved: Reserved bits of the flags word, in their on-wire positions (bit 1 and bits 4-12, i.e. within ``0x4FF8``). version: Version Number; :rfc:`2784` fixes this at ``0``. protocol_type: Protocol Type: the EtherType of the encapsulated payload. payload: Payload data. **kwargs: Arbitrary keyword arguments. Returns: Constructed packet data. Raises: ProtocolError: If ``checksum`` or ``reserved1`` is given with ``C`` clear; if ``reserved`` sets a bit outside ``0x4FF8``; if ``version`` does not fit in 3 bits; if ``protocol_type`` is a name, a :obj:`bool`, or a member or code its field cannot carry; or if ``checksum``, ``key`` or ``sequence_number`` is given but does not fit the width of its field (16 bits for ``checksum``, 32 bits for ``key`` and ``sequence_number``). """ protocol_type_ = self._make_index(protocol_type, Enum_EtherType, bits=16, name='protocol type') if checksum_present is None: checksum_present = checksum is not None elif not checksum_present and checksum is not None: raise ProtocolError(f'{self.alias}: checksum given with checksum_present=False') if reserved1 is not None and not checksum_present: raise ProtocolError(f'{self.alias}: reserved1 given without checksum') if checksum_present: if checksum is not None: checksum = self._make_uint(checksum, bits=16, name='checksum') if reserved1 is None: reserved1 = 0 else: reserved1 = self._make_uint(reserved1, bits=16, name='reserved1') key_present = key is not None if key_present: key = self._make_uint(key, bits=32, name='key') sequence_present = sequence_number is not None if sequence_present: sequence_number = self._make_uint(sequence_number, bits=32, name='sequence_number') if reserved & ~0x4FF8: raise ProtocolError(f'{self.alias}: reserved bits outside 0x4FF8: {reserved:#06x}') self._make_uint(version, bits=3, name='version') schema = Schema_GRE( flags={ 'checksum_present': checksum_present, 'reserved_1': (reserved >> 14) & 0b1, 'key_present': key_present, 'sequence_present': sequence_present, 'reserved_2': (reserved >> 3) & 0x1FF, 'version': version, }, protocol_type=protocol_type_, checksum=0 if checksum_present and checksum is None else checksum, reserved1=reserved1, key=key, sequence_number=sequence_number, payload=payload, ) if checksum_present and checksum is None and config.CHECKSUM_COMPUTE: from pcapkit.corekit.checksum.internet import internet_checksum # isort: skip # pylint: disable=import-outside-toplevel schema.checksum = internet_checksum(schema.pack()) return schema
########################################################################## # Data models. ##########################################################################
[docs] def __length_hint__(self) -> 'Literal[16]': """Return an estimated length for the object. The longest form -- every optional field present, 16 octets -- per the reason :meth:`L2TPv2.__length_hint__ <pcapkit.protocols.link.l2tpv2.protocol.L2TPv2.__length_hint__>` gives for a variable-length header. """ return 16
[docs] @classmethod def __index__(cls) -> 'Enum_TransType': # pylint: disable=invalid-index-returned """Numeral registry index of the protocol. Returns: Numeral registry index of the protocol in `IANA`_ protocol numbers, which :attr:`Internet.__proto__ <pcapkit.protocols.internet.internet.Internet.__proto__>` is keyed by. :attr:`LinuxSLL.__proto__ <pcapkit.protocols.link.linux_sll.protocol.LinuxSLL.__proto__>` names its own keys for this class, :attr:`~pcapkit.const.linux.arphrd.ARPHRD.IPGRE` and :attr:`~pcapkit.const.linux.arphrd.ARPHRD.IP6GRE` (:ref:`registry-protocol-index`). .. _IANA: https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml """ return Enum_TransType.GRE # type: ignore[return-value]
########################################################################## # Utilities. ##########################################################################
[docs] @classmethod def _make_data(cls, data: 'Data_GRE') -> 'dict[str, Any]': # type: ignore[override] """Create key-value pairs from ``data`` for protocol construction. Args: data: protocol data Returns: Key-value pairs for protocol construction. """ return { 'checksum': data.checksum, 'reserved1': data.reserved1, 'key': data.key, 'sequence_number': data.sequence_number, 'reserved': data.reserved, 'version': data.version, 'protocol_type': data.protocol_type, 'payload': cls._make_payload(data), }