# -*- coding: utf-8 -*-
"""ESP - Encapsulating Security Payload
==========================================
.. module:: pcapkit.protocols.internet.esp.protocol
:mod:`pcapkit.protocols.internet.esp.protocol` contains
:class:`~pcapkit.protocols.internet.esp.protocol.ESP`,
which implements the extractor for Encapsulating
Security Payload (ESP) [*]_, whose structure is
described as below:
======= ========= ===================== ==============================================
Octets Bits Name Description
======= ========= ===================== ==============================================
0 0 ``esp.spi`` Security Parameters Index (SPI)
4 32 ``esp.seq`` Sequence Number
8 64 ``esp.payload_data`` Payload Data (variable, encrypted)
? ? ``esp.padding`` Padding (0-255 bytes, encrypted)
? ? ``esp.pad_len`` Pad Length (encrypted)
? ? ``esp.next`` Next Header (encrypted)
? ? ``esp.icv`` Integrity Check Value (ICV, variable)
======= ========= ===================== ==============================================
ESP is **not** self describing. :rfc:`4303` places the ``Pad Length`` and ``Next Header``
fields *inside* the ciphertext, and leaves the length of the ``Integrity
Check Value`` to be determined by the Security Association (SA), which is
negotiated out of band. Therefore:
* **Without** SA context, :class:`ESP` parses the ``SPI`` and ``Sequence
Number``, reports the remainder as an opaque encrypted payload, and says
so through :attr:`esp.status <pcapkit.protocols.internet.esp.data.ESP.status>`.
It does *not* guess at the trailer, and it does not raise.
* **With** SA context, :class:`ESP` splits off the ICV, verifies integrity,
decrypts, strips the padding using ``Pad Length``, and dispatches the
recovered plaintext to the next layer using ``Next Header`` -- so an
ESP tunnelled TCP segment decodes as TCP.
SA context is supplied through the generic, protocol keyed context channel
in :mod:`pcapkit.corekit.context`:
.. code-block:: python
import pcapkit
from pcapkit.protocols.internet.esp.protocol import (Cipher, ESPContext, Integrity,
SecurityAssociation)
sa = SecurityAssociation(
spi=0x4321,
encryption=Cipher.AES_CBC,
encryption_key=bytes.fromhex('90d382b410eeba7ad938c46cec1a82bf'),
integrity=Integrity.HMAC_SHA2_256_128,
integrity_key=bytes.fromhex('00' * 32),
destination='192.168.123.100', # optional, disambiguates several tunnels
)
extraction = pcapkit.extract('esp.pcap', context=ESPContext(sa))
Extended Sequence Numbers
-------------------------
An SA with ``esn=True`` uses the 64-bit sequence numbers of :rfc:`4303`
§2.2.1, whose high-order 32 bits are never transmitted yet enter the ICV
(§3.3.2.1), every combined mode suite's associated data and the implicit IV of
:rfc:`8750`. :class:`SecurityAssociation` infers them as a receiver does, by
Appendix A2.2, from the highest sequence number it has authenticated,
:attr:`SecurityAssociation.seq`, which each authentic packet advances
(Appendix A2.1). :attr:`esp.esn <pcapkit.protocols.internet.esp.data.ESP.esn>`
reports the number each packet was processed under, and :meth:`ESP.make` takes
it as ``esn``. A capture that starts after the SA was established needs
``seq`` set to the receiver's ``T`` at its start.
Registered Algorithms, and Supported Ones
-----------------------------------------
ESP has no algorithm registry of its own -- an SA's algorithms are negotiated
by IKEv2 -- so :class:`Cipher <pcapkit.const.esp.cipher.Cipher>` and
:class:`Integrity <pcapkit.const.esp.integrity.Integrity>` are generated from
the IKEv2 *transform ID* sub-registries and enumerate everything **IANA has
registered**: 3DES, AES-CTR, the AES-CCM and Camellia families,
ChaCha20-Poly1305, the implicit IV variants of :rfc:`8750`, the :rfc:`9227`
MGM suites, and the transforms long since deprecated.
**Registration is not support.** A member of either enumeration says only that
IANA assigned the transform an ID; what :mod:`pcapkit` can actually apply is
the separate, explicit :data:`CIPHER_SUITES` and :data:`INTEGRITY_SUITES`
tables, and :meth:`CipherSuite.get` / :meth:`IntegritySuite.get` refuse
anything outside them rather than half-working:
.. code-block:: python
>>> Cipher.get('ENCR_3DES') # registered, so the enum has it
<Cipher.ENCR_3DES: 3>
>>> CipherSuite.get('ENCR_3DES') # but ESP cannot apply it
Traceback (most recent call last):
...
pcapkit.utilities.exceptions.ProtocolError: ESP: unsupported encryption
algorithm: 'ENCR_3DES'; pcapkit implements ENCR_NULL, ENCR_AES_CBC,
ENCR_AES_CTR, ENCR_AES_CCM_8, ENCR_AES_CCM_12, ENCR_AES_CCM_16,
ENCR_AES_GCM_8, ENCR_AES_GCM_12, ENCR_AES_GCM_16, ENCR_NULL_AUTH_AES_GMAC,
ENCR_CAMELLIA_CBC, ENCR_CHACHA20_POLY1305, ENCR_AES_CCM_8_IIV,
ENCR_AES_GCM_16_IIV, ENCR_CHACHA20_POLY1305_IIV
Every algorithm but ``ENCR_NULL`` and the HMACs requires the optional
|cryptography|_ dependency (``pip install pypcapkit[crypto]``). :mod:`pcapkit`
imports and works without it; an SA that names such a suite simply degrades
to the opaque payload path, with a warning.
The rows marked ``yes`` are exactly the keys of :data:`CIPHER_SUITES`; a
``no`` row's note says why, and everything else the registry lists is
enumerated and rejected. :mod:`pcapkit` applies a transform only through a
|cryptography|_ primitive, so a mode |cryptography|_ lacks is left out.
============================== =================== ============ ===================================================
Encryption :rfc:`8221` status Implemented Notes
============================== =================== ============ ===================================================
``ENCR_NULL`` MUST yes :rfc:`2410`; needs no |cryptography|_
``ENCR_AES_CBC`` MUST yes :rfc:`3602`; 128/192/256-bit keys
``ENCR_AES_GCM_16`` MUST yes :rfc:`4106`; 8-octet explicit IV
``ENCR_AES_GCM_8`` -- yes :rfc:`4106`, 8-octet ICV
``ENCR_AES_GCM_12`` -- yes :rfc:`4106`, 12-octet ICV
``ENCR_AES_CCM_8`` SHOULD yes :rfc:`4309`; 3-octet salt
``ENCR_AES_CCM_12`` -- yes :rfc:`4309`, 12-octet ICV
``ENCR_AES_CCM_16`` -- yes :rfc:`4309`, 16-octet ICV
``ENCR_CHACHA20_POLY1305`` SHOULD yes :rfc:`7634`; 256-bit key
``ENCR_AES_CTR`` -- yes :rfc:`3686`; needs an integrity algorithm
``ENCR_NULL_AUTH_AES_GMAC`` -- yes :rfc:`4543`; authenticates, never encrypts
``ENCR_CAMELLIA_CBC`` -- yes :rfc:`5529`; 128/192/256-bit keys
``ENCR_AES_GCM_16_IIV`` -- yes :rfc:`8750`; IV from the sequence number
``ENCR_AES_CCM_8_IIV`` -- yes :rfc:`8750`; IV from the sequence number
``ENCR_CHACHA20_POLY1305_IIV`` -- yes :rfc:`8750`; IV from the sequence number
``ENCR_CAMELLIA_CTR`` -- **no** |cryptography|_ cannot run Camellia in CTR mode
``ENCR_CAMELLIA_CCM_*`` -- **no** |cryptography|_ has CCM for AES alone
``ENCR_*_MGM_*`` -- **no** :rfc:`9227`; no GOST primitive, :issue:`3009`
``ENCR_3DES`` SHOULD NOT **no** registered, deliberately omitted
DES, Blowfish, 3IDEA MUST NOT **no** registered, deliberately omitted
============================== =================== ============ ===================================================
"DES, Blowfish, 3IDEA" above covers ``ENCR_DES``, ``ENCR_DES_IV64``,
``ENCR_DES_IV32``, ``ENCR_BLOWFISH`` and ``ENCR_3IDEA``;
``ENCR_CAMELLIA_CCM_*`` covers the 8-, 12- and 16-octet ICV suites, and
``ENCR_*_MGM_*`` the Kuznyechik and Magma suites of :rfc:`9227`.
Likewise, the rows marked ``yes`` below are exactly the keys of
:data:`INTEGRITY_SUITES`:
============================ =================== ============ ===================================================
Integrity :rfc:`8221` status Implemented Notes
============================ =================== ============ ===================================================
``NONE`` MUST (AEAD only) yes for AEAD suites
``AUTH_HMAC_SHA2_256_128`` MUST yes :rfc:`4868`
``AUTH_HMAC_SHA2_512_256`` SHOULD yes :rfc:`4868`
``AUTH_HMAC_SHA2_384_192`` -- yes :rfc:`4868`
``AUTH_HMAC_SHA1_96`` MUST- yes :rfc:`2404`; still widely captured
``AUTH_AES_CMAC_96`` -- yes :rfc:`4494`; 128-bit key
``AUTH_AES_XCBC_96`` SHOULD / MAY **no** :rfc:`3566`; |cryptography|_ has no AES-XCBC-MAC
``AUTH_AES_*_GMAC`` MAY **no** AH only (:rfc:`4543` §5.3)
MD5, DES-MAC, KPDK-MD5 MUST NOT **no** registered, deliberately omitted
============================ =================== ============ ===================================================
``AUTH_AES_*_GMAC`` above covers the 128-, 192- and 256-bit key transforms,
which :rfc:`4543` §5.3 keeps to AH; ESP's GMAC is the combined mode
``ENCR_NULL_AUTH_AES_GMAC``. "MD5, DES-MAC, KPDK-MD5" covers ``AUTH_HMAC_MD5_96``,
``AUTH_HMAC_MD5_128``, ``AUTH_DES_MAC`` and ``AUTH_KPDK_MD5``. The registry
spells the "no integrity algorithm" transform ``NONE`` rather than
``AUTH_NONE``, and :attr:`Integrity.NONE
<pcapkit.const.esp.integrity.Integrity.NONE>` follows it.
Both enumerations additionally carry each transform's prefix-stripped spelling
as an alias, since that is how ESP and :rfc:`8221` name the algorithms, so
:attr:`Cipher.AES_CBC <pcapkit.const.esp.cipher.Cipher.AES_CBC>` and
:attr:`Cipher.ENCR_AES_CBC <pcapkit.const.esp.cipher.Cipher.ENCR_AES_CBC>`
are the same member.
Known Limitations
-----------------
* **An ESN is inferred, never re-synchronised.** :rfc:`4303` Appendix A3's
retries for a receiver that lost ``2**32`` packets are not made, so an SA whose
``seq`` is too far from a capture's sequence numbers fails their integrity
checks *cleanly*.
* **Traffic Flow Confidentiality (TFC) padding (§2.7) is not detected.**
TFC padding is indistinguishable from real payload without inspecting the
inner protocol's own length field, so it is handed to the next layer as
part of the plaintext.
* Re-parsing a capture with the same context starts from the shared SA's
advanced ``T``, so a second pass can infer other high-order bits and fail authentication.
* **Anti-replay is not performed.** :mod:`pcapkit` is an analyser, not a
receiver; the sequence number is reported, never checked, and an SA tracks
the window's upper edge only to infer an ESN.
* The ICV is *verified* but a failure is reported rather than raised, so
that one bad packet does not abort a capture.
.. [*] https://en.wikipedia.org/wiki/IPsec
.. versionadded:: 1.5.0
"""
import enum
import hashlib
import hmac
import ipaddress
import os
from typing import TYPE_CHECKING, overload
from pcapkit.const.esp.cipher import Cipher
from pcapkit.const.esp.integrity import Integrity
from pcapkit.const.reg.transtype import TransType as Enum_TransType
from pcapkit.corekit.context import ProtocolContext
from pcapkit.corekit.enum import EnumLookup
from pcapkit.corekit.infoclass import Info, info_final
from pcapkit.protocols.internet.esp.data import ESP as Data_ESP
from pcapkit.protocols.internet.esp.schema import ESP as Schema_ESP
from pcapkit.protocols.internet.ipsec.protocol import IPsec
from pcapkit.protocols.internet.ipv6_ext.protocol import IPv6_Ext
from pcapkit.protocols.schema import Schema
from pcapkit.utilities.exceptions import ProtocolError, ProtocolUnbound, UnsupportedCall
from pcapkit.utilities.warnings import ProtocolWarning, warn
__all__ = ['ESP', 'ESPStatus', 'Cipher', 'Integrity', 'CipherSuite', 'IntegritySuite',
'CIPHER_SUITES', 'INTEGRITY_SUITES', 'SecurityAssociation', 'ESPContext']
if TYPE_CHECKING:
from ipaddress import IPv4Address, IPv6Address
from typing import IO, Any, NoReturn, Optional, Type
from typing_extensions import Literal
from pcapkit.protocols.protocol import ProtocolBase
#: Cached |cryptography|_ primitives, see :func:`load_cryptography`.
#: :data:`NotImplemented` means the import has not been attempted yet, and
#: :data:`None` that it was attempted and |cryptography|_ is not installed, and
#: a tuple holds the loaded primitives, so a missing dependency is not retried
#: on every frame.
_CRYPTO = NotImplemented # type: Any
[docs]
def load_cryptography() -> 'Optional[tuple[Any, Any, Any, Type[Exception], Any, Any, Any]]':
"""Load the optional |cryptography|_ primitives.
Returns:
A 7-tuple of ``(Cipher, algorithms, modes, InvalidTag, aead, cmac,
Camellia)``: the first three taken from
:mod:`cryptography.hazmat.primitives.ciphers`,
:exc:`cryptography.exceptions.InvalidTag`, the
:mod:`cryptography.hazmat.primitives.ciphers.aead` and
:mod:`cryptography.hazmat.primitives.cmac` modules, and the Camellia
block cipher, from :mod:`cryptography.hazmat.decrepit.ciphers.algorithms`
where the installed release keeps it there; or :data:`None` when
|cryptography|_ is not installed.
Notes:
The import is attempted at most once and the outcome is cached, so
that a capture full of ESP packets does not pay for a failing import
on every frame.
.. versionchanged:: 1.10.0
The tuple gains ``aead``, ``cmac`` and ``Camellia`` (:issue:`2958`).
"""
global _CRYPTO # pylint: disable=global-statement
if _CRYPTO is NotImplemented:
try:
from cryptography.exceptions import \
InvalidTag as _InvalidTag # pylint: disable=import-outside-toplevel
from cryptography.hazmat.primitives import \
cmac as _crypto_cmac # pylint: disable=import-outside-toplevel
from cryptography.hazmat.primitives.ciphers import \
Cipher as _CryptoCipher # pylint: disable=import-outside-toplevel
from cryptography.hazmat.primitives.ciphers import \
aead as _crypto_aead # pylint: disable=import-outside-toplevel
from cryptography.hazmat.primitives.ciphers import \
algorithms as _crypto_algorithms # pylint: disable=import-outside-toplevel
from cryptography.hazmat.primitives.ciphers import \
modes as _crypto_modes # pylint: disable=import-outside-toplevel
except ImportError:
_CRYPTO = None
else:
try:
from cryptography.hazmat.decrepit.ciphers.algorithms import \
Camellia as _Camellia # pylint: disable=import-outside-toplevel
except ImportError:
# NOTE: releases before 47.0.0 keep Camellia beside AES, and later ones warn
# on that spelling, so it is only the fallback.
_Camellia = _crypto_algorithms.Camellia
_CRYPTO = (_CryptoCipher, _crypto_algorithms, _crypto_modes, _InvalidTag,
_crypto_aead, _crypto_cmac, _Camellia)
return _CRYPTO
##############################################################################
# Algorithm support.
##############################################################################
[docs]
def _resolve(registry: 'Type[Cipher] | Type[Integrity]', value: 'Any',
prefix: 'str', kind: 'str') -> 'Any':
"""Resolve ``value`` to a member of an IKEv2 transform registry.
Args:
registry: :class:`Cipher <pcapkit.const.esp.cipher.Cipher>` or
:class:`Integrity <pcapkit.const.esp.integrity.Integrity>`.
value: A member of ``registry``, an IKEv2 transform ID, or a
transform name.
prefix: Prefix the registry spells its names with, i.e. ``'ENCR_'``
or ``'AUTH_'``.
kind: Word naming the registry for the error message, i.e.
``'encryption'`` or ``'integrity'``.
Returns:
The corresponding member of ``registry``.
Raises:
ProtocolError: If ``value`` names nothing the registry holds.
Notes:
Both enumerations carry each transform's prefix-stripped spelling as
an alias, so a plain lookup already accepts ``'AES_CBC'`` as well as
``'ENCR_AES_CBC'``. ``prefix`` is still needed for the few names that
are no Python identifier once stripped, and so have no alias --
``ENCR_3DES`` and ``ENCR_3IDEA``.
Resolution is deliberately separate from *support*: it answers only
whether IANA registered the transform. See :meth:`CipherSuite.get`.
"""
if isinstance(value, registry):
return value
if isinstance(value, int):
try:
return registry(value)
except ValueError:
raise ProtocolError(f'ESP: unknown {kind} algorithm: {value!r}') from None
name = str(value).upper().replace('-', '_')
for candidate in (name, f'{prefix}{name}'):
if candidate in registry.__members__:
return registry[candidate]
raise ProtocolError(f'ESP: unknown {kind} algorithm: {value!r}')
[docs]
@info_final
class CipherSuite(Info):
"""Parameters of an ESP encryption algorithm :mod:`pcapkit` implements.
A member of :class:`Cipher <pcapkit.const.esp.cipher.Cipher>` records only
that IANA registered the transform. This records how to apply it, and
membership of :data:`CIPHER_SUITES` is what "supported" means -- see
:ref:`esp-algorithm-support`.
.. versionchanged:: 1.10.0
New field ``implicit_iv`` (:issue:`2963`).
"""
#: Encryption algorithm the suite describes.
cipher: 'Cipher'
#: Whether the algorithm is a combined mode (AEAD) algorithm, i.e. one
#: that provides its own integrity protection.
is_aead: 'bool'
#: Length of the explicit IV carried at the head of the payload data.
iv_length: 'int'
#: Whether the IV is the 64-bit sequence number rather than transmitted
#: [:rfc:`8750` §4], so that :attr:`iv_length` is 0.
implicit_iv: 'bool'
#: Cipher block size, in octets. :rfc:`4303` §2.4 additionally requires
#: the ciphertext to be a multiple of 4 octets, which is why
#: :meth:`ESP.make` aligns to ``max(block_size, 4)`` rather than to this
#: value alone.
block_size: 'int'
#: Length of the ICV the algorithm itself produces (AEAD only).
icv_length: 'int'
#: Permitted lengths of the key, in octets, excluding any salt.
key_sizes: 'tuple[int, ...]'
#: Length of the salt taken from the end of the keying material
#: [:rfc:`4106` §8.1]; for AES-CTR, the counter block's nonce
#: [:rfc:`3686` §5.1].
salt_length: 'int'
#: Whether the algorithm needs the optional |cryptography|_ dependency.
requires_cryptography: 'bool'
[docs]
@classmethod
def get(cls, value: 'Cipher | str | int') -> 'CipherSuite':
"""Look up how to apply an encryption algorithm.
Args:
value: A :class:`Cipher <pcapkit.const.esp.cipher.Cipher>` member,
an IKEv2 transform ID, or a name such as ``'AES-CBC'``,
``'aes_cbc'`` or ``'ENCR_AES_CBC'``.
Returns:
The suite describing how to apply the algorithm.
Raises:
ProtocolError: If ``value`` names no registered algorithm, or
names one :mod:`pcapkit` does not implement. The registry is
far larger than the set of suites here, so the second case is
the common one.
"""
cipher = _resolve(Cipher, value, 'ENCR_', 'encryption')
suite = CIPHER_SUITES.get(cipher)
if suite is None:
raise ProtocolError(f'ESP: unsupported encryption algorithm: {cipher.name!r}; pcapkit '
f'implements {", ".join(key.name for key in CIPHER_SUITES)}')
return suite
[docs]
@info_final
class IntegritySuite(Info):
"""Parameters of an ESP integrity algorithm :mod:`pcapkit` implements.
As with :class:`CipherSuite`, membership of :data:`INTEGRITY_SUITES` --
not membership of the IANA registry -- is what makes an algorithm
supported.
.. versionchanged:: 1.10.0
New fields ``mac`` and ``requires_cryptography``; ``digest`` is
:data:`None` for a MAC that is not an HMAC (:issue:`2958`).
"""
#: Integrity algorithm the suite describes.
integrity: 'Integrity'
#: Hash the HMAC runs, named for :mod:`hashlib`, or :data:`None` when
#: :attr:`mac` is not ``'hmac'``.
digest: 'Optional[str]'
#: Length of the truncated ICV, in octets.
icv_length: 'int'
#: Key length required by the specification, in octets.
key_size: 'int'
#: MAC the ICV truncates, ``'hmac'`` [:rfc:`2104`] or ``'cmac'``
#: [:rfc:`4493`], or :data:`None` when the algorithm computes no ICV of
#: its own.
mac: 'Optional[Literal["hmac", "cmac"]]'
#: Whether the algorithm needs the optional |cryptography|_ dependency.
requires_cryptography: 'bool'
[docs]
@classmethod
def get(cls, value: 'Integrity | str | int') -> 'IntegritySuite':
"""Look up how to apply an integrity algorithm.
Args:
value: An :class:`Integrity
<pcapkit.const.esp.integrity.Integrity>` member, an IKEv2
transform ID, or a name such as ``'HMAC-SHA-256-128'``,
``'hmac_sha2_256_128'`` or ``'AUTH_HMAC_SHA2_256_128'``.
Returns:
The suite describing how to apply the algorithm.
Raises:
ProtocolError: If ``value`` names no registered algorithm, or
names one :mod:`pcapkit` does not implement.
"""
if isinstance(value, str):
# accept the RFC 4868 spelling ``HMAC_SHA_256_128`` as well as the
# IKEv2 spelling ``HMAC_SHA2_256_128``
name = value.upper().replace('-', '_').replace('HMAC_SHA_', 'HMAC_SHA2_')
if name in ('HMAC_SHA2_1_96', 'HMAC_SHA2_1'):
name = 'HMAC_SHA1_96'
value = name
integrity = _resolve(Integrity, value, 'AUTH_', 'integrity')
suite = INTEGRITY_SUITES.get(integrity)
if suite is None:
raise ProtocolError(f'ESP: unsupported integrity algorithm: {integrity.name!r}; '
f'pcapkit implements '
f'{", ".join(key.name for key in INTEGRITY_SUITES)}')
return suite
#: Encryption algorithms :mod:`pcapkit` implements, keyed by IKEv2 transform.
#: This table -- not :class:`Cipher <pcapkit.const.esp.cipher.Cipher>`, which
#: is the whole IANA registry -- defines what an SA may name.
CIPHER_SUITES = {
Cipher.ENCR_NULL: CipherSuite(
cipher=Cipher.ENCR_NULL, is_aead=False, iv_length=0, implicit_iv=False,
block_size=1, icv_length=0, key_sizes=(0,), salt_length=0,
requires_cryptography=False,
),
Cipher.ENCR_AES_CBC: CipherSuite(
cipher=Cipher.ENCR_AES_CBC, is_aead=False, iv_length=16, implicit_iv=False,
block_size=16, icv_length=0, key_sizes=(16, 24, 32), salt_length=0,
requires_cryptography=True,
),
Cipher.ENCR_AES_CTR: CipherSuite(
cipher=Cipher.ENCR_AES_CTR, is_aead=False, iv_length=8, implicit_iv=False,
block_size=1, icv_length=0, key_sizes=(16, 24, 32), salt_length=4,
requires_cryptography=True,
),
Cipher.ENCR_AES_CCM_8: CipherSuite(
cipher=Cipher.ENCR_AES_CCM_8, is_aead=True, iv_length=8, implicit_iv=False,
block_size=1, icv_length=8, key_sizes=(16, 24, 32), salt_length=3,
requires_cryptography=True,
),
Cipher.ENCR_AES_CCM_12: CipherSuite(
cipher=Cipher.ENCR_AES_CCM_12, is_aead=True, iv_length=8, implicit_iv=False,
block_size=1, icv_length=12, key_sizes=(16, 24, 32), salt_length=3,
requires_cryptography=True,
),
Cipher.ENCR_AES_CCM_16: CipherSuite(
cipher=Cipher.ENCR_AES_CCM_16, is_aead=True, iv_length=8, implicit_iv=False,
block_size=1, icv_length=16, key_sizes=(16, 24, 32), salt_length=3,
requires_cryptography=True,
),
Cipher.ENCR_AES_GCM_8: CipherSuite(
cipher=Cipher.ENCR_AES_GCM_8, is_aead=True, iv_length=8, implicit_iv=False,
block_size=1, icv_length=8, key_sizes=(16, 24, 32), salt_length=4,
requires_cryptography=True,
),
Cipher.ENCR_AES_GCM_12: CipherSuite(
cipher=Cipher.ENCR_AES_GCM_12, is_aead=True, iv_length=8, implicit_iv=False,
block_size=1, icv_length=12, key_sizes=(16, 24, 32), salt_length=4,
requires_cryptography=True,
),
Cipher.ENCR_AES_GCM_16: CipherSuite(
cipher=Cipher.ENCR_AES_GCM_16, is_aead=True, iv_length=8, implicit_iv=False,
block_size=1, icv_length=16, key_sizes=(16, 24, 32), salt_length=4,
requires_cryptography=True,
),
Cipher.ENCR_NULL_AUTH_AES_GMAC: CipherSuite(
cipher=Cipher.ENCR_NULL_AUTH_AES_GMAC, is_aead=True, iv_length=8, implicit_iv=False,
block_size=1, icv_length=16, key_sizes=(16, 24, 32), salt_length=4,
requires_cryptography=True,
),
Cipher.ENCR_CAMELLIA_CBC: CipherSuite(
cipher=Cipher.ENCR_CAMELLIA_CBC, is_aead=False, iv_length=16, implicit_iv=False,
block_size=16, icv_length=0, key_sizes=(16, 24, 32), salt_length=0,
requires_cryptography=True,
),
Cipher.ENCR_CHACHA20_POLY1305: CipherSuite(
cipher=Cipher.ENCR_CHACHA20_POLY1305, is_aead=True, iv_length=8, implicit_iv=False,
block_size=1, icv_length=16, key_sizes=(32,), salt_length=4,
requires_cryptography=True,
),
Cipher.ENCR_AES_CCM_8_IIV: CipherSuite(
cipher=Cipher.ENCR_AES_CCM_8_IIV, is_aead=True, iv_length=0, implicit_iv=True,
block_size=1, icv_length=8, key_sizes=(16, 24, 32), salt_length=3,
requires_cryptography=True,
),
Cipher.ENCR_AES_GCM_16_IIV: CipherSuite(
cipher=Cipher.ENCR_AES_GCM_16_IIV, is_aead=True, iv_length=0, implicit_iv=True,
block_size=1, icv_length=16, key_sizes=(16, 24, 32), salt_length=4,
requires_cryptography=True,
),
Cipher.ENCR_CHACHA20_POLY1305_IIV: CipherSuite(
cipher=Cipher.ENCR_CHACHA20_POLY1305_IIV, is_aead=True, iv_length=0, implicit_iv=True,
block_size=1, icv_length=16, key_sizes=(32,), salt_length=4,
requires_cryptography=True,
),
} # type: dict[Cipher, CipherSuite]
#: Integrity algorithms :mod:`pcapkit` implements, keyed by IKEv2 transform.
#: :attr:`Integrity.NONE <pcapkit.const.esp.integrity.Integrity.NONE>` is here
#: because "no separate integrity algorithm" is a supported configuration --
#: it is what an AEAD suite, and an unprotected SA, use.
INTEGRITY_SUITES = {
Integrity.NONE: IntegritySuite(
integrity=Integrity.NONE, digest=None, icv_length=0, key_size=0,
mac=None, requires_cryptography=False,
),
Integrity.AUTH_HMAC_SHA1_96: IntegritySuite(
integrity=Integrity.AUTH_HMAC_SHA1_96, digest='sha1', icv_length=12, key_size=20,
mac='hmac', requires_cryptography=False,
),
Integrity.AUTH_AES_CMAC_96: IntegritySuite(
integrity=Integrity.AUTH_AES_CMAC_96, digest=None, icv_length=12, key_size=16,
mac='cmac', requires_cryptography=True,
),
Integrity.AUTH_HMAC_SHA2_256_128: IntegritySuite(
integrity=Integrity.AUTH_HMAC_SHA2_256_128, digest='sha256', icv_length=16, key_size=32,
mac='hmac', requires_cryptography=False,
),
Integrity.AUTH_HMAC_SHA2_384_192: IntegritySuite(
integrity=Integrity.AUTH_HMAC_SHA2_384_192, digest='sha384', icv_length=24, key_size=48,
mac='hmac', requires_cryptography=False,
),
Integrity.AUTH_HMAC_SHA2_512_256: IntegritySuite(
integrity=Integrity.AUTH_HMAC_SHA2_512_256, digest='sha512', icv_length=32, key_size=64,
mac='hmac', requires_cryptography=False,
),
} # type: dict[Integrity, IntegritySuite]
##############################################################################
# Payload processing status.
##############################################################################
[docs]
class ESPStatus(EnumLookup, enum.IntEnum):
"""Outcome of ESP payload processing.
``get`` / ``get_all`` come from :class:`~pcapkit.corekit.enum.EnumLookup`;
the class defines no ``_missing_``, so an unknown value raises
:exc:`ValueError`.
"""
#: The payload was decrypted and its trailer recovered.
DECRYPTED = 0
#: No Security Association matched the packet's SPI, so the payload is
#: reported as opaque ciphertext. This is the expected state for a
#: capture taken without keys, and is **not** an error.
NO_SA = 1
#: A Security Association matched, but the ICV did not verify.
AUTH_FAILED = 2
#: A Security Association matched and the packet was authentic (or
#: unauthenticated), but decryption did not yield a self consistent
#: :rfc:`4303` trailer -- most commonly a wrong encryption key.
DECRYPT_FAILED = 3
#: The packet is shorter than the Security Association says it must be.
TRUNCATED = 4
#: A Security Association matched but its algorithms cannot be applied,
#: e.g. because the optional |cryptography|_ dependency is missing.
UNSUPPORTED = 5
##############################################################################
# Security Association.
##############################################################################
[docs]
class SecurityAssociation:
"""An inbound IPsec Security Association, as far as ESP parsing needs one.
Args:
spi: Security Parameters Index the SA applies to; :data:`None`
matches any SPI, which is convenient for a capture holding a
single tunnel.
encryption: Encryption algorithm, see :meth:`CipherSuite.get`. Must
be one :mod:`pcapkit` implements; being in the IANA registry is
not enough.
encryption_key: Encryption keying material. For a suite with a
:attr:`~CipherSuite.salt_length`, this is the key followed by the
salt, as IKEv2 splits its KEYMAT [:rfc:`4106` §8.1, :rfc:`4309`
§7.1, :rfc:`4543` §5.4, :rfc:`3686` §5.1, :rfc:`7634` §2],
unless ``salt`` is given separately.
salt: Salt, or AES-CTR's nonce, when not appended to
``encryption_key``.
integrity: Integrity algorithm, see :meth:`IntegritySuite.get`. Must
be :attr:`Integrity.NONE <pcapkit.const.esp.integrity.Integrity.NONE>`
for an AEAD suite, which provides its own, and must not be for
``ENCR_AES_CTR`` [:rfc:`3686` §3.3].
integrity_key: Integrity key. ``AUTH_AES_CMAC_96`` refuses one of the
wrong length with :exc:`~pcapkit.utilities.exceptions.ProtocolError`,
since AES rejects any length but its own, where an HMAC takes a key
of any length and so only warns.
icv_length: Override for the ICV length, in octets. Needed for the
long standing implementation bug noted in :rfc:`8221` §6, where
``AUTH_HMAC_SHA2_256_128`` is truncated to 96 rather than 128
bits.
destination: Outer destination address the SA applies to. IPsec keys
an SA by ``(SPI, destination, protocol)``, and supplying the
address is what lets several tunnels sharing an SPI be told
apart. Matched only when the outer destination is known to
:mod:`pcapkit`; see :meth:`ESP.read`. Must not be a :obj:`bool`
-- see ``Raises`` below.
strict: Whether a padding pattern that does not follow the
monotonically increasing sequence of :rfc:`4303` §2.4 should be
treated as a decryption failure. Only applied when nothing else
authenticated the packet, since a verified ICV or AEAD tag is a
far better signal than the padding is. Some implementations pad
with zeros; set to :data:`False` for those.
esn: Whether the SA uses Extended Sequence Numbers [:rfc:`4303`
§2.2.1], whose high-order 32 bits are not transmitted; see
:meth:`extend`.
seq: Highest sequence number the SA has authenticated, ``T`` of
:rfc:`4303` Appendix A2, from which :meth:`extend` infers the
high-order bits. 0, the receiver's state when an SA is
established [:rfc:`4303` §3.4.3], suits a capture taken from
then; a later capture needs the receiver's state at its start.
window: Size ``W`` of the anti-replay window, in packets; 64 is
:rfc:`4303` §3.4.3's default, and Appendix A2 bounds it at
``2**31``. Only :meth:`extend` uses it.
Raises:
ProtocolError: If the algorithms or key lengths are inconsistent,
``seq`` does not fit in 32 bits, or in 64 with ``esn``,
``window`` is outside ``1`` to ``2**31``, or
``destination`` is a :obj:`bool` -- :obj:`bool` is an
:class:`int` subclass, and :func:`ipaddress.ip_address` treats
any :class:`int` below ``2**32`` as IPv4, so without this check
``destination=True`` would silently become
``IPv4Address('0.0.0.1')`` with no exception and no warning; pass
``int(destination)`` if the numeric value is what is wanted.
Important:
Key material is held in *private* attributes of this object, and is
exposed only through :attr:`encryption_key` / :attr:`integrity_key`.
It is deliberately absent from :meth:`~object.__repr__`, and it is
never copied into the ESP data model, which is the only thing that
reaches :meth:`Info.to_dict <pcapkit.corekit.infoclass.Info.to_dict>`
and hence the output dumpers.
Note:
:attr:`seq` is state that every packet the SA authenticates advances,
a constructed one included. A context holds its SAs by reference, so
two extractions given the same SA share it.
.. versionchanged:: 1.10.0
New arguments ``esn``, ``seq`` and ``window``, and the ``seq`` of
:meth:`compute_icv`, :meth:`decrypt` and :meth:`encrypt` is the full
sequence number, 64 bits with ``esn`` (:issue:`2963`).
"""
##########################################################################
# Properties.
##########################################################################
@property
def encryption_key(self) -> 'bytes':
"""Encryption key, excluding any AEAD salt."""
return self.__key__
@property
def salt(self) -> 'bytes':
"""Salt, or AES-CTR's counter block nonce."""
return self.__salt__
@property
def integrity_key(self) -> 'bytes':
"""Integrity key."""
return self.__integrity_key__
@property
def icv_length(self) -> 'int':
"""Length of the ICV field carried on the wire, in octets."""
if self.__icv_length__ is not None:
return self.__icv_length__
if self.cipher_suite.is_aead:
return self.cipher_suite.icv_length
return self.integrity_suite.icv_length
@property
def authenticated(self) -> 'bool':
"""Whether the SA provides any integrity protection at all."""
return self.cipher_suite.is_aead or self.integrity is not Integrity.NONE
@property
def seq(self) -> 'int':
"""Highest sequence number the SA has authenticated, ``T`` of :rfc:`4303` Appendix A2."""
return self.__seq__
##########################################################################
# Methods.
##########################################################################
[docs]
def matches(self, spi: 'int',
destination: 'Optional[IPv4Address | IPv6Address]' = None) -> 'int':
"""Score how well the SA matches a packet.
Args:
spi: SPI read from the packet.
destination: Outer destination address, if known.
Returns:
A non-negative score, where a higher score is a better match, or
``-1`` when the SA does not apply at all. An SA pinned to this
exact SPI outranks a wildcard one, and an SA whose destination
was confirmed outranks one whose destination is unconstrained.
"""
if self.spi is not None and self.spi != spi:
return -1
score = 2 if self.spi is not None else 0
if self.destination is not None:
if destination is None:
# The outer destination is unknown here, so the constraint
# cannot be confirmed; treat the SA as a weaker candidate
# rather than discarding it.
return score
if self.destination != destination:
return -1
score += 1
return score
[docs]
def unavailable(self) -> 'Optional[str]':
"""Say whether the SA's algorithms can be applied at all.
This is checked before a packet is processed, so that a missing
optional dependency is reported as a configuration problem once per
packet rather than raised as an error from
:meth:`decrypt` -- it is not a defect in the packet.
Returns:
A reason the SA cannot be applied, or :data:`None` when it can.
"""
if self.cipher_suite.requires_cryptography and load_cryptography() is None:
return f'{self._missing_cryptography("encryption")} (pip install pypcapkit[crypto])'
if self.integrity_suite.requires_cryptography and load_cryptography() is None:
return f'{self._missing_cryptography("integrity")} (pip install pypcapkit[crypto])'
return None
[docs]
def extend(self, seq: 'int') -> 'int':
"""Recover the full sequence number of a packet from its Sequence Number field.
Under Extended Sequence Numbers, the high-order 32 bits ``Seqh`` are
chosen by :rfc:`4303` Appendix A2.2 from :attr:`seq` and
:attr:`window`, modulo ``2**32`` as its Appendix A2.3 computes them;
without, the field is the whole number.
Args:
seq: Sequence Number field of the packet, ``Seql``.
Returns:
The full sequence number.
Raises:
ProtocolError: If ``seq`` does not fit in 32 bits.
"""
if not 0 <= seq <= 0xFFFFFFFF:
raise ProtocolError(f'ESP: invalid sequence number: {seq!r} does not fit in 32 bits')
if not self.esn:
return seq
high, low = self.__seq__ >> 32, self.__seq__ & 0xFFFFFFFF
bottom = (low - self.window + 1) % 0x100000000
if low >= self.window - 1:
# Case A: the window lies in one subspace, and a packet below it is in the next.
high = high if seq >= bottom else high + 1
else:
# Case B: the window spans the previous subspace and this one.
high = high - 1 if seq >= bottom else high
return ((high % 0x100000000) << 32) | seq
[docs]
def advance(self, seq: 'int') -> 'None':
"""Record that a packet authenticated, moving :attr:`seq` up to it.
This is :rfc:`4303` Appendix A2.1's update of ``T``; the bitmap of
packets seen within the window is not kept, since anti-replay is not
performed.
Args:
seq: Full sequence number of the packet, as :meth:`extend` gives it.
Raises:
ProtocolError: If ``seq`` does not fit in 32 bits, or in 64 with
:attr:`esn`.
"""
self._split_seq(seq)
if seq <= self.__seq__:
return
self.__seq__ = seq # type: int
[docs]
def compute_icv(self, spi: 'int', seq: 'int', body: 'bytes') -> 'bytes':
"""Compute the ICV over the integrity protected part of the packet.
The integrity computation of :rfc:`4303` §2.8 covers the SPI, the
Sequence Number, the payload data (including any explicit IV) and
the explicit ESP trailer -- that is, everything transmitted except
the ICV itself -- and, under ESN, the high-order 32 bits of the
sequence number after the trailer [:rfc:`4303` §3.3.2.1].
Args:
spi: Security Parameters Index.
seq: Full sequence number, see :meth:`extend`.
body: Payload data and ESP trailer, as transmitted.
Returns:
The truncated ICV.
Raises:
ProtocolError: If the SA has no separate integrity algorithm,
``seq`` does not fit, or |cryptography|_ is needed and
unavailable.
"""
suite = self.integrity_suite
low, high = self._split_seq(seq)
message = spi.to_bytes(4, 'big') + low + body + high
if suite.mac == 'cmac':
_, algorithms, _, _, _, cmac, _ = self._cryptography('integrity')
mac = cmac.CMAC(algorithms.AES(self.__integrity_key__))
mac.update(message)
return mac.finalize()[:self.icv_length]
digest = suite.digest
if suite.mac is None or digest is None:
raise ProtocolError(f'ESP: integrity algorithm computes no ICV: '
f'{self.integrity.name!r}')
return hmac.new(self.__integrity_key__, message,
getattr(hashlib, digest)).digest()[:self.icv_length]
[docs]
def decrypt(self, spi: 'int', seq: 'int', body: 'bytes', icv: 'bytes') -> 'bytes':
"""Decrypt the payload data of an ESP packet.
Args:
spi: Security Parameters Index.
seq: Full sequence number, see :meth:`extend`.
body: Payload data as transmitted, i.e. the explicit IV (if the
algorithm uses one) followed by the ciphertext, which
``ENCR_NULL_AUTH_AES_GMAC`` leaves in clear.
icv: ICV as transmitted; for an AEAD algorithm this is the
authentication tag and is an input to the decryption.
Returns:
The plaintext, i.e. the inner payload followed by the ESP
trailer (padding, pad length, next header).
Raises:
ProtocolError: If the payload is malformed for the algorithm,
``seq`` does not fit, or |cryptography|_ is needed and
unavailable.
cryptography.exceptions.InvalidTag: If an AEAD tag fails to
verify -- typically a wrong key.
"""
cipher = self.encryption
suite = self.cipher_suite
self._split_seq(seq)
if cipher is Cipher.ENCR_NULL:
return body
crypto = self._cryptography('encryption')
iv_length = suite.iv_length
if len(body) < iv_length:
raise ProtocolError(f'ESP: payload too short: {len(body)!r} octets, less than the '
f'{iv_length}-octet {cipher.name} IV')
iv, ciphertext = body[:iv_length], body[iv_length:]
if not suite.is_aead:
if suite.block_size > 1 and (not ciphertext or len(ciphertext) % suite.block_size):
raise ProtocolError(f'ESP: invalid ciphertext length: {len(ciphertext)!r} '
f'octets is not a positive multiple of the '
f'{suite.block_size}-octet {cipher.name} block size')
decryptor = self._cipher(crypto, iv).decryptor()
return decryptor.update(ciphertext) + decryptor.finalize()
if not icv:
raise ProtocolError(f'ESP: missing authentication tag: {cipher.name} requires '
f'one, but the packet carries no ICV')
nonce, aad = self._aead_inputs(spi, seq, iv)
if cipher is Cipher.ENCR_NULL_AUTH_AES_GMAC:
# RFC 4543 Figure 4, as erratum 62 confirms: GMAC authenticates the
# IV and the cleartext payload as associated data, encrypting nothing.
self._open(crypto, nonce, aad + body, b'', icv)
return ciphertext
return self._open(crypto, nonce, aad, ciphertext, icv)
[docs]
def encrypt(self, spi: 'int', seq: 'int', plaintext: 'bytes',
iv: 'Optional[bytes]' = None) -> 'tuple[bytes, bytes]':
"""Encrypt the payload data of an ESP packet.
This is the inverse of :meth:`decrypt`, used by :meth:`ESP.make`.
Args:
spi: Security Parameters Index.
seq: Full sequence number, see :meth:`extend`.
plaintext: Inner payload followed by the ESP trailer.
iv: Explicit IV; a random one is generated when not given, and
an implicit IV suite takes none.
Returns:
A 2-tuple of the payload data as it goes on the wire (explicit
IV followed by ciphertext) and the AEAD tag, which is empty for
a non-AEAD algorithm.
Raises:
ProtocolError: If ``iv`` is of the wrong length, ``seq`` does not
fit, or |cryptography|_ is needed and unavailable.
"""
cipher = self.encryption
suite = self.cipher_suite
self._split_seq(seq)
if cipher is Cipher.ENCR_NULL:
return plaintext, b''
crypto = self._cryptography('encryption')
iv_length = suite.iv_length
if iv is None:
iv = os.urandom(iv_length)
elif len(iv) != iv_length:
if suite.implicit_iv:
raise ProtocolError(f'ESP: invalid IV: {cipher.name} takes its IV from the '
f'sequence number (RFC 8750 s4), got {len(iv)!r} octets')
raise ProtocolError(f'ESP: invalid IV: {cipher.name} needs a {iv_length}-octet IV, '
f'got {len(iv)!r} octets')
if not suite.is_aead:
encryptor = self._cipher(crypto, iv).encryptor()
return iv + encryptor.update(plaintext) + encryptor.finalize(), b''
nonce, aad = self._aead_inputs(spi, seq, iv)
if cipher is Cipher.ENCR_NULL_AUTH_AES_GMAC:
_, tag = self._seal(crypto, nonce, aad + iv + plaintext, b'')
return iv + plaintext, tag
ciphertext, tag = self._seal(crypto, nonce, aad, plaintext)
return iv + ciphertext, tag
##########################################################################
# Data models.
##########################################################################
def __init__(self, spi: 'Optional[int]' = None, *,
encryption: 'Cipher | str | int' = Cipher.ENCR_NULL,
encryption_key: 'bytes' = b'',
salt: 'Optional[bytes]' = None,
integrity: 'Integrity | str | int' = Integrity.NONE,
integrity_key: 'bytes' = b'',
icv_length: 'Optional[int]' = None,
destination: 'Optional[IPv4Address | IPv6Address | str | int | bytes]' = None,
strict: 'bool' = True,
esn: 'bool' = False,
seq: 'int' = 0,
window: 'int' = 64) -> 'None':
if spi is not None and not 0 <= spi <= 0xFFFFFFFF:
raise ProtocolError(f'ESP: invalid SPI: {spi!r}')
if not 1 <= window <= 0x80000000:
raise ProtocolError(f'ESP: invalid window: {window!r} packets is outside 1 to 2**31 '
f'(RFC 4303 Appendix A2)')
if isinstance(destination, bool):
# NOTE: ``ip_address`` is called directly, not through a field, so the field's ``bool``
# guard is repeated; ``True`` would otherwise become ``IPv4Address('0.0.0.1')``.
raise ProtocolError(
f'ESP: invalid destination: must not be a bool, not {destination!r} -- '
f'pass int({destination!r}) if the numeric value is what is wanted')
#: Optional[int]: Security Parameters Index, or :data:`None` for any.
self.spi = spi
#: CipherSuite: How to apply the encryption algorithm.
self.cipher_suite = CipherSuite.get(encryption)
#: IntegritySuite: How to apply the integrity algorithm.
self.integrity_suite = IntegritySuite.get(integrity)
#: Cipher: Encryption algorithm, i.e. its IKEv2 transform.
self.encryption = self.cipher_suite.cipher
#: Integrity: Integrity algorithm, i.e. its IKEv2 transform.
self.integrity = self.integrity_suite.integrity
#: bool: Whether to enforce the :rfc:`4303` §2.4 padding pattern.
self.strict = strict
#: Optional[IPv4Address | IPv6Address]: Outer destination address.
self.destination = ipaddress.ip_address(destination) if destination is not None else None
#: bool: Whether the SA uses Extended Sequence Numbers.
self.esn = esn
#: int: Size of the anti-replay window, in packets.
self.window = window
self._split_seq(seq)
self.__seq__ = seq
if self.cipher_suite.is_aead and self.integrity is not Integrity.NONE:
raise ProtocolError(
f'ESP: invalid integrity algorithm: {self.encryption.name} is a combined mode '
f'algorithm and provides its own integrity, so {self.integrity.name!r} must '
f'not be configured alongside it'
)
if self.encryption is Cipher.ENCR_AES_CTR and self.integrity is Integrity.NONE:
raise ProtocolError(f'ESP: invalid integrity algorithm: {self.encryption.name} must '
f'be used with an integrity algorithm (RFC 3686 s3.3), not '
f'{self.integrity.name!r}')
key, self.__salt__ = self._split_key(self.cipher_suite, encryption_key, salt)
self.__key__ = key
self.__integrity_key__ = bytes(integrity_key)
if self.integrity_suite.mac == 'cmac':
expected = self.integrity_suite.key_size
if len(self.__integrity_key__) != expected:
raise ProtocolError(f'ESP: invalid integrity key: {self.integrity.name} needs a '
f'{expected}-octet key, got {len(self.__integrity_key__)!r} '
f'octets')
elif self.integrity is not Integrity.NONE:
expected = self.integrity_suite.key_size
if len(self.__integrity_key__) != expected:
# NOTE: #2411 -- ``warn`` reports the caller's frame, so here, more than on the
# exceptions above, the ``ESP:`` prefix is all that names the protocol.
warn(f'ESP: invalid integrity key: {self.integrity.name} expects a '
f'{expected}-octet key, got {len(self.__integrity_key__)} octets; '
f'the ICV will very likely fail to verify', ProtocolWarning)
if icv_length is not None and icv_length < 0:
raise ProtocolError(f'ESP: invalid ICV length: {icv_length!r}')
self.__icv_length__ = icv_length
unavailable = self.unavailable()
if unavailable is not None:
warn(f'{unavailable}; ESP payloads for SPI '
f'{"any" if self.spi is None else f"{self.spi:#010x}"} will be reported as '
f'opaque ciphertext', ProtocolWarning)
[docs]
def __repr__(self) -> 'str':
"""Representation of the SA, free of any key material."""
spi = 'any' if self.spi is None else f'{self.spi:#010x}'
dst = '' if self.destination is None else f' dst={self.destination!s}'
return (f'<SecurityAssociation spi={spi} encryption={self.encryption.name} '
f'integrity={self.integrity.name} icv={self.icv_length}{dst}>')
##########################################################################
# Utilities.
##########################################################################
[docs]
@staticmethod
def _split_key(suite: 'CipherSuite', material: 'bytes',
salt: 'Optional[bytes]') -> 'tuple[bytes, bytes]':
"""Split keying material into the key and the AEAD salt.
Args:
suite: Encryption algorithm parameters.
material: Keying material as supplied by the caller.
salt: Explicit salt, if the caller kept it separate.
Returns:
A 2-tuple of the key and the salt.
Raises:
ProtocolError: If the lengths do not match the algorithm.
"""
material = bytes(material)
salt_length = suite.salt_length
if salt is None:
# RFC 4106 s8.1: the last four octets of the keying material are
# the salt value.
if salt_length and len(material) > salt_length:
material, salt = material[:-salt_length], material[-salt_length:]
else:
salt = b''
else:
salt = bytes(salt)
if len(salt) != salt_length:
raise ProtocolError(f'ESP: invalid salt: {suite.cipher.name} needs a '
f'{salt_length}-octet salt, got {len(salt)!r} octets')
if len(material) not in suite.key_sizes:
raise ProtocolError(f'ESP: invalid key: {suite.cipher.name} needs a key of '
f'{" or ".join(map(str, suite.key_sizes))} octets, '
f'got {len(material)!r}')
return material, salt
[docs]
def _missing_cryptography(self, kind: 'Literal["encryption", "integrity"]') -> 'str':
"""Say that one of the SA's algorithms needs the missing |cryptography|_.
Args:
kind: Which algorithm needs it.
Returns:
The reason, as :meth:`unavailable` and :meth:`_cryptography` give it.
"""
algorithm = self.encryption if kind == 'encryption' else self.integrity
return (f'ESP: unavailable {kind} algorithm: {algorithm.name!r} needs the optional '
f'"cryptography" dependency, which is not installed')
[docs]
def _cryptography(self, kind: 'Literal["encryption", "integrity"]') -> 'tuple[Any, ...]':
"""Load |cryptography|_ for one of the SA's algorithms.
Args:
kind: Which algorithm needs it.
Returns:
The primitives :func:`load_cryptography` returns.
Raises:
ProtocolError: If |cryptography|_ is not installed.
"""
crypto = load_cryptography()
if crypto is None:
raise ProtocolError(self._missing_cryptography(kind))
return crypto
[docs]
def _split_seq(self, seq: 'int') -> 'tuple[bytes, bytes]':
"""Split a full sequence number into the octets sent and those kept back.
Args:
seq: Full sequence number.
Returns:
A 2-tuple of the low-order 4 octets, which the Sequence Number
field carries, and the high-order 4 octets under ESN, never
transmitted [:rfc:`4303` §2.2.1], or ``b''`` without.
Raises:
ProtocolError: If ``seq`` does not fit in 32 bits, or in 64 with
:attr:`esn`.
"""
bits = 64 if self.esn else 32
if not 0 <= seq < 1 << bits:
raise ProtocolError(f'ESP: invalid sequence number: {seq!r} does not fit in {bits} '
f'bits')
low = (seq & 0xFFFFFFFF).to_bytes(4, 'big')
return low, (seq >> 32).to_bytes(4, 'big') if self.esn else b''
[docs]
def _cipher(self, crypto: 'tuple[Any, ...]', iv: 'bytes') -> 'Any':
"""Build the |cryptography|_ cipher of a suite that is not AEAD.
Args:
crypto: The primitives :func:`load_cryptography` returns.
iv: Explicit IV.
Returns:
A :class:`cryptography.hazmat.primitives.ciphers.Cipher`.
"""
crypto_cipher, algorithms, modes, _, _, _, camellia = crypto
if self.encryption is Cipher.ENCR_AES_CTR:
# RFC 3686 s4: the nonce, the IV, then a block counter from one.
counter = self.__salt__ + iv + (1).to_bytes(4, 'big')
return crypto_cipher(algorithms.AES(self.__key__), modes.CTR(counter))
algorithm = camellia if self.encryption is Cipher.ENCR_CAMELLIA_CBC else algorithms.AES
return crypto_cipher(algorithm(self.__key__), modes.CBC(iv))
[docs]
def _seal(self, crypto: 'tuple[Any, ...]', nonce: 'bytes', aad: 'bytes',
plaintext: 'bytes') -> 'tuple[bytes, bytes]':
"""Encrypt and authenticate under the SA's AEAD suite.
Args:
crypto: The primitives :func:`load_cryptography` returns.
nonce: Nonce.
aad: Associated data.
plaintext: Plaintext.
Returns:
A 2-tuple of the ciphertext and the tag.
"""
crypto_cipher, algorithms, modes, _, aead, _, _ = crypto
cipher = self.encryption
icv_length = self.cipher_suite.icv_length
if cipher in (Cipher.ENCR_AES_CCM_8, Cipher.ENCR_AES_CCM_12, Cipher.ENCR_AES_CCM_16,
Cipher.ENCR_AES_CCM_8_IIV):
sealed = aead.AESCCM(self.__key__, tag_length=icv_length).encrypt(nonce, plaintext, aad)
elif cipher in (Cipher.ENCR_CHACHA20_POLY1305, Cipher.ENCR_CHACHA20_POLY1305_IIV):
sealed = aead.ChaCha20Poly1305(self.__key__).encrypt(nonce, plaintext, aad)
else:
encryptor = crypto_cipher(algorithms.AES(self.__key__), modes.GCM(nonce)).encryptor()
encryptor.authenticate_additional_data(aad)
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return ciphertext, encryptor.tag[:self.icv_length]
return sealed[:-icv_length], sealed[-icv_length:]
[docs]
def _open(self, crypto: 'tuple[Any, ...]', nonce: 'bytes', aad: 'bytes',
ciphertext: 'bytes', tag: 'bytes') -> 'bytes':
"""Verify and decrypt under the SA's AEAD suite; the inverse of :meth:`_seal`.
Args:
crypto: The primitives :func:`load_cryptography` returns.
nonce: Nonce.
aad: Associated data.
ciphertext: Ciphertext.
tag: Authentication tag.
Returns:
The plaintext.
Raises:
cryptography.exceptions.InvalidTag: If the tag does not verify.
"""
crypto_cipher, algorithms, modes, _, aead, _, _ = crypto
cipher = self.encryption
if cipher in (Cipher.ENCR_AES_CCM_8, Cipher.ENCR_AES_CCM_12, Cipher.ENCR_AES_CCM_16,
Cipher.ENCR_AES_CCM_8_IIV):
ccm = aead.AESCCM(self.__key__, tag_length=self.cipher_suite.icv_length)
return ccm.decrypt(nonce, ciphertext + tag, aad)
if cipher in (Cipher.ENCR_CHACHA20_POLY1305, Cipher.ENCR_CHACHA20_POLY1305_IIV):
return aead.ChaCha20Poly1305(self.__key__).decrypt(nonce, ciphertext + tag, aad)
decryptor = crypto_cipher(
algorithms.AES(self.__key__),
modes.GCM(nonce, tag, min_tag_length=len(tag)),
).decryptor()
decryptor.authenticate_additional_data(aad)
return decryptor.update(ciphertext) + decryptor.finalize()
[docs]
class ESPContext(ProtocolContext):
"""Caller supplied Security Association context for :class:`ESP`.
Args:
*associations: Security Associations to make available to the
parser, in order of preference for otherwise equal matches.
"""
##########################################################################
# Properties.
##########################################################################
@property
def associations(self) -> 'tuple[SecurityAssociation, ...]':
"""Registered Security Associations."""
return tuple(self.__associations__)
##########################################################################
# Methods.
##########################################################################
[docs]
@classmethod
def protocol(cls) -> 'tuple[Literal["ESP"]]':
"""Index ID of the protocol this context applies to."""
return ('ESP',)
[docs]
def register(self, association: 'SecurityAssociation') -> 'None':
"""Add a Security Association to the context.
Args:
association: Security Association to add.
Raises:
ProtocolError: If ``association`` is not a
:class:`SecurityAssociation`.
"""
if not isinstance(association, SecurityAssociation):
raise ProtocolError(f'ESP: not a security association: {association!r}')
self.__associations__.append(association)
[docs]
def match(self, spi: 'int',
destination: 'Optional[IPv4Address | IPv6Address]' = None) -> 'Optional[SecurityAssociation]': # pylint: disable=line-too-long
"""Find the Security Association that best fits a packet.
Args:
spi: SPI read from the packet.
destination: Outer destination address, if known.
Returns:
The best matching SA, or :data:`None` when none applies.
"""
best = None # type: Optional[SecurityAssociation]
best_score = -1
for association in self.__associations__:
score = association.matches(spi, destination)
if score > best_score:
best, best_score = association, score
return best
##########################################################################
# Data models.
##########################################################################
def __init__(self, *associations: 'SecurityAssociation') -> 'None':
self.__associations__ = [] # type: list[SecurityAssociation]
for association in associations:
self.register(association)
[docs]
def __repr__(self) -> 'str':
"""Representation of the context, free of any key material."""
return f'<ESPContext associations={len(self.__associations__)}>'
##############################################################################
# Protocol.
##############################################################################
[docs]
class ESP(IPsec[Data_ESP, Schema_ESP], IPv6_Ext[Data_ESP, Schema_ESP],
schema=Schema_ESP, data=Data_ESP):
"""This class implements Encapsulating Security Payload.
Double-inherited, mirroring :class:`~pcapkit.protocols.internet.ah.protocol.AH`:
IANA's *IPv6 Extension Header Types* registry lists ``ESP`` at 50
(:rfc:`4303#section-3.1.1` has it follow the hop-by-hop, routing and
fragmentation extension headers in the IPv6 header chain), and this
package's own
:class:`~pcapkit.const.ipv6.extension_header.ExtensionHeader` registry
agrees, so it must honour the same extension-mode contract as its
siblings. The same section places ESP after the IP header and before the
next-layer protocol in IPv4, so it also travels directly as an IPv4
payload, which is what qualifies it for a base besides
:class:`~pcapkit.protocols.internet.ipv6_ext.protocol.IPv6_Ext`.
:attr:`~pcapkit.protocols.internet.ipv6_ext.protocol.IPv6_Ext.payload` and
:attr:`~pcapkit.protocols.internet.ipv6_ext.protocol.IPv6_Ext.protochain` come from
:class:`~pcapkit.protocols.internet.ipv6_ext.protocol.IPv6_Ext`; ``protocol`` is
spelled out here for the reason given on
:attr:`IPv6_Ext.protocol <pcapkit.protocols.internet.ipv6_ext.protocol.IPv6_Ext.protocol>`.
Note:
:rfc:`8200#section-4.5` says outright that ESP "is not considered an
extension header". The library follows IANA's registry rather than
that sentence (decided on :issue:`895`).
.. versionchanged:: 1.6.0
``next`` of :meth:`make`, written when ``encrypt`` is :data:`True`,
takes a member or an :class:`int` code, resolved with the
enumeration's ``get``; a name, a :obj:`bool`, or a code that does not
fit in one octet raises
:exc:`~pcapkit.utilities.exceptions.ProtocolError`, rather than
resolving against an enumeration inferred from the caller's frame,
writing a different value or raising another exception
(:issue:`2594`).
.. versionremoved:: 1.6.0
The ``next_default``, ``next_namespace`` and ``next_reversed``
arguments of :meth:`make`; resolve a name with
:meth:`~pcapkit.protocols.protocol.Protocol.resolve_index` first
(:issue:`2594`).
"""
#: ESP's octets run to the end of the packet, padded to 4 octets
#: (:rfc:`4303#section-2.4`), so :rfc:`8200#section-4`'s 8-octet length
#: does not bind it (:issue:`2886`).
_ipv6_aligned = False
##########################################################################
# Properties.
##########################################################################
@property
def name(self) -> 'Literal["Encapsulating Security Payload"]':
"""Name of corresponding protocol."""
return 'Encapsulating Security Payload'
@property
def alias(self) -> 'Literal["ESP"]':
"""Acronym of corresponding protocol.
Spelled out rather than left to
:attr:`Protocol.alias <pcapkit.protocols.protocol.Protocol.alias>`'s
class-name default, because
:class:`~pcapkit.protocols.internet.ipv6_ext.protocol.IPv6_Ext` sits
between this class and that default in the MRO and carries a concrete
``'IPv6-Ext'`` of its own. Inheriting it would rename this header in
every :class:`~pcapkit.corekit.protochain.ProtoChain` string and in
:meth:`IPv6._decode_next_layer
<pcapkit.protocols.internet.ipv6.protocol.IPv6._decode_next_layer>`'s packet
dict key. The value equals the class-name default.
"""
return 'ESP'
@property
def protocol(self) -> 'Optional[str] | NoReturn':
"""Name of next layer protocol (if any).
Raises:
UnsupportedCall: if the protocol is used as an IPv6 extension header
"""
if self._extf:
raise UnsupportedCall(f"'{self.__class__.__name__}' object has no attribute 'protocol'")
return super().protocol
@property
def length(self) -> 'int':
"""Length of the ESP header, payload, trailer and ICV.
Note:
Unlike most protocols, this is *not* just the fixed header:
:rfc:`4303` puts the trailer and the ICV at the end of the
packet, and the next layer is recovered from inside the
ciphertext rather than from the bytes that follow. Every byte
ESP owns is therefore counted here.
"""
return self._info.length
##########################################################################
# Methods.
##########################################################################
[docs]
def read(self, length: 'Optional[int]' = None, *, version: 'Literal[4, 6]' = 4, # pylint: disable=arguments-differ,unused-argument
extension: 'bool' = False, **kwargs: 'Any') -> 'Data_ESP':
"""Read Encapsulating Security Payload.
Structure of ESP header [:rfc:`4303`]:
.. 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ----
| Security Parameters Index (SPI) | ^Int.
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Cov-
| Sequence Number | |ered
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ----
| Payload Data* (variable) | | ^
~ ~ | |
| | |Conf.
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Cov-
| | Padding (0-255 bytes) | |ered*
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
| | Pad Length | Next Header | v v
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ------
| Integrity Check Value-ICV (variable) |
~ ~
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Args:
length: Length of packet data.
version: IP protocol version.
extension: If the protocol is used as an IPv6 extension header.
Unlike the other extension headers, ESP terminates the
header chain -- everything after it is encrypted -- so it
decodes its own next layer either way.
**kwargs: Arbitrary keyword arguments.
Returns:
Parsed packet data.
Notes:
The outer destination address, used to disambiguate Security
Associations that share an SPI, is taken from the ``packet``
information the enclosing IP layer passes down. It is not
available for every encapsulation, and an SA that names a
destination still matches when it cannot be confirmed -- see
:meth:`SecurityAssociation.matches`.
Under Extended Sequence Numbers, a parsed packet's high-order
bits come from :meth:`SecurityAssociation.extend`, and a packet
that authenticates moves :attr:`SecurityAssociation.seq` on
(:meth:`SecurityAssociation.advance`). A constructed one is
processed under the ``esn``, or else the ``seq``, :meth:`make` was
given.
"""
schema = self.__header__
# NOTE: The packed octets, not the field's value, which ``make`` leaves a
# protocol or schema payload as (#2860).
data = schema.get_payload()
spi, seq = schema.spi, schema.seq
total = 8 + len(data)
packet = kwargs.get('packet')
if packet is None:
packet = {}
context = self._get_context(ESPContext)
association = context.match(spi, packet.get('dst')) if context is not None else None
if association is None:
return self._make_opaque(
spi, seq, total, data, ESPStatus.NO_SA,
f'{self.alias}: no security association for SPI {spi:#010x}',
version=version, packet=packet, warning=False,
)
# NOTE: A constructed packet takes the full number ``make`` was given, which a parsed one
# infers (RFC 4303 Appendix A2.2); see ``__post_init__``.
full = self._built_seq if self._built_seq is not None and association.esn \
else association.extend(seq)
esn = full if association.esn else None
# NOTE: The ICV length comes from the association, so splitting first reports a truncated
# packet as TRUNCATED, not UNSUPPORTED, and an UNSUPPORTED one still carries its ``icv``.
icv_length = association.icv_length
if icv_length > len(data):
return self._make_opaque(
spi, seq, total, data, ESPStatus.TRUNCATED,
f'{self.alias}: payload too short: {len(data)} octets, shorter than the '
f'{icv_length}-octet ICV the security association declares',
esn=esn, version=version, packet=packet,
)
body, icv = (data[:len(data) - icv_length], data[len(data) - icv_length:]) \
if icv_length else (data, b'')
unavailable = association.unavailable()
if unavailable is not None:
return self._make_opaque(
spi, seq, total, body, ESPStatus.UNSUPPORTED, unavailable,
icv=icv, esn=esn, version=version, packet=packet,
)
# Separate integrity algorithm, RFC 4303 s3.4.4.1. A combined mode
# algorithm verifies its own tag as part of decryption instead.
if association.integrity is not Integrity.NONE:
if not hmac.compare_digest(association.compute_icv(spi, full, body), icv):
return self._make_opaque(
spi, seq, total, body, ESPStatus.AUTH_FAILED,
f'{self.alias}: integrity check value does not verify for SPI '
f'{spi:#010x} sequence {full}', icv=icv, esn=esn, version=version,
packet=packet,
)
association.advance(full)
crypto = load_cryptography()
invalid_tag = crypto[3] if crypto is not None else () # type: Any
try:
plaintext = association.decrypt(spi, full, body, icv)
except ProtocolError as exc:
return self._make_opaque(
spi, seq, total, body, ESPStatus.DECRYPT_FAILED, str(exc),
icv=icv, esn=esn, version=version, packet=packet,
)
except invalid_tag:
return self._make_opaque(
spi, seq, total, body, ESPStatus.AUTH_FAILED,
f'{self.alias}: authentication tag does not verify for SPI {spi:#010x} '
f'sequence {full}; the encryption key is most likely wrong',
icv=icv, esn=esn, version=version, packet=packet,
)
if association.cipher_suite.is_aead:
association.advance(full)
trailer = self._read_trailer(plaintext, association, spi)
if isinstance(trailer, str):
return self._make_opaque(
spi, seq, total, body, ESPStatus.DECRYPT_FAILED, trailer,
icv=icv, esn=esn, version=version, packet=packet,
)
inner, padding, pad_len, next_ = trailer
next_type = Enum_TransType.get(next_)
esp = Data_ESP(
spi=spi,
seq=seq,
esn=esn,
length=total,
payload_data=body,
icv=icv,
status=ESPStatus.DECRYPTED,
error=None,
next=next_type,
pad_len=pad_len,
padding=padding,
plaintext=inner,
)
return self._decode_next_layer(esp, next_type, len(inner), packet=packet,
version=version, payload=inner)
[docs]
def make(self, *,
spi: 'int' = 0,
seq: 'int' = 0,
esn: 'Optional[int]' = None,
next: 'Enum_TransType | int' = Enum_TransType.UDP, # pylint: disable=redefined-builtin
encrypt: 'bool' = False,
iv: 'Optional[bytes]' = None,
pad_len: 'Optional[int]' = None,
icv: 'bytes' = b'',
payload: 'bytes | ProtocolBase | Schema' = b'',
**kwargs: 'Any') -> 'Schema_ESP':
"""Make (construct) packet data.
There are two modes, chosen by ``encrypt``:
* ``encrypt=False`` (the default) writes ``payload`` after the SPI
and sequence number verbatim, followed by ``icv``. This is the
mode used to reproduce a captured packet byte for byte, and is
what :meth:`_make_data` drives -- re-encrypting a packet that was
only ever read would change its bytes.
* ``encrypt=True`` treats ``payload`` as the inner plaintext: it
appends :rfc:`4303` §2.4 padding, the pad length and ``next``,
encrypts the result under the Security Association matching
``spi``, and appends the resulting ICV.
Args:
spi: Security Parameters Index.
seq: Sequence Number field.
esn: Extended Sequence Number the packet is protected and
processed under, whose low-order 32 bits are ``seq``
[:rfc:`4303` §2.2.1]; :data:`None` takes ``seq`` itself. A
Security Association matching ``spi`` must use Extended
Sequence Numbers; with none, the verbatim mode writes the same
octets, as :meth:`_make_data` needs for a rebuild without keys.
next: Next header type, written into the ESP trailer. Only used
when ``encrypt`` is :data:`True`.
encrypt: Whether to protect ``payload``, as described above.
iv: Explicit IV to use; a random one is generated when omitted,
and an implicit IV suite takes none. Only used when
``encrypt`` is :data:`True`.
pad_len: Pad length to use; the smallest value that satisfies
the alignment requirement is chosen when omitted. Only used
when ``encrypt`` is :data:`True`.
icv: Integrity check value. Ignored when ``encrypt`` is
:data:`True`, where it is computed instead.
payload: Payload of current instance, as :obj:`bytes`, a protocol
or a schema, which is packed to its octets.
**kwargs: Arbitrary keyword arguments.
Returns:
Constructed packet data.
Raises:
ProtocolError: If ``seq`` does not fit in 32 bits, ``esn`` does not
extend it or names a Security Association without Extended
Sequence Numbers, or ``encrypt`` is :data:`True` and no
Security Association is available for ``spi``, ``next`` is a
name, a :obj:`bool`, or a member or code that does not fit in
one octet, or ``pad_len`` is outside ``0`` to ``255`` or does
not satisfy the algorithm's alignment requirement, or if
:meth:`SecurityAssociation.encrypt` rejects ``iv`` or cannot
run without |cryptography|_.
.. versionchanged:: 1.7.0
A protocol or schema ``payload`` without ``icv`` or ``encrypt`` is
packed to its octets, where it raised :exc:`TypeError`
(:issue:`2860`).
.. versionchanged:: 1.10.0
New argument ``esn``, and a ``seq`` that does not fit in 32 bits
raises :exc:`~pcapkit.utilities.exceptions.ProtocolError` rather
than being written modulo ``2**32`` (:issue:`2963`).
"""
if not 0 <= seq <= 0xFFFFFFFF:
raise ProtocolError(f'{self.alias}: invalid sequence number: {seq!r} does not fit in '
f'32 bits')
association = None # type: Optional[SecurityAssociation]
if encrypt or esn is not None:
context = self._get_context(ESPContext)
association = context.match(spi) if context is not None else None
if esn is not None:
if not 0 <= esn <= 0xFFFFFFFFFFFFFFFF or esn & 0xFFFFFFFF != seq:
raise ProtocolError(f'{self.alias}: invalid extended sequence number: {esn!r} '
f'does not extend sequence number {seq!r}')
if association is not None and not association.esn:
raise ProtocolError(f'{self.alias}: invalid extended sequence number: the '
f'security association for SPI {spi:#010x} does not use '
f'Extended Sequence Numbers')
if not encrypt:
# the ICV goes after the payload data, so the two have to be
# concatenated by hand; without one, the payload is handed to the
# schema untouched, so that a Protocol or Schema payload is packed
# by the field rather than here
if icv:
return Schema_ESP(spi=spi, seq=seq, payload=self._payload_bytes(payload) + icv)
return Schema_ESP(spi=spi, seq=seq, payload=payload)
if association is None:
raise ProtocolError(f'{self.alias}: no security association for SPI {spi:#010x}; '
f'encrypt=True needs one')
next_value = self._make_index(next, Enum_TransType, bits=8, name='next header')
plain = self._payload_bytes(payload)
align = max(association.cipher_suite.block_size, 4)
if pad_len is None:
pad_len = -(len(plain) + 2) % align
elif (len(plain) + pad_len + 2) % align:
raise ProtocolError(f'{self.alias}: invalid pad length: {pad_len!r} leaves '
f'{len(plain) + pad_len + 2} octets, which is not a multiple '
f'of the required {align}-octet alignment')
if not 0 <= pad_len <= 255:
raise ProtocolError(f'{self.alias}: invalid pad length: {pad_len!r}')
# RFC 4303 s2.4: padding bytes are a monotonically increasing
# sequence starting at 1.
plaintext = plain + bytes(range(1, pad_len + 1)) + bytes([pad_len, next_value])
full = seq if esn is None else esn
body, tag = association.encrypt(spi, full, plaintext, iv)
if association.integrity is not Integrity.NONE:
tag = association.compute_icv(spi, full, body)
return Schema_ESP(
spi=spi,
seq=seq,
payload=body + tag,
)
[docs]
@classmethod
def id(cls) -> 'tuple[Literal["ESP"]]': # type: ignore[override]
"""Index ID of the protocol.
Returns:
Index ID of the protocol.
"""
return ('ESP',)
##########################################################################
# Data models.
##########################################################################
@overload
def __post_init__(self, file: 'IO[bytes] | bytes', length: 'Optional[int]' = ..., *, # pylint: disable=arguments-differ
version: 'Literal[4, 6]' = ..., extension: 'bool' = ...,
**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, *, # pylint: disable=arguments-differ
version: 'Literal[4, 6]' = 4, extension: 'bool' = False,
**kwargs: 'Any') -> 'None':
"""Post initialisation hook.
Args:
file: Source packet stream.
length: Length of packet data.
version: IP protocol version.
extension: If the protocol is used as an IPv6 extension header.
**kwargs: Arbitrary keyword arguments.
See Also:
For construction arguments, please refer to :meth:`self.make <ESP.make>`.
"""
#: bool: If the protocol is used as an IPv6 extension header.
self._extf = extension
#: Optional[int]: Full sequence number a construction was given, which
#: :meth:`read` processes it under; :data:`None` for a parsed packet.
self._built_seq = None # type: Optional[int]
if file is None:
esn = kwargs.get('esn')
self._built_seq = kwargs.get('seq', 0) if esn is None else esn
# call super __post_init__
super().__post_init__(file, length, version=version, extension=extension, **kwargs) # type: ignore[arg-type]
def __length_hint__(self) -> 'Literal[8]':
"""Return an estimated length for the object."""
return 8
[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`_.
.. _IANA: https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
"""
return Enum_TransType.ESP # type: ignore[return-value]
##########################################################################
# Utilities.
##########################################################################
[docs]
@classmethod
def _make_data(cls, data: 'Data_ESP') -> 'dict[str, Any]': # type: ignore[override]
"""Create key-value pairs from ``data`` for protocol construction.
The payload is reproduced verbatim rather than re-encrypted, so that
reconstruction is byte exact and does not need the keys. ``esn`` is
given where the packet had an Extended Sequence Number, so that it is
processed under the same number again.
Args:
data: protocol data
Returns:
Key-value pairs for protocol construction.
"""
values = {
'spi': data.spi,
'seq': data.seq,
'payload': data.payload_data + data.icv,
} # type: dict[str, Any]
if data.esn is not None:
values['esn'] = data.esn
return values
[docs]
def _make_opaque(self, spi: 'int', seq: 'int', total: 'int', payload_data: 'bytes',
status: 'ESPStatus', error: 'str', *, icv: 'bytes' = b'',
esn: 'Optional[int]' = None, version: 'Literal[4, 6]' = 4,
packet: 'Optional[dict[str, Any]]' = None,
warning: 'bool' = True) -> 'Data_ESP':
"""Report an ESP packet whose payload was not decrypted.
The payload is surfaced as :class:`~pcapkit.protocols.misc.raw.protocol.Raw`
-- which is what a next header of :data:`None` resolves to -- so that
:attr:`self.payload <pcapkit.protocols.protocol.Protocol.payload>`
and the protocol chain behave as they do for any other protocol, and
the trailer fields are left :data:`None` rather than guessed at.
Args:
spi: Security Parameters Index.
seq: Sequence number.
total: Total length of the ESP portion of the packet.
payload_data: Payload data, excluding the ICV.
status: Why the payload was not decrypted.
error: Human readable form of ``status``.
icv: Integrity check value, when its length is known.
esn: Extended Sequence Number, when the SA uses them.
version: IP protocol version.
packet: Packet information from the enclosing layer.
warning: Whether to warn; a capture taken without keys is the
expected case and does not warrant one.
Returns:
Parsed packet data.
"""
if warning:
warn(error, ProtocolWarning)
esp = Data_ESP(
spi=spi,
seq=seq,
esn=esn,
length=total,
payload_data=payload_data,
icv=icv,
status=status,
error=error,
next=None,
pad_len=None,
padding=None,
plaintext=None,
)
return self._decode_next_layer(esp, None, len(payload_data) + len(icv),
packet=packet or None, version=version,
payload=payload_data + icv)
[docs]
@staticmethod
def _read_trailer(plaintext: 'bytes', association: 'SecurityAssociation',
spi: 'int') -> 'tuple[bytes, bytes, int, int] | str':
"""Split the ESP trailer off the decrypted plaintext.
Args:
plaintext: Decrypted payload data, i.e. the inner payload
followed by the ESP trailer.
association: Security Association the packet was decrypted with.
spi: Security Parameters Index, for the diagnostic message.
Returns:
A 4-tuple of the inner payload, the padding, the pad length and
the next header, or a :obj:`str` explaining why the trailer is
not self consistent.
"""
if len(plaintext) < 2:
return (f'ESP: decrypted payload too short: SPI {spi:#010x} decrypts to '
f'{len(plaintext)} octets, too short to hold a pad length and next header')
pad_len, next_ = plaintext[-2], plaintext[-1]
if pad_len + 2 > len(plaintext):
return (f'ESP: invalid pad length: the decrypted payload for SPI {spi:#010x} '
f'declares {pad_len} octets of padding but holds only '
f'{len(plaintext) - 2}; the encryption key is most likely wrong')
padding = plaintext[len(plaintext) - 2 - pad_len:len(plaintext) - 2]
inner = plaintext[:len(plaintext) - 2 - pad_len]
if padding != bytes(range(1, pad_len + 1)):
message = (f'ESP: invalid padding: the decrypted payload for SPI {spi:#010x} does '
f'not follow the monotonically increasing sequence of RFC 4303 s2.4')
if association.strict and not association.authenticated:
# Nothing authenticated this packet, so the padding pattern
# is the only wrong-key signal available.
return f'{message}; the encryption key is most likely wrong'
warn(message, ProtocolWarning)
return inner, padding, pad_len, next_
[docs]
@staticmethod
def _payload_bytes(payload: 'bytes | ProtocolBase | Schema') -> 'bytes':
"""Render ``payload`` as :obj:`bytes`.
Args:
payload: Payload as supplied to :meth:`make`.
Returns:
Packed payload.
Raises:
ProtocolUnbound: If ``payload`` is of an unsupported type. This
mirrors :meth:`Schema.pack <pcapkit.protocols.schema.Schema.pack>`,
which rejects the same set.
"""
from pcapkit.protocols.protocol import \
ProtocolBase # pylint: disable=import-outside-toplevel
if isinstance(payload, bytes):
return payload
if isinstance(payload, Schema):
return payload.pack()
if isinstance(payload, ProtocolBase):
return bytes(payload)
raise ProtocolUnbound(f'unsupported type {type(payload)}')