|
4 | 4 | from ipaddress import ip_address |
5 | 5 | import builtins |
6 | 6 | import importlib |
| 7 | +import os |
| 8 | +import struct |
| 9 | +import tempfile |
7 | 10 | import unittest |
| 11 | +import warnings |
8 | 12 | from unittest import mock |
9 | 13 |
|
10 | | -from tests._support import purge_modules, reimport_once_per_class |
| 14 | +from tests._support import close_extractor, purge_modules, reimport_once_per_class |
11 | 15 |
|
12 | 16 | HAS_SCAPY = importlib.util.find_spec('scapy') is not None |
13 | 17 | RUNTIME_DEPS = ('tbtrim', 'aenum', 'chardet', 'dictdumper') |
14 | 18 | HAS_RUNTIME = all(importlib.util.find_spec(name) is not None for name in RUNTIME_DEPS) |
15 | 19 |
|
| 20 | +#: Octets an Ethernet frame carries past its IP datagram -- an FCS, say. |
| 21 | +TRAILER = bytes.fromhex('deadbeef') |
| 22 | +#: The datagram #1584 sends as two 40-octet fragments. |
| 23 | +DATAGRAM = bytes(range(80)) |
| 24 | + |
| 25 | + |
| 26 | +def write_pcap(frames: 'list[bytes]') -> 'str': |
| 27 | + """Write ``frames`` to a temporary Ethernet PCAP file and return its path.""" |
| 28 | + fd, path = tempfile.mkstemp(suffix='.pcap') |
| 29 | + with os.fdopen(fd, 'wb') as file: |
| 30 | + file.write(struct.pack('<IHHiIII', 0xA1B2C3D4, 2, 4, 0, 0, 65535, 1)) |
| 31 | + for index, frame in enumerate(frames): |
| 32 | + file.write(struct.pack('<IIII', 1_600_000_000 + index, 0, len(frame), len(frame))) |
| 33 | + file.write(frame) |
| 34 | + return path |
| 35 | + |
16 | 36 |
|
17 | 37 | @unittest.skipUnless(HAS_RUNTIME and HAS_SCAPY, 'runtime dependencies not installed') |
18 | 38 | class ScapyToolkitTests(unittest.TestCase): |
@@ -334,5 +354,214 @@ def test_tcp_traceflow_raises_for_an_ip_rooted_packet(self) -> None: |
334 | 354 | self.assertEqual(before, after) |
335 | 355 |
|
336 | 356 |
|
| 357 | +@unittest.skipUnless(HAS_RUNTIME and HAS_SCAPY, 'runtime dependencies not installed') |
| 358 | +class ScapyTrailerTests(unittest.TestCase): |
| 359 | + """The adapters stop at the datagram's declared length (GitHub issue #1584). |
| 360 | +
|
| 361 | + Scapy files the octets past an IP layer's Total Length or Payload Length as a |
| 362 | + ``Padding`` layer, and ``bytes()`` of every layer above it ends with them, so |
| 363 | + an IPv6 fragment's data and a TCP segment's payload both carried the frame's |
| 364 | + trailer. Every frame here is written to a capture and read back through the |
| 365 | + engine, and the default engine reads the same capture for comparison. |
| 366 | +
|
| 367 | + """ |
| 368 | + |
| 369 | + #: The TCP payload each of :meth:`_tcp_frames` carries. |
| 370 | + TCP_PAYLOADS = { |
| 371 | + 'padded': b'X', |
| 372 | + 'trailer': b'YZ', |
| 373 | + 'pure-ack-padded': b'', |
| 374 | + 'ipv6-ext-header-trailer': b'six', |
| 375 | + 'ip-in-ip-trailers': b'in', |
| 376 | + 'jumbogram-trailer': b'jmb', |
| 377 | + 'zero-total-length': b'tso-data', |
| 378 | + } |
| 379 | + |
| 380 | + def setUp(self) -> None: |
| 381 | + reimport_once_per_class(self) |
| 382 | + |
| 383 | + def _ether(self): |
| 384 | + from scapy.layers.l2 import Ether |
| 385 | + |
| 386 | + return Ether(src='aa:aa:aa:aa:aa:aa', dst='bb:bb:bb:bb:bb:bb') |
| 387 | + |
| 388 | + def _ip_frames(self) -> 'list[bytes]': |
| 389 | + """``DATAGRAM`` as IPv4, then as IPv6, fragments; each last one has a trailer.""" |
| 390 | + from scapy.layers.inet import IP |
| 391 | + from scapy.layers.inet6 import IPv6, IPv6ExtHdrFragment |
| 392 | + from scapy.packet import Raw |
| 393 | + |
| 394 | + ipv4 = {'src': '192.0.2.1', 'dst': '198.51.100.1', 'id': 7, 'proto': 17} |
| 395 | + ipv6 = {'src': '2001:db8::1', 'dst': '2001:db8::2'} |
| 396 | + return [ |
| 397 | + bytes(self._ether() / IP(**ipv4, flags='MF', frag=0) / Raw(DATAGRAM[:40])), |
| 398 | + bytes(self._ether() / IP(**ipv4, frag=5) / Raw(DATAGRAM[40:])) + TRAILER, |
| 399 | + bytes(self._ether() / IPv6(**ipv6) / |
| 400 | + IPv6ExtHdrFragment(nh=17, offset=0, m=1, id=99) / Raw(DATAGRAM[:40])), |
| 401 | + bytes(self._ether() / IPv6(**ipv6) / |
| 402 | + IPv6ExtHdrFragment(nh=17, offset=5, m=0, id=99) / Raw(DATAGRAM[40:])) + TRAILER, |
| 403 | + ] |
| 404 | + |
| 405 | + def _tcp_frames(self) -> 'list[bytes]': |
| 406 | + """One frame per :attr:`TCP_PAYLOADS` entry, in its order.""" |
| 407 | + from scapy.layers.inet import IP, TCP |
| 408 | + from scapy.layers.inet6 import IPv6, IPv6ExtHdrDestOpt, IPv6ExtHdrHopByHop, Jumbo |
| 409 | + from scapy.packet import Raw |
| 410 | + |
| 411 | + ipv4 = {'src': '192.0.2.1', 'dst': '198.51.100.1'} |
| 412 | + ipv6 = {'src': '2001:db8::1', 'dst': '2001:db8::2'} |
| 413 | + |
| 414 | + def padded(frame: 'bytes') -> 'bytes': |
| 415 | + return frame + bytes(60 - len(frame)) # Ethernet's minimum frame |
| 416 | + |
| 417 | + inner = bytes(IP(src='10.0.0.1', dst='10.0.0.2') / TCP(sport=5, dport=6, flags='PA') / |
| 418 | + Raw(b'in')) + b'\xaa\xbb' |
| 419 | + tso = bytes(self._ether() / IP(**ipv4) / TCP(sport=9, dport=10, flags='PA') / Raw(b'tso-data')) |
| 420 | + return [ |
| 421 | + padded(bytes(self._ether() / IP(**ipv4) / TCP(sport=1, dport=2, seq=100, flags='PA') / |
| 422 | + Raw(b'X'))), |
| 423 | + bytes(self._ether() / IP(**ipv4) / TCP(sport=1, dport=2, seq=101, flags='PA') / |
| 424 | + Raw(b'YZ')) + TRAILER, |
| 425 | + padded(bytes(self._ether() / IP(**ipv4) / TCP(sport=3, dport=4, seq=7, flags='A'))), |
| 426 | + bytes(self._ether() / IPv6(**ipv6) / IPv6ExtHdrDestOpt() / |
| 427 | + TCP(sport=1, dport=2, flags='PA') / Raw(b'six')) + TRAILER, |
| 428 | + bytes(self._ether() / IP(**ipv4, proto=4) / Raw(inner)) + TRAILER, |
| 429 | + # the Jumbo Payload Length counts the Hop-by-Hop Options header too |
| 430 | + bytes(self._ether() / IPv6(**ipv6, plen=0, nh=0) / |
| 431 | + IPv6ExtHdrHopByHop(nh=6, options=[Jumbo(jumboplen=8 + 20 + 3)]) / |
| 432 | + TCP(sport=7, dport=8, flags='PA') / Raw(b'jmb')) + TRAILER, |
| 433 | + # a Total Length of 0 runs the datagram to the end of the frame |
| 434 | + tso[:16] + b'\x00\x00' + tso[18:], |
| 435 | + ] |
| 436 | + |
| 437 | + def _extract(self, frames: 'list[bytes]', engine: 'str' = 'scapy', **kwargs: 'object'): |
| 438 | + import pcapkit |
| 439 | + |
| 440 | + path = write_pcap(frames) |
| 441 | + self.addCleanup(os.remove, path) |
| 442 | + with warnings.catch_warnings(): |
| 443 | + warnings.simplefilter('ignore') |
| 444 | + extractor = pcapkit.extract(fin=path, nofile=True, engine=engine, **kwargs) |
| 445 | + self.addCleanup(close_extractor, extractor) |
| 446 | + return extractor |
| 447 | + |
| 448 | + def test_ipv6_fragment_data_stops_at_the_payload_length(self) -> None: |
| 449 | + from pcapkit.toolkit import scapy as toolkit |
| 450 | + |
| 451 | + packets = self._extract(self._ip_frames(), store=True).frame |
| 452 | + first, last = (toolkit.ipv6_reassembly(packet) for packet in packets[2:]) |
| 453 | + assert first is not None and last is not None |
| 454 | + self.assertEqual(bytes(first.payload), DATAGRAM[:40]) |
| 455 | + # 44 octets and a ``tl`` of 84 before the fix |
| 456 | + self.assertEqual(bytes(last.payload), DATAGRAM[40:]) |
| 457 | + self.assertEqual((last.ihl, last.tl), (40, 80)) |
| 458 | + |
| 459 | + def test_reassembled_datagrams_are_the_datagram_sent(self) -> None: |
| 460 | + extractor = self._extract(self._ip_frames(), store=False, reassembly=True, ip=True) |
| 461 | + for name, datagrams in (('ipv4', extractor.reassembly.ipv4), |
| 462 | + ('ipv6', extractor.reassembly.ipv6)): |
| 463 | + with self.subTest(version=name): |
| 464 | + datagram, = datagrams |
| 465 | + # only ``Completion.COMPLETE`` is truthy |
| 466 | + self.assertTrue(datagram.completed) |
| 467 | + # IPv6 came back 84 octets long, ending in the trailer |
| 468 | + self.assertEqual(datagram.payload, DATAGRAM) |
| 469 | + |
| 470 | + def test_tcp_payload_stops_at_the_datagram_end(self) -> None: |
| 471 | + from scapy.layers.inet import TCP |
| 472 | + |
| 473 | + from pcapkit.toolkit import scapy as toolkit |
| 474 | + |
| 475 | + packets = self._extract(self._tcp_frames(), store=True).frame |
| 476 | + self.assertEqual(len(packets), len(self.TCP_PAYLOADS)) |
| 477 | + for (name, expected), packet in zip(self.TCP_PAYLOADS.items(), packets): |
| 478 | + with self.subTest(frame=name): |
| 479 | + header = bytes(packet[TCP])[:20] |
| 480 | + segment = toolkit.tcp_reassembly(packet) |
| 481 | + assert segment is not None |
| 482 | + self.assertEqual(bytes(segment.payload), expected) |
| 483 | + self.assertEqual(segment.len, len(expected)) |
| 484 | + self.assertEqual(segment.last, segment.first + len(expected) - 1) |
| 485 | + self.assertEqual(segment.header, header) |
| 486 | + |
| 487 | + flow = toolkit.tcp_traceflow(packet) |
| 488 | + assert flow is not None |
| 489 | + self.assertEqual(bytes(flow.payload), expected) |
| 490 | + self.assertEqual(flow.header, header) |
| 491 | + |
| 492 | + def test_tcp_reassembly_is_the_stream_sent(self) -> None: |
| 493 | + def streams(engine: 'str') -> 'dict[tuple[str, int], bytes]': |
| 494 | + extractor = self._extract(self._tcp_frames(), engine=engine, store=False, |
| 495 | + reassembly=True, tcp=True) |
| 496 | + return {(str(datagram.id.src[0]), datagram.id.src[1]): datagram.payload |
| 497 | + for datagram in extractor.reassembly.tcp} |
| 498 | + |
| 499 | + scapy = streams('scapy') |
| 500 | + # ``b'X\x00\x00\x00\x00\x00\xef'`` before the fix: the first segment's |
| 501 | + # padding took the place of the second's data, and its trailer followed |
| 502 | + self.assertEqual(scapy.get(('192.0.2.1', 1)), b'XYZ') |
| 503 | + self.assertEqual(scapy.get(('2001:db8::1', 1)), b'six') |
| 504 | + self.assertEqual(scapy, streams('default')) |
| 505 | + |
| 506 | + def test_every_adapter_agrees_with_the_default_engine(self) -> None: |
| 507 | + from pcapkit.const.reg.linktype import LinkType |
| 508 | + from pcapkit.toolkit import pcap as toolkit_pcap |
| 509 | + from pcapkit.toolkit import scapy as toolkit |
| 510 | + |
| 511 | + frames = self._ip_frames() + self._tcp_frames() |
| 512 | + packets = self._extract(frames, store=True).frame |
| 513 | + defaults = self._extract(frames, engine='default', store=True).frame |
| 514 | + self.assertEqual(len(packets), len(defaults)) |
| 515 | + |
| 516 | + def fields(data: 'object', names: 'tuple[str, ...]') -> 'object': |
| 517 | + if data is None: |
| 518 | + return None |
| 519 | + return {name: bytes(value) if isinstance(value, (bytes, bytearray)) else value |
| 520 | + for name, value in ((name, getattr(data, name)) for name in names)} |
| 521 | + |
| 522 | + ip_fields = ('fo', 'ihl', 'mf', 'tl', 'header', 'payload') |
| 523 | + tcp_fields = ('dsn', 'ack', 'header', 'payload', 'first', 'last', 'len') |
| 524 | + trace_fields = ('seq', 'ack', 'header', 'payload') |
| 525 | + compared = 0 |
| 526 | + for index, (packet, default) in enumerate(zip(packets, defaults)): |
| 527 | + for adapter, expected, actual in ( |
| 528 | + ('ipv4', fields(toolkit_pcap.ipv4_reassembly(default), ip_fields), |
| 529 | + fields(toolkit.ipv4_reassembly(packet), ip_fields)), |
| 530 | + ('ipv6', fields(toolkit_pcap.ipv6_reassembly(default), ip_fields), |
| 531 | + fields(toolkit.ipv6_reassembly(packet), ip_fields)), |
| 532 | + ('tcp', fields(toolkit_pcap.tcp_reassembly(default), tcp_fields), |
| 533 | + fields(toolkit.tcp_reassembly(packet), tcp_fields)), |
| 534 | + ('trace', fields(toolkit_pcap.tcp_traceflow(default, data_link=LinkType.ETHERNET), |
| 535 | + trace_fields), |
| 536 | + fields(toolkit.tcp_traceflow(packet), trace_fields)), |
| 537 | + ): |
| 538 | + compared += expected is not None |
| 539 | + with self.subTest(frame=index, adapter=adapter): |
| 540 | + self.assertEqual(actual, expected) |
| 541 | + # every IPv4 frame here leaves DF clear, so each of the 7 makes an IPv4 |
| 542 | + # record; then the 2 IPv6 fragments, and a TCP and a trace record for |
| 543 | + # each TCP frame |
| 544 | + self.assertEqual(compared, 7 + 2 + 2 * len(self.TCP_PAYLOADS)) |
| 545 | + |
| 546 | + def test_data_with_no_length_to_stop_at_is_taken_whole(self) -> None: |
| 547 | + from scapy.layers.inet import TCP |
| 548 | + from scapy.layers.inet6 import IPv6, IPv6ExtHdrFragment |
| 549 | + from scapy.packet import Raw |
| 550 | + |
| 551 | + from pcapkit.toolkit import scapy as toolkit |
| 552 | + |
| 553 | + # a segment with no IP layer above it at all |
| 554 | + tcp = TCP(bytes(TCP(sport=1, dport=2, flags='PA') / Raw(b'bare'))) |
| 555 | + self.assertEqual(toolkit._tcp_segment(tcp), (bytes(tcp)[:20], b'bare')) |
| 556 | + |
| 557 | + # a fragment built by hand, whose Payload Length is only filled in when |
| 558 | + # the packet is built |
| 559 | + packet = self._ether() / IPv6() / IPv6ExtHdrFragment(id=1) / Raw(b'hand') |
| 560 | + self.assertIsNone(packet[IPv6].plen) |
| 561 | + fragment = toolkit.ipv6_reassembly(packet) |
| 562 | + assert fragment is not None |
| 563 | + self.assertEqual(bytes(fragment.payload), b'hand') |
| 564 | + |
| 565 | + |
337 | 566 | if __name__ == '__main__': |
338 | 567 | unittest.main() |
0 commit comments