Skip to content

Commit 0599a3b

Browse files
authored
fix(internet): the ESP read path and integrity-key warning name the protocol (#2411) (#2413)
#2366 (fixing #2297) put the house `ESP: <lowercase description>` prefix on `ESP.make`'s ProtocolError messages and on `SecurityAssociation.unavailable`, but eight sites were outside its checklist. The same condition therefore read two ways depending on the direction it was hit from -- `make` said `ESP: no security association for SPI 0x...`, `read` said `no security association for SPI 0x...`. - esp.py `ESP._read_trailer` (a staticmethod, so the prefix is spelled literally, as every `SecurityAssociation` site does): the plaintext-too-short diagnostic, the pad-length-beyond-the-plaintext one, and the padding-pattern one, which is both returned and warned with. - esp.py `ESP.read` (an instance method, so `{self.alias}:`, as `ESP.make`): the NO_SA, TRUNCATED, separate-integrity AUTH_FAILED and AEAD-tag AUTH_FAILED messages, surfaced as `esp.error`. - esp.py `SecurityAssociation.__init__`: the short-integrity-key warning. `warn` reports the caller's frame rather than the protocol, so the message text is the only thing naming ESP -- it needs the prefix more than the exceptions do, not less. - test_tier_guard.py `DependencyGateFalsifiabilityTests .test_removing_crypto_from_the_test_job_is_caught`: the new module is the second to carry a `HAS_CRYPTO` gate, so it joins that test's expected set of gated modules and its `describe_gap` location assertions. #2324 dropped this test's `len(gap.gates)` pin and kept the set equality as the structural claim, so the fix is to extend the set rather than to loosen it. Two messages were reworded rather than only prefixed, to avoid `ESP: ESP payload ...` and `ESP: decrypted ESP payload ...`, and the three that read as `<thing> for SPI x does/declares y` were turned into the `description: detail` house form. Every substring the existing tests match on is preserved. Test: tests/protocols/internet/test_esp_message_prefix_2411_unit.py (new, 13 tests, every message pinned whole rather than by substring -- matching fragments is why the omission survived #2366). Confirmed 10 failed / 3 passed against unpatched esp.py, each failure a missing prefix; the 3 that passed are the controls that assert the guards did not widen. All but one of the new tests runs without `cryptography`: an ENCR_NULL SA reaches the trailer and separate-integrity paths on hmac and hashlib alone. tests/test_tier_guard.py in full: 135 passed / 2497 subtests / 0 failed. tests/ in full, after `examples/generators/make_samples.py`: 6776 passed / 118 skipped / 101828 subtests / 0 failed. Fixes #2411.
1 parent 8f3f3e5 commit 0599a3b

3 files changed

Lines changed: 320 additions & 18 deletions

File tree

‎pcapkit/protocols/internet/esp.py‎

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -597,9 +597,12 @@ def __init__(self, spi: 'Optional[int]' = None, *,
597597
if self.integrity is not Integrity.NONE:
598598
expected = self.integrity_suite.key_size
599599
if len(self.__integrity_key__) != expected:
600-
warn(f'{self.integrity.name} expects a {expected}-octet key, got '
601-
f'{len(self.__integrity_key__)} octets; the ICV will very likely '
602-
f'fail to verify', ProtocolWarning)
600+
# NOTE: #2411 -- the ``ESP:`` prefix matters more here than on
601+
# the exceptions above: ``warn`` reports the caller's frame, so
602+
# the message text is the only thing that names the protocol.
603+
warn(f'ESP: invalid integrity key: {self.integrity.name} expects a '
604+
f'{expected}-octet key, got {len(self.__integrity_key__)} octets; '
605+
f'the ICV will very likely fail to verify', ProtocolWarning)
603606

604607
if icv_length is not None and icv_length < 0:
605608
raise ProtocolError(f'ESP: invalid ICV length: {icv_length!r}')
@@ -1126,7 +1129,7 @@ def read(self, length: 'Optional[int]' = None, *, version: 'Literal[4, 6]' = 4,
11261129
if association is None:
11271130
return self._make_opaque(
11281131
spi, seq, total, data, ESPStatus.NO_SA,
1129-
f'no security association for SPI {spi:#010x}',
1132+
f'{self.alias}: no security association for SPI {spi:#010x}',
11301133
version=version, packet=packet, warning=False,
11311134
)
11321135

@@ -1141,8 +1144,8 @@ def read(self, length: 'Optional[int]' = None, *, version: 'Literal[4, 6]' = 4,
11411144
if icv_length > len(data):
11421145
return self._make_opaque(
11431146
spi, seq, total, data, ESPStatus.TRUNCATED,
1144-
f'ESP payload is {len(data)} octets, shorter than the {icv_length}-octet '
1145-
f'ICV the security association declares',
1147+
f'{self.alias}: payload too short: {len(data)} octets, shorter than the '
1148+
f'{icv_length}-octet ICV the security association declares',
11461149
version=version, packet=packet,
11471150
)
11481151
body, icv = (data[:len(data) - icv_length], data[len(data) - icv_length:]) \
@@ -1161,8 +1164,8 @@ def read(self, length: 'Optional[int]' = None, *, version: 'Literal[4, 6]' = 4,
11611164
if not hmac.compare_digest(association.compute_icv(spi, seq, body), icv):
11621165
return self._make_opaque(
11631166
spi, seq, total, body, ESPStatus.AUTH_FAILED,
1164-
f'integrity check value does not verify for SPI {spi:#010x} '
1165-
f'sequence {seq}', icv=icv, version=version, packet=packet,
1167+
f'{self.alias}: integrity check value does not verify for SPI '
1168+
f'{spi:#010x} sequence {seq}', icv=icv, version=version, packet=packet,
11661169
)
11671170

11681171
crypto = load_cryptography()
@@ -1177,8 +1180,8 @@ def read(self, length: 'Optional[int]' = None, *, version: 'Literal[4, 6]' = 4,
11771180
except invalid_tag:
11781181
return self._make_opaque(
11791182
spi, seq, total, body, ESPStatus.AUTH_FAILED,
1180-
f'authentication tag does not verify for SPI {spi:#010x} sequence {seq}; '
1181-
f'the encryption key is most likely wrong',
1183+
f'{self.alias}: authentication tag does not verify for SPI {spi:#010x} '
1184+
f'sequence {seq}; the encryption key is most likely wrong',
11821185
icv=icv, version=version, packet=packet,
11831186
)
11841187

@@ -1435,21 +1438,21 @@ def _read_trailer(plaintext: 'bytes', association: 'SecurityAssociation',
14351438
14361439
"""
14371440
if len(plaintext) < 2:
1438-
return (f'decrypted ESP payload for SPI {spi:#010x} is {len(plaintext)} octets, '
1439-
f'too short to hold a pad length and next header')
1441+
return (f'ESP: decrypted payload too short: SPI {spi:#010x} decrypts to '
1442+
f'{len(plaintext)} octets, too short to hold a pad length and next header')
14401443

14411444
pad_len, next_ = plaintext[-2], plaintext[-1]
14421445
if pad_len + 2 > len(plaintext):
1443-
return (f'decrypted ESP payload for SPI {spi:#010x} declares {pad_len} octets of '
1444-
f'padding but holds only {len(plaintext) - 2}; the encryption key is most '
1445-
f'likely wrong')
1446+
return (f'ESP: invalid pad length: the decrypted payload for SPI {spi:#010x} '
1447+
f'declares {pad_len} octets of padding but holds only '
1448+
f'{len(plaintext) - 2}; the encryption key is most likely wrong')
14461449

14471450
padding = plaintext[len(plaintext) - 2 - pad_len:len(plaintext) - 2]
14481451
inner = plaintext[:len(plaintext) - 2 - pad_len]
14491452

14501453
if padding != bytes(range(1, pad_len + 1)):
1451-
message = (f'padding of the decrypted ESP payload for SPI {spi:#010x} does not '
1452-
f'follow the monotonically increasing sequence of RFC 4303 s2.4')
1454+
message = (f'ESP: invalid padding: the decrypted payload for SPI {spi:#010x} does '
1455+
f'not follow the monotonically increasing sequence of RFC 4303 s2.4')
14531456
if association.strict and not association.authenticated:
14541457
# Nothing authenticated this packet, so the padding pattern
14551458
# is the only wrong-key signal available.
Lines changed: 292 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,292 @@
1+
# -*- coding: utf-8 -*-
2+
"""GitHub issue #2411: the ESP read path and one warning missed the ``ESP:`` prefix.
3+
4+
#2366 (fixing #2297) put the house ``ESP: <lowercase description>`` prefix on
5+
:meth:`ESP.make <pcapkit.protocols.internet.esp.ESP.make>`'s
6+
:exc:`~pcapkit.utilities.exceptions.ProtocolError` messages and on
7+
:meth:`SecurityAssociation.unavailable
8+
<pcapkit.protocols.internet.esp.SecurityAssociation.unavailable>`, but eight
9+
sites were outside its checklist and kept the bare wording -- so the *same*
10+
condition read two different ways depending on which direction it was hit from
11+
(``ESP: no security association for SPI 0x...`` from ``make``, and
12+
``no security association for SPI 0x...`` from ``read``).
13+
14+
The eight, as #2411 enumerates them:
15+
16+
* three diagnostics returned by :meth:`ESP._read_trailer
17+
<pcapkit.protocols.internet.esp.ESP._read_trailer>` -- the one for a
18+
plaintext too short to hold a trailer, the one for a pad length the
19+
plaintext cannot hold, and the padding-pattern one, which is both returned
20+
and warned with (:class:`ReadTrailerMessages`);
21+
* four built inline in :meth:`ESP.read
22+
<pcapkit.protocols.internet.esp.ESP.read>` and surfaced as
23+
:attr:`esp.error <pcapkit.protocols.data.internet.esp.ESP.error>`
24+
(:class:`ReadErrorMessages`);
25+
* the integrity-key warning in :meth:`SecurityAssociation.__init__
26+
<pcapkit.protocols.internet.esp.SecurityAssociation.__init__>`
27+
(:class:`IntegrityKeyWarning`). :func:`~pcapkit.utilities.warnings.warn`
28+
blames the caller's frame rather than the protocol, so the message text is
29+
the only thing that names ESP at all -- it needs the prefix more than the
30+
exceptions do, not less.
31+
32+
Every message is pinned **whole**, not by substring: the existing tests in
33+
``tests/protocols/internet/test_esp_unit.py`` match fragments and so pass with
34+
or without a prefix, which is exactly why the omission survived #2366. This
35+
follows the pinning style of
36+
``tests/protocols/test_maker_invalid_format_messages_2296_unit.py`` and its
37+
#2406 companion.
38+
39+
Nothing here needs |cryptography|_ bar
40+
:meth:`ReadErrorMessages.test_aead_tag_mismatch_names_the_protocol`: an
41+
``ENCR_NULL`` SA exercises the trailer and the separate-integrity paths on
42+
:mod:`hmac` and :mod:`hashlib` alone.
43+
44+
:mod:`pcapkit` is imported inside each test, after
45+
:func:`~tests._support.reimport_once_per_class`.
46+
47+
"""
48+
49+
from __future__ import annotations
50+
51+
import hashlib
52+
import hmac
53+
import importlib.util
54+
import struct
55+
import unittest
56+
import warnings
57+
from typing import TYPE_CHECKING
58+
59+
from tests._support import reimport_once_per_class
60+
61+
if TYPE_CHECKING:
62+
from typing import Any
63+
64+
RUNTIME_DEPS = ('tbtrim', 'aenum', 'chardet', 'dictdumper')
65+
HAS_RUNTIME = all(importlib.util.find_spec(name) is not None for name in RUNTIME_DEPS)
66+
HAS_CRYPTO = importlib.util.find_spec('cryptography') is not None
67+
68+
#: The SPI every message below names, and its ``{spi:#010x}`` rendering.
69+
SPI = 0x4321
70+
SPI_TEXT = '0x00004321'
71+
72+
73+
def esp_packet(payload: bytes, *, spi: int = SPI, seq: int = 1) -> bytes:
74+
"""An ESP packet: the 8-octet header, then ``payload`` verbatim."""
75+
return struct.pack('!II', spi, seq) + payload
76+
77+
78+
@unittest.skipUnless(HAS_RUNTIME, 'runtime dependencies not installed')
79+
class ESPMessageTestCase(unittest.TestCase):
80+
"""Re-import :mod:`pcapkit` once per class, as the suite's convention asks."""
81+
82+
def setUp(self) -> None:
83+
reimport_once_per_class(self)
84+
85+
def sa(self, **kwargs: 'Any') -> 'Any':
86+
"""A Security Association for :data:`SPI`, ``ENCR_NULL`` unless told otherwise.
87+
88+
``ENCR_NULL`` returns the payload as its own plaintext and needs no
89+
|cryptography|_, so it reaches the trailer and separate-integrity
90+
paths that carry the messages under test without a cipher in the way.
91+
92+
"""
93+
from pcapkit.protocols.internet.esp import SecurityAssociation
94+
95+
kwargs.setdefault('spi', SPI)
96+
return SecurityAssociation(**kwargs)
97+
98+
def parse(self, packet: bytes, *associations: 'Any') -> 'Any':
99+
"""Parse ``packet`` with ``associations`` in context, swallowing warnings.
100+
101+
Returns:
102+
The parsed data model, i.e. ``esp.info``.
103+
104+
"""
105+
from pcapkit.corekit.context import ContextRegistry
106+
from pcapkit.protocols.internet.esp import ESP, ESPContext
107+
108+
registry = ContextRegistry.make(ESPContext(*associations)) if associations else None
109+
with warnings.catch_warnings():
110+
warnings.simplefilter('ignore')
111+
if registry is None:
112+
return ESP(packet, len(packet)).info
113+
return ESP(packet, len(packet), __context__=registry).info
114+
115+
116+
class ReadTrailerMessages(ESPMessageTestCase):
117+
"""``ESP._read_trailer``'s three diagnostics name the protocol.
118+
119+
``_read_trailer`` is a :func:`staticmethod`, so it has no ``self.alias`` to
120+
read and spells the prefix literally -- the same way every site in
121+
:class:`~pcapkit.protocols.internet.esp.SecurityAssociation` does.
122+
123+
"""
124+
125+
def trailer(self, plaintext: bytes, **kwargs: 'Any') -> 'Any':
126+
"""``_read_trailer`` over ``plaintext``, for an SA built from ``kwargs``."""
127+
from pcapkit.protocols.internet.esp import ESP
128+
129+
return ESP._read_trailer(plaintext, self.sa(**kwargs), SPI)
130+
131+
def test_plaintext_too_short_for_a_trailer(self) -> None:
132+
# one octet cannot hold both the pad length and the next header, which
133+
# are the last two octets of the plaintext
134+
self.assertEqual(
135+
self.trailer(b'\x06'),
136+
f'ESP: decrypted payload too short: SPI {SPI_TEXT} decrypts to 1 octets, '
137+
f'too short to hold a pad length and next header')
138+
139+
def test_an_empty_plaintext_too(self) -> None:
140+
self.assertEqual(
141+
self.trailer(b''),
142+
f'ESP: decrypted payload too short: SPI {SPI_TEXT} decrypts to 0 octets, '
143+
f'too short to hold a pad length and next header')
144+
145+
def test_pad_length_beyond_the_plaintext(self) -> None:
146+
# pad length 255 over a 5-octet plaintext: 3 octets remain once the
147+
# trailer's own two are taken off
148+
self.assertEqual(
149+
self.trailer(b'abc' + bytes([255, 6])),
150+
f'ESP: invalid pad length: the decrypted payload for SPI {SPI_TEXT} declares '
151+
f'255 octets of padding but holds only 3; the encryption key is most likely wrong')
152+
153+
def test_padding_pattern_is_decisive_when_nothing_authenticated_it(self) -> None:
154+
# zero padding where RFC 4303 s2.4 asks for 1, 2, ...; a strict SA with
155+
# no integrity has the pattern as its only wrong-key signal, so the
156+
# mismatch is returned rather than warned about
157+
self.assertEqual(
158+
self.trailer(b'payload' + bytes(2) + bytes([2, 6])),
159+
f'ESP: invalid padding: the decrypted payload for SPI {SPI_TEXT} does not follow '
160+
f'the monotonically increasing sequence of RFC 4303 s2.4; the encryption key is '
161+
f'most likely wrong')
162+
163+
def test_a_lenient_sa_warns_with_the_same_prefixed_text(self) -> None:
164+
from pcapkit.utilities.warnings import ProtocolWarning
165+
166+
with warnings.catch_warnings(record=True) as caught:
167+
warnings.simplefilter('always')
168+
trailer = self.trailer(b'payload' + bytes(2) + bytes([2, 6]), strict=False)
169+
170+
# accepted, so the trailer comes back parsed rather than as a reason
171+
self.assertEqual(trailer, (b'payload', bytes(2), 2, 6))
172+
messages = [str(w.message) for w in caught
173+
if issubclass(w.category, ProtocolWarning)]
174+
self.assertEqual(
175+
messages,
176+
[f'ESP: invalid padding: the decrypted payload for SPI {SPI_TEXT} does not follow '
177+
f'the monotonically increasing sequence of RFC 4303 s2.4'])
178+
179+
def test_a_consistent_trailer_is_still_read(self) -> None:
180+
# the guards have not widened: padding 01 02, pad length 2, next 6 (TCP)
181+
self.assertEqual(self.trailer(b'payload' + bytes([1, 2]) + bytes([2, 6])),
182+
(b'payload', bytes([1, 2]), 2, 6))
183+
184+
185+
class ReadErrorMessages(ESPMessageTestCase):
186+
"""``ESP.read``'s four inline diagnostics name the protocol.
187+
188+
``read`` is an instance method, so it spells the prefix ``{self.alias}:``,
189+
as ``ESP.make``'s messages do.
190+
191+
"""
192+
193+
def test_no_security_association_names_the_protocol(self) -> None:
194+
from pcapkit.protocols.internet.esp import ESPStatus
195+
196+
info = self.parse(esp_packet(b'opaque-ciphertext'))
197+
self.assertIs(info.status, ESPStatus.NO_SA)
198+
self.assertEqual(info.error, f'ESP: no security association for SPI {SPI_TEXT}')
199+
200+
def test_a_payload_shorter_than_the_declared_icv(self) -> None:
201+
from pcapkit.protocols.internet.esp import ESPStatus
202+
203+
# the ICV length comes from the SA, so declaring 16 octets over a
204+
# 4-octet payload is reported as TRUNCATED with no cipher involved
205+
info = self.parse(esp_packet(b'tiny'), self.sa(icv_length=16))
206+
self.assertIs(info.status, ESPStatus.TRUNCATED)
207+
self.assertEqual(
208+
info.error,
209+
'ESP: payload too short: 4 octets, shorter than the 16-octet ICV the '
210+
'security association declares')
211+
212+
def test_an_icv_that_does_not_verify(self) -> None:
213+
from pcapkit.protocols.internet.esp import ESPStatus, Integrity
214+
215+
sa = self.sa(integrity=Integrity.HMAC_SHA2_256_128, integrity_key=bytes(32))
216+
# a 16-octet ICV that is not the one the key computes
217+
packet = esp_packet(b'payload' + bytes([1, 2]) + bytes([2, 6]) + bytes(16), seq=7)
218+
info = self.parse(packet, sa)
219+
220+
self.assertIs(info.status, ESPStatus.AUTH_FAILED)
221+
self.assertEqual(
222+
info.error,
223+
f'ESP: integrity check value does not verify for SPI {SPI_TEXT} sequence 7')
224+
225+
def test_the_right_icv_still_verifies(self) -> None:
226+
from pcapkit.protocols.internet.esp import ESPStatus, Integrity
227+
228+
key = bytes(range(32))
229+
sa = self.sa(integrity=Integrity.HMAC_SHA2_256_128, integrity_key=key)
230+
body = b'payload' + bytes([1, 2]) + bytes([2, 6])
231+
icv = hmac.new(key, struct.pack('!II', SPI, 7) + body, hashlib.sha256).digest()[:16]
232+
info = self.parse(esp_packet(body + icv, seq=7), sa)
233+
234+
self.assertIs(info.status, ESPStatus.DECRYPTED)
235+
self.assertIsNone(info.error)
236+
237+
@unittest.skipUnless(HAS_CRYPTO, 'cryptography not installed')
238+
def test_aead_tag_mismatch_names_the_protocol(self) -> None:
239+
from pcapkit.protocols.internet.esp import Cipher, ESPStatus
240+
241+
# a combined-mode SA verifies its own tag inside decryption, so the
242+
# wrong key surfaces as the library's InvalidTag rather than as a
243+
# ProtocolError -- the one message here that needs |cryptography|_
244+
sa = self.sa(encryption=Cipher.AES_GCM_16, encryption_key=bytes(16) + b'salt')
245+
packet = esp_packet(bytes(8) + bytes(16) + bytes(16), seq=3)
246+
info = self.parse(packet, sa)
247+
248+
self.assertIs(info.status, ESPStatus.AUTH_FAILED)
249+
self.assertEqual(
250+
info.error,
251+
f'ESP: authentication tag does not verify for SPI {SPI_TEXT} sequence 3; '
252+
f'the encryption key is most likely wrong')
253+
254+
255+
class IntegrityKeyWarning(ESPMessageTestCase):
256+
"""``SecurityAssociation.__init__``'s integrity-key warning names the protocol.
257+
258+
:func:`~pcapkit.utilities.warnings.warn` reports the *caller's* frame, so
259+
without the prefix the text is all a reader has to go on -- there is no
260+
``pcapkit/protocols/internet/esp.py`` in the location it prints.
261+
262+
"""
263+
264+
def test_a_short_integrity_key_warns_by_name(self) -> None:
265+
from pcapkit.protocols.internet.esp import Integrity
266+
from pcapkit.utilities.warnings import ProtocolWarning
267+
268+
with warnings.catch_warnings(record=True) as caught:
269+
warnings.simplefilter('always')
270+
self.sa(integrity=Integrity.HMAC_SHA2_256_128, integrity_key=bytes(16))
271+
272+
messages = [str(w.message) for w in caught
273+
if issubclass(w.category, ProtocolWarning)]
274+
self.assertEqual(
275+
messages,
276+
['ESP: invalid integrity key: AUTH_HMAC_SHA2_256_128 expects a 32-octet key, '
277+
'got 16 octets; the ICV will very likely fail to verify'])
278+
279+
def test_a_key_of_the_right_size_does_not_warn(self) -> None:
280+
from pcapkit.protocols.internet.esp import Integrity
281+
from pcapkit.utilities.warnings import ProtocolWarning
282+
283+
with warnings.catch_warnings(record=True) as caught:
284+
warnings.simplefilter('always')
285+
self.sa(integrity=Integrity.HMAC_SHA2_256_128, integrity_key=bytes(32))
286+
287+
self.assertEqual([str(w.message) for w in caught
288+
if issubclass(w.category, ProtocolWarning)], [])
289+
290+
291+
if __name__ == '__main__':
292+
unittest.main()

0 commit comments

Comments
 (0)