Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions examples/generators/pcap.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@
Pinned by ``tests/protocols/internet/test_ip_runtime.py`` and
``tests/protocols/transport/test_udp_runtime.py``.

``ipv4-frag.pcap`` (7 frames)
UDP between two hosts on a 1500-octet MTU link: a whole datagram with DF
set, a 3208-octet datagram in three fragments with DF clear, the second
delivered last, a whole datagram with DF clear, and a 2008-octet datagram
in two fragments that both carry DF. Exercises IPv4 reassembly, which takes
fragments only, whatever their DF flag, as Wireshark does (#2961, #3216).
Pinned by ``tests/integration/test_reassembly_end_to_end.py`` and
``tests/integration/test_reassembly_engine_parity.py``.

``ipv6.pcap`` (16 frames)
Link-local IPv6 between two hosts: neighbour discovery, ICMPv6 echoes,
and then a 4778-octet UDP datagram fragmented into four pieces
Expand Down Expand Up @@ -535,6 +544,60 @@ def build(index: 'int', word: 'int') -> 'Packet':
return capture.write(dest / 'ipv4.pcap')


###############################################################################
# examples/captures/ipv4-frag.pcap
###############################################################################


def _write_ipv4_frag(dest: 'pathlib.Path') -> 'pathlib.Path':
"""Write ``ipv4-frag.pcap``.

Two whole datagrams, and two fragmented to fit a 1500-octet MTU, every
fragment but the last of each carrying 1480 octets of data.

Args:
dest: Destination directory.

Returns:
The path written.

"""
local = _Endpoint('00:0c:29:5b:8e:12', '192.168.88.20')
peer = _Endpoint('00:0c:29:a4:07:3c', '192.168.88.31')
capture = _Capture(step=0.000517)

def datagram(ident: 'int', length: 'int') -> 'bytes':
# the UDP datagram the fragments carry, its checksum over the whole of it
return bytes(IP(src=local.ip, dst=peer.ip, id=ident)
/ UDP(sport=40812, dport=5001)
/ Raw(load=_filler(length - 8, b'ipv4-frag/%d' % ident)))[20:]

def frame(ident: 'int', flags: 'str', offset: 'int', data: 'bytes') -> 'Packet':
return (Ether(src=local.mac, dst=peer.mac)
/ IP(src=local.ip, dst=peer.ip, ttl=64, id=ident, flags=flags,
frag=offset // 8, proto=17)
/ Raw(load=data))

# 0: a whole datagram with DF set, an atomic datagram (RFC 6864)
capture.add(frame(0x5a00, 'DF', 0, datagram(0x5a00, 128)))

# 1-3: three fragments with DF clear, the second delivered last
whole = datagram(0x5a01, 3208)
for offset in (0, 2960, 1480):
more = offset + 1480 < len(whole)
capture.add(frame(0x5a01, 'MF' if more else '', offset, whole[offset:offset + 1480]))

# 4: a whole datagram with DF clear
capture.add(frame(0x5a02, '', 0, datagram(0x5a02, 128)))

# 5-6: two fragments that both carry DF
whole = datagram(0x5a03, 2008)
capture.add(frame(0x5a03, 'DF+MF', 0, whole[:1480]))
capture.add(frame(0x5a03, 'DF', 1480, whole[1480:]))

return capture.write(dest / 'ipv4-frag.pcap')


###############################################################################
# examples/captures/ipv6.pcap
###############################################################################
Expand Down Expand Up @@ -1132,6 +1195,7 @@ def generate(dest: 'pathlib.Path | None' = None) -> 'list[pathlib.Path]':
return [
_write_arp(dest),
_write_ipv4(dest),
_write_ipv4_frag(dest),
_write_ipv6(dest),
_write_tcp(dest),
_write_stream(dest),
Expand Down
15 changes: 11 additions & 4 deletions pcapkit/toolkit/dpkt.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,9 +581,10 @@ def ipv4_reassembly(packet: 'Packet', timestamp: 'float', *,
"""Make data for IPv4 reassembly.

A packet can be reassembled if it has an IPv4 layer (:class:`dpkt.ip.IP`) whose
header was captured whole, and the **DF** (:attr:`dpkt.ip.IP.df`) flag is
:data:`False`. The layer is the first that is a fragment, or with none, the network
layer if it is IPv4 (see :func:`_fragment`).
header was captured whole, and that is a fragment, with **MF** set or a non-zero
fragment offset, whatever its **DF** (:attr:`dpkt.ip.IP.df`) flag, as
:func:`pcapkit.toolkit.pcap._ipv4_fragment` reads one. The layer is the first that
is a fragment (see :func:`_fragment`).

Args:
packet: DPKT packet.
Expand Down Expand Up @@ -628,10 +629,16 @@ def ipv4_reassembly(packet: 'Packet', timestamp: 'float', *,
``timestamp`` is a new second positional parameter, so a 1.4.x call
with ``packet`` alone fails.

.. versionchanged:: 1.10.0

A packet is reassembled if its IPv4 layer is a fragment, with **DF** set or
clear, rather than whenever **DF** is clear, so a whole datagram is not
(:issue:`3216`).

"""
ipv4 = cast('Optional[IP]', _fragment(packet, 4))
if ipv4 is not None:
if ipv4.df: # dismiss not fragmented packet
if not (ipv4.mf or ipv4.offset): # dismiss whole datagram
return None
# internet header length, in octets -- ``IP.hl`` counts 32-bit words and
# covers any IP options, whereas ``IP.__hdr_len__`` is the fixed 20-octet
Expand Down
12 changes: 10 additions & 2 deletions pcapkit/toolkit/pypcapfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,9 @@ def ipv4_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'IP_Packet[IPv4Ad

A packet can be reassembled if it contains an IPv4 layer
(``pcapfile.protocols.network.ip.IP``) whose header was captured whole (see
:func:`_network`), and the **DF** flag is :data:`False`.
:func:`_network`), and that is a fragment, with **MF** set or a non-zero
fragment offset, whatever its **DF** flag, as
:func:`pcapkit.toolkit.pcap._ipv4_fragment` reads one.

Args:
packet: PyPCAPFile packet.
Expand All @@ -745,11 +747,17 @@ def ipv4_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'IP_Packet[IPv4Ad
See Also:
:class:`pcapkit.foundation.reassembly.ipv4.reassembly.IPv4`

.. versionchanged:: 1.10.0

A packet is reassembled if its IPv4 layer is a fragment, with **DF** set or
clear, rather than whenever **DF** is clear, so a whole datagram is not
(:issue:`3216`).

"""
ipv4 = _network(packet)
if ipv4 is None:
return None
if ipv4.flags & IPV4_FLAG_DF: # dismiss not fragmented packet
if not (ipv4.flags & IPV4_FLAG_MF or ipv4.off): # dismiss whole datagram
return None

header = ipv4_header(ipv4)
Expand Down
21 changes: 13 additions & 8 deletions pcapkit/toolkit/scapy.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,11 +529,12 @@ def ipv4_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'IP_Packet[IPv4Ad
A packet can be reassembled if it contains an IPv4 layer
(:class:`scapy.layers.inet.IP`) whose header -- as many octets as its IHL counts,
and at least 20 -- lies inside the frame and every IP datagram carrying it (see
:func:`_within_datagrams`), and the **DF** (``scapy.layers.inet.IP.flags.DF``)
flag is :data:`False`. A zero-length frame has none, though `Scapy`_ hands it back
as an IPv4 layer of defaults at the ``RAW`` and ``IPV4`` link types (see
:func:`_frame`). In an IP-in-IP tunnel, the layer is the first that is a
fragment (see :func:`_fragment`).
:func:`_within_datagrams`), and that is a fragment, with **MF** set or a non-zero
fragment offset, whatever its **DF** (``scapy.layers.inet.IP.flags.DF``) flag, as
:func:`pcapkit.toolkit.pcap._ipv4_fragment` reads one. A zero-length frame has
none, since the IPv4 layer of defaults `Scapy`_ hands it back as at the ``RAW``
and ``IPV4`` link types (see :func:`_frame`) is no fragment. In an IP-in-IP
tunnel, the layer is the first that is a fragment (see :func:`_fragment`).

Args:
packet: Scapy packet.
Expand All @@ -546,11 +547,15 @@ def ipv4_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'IP_Packet[IPv4Ad
See Also:
:class:`pcapkit.foundation.reassembly.ipv4.reassembly.IPv4`

.. versionchanged:: 1.10.0

A packet is reassembled if its IPv4 layer is a fragment, with **DF** set or
clear, rather than whenever **DF** is clear, so a whole datagram is not
(:issue:`3216`).

"""
if (ipv4 := cast('IP | None', _fragment(packet, 'IP'))) is not None:
if ipv4.flags.DF: # dismiss not fragmented packet
return None
if not _frame(packet): # a zero-length frame (#1676)
if not (ipv4.flags.MF or ipv4.frag): # dismiss whole datagram
return None
# NOTE: keep only the octets inside every enclosing datagram, dropping the
# trailer Scapy files as padding (#1623); read IHL and Total Length off them (#1676).
Expand Down
15 changes: 11 additions & 4 deletions tests/foundation/engines/test_dpkt_raw_null_linktypes_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,15 @@
import warnings

from tests._support import reimport_once_per_class
from tests.protocols.link.test_loopback_unit import IPV4, IPV6, _pcap
from tests.protocols.link.test_loopback_unit import IPV4 as IPV4_WHOLE
from tests.protocols.link.test_loopback_unit import IPV6, _pcap

HAS_DPKT = importlib.util.find_spec('dpkt') is not None

#: The loopback tests' IPv4 datagram with **MF** set, a first fragment, which IPv4
#: reassembly reads where it reads no whole datagram (#3216).
IPV4 = IPV4_WHOLE[:6] + bytes([IPV4_WHOLE[6] | 0x20]) + IPV4_WHOLE[7:]

#: ``(link type, records, dpkt class name per record)``.
CAPTURES = (
(101, [IPV4, IPV6, b'\x50' + IPV4[1:]], ['IP', 'IP6', 'RawPacket']),
Expand Down Expand Up @@ -78,8 +83,7 @@ def test_frames_parse_into_their_network_layer(self) -> None:
record[4:] if loopback else record)

def test_reassembly_inputs_are_the_captured_datagrams(self) -> None:
# each frame read as IPv4 is one whole datagram: IPV4's header, then its UDP
# header; IPv4 reassembly takes no whole datagram (#2961), so it reports none
# each frame read as IPv4 is one first fragment: IPV4's header, then its UDP header
from pcapkit.toolkit.dpkt import ipv4_reassembly

for (linktype, records, _), frames in zip(CAPTURES, ((1,), (1, 2), (1,))):
Expand All @@ -90,7 +94,10 @@ def test_reassembly_inputs_are_the_captured_datagrams(self) -> None:
self.assertEqual([(data.num, bytes(data.header), bytes(data.payload))
for data in inputs if data is not None],
[(frame, IPV4[:20], IPV4[20:]) for frame in frames])
self.assertEqual(list(dpkt.reassembly.ipv4), [])
# the capture's fragments, each at offset zero, are one unfinished datagram
datagram, = dpkt.reassembly.ipv4
self.assertEqual((datagram.index, datagram.payload), (frames, (IPV4[20:],)))
self.assertFalse(datagram.completed)

def test_get_protocol_by_link_type(self) -> None:
import dpkt
Expand Down
58 changes: 55 additions & 3 deletions tests/integration/test_reassembly_end_to_end.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,8 @@ class IPv4ReassemblyTests(EndToEndTestCase):

The fixture is a multicast stream captured on the sending host, so none of
its four datagrams is fragmented, and IPv4 reassembly, which takes fragments
only, submits none of them (#2961). No fixture in the repository carries
IPv4 fragments, so the unit tier builds them, and the IPv6 class below is
where fragmentation is exercised end to end.
only, submits none of them (#2961). :class:`IPv4FragmentReassemblyTests`
below reassembles fragments, over :file:`ipv4-frag.pcap`.

"""

Expand All @@ -208,6 +207,59 @@ def test_no_unfragmented_datagram_is_submitted(self) -> None:
self.assertEqual((info.offset, info.flags.mf), (0, False))


@unittest.skipUnless(HAS_RUNTIME, 'runtime dependencies not installed')
class IPv4FragmentReassemblyTests(EndToEndTestCase):
"""IPv4 fragment reassembly over :file:`ipv4-frag.pcap`.

Frames 2 to 4 are one 3208 octet UDP datagram fragmented into 1480/248/1480
octets at offsets 0, 2960 and 1480, with DF clear, and frames 6 and 7 one
2008 octet UDP datagram fragmented into 1480/528 octets, both with DF set.
Frames 1 and 5 are whole datagrams, with DF set and clear. Every engine is
held to the same result in
:file:`tests/integration/test_reassembly_engine_parity.py`.

"""

def reassemble(self) -> 'tuple':
extractor = self.extract(fin=sample_path('ipv4-frag.pcap'), store=True, reassembly=['ipv4'])
self.assertEqual(extractor.length, 7)
return extractor.frame, extractor.reassembly.ipv4

def test_only_fragments_are_submitted_whatever_their_df_flag(self) -> None:
frames, datagrams = self.reassemble()

# a fragment is reassembled whatever its DF flag, as Wireshark does (#2961, #3216)
self.assertEqual([datagram.index for datagram in datagrams], [(2, 3, 4), (6, 7)])
self.assertEqual([frames[number - 1]['IPv4'].info.flags.df for number in (1, 5, 6, 7)],
[True, False, True, True])
self.assertEqual([datagram.id.id for datagram in datagrams], [0x5a01, 0x5a03])
for datagram in datagrams:
with self.subTest(index=datagram.index):
self.assertTrue(datagram.completed)
self.assertEqual((str(datagram.id.src), str(datagram.id.dst), int(datagram.id.proto)),
('192.168.88.20', '192.168.88.31', 17))

def test_the_fragments_reassemble_in_offset_order(self) -> None:
frames, datagrams = self.reassemble()

for datagram, numbers, length in zip(datagrams, ((2, 4, 3), (6, 7)), (3208, 2008)):
with self.subTest(index=datagram.index):
fragments = [bytes(frames[number - 1]['IPv4'].packet.payload) for number in numbers]
self.assertEqual(len(datagram.payload), length)
self.assertEqual(bytes(datagram.payload), b''.join(fragments))
# the datagram's header is its first fragment's (RFC 791, section 3.2)
self.assertEqual(bytes(datagram.header), bytes(frames[numbers[0] - 1]['IPv4'].packet.header))

def test_each_datagram_analyses_as_the_udp_datagram_it_carries(self) -> None:
_, datagrams = self.reassemble()

for datagram, length in zip(datagrams, (3208, 2008)):
with self.subTest(index=datagram.index):
udp = datagram.packet.info
# the UDP length counts the whole datagram, not its first fragment (RFC 768)
self.assertEqual((int(udp.srcport), int(udp.dstport), udp.len), (40812, 5001, length))


@unittest.skipUnless(HAS_RUNTIME, 'runtime dependencies not installed')
class IPv6FragmentReassemblyTests(EndToEndTestCase):
"""IPv6 fragment reassembly over :file:`ipv6.pcap`.
Expand Down
Loading
Loading