# -*- coding: utf-8 -*-
"""IP Pseudo-Header
======================
.. module:: pcapkit.protocols.misc.checksum.ip_pseudo.protocol
:mod:`pcapkit.protocols.misc.checksum.ip_pseudo.protocol` contains
:class:`~pcapkit.protocols.misc.checksum.ip_pseudo.protocol.IP_Pseudo`,
which implements the pseudo-header of the IP protocol family
that the upper-layer checksums cover, and :func:`pseudo_header`,
:func:`compute_upper` and :func:`verify_upper`, through which the IP layers
use it. The pseudo-header's structure is described as below:
IPv4 (:rfc:`793#section-3.1`, :rfc:`768`):
======= ========= ========================= ===============================
Octets Bits Name Description
======= ========= ========================= ===============================
0 0 ``ip_pseudo.src`` Source Address
4 32 ``ip_pseudo.dst`` Destination Address
8 64 ``ip_pseudo.zero`` Reserved
9 72 ``ip_pseudo.protocol`` Protocol
10 80 ``ip_pseudo.len`` Upper-Layer Packet Length
======= ========= ========================= ===============================
IPv6 (:rfc:`8200#section-8.1`):
======= ========= ========================= ===============================
Octets Bits Name Description
======= ========= ========================= ===============================
0 0 ``ip_pseudo.src`` Source Address
16 128 ``ip_pseudo.dst`` Destination Address
32 256 ``ip_pseudo.len`` Upper-Layer Packet Length
36 288 ``ip_pseudo.zero`` Reserved
39 312 ``ip_pseudo.protocol`` Next Header
======= ========= ========================= ===============================
A checksum over the IP pseudo-header is left to the enclosing IP layer, which
alone knows the pseudo-header, and builds it as an
:class:`~pcapkit.protocols.misc.checksum.ip_pseudo.protocol.IP_Pseudo`, rather than the
upper layer reaching back to its parent. The upper layer takes part through
these members:
* ``_verify_pseudo_checksum(pseudo)`` verifies the checksum against
``pseudo``, or records
:attr:`~pcapkit.corekit.checksum.internet.ChecksumStatus.NO_PSEUDO_HEADER`
for :data:`None`; the IP layer calls it once parsed, see :func:`verify_upper`;
* ``make()`` takes the ``pseudo`` it computes the checksum over, and replaces
the length it carries with the upper layer's own, see :func:`pseudo_header`;
* ``_checksum_pending`` is :data:`True` once ``make()`` left out a checksum it
had no ``pseudo`` for. An IP layer constructed with that upper layer as its
payload, or behind an IPv4 Authentication Header or IPv6 extension headers,
then rebuilds it with its own pseudo-header, see :func:`compute_upper`.
The sum itself is in :mod:`pcapkit.corekit.checksum.internet`.
"""
import ipaddress
from typing import TYPE_CHECKING, cast, overload
from pcapkit.const.ipv4.option_number import OptionNumber as Enum_IPv4Option
from pcapkit.const.ipv6.extension_header import ExtensionHeader as Enum_ExtensionHeader
from pcapkit.const.ipv6.option import Option as Enum_Option
from pcapkit.const.reg.transtype import TransType as Enum_TransType
from pcapkit.corekit.const.ipheader import IP_MAX_LENGTH, IPV6_HEADER_LEN
from pcapkit.corekit.module import ModuleDescriptor
from pcapkit.corekit.protochain import ProtoChain
from pcapkit.corekit.schema.ipaddress import parse_ip_address
from pcapkit.corekit.schema.jumbogram import jumbo_payload_length
from pcapkit.protocols.internet.ipv4.protocol import IPv4
from pcapkit.protocols.internet.ipv4.schema import IPv4 as Schema_IPv4
from pcapkit.protocols.internet.ipv6.protocol import IPv6
from pcapkit.protocols.misc.checksum.ip_pseudo.const import (_TERMINAL_HEADERS, IPV4_PSEUDO_LEN,
IPV6_PSEUDO_LEN)
from pcapkit.protocols.misc.checksum.ip_pseudo.data import IP_Pseudo as Data_IP_Pseudo
from pcapkit.protocols.misc.checksum.ip_pseudo.schema import IP_Pseudo as Schema_IP_Pseudo
from pcapkit.protocols.misc.no_payload.protocol import NoPayload
from pcapkit.protocols.protocol import ProtocolBase
from pcapkit.utilities.contextvars import rebuilding
from pcapkit.utilities.exceptions import (CaughtByCaller, FieldValueError, ProtocolError,
UnsupportedCall)
if TYPE_CHECKING:
from ipaddress import IPv4Address, IPv6Address
from typing import IO, Any, Iterable, Mapping, NoReturn, Optional, Type
from typing_extensions import Literal
from pcapkit.corekit.context import ContextRegistry, ProtocolContext
from pcapkit.protocols.internet.ah.protocol import AH
from pcapkit.protocols.internet.ipv6.schema import IPv6 as Schema_IPv6
from pcapkit.protocols.internet.ipv6_ext.protocol import IPv6_Ext
__all__ = ['IP_Pseudo', 'pseudo_header', 'compute_upper', 'verify_upper']
#: The Authentication Header :func:`verify_upper` and :func:`compute_upper` look
#: past to the upper layer of IPv4, and the extension header base
#: :func:`compute_upper` looks through under IPv6, resolved there rather than
#: imported, so their first import holds
#: :data:`~pcapkit.utilities.importlib.import_lock` (:issue:`2771`).
_AH: 'ModuleDescriptor[AH]' = ModuleDescriptor('pcapkit.protocols.internet.ah.protocol', 'AH')
_IPV6_EXT: 'ModuleDescriptor[IPv6_Ext]' = \
ModuleDescriptor('pcapkit.protocols.internet.ipv6_ext.protocol', 'IPv6_Ext')
[docs]
class IP_Pseudo(ProtocolBase[Data_IP_Pseudo, Schema_IP_Pseudo],
schema=Schema_IP_Pseudo, data=Data_IP_Pseudo):
"""This class implements the IP pseudo-header.
It is not a layer on the wire: it is built from the enclosing
:class:`~pcapkit.protocols.internet.ipv4.protocol.IPv4` or
:class:`~pcapkit.protocols.internet.ipv6.protocol.IPv6` layer, or from explicit
values, and its :attr:`data` is the octets an upper-layer checksum covers
ahead of that layer's own. The layout follows the IP version of the source
address, or the length of the octets parsed.
.. versionadded:: 1.6.0
"""
##########################################################################
# Properties.
##########################################################################
@property
def name(self) -> 'Literal["IP Pseudo-Header"]':
"""Name of current protocol."""
return 'IP Pseudo-Header'
@property
def length(self) -> 'Literal[12, 40]':
"""Header length of current protocol."""
return IPV6_PSEUDO_LEN if self._is_ipv6(self._info.src) else IPV4_PSEUDO_LEN # type: ignore[return-value]
@property
def protocol(self) -> 'Enum_TransType':
"""Upper-layer protocol."""
return self._info.protocol
@property
def version(self) -> 'Literal[4, 6]':
"""IP version of the enclosing layer."""
return self._info.version
@property
def src(self) -> 'IPv4Address | IPv6Address':
"""Source address."""
return self._info.src
@property
def dst(self) -> 'IPv4Address | IPv6Address':
"""Destination address."""
return self._info.dst
##########################################################################
# Methods.
##########################################################################
[docs]
def read(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_IP_Pseudo': # pylint: disable=unused-argument
"""Read IP pseudo-header.
Structure of the IPv4 pseudo-header [:rfc:`793`]:
.. code-block:: text
+--------+--------+--------+--------+
| Source Address |
+--------+--------+--------+--------+
| Destination Address |
+--------+--------+--------+--------+
| zero | PTCL | TCP Length |
+--------+--------+--------+--------+
Structure of the IPv6 pseudo-header [:rfc:`8200`]:
.. code-block:: text
+--------+--------+--------+--------+
| |
+ +
| |
+ Source Address +
| |
+ +
| |
+--------+--------+--------+--------+
| |
+ +
| |
+ Destination Address +
| |
+ +
| |
+--------+--------+--------+--------+
| Upper-Layer Packet Length |
+--------+--------+--------+--------+
| zero | Next |
+--------+--------+--------+--------+
Args:
length: Length of packet data.
**kwargs: Arbitrary keyword arguments.
Returns:
Parsed packet data.
"""
schema = self.__header__
version: 'Literal[4, 6]' = schema.src.version
return Data_IP_Pseudo(
version=version,
src=schema.src,
dst=schema.dst,
protocol=Enum_TransType.get(schema.protocol),
len=schema.ipv6_len if self._is_ipv6(schema.src) else schema.ipv4_len,
zero=schema.zero,
)
[docs]
def make(self, *,
ip: 'Optional[IPv4 | IPv6]' = None,
src: 'Optional[IPv4Address | IPv6Address | str | int | bytes]' = None,
dst: 'Optional[IPv4Address | IPv6Address | str | int | bytes]' = None,
protocol: 'Optional[Enum_TransType | int]' = None,
upper_length: 'Optional[int]' = None,
zero: 'bytes' = b'',
**kwargs: 'Any') -> 'Schema_IP_Pseudo':
"""Make (construct) packet data.
Values not given are read from ``ip``. ``src`` is a Home Address option's
address (:rfc:`6275#section-11.3.1`); ``dst`` is the final destination of a
Routing header with segments left, or of a source route (:rfc:`791`) not
yet exhausted; ``protocol`` and ``upper_length`` lie past the extension
headers, a UDP upper layer giving its Length field (:rfc:`768`) and a
jumbogram its Jumbo Payload Length (:rfc:`2675`). Values ``ip`` lacks are
to be given: an unparsed Routing destination (:rfc:`8754`), a fragment's
length, or an upper layer behind an unparsed header such as ESP.
Args:
ip: Parsed or constructed IP layer enclosing the upper layer.
src: Source address; its IP version selects the layout.
dst: Destination address, of the same IP version as ``src``.
protocol: Upper-layer protocol number.
upper_length: Upper-layer packet length, header included.
zero: Reserved octets, one for IPv4 and three for IPv6; empty for
zeros.
**kwargs: Arbitrary keyword arguments.
Returns:
Constructed packet data.
Raises:
ProtocolError: If ``ip`` is neither IPv4 nor IPv6, a value is given
by neither the arguments nor ``ip``, a header of ``ip`` is
malformed or not parsed, ``protocol`` is a name, a
:obj:`bool`, or a member or code the 8-bit protocol field
cannot carry, or ``zero`` is neither empty nor the layout's
width.
FieldValueError: If ``src`` or ``dst`` is not a valid address,
they differ in IP version, or ``upper_length`` does not fit
the layout's length field.
"""
if ip is not None:
if not isinstance(ip, (IPv4, IPv6)):
raise ProtocolError(f'{self.alias}: unsupported enclosing layer '
f'{type(ip).__name__}')
if src is None:
src = self._source(ip)
if dst is None:
dst = self._destination(ip)
from_layer = protocol is None
if from_layer:
protocol = self._upper_protocol(ip)
if upper_length is None:
upper_length = self._upper_length(ip, from_layer=from_layer)
if src is None or dst is None or protocol is None or upper_length is None:
raise ProtocolError(f'{self.alias}: src, dst, protocol and upper_length '
'are required without ip')
src_val = parse_ip_address(src, f'{self.alias}: source address')
dst_val = parse_ip_address(dst, f'{self.alias}: destination address', src_val.version)
is_v6 = self._is_ipv6(src_val)
limit = 0xFFFFFFFF if is_v6 else IP_MAX_LENGTH
if not 0 <= upper_length <= limit:
raise FieldValueError(f'{self.alias}: upper-layer length {upper_length} '
f'out of range 0 to {limit:#x}')
proto = self._make_index(protocol, Enum_TransType, bits=8, name='protocol')
# NOTE: Empty is zeros at the layout's width; any other width is refused.
width = 3 if is_v6 else 1
zero = bytes(width) if zero == b'' else self._make_octets(zero, size=width, name='zero octets')
if is_v6:
return Schema_IP_Pseudo(
src=src_val,
dst=dst_val,
ipv6_len=upper_length,
zero=zero,
protocol=proto,
)
return Schema_IP_Pseudo(
src=src_val,
dst=dst_val,
zero=zero,
protocol=proto,
ipv4_len=upper_length,
)
##########################################################################
# Data models.
##########################################################################
if TYPE_CHECKING:
# NOTE: ``protocol`` stops a parse and is a field of a construction, so each
# shape types it as such (#3081); the ``__init__`` called is the inherited one.
@overload
def __init__(self, file: 'IO[bytes] | bytes', length: 'Optional[int]' = ..., /, *,
layer: 'Optional[str]' = ...,
protocol: 'Optional[str | ProtocolBase | Type[ProtocolBase]]' = ...,
context: 'Optional[ContextRegistry | ProtocolContext | Mapping[str, ProtocolContext] | Iterable[ProtocolContext]]' = ..., # pylint: disable=line-too-long
) -> 'None': ...
@overload
def __init__(self, *, protocol: 'Optional[Enum_TransType | int]' = ...,
context: 'Optional[ContextRegistry | ProtocolContext | Mapping[str, ProtocolContext] | Iterable[ProtocolContext]]' = ..., # pylint: disable=line-too-long
**fields: 'Any') -> 'None': ...
def __init__(self, *args: 'Any', **kwargs: 'Any') -> 'None': ... # pylint: disable=super-init-not-called,unused-argument
@overload
def __post_init__(self, file: 'IO[bytes] | bytes', length: 'Optional[int]' = ..., **kwargs: 'Any') -> 'None': ...
@overload
def __post_init__(self, **kwargs: 'Any') -> 'None': ... # pylint: disable=arguments-differ
[docs]
def __post_init__(self, file: 'Optional[IO[bytes] | bytes]' = None,
length: 'Optional[int]' = None, **kwargs: 'Any') -> 'None':
"""Post initialisation hook.
Args:
file: Source packet stream.
length: Length of packet data.
**kwargs: Arbitrary keyword arguments.
Raises:
ProtocolError: If the octets parsed are not ``length`` long, or
not 12 (IPv4) or 40 (IPv6) long.
See Also:
For construction arguments, please refer to :meth:`make`.
"""
if file is not None:
file = file if isinstance(file, bytes) else file.read(length) # type: ignore[arg-type]
if length is None:
length = len(file)
if len(file) != length:
raise ProtocolError(f'{self.alias}: length {length} disagrees with '
f'{len(file)} octets')
if length not in (IPV4_PSEUDO_LEN, IPV6_PSEUDO_LEN):
raise ProtocolError(f'{self.alias}: invalid length {length}; '
f'expected {IPV4_PSEUDO_LEN} or {IPV6_PSEUDO_LEN}')
super().__post_init__(file, length, **kwargs) # type: ignore[arg-type]
#: pcapkit.protocols.misc.no_payload.protocol.NoPayload: Next layer (no payload).
self._next = NoPayload.from_fields()
#: pcapkit.corekit.protochain.ProtoChain: Protocol chain from current layer.
self._protos = ProtoChain(self.__class__, self.alias)
def __length_hint__(self) -> 'Literal[12]':
"""Return an estimated length for the object."""
return IPV4_PSEUDO_LEN # type: ignore[return-value]
[docs]
@classmethod
def __index__(cls) -> 'NoReturn':
"""Numeral registry index of the protocol.
Raises:
UnsupportedCall: This protocol has no registry entry.
"""
raise UnsupportedCall(f'{cls.__name__!r} object cannot be interpreted as an integer')
##########################################################################
# Utilities.
##########################################################################
[docs]
@classmethod
def _make_data(cls, data: 'Data_IP_Pseudo') -> '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 {
'src': data.src,
'dst': data.dst,
'protocol': data.protocol,
'upper_length': data.len,
'zero': data.zero,
}
@staticmethod
def _is_ipv6(address: 'IPv4Address | IPv6Address') -> 'bool':
"""Tell whether ``address`` selects the IPv6 layout."""
return isinstance(address, ipaddress.IPv6Address)
[docs]
def _source(self, ip: 'IPv4 | IPv6') -> 'IPv4Address | IPv6Address':
"""Read the pseudo-header source address from an IP layer.
Args:
ip: IPv4 or IPv6 layer.
Returns:
The address of a Home Address option (:rfc:`6275#section-11.3.1`)
if any, the source address otherwise.
Raises:
ProtocolError: If a Destination Options header is not parsed,
however deep in the chain.
"""
src = ip.info.src
if isinstance(ip, IPv6):
for header in ip.extension_headers.getlist(Enum_ExtensionHeader.IPv6_Opts): # type: ignore[arg-type]
options = header.info.get('options')
if options is None:
raise ProtocolError(f'{self.alias}: Destination Options of {ip.alias} not '
'parsed; give src')
option = options.get(Enum_Option.Home_Address)
if option is not None:
src = option.address
# NOTE: A header the walk stopped on, at any depth, is unparsed too, as
# a malformed one is (#2480), and may hold a Home Address option.
if self._walk(ip)[0] == Enum_ExtensionHeader.IPv6_Opts:
raise ProtocolError(f'{self.alias}: Destination Options of {ip.alias} not '
'parsed; give src')
return src
[docs]
def _destination(self, ip: 'IPv4 | IPv6') -> 'IPv4Address | IPv6Address':
"""Read the pseudo-header destination address from an IP layer.
Args:
ip: IPv4 or IPv6 layer.
Returns:
The last address still to be visited of a source route
(:rfc:`791`) not yet exhausted, or of a Routing header with
segments left; the destination address otherwise.
Raises:
ProtocolError: If a source route or Routing header is not parsed,
or a Routing header with segments left has no parsed last
address.
"""
dst = ip.info.dst
if isinstance(ip, IPv4):
# NOTE: The header holds the next hop while the route has addresses
# left; once exhausted (RFC 791 section 3.1) it is the destination.
options = ip.info.get('options')
if options is None:
return dst
for code in (Enum_IPv4Option.LSR, Enum_IPv4Option.SSR):
for option in options.getlist(code):
if option.remaining:
dst = option.remaining[-1]
return dst
for header in ip.extension_headers.getlist(Enum_ExtensionHeader.IPv6_Route): # type: ignore[arg-type]
route = header.info
seg_left = route.get('seg_left')
if seg_left is None or route.get('__short_read__') is not None:
raise ProtocolError(f'{self.alias}: Routing header of {ip.alias} not parsed; give dst')
if not seg_left:
continue
# NOTE: Type 2 carries one address, the source routes a tuple. A
# truncated RPL address stays bytes; unparsed types carry none.
final = route.get('ip')
if isinstance(final, tuple) and final:
final = final[-1]
if not isinstance(final, ipaddress.IPv6Address):
raise ProtocolError(f'{self.alias}: final destination of Routing type '
f'{route.type} not parsed; give dst')
dst = final
# NOTE: A header the walk stopped on, at any depth, is unparsed too, as
# a malformed one is (#2480), and may have segments left.
if self._walk(ip)[0] == Enum_ExtensionHeader.IPv6_Route:
raise ProtocolError(f'{self.alias}: Routing header of {ip.alias} not parsed; give dst')
return dst
[docs]
def _upper_protocol(self, ip: 'IPv4 | IPv6') -> 'Enum_TransType':
"""Read the upper-layer protocol from an IP layer.
Args:
ip: IPv4 or IPv6 layer.
Returns:
The protocol past the extension headers.
Raises:
ProtocolError: If the walk ended at an unparsed header: none, or
an IPv6 extension header that was not walked, as past the
header limit, or a truncated Routing or Fragment header.
"""
return self._upper(ip)[0]
[docs]
def _upper_length(self, ip: 'IPv4 | IPv6', *, from_layer: 'bool' = True) -> 'int':
"""Read the upper-layer packet length from an IP layer.
Args:
ip: IPv4 or IPv6 layer.
from_layer: Whether the upper layer is the one ``ip`` carries,
rather than one given by the caller.
Returns:
The Length field of a UDP header that is present, else the length
past the IP header and extension headers.
Raises:
ProtocolError: If ``ip`` is a fragment, ends at an unparsed header,
or has a zero Payload Length and no Jumbo Payload option.
"""
if isinstance(ip, IPv4):
info4 = ip.info
if info4.offset or info4.flags.mf:
raise ProtocolError(f'{self.alias}: {ip.alias} fragment; give upper_length')
protocol, before = self._upper(ip)
return self._udp_length(ip, protocol, info4.hdr_len + before,
info4.len - info4.hdr_len - before, from_layer)
protocol, before = self._upper(ip)
info = ip.info
for frag in ip.extension_headers.getlist(Enum_ExtensionHeader.IPv6_Frag): # type: ignore[arg-type]
if frag.info.offset or frag.info.mf:
raise ProtocolError(f'{self.alias}: {ip.alias} fragment; give upper_length')
extent = info.payload
if not extent:
jumbo = jumbo_payload_length(info.next, ip.data[IPV6_HEADER_LEN:])
if jumbo is None:
raise ProtocolError(f'{self.alias}: Payload Length 0 and no Jumbo Payload '
'option; give upper_length')
extent = jumbo
# NOTE: ``info.hdr_len`` ends at the first Fragment header, so headers
# after it are not counted; the fixed header plus ``before`` is the offset.
return self._udp_length(ip, protocol, IPV6_HEADER_LEN + before, extent - before, from_layer)
@staticmethod
def _walk(ip: 'IPv6') -> 'tuple[Enum_TransType, int]':
"""Walk the extension headers of an IPv6 layer up to its upper layer.
A Mobility Header or HIP (:rfc:`6275#section-6.1.1`, :rfc:`7401#section-5.1.1`)
is the upper layer itself, and an Encapsulating Security Payload
(:rfc:`4303`) ends the walk, its upper layer being encrypted.
Args:
ip: IPv6 layer.
Returns:
The code the walk stopped on, and the octets of the headers ahead of
it. The code is an extension header's if ``ip`` did not parse that
header: a malformed one (:issue:`2477`), one past the header limit
or past a stop (:issue:`3067`), or one not captured, or cut short
by the capture (:issue:`2694`).
"""
code, before = ip.info.next, 0
for _, header in ip.extension_headers.items(multi=True):
if code in _TERMINAL_HEADERS or code == Enum_TransType.ESP:
break
# NOTE: A header the capture cut short is its schema's short read
# (#2694), and as unwalked as one not captured at all.
if header.info.get('__short_read__') is not None:
break
before += header.length
code = header.info.next
return code, before
def _upper(self, ip: 'IPv4 | IPv6') -> 'tuple[Enum_TransType, int]':
"""Read the upper-layer protocol and the octets of the headers ahead of it.
A Mobility Header or HIP (:rfc:`6275#section-6.1.1`, :rfc:`7401#section-5.1.1`)
is the upper layer itself. An Authentication Header (:rfc:`4302#section-2.2`)
is walked past, its Next Header naming the upper layer, as in IPv6.
Args:
ip: IPv4 or IPv6 layer.
Returns:
The protocol past the extension headers, and the octets of those
headers ahead of it.
Raises:
ProtocolError: If the walk ended at an unparsed header: none, an
IPv6 extension header that was not walked, an Authentication
Header cut short or in a non-first IPv4 fragment. An Encapsulating Security Payload
(:rfc:`4303`) is never walked, its upper layer being encrypted.
"""
if isinstance(ip, IPv4):
code, before, offset = ip.info.protocol, 0, ip.info.hdr_len
# NOTE: A non-first fragment's payload does not start with the AH its Protocol names.
while code == Enum_TransType.AH and not ip.info.offset:
# NOTE: Payload Len counts 32-bit words, less two (RFC 4302 section 2.2).
octets = ip.data[offset:offset + 2]
size = (octets[1] + 2) * 4 if len(octets) == 2 else 0
if not size or offset + size > len(ip.data):
raise ProtocolError(f'{self.alias}: Authentication Header of {ip.alias} '
'not parsed; give protocol and upper_length')
code = Enum_TransType.get(ip.data[offset])
before, offset = before + size, offset + size
# NOTE: The upper layer of an ESP (RFC 4303) is encrypted, so it is never walked.
unparsed = code in (Enum_TransType.AH, Enum_TransType.ESP)
else:
code, before = self._walk(ip)
unparsed = code not in _TERMINAL_HEADERS and self._is_extension_header(code)
# NOTE: What is missing is the protocol and the length, even where an
# unparsed header also hides an address (#2513).
if code is None or unparsed:
raise ProtocolError(f'{self.alias}: upper layer of {ip.alias} not parsed; '
'give protocol and upper_length')
return code, before
@staticmethod
def _is_extension_header(code: 'int') -> 'bool':
"""Tell whether ``code`` is an IPv6 extension header number."""
try:
Enum_ExtensionHeader(code)
except ValueError:
return False
return True
def _udp_length(self, ip: 'IPv4 | IPv6', protocol: 'int', hdr_len: 'int', length: 'int',
from_layer: 'bool') -> 'int':
"""Prefer the Length field of a UDP header to the length from the IP layer.
Args:
ip: IPv4 or IPv6 layer.
protocol: Upper-layer protocol.
hdr_len: Length of the IP header and extension headers.
length: Length from the IP layer.
from_layer: Whether the upper layer is the one ``ip`` carries.
Returns:
The UDP Length field (:rfc:`768`) if the upper layer is UDP and its
header is present with a non-zero field, ``length`` otherwise.
"""
if not from_layer or protocol != Enum_TransType.UDP:
return length
# NOTE: Octets 4 and 5 of the UDP header are its Length field. A zero
# field is a jumbogram's, so the IP layer's length stands.
start = hdr_len + 4
octets = ip.data[start:start + 2]
if len(octets) < 2:
return length
return int.from_bytes(octets, 'big') or length
[docs]
def compute_upper(ip: 'Schema_IPv4 | Schema_IPv6') -> 'Optional[bytes]':
"""Compute the pending checksum of the upper layer an IP header carries.
The upper layer is the payload of ``ip``, or a layer that headers of that
payload carry as constructed, whose ``make()`` left its checksum pending:
IPv6 extension headers, or Authentication Headers under IPv4
(:rfc:`4302#section-3.1.1`). Behind them, the pseudo-header is the one
:func:`verify_upper` derives from the packet parsed back: the address of a
Home Address option as the source (:rfc:`6275#section-6.1.1`,
:rfc:`6275#section-11.3.1`), and the final destination of a Routing header
(:rfc:`8200#section-8.1`) or of an IPv4 source route (:rfc:`791`).
Where that packet gives no pseudo-header, the checksum stays pending. So
none is computed for an IPv4 fragment, and behind a Fragment header only an
atomic fragment's is, since the checksum covers the reassembled packet
(:rfc:`8200#section-8.1`).
Args:
ip: IP header as :meth:`IPv4.make <pcapkit.protocols.internet.ipv4.protocol.IPv4.make>`
or :meth:`IPv6.make <pcapkit.protocols.internet.ipv6.protocol.IPv6.make>`
constructed it, holding its payload as given.
Returns:
The payload octets with the checksum computed, or :data:`None` if
there is none to compute.
.. versionadded:: 1.7.0
"""
payload = ip.payload
layer = payload # type: Any
through = _IPV6_EXT.klass
if isinstance(ip, Schema_IPv4):
# NOTE: A fragment's checksum covers the datagram (#2471).
if ip.flags['offset'] or ip.flags['mf']:
return None
code, through = ip.proto, _AH.klass
else:
code = ip.next
before = 0
# NOTE: Only the layers as constructed keep the pending flag; the walk of the packet
# parsed back then confirms where the upper layer is, as the receiver finds it.
while not (getattr(layer, '_checksum_pending', False) and layer.__index__() == code):
if not isinstance(layer, through):
return None
before += layer.length
code, layer = layer.info.next, getattr(layer.__header__, 'payload', None)
upper = cast('ProtocolBase', layer)
if before:
# NOTE: Quietly, as the IP layer parses these octets again and reports
# what they carry; a refusal leaves the checksum pending (#2824).
token = rebuilding.set(True)
try:
with CaughtByCaller(ProtocolError, FieldValueError):
packet = (IPv4 if isinstance(ip, Schema_IPv4) else IPv6)(ip.pack())
pseudo = IP_Pseudo.from_fields(ip=packet)
if pseudo._upper(packet) != (code, before): # pylint: disable=protected-access
return None
except (ProtocolError, FieldValueError):
return None
finally:
rebuilding.reset(token)
elif isinstance(ip, Schema_IPv4):
# NOTE: The header is parsed back for a source route's destination,
# quietly, as the IPv4 layer parses it again (cf. rebuilding).
token = rebuilding.set(True)
try:
header = IPv4(ip.pack()[:ip.vihl['ihl'] * 4])
finally:
rebuilding.reset(token)
# NOTE: The upper layer puts its own length in the pseudo-header.
pseudo = IP_Pseudo.from_fields(ip=header, protocol=code, upper_length=0)
else:
# NOTE: The upper layer follows the fixed header, so no extension header
# moves an address; it puts its own length in the pseudo-header.
pseudo = IP_Pseudo.from_fields(src=ip.src, dst=ip.dst, protocol=code, upper_length=0)
octets = cast('ProtocolBase', payload).data
computed = upper.from_data(upper.info, checksum=None, pseudo=pseudo).data
return octets[:before] + computed + octets[before + len(upper.data):]
[docs]
def verify_upper(ip: 'IPv4 | IPv6') -> 'None':
"""Verify the checksum of the upper layer ``ip`` carries over its pseudo-header.
The upper layer is the payload of ``ip``, past any Authentication Header
of IPv4, and for IPv6 also the Mobility Header or HIP its walk ends at
(:rfc:`6275#section-6.1.1`, :rfc:`7401#section-5.1.1`), which it parses as
an extension header. Each is verified if it defines
``_verify_pseudo_checksum``, against the
:class:`~pcapkit.protocols.misc.checksum.ip_pseudo.protocol.IP_Pseudo` of ``ip``,
or quietly against :data:`None` if that cannot be derived or names another
protocol.
Args:
ip: Parsed IPv4 or IPv6 layer.
.. versionchanged:: 1.7.0
Verifies a Mobility Header or HIP that IPv6 walks as an extension
header (:issue:`2813`). Where the pseudo-header cannot be derived, the
refusal logs nothing and installs no exception hook (:issue:`2859`).
"""
ah = _AH.klass
upper = ip.payload
# NOTE: IPv6 walks an AH as an extension header; IPv4 carries it as its payload.
while isinstance(upper, ah):
upper = upper.payload
layers = [upper]
if isinstance(ip, IPv6):
code, _ = IP_Pseudo._walk(ip) # pylint: disable=protected-access
if code in _TERMINAL_HEADERS:
# NOTE: The first such header is the one the walk ended at; none was parsed
# when the walk stopped short of it, as at a later fragment.
layers = ip.extension_headers.getlist(Enum_ExtensionHeader(code))[:1] + layers
pseudo = None # type: Optional[IP_Pseudo]
derived = False
for layer in layers:
verify = getattr(layer, '_verify_pseudo_checksum', None)
if verify is None:
continue
if not derived:
derived = True
# NOTE: Quietly, as the refusal is recorded as NO_PSEUDO_HEADER (#2859).
try:
with CaughtByCaller(ProtocolError, FieldValueError):
pseudo = IP_Pseudo.from_fields(ip=ip)
except (ProtocolError, FieldValueError):
pseudo = None
verify(pseudo if pseudo is not None and pseudo.protocol == layer.__index__() else None)