|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""A header length declared past the data, and TS address keys given as strings. |
| 3 | +
|
| 4 | +GitHub issue #1404: an IPv4 ``ihl`` or a TCP Data Offset declaring more header |
| 5 | +than the data holds read the missing octets as zeros, and ``from_data`` rebuilt |
| 6 | +them -- 34 octets in and 38 out for an Ethernet frame whose IPv4 ``ihl`` is 6 |
| 7 | +with only 20 header octets present. Such a header now raises |
| 8 | +:exc:`~pcapkit.utilities.exceptions.ProtocolError`, so its parent keeps the |
| 9 | +octets as a :class:`~pcapkit.protocols.misc.raw.Raw` payload and rebuilds them |
| 10 | +byte for byte. |
| 11 | +
|
| 12 | +GitHub issue #1402: ``IPv4.make()`` called :func:`int` on each key of a TS |
| 13 | +option's ``timestamp`` mapping, so a dotted-quad string key raised a bare |
| 14 | +:exc:`ValueError`. The keys are now converted as addresses, and a :obj:`bool` |
| 15 | +key is rejected with :exc:`~pcapkit.utilities.exceptions.FieldValueError`. |
| 16 | +
|
| 17 | +Every case builds its own octets in memory and reads no capture. |
| 18 | +
|
| 19 | +""" |
| 20 | + |
| 21 | +import struct |
| 22 | +import unittest |
| 23 | +import warnings |
| 24 | + |
| 25 | +from tests._support import reimport_once_per_class |
| 26 | + |
| 27 | +_ETH = bytes.fromhex('0123456789ab fedcba987654 0800') |
| 28 | + |
| 29 | + |
| 30 | +def _ipv4(ihl: int, proto: int, body: bytes) -> bytes: |
| 31 | + """An IPv4 header declaring ``ihl``, followed by ``body``.""" |
| 32 | + return (bytes([0x40 | ihl, 0]) + struct.pack('>H', 20 + len(body)) |
| 33 | + + bytes.fromhex('00010000 40') + bytes([proto]) + bytes(2) |
| 34 | + + bytes.fromhex('0a000001 0a000002') + body) |
| 35 | + |
| 36 | + |
| 37 | +def _tcp(offset: int, opts: bytes = b'') -> bytes: |
| 38 | + """A TCP header declaring ``offset``, followed by ``opts``.""" |
| 39 | + return struct.pack('>HHIIBBHHH', 1, 2, 0, 0, offset << 4, 0x10, 0, 0, 0) + opts |
| 40 | + |
| 41 | + |
| 42 | +#: Layers whose declared header length runs past the data: (module, class, octets). |
| 43 | +SHORT = { |
| 44 | + # issue #1404: options declared, none present |
| 45 | + 'IPv4 ihl=6, 20 octets': ('pcapkit.protocols.internet.ipv4', 'IPv4', _ipv4(6, 253, b'')), |
| 46 | + 'IPv4 ihl=7, 24 octets': ('pcapkit.protocols.internet.ipv4', 'IPv4', _ipv4(7, 253, bytes.fromhex('01010101'))), |
| 47 | + 'TCP offset=6, 20 octets': ('pcapkit.protocols.transport.tcp', 'TCP', _tcp(6)), |
| 48 | + 'TCP offset=10, 28 octets': ('pcapkit.protocols.transport.tcp', 'TCP', _tcp(10, bytes.fromhex('0101010101010101'))), |
| 49 | +} |
| 50 | + |
| 51 | +#: Each short layer inside its parent: (parent module, parent class, frame). |
| 52 | +IN_PARENT = { |
| 53 | + 'IPv4 ihl=6, 20 octets': ('pcapkit.protocols.link.ethernet', 'Ethernet', _ETH + SHORT['IPv4 ihl=6, 20 octets'][2]), |
| 54 | + 'IPv4 ihl=7, 24 octets': ('pcapkit.protocols.link.ethernet', 'Ethernet', _ETH + SHORT['IPv4 ihl=7, 24 octets'][2]), |
| 55 | + 'TCP offset=6, 20 octets': ('pcapkit.protocols.internet.ipv4', 'IPv4', |
| 56 | + _ipv4(5, 6, SHORT['TCP offset=6, 20 octets'][2])), |
| 57 | + 'TCP offset=10, 28 octets': ('pcapkit.protocols.internet.ipv4', 'IPv4', |
| 58 | + _ipv4(5, 6, SHORT['TCP offset=10, 28 octets'][2])), |
| 59 | +} |
| 60 | + |
| 61 | + |
| 62 | +class TestHeaderLengthOverrun(unittest.TestCase): |
| 63 | + """Pin the rejection of a header length running past the end of its data.""" |
| 64 | + |
| 65 | + def setUp(self) -> None: |
| 66 | + reimport_once_per_class(self) |
| 67 | + |
| 68 | + @staticmethod |
| 69 | + def _protocol(module: str, name: str) -> type: |
| 70 | + import importlib |
| 71 | + |
| 72 | + return getattr(importlib.import_module(module), name) |
| 73 | + |
| 74 | + def test_a_short_header_raises_protocol_error(self) -> None: |
| 75 | + from pcapkit.utilities.exceptions import ProtocolError |
| 76 | + |
| 77 | + for case, (module, name, data) in SHORT.items(): |
| 78 | + with self.subTest(case=case): |
| 79 | + protocol = self._protocol(module, name) |
| 80 | + with warnings.catch_warnings(): |
| 81 | + warnings.simplefilter('ignore') |
| 82 | + with self.assertRaisesRegex(ProtocolError, 'header length .* runs past the end of the data'): |
| 83 | + protocol(data, len(data)) |
| 84 | + |
| 85 | + def test_a_short_header_is_kept_as_captured_by_its_parent(self) -> None: |
| 86 | + from pcapkit.protocols.misc.raw import Raw |
| 87 | + |
| 88 | + for case, (module, name, frame) in IN_PARENT.items(): |
| 89 | + with self.subTest(case=case): |
| 90 | + protocol = self._protocol(module, name) |
| 91 | + with warnings.catch_warnings(): |
| 92 | + warnings.simplefilter('ignore') |
| 93 | + parsed = protocol(frame, len(frame)) |
| 94 | + self.assertIsInstance(parsed.payload, Raw) |
| 95 | + self.assertEqual(parsed.payload.data, SHORT[case][2]) |
| 96 | + self.assertEqual(protocol.from_data(parsed.info).data, frame) |
| 97 | + |
| 98 | + def test_a_complete_header_still_rebuilds_byte_for_byte(self) -> None: |
| 99 | + # the same option areas, every declared octet present |
| 100 | + for module, name, data in (('pcapkit.protocols.internet.ipv4', 'IPv4', _ipv4(6, 253, bytes(4))), |
| 101 | + ('pcapkit.protocols.transport.tcp', 'TCP', _tcp(6, bytes(4)))): |
| 102 | + with self.subTest(name=name): |
| 103 | + protocol = self._protocol(module, name) |
| 104 | + parsed = protocol(data, len(data)) |
| 105 | + self.assertEqual(protocol.from_data(parsed.info).data, data) |
| 106 | + |
| 107 | + |
| 108 | +class TestTimestampAddressKeys(unittest.TestCase): |
| 109 | + """Pin the conversion of a TS option's address keys on ``make()``.""" |
| 110 | + |
| 111 | + def setUp(self) -> None: |
| 112 | + reimport_once_per_class(self) |
| 113 | + |
| 114 | + def _make(self, key: object) -> bytes: |
| 115 | + from datetime import timedelta |
| 116 | + |
| 117 | + from pcapkit.const.ipv4.option_number import OptionNumber |
| 118 | + from pcapkit.protocols.internet.ipv4 import IPv4 |
| 119 | + |
| 120 | + return IPv4(options=[(OptionNumber.TS, {'timestamp': {key: timedelta(milliseconds=1)}})], |
| 121 | + protocol=253).data |
| 122 | + |
| 123 | + def test_a_string_key_builds_like_an_address_key(self) -> None: |
| 124 | + from ipaddress import IPv4Address |
| 125 | + |
| 126 | + from pcapkit.protocols.internet.ipv4 import IPv4 |
| 127 | + |
| 128 | + expected = self._make(IPv4Address('1.2.3.4')) |
| 129 | + data = self._make('1.2.3.4') |
| 130 | + self.assertEqual(data, expected) |
| 131 | + self.assertEqual(data[20:32], bytes.fromhex('44240d01 01020304 00000001')) |
| 132 | + self.assertEqual(IPv4(data, len(data)).data, data) |
| 133 | + |
| 134 | + def test_a_string_key_in_parsed_data_rebuilds(self) -> None: |
| 135 | + from datetime import timedelta |
| 136 | + from ipaddress import IPv4Address |
| 137 | + |
| 138 | + from pcapkit.corekit.multidict import OrderedMultiDict |
| 139 | + from pcapkit.protocols.internet.ipv4 import IPv4 |
| 140 | + |
| 141 | + data = self._make(IPv4Address('1.2.3.4')) |
| 142 | + parsed = IPv4(data, len(data)) |
| 143 | + option = next(iter(parsed.info.options.values())) |
| 144 | + option.__update__(timestamp=OrderedMultiDict([('1.2.3.4', timedelta(milliseconds=1))])) |
| 145 | + self.assertEqual(IPv4.from_data(parsed.info).data, data) |
| 146 | + |
| 147 | + def test_a_bool_key_raises_field_value_error(self) -> None: |
| 148 | + from pcapkit.utilities.exceptions import FieldValueError |
| 149 | + |
| 150 | + with self.assertRaisesRegex(FieldValueError, 'timestamp address: must not be a bool'): |
| 151 | + self._make(True) |
| 152 | + |
| 153 | + def test_an_invalid_key_raises_field_value_error(self) -> None: |
| 154 | + from pcapkit.utilities.exceptions import FieldValueError |
| 155 | + |
| 156 | + with self.assertRaisesRegex(FieldValueError, 'timestamp address'): |
| 157 | + self._make('1.2.3') |
| 158 | + |
| 159 | + |
| 160 | +if __name__ == '__main__': |
| 161 | + unittest.main() |
0 commit comments