|
| 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