Skip to content

Commit 051defa

Browse files
committed
fix(toolkit): the scapy adapters stop at the IP datagram's declared length (#1584)
Scapy files the octets past an IP layer's Total Length or Payload Length as a Padding layer, and bytes() of every layer above it ends with them. - ipv6_reassembly took the fragment's data, and so its tl, with the frame's trailer on the end: an 80-octet datagram reassembled to 84 octets. - tcp_reassembly and tcp_traceflow did the same to the TCP payload, len and last, so Ethernet padding and trailers entered TCP reassembly and traced flows. The segment now ends with the nearest IP datagram above it. - Jumbograms use pcapkit's own Jumbo Payload Length, since Scapy misreads it and splits nothing off. - ipv4_reassembly is unchanged: it hands the trailer on as the default engine's adapter does, and the reassembler cuts at tl - ihl. Tests: every adapter matches the default engine on 11 frames; all six new tests fail on main.
1 parent e9f3340 commit 051defa

2 files changed

Lines changed: 316 additions & 7 deletions

File tree

‎pcapkit/toolkit/scapy.py‎

Lines changed: 86 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,78 @@ def packet2frame(packet: 'Packet') -> 'FrameRecord':
226226
), time_epoch=decimal.Decimal(epoch))
227227

228228

229+
def _within_datagram(ip: 'IP | IPv6', layer: 'Packet') -> 'bytes':
230+
"""Return the octets from ``layer`` on that lie inside the datagram ``ip``.
231+
232+
Args:
233+
ip: IPv4 or IPv6 layer of a dissected Scapy packet.
234+
layer: A layer below ``ip``, or its empty payload.
235+
236+
Returns:
237+
The octets of ``layer`` and everything after it, up to where ``ip``'s
238+
Total Length or Payload Length ends the datagram.
239+
240+
Note:
241+
When `Scapy`_ dissects an IP layer, it files whatever follows the
242+
datagram's declared length as a :class:`~scapy.packet.Padding` layer --
243+
an Ethernet frame's padding up to its 60-octet minimum, or a trailer
244+
such as an FCS -- and ``bytes()`` of *any* layer above that one ends
245+
with it. Those octets are no part of the datagram, and the default
246+
engine never hands them over (:issue:`1584`), so they are cut off here
247+
by the default engine's rules: an IPv4 Total Length of zero, as TCP
248+
segmentation offload leaves, runs the datagram to the end of the frame
249+
(:issue:`1547`), and an IPv6 Payload Length of zero gives way to a
250+
Jumbo Payload option (:issue:`1434`). The latter is not left to Scapy,
251+
which reads that option's length in host byte order and adds the
252+
Hop-by-Hop Options header to it a second time.
253+
254+
"""
255+
from scapy.layers.inet6 import IPv6
256+
257+
data = bytes(layer)
258+
if isinstance(ip, IPv6):
259+
length = ip.plen
260+
if length is None: # a packet built by hand
261+
return data
262+
if not length: # a jumbogram's, or else it declares nothing
263+
from pcapkit.protocols.schema.internet.ipv6 import jumbo_payload_length
264+
length = jumbo_payload_length(ip.nh, bytes(ip.payload)) or 0
265+
elif ip.len:
266+
length = max(ip.len - ip.ihl * 4, 0)
267+
else: # a packet built by hand, or by TSO
268+
return data
269+
# ``bytes()`` of a layer spans it and every layer after it, padding
270+
# included, so the difference is the octets from the end of the IP header
271+
# to ``layer``
272+
payload = bytes(ip.payload)
273+
return payload[:length][len(payload) - len(data):]
274+
275+
276+
def _tcp_segment(tcp: 'TCP') -> 'tuple[bytes, bytes]':
277+
"""Split the TCP segment ``tcp`` heads into its header and its payload.
278+
279+
Args:
280+
tcp: TCP layer of a dissected Scapy packet.
281+
282+
Returns:
283+
The header, as many octets as the Data Offset counts, and the payload
284+
after it, up to the end of the datagram that carries the segment, c.f.
285+
``_within_datagram()``. That datagram is the nearest IP layer above
286+
``tcp``, whose own length is what ends the segment when IP is tunnelled
287+
in IP; a ``tcp`` with none above it is taken whole.
288+
289+
"""
290+
from scapy.layers.inet import IP
291+
from scapy.layers.inet6 import IPv6
292+
293+
carrier = tcp.underlayer
294+
while carrier is not None and not isinstance(carrier, (IP, IPv6)):
295+
carrier = carrier.underlayer
296+
segment = bytes(tcp) if carrier is None else _within_datagram(carrier, tcp)
297+
hdr_len = tcp.dataofs * 4
298+
return segment[:hdr_len], segment[hdr_len:]
299+
300+
229301
def ipv4_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'IP_Packet[IPv4Address] | None':
230302
"""Make data for IPv4 reassembly.
231303
@@ -271,6 +343,10 @@ def ipv4_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'IP_Packet[IPv4Ad
271343
mf=bool(ipv4.flags.MF), # more fragment flag
272344
tl=ipv4.len, # total length, header includes
273345
header=bytes(ipv4)[:ipv4.ihl * 4], # raw bytes type header
346+
# NOTE: this keeps the octets past the Total Length, as the default
347+
# engine's adapter does, since the reassembly machinery cuts the
348+
# payload at ``tl - ihl`` itself. :func:`ipv6_reassembly` derives
349+
# its ``tl`` from the payload, so it has to cut them (:issue:`1584`).
274350
payload=bytearray(bytes(ipv4.payload)), # raw bytearray type payload
275351
timestamp=float(packet.time), # capture timestamp
276352
)
@@ -316,7 +392,9 @@ def ipv6_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'IP_Packet[IPv6Ad
316392
# the Fragment header, which is the only part of the header the
317393
# reassembled packet keeps (:rfc:`8200#section-4.5`).
318394
hdr_len = len(ipv6) - len(ipv6_frag)
319-
payload = bytearray(bytes(ipv6_frag.payload))
395+
# the fragment's data stops at the Payload Length, so neither it nor
396+
# ``tl`` below counts the frame's trailer (:issue:`1584`)
397+
payload = bytearray(_within_datagram(ipv6, ipv6_frag.payload))
320398

321399
data = IP_Packet(
322400
bufid=(
@@ -375,8 +453,9 @@ def tcp_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'TCP_Packet | None
375453

376454
if 'TCP' in packet:
377455
tcp = cast('TCP', packet['TCP'])
456+
header, payload = _tcp_segment(tcp)
378457

379-
raw_len = len(tcp.payload) # payload length, header excludes
458+
raw_len = len(payload) # payload length, header excludes
380459
data = TCP_Packet(
381460
bufid=(
382461
ipaddress.ip_address(ip.src), # source IP address
@@ -390,8 +469,8 @@ def tcp_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'TCP_Packet | None
390469
syn=bool(tcp.flags.S), # synchronise flag
391470
fin=bool(tcp.flags.F), # finish flag
392471
rst=bool(tcp.flags.R), # reset connection flag
393-
header=bytes(tcp)[:tcp.dataofs * 4], # raw bytes type header
394-
payload=bytearray(bytes(tcp.payload)), # raw bytearray type payload
472+
header=header, # raw bytes type header
473+
payload=bytearray(payload), # raw bytearray type payload
395474
first=tcp.seq, # first sequence number of payload
396475
last=tcp.seq + raw_len - 1, # last sequence number of payload
397476
len=raw_len, # payload length, header excludes
@@ -423,6 +502,7 @@ def tcp_traceflow(packet: 'Packet', *, count: 'int' = -1) -> 'TF_TCP_Packet | No
423502
if 'TCP' in packet:
424503
ip = cast('IP', packet['IP']) if 'IP' in packet else cast('IPv6', packet['IPv6'])
425504
tcp = cast('TCP', packet['TCP'])
505+
header, payload = _tcp_segment(tcp)
426506

427507
# NOTE: the link type of the interface the packet was read from, which
428508
# :class:`~pcapkit.foundation.engines.scapy.Scapy` attaches with
@@ -475,8 +555,8 @@ def tcp_traceflow(packet: 'Packet', *, count: 'int' = -1) -> 'TF_TCP_Packet | No
475555
timestamp=float(packet.time), # capture timestamp
476556
seq=tcp.seq, # TCP sequence number
477557
ack=tcp.ack, # TCP acknowledgement number
478-
header=bytes(tcp)[:tcp.dataofs * 4], # raw bytes type header
479-
payload=bytearray(bytes(tcp.payload)), # raw bytearray type payload
558+
header=header, # raw bytes type header
559+
payload=bytearray(payload), # raw bytearray type payload
480560
)
481561
return data
482562
return None

‎tests/toolkit/test_scapy_unit.py‎

Lines changed: 230 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,35 @@
44
from ipaddress import ip_address
55
import builtins
66
import importlib
7+
import os
8+
import struct
9+
import tempfile
710
import unittest
11+
import warnings
812
from unittest import mock
913

10-
from tests._support import purge_modules, reimport_once_per_class
14+
from tests._support import close_extractor, purge_modules, reimport_once_per_class
1115

1216
HAS_SCAPY = importlib.util.find_spec('scapy') is not None
1317
RUNTIME_DEPS = ('tbtrim', 'aenum', 'chardet', 'dictdumper')
1418
HAS_RUNTIME = all(importlib.util.find_spec(name) is not None for name in RUNTIME_DEPS)
1519

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

1737
@unittest.skipUnless(HAS_RUNTIME and HAS_SCAPY, 'runtime dependencies not installed')
1838
class ScapyToolkitTests(unittest.TestCase):
@@ -334,5 +354,214 @@ def test_tcp_traceflow_raises_for_an_ip_rooted_packet(self) -> None:
334354
self.assertEqual(before, after)
335355

336356

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+
337566
if __name__ == '__main__':
338567
unittest.main()

0 commit comments

Comments
 (0)