From 8e9cbf361dcb46e5fde8249796d9f3c09a57c995 Mon Sep 17 00:00:00 2001 From: Jarry Shaw Date: Fri, 27 Nov 2026 03:12:57 -0500 Subject: [PATCH] feat(foundation): reassemble TLS records split across TCP segments (#2938) - add pcapkit.foundation.reassembly.tls.TLS, registered as 'tls': each TCP direction is one octet stream, followed from its SYN or from a segment whose payload opens a record header, and cut into records by their headers (RFC 9846 section 5.1); out-of-order octets wait and the first received win (RFC 9293 sections 3.4 and 3.10); a FIN or RST closes it - report every record of the stream, COMPLETE, or PARTIAL/TIMEOUT with no packet when a hole or the stream's end cuts it - add TLS.record_header and TLS.analyze_record, and the public wrapper pcapkit.foundation.analysis.tls.tls_record - refuse a TLS or legacy DTLS record declaring more than 2^14 + 2048 octets (RFC 5246 section 6.2.3), and a DTLS 1.3 unified-header one more than 2^14 + 256 (RFC 9147 section 4), in parse and make, first or further - add tls_reassembly adapters for pcap, pcapng, dpkt, scapy and pypcapfile, keeping the TCP adapter's record of a segment on a port TCP binds to TLS - add ReassemblyData.tls; Deferred admits the TLS record header - move TCP reassembly's _unwrap to pcapkit.utilities.seqnum.unwrap, which both reassemblers read - document the reassembler, its analysis and the toolkit adapters Tests: new TLS reassembly and seqnum tests fail on origin/develop; tests/project, tests/foundation, tests/toolkit, tests/protocols/application pass. --- .../conventions/reassembly-integration.rst | 61 +- docs/source/ext.rst | 1 + .../pcapkit/foundation/analysis/index.rst | 1 + .../pcapkit/foundation/analysis/tls.rst | 15 + docs/source/pcapkit/foundation/index.rst | 2 +- .../pcapkit/foundation/reassembly/index.rst | 14 +- .../foundation/reassembly/reassembly.rst | 2 +- .../pcapkit/foundation/reassembly/tls.rst | 162 ++++++ .../pcapkit/protocols/application/dtls.rst | 5 +- .../pcapkit/protocols/application/tls.rst | 14 +- docs/source/pcapkit/toolkit/3rdparty.rst | 9 +- docs/source/pcapkit/toolkit/builtin.rst | 9 +- docs/source/pcapkit/utilities/index.rst | 4 +- docs/source/pcapkit/utilities/seqnum.rst | 12 + pcapkit/all.py | 14 +- pcapkit/corekit/packet.py | 3 +- pcapkit/foundation/__init__.py | 5 +- pcapkit/foundation/analysis/__init__.py | 3 + pcapkit/foundation/analysis/tls.py | 56 ++ pcapkit/foundation/engines/dpkt.py | 1 + pcapkit/foundation/engines/pcap.py | 1 + pcapkit/foundation/engines/pcapng.py | 1 + pcapkit/foundation/engines/pypcapfile.py | 1 + pcapkit/foundation/engines/scapy.py | 1 + pcapkit/foundation/extraction.py | 2 + pcapkit/foundation/options.py | 2 +- pcapkit/foundation/reassembly/__init__.py | 7 +- pcapkit/foundation/reassembly/data.py | 27 +- pcapkit/foundation/reassembly/reassembly.py | 13 +- .../foundation/reassembly/tcp/reassembly.py | 19 +- pcapkit/foundation/reassembly/tls/__init__.py | 26 + pcapkit/foundation/reassembly/tls/data.py | 128 +++++ .../foundation/reassembly/tls/reassembly.py | 475 ++++++++++++++++ pcapkit/protocols/application/dtls/const.py | 4 + .../protocols/application/dtls/protocol.py | 57 +- pcapkit/protocols/application/ssl/const.py | 8 + pcapkit/protocols/application/ssl/protocol.py | 15 +- pcapkit/protocols/application/tls/protocol.py | 114 +++- pcapkit/toolkit/__init__.py | 19 +- pcapkit/toolkit/dpkt.py | 29 +- pcapkit/toolkit/pcap.py | 57 +- pcapkit/toolkit/pcapng.py | 29 +- pcapkit/toolkit/pypcapfile.py | 28 +- pcapkit/toolkit/scapy.py | 28 +- pcapkit/utilities/seqnum.py | 36 ++ .../corekit/test_deferred_packet_1516_unit.py | 6 + .../test_renamed_field_dump_2733_unit.py | 6 +- .../test_deferred_proto_type_2417_unit.py | 26 +- ...est_reassembly_callbacks_2867_2881_unit.py | 8 + .../test_reassembly_field_order_2847_unit.py | 8 +- .../test_registered_reassembler_2814_unit.py | 6 +- .../test_sctp_reassembly_2935_unit.py | 2 +- .../test_tls_record_reassembly_2938_unit.py | 534 ++++++++++++++++++ .../test_tls_dtls_record_length_2938_unit.py | 168 ++++++ ...t_tls_sslv2_fallback_warnings_2525_unit.py | 11 +- .../test_pcap_tcp_segment_public_1570_unit.py | 4 +- tests/utilities/test_seqnum_2938_unit.py | 40 ++ 57 files changed, 2198 insertions(+), 141 deletions(-) create mode 100644 docs/source/pcapkit/foundation/analysis/tls.rst create mode 100644 docs/source/pcapkit/foundation/reassembly/tls.rst create mode 100644 docs/source/pcapkit/utilities/seqnum.rst create mode 100644 pcapkit/foundation/analysis/tls.py create mode 100644 pcapkit/foundation/reassembly/tls/__init__.py create mode 100644 pcapkit/foundation/reassembly/tls/data.py create mode 100644 pcapkit/foundation/reassembly/tls/reassembly.py create mode 100644 pcapkit/utilities/seqnum.py create mode 100644 tests/foundation/reassembly/test_tls_record_reassembly_2938_unit.py create mode 100644 tests/protocols/application/test_tls_dtls_record_length_2938_unit.py create mode 100644 tests/utilities/test_seqnum_2938_unit.py diff --git a/docs/source/contributing/conventions/reassembly-integration.rst b/docs/source/contributing/conventions/reassembly-integration.rst index 80b72d9d77..672660acb9 100644 --- a/docs/source/contributing/conventions/reassembly-integration.rst +++ b/docs/source/contributing/conventions/reassembly-integration.rst @@ -73,9 +73,11 @@ Parse Ownership IPv6, :meth:`Transport.analyze ` for TCP, :meth:`DTLS.analyze_handshake ` - for a DTLS handshake message, and + for a DTLS handshake message, :meth:`SCTP.analyze ` for an - SCTP user message. + SCTP user message, and + :meth:`TLS.analyze_record ` + for a TLS record (:issue:`2938`). * Each :mod:`pcapkit.foundation.analysis` function is a public wrapper that calls that method and holds no parsing of its own. * The reassembly :class:`~pcapkit.foundation.reassembly.data.Deferred` calls the @@ -105,9 +107,9 @@ Parse Ownership TK["the pcapkit.toolkit.<engine> adapter the engine's
\_\_reassembly\_\_ names, e.g. toolkit.pcap.dtls\_reassembly"] RE["each enabled reassembler the Extractor holds,
by its registered name, advanced to the frame's timestamp"] DEF["Deferred: a datagram's packet,
parsed on first read"] - AN["pcapkit.foundation.analysis
ip\_datagram, tcp\_datagram, dtls\_handshake, sctp\_message
public wrappers, no parsing"] + AN["pcapkit.foundation.analysis
ip\_datagram, tcp\_datagram, dtls\_handshake,
sctp\_message, tls\_record
public wrappers, no parsing"] subgraph protocols ["pcapkit.protocols"] - PM["the protocol class's parse method
Protocol.analyze: IPv4, IPv6
Transport.analyze: TCP
DTLS.analyze\_handshake
SCTP.analyze: SCTP"] + PM["the protocol class's parse method
Protocol.analyze: IPv4, IPv6
Transport.analyze: TCP
DTLS.analyze\_handshake
SCTP.analyze: SCTP
TLS.analyze\_record"] end REG["pcapkit.foundation.registry.protocols"] @@ -126,8 +128,9 @@ Compliance, Measured :class:`~pcapkit.protocols.internet.ipv4.protocol.IPv4`, :class:`~pcapkit.protocols.internet.ipv6.protocol.IPv6`, :class:`~pcapkit.protocols.transport.tcp.protocol.TCP`, -:class:`~pcapkit.protocols.application.dtls.protocol.DTLS` and -:class:`~pcapkit.protocols.transport.sctp.protocol.SCTP` imports or calls into +:class:`~pcapkit.protocols.application.dtls.protocol.DTLS`, +:class:`~pcapkit.protocols.transport.sctp.protocol.SCTP` and +:class:`~pcapkit.protocols.application.tls.protocol.TLS` imports or calls into :mod:`pcapkit.foundation.reassembly`. Instead :mod:`pcapkit.foundation.engines` calls a ``pcapkit.toolkit.`` extraction function on an already-parsed frame and feeds the result to the reassembly instance the @@ -141,7 +144,11 @@ that name, and each is advanced to every frame's timestamp before the frame is f (:issue:`2814`). :meth:`DTLS.read_handshake ` and :meth:`DTLS.analyze_handshake ` -are the parser methods the rule allows. +are the parser methods the rule allows, and so are +:meth:`TLS.record_header `, which +reads the header a TLS stream is cut into records by, and +:meth:`TLS.analyze_record ` +(:issue:`2938`). **Point 2 holds through the engines, not through one** :mod:`pcapkit.toolkit` **helper.** Each engine's :attr:`EngineBase.__reassembly__ @@ -153,7 +160,10 @@ declare which engines support a reassembler, and registering an adapter on an en makes it support one. An enabled reassembler with no entry is disabled with an :class:`~pcapkit.utilities.warnings.AttributeWarning`, and an engine with no entries at all, as :mod:`pcapkit.foundation.engines.pyshark`, disables -reassembly (:issue:`2814`). DTLS and SCTP have entries on the default engine alone. +reassembly (:issue:`2814`). DTLS and SCTP have entries on the default engine alone. TLS has +entries on every engine with a TCP one: TLS reassembly reads TCP reassembly's record of each +segment, which each engine's ``tls_reassembly`` keeps for a stream on a port TCP binds to TLS +(:issue:`2938`). **Flow tracing takes the same shape.** Every enabled flow tracer is made by the name it is registered under in :attr:`Extractor.__traceflow__ @@ -189,21 +199,26 @@ datagram's by its ports, through :func:`~pcapkit.foundation.analysis.dtls.dtls_handshake` decodes a reassembled DTLS handshake message (:issue:`2496`), through :meth:`DTLS.analyze_handshake ` -(:issue:`2622`); and :func:`~pcapkit.foundation.analysis.sctp.sctp_message` parses a +(:issue:`2622`); :func:`~pcapkit.foundation.analysis.sctp.sctp_message` parses a reassembled SCTP user message's by its payload protocol identifier, through -:meth:`SCTP.analyze `. IP and -TCP have analysis modules of their own, each function named for the datagram its engine -reassembles, by the owner's choice on :issue:`2581`; without them the rule held for DTLS -alone. +:meth:`SCTP.analyze `; and +:func:`~pcapkit.foundation.analysis.tls.tls_record` decodes a TLS record reassembled from a +TCP stream, through +:meth:`TLS.analyze_record ` +(:issue:`2938`). IP and TCP have analysis modules of their own, each function named for the +datagram its engine reassembles, by the owner's choice on :issue:`2581`; without them the +rule held for DTLS alone. **Where the rule is silent, DTLS takes the IP/TCP shape** (:issue:`2531`), and so does -SCTP. IPv4, IPv6, TCP, DTLS and SCTP reassembly each set ``__protocol_type__`` and -report the parsed outcome as a datagram's ``packet``, deferred to first read by -:class:`~pcapkit.foundation.reassembly.data.Deferred`. Each ``Deferred`` runs the -parse behind its engine's analysis function, so a ``packet`` is what that function -returns, and binds it to ``__protocol_type__`` -- ``analyze`` for IP and TCP -(:issue:`2581`) and for SCTP, ``analyze_handshake`` for DTLS (:issue:`2622`) -- so a -subclass naming another protocol has its ``packet`` parsed by that one. They differ on -an incomplete outcome: IP, TCP and SCTP parse a contiguous payload, complete or not, as -``strict=False`` reports one, and hold :data:`None` only for the received runs -``strict=True`` reports; DTLS holds :data:`None` for any incomplete message. +SCTP, and TLS takes DTLS's (:issue:`2938`). IPv4, IPv6, TCP, DTLS, SCTP and TLS reassembly +each set ``__protocol_type__`` and report the parsed outcome as a datagram's ``packet``, +deferred to first read by :class:`~pcapkit.foundation.reassembly.data.Deferred`. Each +``Deferred`` runs the parse behind its engine's analysis function, so a ``packet`` is what +that function returns, and binds it to ``__protocol_type__`` -- ``analyze`` for IP and TCP +(:issue:`2581`) and for SCTP, ``analyze_handshake`` for DTLS (:issue:`2622`), +``analyze_record`` for TLS -- so a subclass naming another protocol has its ``packet`` +parsed by that one. They differ on an incomplete outcome: IP, TCP and SCTP parse a +contiguous payload, complete or not, as ``strict=False`` reports one, and hold :data:`None` +only for the received runs ``strict=True`` reports; DTLS holds :data:`None` for any +incomplete message, and TLS for any incomplete record, whose zero-filled octets would decode +as content. diff --git a/docs/source/ext.rst b/docs/source/ext.rst index 3d4a9bca08..a05b6f2cdb 100644 --- a/docs/source/ext.rst +++ b/docs/source/ext.rst @@ -758,6 +758,7 @@ The reassembly and flow tracing classes, per protocol: | :class:`~pcapkit.protocols.application.dtls.protocol.DTLS` | :class:`pcapkit.foundation.reassembly.dtls.reassembly.DTLS` | | +------------------------------------------------------------+-------------------------------------------------------------+---------------------------------------------------------+ | :class:`~pcapkit.protocols.transport.sctp.protocol.SCTP` | :class:`pcapkit.foundation.reassembly.sctp.reassembly.SCTP` | | +| :class:`~pcapkit.protocols.application.tls.protocol.TLS` | :class:`pcapkit.foundation.reassembly.tls.reassembly.TLS` | | +------------------------------------------------------------+-------------------------------------------------------------+---------------------------------------------------------+ .. seealso:: diff --git a/docs/source/pcapkit/foundation/analysis/index.rst b/docs/source/pcapkit/foundation/analysis/index.rst index 2e4e42a086..b986bf0c12 100644 --- a/docs/source/pcapkit/foundation/analysis/index.rst +++ b/docs/source/pcapkit/foundation/analysis/index.rst @@ -19,3 +19,4 @@ itself is a method of the protocol class, which the function calls. tcp dtls sctp + tls diff --git a/docs/source/pcapkit/foundation/analysis/tls.rst b/docs/source/pcapkit/foundation/analysis/tls.rst new file mode 100644 index 0000000000..8c1b066374 --- /dev/null +++ b/docs/source/pcapkit/foundation/analysis/tls.rst @@ -0,0 +1,15 @@ +=================== +TLS Record Analysis +=================== + +.. module:: pcapkit.foundation.analysis.tls + +:mod:`pcapkit.foundation.analysis.tls` contains +:func:`~pcapkit.foundation.analysis.tls.tls_record` only, which decodes a TLS record +that :class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS` reassembled from a TCP +stream (:rfc:`9846#section-5`). The decode itself is :meth:`TLS.analyze_record +`. + +.. versionadded:: 1.9.0 + +.. autofunction:: pcapkit.foundation.analysis.tls.tls_record diff --git a/docs/source/pcapkit/foundation/index.rst b/docs/source/pcapkit/foundation/index.rst index 35c56648ff..eaab05e8f8 100644 --- a/docs/source/pcapkit/foundation/index.rst +++ b/docs/source/pcapkit/foundation/index.rst @@ -8,7 +8,7 @@ Library Foundation * the PCAP file extractor :class:`~pcapkit.foundation.extraction.Extractor`, the :mod:`~pcapkit.foundation.options` it takes, and the :mod:`~pcapkit.foundation.engines` it reads through; -* the IP, TCP, DTLS and SCTP :mod:`~pcapkit.foundation.reassembly`, and the +* the IP, TCP, DTLS, SCTP and TLS :mod:`~pcapkit.foundation.reassembly`, and the :mod:`~pcapkit.foundation.analysis` of what it reassembles; * the TCP flow tracer of :mod:`~pcapkit.foundation.traceflow`, and any other registered one; * the :mod:`~pcapkit.foundation.registry` management APIs. diff --git a/docs/source/pcapkit/foundation/reassembly/index.rst b/docs/source/pcapkit/foundation/reassembly/index.rst index 1aeb055c8f..30a04a023c 100644 --- a/docs/source/pcapkit/foundation/reassembly/index.rst +++ b/docs/source/pcapkit/foundation/reassembly/index.rst @@ -5,9 +5,9 @@ Packets Reassembly .. module:: pcapkit.foundation.reassembly :mod:`pcapkit.foundation.reassembly` implements datagram reassembly -of IP packets, TCP segments, DTLS handshake messages and SCTP user messages, -based on the algorithms described in :rfc:`791`, :rfc:`815`, :rfc:`6347`, -:rfc:`9260` and :rfc:`8260`. +of IP packets, TCP segments, DTLS handshake messages, SCTP user messages and TLS +records, based on the algorithms described in :rfc:`791`, :rfc:`815`, :rfc:`6347`, +:rfc:`9260`, :rfc:`8260` and :rfc:`9846`. .. seealso:: @@ -21,6 +21,7 @@ based on the algorithms described in :rfc:`791`, :rfc:`815`, :rfc:`6347`, tcp dtls sctp + tls Every reassembly class subclasses :class:`~pcapkit.foundation.reassembly.reassembly.ReassemblyBase`, reassembling @@ -31,7 +32,7 @@ extracted fragments into whole datagrams: flowchart TD A{{ReassemblyMeta}} -.->|metaclass| B(ReassemblyBase) - B --> IP & TCP & DTLS & SCTP + B --> IP & TCP & DTLS & SCTP & TLS IP --> IPv4 & IPv6 B --> C(Reassembly) @@ -49,6 +50,7 @@ extracted fragments into whole datagrams: click TCP "tcp.html#pcapkit.foundation.reassembly.tcp.reassembly.TCP" click DTLS "dtls.html#pcapkit.foundation.reassembly.dtls.reassembly.DTLS" click SCTP "sctp.html#pcapkit.foundation.reassembly.sctp.reassembly.SCTP" + click TLS "tls.html#pcapkit.foundation.reassembly.tls.reassembly.TLS" Auxiliary Data ============== @@ -83,7 +85,7 @@ What submits a buffer, and how its holes at that point pick the flowchart TD subgraph trig ["What submits a buffer"] direction TB - T1["IP: every octet received
TCP: a FIN and every octet below it"] + T1["IP: every octet received
TCP, TLS: a FIN and every octet below it"] T2["a session torn down: a TCP RST,
a TCP SYN on a buffered 4-tuple,
an unfragmented IPv4 datagram reusing the BUFID"] T3["a TCP segment farther than TCP\_GAP\_LIMIT
from its buffer: the stream splits"] T4["a DTLS fragment whose length or type disagrees
with the message held under its message\_seq"] @@ -92,7 +94,7 @@ What submits a buffer, and how its holes at that point pick the T7[".datagram or fetch() read outside a callback
while buffers are outstanding"] T1 ~~~ T2 ~~~ T3 ~~~ T4 ~~~ T5 ~~~ T6 ~~~ T7 end - T1D["DTLS, SCTP: a message whole"] + T1D["DTLS, SCTP: a message whole
TLS: a record whole at the boundary"] SUB["submit(buffer)"] Q1{"overlap?"} Q2{"no holes left?"} diff --git a/docs/source/pcapkit/foundation/reassembly/reassembly.rst b/docs/source/pcapkit/foundation/reassembly/reassembly.rst index eebd3505be..fa5a2ccea6 100644 --- a/docs/source/pcapkit/foundation/reassembly/reassembly.rst +++ b/docs/source/pcapkit/foundation/reassembly/reassembly.rst @@ -7,7 +7,7 @@ Reassembly Base Class :class:`~pcapkit.foundation.reassembly.reassembly.Reassembly`, the abstract base class of a custom reassembly class, and :class:`~pcapkit.foundation.reassembly.reassembly.ReassemblyBase`, which it and -the built-in IP, TCP, DTLS and SCTP reassembly classes derive from. The algorithms +the built-in IP, TCP, DTLS, SCTP and TLS reassembly classes derive from. The algorithms follow :rfc:`791` and :rfc:`815`. .. autoclass:: pcapkit.foundation.reassembly.reassembly.Reassembly diff --git a/docs/source/pcapkit/foundation/reassembly/tls.rst b/docs/source/pcapkit/foundation/reassembly/tls.rst new file mode 100644 index 0000000000..f2b1ba93eb --- /dev/null +++ b/docs/source/pcapkit/foundation/reassembly/tls.rst @@ -0,0 +1,162 @@ +===================== +TLS Record Reassembly +===================== + +.. module:: pcapkit.foundation.reassembly.tls +.. module:: pcapkit.foundation.reassembly.tls.reassembly + +:mod:`pcapkit.foundation.reassembly.tls.reassembly` contains +:class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS` only, which reconstructs +the TLS records of a TCP stream, a record split across segments included +(:rfc:`9846#section-5`). + +.. versionadded:: 1.9.0 + +.. autoclass:: pcapkit.foundation.reassembly.tls.reassembly.TLS + :no-members: + :show-inheritance: + + .. rubric:: Defaults + + .. autoattribute:: __protocol_name__ + .. autoattribute:: __protocol_type__ + + .. rubric:: Methods + + .. automethod:: reassembly + .. automethod:: submit + + .. rubric:: Utilities + + .. automethod:: _read_header + .. automethod:: _opens_record + .. automethod:: _close_runs + .. automethod:: _hold_segment + .. automethod:: _hold_octets + .. automethod:: _cut_records + .. automethod:: _stream_whole + .. automethod:: _make_datagram + +Algorithm +========= + +.. seealso:: + + A record over TCP is delimited by its header alone (:rfc:`9846#section-5.1`), and + the stream is the segments' octets in sequence order (:rfc:`9293#section-3.4`). + +Each direction of a connection is a buffer, which holds the octets past the next +record's boundary as runs in sequence order. A segment's new octets join the runs, +and the records whole from the boundary on are cut off and reported: + +.. mermaid:: + + flowchart TD + SEG["a segment, as TCP reassembly records it"] + SYN{"SYN?"} + OPEN["a fresh buffer, its boundary
the octet after the SYN"] + HAS{"a buffer?"} + SYNC{"its payload opens
a record header?"} + DROP["ignored"] + HOLD["hold the octets no earlier
segment brought"] + HEAD{"a header held
at the boundary?"} + BAD{"it opens a record?"} + GONE["the buffer is dropped"] + WHOLE{"the record whole?"} + CUT["report it COMPLETE, and
move the boundary past it"] + END{"an RST, or a FIN with
every octet before it?"} + CLOSE["submit the buffer, and
close the stream"] + WAIT["wait for the next segment"] + + SEG --> SYN + SYN -->|yes| OPEN --> HOLD + SYN -->|no| HAS + HAS -->|open| HOLD + HAS -->|closed| DROP + HAS -->|none| SYNC + SYNC -->|no| DROP + SYNC -->|"yes: a buffer from it"| HOLD + HOLD --> HEAD + HEAD -->|no| END + HEAD -->|yes| BAD + BAD -->|no| GONE + BAD -->|yes| WHOLE + WHOLE -->|yes| CUT --> HEAD + WHOLE -->|no| END + END -->|yes| CLOSE + END -->|no| WAIT + +Without the SYN, the boundary a buffer opens at is a guess, which the length bound of +:meth:`TLS.record_header ` +narrows but cannot make safe; the class's warning above says what it rules out. + +:meth:`~pcapkit.foundation.reassembly.tls.reassembly.TLS.submit` reports what a buffer +still holds, record by record from the boundary: one whose fragment is whole +:attr:`~pcapkit.foundation.reassembly.data.Completion.COMPLETE`, and one with a hole +:attr:`~pcapkit.foundation.reassembly.data.Completion.PARTIAL`, or +:attr:`~pcapkit.foundation.reassembly.data.Completion.TIMEOUT` once expired. It stops at +the first hole a header lies in. + +Terminology +=========== + +The reassembly is fed :term:`reasm.tcp.packet`, TCP reassembly's record of a segment. + +.. glossary:: + + reasm.tls.datagram + Data structure for **reassembled TLS record** (element of + :attr:`TLS.datagram `) + is :class:`~pcapkit.foundation.reassembly.tls.data.Datagram` -- ``completed``, + the original record identifier, the packet numbers that carried it, the + record header's ``content_type``, ``version`` and ``length``, ``fragment``, + the reassembled fragment (a contiguous :obj:`bytes`, or -- under + ``strict=True`` and an incomplete record -- a :obj:`tuple` of the octet runs + actually received), and ``packet``, what + :func:`~pcapkit.foundation.analysis.tls.tls_record` decodes the record to. + ``packet`` is decoded on first read, as a DTLS message's is, and is + :data:`None` for an incomplete record. + + reasm.tls.buffer + Data structure for internal buffering + (:attr:`TLS._buffer `) + is :class:`~pcapkit.foundation.reassembly.tls.data.Buffer` -- one direction of + a TCP connection, keyed by its + :data:`~pcapkit.foundation.reassembly.tls.data.BufferID`: the next record's + boundary, the octets held past it as + :class:`~pcapkit.foundation.reassembly.tls.data.Run` objects, the octets each + packet added, and where the stream ends. + +Data Models +=========== + +.. module:: pcapkit.foundation.reassembly.tls.data + +.. currentmodule:: pcapkit.foundation.reassembly.tls.reassembly + +.. autodata:: pcapkit.foundation.reassembly.tls.data.BufferID + +.. autoclass:: pcapkit.foundation.reassembly.tls.data.DatagramID + :members: + :show-inheritance: + +.. autoclass:: pcapkit.foundation.reassembly.tls.data.Datagram + :members: + :show-inheritance: + +.. autoclass:: pcapkit.foundation.reassembly.tls.data.Run + :members: + :show-inheritance: + +.. autoclass:: pcapkit.foundation.reassembly.tls.data.Buffer + :members: + :show-inheritance: + +Type Variables +============== + +.. data:: _AT + :module: pcapkit.foundation.reassembly.tls.data + :type: ipaddress.IPv4Address | ipaddress.IPv6Address + + IP address type. diff --git a/docs/source/pcapkit/protocols/application/dtls.rst b/docs/source/pcapkit/protocols/application/dtls.rst index dbc0bb4591..fe9eac3bd8 100644 --- a/docs/source/pcapkit/protocols/application/dtls.rst +++ b/docs/source/pcapkit/protocols/application/dtls.rst @@ -113,8 +113,9 @@ exceptions: :class:`~pcapkit.protocols.misc.raw.protocol.Raw` together with everything after it. * Octets that open no whole record stay raw, with no error: an unsupported content type, a legacy version outside ``0xFExx``, a header cut short, a - length past the end of the datagram, or a connection ID whose length is - not known, which leaves the record's end unknown. + length past the end of the datagram or past the RFCs' bound (``2 ** 14 + + 2048``, or ``2 ** 14 + 256`` for a unified header), or a connection ID whose + length is not known, which leaves the record's end unknown. * A parse told to stop at DTLS (``protocol='DTLS'`` or ``layer='Application'``) keeps the rest of the datagram raw. * Each record is a layer, so :data:`~pcapkit.utilities.config.FRAME_LAYER_LIMIT` diff --git a/docs/source/pcapkit/protocols/application/tls.rst b/docs/source/pcapkit/protocols/application/tls.rst index ac677eabe9..5c30ad2edd 100644 --- a/docs/source/pcapkit/protocols/application/tls.rst +++ b/docs/source/pcapkit/protocols/application/tls.rst @@ -99,7 +99,8 @@ reads ``TCP:TLS 1.3:TLS 1.2``. The exceptions: :class:`~pcapkit.protocols.misc.raw.protocol.Raw` together with everything after it, with no SSLv2 trial. * Octets that open no record -- an unsupported content type, a legacy - version outside ``0x03xx``, or a header cut short -- stay raw, with no error. + version outside ``0x03xx``, a length past the ``2 ** 14 + 2048`` of + :rfc:`5246#section-6.2.3`, or a header cut short -- stay raw, with no error. * A parse told to stop at TLS (``protocol='TLS'`` or ``layer='Application'``) keeps the rest of the segment raw. * Each record is a layer, so :data:`~pcapkit.utilities.config.FRAME_LAYER_LIMIT` @@ -108,10 +109,15 @@ reads ``TCP:TLS 1.3:TLS 1.2``. The exceptions: Known Limitation ---------------- -**A record split across two TCP segments is not reassembled**, and decodes as +**A record split across TCP segments is not reassembled here**, and decodes as :class:`~pcapkit.protocols.misc.raw.protocol.Raw`, as does the partial record a segment ends inside. A record may be up to 16 KiB against a typical 1460-octet MSS, so -this is routine. +this is routine. ``Extractor(fin, reassembly=['tls'])`` reassembles every record of +the stream (:class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS`), framing it with +:meth:`~pcapkit.protocols.application.tls.protocol.TLS.record_header`, and +:func:`~pcapkit.foundation.analysis.tls.tls_record` decodes it with +:meth:`~pcapkit.protocols.application.tls.protocol.TLS.analyze_record`, as a segment's +first record is decoded. .. versionadded:: 1.6.0 @@ -136,6 +142,8 @@ this is routine. .. automethod:: read .. automethod:: make .. automethod:: unpack + .. automethod:: record_header + .. automethod:: analyze_record .. rubric:: Data Models diff --git a/docs/source/pcapkit/toolkit/3rdparty.rst b/docs/source/pcapkit/toolkit/3rdparty.rst index 7207f6ca39..7519398484 100644 --- a/docs/source/pcapkit/toolkit/3rdparty.rst +++ b/docs/source/pcapkit/toolkit/3rdparty.rst @@ -28,6 +28,8 @@ Scapy Tools .. autofunction:: pcapkit.toolkit.scapy.tcp_reassembly +.. autofunction:: pcapkit.toolkit.scapy.tls_reassembly + .. autofunction:: pcapkit.toolkit.scapy.tcp_traceflow Auxiliary Functions @@ -70,6 +72,8 @@ DPKT Tools .. autofunction:: pcapkit.toolkit.dpkt.tcp_reassembly +.. autofunction:: pcapkit.toolkit.dpkt.tls_reassembly + .. autofunction:: pcapkit.toolkit.dpkt.tcp_traceflow Auxiliary Functions @@ -218,7 +222,8 @@ PyPCAPFile Tools IPv6 fragment". TCP over IPv6 is therefore left out of - :func:`~pcapkit.toolkit.pypcapfile.tcp_reassembly` and + :func:`~pcapkit.toolkit.pypcapfile.tcp_reassembly`, + :func:`~pcapkit.toolkit.pypcapfile.tls_reassembly` and :func:`~pcapkit.toolkit.pypcapfile.tcp_traceflow`, with an :class:`~pcapkit.utilities.warnings.AttributeWarning` once per capture when the IPv6 packet is straight over Ethernet. `PyPCAPFile`_ decodes no link @@ -233,6 +238,8 @@ PyPCAPFile Tools .. autofunction:: pcapkit.toolkit.pypcapfile.tcp_reassembly +.. autofunction:: pcapkit.toolkit.pypcapfile.tls_reassembly + .. autofunction:: pcapkit.toolkit.pypcapfile.tcp_traceflow Auxiliary Functions diff --git a/docs/source/pcapkit/toolkit/builtin.rst b/docs/source/pcapkit/toolkit/builtin.rst index 49799a24fc..c9bb1fa587 100644 --- a/docs/source/pcapkit/toolkit/builtin.rst +++ b/docs/source/pcapkit/toolkit/builtin.rst @@ -16,7 +16,8 @@ adapters here and in :mod:`pcapkit.toolkit.pcapng` read the segment with :func:`~pcapkit.toolkit.pcap.tcp_segment`, the DTLS ones the record with :func:`~pcapkit.toolkit.pcap._dtls_fragments`, and the SCTP ones the packet with -:func:`~pcapkit.toolkit.pcap._sctp_fragments`. +:func:`~pcapkit.toolkit.pcap._sctp_fragments`. The TLS adapters of every engine keep +the TCP ones' records of a TLS stream with :func:`~pcapkit.toolkit.pcap._tls_segment`. .. autofunction:: pcapkit.toolkit.pcap.ipv4_reassembly @@ -28,6 +29,8 @@ adapters here and in .. autofunction:: pcapkit.toolkit.pcap.sctp_reassembly +.. autofunction:: pcapkit.toolkit.pcap.tls_reassembly + .. autofunction:: pcapkit.toolkit.pcap.tcp_traceflow Auxiliary Functions @@ -41,6 +44,8 @@ Auxiliary Functions .. autofunction:: pcapkit.toolkit.pcap._sctp_fragments +.. autofunction:: pcapkit.toolkit.pcap._tls_segment + .. autoclass:: pcapkit.toolkit.pcap.TCPSegment :members: :show-inheritance: @@ -62,6 +67,8 @@ PCAP-NG Tools .. autofunction:: pcapkit.toolkit.pcapng.sctp_reassembly +.. autofunction:: pcapkit.toolkit.pcapng.tls_reassembly + .. autofunction:: pcapkit.toolkit.pcapng.tcp_traceflow Auxiliary Functions diff --git a/docs/source/pcapkit/utilities/index.rst b/docs/source/pcapkit/utilities/index.rst index 3eed2dc4bb..d01fbad7ce 100644 --- a/docs/source/pcapkit/utilities/index.rst +++ b/docs/source/pcapkit/utilities/index.rst @@ -10,7 +10,8 @@ built with, and imports nothing from :mod:`pcapkit` outside itself (see * user-refined exceptions and warnings, and logging; * the tunable limits of :mod:`~pcapkit.utilities.config`; -* a compatibility layer, timestamp conversion and pickle reductions; +* a compatibility layer, timestamp conversion, sequence-number arithmetic and + pickle reductions; * the :mod:`context variables ` its modules share, :mod:`lazy imports ` for a package's exports, an :mod:`abstract-class check ` that @@ -27,6 +28,7 @@ built with, and imports nothing from :mod:`pcapkit` outside itself (see config chardet datetime + seqnum pickle contextvars importlib diff --git a/docs/source/pcapkit/utilities/seqnum.rst b/docs/source/pcapkit/utilities/seqnum.rst new file mode 100644 index 0000000000..9fb8530f99 --- /dev/null +++ b/docs/source/pcapkit/utilities/seqnum.rst @@ -0,0 +1,12 @@ +Sequence Number Arithmetic +========================== + +.. module:: pcapkit.utilities.seqnum + +:mod:`pcapkit.utilities.seqnum` places a 32-bit sequence number on one unbounded +line, as :rfc:`9293#section-3.4` compares TCP sequence numbers. TCP and TLS +reassembly share it, so it lives beside neither. + +.. versionadded:: 1.9.0 + +.. autofunction:: pcapkit.utilities.seqnum.unwrap diff --git a/pcapkit/all.py b/pcapkit/all.py index b425e32bf2..7e81662c8f 100644 --- a/pcapkit/all.py +++ b/pcapkit/all.py @@ -28,6 +28,7 @@ from pcapkit.toolkit.scapy import ipv4_reassembly as scapy_ipv4_reassembly # isort: skip from pcapkit.toolkit.scapy import ipv6_reassembly as scapy_ipv6_reassembly # isort: skip from pcapkit.toolkit.scapy import tcp_reassembly as scapy_tcp_reassembly # isort: skip +from pcapkit.toolkit.scapy import tls_reassembly as scapy_tls_reassembly # isort: skip from pcapkit.toolkit.scapy import tcp_traceflow as scapy_tcp_traceflow # isort: skip # tools for DPKT engine @@ -37,6 +38,7 @@ from pcapkit.toolkit.dpkt import ipv4_reassembly as dpkt_ipv4_reassembly # isort: skip from pcapkit.toolkit.dpkt import ipv6_reassembly as dpkt_ipv6_reassembly # isort: skip from pcapkit.toolkit.dpkt import tcp_reassembly as dpkt_tcp_reassembly # isort: skip +from pcapkit.toolkit.dpkt import tls_reassembly as dpkt_tls_reassembly # isort: skip from pcapkit.toolkit.dpkt import tcp_traceflow as dpkt_tcp_traceflow # isort: skip # tools for PyShark engine @@ -90,12 +92,14 @@ 'TCP_Reassembly', # TCP Reassembly 'DTLS_Reassembly', # DTLS Reassembly 'SCTP_Reassembly', # SCTP Reassembly + 'TLS_Reassembly', # TLS Reassembly # pcapkit.foundation.analysis 'ip_datagram', # IP Analysis 'tcp_datagram', # TCP Analysis 'dtls_handshake', # DTLS Analysis 'sctp_message', # SCTP Analysis + 'tls_record', # TLS Analysis # pcapkit.foundation.registry 'register_protocol', @@ -160,16 +164,18 @@ # pcapkit.toolkit 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'dtls_reassembly', 'sctp_reassembly', - 'tcp_traceflow', + 'tls_reassembly', 'tcp_traceflow', 'pcapng_ipv4_reassembly', 'pcapng_ipv6_reassembly', 'pcapng_tcp_reassembly', 'pcapng_dtls_reassembly', - 'pcapng_sctp_reassembly', 'pcapng_tcp_traceflow', + 'pcapng_sctp_reassembly', 'pcapng_tls_reassembly', 'pcapng_tcp_traceflow', 'pcapng_block2frame', # default engine 'dpkt_ipv6_hdr_len', 'dpkt_packet2chain', 'dpkt_packet2dict', - 'dpkt_ipv4_reassembly', 'dpkt_ipv6_reassembly', 'dpkt_tcp_reassembly', 'dpkt_tcp_traceflow', + 'dpkt_ipv4_reassembly', 'dpkt_ipv6_reassembly', 'dpkt_tcp_reassembly', 'dpkt_tls_reassembly', + 'dpkt_tcp_traceflow', # DPKT engine 'pyshark_packet2dict', 'pyshark_tcp_traceflow', # PyShark engine 'scapy_packet2chain', 'scapy_packet2dict', - 'scapy_ipv4_reassembly', 'scapy_ipv6_reassembly', 'scapy_tcp_reassembly', 'scapy_tcp_traceflow', + 'scapy_ipv4_reassembly', 'scapy_ipv6_reassembly', 'scapy_tcp_reassembly', 'scapy_tls_reassembly', + 'scapy_tcp_traceflow', # Scapy engine # pcapkit.utilities -- unlisted: its names stay reachable as attributes, but diff --git a/pcapkit/corekit/packet.py b/pcapkit/corekit/packet.py index 0dd8101132..cd990914d3 100644 --- a/pcapkit/corekit/packet.py +++ b/pcapkit/corekit/packet.py @@ -63,7 +63,8 @@ class DeferredPacket: :class:`pcapkit.foundation.reassembly.ip.data.Datagram`, :class:`pcapkit.foundation.reassembly.tcp.data.Datagram`, :class:`pcapkit.foundation.reassembly.dtls.data.Datagram`, - :class:`pcapkit.foundation.reassembly.sctp.data.Datagram` and + :class:`pcapkit.foundation.reassembly.sctp.data.Datagram`, + :class:`pcapkit.foundation.reassembly.tls.data.Datagram` and :class:`pcapkit.foundation.traceflow.tcp.data.Index`, which differ only in the placeholder class each names in :attr:`__deferred__` (:issue:`1516`). diff --git a/pcapkit/foundation/__init__.py b/pcapkit/foundation/__init__.py index e213d2d939..237b6617a2 100644 --- a/pcapkit/foundation/__init__.py +++ b/pcapkit/foundation/__init__.py @@ -9,7 +9,7 @@ :mod:`pcapkit`, including PCAP file extraction tool :class:`~pcapkit.foundation.extraction.Extractor`, flow tracing :mod:`~pcapkit.foundation.traceflow`, registry management -APIs for :mod:`pcapkit`, TCP/IP, DTLS and SCTP reassembly implementations, and +APIs for :mod:`pcapkit`, TCP/IP, DTLS, SCTP and TLS reassembly implementations, and the :mod:`~pcapkit.foundation.analysis` of what they reassemble. """ @@ -25,9 +25,10 @@ 'DumpOptions', 'ReassemblyOptions', 'TraceFlowOptions', 'StreamOptions', 'IPv4_Reassembly', 'IPv6_Reassembly', 'TCP_Reassembly', 'DTLS_Reassembly', 'SCTP_Reassembly', + 'TLS_Reassembly', 'ReassemblyManager', - 'ip_datagram', 'tcp_datagram', 'dtls_handshake', 'sctp_message', + 'ip_datagram', 'tcp_datagram', 'dtls_handshake', 'sctp_message', 'tls_record', 'TCP_TraceFlow', 'TraceFlowManager', diff --git a/pcapkit/foundation/analysis/__init__.py b/pcapkit/foundation/analysis/__init__.py index edf81cea48..b0bdc0d960 100644 --- a/pcapkit/foundation/analysis/__init__.py +++ b/pcapkit/foundation/analysis/__init__.py @@ -21,10 +21,13 @@ from pcapkit.foundation.analysis.sctp import sctp_message # Analysis of TCP datagrams from pcapkit.foundation.analysis.tcp import tcp_datagram +# Analysis of TLS records +from pcapkit.foundation.analysis.tls import tls_record __all__ = [ 'ip_datagram', # IP Analysis 'tcp_datagram', # TCP Analysis 'dtls_handshake', # DTLS Analysis 'sctp_message', # SCTP Analysis + 'tls_record', # TLS Analysis ] diff --git a/pcapkit/foundation/analysis/tls.py b/pcapkit/foundation/analysis/tls.py new file mode 100644 index 0000000000..3b958afb64 --- /dev/null +++ b/pcapkit/foundation/analysis/tls.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +"""TLS Record Analysis +========================= + +.. module:: pcapkit.foundation.analysis.tls + +:mod:`pcapkit.foundation.analysis.tls` contains +:func:`~pcapkit.foundation.analysis.tls.tls_record` only, which decodes a TLS record +that :class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS` reassembled from a TCP +stream (:rfc:`9846#section-5`). The decode itself is :meth:`TLS.analyze_record +`. + +.. versionadded:: 1.9.0 + +""" +from typing import TYPE_CHECKING, cast + +from pcapkit.protocols.application.tls.protocol import TLS + +if TYPE_CHECKING: + from typing import Optional + + from pcapkit.foundation.reassembly.tls.data import Datagram as TLS_Datagram + from pcapkit.protocols.protocol import ProtocolBase + +__all__ = ['tls_record'] + + +def tls_record(datagram: 'TLS_Datagram') -> 'Optional[ProtocolBase]': + """Parse a TLS record reassembled by + :class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS`. + + The record is decoded by :meth:`TLS.analyze_record + `, as a segment's + first record is, so a record split across segments decodes as a whole one does. + + Args: + datagram: Reassembled record (:term:`reasm.tls.datagram`). + + Returns: + The record, as a :class:`~pcapkit.protocols.application.tls.protocol.TLS` + instance, or :class:`~pcapkit.protocols.misc.raw.protocol.Raw` if it does not + decode. :data:`None` if ``datagram`` is incomplete, as its missing octets + cannot be decoded. + + Note: + :attr:`Datagram.packet ` + holds the same result, decoded on its first read, unless the reassembly's + ``__protocol_type__`` names another protocol, whose ``analyze_record`` then + decodes it instead. + + """ + if not datagram.completed: + return None + # NOTE: a complete record's fragment is always one contiguous run. + return TLS.analyze_record((datagram.content_type, datagram.version), cast('bytes', datagram.fragment)) diff --git a/pcapkit/foundation/engines/dpkt.py b/pcapkit/foundation/engines/dpkt.py index b84c11ae18..2a17702dda 100644 --- a/pcapkit/foundation/engines/dpkt.py +++ b/pcapkit/foundation/engines/dpkt.py @@ -451,6 +451,7 @@ class DPKT(EngineBase['DPKTPacket']): 'ipv4': ModuleDescriptor('pcapkit.toolkit.dpkt', 'ipv4_reassembly'), 'ipv6': ModuleDescriptor('pcapkit.toolkit.dpkt', 'ipv6_reassembly'), 'tcp': ModuleDescriptor('pcapkit.toolkit.dpkt', 'tcp_reassembly'), + 'tls': ModuleDescriptor('pcapkit.toolkit.dpkt', 'tls_reassembly'), } # type: dict[str, ModuleDescriptor[Any] | Callable[..., Any]] #: Flow tracing adapters, each called as diff --git a/pcapkit/foundation/engines/pcap.py b/pcapkit/foundation/engines/pcap.py index bfd31faf70..63a8ca2b80 100644 --- a/pcapkit/foundation/engines/pcap.py +++ b/pcapkit/foundation/engines/pcap.py @@ -75,6 +75,7 @@ class PCAP(EngineBase[Frame]): 'tcp': ModuleDescriptor('pcapkit.toolkit.pcap', 'tcp_reassembly'), 'dtls': ModuleDescriptor('pcapkit.toolkit.pcap', 'dtls_reassembly'), 'sctp': ModuleDescriptor('pcapkit.toolkit.pcap', 'sctp_reassembly'), + 'tls': ModuleDescriptor('pcapkit.toolkit.pcap', 'tls_reassembly'), } # type: dict[str, ModuleDescriptor[Any] | Callable[..., Any]] #: Flow tracing adapters, each called as ``adapter(frame, data_link=link)`` on diff --git a/pcapkit/foundation/engines/pcapng.py b/pcapkit/foundation/engines/pcapng.py index 7f15ac6e99..51a6c67fc2 100644 --- a/pcapkit/foundation/engines/pcapng.py +++ b/pcapkit/foundation/engines/pcapng.py @@ -152,6 +152,7 @@ class PCAPNG(EngineBase[P_PCAPNG]): 'tcp': ModuleDescriptor('pcapkit.toolkit.pcapng', 'tcp_reassembly'), 'dtls': ModuleDescriptor('pcapkit.toolkit.pcapng', 'dtls_reassembly'), 'sctp': ModuleDescriptor('pcapkit.toolkit.pcapng', 'sctp_reassembly'), + 'tls': ModuleDescriptor('pcapkit.toolkit.pcapng', 'tls_reassembly'), } # type: dict[str, ModuleDescriptor[Any] | Callable[..., Any]] #: Flow tracing adapters, each called as ``adapter(block, nanosecond=flag)`` on diff --git a/pcapkit/foundation/engines/pypcapfile.py b/pcapkit/foundation/engines/pypcapfile.py index d3b3ee93c6..20c8a7073c 100644 --- a/pcapkit/foundation/engines/pypcapfile.py +++ b/pcapkit/foundation/engines/pypcapfile.py @@ -136,6 +136,7 @@ class PyPCAPFile(EngineBase['PCAPFilePacket']): __reassembly__ = { 'ipv4': ModuleDescriptor('pcapkit.toolkit.pypcapfile', 'ipv4_reassembly'), 'tcp': ModuleDescriptor('pcapkit.toolkit.pypcapfile', 'tcp_reassembly'), + 'tls': ModuleDescriptor('pcapkit.toolkit.pypcapfile', 'tls_reassembly'), } # type: dict[str, ModuleDescriptor[Any] | Callable[..., Any]] #: Flow tracing adapters, each called as diff --git a/pcapkit/foundation/engines/scapy.py b/pcapkit/foundation/engines/scapy.py index a77259875f..be7d3dfb64 100644 --- a/pcapkit/foundation/engines/scapy.py +++ b/pcapkit/foundation/engines/scapy.py @@ -305,6 +305,7 @@ class Scapy(EngineBase['ScapyPacket']): 'ipv4': ModuleDescriptor('pcapkit.toolkit.scapy', 'ipv4_reassembly'), 'ipv6': ModuleDescriptor('pcapkit.toolkit.scapy', 'ipv6_reassembly'), 'tcp': ModuleDescriptor('pcapkit.toolkit.scapy', 'tcp_reassembly'), + 'tls': ModuleDescriptor('pcapkit.toolkit.scapy', 'tls_reassembly'), } # type: dict[str, ModuleDescriptor[Any] | Callable[..., Any]] #: Flow tracing adapters, each called as ``adapter(packet, count=n)`` on the diff --git a/pcapkit/foundation/extraction.py b/pcapkit/foundation/extraction.py index 9ea8900a12..caf932e1a0 100644 --- a/pcapkit/foundation/extraction.py +++ b/pcapkit/foundation/extraction.py @@ -395,6 +395,7 @@ class Extractor(Generic[_P]): 'tcp': ModuleDescriptor('pcapkit.foundation.reassembly.tcp.reassembly', 'TCP'), 'dtls': ModuleDescriptor('pcapkit.foundation.reassembly.dtls.reassembly', 'DTLS'), 'sctp': ModuleDescriptor('pcapkit.foundation.reassembly.sctp.reassembly', 'SCTP'), + 'tls': ModuleDescriptor('pcapkit.foundation.reassembly.tls.reassembly', 'TLS'), } # type: dict[str, ModuleDescriptor[ReassemblyBase] | Type[ReassemblyBase]] #: Flow tracing support mapping for extracting frames, keyed by lower-cased protocol @@ -482,6 +483,7 @@ def reassembly(self) -> 'ReassemblyData': * ``tcp`` -- tuple of TCP payload fragment (:term:`reasm.tcp.datagram`) * ``dtls`` -- tuple of DTLS handshake message (:term:`reasm.dtls.datagram`) * ``sctp`` -- tuple of SCTP user message (:term:`reasm.sctp.datagram`) + * ``tls`` -- tuple of TLS record (:term:`reasm.tls.datagram`) Each is :data:`None` when its reassembly is disabled, and every other enabled reassembler adds the tuple of its datagrams, under the name it is diff --git a/pcapkit/foundation/options.py b/pcapkit/foundation/options.py index f7bbf94e47..5fd3e358d8 100644 --- a/pcapkit/foundation/options.py +++ b/pcapkit/foundation/options.py @@ -103,7 +103,7 @@ class ReassemblyOptions(Info): timeout: reassembly timeout in seconds, on the *capture's* own clock; :data:`None` selects each protocol's own default -- 60 seconds for IPv4 (:rfc:`1122#section-3.3.2`) and IPv6 (:rfc:`8200#section-4.5`), - disabled for TCP, DTLS and SCTP, which no specification gives a + disabled for TCP, DTLS, SCTP and TLS, which no specification gives a deadline (:rfc:`6347#section-4.2.3`, :rfc:`9260#section-6.9`). Pass :data:`math.inf` to disable it everywhere diff --git a/pcapkit/foundation/reassembly/__init__.py b/pcapkit/foundation/reassembly/__init__.py index e583b2e971..878b6f472c 100644 --- a/pcapkit/foundation/reassembly/__init__.py +++ b/pcapkit/foundation/reassembly/__init__.py @@ -6,9 +6,9 @@ .. module:: pcapkit.foundation.reassembly :mod:`pcapkit.foundation.reassembly`, based on algorithms described -in :rfc:`791`, :rfc:`815`, :rfc:`6347`, :rfc:`9260` and :rfc:`8260`, +in :rfc:`791`, :rfc:`815`, :rfc:`6347`, :rfc:`9260`, :rfc:`8260` and :rfc:`9846`, implements datagram reassembly of IP packets, TCP segments, DTLS handshake -messages and SCTP user messages. +messages, SCTP user messages and TLS records. """ # Reassembly for DTLS handshake messages @@ -23,12 +23,15 @@ from pcapkit.foundation.reassembly.sctp.reassembly import SCTP as SCTP_Reassembly # Reassembly for TCP from pcapkit.foundation.reassembly.tcp.reassembly import TCP as TCP_Reassembly +# Reassembly for TLS records +from pcapkit.foundation.reassembly.tls.reassembly import TLS as TLS_Reassembly __all__ = [ 'IPv4_Reassembly', 'IPv6_Reassembly', # IP Reassembly 'TCP_Reassembly', # TCP Reassembly 'DTLS_Reassembly', # DTLS Reassembly 'SCTP_Reassembly', # SCTP Reassembly + 'TLS_Reassembly', # TLS Reassembly 'ReassemblyManager', # Reassembly Manager, defined below ] diff --git a/pcapkit/foundation/reassembly/data.py b/pcapkit/foundation/reassembly/data.py index 8571679521..9d151aa7d3 100644 --- a/pcapkit/foundation/reassembly/data.py +++ b/pcapkit/foundation/reassembly/data.py @@ -26,17 +26,19 @@ from pcapkit.const.reg.apptype import TCP as AppType_TCP from pcapkit.const.reg.transtype import TransType from pcapkit.const.sctp.payload_protocol_identifier import PayloadProtocolIdentifier + from pcapkit.const.tls.content_type import ContentType from pcapkit.const.tls.handshake_type import HandshakeType from pcapkit.foundation.reassembly.dtls.data import Datagram as DTLS_Datagram from pcapkit.foundation.reassembly.ip.data import Datagram as IP_Datagram from pcapkit.foundation.reassembly.sctp.data import Datagram as SCTP_Datagram from pcapkit.foundation.reassembly.tcp.data import Datagram as TCP_Datagram + from pcapkit.foundation.reassembly.tls.data import Datagram as TLS_Datagram from pcapkit.protocols.application.dtls.data import DTLSHandshake from pcapkit.protocols.protocol import ProtocolBase # registry key an analyser dispatches a reassembled payload on; see ``Deferred`` _KT = TypeVar('_KT', 'TransType', 'tuple[AppType_TCP, AppType_TCP]', 'tuple[HandshakeType, int, int]', - 'Optional[PayloadProtocolIdentifier]') + 'Optional[PayloadProtocolIdentifier]', 'tuple[ContentType, int]') class Completion(EnumLookup, StrEnum): @@ -201,6 +203,14 @@ class Deferred(ReduceAsProtocol2, Generic[_KT]): :func:`~pcapkit.foundation.analysis.sctp.sctp_message` runs, :meth:`SCTP.analyze `, which looks the next layer up by that identifier. + * :meth:`TLS._make_datagram + ` builds a + ``Deferred[tuple[ContentType, int]]`` for a complete record. It passes the + record's ``(type, legacy_record_version)`` (:rfc:`9846#section-5.1`) to the + decoder :func:`~pcapkit.foundation.analysis.tls.tls_record` runs, + :meth:`TLS.analyze_record + `, which reads + the fragment by its :class:`~pcapkit.const.tls.content_type.ContentType`. Those are the cases the type parameter is constrained to. IP's and TCP's are *named registry values* rather than one named value and one pair of bare @@ -240,10 +250,11 @@ class Deferred(ReduceAsProtocol2, Generic[_KT]): ``analyze`` it calls, to the stops and context the extraction's engine parses its frames with (:issue:`2933`), and for IP to the datagram's addresses (:issue:`2945`); that protocol's - ``analyze_handshake`` for DTLS. + ``analyze_handshake`` for DTLS, and ``analyze_record`` for TLS. proto: What the analyser dispatches the payload on -- the payload protocol type for IP, the port pair for TCP, the handshake header - for DTLS, the payload protocol identifier for SCTP, as above. + for DTLS, the payload protocol identifier for SCTP, the record's type and + version for TLS, as above. payload: Reassembled payload to parse. .. versionadded:: 1.5.0 @@ -263,7 +274,8 @@ class Deferred(ReduceAsProtocol2, Generic[_KT]): .. versionchanged:: 1.9.0 Also constrained to the payload protocol identifier SCTP reassembly - dispatches on (:issue:`2935`). + dispatches on (:issue:`2935`), and to the TLS record header + (:issue:`2938`). """ @@ -340,12 +352,17 @@ class ReassemblyData(Info): #: #: .. versionadded:: 1.9.0 sctp: 'tuple[SCTP_Datagram, ...]' + #: TLS reassembled records. + #: + #: .. versionadded:: 1.9.0 + tls: 'tuple[TLS_Datagram, ...]' def __init__(self, ipv4: 'Optional[tuple[IP_Datagram, ...]]' = None, # pylint: disable=super-init-not-called ipv6: 'Optional[tuple[IP_Datagram, ...]]' = None, tcp: 'Optional[tuple[TCP_Datagram, ...]]' = None, dtls: 'Optional[tuple[DTLS_Datagram, ...]]' = None, sctp: 'Optional[tuple[SCTP_Datagram, ...]]' = None, + tls: 'Optional[tuple[TLS_Datagram, ...]]' = None, **kwargs: 'Optional[tuple[Any, ...]]') -> 'None': - self.__update__(ipv4=ipv4, ipv6=ipv6, tcp=tcp, dtls=dtls, sctp=sctp, **kwargs) + self.__update__(ipv4=ipv4, ipv6=ipv6, tcp=tcp, dtls=dtls, sctp=sctp, tls=tls, **kwargs) self.__post_init__() diff --git a/pcapkit/foundation/reassembly/reassembly.py b/pcapkit/foundation/reassembly/reassembly.py index 4af0b52e1d..6f3e02b6bf 100644 --- a/pcapkit/foundation/reassembly/reassembly.py +++ b/pcapkit/foundation/reassembly/reassembly.py @@ -115,7 +115,8 @@ class ReassemblyBase(ReduceAsProtocol2, Generic[_PT, _DT, _IT, _BT], metaclass=R reassembled as the tuple of its received runs; otherwise as one contiguous payload, its holes zero-filled -- or, for IP while the total length is unknown and for SCTP, only the prefix up to the - first hole + first hole; for TLS, a record's fragment, zero-filled to the length + its header declares store: if store reassembled datagram in memory, i.e., :attr:`self._dtgram ` @@ -519,7 +520,8 @@ def __init__(self, *, strict: 'bool' = True, store: 'bool' = True, reassembled as the tuple of its received runs; otherwise as one contiguous payload, its holes zero-filled -- or, for IP while the total length is unknown and for SCTP, only the prefix up to the - first hole + first hole; for TLS, a record's fragment, zero-filled to the + length its header declares store: if store reassembled datagram in memory, i.e., :attr:`self._dtgram <_dtgram>` (if not, datagram will be discarded after callback) @@ -536,7 +538,9 @@ def __init__(self, *, strict: 'bool' = True, store: 'bool' = True, #: not completely reassembled is reported as the tuple of its #: received runs; otherwise, as one contiguous payload, its #: holes zero-filled -- or, for IP while the total length is - #: unknown and for SCTP, only the prefix up to the first hole. + #: unknown and for SCTP, only the prefix up to the first hole; for + #: TLS, a record's fragment, zero-filled to the length its header + #: declares. self._flag_s = strict #: bool: Store mode flag. If set to :data:`True`, all #: reassembled datagram will be stored in memory, i.e., @@ -707,7 +711,8 @@ class MyMixin(Reassembly): # not registered reassembled as the tuple of its received runs; otherwise as one contiguous payload, its holes zero-filled -- or, for IP while the total length is unknown and for SCTP, only the prefix up to the - first hole + first hole; for TLS, a record's fragment, zero-filled to the length + its header declares store: if store reassembled datagram in memory, i.e., :attr:`self._dtgram <_dtgram>` (if not, datagram will be discarded after callback) diff --git a/pcapkit/foundation/reassembly/tcp/reassembly.py b/pcapkit/foundation/reassembly/tcp/reassembly.py index a8bb5467b0..501c9ada76 100644 --- a/pcapkit/foundation/reassembly/tcp/reassembly.py +++ b/pcapkit/foundation/reassembly/tcp/reassembly.py @@ -21,6 +21,7 @@ DatagramID, Fragment, HoleDescriptor, Packet) from pcapkit.protocols.transport.tcp.protocol import TCP as TCP_Protocol from pcapkit.utilities import config +from pcapkit.utilities.seqnum import unwrap if TYPE_CHECKING: from typing import Type @@ -213,7 +214,7 @@ def reassembly(self, info: 'Packet') -> 'None': if fragment is None: fragment = next(reversed(buffer.ack.values())) END = fragment.isn + fragment.len - UNWRAPPED = self._unwrap(PSN, END) + UNWRAPPED = unwrap(PSN, END) # the zero-filled gap merging this segment would open, either side limit = config.TCP_GAP_LIMIT if limit != -1 and max(UNWRAPPED - END, fragment.isn - (UNWRAPPED + info.len)) > limit: @@ -471,22 +472,6 @@ def submit(self, buf: 'Buffer', *, bufid: 'BufferID', # type: ignore[override] # Utilities. ########################################################################## - @staticmethod - def _unwrap(seq: 'int', ref: 'int') -> 'int': - """Place a 32-bit sequence number on the unwrapped line near ``ref``. - - Arguments: - seq: sequence number as carried on the wire, i.e. modulo 2**32 - ref: unwrapped sequence number the segment is expected to be near - - Returns: - The integer congruent to ``seq`` modulo 2**32 that lies within - 2**31 of ``ref``, which is how :rfc:`9293#section-3.4` compares - sequence numbers. - - """ - return ref + (seq - ref + 0x80000000) % 0x100000000 - 0x80000000 - @staticmethod def _anchored(buf: 'Buffer') -> 'bool': """Whether a buffer's stream start is known, i.e. its SYN was captured. diff --git a/pcapkit/foundation/reassembly/tls/__init__.py b/pcapkit/foundation/reassembly/tls/__init__.py new file mode 100644 index 0000000000..07ccd7220f --- /dev/null +++ b/pcapkit/foundation/reassembly/tls/__init__.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# pylint: disable=unused-import +"""TLS Record Reassembly +=========================== + +.. module:: pcapkit.foundation.reassembly.tls + +:mod:`pcapkit.foundation.reassembly.tls` holds the TLS record reassembly class, +:class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS`, in +:mod:`~pcapkit.foundation.reassembly.tls.reassembly`, and its data models in +:mod:`~pcapkit.foundation.reassembly.tls.data`. + +Its data classes are importable as ``Data_*``. + +.. versionadded:: 1.9.0 + +""" +from pcapkit.foundation.reassembly.tls.reassembly import TLS + +# Data Models +from pcapkit.foundation.reassembly.tls.data import Buffer as Data_Buffer +from pcapkit.foundation.reassembly.tls.data import Datagram as Data_Datagram +from pcapkit.foundation.reassembly.tls.data import DatagramID as Data_DatagramID +from pcapkit.foundation.reassembly.tls.data import Run as Data_Run + +__all__ = ['TLS'] diff --git a/pcapkit/foundation/reassembly/tls/data.py b/pcapkit/foundation/reassembly/tls/data.py new file mode 100644 index 0000000000..8a98f1bd44 --- /dev/null +++ b/pcapkit/foundation/reassembly/tls/data.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- +"""data models for TLS record reassembly + +.. versionadded:: 1.9.0 + +""" + +from typing import TYPE_CHECKING, Generic, TypeVar + +from pcapkit.corekit.infoclass import Info, info_final +from pcapkit.corekit.packet import DeferredPacket +from pcapkit.foundation.reassembly.data import Deferred +from pcapkit.utilities.compat import Tuple + +__all__ = [ + 'DatagramID', 'Datagram', 'Run', 'Buffer', 'BufferID', +] + +if TYPE_CHECKING: + from ipaddress import IPv4Address, IPv6Address + from typing import Optional + + from typing_extensions import TypeAlias + + from pcapkit.const.tls.content_type import ContentType as Enum_ContentType + from pcapkit.foundation.reassembly.data import Completion + from pcapkit.protocols.protocol import ProtocolBase + +_AT = TypeVar('_AT', 'IPv4Address', 'IPv6Address') + +#: Buffer ID -- one direction of a TCP connection, its source address and port +#: and its destination address and port, as for TCP reassembly. +BufferID: 'TypeAlias' = Tuple[_AT, int, _AT, int] + + +@info_final +class DatagramID(Info, Generic[_AT]): + """Data model for :term:`TLS ` original record identifier.""" + + #: Source address and port. + src: 'tuple[_AT, int]' + #: Destination address and port. + dst: 'tuple[_AT, int]' + #: TCP sequence number of the record's first octet. + seq: 'int' + + if TYPE_CHECKING: + def __init__(self, src: 'tuple[_AT, int]', dst: 'tuple[_AT, int]', seq: 'int') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long + + +@info_final +class Datagram(DeferredPacket, Info, Generic[_AT]): + """Data model for :term:`TLS ` reassembled record.""" + + #: Listing ``packet`` here is what makes :attr:`packet` lazy -- see + #: :class:`~pcapkit.corekit.packet.DeferredPacket`. + __additional__ = ['packet'] + #: Placeholder class :attr:`packet` may hold, for + #: :class:`~pcapkit.corekit.packet.DeferredPacket` to resolve. + __deferred__ = Deferred + + #: How completely the record was reassembled, and why reassembly stopped; + #: see :class:`~pcapkit.foundation.reassembly.data.Completion`. + completed: 'Completion' + #: Original record identifier. + id: 'DatagramID[_AT]' + #: Numbers of the packets that carried the record's octets. + index: 'tuple[int, ...]' + #: Record content type. + content_type: 'Enum_ContentType' + #: Legacy record version. + version: 'int' + #: Fragment length the record header declares. + length: 'int' + #: Reassembled fragment, undecoded. + fragment: 'bytes | tuple[bytes, ...]' + #: Decoded record, as :func:`~pcapkit.foundation.analysis.tls.tls_record` returns + #: it unless the reassembly's ``__protocol_type__`` names another protocol, whose + #: ``analyze_record`` then decodes it. Decoded on first read, and :data:`None` + #: for an incomplete record. A + #: :class:`~pcapkit.foundation.reassembly.data.Deferred` may be passed in its + #: place, and reading this attribute then runs it and keeps the result. + packet: 'Optional[ProtocolBase]' + + if TYPE_CHECKING: + def __init__(self, completed: 'Completion', id: 'DatagramID[_AT]', index: 'tuple[int, ...]', content_type: 'Enum_ContentType', version: 'int', length: 'int', fragment: 'bytes | tuple[bytes, ...]', packet: 'Optional[ProtocolBase | Deferred[tuple[Enum_ContentType, int]]]') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin + + +@info_final +class Run(Info): + """Data model for :term:`TLS ` run of contiguous octets held.""" + + #: Unwrapped sequence number of the octet held in ``raw[0]``. + first: 'int' + #: Octets held, in sequence order. + raw: 'bytearray' + + if TYPE_CHECKING: + def __init__(self, first: 'int', raw: 'bytearray') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long + + +@info_final +class Buffer(Info): + """Data model for :term:`TLS ` buffer entry -- one direction + of a TCP connection, followed from a record boundary.""" + + #: Unwrapped sequence number of the next record's first octet. Sequence + #: numbers here are read modulo ``2 ** 32`` relative to it, so a stream + #: crossing ``2 ** 32`` continues past it. + boundary: 'int' + #: Octets held at or past :attr:`boundary`, in sequence order, none adjacent + #: to or overlapping another. + runs: 'list[Run]' + #: Octets each packet added. Each entry is ``(num, first, stop)``, its number and + #: the unwrapped sequence range, ``stop`` exclusive, in the order they arrived. + ind: 'list[tuple[int, int, int]]' + #: Unwrapped sequence number the stream ends at, once its FIN is seen. + fin: 'Optional[int]' + #: Whether the stream has ended, at its FIN or an RST, so that only a SYN + #: opens it again. + closed: 'bool' + #: Capture timestamp of the first segment buffered under this buffer ID, in + #: seconds since the Unix epoch. Origin of the reassembly timer, and never + #: revised. + timestamp: 'float' + + if TYPE_CHECKING: + def __init__(self, boundary: 'int', runs: 'list[Run]', ind: 'list[tuple[int, int, int]]', fin: 'Optional[int]', closed: 'bool', timestamp: 'float') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long diff --git a/pcapkit/foundation/reassembly/tls/reassembly.py b/pcapkit/foundation/reassembly/tls/reassembly.py new file mode 100644 index 0000000000..4bc6a6a1da --- /dev/null +++ b/pcapkit/foundation/reassembly/tls/reassembly.py @@ -0,0 +1,475 @@ +# -*- coding: utf-8 -*- +"""TLS Record Reassembly +=========================== + +.. module:: pcapkit.foundation.reassembly.tls.reassembly + +:mod:`pcapkit.foundation.reassembly.tls.reassembly` contains +:class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS` only, which reconstructs +the TLS records of a TCP stream, a record split across segments included +(:rfc:`9846#section-5`). + +.. versionadded:: 1.9.0 + +""" +from typing import TYPE_CHECKING, Generic + +from pcapkit.foundation.reassembly.data import Completion, Deferred +from pcapkit.foundation.reassembly.reassembly import ReassemblyBase +from pcapkit.foundation.reassembly.tcp.data import Packet as TCP_Packet +from pcapkit.foundation.reassembly.tls.data import _AT, Buffer, BufferID, Datagram, DatagramID, Run +from pcapkit.protocols.application.tls.protocol import TLS as TLS_Protocol +from pcapkit.utilities.exceptions import CaughtByCaller, ProtocolError +from pcapkit.utilities.seqnum import unwrap + +if TYPE_CHECKING: + from typing import Optional, Type + + from pcapkit.const.tls.content_type import ContentType as Enum_ContentType + +__all__ = ['TLS'] + + +class TLS(ReassemblyBase[TCP_Packet, Datagram[_AT], BufferID, Buffer], Generic[_AT]): # pylint: disable=abstract-method + """Reassembly for TLS records. + + Args: + strict: if :data:`True`, report a record that is not completely + reassembled as the tuple of its fragment's received runs; otherwise + as one contiguous fragment, its holes zero-filled + store: if store reassembled datagram in memory, i.e., + :attr:`self._dtgram ` + (if not, datagram will be discarded after callback) + timeout: reassembly timeout in seconds, on the capture's own clock; + :data:`None` selects + :attr:`~pcapkit.foundation.reassembly.reassembly.Reassembly.__timeout__`, + which for TLS disables expiry + + Note: + Over TCP a record is delimited by its header alone (:rfc:`9846#section-5.1`), + so each direction of a connection is followed as one octet stream, from a + record boundary, and cut into records by + :meth:`TLS.record_header `. + Every record is reported, the ones a segment holds whole included, since a + boundary is known only from the record before it. + + The stream is the segments' octets in sequence order (:rfc:`9293#section-3.4`). + A segment ahead of the octets held waits for those before it, and of + octets received twice the first are kept (:rfc:`9293#section-3.10`). A + record is reported once whole. One the stream ends inside -- at its FIN, + an RST or the end of the capture -- is reported incomplete, and so is + one a lost segment left a hole in, as the records after it are. + + The :class:`~pcapkit.foundation.extraction.Extractor` feeds it TCP + reassembly's :term:`reasm.tcp.packet` of every segment on a port + :attr:`TCP.__proto__ ` + binds to TLS, through :func:`pcapkit.toolkit.pcap.tls_reassembly` and its + siblings, and :func:`~pcapkit.foundation.analysis.tls.tls_record` decodes + what it reassembles. A complete record's + :attr:`~pcapkit.foundation.reassembly.tls.data.Datagram.packet` holds the + same decode, run on first read; both call the protocol's + :meth:`~pcapkit.protocols.application.tls.protocol.TLS.analyze_record`, the + ``packet`` that of :attr:`__protocol_type__`. + + Warning: + **Where the stream starts.** With its SYN captured, the stream is followed + from the octet after it, a record boundary. Without it, and again after + octets that open no record, the boundary is a guess: the first segment + arriving whose payload opens a record header, by + :meth:`TLS.record_header `, + is taken to open a record, and the octets before it are not reported. + Octets past a hole that covers a record header cannot be cut into + records, and are not reported either. + + **What the guess can get wrong.** The header's length may not exceed + ``2 ** 14 + 2048`` (:rfc:`5246#section-6.2.3`), so a segment whose first + octets declare a longer record, as ``17 03 03 ff ff`` would, opens no + stream. Ciphertext or a record's tail whose first five octets read as a + header within that bound still does: the records cut from it are false, + and those of the real stream behind it, up to the next octets that open no + record, are lost. + + **Where it ends.** A FIN or an RST closes the stream, and a later segment + on the same endpoints is ignored unless it is a SYN. + + Example: + >>> from pcapkit.foundation.reassembly.tls.reassembly import TLS + # Initialise instance: + >>> tls_reassembly = TLS() + # Call reassembly: + >>> tls_reassembly(packet_dict) + # Fetch result: + >>> result = tls_reassembly.datagram + + """ + if TYPE_CHECKING: + protocol: 'Type[TLS_Protocol]' + + ########################################################################## + # Defaults. + ########################################################################## + + #: Protocol name of current reassembly object. + __protocol_name__ = 'TLS' + #: Protocol of current reassembly object. An extension point -- a protocol + #: named here need only define ``record_header`` and ``analyze_record``, with + #: the signatures of :meth:`TLS.record_header + #: ` and + #: :meth:`TLS.analyze_record + #: `. + __protocol_type__ = TLS_Protocol + + # No ``__timeout__``: neither RFC 9846 nor RFC 9293 gives a record a deadline, + # so it inherits the base default, ``math.inf``, as TCP reassembly does. + + ########################################################################## + # Methods. + ########################################################################## + + def reassembly(self, info: 'TCP_Packet') -> 'None': + """Reassembly procedure. + + Arguments: + info: :term:`info ` record of the segment to be + reassembled + + Note: + The records the segment completes are reported before its RST, or + the FIN it completes the stream to, releases the buffer. So a + callback raising on one of them leaves the buffer in place, holding + the octets after them, and nothing is lost. + + """ + # clear cache + self._flag_n = False + self.__cached__.clear() + + BUFID = info.bufid # Buffer Identifier + TS = info.timestamp # Capture timestamp, i.e. the only clock we have + self.expire(TS) + + # NOTE: a SYN occupies a sequence number of its own (RFC 9293, section 3.4). + PSN = info.dsn + 1 if info.syn else info.dsn + + # A SYN opens a connection, whose first octet a record opens. + if info.syn: + old = self._buffer.pop(BUFID, None) + self._buffer[BUFID] = Buffer(boundary=PSN, runs=[], ind=[], fin=None, closed=False, timestamp=TS) + if old is not None: + self._release(old, bufid=BUFID) + + buf = self._buffer.get(BUFID) + if buf is None: + if not self._opens_record(info.payload): + return + buf = Buffer(boundary=PSN, runs=[], ind=[], fin=None, closed=False, timestamp=TS) + self._buffer[BUFID] = buf + elif buf.closed: + return + + FIRST = unwrap(PSN, buf.boundary) + # NOTE: a FIN below the boundary contradicts the records already cut, so it is ignored. + if info.fin and buf.fin is None and FIRST + info.len >= buf.boundary: + buf.__update__(fin=FIRST + info.len) + self._close_runs(buf, FIRST + info.len) + if info.len: + self._hold_segment(buf, FIRST, bytes(info.payload), info.num) + + records, framed = self._cut_records(buf, BUFID) + if not framed: + # NOTE: what follows octets that open no record cannot be cut into records. + del self._buffer[BUFID] + if records: + self._notify(records, store=True) + if not framed: + return + + # An RST closes the connection at once (RFC 9293, section 3.10.7.4), and a FIN + # once every octet before it is held. + if info.rst or self._stream_whole(buf): + self._buffer[BUFID] = Buffer(boundary=buf.boundary, runs=[], ind=[], fin=buf.fin, + closed=True, timestamp=TS) + self._release(buf, bufid=BUFID) + + def submit(self, buf: 'Buffer', *, bufid: 'BufferID', expired: 'bool' = False, # type: ignore[override] # pylint: disable=arguments-differ + store: 'bool' = False) -> 'list[Datagram[_AT]]': + """Submit reassembled payload. + + Arguments: + buf: :term:`buffer ` of the stream + bufid: buffer identifier + expired: whether this buffer is being submitted because + :meth:`~pcapkit.foundation.reassembly.reassembly.Reassembly.expire` + abandoned it under the reassembly timeout + store: whether ``buf`` has left + :attr:`~pcapkit.foundation.reassembly.reassembly.Reassembly._buffer` + for good, so its records join + :attr:`~pcapkit.foundation.reassembly.reassembly.Reassembly._dtgram` + before the callbacks run, and one that raises cannot lose them + + Returns: + Every record still held in ``buf`` whose header is, in sequence + order up to the first hole a header lies in, each reported + :attr:`~pcapkit.foundation.reassembly.data.Completion.COMPLETE` if + its fragment is whole, otherwise + :attr:`~pcapkit.foundation.reassembly.data.Completion.TIMEOUT` or + :attr:`~pcapkit.foundation.reassembly.data.Completion.PARTIAL`. + + """ + ret = [] # type: list[Datagram[_AT]] + start = buf.boundary + while True: + run = next((run for run in buf.runs if run.first <= start < run.first + len(run.raw)), None) + if run is None: + break + try: + header = self._read_header(run.raw[start - run.first:]) + except ProtocolError: + break + if header is None: + break + + lo = start + header[2] + hi = lo + header[3] + pieces = [(max(held.first, lo), bytes(held.raw[max(held.first, lo) - held.first:hi - held.first])) + for held in buf.runs if held.first < hi and held.first + len(held.raw) > lo] + fragment = b''.join(piece for (_, piece) in pieces) # type: bytes | tuple[bytes, ...] + if len(fragment) == header[3]: + completion = Completion.COMPLETE + else: + completion = Completion.TIMEOUT if expired else Completion.PARTIAL + if self._flag_s: + fragment = tuple(piece for (_, piece) in pieces) + else: + filled = bytearray(header[3]) + for (pos, piece) in pieces: + filled[pos - lo:pos - lo + len(piece)] = piece + fragment = bytes(filled) + ret.append(self._make_datagram(buf, bufid, start, header, completion, fragment)) + start = hi + + # NOTE: an open stream holding no record, or a closed one, reports none and runs no callback. + if not ret: + return ret + return self._notify(ret, store=store) + + ########################################################################## + # Utilities. + ########################################################################## + + def _read_header(self, data: 'bytes | bytearray') -> 'Optional[tuple[Enum_ContentType, int, int, int]]': + """Read the header of the record ``data`` opens. + + Arguments: + data: octets from a record boundary on + + Returns: + As :meth:`TLS.record_header + ` of + :attr:`__protocol_type__` returns it. + + Raises: + ProtocolError: If the header opens no record, constructed quietly, + since the caller handles it. + + """ + with CaughtByCaller(ProtocolError): + return self.protocol.record_header(data) # type: ignore[arg-type] + + def _opens_record(self, data: 'bytes | bytearray') -> 'bool': + """Whether a segment's payload opens a record header. + + Arguments: + data: the segment's payload + + Returns: + Whether a whole record header opens ``data``. + + """ + try: + return self._read_header(data) is not None + except ProtocolError: + return False + + @staticmethod + def _close_runs(buf: 'Buffer', end: 'int') -> 'None': + """Drop the octets held at or past the FIN. + + Arguments: + buf: :term:`buffer ` of the stream + end: unwrapped sequence number the stream ends at, its + :attr:`~Buffer.fin` + + """ + runs = [] # type: list[Run] + for run in buf.runs: + if run.first < end: + del run.raw[end - run.first:] + runs.append(run) + buf.runs[:] = runs + buf.ind[:] = [(num, first, min(stop, end)) for (num, first, stop) in buf.ind if first < end] + + @staticmethod + def _hold_segment(buf: 'Buffer', first: 'int', payload: 'bytes', num: 'int') -> 'None': + """Hold the octets of a segment that no earlier segment brought. + + Arguments: + buf: :term:`buffer ` of the stream + first: unwrapped sequence number of the segment's first octet + payload: the segment's payload + num: the segment's packet number + + Octets before :attr:`~Buffer.boundary` were cut into records already, + and octets at or past :attr:`~Buffer.fin` are not the stream's, so + neither is held. Of octets already held the first received are kept, + and only the new parts are processed (:rfc:`9293#section-3.10`). + + """ + lo = max(first, buf.boundary) + hi = first + len(payload) + if buf.fin is not None: + hi = min(hi, buf.fin) + + parts = [] # type: list[tuple[int, int]] + pos = lo + for run in buf.runs: + start, stop = run.first, run.first + len(run.raw) + if pos >= hi or start >= hi: + break + if stop <= pos: + continue + if start > pos: + parts.append((pos, start)) + pos = stop + if pos < hi: + parts.append((pos, hi)) + + for (start, stop) in parts: + TLS._hold_octets(buf.runs, start, payload[start - first:stop - first]) + buf.ind.append((num, start, stop)) + + @staticmethod + def _hold_octets(runs: 'list[Run]', first: 'int', octets: 'bytes') -> 'None': + """Add octets no run holds to the runs, merging the runs they adjoin. + + Arguments: + runs: runs held, in sequence order, mutated in place + first: unwrapped sequence number of the first octet + octets: the octets + + """ + index = 0 + while index < len(runs) and runs[index].first < first: + index += 1 + if index and runs[index - 1].first + len(runs[index - 1].raw) == first: + run = runs[index - 1] + run.raw.extend(octets) + else: + run = Run(first=first, raw=bytearray(octets)) + runs.insert(index, run) + index += 1 + if index < len(runs) and run.first + len(run.raw) == runs[index].first: + run.raw.extend(runs.pop(index).raw) + + def _cut_records(self, buf: 'Buffer', bufid: 'BufferID') -> 'tuple[list[Datagram[_AT]], bool]': + """Cut the whole records held from :attr:`~Buffer.boundary` on off the stream. + + Arguments: + buf: :term:`buffer ` of the stream, mutated in place + bufid: buffer identifier + + Returns: + The records cut, each + :attr:`~pcapkit.foundation.reassembly.data.Completion.COMPLETE`, and + whether the octets after them can still be cut: :data:`False` once + they open no record. + + """ + records = [] # type: list[Datagram[_AT]] + while buf.runs and buf.runs[0].first == buf.boundary: + run = buf.runs[0] + try: + header = self._read_header(run.raw) + except ProtocolError: + return records, False + if header is None: + break + size = header[2] + header[3] + if len(run.raw) < size: + break + records.append(self._make_datagram(buf, bufid, buf.boundary, header, Completion.COMPLETE, + bytes(run.raw[header[2]:size]))) + + end = buf.boundary + size + del run.raw[:size] + if run.raw: + run.__update__(first=end) + else: + del buf.runs[0] + buf.__update__(boundary=end) + buf.ind[:] = [entry for entry in buf.ind if entry[2] > end] + return records, True + + @staticmethod + def _stream_whole(buf: 'Buffer') -> 'bool': + """Whether a stream has seen its FIN and every octet before it. + + Arguments: + buf: :term:`buffer ` of the stream + + Returns: + :data:`True` once a FIN has been seen and every octet from + :attr:`~Buffer.boundary` up to it is held. + + """ + if buf.fin is None: + return False + if buf.boundary >= buf.fin: + return True + return (len(buf.runs) == 1 and buf.runs[0].first == buf.boundary + and buf.runs[0].first + len(buf.runs[0].raw) == buf.fin) + + def _make_datagram(self, buf: 'Buffer', bufid: 'BufferID', start: 'int', + header: 'tuple[Enum_ContentType, int, int, int]', completion: 'Completion', + fragment: 'bytes | tuple[bytes, ...]') -> 'Datagram[_AT]': + """Build a :class:`~pcapkit.foundation.reassembly.tls.data.Datagram` for a record. + + Arguments: + buf: :term:`buffer ` the record was held in + bufid: buffer identifier it was held under + start: unwrapped sequence number of the record's first octet + header: the record's header, as :meth:`_read_header` reads it + completion: how completely it was reassembled + fragment: its fragment, as the record reports it + + Returns: + The record. Its ``packet`` is the decode + :func:`~pcapkit.foundation.analysis.tls.tls_record` runs, by this + reassembly's own + :attr:`protocol `, + deferred to its first read, if the record is complete, and + :data:`None` otherwise, as that function returns. + + """ + content_type, version, header_length, length = header + stop = start + header_length + length + index = tuple(dict.fromkeys(num for (num, first, last) in buf.ind if first < stop and last > start)) + + packet = None # type: Optional[Deferred[tuple[Enum_ContentType, int]]] + if completion: + packet = Deferred(self.protocol.analyze_record, (content_type, version), fragment) # type: ignore[arg-type] + + return Datagram( + completed=completion, + id=DatagramID( + src=(bufid[0], bufid[1]), + dst=(bufid[2], bufid[3]), + seq=start & 0xFFFFFFFF, + ), + index=index, + content_type=content_type, + version=version, + length=length, + fragment=fragment, + packet=packet, + ) diff --git a/pcapkit/protocols/application/dtls/const.py b/pcapkit/protocols/application/dtls/const.py index f0227cfed4..a70eacfa87 100644 --- a/pcapkit/protocols/application/dtls/const.py +++ b/pcapkit/protocols/application/dtls/const.py @@ -21,6 +21,10 @@ _DTLS13_LEGACY_VERSIONS = frozenset({_DTLSV1_0_VERSION, _DTLSV1_2_VERSION}) #: Top three bits of a unified-header first octet, ``001`` (:rfc:`9147#section-4.1`). _UNIFIED_PREFIX = 0b001 +#: Longest ciphertext a unified-header record may carry. Its length is a TLS 1.3 +#: record's (:rfc:`9147#section-4`), at most ``2 ** 14 + 256`` +#: (:rfc:`9846#section-5.2`). +_UNIFIED_MAX_LENGTH = 2 ** 14 + 256 #: Shortest ciphertext a unified-header record may carry. The record-number #: sample is taken from its first 16 octets (:rfc:`9147#section-4.2.3`). _CIPHERTEXT_MIN_LENGTH = 16 diff --git a/pcapkit/protocols/application/dtls/protocol.py b/pcapkit/protocols/application/dtls/protocol.py index 36d2f4a843..e5cad8add9 100644 --- a/pcapkit/protocols/application/dtls/protocol.py +++ b/pcapkit/protocols/application/dtls/protocol.py @@ -69,8 +69,9 @@ :class:`~pcapkit.protocols.misc.raw.protocol.Raw` together with everything after it. * Octets that open no whole record stay raw, with no error: an unsupported content type, a legacy version outside ``0xFExx``, a header cut short, a - length past the end of the datagram, or a connection ID whose length is - not known, which leaves the record's end unknown. + length past the end of the datagram or past the RFCs' bound (``2 ** 14 + + 2048``, or ``2 ** 14 + 256`` for a unified header), or a connection ID whose + length is not known, which leaves the record's end unknown. * A parse told to stop at DTLS (``protocol='DTLS'`` or ``layer='Application'``) keeps the rest of the datagram raw. * Each record is a layer, so :data:`~pcapkit.utilities.config.FRAME_LAYER_LIMIT` @@ -114,7 +115,7 @@ _CIPHERTEXT_MIN_LENGTH, _DTLS13_LEGACY_VERSIONS, _DTLSV1_0_VERSION, _DTLSV1_2_VERSION, _LEGACY_HEADER_LENGTH, - _UNIFIED_PREFIX) + _UNIFIED_MAX_LENGTH, _UNIFIED_PREFIX) from pcapkit.protocols.application.dtls.data import DTLS as Data_DTLS from pcapkit.protocols.application.dtls.data import DTLSCIDCiphertext as Data_DTLSCIDCiphertext from pcapkit.protocols.application.dtls.data import DTLSCiphertext as Data_DTLSCiphertext @@ -122,8 +123,8 @@ from pcapkit.protocols.application.dtls.schema import DTLS as Schema_DTLS from pcapkit.protocols.application.dtls.schema import DTLSCIDCiphertext as Schema_DTLSCIDCiphertext from pcapkit.protocols.application.dtls.schema import DTLSCiphertext as Schema_DTLSCiphertext -from pcapkit.protocols.application.ssl.const import (_DTLS_VERSION_MAJOR, _WIRE_CONTENT_TYPES, - DTLS13_VERSION) +from pcapkit.protocols.application.ssl.const import (_DTLS_VERSION_MAJOR, _RECORD_MAX_LENGTH, + _WIRE_CONTENT_TYPES, DTLS13_VERSION) from pcapkit.protocols.application.ssl.data import ConnectionId as Data_ConnectionId from pcapkit.protocols.application.ssl.protocol import SSL from pcapkit.utilities.exceptions import CaughtByCaller, ProtocolError @@ -241,11 +242,13 @@ def _opens_whole_record(data: 'bytes', context: 'Optional[DTLSContext]') -> 'boo :meth:`SSL._validate_tls_record `: a content type a genuine record carries, a ``0xFExx`` legacy version, and a fragment - that ends inside ``data``. A ``tls12_cid`` header needs DTLS 1.2's version - and a connection ID ``context`` knows the length of. A unified header needs - the same of its connection ID, if it carries one, and a fragment that ends - inside ``data``; without a length it runs to the end of ``data``, as the - last record of a datagram does (:rfc:`9147#section-4`). + of at most ``2 ** 14 + 2048`` octets that ends inside ``data``. A + ``tls12_cid`` header needs DTLS 1.2's version, a connection ID ``context`` + knows the length of, and the same of its fragment. A unified header needs + the same of its connection ID, if it carries one, and a fragment of at most + ``2 ** 14 + 256`` octets that ends inside ``data``; without a length it runs + to the end of ``data``, as the last record of a datagram does + (:rfc:`9147#section-4`). Args: data: Octets after a record. @@ -266,7 +269,8 @@ def _opens_whole_record(data: 'bytes', context: 'Optional[DTLSContext]') -> 'boo if len(data) < header: return False if not flags['length_present']: - return True + return len(data) - header <= _UNIFIED_MAX_LENGTH + limit = _UNIFIED_MAX_LENGTH elif data[0] == Enum_ContentType.tls12_cid: cid_length = _record_cid_length(data, context) if cid_length is None or int.from_bytes(data[1:3], 'big') != _DTLSV1_2_VERSION: @@ -274,12 +278,15 @@ def _opens_whole_record(data: 'bytes', context: 'Optional[DTLSContext]') -> 'boo header = _LEGACY_HEADER_LENGTH + cid_length if len(data) < header: return False + limit = _RECORD_MAX_LENGTH else: header = _LEGACY_HEADER_LENGTH if len(data) < header or data[0] not in _WIRE_CONTENT_TYPES or data[1] != _DTLS_VERSION_MAJOR: return False + limit = _RECORD_MAX_LENGTH # Every header ends with its 16-bit length. - return header + int.from_bytes(data[header - 2:header], 'big') <= len(data) + length = int.from_bytes(data[header - 2:header], 'big') + return length <= limit and header + length <= len(data) class DTLSContext(ProtocolContext): @@ -551,8 +558,10 @@ def make(self, *, record, or given for a legacy-format one of another type; if a legacy-format record's ``content_type`` is a name, a :obj:`bool`, or a member or code the 8-bit content type field - cannot carry; or if an extension of ``content`` given as a - ``(type, kwargs)`` pair has such a type for its 16-bit field. + cannot carry; if an extension of ``content`` given as a + ``(type, kwargs)`` pair has such a type for its 16-bit field; or + if the fragment is longer than the RFCs allow, ``2 ** 14 + 2048`` + octets, or ``2 ** 14 + 256`` for a unified header. StructError: If another record-header field, or a field of ``content``, does not fit its width. FieldValueError: If a unified-header record's ``epoch`` does not @@ -568,6 +577,9 @@ def make(self, *, self._make_pack(sequence_number, size=2 if sequence_long else 1) if length_present: self._make_pack(len(content), size=2) + if len(content) > _UNIFIED_MAX_LENGTH: + raise ProtocolError(f'{self.alias}: invalid ciphertext length {len(content)}: exceeds ' + f'{_UNIFIED_MAX_LENGTH} (record_overflow)') return Schema_DTLSCiphertext( flags={ 'fixed': _UNIFIED_PREFIX, @@ -591,6 +603,9 @@ def make(self, *, for value, size in ((version, 2), (epoch, 2), (len(fragment), 2)): self._make_pack(value, size=size) self._make_pack(sequence_number, size=6) + if len(fragment) > _RECORD_MAX_LENGTH: + raise ProtocolError(f'{self.alias}: invalid record length {len(fragment)}: exceeds ' + f'{_RECORD_MAX_LENGTH} (record_overflow)') if content_type_ == Enum_ContentType.tls12_cid: if cid is None or not _is_cid(cid): raise ProtocolError(f'{self.alias}: invalid connection ID: {cid!r} ' @@ -944,7 +959,8 @@ def _read_dtls_ciphertext(self, length: 'Optional[int]' = None, **kwargs: 'Any') ProtocolError: If ``C`` is set but no connection ID is carried; if the header or its declared length runs past the buffer; or if the ciphertext is shorter than the record-number sample - (:rfc:`9147#section-4.2.3`). + (:rfc:`9147#section-4.2.3`), or longer than a TLS 1.3 record's + ``2 ** 14 + 256`` (:rfc:`9147#section-4`, :rfc:`9846#section-5.2`). """ self._alias = 'DTLS 1.3' @@ -962,6 +978,9 @@ def _read_dtls_ciphertext(self, length: 'Optional[int]' = None, **kwargs: 'Any') if len(schema.fragment or b'') < _CIPHERTEXT_MIN_LENGTH: raise ProtocolError(f'{self.alias}: invalid format: ciphertext is shorter than the ' 'record-number sample (RFC 9147 section 4.2.3)') + if len(schema.fragment or b'') > _UNIFIED_MAX_LENGTH: + raise ProtocolError(f'{self.alias}: invalid format: ciphertext of {len(schema.fragment)} ' + f'octets exceeds {_UNIFIED_MAX_LENGTH} (record_overflow)') dtls = Data_DTLSCiphertext( epoch=flags['epoch'], @@ -1001,8 +1020,9 @@ def _read_dtls_cid_ciphertext(self, length: 'Optional[int]' = None, **kwargs: 'A Raises: ProtocolError: If the legacy version is not DTLS 1.2's, the only one ``tls12_cid`` applies to (:rfc:`9146#section-10.3`); if the - connection ID is empty; or if the record runs past the end of - the buffer. + connection ID is empty; or if the record's length runs past the + end of the buffer, or past the ``2 ** 14 + 2048`` of DTLS 1.2 + (:rfc:`9146#section-4`, :rfc:`5246#section-6.2.3`). """ schema = cast('Schema_DTLSCIDCiphertext', self.__header__) @@ -1014,6 +1034,9 @@ def _read_dtls_cid_ciphertext(self, length: 'Optional[int]' = None, **kwargs: 'A self._alias = 'DTLS 1.2' if not _is_cid(schema.cid): raise ProtocolError(f'{self.alias}: invalid format: a tls12_cid record carries no connection ID') + if schema.length > _RECORD_MAX_LENGTH: + raise ProtocolError(f'{self.alias}: invalid format: record length {schema.length} exceeds ' + f'{_RECORD_MAX_LENGTH} (record_overflow)') if self.length + schema.length > available: raise ProtocolError(f'{self.alias}: invalid format: record length {schema.length} runs past ' 'the end of the buffer') diff --git a/pcapkit/protocols/application/ssl/const.py b/pcapkit/protocols/application/ssl/const.py index 528a0c8db3..ba478826eb 100644 --- a/pcapkit/protocols/application/ssl/const.py +++ b/pcapkit/protocols/application/ssl/const.py @@ -17,6 +17,14 @@ #: DTLS encodes its legacy version as the one's complement of TLS's). _DTLS_VERSION_MAJOR = 0xFE +#: The longest fragment a legacy record header may declare, that of a TLSCiphertext +#: of SSLv3 to TLS 1.2 (:rfc:`6101#section-5.2.3`, :rfc:`5246#section-6.2.3`), which +#: DTLS 1.0 and 1.2 keep (:rfc:`4347#section-4`, :rfc:`6347#section-4`). TLS 1.3's +#: ``2 ** 14 + 256`` (:rfc:`9846#section-5.2`) and every plaintext's ``2 ** 14`` are +#: within it, and the header does not tell the versions apart. A peer that +#: receives a longer record sends ``record_overflow``. +_RECORD_MAX_LENGTH = 2 ** 14 + 2048 + #: The content types a genuine record may carry. An allowlist rather than #: every :class:`~pcapkit.const.tls.content_type.ContentType` member: 0 is #: never assigned, a value :rfc:`9846#section-5.1` rejects outright, and the diff --git a/pcapkit/protocols/application/ssl/protocol.py b/pcapkit/protocols/application/ssl/protocol.py index 8886d94ec3..b174e1bab1 100644 --- a/pcapkit/protocols/application/ssl/protocol.py +++ b/pcapkit/protocols/application/ssl/protocol.py @@ -61,8 +61,8 @@ from pcapkit.protocols.application.application import Application from pcapkit.protocols.application.ssl.const import (_DTLS_VERSION_MAJOR, _ECH_CONFIRMATION_LENGTH, _ECH_INNER, _ECH_OUTER, _HOST_NAME, - _HRR_RANDOM, _TLS_VERSION_MAJOR, - _WIRE_CONTENT_TYPES) + _HRR_RANDOM, _RECORD_MAX_LENGTH, + _TLS_VERSION_MAJOR, _WIRE_CONTENT_TYPES) from pcapkit.protocols.application.ssl.data import Alert as Data_Alert from pcapkit.protocols.application.ssl.data import \ CertificateCompressionAlgorithms as Data_CertificateCompressionAlgorithms @@ -2362,12 +2362,14 @@ def _validate_tls_record(self, schema: 'Any', *, available: 'int', dtls: 'bool') ProtocolError: If ``schema`` cannot be a genuine record, so that :func:`~pcapkit.corekit.decorators.beholder` degrades dispatch to :class:`~pcapkit.protocols.misc.raw.protocol.Raw` instead - of accepting a fabricated one. + of accepting a fabricated one. That includes a ``length`` past + ``2 ** 14 + 2048``, more than any TLS or DTLS version allows + (:rfc:`5246#section-6.2.3`). Note: A record split across TCP segments is rejected too: this layer holds only a fragment of it, and reassembly is - :class:`~pcapkit.foundation.reassembly.tcp.reassembly.TCP`'s job. + :class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS`'s job. """ # NOTE: ``make()`` leaves ``content_type`` a bare :obj:`int`, not the enum member a @@ -2386,6 +2388,11 @@ def _validate_tls_record(self, schema: 'Any', *, available: 'int', dtls: 'bool') f'{self.alias}: invalid format: legacy record version {schema.version:#06x} is ' f'not a {"DTLS" if dtls else "TLS"} one') + if schema.length > _RECORD_MAX_LENGTH: + raise ProtocolError( + f'{self.alias}: invalid format: record length {schema.length} exceeds ' + f'{_RECORD_MAX_LENGTH} (record_overflow)') + if self.length + schema.length > available: raise ProtocolError( f'{self.alias}: invalid format: record length {schema.length} runs past ' diff --git a/pcapkit/protocols/application/tls/protocol.py b/pcapkit/protocols/application/tls/protocol.py index 75b8da27b6..7495286b33 100644 --- a/pcapkit/protocols/application/tls/protocol.py +++ b/pcapkit/protocols/application/tls/protocol.py @@ -47,7 +47,8 @@ :class:`~pcapkit.protocols.misc.raw.protocol.Raw` together with everything after it, with no SSLv2 trial. * Octets that open no record -- an unsupported content type, a legacy - version outside ``0x03xx``, or a header cut short -- stay raw, with no error. + version outside ``0x03xx``, a length past the ``2 ** 14 + 2048`` of + :rfc:`5246#section-6.2.3`, or a header cut short -- stay raw, with no error. * A parse told to stop at TLS (``protocol='TLS'`` or ``layer='Application'``) keeps the rest of the segment raw. * Each record is a layer, so :data:`~pcapkit.utilities.config.FRAME_LAYER_LIMIT` @@ -56,10 +57,14 @@ Known Limitation ---------------- -**A record split across two TCP segments is not reassembled**, and decodes as +**A record split across TCP segments is not reassembled here**, and decodes as :class:`~pcapkit.protocols.misc.raw.protocol.Raw`, as does the partial record a segment ends inside. A record may be up to 16 KiB against a typical 1460-octet MSS, so -this is routine. +this is routine. ``Extractor(fin, reassembly=['tls'])`` reassembles every record +of the stream (:class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS`), framing +it with :meth:`TLS.record_header`, and +:func:`~pcapkit.foundation.analysis.tls.tls_record` decodes it with +:meth:`TLS.analyze_record`. .. versionadded:: 1.6.0 @@ -69,8 +74,8 @@ from pcapkit.const.tls.content_type import ContentType as Enum_ContentType from pcapkit.corekit.decorators import beholder from pcapkit.corekit.module import ModuleDescriptor -from pcapkit.protocols.application.ssl.const import (_TLS_VERSION_MAJOR, _WIRE_CONTENT_TYPES, - TLS13_VERSION) +from pcapkit.protocols.application.ssl.const import (_RECORD_MAX_LENGTH, _TLS_VERSION_MAJOR, + _WIRE_CONTENT_TYPES, TLS13_VERSION) from pcapkit.protocols.application.ssl.protocol import SSL from pcapkit.protocols.application.sslv2.data import ClientHello as SSLv2_ClientHello from pcapkit.protocols.application.sslv2.data import ServerHello as SSLv2_ServerHello @@ -81,7 +86,7 @@ from pcapkit.protocols.application.tls.data import TLS as Data_TLS from pcapkit.protocols.application.tls.schema import TLS as Schema_TLS from pcapkit.utilities.contextvars import beholding -from pcapkit.utilities.exceptions import ProtocolError +from pcapkit.utilities.exceptions import CaughtByCaller, ProtocolError from pcapkit.utilities.warnings import hold_warnings if TYPE_CHECKING: @@ -105,11 +110,8 @@ def _opens_whole_record(data: 'bytes') -> 'bool': """Whether ``data`` opens with a whole TLS record. - Only the record header is read, against the same checks as - :meth:`SSL._validate_tls_record - `: a content - type a genuine record carries, a ``0x03xx`` legacy version, and a fragment - that ends inside ``data``. + Only the record header is read, by :meth:`TLS.record_header`, and its fragment + must end inside ``data``. Args: data: Octets after a record. @@ -118,10 +120,12 @@ def _opens_whole_record(data: 'bytes') -> 'bool': Whether a further record opens ``data`` and ends inside it. """ - if len(data) < _RECORD_HEADER_LENGTH: + try: + with CaughtByCaller(ProtocolError): + header = TLS.record_header(data) + except ProtocolError: return False - return (data[0] in _WIRE_CONTENT_TYPES and data[1] == _TLS_VERSION_MAJOR - and _RECORD_HEADER_LENGTH + int.from_bytes(data[3:5], 'big') <= len(data)) + return header is not None and header[2] + header[3] <= len(data) class TLS(SSL[Data_TLS, Schema_TLS], schema=Schema_TLS, data=Data_TLS): @@ -246,7 +250,9 @@ def make(self, *, ProtocolError: If ``content_type`` is a name, a :obj:`bool`, or a member or code the 8-bit content type field cannot carry, or an extension of ``content`` given as a ``(type, kwargs)`` pair - has such a type for its 16-bit field. + has such a type for its 16-bit field; or if the fragment is + longer than ``2 ** 14 + 2048`` octets, which no version allows + (:rfc:`5246#section-6.2.3`). StructError: If ``version`` or the record length, or a field of ``content``, does not fit its width. @@ -258,6 +264,9 @@ def make(self, *, # refuse a wider value with the StructError the content makers raise. for value, size in ((version, 2), (len(fragment), 2)): self._make_pack(value, size=size) + if len(fragment) > _RECORD_MAX_LENGTH: + raise ProtocolError(f'{self.alias}: invalid record length {len(fragment)}: exceeds ' + f'{_RECORD_MAX_LENGTH} (record_overflow)') return Schema_TLS( content_type=content_type_, version=version, @@ -336,6 +345,81 @@ def from_data(cls, data: 'Any', /, **kwargs: 'Any') -> 'Any': return SSLv2.from_data(data, **kwargs) return super().from_data(data, **kwargs) + @classmethod + def record_header(cls, data: 'bytes', /) -> 'Optional[tuple[Enum_ContentType, int, int, int]]': + """Read the header of the record ``data`` opens, as a stream delimits it. + + A record over TCP is delimited by its header alone + [:rfc:`9846#section-5.1`], read against the checks of + :meth:`SSL._validate_tls_record + `: a + content type a genuine record carries and a ``0x03xx`` legacy version. Its + length may not exceed ``2 ** 14 + 2048``, the longest TLSCiphertext of + SSLv3 to TLS 1.2 [:rfc:`6101#section-5.2.3`, :rfc:`5246#section-6.2.3`]; + TLS 1.3's ``2 ** 14 + 256`` [:rfc:`9846#section-5.2`] is within it, and + the record header does not tell the two apart. + :class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS` frames a stream + with this. + + Args: + data: Octets from a record boundary on. + + Returns: + The record's content type, legacy version, header length and + fragment length; :data:`None` if ``data`` is shorter than a record + header. + + Raises: + ProtocolError: If the header opens no TLS record, a length past + that bound included. + + .. versionadded:: 1.9.0 + + """ + if len(data) < _RECORD_HEADER_LENGTH: + return None + content_type = Enum_ContentType.get(data[0]) + if content_type not in _WIRE_CONTENT_TYPES: + raise ProtocolError(f'{cls.__name__}: invalid format: unrecognised content type {data[0]}') + if data[1] != _TLS_VERSION_MAJOR: + raise ProtocolError(f'{cls.__name__}: invalid format: legacy record version ' + f'{int.from_bytes(data[1:3], "big"):#06x} is not a TLS one') + length = int.from_bytes(data[3:5], 'big') + if length > _RECORD_MAX_LENGTH: + raise ProtocolError(f'{cls.__name__}: invalid format: record length {length} exceeds ' + f'{_RECORD_MAX_LENGTH} (record_overflow)') + return (content_type, int.from_bytes(data[1:3], 'big'), _RECORD_HEADER_LENGTH, length) + + @classmethod + def analyze_record(cls, header: 'tuple[Enum_ContentType, int]', fragment: 'bytes') -> 'ProtocolBase': + """Analyse a record reassembled from a TCP stream, from its header and fragment. + + :func:`~pcapkit.foundation.analysis.tls.tls_record` runs this, and so does + the :class:`~pcapkit.foundation.reassembly.data.Deferred` that + :class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS` stores as a + complete record's ``packet``. + + The record is parsed as a segment's first record is, without the SSLv2 + trial, since its header is a TLS one. + + Args: + header: The record's ``(type, legacy_record_version)``. + fragment: The record's fragment, its ``length`` octets. + + Returns: + The record, as an instance of this class. A record that fails to + decode is kept as :class:`~pcapkit.protocols.misc.raw.protocol.Raw`, + as :meth:`Protocol.analyze ` + keeps a payload, its ``protocol`` this class's :meth:`__index__`. + + .. versionadded:: 1.9.0 + + """ + content_type, version = header + record = (bytes((int(content_type),)) + version.to_bytes(2, 'big') + + len(fragment).to_bytes(2, 'big') + fragment) + return cls._analyze_next_layer(cls, record, cls.__index__(), chained=True) + ########################################################################## # Data models. ########################################################################## diff --git a/pcapkit/toolkit/__init__.py b/pcapkit/toolkit/__init__.py index a094941189..298cbf570a 100644 --- a/pcapkit/toolkit/__init__.py +++ b/pcapkit/toolkit/__init__.py @@ -11,12 +11,13 @@ """ # tools for default engine from pcapkit.toolkit.pcap import (dtls_reassembly, ipv4_reassembly, ipv6_reassembly, sctp_reassembly, - tcp_reassembly, tcp_traceflow) + tcp_reassembly, tcp_traceflow, tls_reassembly) from pcapkit.toolkit.pcapng import ipv4_reassembly as pcapng_ipv4_reassembly from pcapkit.toolkit.pcapng import ipv6_reassembly as pcapng_ipv6_reassembly from pcapkit.toolkit.pcapng import tcp_reassembly as pcapng_tcp_reassembly from pcapkit.toolkit.pcapng import dtls_reassembly as pcapng_dtls_reassembly from pcapkit.toolkit.pcapng import sctp_reassembly as pcapng_sctp_reassembly +from pcapkit.toolkit.pcapng import tls_reassembly as pcapng_tls_reassembly from pcapkit.toolkit.pcapng import tcp_traceflow as pcapng_tcp_traceflow from pcapkit.toolkit.pcapng import block2frame as pcapng_block2frame @@ -27,6 +28,7 @@ # from pcapkit.toolkit.dpkt import ipv4_reassembly as dpkt_ipv4_reassembly # from pcapkit.toolkit.dpkt import ipv6_reassembly as dpkt_ipv6_reassembly # from pcapkit.toolkit.dpkt import tcp_reassembly as dpkt_tcp_reassembly +# from pcapkit.toolkit.dpkt import tls_reassembly as dpkt_tls_reassembly # from pcapkit.toolkit.dpkt import tcp_traceflow as dpkt_tcp_traceflow # # tools for PyShark engine @@ -39,6 +41,7 @@ # from pcapkit.toolkit.scapy import ipv4_reassembly as scapy_ipv4_reassembly # from pcapkit.toolkit.scapy import ipv6_reassembly as scapy_ipv6_reassembly # from pcapkit.toolkit.scapy import tcp_reassembly as scapy_tcp_reassembly +# from pcapkit.toolkit.scapy import tls_reassembly as scapy_tls_reassembly # from pcapkit.toolkit.scapy import tcp_traceflow as scapy_tcp_traceflow # # tools for PyPCAP engine @@ -56,26 +59,29 @@ # from pcapkit.toolkit.pypcapfile import packet2dict as pypcapfile_packet2dict # from pcapkit.toolkit.pypcapfile import ipv4_reassembly as pypcapfile_ipv4_reassembly # from pcapkit.toolkit.pypcapfile import tcp_reassembly as pypcapfile_tcp_reassembly +# from pcapkit.toolkit.pypcapfile import tls_reassembly as pypcapfile_tls_reassembly # from pcapkit.toolkit.pypcapfile import tcp_traceflow as pypcapfile_tcp_traceflow __all__ = [ # default engine 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'dtls_reassembly', 'sctp_reassembly', - 'tcp_traceflow', + 'tls_reassembly', 'tcp_traceflow', 'pcapng_ipv4_reassembly', 'pcapng_ipv6_reassembly', 'pcapng_tcp_reassembly', 'pcapng_dtls_reassembly', - 'pcapng_sctp_reassembly', 'pcapng_tcp_traceflow', + 'pcapng_sctp_reassembly', 'pcapng_tls_reassembly', 'pcapng_tcp_traceflow', 'pcapng_block2frame', # # DPKT engine # 'dpkt_ipv6_hdr_len', 'dpkt_packet2chain', 'dpkt_packet2dict', - # 'dpkt_ipv4_reassembly', 'dpkt_ipv6_reassembly', 'dpkt_tcp_reassembly', 'dpkt_tcp_traceflow', + # 'dpkt_ipv4_reassembly', 'dpkt_ipv6_reassembly', 'dpkt_tcp_reassembly', 'dpkt_tls_reassembly', + # 'dpkt_tcp_traceflow', # # PyShark engine # 'pyshark_packet2dict', 'pyshark_tcp_traceflow', # # Scapy engine # 'scapy_packet2chain', 'scapy_packet2dict', - # 'scapy_ipv4_reassembly', 'scapy_ipv6_reassembly', 'scapy_tcp_reassembly', 'scapy_tcp_traceflow', + # 'scapy_ipv4_reassembly', 'scapy_ipv6_reassembly', 'scapy_tcp_reassembly', 'scapy_tls_reassembly', + # 'scapy_tcp_traceflow', # # PyPCAP engine # 'pypcap_packet2chain', 'pypcap_packet2dict', @@ -86,5 +92,6 @@ # # PyPCAPFile engine # 'pypcapfile_packet2timestamp', 'pypcapfile_ipv4_header', # 'pypcapfile_packet2chain', 'pypcapfile_packet2dict', - # 'pypcapfile_ipv4_reassembly', 'pypcapfile_tcp_reassembly', 'pypcapfile_tcp_traceflow', + # 'pypcapfile_ipv4_reassembly', 'pypcapfile_tcp_reassembly', 'pypcapfile_tls_reassembly', + # 'pypcapfile_tcp_traceflow', ] diff --git a/pcapkit/toolkit/dpkt.py b/pcapkit/toolkit/dpkt.py index 438079163d..df8cb64a11 100644 --- a/pcapkit/toolkit/dpkt.py +++ b/pcapkit/toolkit/dpkt.py @@ -22,6 +22,7 @@ from pcapkit.foundation.traceflow.data import FrameRecord from pcapkit.foundation.traceflow.tcp.data import Packet as TF_TCP_Packet from pcapkit.protocols.misc.pcap.frame.data import FrameInfo as Data_FrameInfo +from pcapkit.toolkit.pcap import _tls_segment from pcapkit.utilities.exceptions import UnsupportedCall if TYPE_CHECKING: @@ -39,7 +40,7 @@ __all__ = [ 'RecordTimestamp', 'Timestamp', 'DecimalTimestamp', 'ipv6_hdr_len', 'attach_timestamp', 'packet2timestamp', 'attach_buffer', 'packet2bytes', 'packet2frame', 'packet2chain', 'packet2dict', - 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tcp_traceflow' + 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tls_reassembly', 'tcp_traceflow' ] #: Attribute a frame's capture timestamp is stashed under. @@ -839,6 +840,32 @@ def tcp_reassembly(packet: 'Packet', timestamp: 'float', *, return None +def tls_reassembly(packet: 'Packet', timestamp: 'float', *, count: 'int' = -1) -> 'TCP_Packet | None': + """Make data for TLS record reassembly. + + A packet can be reassembled if it can be for TCP reassembly (see + :func:`tcp_reassembly`) and the port its TCP segment's next layer is looked up + by binds TLS (see :func:`pcapkit.toolkit.pcap._tls_segment`), whether its + payload opens a record or continues one. + + Args: + packet: DPKT packet. + timestamp: Capture timestamp of the packet, as for :func:`tcp_reassembly`. + count: Packet index. If not provided, defaults to ``-1``. + + Returns: + Data for TCP reassembly (:term:`reasm.tcp.packet`) if the ``packet`` can be + reassembled; otherwise :data:`None`. + + See Also: + :class:`pcapkit.foundation.reassembly.tls.reassembly.TLS` + + .. versionadded:: 1.9.0 + + """ + return _tls_segment(tcp_reassembly(packet, timestamp, count=count)) + + def tcp_traceflow(packet: 'Packet', timestamp: 'float', *, data_link: 'Enum_LinkType', count: 'int' = -1) -> 'TF_TCP_Packet | None': """Trace packet flow for TCP. diff --git a/pcapkit/toolkit/pcap.py b/pcapkit/toolkit/pcap.py index fec1b85966..2ae11bac9f 100644 --- a/pcapkit/toolkit/pcap.py +++ b/pcapkit/toolkit/pcap.py @@ -11,7 +11,9 @@ :mod:`pcapkit.toolkit.pcapng` read the segment with :func:`~pcapkit.toolkit.pcap.tcp_segment`, the DTLS ones the record with :func:`~pcapkit.toolkit.pcap._dtls_fragments`, and the SCTP ones the packet with -:func:`~pcapkit.toolkit.pcap._sctp_fragments`. +:func:`~pcapkit.toolkit.pcap._sctp_fragments`. The TLS adapters of every engine +keep the TCP ones' records of a TLS stream with +:func:`~pcapkit.toolkit.pcap._tls_segment`. """ from typing import TYPE_CHECKING, NamedTuple, cast @@ -28,6 +30,7 @@ from pcapkit.protocols.application.dtls.data import DTLS as Data_DTLS from pcapkit.protocols.application.dtls.data import DTLSHandshake as Data_DTLSHandshake from pcapkit.protocols.application.dtls.protocol import DTLS +from pcapkit.protocols.application.tls.protocol import TLS from pcapkit.protocols.internet.ip.protocol import IP as Protocol_IP from pcapkit.protocols.internet.ipv4.protocol import IPv4 from pcapkit.protocols.internet.ipv6.protocol import IPv6 @@ -51,7 +54,7 @@ from pcapkit.protocols.misc.pcap import Frame __all__ = ['ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'dtls_reassembly', - 'sctp_reassembly', 'tcp_traceflow', 'tcp_segment', 'TCPSegment'] + 'sctp_reassembly', 'tls_reassembly', 'tcp_traceflow', 'tcp_segment', 'TCPSegment'] class TCPSegment(NamedTuple): @@ -567,6 +570,56 @@ def sctp_reassembly(frame: 'Frame') -> 'Optional[tuple[SCTP_Packet, ...]]': return _sctp_fragments(frame, num=frame.info.number, timestamp=float(frame.info.time_epoch)) +def _tls_segment(packet: 'Optional[TCP_Packet]') -> 'Optional[TCP_Packet]': + """Keep a segment's TCP reassembly record if its stream carries TLS. + + The TLS adapters of this module and of the other :mod:`pcapkit.toolkit` modules + keep their TCP adapter's record with this. + + Args: + packet: Data for TCP reassembly (:term:`reasm.tcp.packet`), or :data:`None`. + + Returns: + ``packet`` if the port a frame's TCP layer looks its next layer up by + binds TLS in :attr:`TCP.__proto__ + `; otherwise + :data:`None`. + + .. versionadded:: 1.9.0 + + """ + if packet is None: + return None + port = TCP._next_layer_port((packet.bufid[1], packet.bufid[3])) # pylint: disable=protected-access + if not issubclass(TCP._lookup_next_layer(TCP.__proto__, port), TLS): # pylint: disable=protected-access + return None + return packet + + +def tls_reassembly(frame: 'Frame') -> 'TCP_Packet | None': + """Make data for TLS record reassembly. + + A frame can be reassembled if it can be for TCP reassembly (see + :func:`tcp_reassembly`) and the port its TCP layer looks the next layer up by + binds TLS (see :func:`_tls_segment`), whether its payload opens a record or + continues one. + + Args: + frame: PCAP frame. + + Returns: + Data for TCP reassembly (:term:`reasm.tcp.packet`) if the ``frame`` can be + reassembled; otherwise :data:`None`. + + See Also: + :class:`pcapkit.foundation.reassembly.tls.reassembly.TLS` + + .. versionadded:: 1.9.0 + + """ + return _tls_segment(tcp_reassembly(frame)) + + def tcp_traceflow(frame: 'Frame', *, data_link: 'LinkType') -> 'TF_TCP_Packet | None': """Trace packet flow for TCP. diff --git a/pcapkit/toolkit/pcapng.py b/pcapkit/toolkit/pcapng.py index 8125cd0317..3cbc03440c 100644 --- a/pcapkit/toolkit/pcapng.py +++ b/pcapkit/toolkit/pcapng.py @@ -21,7 +21,8 @@ from pcapkit.protocols.internet.ipv6.protocol import IPv6 from pcapkit.protocols.misc.pcap.frame.data import Frame as Data_Frame from pcapkit.protocols.misc.pcap.frame.data import FrameInfo as Data_FrameInfo -from pcapkit.toolkit.pcap import _dtls_fragments, _fragment, _sctp_fragments, tcp_segment +from pcapkit.toolkit.pcap import (_dtls_fragments, _fragment, _sctp_fragments, _tls_segment, + tcp_segment) if TYPE_CHECKING: from ipaddress import IPv4Address, IPv6Address @@ -35,7 +36,7 @@ from pcapkit.protocols.misc.pcapng.protocol import PCAPNG, Packet __all__ = ['ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'dtls_reassembly', - 'sctp_reassembly', 'tcp_traceflow', 'block2frame'] + 'sctp_reassembly', 'tls_reassembly', 'tcp_traceflow', 'block2frame'] def ipv4_reassembly(frame: 'PCAPNG') -> 'IP_Packet[IPv4Address] | None': @@ -240,6 +241,30 @@ def sctp_reassembly(frame: 'PCAPNG') -> 'Optional[tuple[SCTP_Packet, ...]]': return _sctp_fragments(frame, num=frame_info.number, timestamp=float(frame_info.timestamp_epoch)) +def tls_reassembly(frame: 'PCAPNG') -> 'TCP_Packet | None': + """Make data for TLS record reassembly. + + A frame can be reassembled if it can be for TCP reassembly (see + :func:`tcp_reassembly`) and the port its TCP layer looks the next layer up by + binds TLS (see :func:`pcapkit.toolkit.pcap._tls_segment`), whether its payload + opens a record or continues one. + + Args: + frame: PCAP-NG frame. + + Returns: + Data for TCP reassembly (:term:`reasm.tcp.packet`) if the ``frame`` can be + reassembled; otherwise :data:`None`. + + See Also: + :class:`pcapkit.foundation.reassembly.tls.reassembly.TLS` + + .. versionadded:: 1.9.0 + + """ + return _tls_segment(tcp_reassembly(frame)) + + def tcp_traceflow(frame: 'PCAPNG', *, nanosecond: 'bool' = False) -> 'TF_TCP_Packet | None': """Trace packet flow for TCP. diff --git a/pcapkit/toolkit/pypcapfile.py b/pcapkit/toolkit/pypcapfile.py index 37689b077f..89e27dc173 100644 --- a/pcapkit/toolkit/pypcapfile.py +++ b/pcapkit/toolkit/pypcapfile.py @@ -57,6 +57,7 @@ from pcapkit.foundation.traceflow.tcp.data import Packet as TF_TCP_Packet from pcapkit.protocols.internet.ipv4.protocol import IPv4 as Protocol_IPv4 from pcapkit.protocols.transport.tcp.protocol import TCP as Protocol_TCP +from pcapkit.toolkit.pcap import _tls_segment from pcapkit.utilities import config from pcapkit.utilities.contextvars import beholding from pcapkit.utilities.exceptions import ProtocolError, UnsupportedCall, stacklevel @@ -74,7 +75,7 @@ __all__ = [ 'packet2timestamp', 'ipv4_header', 'packet2chain', 'packet2dict', - 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tcp_traceflow', + 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tls_reassembly', 'tcp_traceflow', ] #: Message prefix shared by every message below, read off @@ -850,6 +851,31 @@ def tcp_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'TCP_Packet | None ) +def tls_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'TCP_Packet | None': + """Make data for TLS record reassembly. + + A packet can be reassembled if it can be for TCP reassembly (see + :func:`tcp_reassembly`) and the port its TCP segment's next layer is looked up + by binds TLS (see :func:`pcapkit.toolkit.pcap._tls_segment`), whether its + payload opens a record or continues one. + + Args: + packet: PyPCAPFile packet. + count: Packet index. If not provided, defaults to ``-1``. + + Returns: + Data for TCP reassembly (:term:`reasm.tcp.packet`) if the ``packet`` can be + reassembled; otherwise :data:`None`. + + See Also: + :class:`pcapkit.foundation.reassembly.tls.reassembly.TLS` + + .. versionadded:: 1.9.0 + + """ + return _tls_segment(tcp_reassembly(packet, count=count)) + + def tcp_traceflow(packet: 'Packet', *, data_link: 'Enum_LinkType', count: 'int' = -1) -> 'TF_TCP_Packet | None': """Trace packet flow for TCP. diff --git a/pcapkit/toolkit/scapy.py b/pcapkit/toolkit/scapy.py index d2919f083e..83b2de8b7d 100644 --- a/pcapkit/toolkit/scapy.py +++ b/pcapkit/toolkit/scapy.py @@ -41,6 +41,7 @@ from pcapkit.foundation.traceflow.data import FrameRecord from pcapkit.foundation.traceflow.tcp.data import Packet as TF_TCP_Packet from pcapkit.protocols.misc.pcap.frame.data import FrameInfo as Data_FrameInfo +from pcapkit.toolkit.pcap import _tls_segment from pcapkit.toolkit.pypcapfile import (IP_TUNNELS, IPV4_EXTENSION_HEADERS, _default_accepts, _walk_extension_headers) from pcapkit.utilities.compat import ModuleNotFoundError # pylint: disable=redefined-builtin @@ -71,7 +72,7 @@ __all__ = [ 'attach_linktype', 'attach_resolution', 'packet2chain', 'packet2dict', 'packet2frame', - 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tcp_traceflow' + 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tls_reassembly', 'tcp_traceflow' ] @@ -700,6 +701,31 @@ def tcp_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'TCP_Packet | None return None +def tls_reassembly(packet: 'Packet', *, count: 'int' = -1) -> 'TCP_Packet | None': + """Make data for TLS record reassembly. + + A packet can be reassembled if it can be for TCP reassembly (see + :func:`tcp_reassembly`) and the port its TCP segment's next layer is looked up + by binds TLS (see :func:`pcapkit.toolkit.pcap._tls_segment`), whether its + payload opens a record or continues one. + + Args: + packet: Scapy packet. + count: Packet index. If not provided, defaults to ``-1``. + + Returns: + Data for TCP reassembly (:term:`reasm.tcp.packet`) if the ``packet`` can be + reassembled; otherwise :data:`None`. + + See Also: + :class:`pcapkit.foundation.reassembly.tls.reassembly.TLS` + + .. versionadded:: 1.9.0 + + """ + return _tls_segment(tcp_reassembly(packet, count=count)) + + def tcp_traceflow(packet: 'Packet', *, count: 'int' = -1) -> 'TF_TCP_Packet | None': """Trace packet flow for TCP. diff --git a/pcapkit/utilities/seqnum.py b/pcapkit/utilities/seqnum.py new file mode 100644 index 0000000000..1e846ba88c --- /dev/null +++ b/pcapkit/utilities/seqnum.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +"""Sequence Number Arithmetic +================================ + +.. module:: pcapkit.utilities.seqnum + +:mod:`pcapkit.utilities.seqnum` places a 32-bit sequence number on one unbounded +line, as :rfc:`9293#section-3.4` compares TCP sequence numbers, so a stream crossing +``2 ** 32`` continues past it rather than back at zero. + +.. versionadded:: 1.9.0 + +""" + +__all__ = ['unwrap'] + +#: Half the 32-bit sequence space, the farthest two compared numbers may lie apart. +_HALF = 1 << 31 +#: The 32-bit sequence space. +_SPACE = 1 << 32 + + +def unwrap(seq: 'int', ref: 'int') -> 'int': + """Place a 32-bit sequence number on the unwrapped line near ``ref``. + + Arguments: + seq: sequence number as carried on the wire, i.e. modulo ``2 ** 32`` + ref: unwrapped sequence number ``seq`` is expected to be near + + Returns: + The integer congruent to ``seq`` modulo ``2 ** 32`` that lies within + ``2 ** 31`` of ``ref``, which is how :rfc:`9293#section-3.4` compares + sequence numbers. + + """ + return ref + (seq - ref + _HALF) % _SPACE - _HALF diff --git a/tests/corekit/test_deferred_packet_1516_unit.py b/tests/corekit/test_deferred_packet_1516_unit.py index f4f4e7edf6..6db4835c20 100644 --- a/tests/corekit/test_deferred_packet_1516_unit.py +++ b/tests/corekit/test_deferred_packet_1516_unit.py @@ -236,6 +236,7 @@ def test_each_model_resolves_its_own_placeholder_and_not_the_other(self) -> 'Non from pcapkit.foundation.reassembly.ip.data import Datagram as IP_Datagram from pcapkit.foundation.reassembly.sctp.data import Datagram as SCTP_Datagram from pcapkit.foundation.reassembly.tcp.data import Datagram as TCP_Datagram + from pcapkit.foundation.reassembly.tls.data import Datagram as TLS_Datagram from pcapkit.foundation.traceflow.data import Deferred as TraceFlowDeferred from pcapkit.foundation.traceflow.tcp.data import Index @@ -261,6 +262,10 @@ def user_message(packet: 'object') -> 'DeferredPacket': unordered=False, ssn=0, mid=None, tsn=(1,), ppid=None, payload=b'payload', packet=packet) + def record(packet: 'object') -> 'DeferredPacket': + return TLS_Datagram(completed=Completion.COMPLETE, id=None, index=(1,), content_type=None, + version=0x0303, length=7, fragment=b'payload', packet=packet) + cases = ( ('ip', lambda packet: datagram(IP_Datagram, packet), reassembly, traceflow, ('parsed', 'proto', b'payload')), @@ -268,6 +273,7 @@ def user_message(packet: 'object') -> 'DeferredPacket': ('parsed', 'proto', b'payload')), ('dtls', message, reassembly, traceflow, ('parsed', 'proto', b'payload')), ('sctp', user_message, reassembly, traceflow, ('parsed', 'proto', b'payload')), + ('tls', record, reassembly, traceflow, ('parsed', 'proto', b'payload')), ('trace', index, traceflow, reassembly, ('reassembled',)), ) for (label, build, own, other, expected) in cases: diff --git a/tests/dumpkit/test_renamed_field_dump_2733_unit.py b/tests/dumpkit/test_renamed_field_dump_2733_unit.py index 46ddc82268..b8d35abbbd 100644 --- a/tests/dumpkit/test_renamed_field_dump_2733_unit.py +++ b/tests/dumpkit/test_renamed_field_dump_2733_unit.py @@ -272,13 +272,14 @@ def test_a_reassembled_tcp_datagram_dumps_its_packet(self) -> None: self.assertEqual(block['packet'], self.block(writer, {'packet': packet})['packet']) def test_the_dump_resolves_a_deferred_packet_once(self) -> None: - """Every model with a deferred ``packet``, IP, TCP, DTLS and SCTP reassembly's and a traced flow's.""" + """Every model with a deferred ``packet``, IP, TCP, DTLS, SCTP and TLS reassembly's and a traced flow's.""" from pcapkit.foundation.reassembly.data import Completion from pcapkit.foundation.reassembly.data import Deferred as ReassemblyDeferred from pcapkit.foundation.reassembly.dtls.data import Datagram as DTLS_Datagram from pcapkit.foundation.reassembly.ip.data import Datagram as IP_Datagram from pcapkit.foundation.reassembly.sctp.data import Datagram as SCTP_Datagram from pcapkit.foundation.reassembly.tcp.data import Datagram as TCP_Datagram + from pcapkit.foundation.reassembly.tls.data import Datagram as TLS_Datagram from pcapkit.foundation.traceflow.data import Deferred as TraceFlowDeferred from pcapkit.foundation.traceflow.tcp.data import Index @@ -296,6 +297,9 @@ def datagram(cls: 'type', counting: 'Counting') -> 'object': completed=Completion.COMPLETE, id=None, index=(1,), chunk=None, stream_id=0, unordered=False, ssn=0, mid=None, tsn=(1,), ppid=None, payload=b'payload', packet=ReassemblyDeferred(counting, 'proto', b'payload')), + 'tls': lambda counting: TLS_Datagram( + completed=Completion.COMPLETE, id=None, index=(1,), content_type=None, version=0x0303, + length=7, fragment=b'payload', packet=ReassemblyDeferred(counting, 'proto', b'payload')), 'trace': lambda counting: Index(fpout=None, index=(1,), label='label', forward=(1,), reverse=(), packet=TraceFlowDeferred(counting)), # type: ignore[arg-type] } diff --git a/tests/foundation/reassembly/test_deferred_proto_type_2417_unit.py b/tests/foundation/reassembly/test_deferred_proto_type_2417_unit.py index ecd79a27d9..f6cfa133d2 100644 --- a/tests/foundation/reassembly/test_deferred_proto_type_2417_unit.py +++ b/tests/foundation/reassembly/test_deferred_proto_type_2417_unit.py @@ -213,13 +213,14 @@ def _declared_proto_types(cls): from pcapkit.const.reg.apptype import TCP as AppType_TCP from pcapkit.const.reg.transtype import TransType from pcapkit.const.sctp.payload_protocol_identifier import PayloadProtocolIdentifier + from pcapkit.const.tls.content_type import ContentType from pcapkit.const.tls.handshake_type import HandshakeType return tuple( eval(getattr(constraint, '__forward_arg__', constraint), # pylint: disable=eval-used {'TransType': TransType, 'AppType_TCP': AppType_TCP, 'HandshakeType': HandshakeType, 'Optional': typing.Optional, - 'PayloadProtocolIdentifier': PayloadProtocolIdentifier}) + 'PayloadProtocolIdentifier': PayloadProtocolIdentifier, 'ContentType': ContentType}) for constraint in cls._proto_type_variable().__constraints__ ) @@ -275,6 +276,27 @@ def test_sctp_passes_the_payload_protocol_identifier(self) -> None: self.assertIs(self._sctp_proto(), PayloadProtocolIdentifier(46)) + def _tls_proto(self): + """The ``proto`` TLS reassembly hands :class:`Deferred` for a complete + record (#2938): its ``(type, legacy_record_version)``.""" + from pcapkit.foundation.reassembly.tcp.data import Packet + from pcapkit.foundation.reassembly.tls.reassembly import TLS + + reasm = TLS() + record = b'\x17\x03\x03\x00\x05hello' + reasm(Packet(TCP_BUFID, 1, 500, 1, False, False, False, len(record), 1, len(record), + b'', bytearray(record), 1000.0)) + datagram, = reasm.datagram + return held(datagram).proto + + def test_tls_passes_the_record_header(self) -> None: + """The fragment decodes by its content type; the version brands the record.""" + from pcapkit.const.tls.content_type import ContentType + + content_type, version = self._tls_proto() + self.assertIs(content_type, ContentType.application_data) + self.assertEqual(version, 0x0303) + def test_dtls_passes_the_handshake_header(self) -> None: """The body decodes by ``msg_type``; ``length`` and ``message_seq`` frame it.""" from pcapkit.const.tls.handshake_type import HandshakeType @@ -331,7 +353,7 @@ def test_declared_type_admits_what_each_reassembler_passes(self) -> None: declared = self._declared_proto_types() matched = {} values = (('ip', self._ip_proto()), ('tcp', self._tcp_proto()), ('dtls', self._dtls_proto()), - ('sctp', self._sctp_proto())) + ('sctp', self._sctp_proto()), ('tls', self._tls_proto())) for name, value in values: with self.subTest(reassembler=name): admitting = [each for each in declared if admits(each, value)] diff --git a/tests/foundation/reassembly/test_reassembly_callbacks_2867_2881_unit.py b/tests/foundation/reassembly/test_reassembly_callbacks_2867_2881_unit.py index 7a0c53887c..7e59f3787f 100644 --- a/tests/foundation/reassembly/test_reassembly_callbacks_2867_2881_unit.py +++ b/tests/foundation/reassembly/test_reassembly_callbacks_2867_2881_unit.py @@ -135,6 +135,14 @@ def build_sctp(self, num: int, ident: int, tail: bool, ts: float) -> 'list[Any]' chunk=Chunk.Payload_Data, tsn=tsn, stream_id=0, unordered=False, beginning=not tail, ending=tail, ssn=0, mid=None, fsn=None, ppid=PayloadProtocolIdentifier(0), payload=payload, timestamp=ts)] + def build_tls(self, num: int, ident: int, tail: bool, ts: float) -> 'list[Any]': + from pcapkit.foundation.reassembly.tcp.data import Packet + + bufid = (ip_address('192.0.2.1'), ident, ip_address('198.51.100.2'), 443) + record = b'\x17\x03\x03\x00\x08' + bytes([ident]) * 8 # an 8-octet application_data record + dsn, payload = (1000 * ident + 9, record[9:]) if tail else (1000 * ident, record[:9]) + return [Packet(bufid, dsn, 500, num, False, False, False, len(payload), dsn, + dsn + len(payload) - 1, b'tcp-header', bytearray(payload), ts)] # harness diff --git a/tests/foundation/reassembly/test_reassembly_field_order_2847_unit.py b/tests/foundation/reassembly/test_reassembly_field_order_2847_unit.py index bd7316ddec..5cc720965e 100644 --- a/tests/foundation/reassembly/test_reassembly_field_order_2847_unit.py +++ b/tests/foundation/reassembly/test_reassembly_field_order_2847_unit.py @@ -29,7 +29,7 @@ BOOKKEEPING = ('__map__', '__map_reverse__', '__multi__', '__keys__') #: The built-in fields of the record, which come first. -BUILTINS = ('ipv4', 'ipv6', 'tcp', 'dtls', 'sctp') +BUILTINS = ('ipv4', 'ipv6', 'tcp', 'dtls', 'sctp', 'tls') def scramble(info): # type: ignore[no-untyped-def] @@ -123,7 +123,7 @@ class DataOrderTests(_OrderCase): def pairs(self, **extra): # type: ignore[no-untyped-def] """The record's pairs for ``ReassemblyData(tcp=('t',), **extra)``.""" return [('ipv4', None), ('ipv6', None), ('tcp', ('t',)), ('dtls', None), ('sctp', None), - *extra.items()] + ('tls', None), *extra.items()] def test_built_ins_then_the_rest_as_given(self) -> None: for extra in ({}, {'late': (), 'early': ('e',)}, {'early': ('e',), 'late': ()}): @@ -131,8 +131,10 @@ def test_built_ins_then_the_rest_as_given(self) -> None: self.assertOrder(scramble(self.Data(tcp=('t',), **extra)), self.pairs(**extra)) def test_built_ins_given_out_of_order(self) -> None: - data = scramble(self.Data(dummy=('d',), sctp=('s',), dtls=(), tcp=('t',), ipv6=(), ipv4=('4',))) + data = scramble(self.Data(dummy=('d',), tls=('r',), sctp=('s',), dtls=(), tcp=('t',), ipv6=(), + ipv4=('4',))) self.assertOrder(data, [('ipv4', ('4',)), ('ipv6', ()), ('tcp', ('t',)), ('dtls', ()), ('sctp', ('s',)), + ('tls', ('r',)), ('dummy', ('d',))]) def test_from_dict(self) -> None: diff --git a/tests/foundation/reassembly/test_registered_reassembler_2814_unit.py b/tests/foundation/reassembly/test_registered_reassembler_2814_unit.py index 4e46eed031..c05a94b0c7 100644 --- a/tests/foundation/reassembly/test_registered_reassembler_2814_unit.py +++ b/tests/foundation/reassembly/test_registered_reassembler_2814_unit.py @@ -375,15 +375,15 @@ def test_iteration_follows_the_order_given(self) -> None: self.assertEqual([name for (name, _) in manager.items()], [NAME, 'tcp']) self.assertEqual(list(ReassemblyManager(manager)), [NAME, 'tcp']) - self.assertEqual(list(ReassemblyData(late=(), early=()))[5:], ['late', 'early']) + self.assertEqual(list(ReassemblyData(late=(), early=()))[6:], ['late', 'early']) self.assertEqual(list(ReassemblyData(early=(), late=())), - ['ipv4', 'ipv6', 'tcp', 'dtls', 'sctp', 'early', 'late']) + ['ipv4', 'ipv6', 'tcp', 'dtls', 'sctp', 'tls', 'early', 'late']) def test_data_keeps_the_built_in_fields(self) -> None: from pcapkit.foundation.reassembly.data import ReassemblyData data = ReassemblyData(tcp=(), dummy=('datagram',)) - self.assertEqual(list(data), ['ipv4', 'ipv6', 'tcp', 'dtls', 'sctp', NAME]) + self.assertEqual(list(data), ['ipv4', 'ipv6', 'tcp', 'dtls', 'sctp', 'tls', NAME]) self.assertIsNone(data.ipv4) self.assertEqual(data.dummy, ('datagram',)) diff --git a/tests/foundation/reassembly/test_sctp_reassembly_2935_unit.py b/tests/foundation/reassembly/test_sctp_reassembly_2935_unit.py index a95832502b..d0a73fc556 100644 --- a/tests/foundation/reassembly/test_sctp_reassembly_2935_unit.py +++ b/tests/foundation/reassembly/test_sctp_reassembly_2935_unit.py @@ -551,7 +551,7 @@ def test_the_record_holds_sctp_as_a_builtin(self) -> None: from pcapkit.protocols.transport.sctp.protocol import SCTP as SCTP_Protocol self.assertIsNone(ReassemblyData().sctp) - self.assertEqual(list(ReassemblyData()), ['ipv4', 'ipv6', 'tcp', 'dtls', 'sctp']) + self.assertEqual(list(ReassemblyData()), ['ipv4', 'ipv6', 'tcp', 'dtls', 'sctp', 'tls']) self.assertIsInstance(Extractor.make_reassembly('sctp'), SCTP) for protocol in ('sctp', 'SCTP', SCTP_Protocol): with self.subTest(protocol=protocol): diff --git a/tests/foundation/reassembly/test_tls_record_reassembly_2938_unit.py b/tests/foundation/reassembly/test_tls_record_reassembly_2938_unit.py new file mode 100644 index 0000000000..850c0c1e34 --- /dev/null +++ b/tests/foundation/reassembly/test_tls_record_reassembly_2938_unit.py @@ -0,0 +1,534 @@ +# -*- coding: utf-8 -*- +"""TLS records split across TCP segments are reassembled (#2938). + +:meth:`TLS.record_header ` +frames a stream, :class:`~pcapkit.foundation.reassembly.tls.reassembly.TLS` cuts each +direction of a TCP connection into records, every engine with a TCP adapter feeds it the +segments of a stream on a port TCP binds to TLS through its ``tls_reassembly`` adapter, +and :func:`~pcapkit.foundation.analysis.tls.tls_record` decodes a record with +:meth:`TLS.analyze_record `, +the #2810 extensions included. + +Every case builds its segments and captures in memory and reads no sample capture. +Classes are imported inside each test, after :func:`~tests._support.reimport_once_per_class`. + +""" + +from __future__ import annotations + +import importlib.util +import ipaddress +import os +import pickle # nosec: B403 -- round-trips objects built here +import struct +import tempfile +import unittest +import warnings +from typing import TYPE_CHECKING +from unittest import mock + +from tests._support import close_extractor, reimport_once_per_class +from tests.foundation.reassembly.test_dtls_handshake_reassembly_2440_unit import (_extract, _pcap, + _pcapng) + +if TYPE_CHECKING: + from typing import Any + +#: Test tier (#1958): pure-Python stream bookkeeping, the same on every interpreter. +__tier__ = 'LATEST' + +#: The client and server endpoints, the server on the HTTPS port TCP binds TLS to. +CLIENT = (ipaddress.ip_address('192.0.2.1'), 50000) +SERVER = (ipaddress.ip_address('198.51.100.2'), 443) +#: The buffer ID of the client's direction. +BUFID = (CLIENT[0], CLIENT[1], SERVER[0], SERVER[1]) + + +def _record(content_type: int, fragment: bytes, version: int = 0x0303) -> bytes: + """A TLS record [RFC 9846, section 5.1].""" + return bytes([content_type]) + version.to_bytes(2, 'big') + len(fragment).to_bytes(2, 'big') + fragment + + +def _extension(code: int, body: bytes) -> bytes: + return code.to_bytes(2, 'big') + len(body).to_bytes(2, 'big') + body + + +def _client_hello(host: bytes = b'example.com', padding: int = 300) -> bytes: + """A ``ClientHello`` record carrying ``server_name``, ``supported_versions`` and ``padding``.""" + names = b'\x00' + len(host).to_bytes(2, 'big') + host + extensions = (_extension(0, len(names).to_bytes(2, 'big') + names) + + _extension(43, b'\x04\x03\x04\x03\x03') + _extension(21, bytes(padding))) + body = (b'\x03\x03' + bytes(range(32)) + b'\x00' + b'\x00\x04\x13\x01\x13\x02' + b'\x01\x00' + + len(extensions).to_bytes(2, 'big') + extensions) + return _record(22, b'\x01' + len(body).to_bytes(3, 'big') + body, version=0x0301) + + +#: A ``ClientHello`` too long for one 100-octet segment, then two short records. +HELLO = _client_hello() +ALERT = _record(21, b'\x01\x00') +DATA = _record(23, b'\xa5' * 40) + + +def _segment(num: int, seq: int, payload: bytes = b'', *, syn: bool = False, fin: bool = False, + rst: bool = False, bufid: 'tuple[Any, ...]' = BUFID, ts: float = 1000.0) -> 'Any': + """TCP reassembly's record of a segment, as the adapters build one.""" + from pcapkit.foundation.reassembly.tcp.data import Packet + + return Packet(bufid=bufid, dsn=seq, ack=1, num=num, syn=syn, fin=fin, rst=rst, len=len(payload), + first=seq, last=seq + len(payload) - 1, header=b'', payload=bytearray(payload), + timestamp=ts + num) + + +def _split(stream: bytes, *cuts: int) -> 'list[tuple[int, bytes]]': + """``stream`` cut at ``cuts``, as ``(offset, octets)`` pairs.""" + bounds = (0, *cuts, len(stream)) + return [(lo, stream[lo:hi]) for (lo, hi) in zip(bounds, bounds[1:])] + + +def _tcp(src: 'tuple[Any, int]', dst: 'tuple[Any, int]', seq: int, flags: int, payload: bytes = b'') -> bytes: + return struct.pack('!HHIIBBHHH', src[1], dst[1], seq, 1, 5 << 4, flags, 65535, 0, 0) + payload + + +def _frame(segment: bytes, src: 'tuple[Any, int]' = CLIENT, dst: 'tuple[Any, int]' = SERVER) -> bytes: + """An Ethernet frame of IPv4 carrying the TCP ``segment``.""" + return (b'\xbb' * 6 + b'\xaa' * 6 + b'\x08\x00' + + struct.pack('!BBHHHBBH4s4s', 0x45, 0, 20 + len(segment), 1, 0x4000, 64, 6, 0, + src[0].packed, dst[0].packed) + + segment) + + +def _hello_frames(isn: int, src: 'tuple[Any, int]' = CLIENT, dst: 'tuple[Any, int]' = SERVER) -> 'list[bytes]': + """A SYN, then :data:`HELLO` in three segments, then a FIN.""" + frames = [_frame(_tcp(src, dst, isn, 0x02), src, dst)] + for (offset, octets) in _split(HELLO, 100, 250): + frames.append(_frame(_tcp(src, dst, (isn + 1 + offset) % 2 ** 32, 0x10, octets), src, dst)) + frames.append(_frame(_tcp(src, dst, (isn + 1 + len(HELLO)) % 2 ** 32, 0x11), src, dst)) + return frames + + +class _Case(unittest.TestCase): + + def setUp(self) -> None: + reimport_once_per_class(self) + + def assertHello(self, packet: 'Any') -> None: # pylint: disable=invalid-name + """``packet`` is :data:`HELLO`, decoded down to its ``server_name``.""" + from pcapkit.protocols.application.tls.protocol import TLS + + self.assertIsInstance(packet, TLS) + self.assertEqual(packet.alias, 'TLS 1.3') + hello, = packet.info.content + names = hello.body.extensions[0].data.server_name_list + self.assertEqual([name.name for name in names], [b'example.com']) + self.assertEqual(packet.data, HELLO) + + +class RecordHeaderTests(_Case): + """:meth:`TLS.record_header` reads the header a stream is delimited by.""" + + def test_a_header_is_read(self) -> None: + from pcapkit.const.tls.content_type import ContentType + from pcapkit.protocols.application.tls.protocol import TLS + + self.assertEqual(TLS.record_header(HELLO), (ContentType.handshake, 0x0301, 5, len(HELLO) - 5)) + self.assertEqual(TLS.record_header(ALERT[:5]), (ContentType.alert, 0x0303, 5, 2)) + + def test_too_few_octets_are_no_header_yet(self) -> None: + from pcapkit.protocols.application.tls.protocol import TLS + + for size in range(5): + with self.subTest(size=size): + self.assertIsNone(TLS.record_header(HELLO[:size])) + + def test_octets_opening_no_record_are_refused(self) -> None: + from pcapkit.protocols.application.tls.protocol import TLS + from pcapkit.utilities.exceptions import ProtocolError + + for name, octets in (('content type 0', b'\x00\x03\x03\x00\x00'), + ('tls12_cid', b'\x19\x03\x03\x00\x00'), + ('DTLS version', b'\x17\xfe\xfd\x00\x00'), + ('SSLv2 hello', b'\x80\x2e\x01\x00\x02'), + ('length past 2 ** 14 + 2048', b'\x17\x03\x03' + (2 ** 14 + 2049).to_bytes(2, 'big')), + ('length 0xffff', b'\x17\x03\x03\xff\xff')): + with self.subTest(case=name), self.assertRaises(ProtocolError): + TLS.record_header(octets) + + def test_the_longest_record_any_version_allows_is_read(self) -> None: + # TLSCiphertext of SSLv3 to TLS 1.2 (RFC 6101 section 5.2.3, RFC 5246 section 6.2.3) + from pcapkit.const.tls.content_type import ContentType + from pcapkit.protocols.application.tls.protocol import TLS + + octets = b'\x17\x03\x03' + (2 ** 14 + 2048).to_bytes(2, 'big') + self.assertEqual(TLS.record_header(octets), (ContentType.application_data, 0x0303, 5, 2 ** 14 + 2048)) + + +class AnalyzeRecordTests(_Case): + """:meth:`TLS.analyze_record` parses a record as a segment's first record is.""" + + def test_a_record_decodes_and_rebuilds_byte_exact(self) -> None: + from pcapkit.const.tls.content_type import ContentType + from pcapkit.protocols.application.tls.protocol import TLS + + packet = TLS.analyze_record((ContentType.handshake, 0x0301), HELLO[5:]) + self.assertHello(packet) + self.assertEqual(TLS.from_data(packet.info).data, HELLO) + + def test_a_record_that_fails_to_decode_is_raw(self) -> None: + from pcapkit.const.tls.content_type import ContentType + from pcapkit.protocols.application.tls.protocol import TLS + from pcapkit.protocols.misc.raw.protocol import Raw + + packet = TLS.analyze_record((ContentType.handshake, 0x0303), b'\x01\x00\x00\x02\x03\x03') + self.assertIsInstance(packet, Raw) + self.assertEqual(packet.info.protocol, 443) + self.assertIn('client_hello', packet.info.error) + self.assertEqual(packet.data, b'\x16\x03\x03\x00\x06\x01\x00\x00\x02\x03\x03') + + +class ReassemblyTests(_Case): + """The reassembler, fed TCP reassembly's records of each segment.""" + + def _run(self, segments: 'list[Any]', **kwargs: 'Any') -> 'Any': + from pcapkit.foundation.reassembly.tls.reassembly import TLS + + reasm = TLS(**kwargs) + for segment in segments: + reasm(segment) + return reasm + + def test_records_split_and_coalesced_are_each_reported(self) -> None: + from pcapkit.const.tls.content_type import ContentType + from pcapkit.foundation.reassembly.data import Completion + + stream = HELLO + ALERT + DATA + segments = [_segment(1, 999, syn=True)] + segments += [_segment(num, 1000 + offset, octets) + for num, (offset, octets) in enumerate(_split(stream, 100, 250, len(HELLO) + 3), 2)] + segments.append(_segment(6, 1000 + len(stream), fin=True)) + reasm = self._run(segments) + + hello, alert, data = reasm.datagram + self.assertEqual([datagram.completed for datagram in reasm.datagram], [Completion.COMPLETE] * 3) + self.assertEqual([datagram.index for datagram in reasm.datagram], [(2, 3, 4), (4, 5), (5,)]) + self.assertEqual([datagram.id.seq for datagram in reasm.datagram], + [1000, 1000 + len(HELLO), 1000 + len(HELLO) + len(ALERT)]) + self.assertEqual((hello.id.src, hello.id.dst), (CLIENT, SERVER)) + self.assertEqual([(datagram.content_type, datagram.version, datagram.length) for datagram in reasm.datagram], + [(ContentType.handshake, 0x0301, len(HELLO) - 5), (ContentType.alert, 0x0303, 2), + (ContentType.application_data, 0x0303, 40)]) + self.assertEqual([datagram.fragment for datagram in reasm.datagram], [HELLO[5:], ALERT[5:], DATA[5:]]) + self.assertHello(hello.packet) + self.assertEqual(alert.packet.info.content.description, 0) + self.assertEqual(data.packet.data, DATA) + + def test_segments_out_of_order_wait_for_those_before_them(self) -> None: + pieces = _split(HELLO, 100, 250) + segments = [_segment(1, 999, syn=True)] + [_segment(num, 1000 + pieces[index][0], pieces[index][1]) + for num, index in ((2, 2), (3, 0), (4, 1))] + reasm = self._run(segments) + datagram, = reasm.datagram + self.assertEqual(datagram.index, (2, 3, 4)) + self.assertHello(datagram.packet) + + def test_octets_received_twice_keep_the_first(self) -> None: + overlap = bytearray(HELLO[50:150]) + overlap[0:50] = b'\xff' * 50 # disagrees with the octets 50 to 100 already held + segments = [_segment(1, 999, syn=True), _segment(2, 1000, HELLO[:100]), + _segment(3, 1050, bytes(overlap)), _segment(4, 1000, HELLO[:100]), + _segment(5, 1150, HELLO[150:])] + datagram, = self._run(segments).datagram + self.assertEqual(datagram.fragment, HELLO[5:]) + self.assertEqual(datagram.index, (2, 3, 5)) + self.assertHello(datagram.packet) + + def test_a_segment_reaching_into_a_held_run_adds_only_the_octets_before_it(self) -> None: + overlap = HELLO[:100] + b'\xff' * 50 # its last 50 octets disagree with the run held + segments = [_segment(1, 999, syn=True), _segment(2, 1100, HELLO[100:]), _segment(3, 1000, overlap)] + datagram, = self._run(segments).datagram + self.assertEqual(datagram.index, (2, 3)) + self.assertHello(datagram.packet) + + def test_a_stream_crossing_two_to_the_thirty_second_continues_past_it(self) -> None: + isn = 2 ** 32 - 120 + segments = [_segment(1, isn, syn=True)] + segments += [_segment(num, (isn + 1 + offset) % 2 ** 32, octets) + for num, (offset, octets) in enumerate(_split(HELLO + DATA, 100, 250), 2)] + hello, data = self._run(segments).datagram + self.assertEqual((hello.id.seq, data.id.seq), (isn + 1, (isn + 1 + len(HELLO)) % 2 ** 32)) + self.assertHello(hello.packet) + self.assertEqual(data.fragment, DATA[5:]) + + def test_without_the_syn_the_stream_is_followed_from_a_record_header(self) -> None: + # the tail of a record before the capture began, then a record opening a segment + segments = [_segment(1, 5000, b'\x99' * 30), _segment(2, 5030, HELLO[:200]), + _segment(3, 5230, HELLO[200:])] + datagram, = self._run(segments).datagram + self.assertEqual((datagram.index, datagram.id.seq), ((2, 3), 5030)) + self.assertHello(datagram.packet) + + def test_a_header_declaring_an_overlong_record_does_not_open_the_stream(self) -> None: + # a record's tail from before the capture, opening as a header declaring 0xffff + # octets would; the real records behind it must not be swallowed into it + bogus = b'\x17\x03\x03\xff\xff' + b'\x99' * 100 + segments = [_segment(1, 5000, bogus), _segment(2, 5105, DATA), _segment(3, 5105 + len(DATA), ALERT)] + reasm = self._run(segments) + self.assertEqual([(datagram.completed, datagram.index, datagram.id.seq) for datagram in reasm.datagram], + [('complete', (2,), 5105), ('complete', (3,), 5105 + len(DATA))]) + self.assertEqual(reasm.datagram[0].fragment, DATA[5:]) + + def test_octets_opening_no_record_drop_the_stream_until_one_does(self) -> None: + segments = [_segment(1, 999, syn=True), _segment(2, 1000, ALERT + b'\x80\x2e\x01\x00\x02'), + _segment(3, 1012, b'\x00' * 20), _segment(4, 1032, DATA)] + reasm = self._run(segments) + self.assertEqual([datagram.fragment for datagram in reasm.datagram], [ALERT[5:], DATA[5:]]) + self.assertEqual([datagram.index for datagram in reasm.datagram], [(2,), (4,)]) + + def test_a_hole_leaves_its_record_incomplete_and_the_next_whole(self) -> None: + from pcapkit.foundation.reassembly.data import Completion + + stream = HELLO + DATA + segments = [_segment(1, 999, syn=True), _segment(2, 1000, stream[:100]), + _segment(3, 1250, stream[250:])] # octets 100 to 250 are never captured + for strict, fragment in ((True, (HELLO[5:100], HELLO[250:])), + (False, HELLO[5:100] + bytes(150) + HELLO[250:])): + with self.subTest(strict=strict): + reasm = self._run(segments, strict=strict) + hello, data = reasm.datagram + self.assertEqual((hello.completed, hello.index, hello.fragment, hello.packet), + (Completion.PARTIAL, (2, 3), fragment, None)) + self.assertEqual((data.completed, data.index, data.fragment), (Completion.COMPLETE, (3,), DATA[5:])) + self.assertEqual(data.packet.data, DATA) + # the read is not destructive, and the hole may still be filled + self.assertEqual(reasm.datagram, (hello, data)) + reasm(_segment(4, 1100, stream[100:250])) + filled, again = reasm.datagram + self.assertEqual((filled.completed, filled.index), (Completion.COMPLETE, (2, 3, 4))) + self.assertHello(filled.packet) + self.assertEqual(again.fragment, DATA[5:]) + + def test_octets_past_a_hole_over_a_header_are_not_reported(self) -> None: + from pcapkit.foundation.reassembly.data import Completion + + stream = ALERT + DATA + segments = [_segment(1, 999, syn=True), _segment(2, 1000, stream[:9]), _segment(3, 1010, stream[10:])] + alert, = self._run(segments).datagram + self.assertEqual((alert.completed, alert.index), (Completion.COMPLETE, (2,))) + + def test_octets_opening_no_record_past_a_hole_end_the_records_reported(self) -> None: + from pcapkit.foundation.reassembly.data import Completion + + segments = [_segment(1, 999, syn=True), _segment(2, 1000, DATA[:10]), + _segment(3, 1020, DATA[20:] + bytes(10))] # a hole, then no record after it + data, = self._run(segments).datagram + self.assertEqual((data.completed, data.index, data.fragment), (Completion.PARTIAL, (2, 3), (DATA[5:10], DATA[20:]))) + + def test_a_fin_drops_the_octets_held_past_it(self) -> None: + from pcapkit.foundation.reassembly.data import Completion + + end = 1000 + len(DATA) + reasm = self._run([_segment(1, 999, syn=True), _segment(2, 1000, DATA[:30]), + _segment(3, end + 5, b'\xee' * 10), _segment(4, end, fin=True)]) + self.assertEqual([run.first for run in reasm._buffer[BUFID].runs], [1000]) # pylint: disable=protected-access + reasm(_segment(5, 1030, DATA[30:] + b'\xee' * 5)) + data, = reasm.datagram + self.assertEqual((data.completed, data.index, data.fragment), (Completion.COMPLETE, (2, 5), DATA[5:])) + self.assertTrue(reasm._buffer[BUFID].closed) # pylint: disable=protected-access + + def test_an_rst_reports_the_record_it_cuts_and_closes_the_stream(self) -> None: + from pcapkit.foundation.reassembly.data import Completion + + reasm = self._run([_segment(1, 999, syn=True), _segment(2, 1000, HELLO[:100]), + _segment(3, 1100, rst=True), _segment(4, 1100, HELLO[100:])]) + hello, = reasm.datagram + self.assertEqual((hello.completed, hello.index, hello.fragment), (Completion.PARTIAL, (2,), (HELLO[5:100],))) + self.assertEqual(len(reasm._dtgram), 1) # pylint: disable=protected-access + + # a SYN opens the endpoints again + reasm(_segment(5, 7999, syn=True)) + reasm(_segment(6, 8000, DATA)) + self.assertEqual([datagram.index for datagram in reasm.datagram], [(2,), (6,)]) + + def test_a_fin_closes_the_stream_once_every_octet_before_it_is_held(self) -> None: + from pcapkit.foundation.reassembly.data import Completion + + record = DATA[:-10] # the peer closed before the record's last ten octets + reasm = self._run([_segment(1, 999, syn=True), _segment(2, 1020, record[20:], fin=True)]) + self.assertEqual(reasm._dtgram, []) # pylint: disable=protected-access + reasm(_segment(3, 1000, record[:20])) + data, = reasm._dtgram # pylint: disable=protected-access + self.assertEqual((data.completed, data.index, data.fragment), (Completion.PARTIAL, (2, 3), (DATA[5:-10],))) + + # a late retransmission is not taken for a new stream + reasm(_segment(4, 1000, DATA)) + self.assertEqual(reasm.datagram, (data,)) + + def test_a_buffer_past_its_timeout_reports_its_record_timed_out(self) -> None: + from pcapkit.foundation.reassembly.data import Completion + + reasm = self._run([_segment(1, 999, syn=True), _segment(2, 1000, HELLO[:100])], timeout=10.0) + reasm.advance(1000.0 + 12) + hello, = reasm.datagram + self.assertEqual((hello.completed, hello.index), (Completion.TIMEOUT, (2,))) + self.assertEqual(reasm._buffer, {}) # pylint: disable=protected-access + + def test_each_direction_is_a_stream_of_its_own(self) -> None: + reverse = (SERVER[0], SERVER[1], CLIENT[0], CLIENT[1]) + reasm = self._run([_segment(1, 1000, HELLO[:100]), _segment(2, 7000, DATA[:20], bufid=reverse), + _segment(3, 1100, HELLO[100:]), _segment(4, 7020, DATA[20:], bufid=reverse)]) + hello, data = reasm.datagram + self.assertEqual((hello.id.src, hello.index, data.id.src, data.index), (CLIENT, (1, 3), SERVER, (2, 4))) + + def test_an_open_stream_holding_no_record_runs_no_callback(self) -> None: + from pcapkit.foundation.reassembly.tls.reassembly import TLS + + seen = [] # type: list[Any] + TLS.register_callback(seen.append) + self.addCleanup(TLS.__callback_fn__.remove, seen.append) + reasm = self._run([_segment(1, 1000, DATA)]) + self.assertEqual(reasm.datagram, tuple(seen[0])) + self.assertEqual(len(seen), 1) + + def test_a_datagram_pickles_with_its_packet_deferred(self) -> None: + from pcapkit.foundation.reassembly.data import Deferred + + datagram, = self._run([_segment(1, 1000, HELLO)]).datagram + held = datagram.__dict__[datagram.__map__['packet']] + self.assertIsInstance(held, Deferred) + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=protocol): + copy = pickle.loads(pickle.dumps(datagram, protocol=protocol)) # nosec: B301 + self.assertIsInstance(copy.__dict__[copy.__map__['packet']], Deferred) + self.assertEqual(copy.id, datagram.id) + self.assertHello(copy.packet) + + +class AnalysisTests(_Case): + """:func:`tls_record` decodes a complete record, and nothing else.""" + + def test_a_complete_record_decodes_as_its_packet_does(self) -> None: + from pcapkit.foundation.analysis import tls_record + from pcapkit.foundation.reassembly.tls.reassembly import TLS + + reasm = TLS() + for segment in (_segment(1, 1000, HELLO[:100]), _segment(2, 1100, HELLO[100:])): + reasm(segment) + datagram, = reasm.datagram + self.assertHello(tls_record(datagram)) + self.assertEqual(tls_record(datagram).info, datagram.packet.info) + + def test_an_incomplete_record_decodes_to_none(self) -> None: + from pcapkit.foundation.analysis import tls_record + from pcapkit.foundation.reassembly.tls.reassembly import TLS + + for strict in (True, False): + with self.subTest(strict=strict): + reasm = TLS(strict=strict) + reasm(_segment(1, 1000, HELLO[:100])) + datagram, = reasm.datagram + self.assertIsNone(tls_record(datagram)) + self.assertIsNone(datagram.packet) + + +class AdapterTests(_Case): + """Each engine's ``tls_reassembly`` keeps its TCP adapter's record of a TLS stream.""" + + def test_the_default_engine_keeps_a_segment_on_a_tls_port(self) -> None: + from pcapkit.toolkit import pcap as toolkit_pcap + from pcapkit.toolkit import pcapng as toolkit_pcapng + + frames = _hello_frames(999) + other = [_frame(_tcp((CLIENT[0], 50001), (SERVER[0], 80), 1, 0x10, HELLO[:100]), + (CLIENT[0], 50001), (SERVER[0], 80))] + for (module, write) in ((toolkit_pcap, _pcap), (toolkit_pcapng, _pcapng)): + with self.subTest(module=module.__name__): + parsed = _extract(self, write(frames + other)).frame + self.assertEqual([module.tls_reassembly(frame) for frame in parsed[:-1]], + [module.tcp_reassembly(frame) for frame in parsed[:-1]]) + self.assertIsNotNone(module.tcp_reassembly(parsed[-1])) + self.assertIsNone(module.tls_reassembly(parsed[-1])) + + def test_a_port_registered_to_tls_is_kept(self) -> None: + from pcapkit.protocols.application.tls.protocol import TLS + from pcapkit.protocols.transport.tcp.protocol import TCP + from pcapkit.toolkit.pcap import _tls_segment + + packet = _segment(1, 1000, HELLO, bufid=(CLIENT[0], 50000, SERVER[0], 8443)) + self.assertIsNone(_tls_segment(packet)) + with mock.patch.dict(TCP.__proto__, {8443: TLS}): + self.assertIs(_tls_segment(packet), packet) + self.assertIsNone(_tls_segment(None)) + + def test_every_third_party_adapter_wraps_its_tcp_one(self) -> None: + import pcapkit.toolkit.pypcapfile as toolkit_pypcapfile + + modules = [toolkit_pypcapfile] + for name in ('dpkt', 'scapy'): + if importlib.util.find_spec(name) is not None: + modules.append(importlib.import_module(f'pcapkit.toolkit.{name}')) + tls, web = _segment(1, 1000, HELLO), _segment(2, 1000, HELLO, bufid=(CLIENT[0], 50000, SERVER[0], 80)) + for module in modules: + args = (object(), 1000.0) if module.__name__.endswith('dpkt') else (object(),) + for (packet, expected) in ((tls, tls), (web, None), (None, None)): + with self.subTest(module=module.__name__, port=packet and packet.bufid[3]), \ + mock.patch.object(module, 'tcp_reassembly', return_value=packet) as tcp: + self.assertIs(module.tls_reassembly(*args, count=7), expected) + tcp.assert_called_once_with(*args, count=7) + + +class ExtractionTests(_Case): + """``Extractor(reassembly=['tls'])`` reports the records of every TLS stream.""" + + def test_a_record_split_across_segments_decodes_on_every_engine(self) -> None: + from pcapkit.foundation.reassembly.data import Completion + + frames = _hello_frames(2 ** 32 - 50) + engines = [('default', _pcap), ('default', _pcapng)] + engines += [(name, _pcap) for name in ('dpkt', 'scapy') if importlib.util.find_spec(name) is not None] + for (engine, write) in engines: + with self.subTest(engine=engine, container=write.__name__): + extractor = self._extract(write(frames), engine) + datagram, = extractor.reassembly.tls + self.assertEqual((datagram.completed, datagram.index, datagram.id.seq), + (Completion.COMPLETE, (2, 3, 4), 2 ** 32 - 49)) + self.assertHello(datagram.packet) + if engine == 'default': + # each segment alone holds part of the record, which a frame keeps raw + self.assertEqual([str(frame.protochain) for frame in extractor.frame[1:4]], + ['Ethernet:IPv4:TCP:Raw'] * 3) + + def _extract(self, capture: bytes, engine: str) -> 'Any': + """Extract ``capture`` with TLS reassembly, from a file for an engine opening one by name.""" + from pcapkit import extract + + if engine != 'scapy': + return _extract(self, capture, reassembly=['tls'], engine=engine) + with tempfile.NamedTemporaryFile(suffix='.pcap', delete=False) as file: + file.write(capture) + self.addCleanup(os.unlink, file.name) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + extractor = extract(fin=file.name, store=True, reassembly=['tls'], engine=engine) + self.addCleanup(close_extractor, extractor) + return extractor + + def test_the_record_holds_no_field_unless_enabled(self) -> None: + from pcapkit.foundation.reassembly.data import ReassemblyData + + extractor = _extract(self, _pcap(_hello_frames(999)), reassembly=['tcp']) + self.assertIsNone(extractor.reassembly.tls) + self.assertEqual(list(ReassemblyData())[-1], 'tls') + + def test_reassemble_makes_it_by_name_and_by_protocol(self) -> None: + from pcapkit.foundation.reassembly.tls.reassembly import TLS + from pcapkit.interface import reassemble + from pcapkit.protocols.application.tls.protocol import TLS as TLS_Protocol + + for protocol in ('tls', 'TLS', TLS_Protocol): + with self.subTest(protocol=protocol): + reasm = reassemble(protocol, strict=False) + self.assertIsInstance(reasm, TLS) + self.assertFalse(reasm._flag_s) # pylint: disable=protected-access + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/protocols/application/test_tls_dtls_record_length_2938_unit.py b/tests/protocols/application/test_tls_dtls_record_length_2938_unit.py new file mode 100644 index 0000000000..25d3a5d20c --- /dev/null +++ b/tests/protocols/application/test_tls_dtls_record_length_2938_unit.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +"""A TLS or DTLS record declaring more than its RFCs allow is no record (#2938). + +A TLSCiphertext of SSLv3 to TLS 1.2 holds at most ``2 ** 14 + 2048`` octets (RFC 6101 +section 5.2.3, RFC 5246 section 6.2.3), and DTLS 1.0 and 1.2 change none of it (RFC 4347 +and RFC 6347, section 4); the legacy header cannot tell TLS 1.3's ``2 ** 14 + 256`` (RFC +9846 section 5.2) from it. A DTLS 1.3 unified header's length is a TLS 1.3 record's (RFC +9147 section 4). A record past its bound is refused, first in its segment or datagram or +after another, so the parser decodes no superset of the RFCs. + +""" + +from __future__ import annotations + +import unittest + +from tests._support import reimport_once_per_class + +#: Test tier (#1958): pure-Python header checks, the same on every interpreter. +__tier__ = 'LATEST' + +#: The largest fragment a legacy record header may declare. +LIMIT = 2 ** 14 + 2048 +#: The largest ciphertext a DTLS 1.3 unified-header record may carry. +UNIFIED_LIMIT = 2 ** 14 + 256 + + +def _tls(fragment: bytes, content_type: int = 23) -> bytes: + return bytes([content_type]) + b'\x03\x03' + len(fragment).to_bytes(2, 'big') + fragment + + +def _dtls(fragment: bytes, content_type: int = 23) -> bytes: + return (bytes([content_type]) + b'\xfe\xfd' + (1).to_bytes(2, 'big') + (1).to_bytes(6, 'big') + + len(fragment).to_bytes(2, 'big') + fragment) + + +def _cid(fragment: bytes, cid: bytes = b'\xc1\xc2\xc3\xc4') -> bytes: + """A ``tls12_cid`` record (RFC 9146 section 4).""" + return (b'\x19\xfe\xfd' + (1).to_bytes(2, 'big') + (1).to_bytes(6, 'big') + cid + + len(fragment).to_bytes(2, 'big') + fragment) + + +def _unified(fragment: bytes, *, length: bool = True) -> bytes: + """A unified-header record with an 8-bit sequence number, its length if ``length``.""" + first = 0x25 if length else 0x21 # 001 0 0 L 01 + return bytes([first, 0x2A]) + (len(fragment).to_bytes(2, 'big') if length else b'') + fragment + + +class FirstRecordTests(unittest.TestCase): + """A record opening the octets parsed is refused past its bound, and read at it.""" + + def setUp(self) -> None: + reimport_once_per_class(self) + + def test_tls(self) -> None: + from pcapkit.protocols.application.tls.protocol import TLS + from pcapkit.utilities.exceptions import ProtocolError + + at = _tls(b'\xa5' * LIMIT) + self.assertEqual((TLS(at).info.length, TLS(at).data), (LIMIT, at)) + with self.assertRaisesRegex(ProtocolError, 'record_overflow'): + TLS(_tls(b'\xa5' * (LIMIT + 1))) + + def test_tls_reassembled(self) -> None: + from pcapkit.const.tls.content_type import ContentType + from pcapkit.protocols.application.tls.protocol import TLS + from pcapkit.protocols.misc.raw.protocol import Raw + + self.assertIsInstance(TLS.analyze_record((ContentType.application_data, 0x0303), b'\xa5' * LIMIT), TLS) + packet = TLS.analyze_record((ContentType.application_data, 0x0303), b'\xa5' * (LIMIT + 1)) + self.assertIsInstance(packet, Raw) + self.assertIn('record_overflow', packet.info.error) + + def test_dtls(self) -> None: + from pcapkit.protocols.application.dtls.protocol import DTLS + from pcapkit.utilities.exceptions import ProtocolError + + at = _dtls(b'\xa5' * LIMIT) + self.assertEqual((DTLS(at).info.length, DTLS(at).data), (LIMIT, at)) + with self.assertRaisesRegex(ProtocolError, 'record_overflow'): + DTLS(_dtls(b'\xa5' * (LIMIT + 1))) + + def test_dtls_tls12_cid(self) -> None: + from pcapkit.protocols.application.dtls.protocol import DTLS, DTLSContext + from pcapkit.utilities.exceptions import ProtocolError + + at = _cid(b'\xa5' * LIMIT) + self.assertEqual(DTLS(at, context=DTLSContext(cid_length=4)).info.length, LIMIT) + with self.assertRaisesRegex(ProtocolError, 'record_overflow'): + DTLS(_cid(b'\xa5' * (LIMIT + 1)), context=DTLSContext(cid_length=4)) + + def test_dtls13_unified_header(self) -> None: + from pcapkit.protocols.application.dtls.protocol import DTLS + from pcapkit.utilities.exceptions import ProtocolError + + for length in (True, False): + with self.subTest(length_present=length): + at = _unified(b'\xa5' * UNIFIED_LIMIT, length=length) + self.assertEqual(DTLS(at).data, at) + with self.assertRaisesRegex(ProtocolError, 'record_overflow'): + DTLS(_unified(b'\xa5' * (UNIFIED_LIMIT + 1), length=length)) + + +class MakeTests(unittest.TestCase): + """``make`` builds a record at its bound and refuses one past it, as the parse does.""" + + def setUp(self) -> None: + reimport_once_per_class(self) + + def test_make(self) -> None: + from pcapkit.protocols.application.dtls.protocol import DTLS + from pcapkit.protocols.application.tls.protocol import TLS + from pcapkit.utilities.exceptions import ProtocolError + + cases = ( + ('TLS', TLS, LIMIT, 'data', {}, _tls), + ('DTLS', DTLS, LIMIT, 'data', {'epoch': 1, 'sequence_number': 1}, _dtls), + ('tls12_cid', DTLS, LIMIT, 'data', + {'content_type': 25, 'epoch': 1, 'sequence_number': 1, 'cid': b'\xc1\xc2\xc3\xc4'}, _cid), + ('unified header', DTLS, UNIFIED_LIMIT, 'content', + {'ciphertext': True, 'epoch': 1, 'sequence_number': 0x2A}, _unified), + ('unified header, no length', DTLS, UNIFIED_LIMIT, 'content', + {'ciphertext': True, 'epoch': 1, 'sequence_number': 0x2A, 'length_present': False}, + lambda fragment: _unified(fragment, length=False)), + ) + for (name, klass, limit, field, kwargs, wire) in cases: + maker = object.__new__(klass) + with self.subTest(record=name, size=limit): + made = bytes(maker.make(**kwargs, **{field: b'\xa5' * limit})) + self.assertEqual(made, wire(b'\xa5' * limit)) + with self.subTest(record=name, size=limit + 1), self.assertRaisesRegex(ProtocolError, 'record_overflow'): + maker.make(**kwargs, **{field: b'\xa5' * (limit + 1)}) + + +class FurtherRecordTests(unittest.TestCase): + """A record after another past its bound stays raw, and one at it is a further layer.""" + + def setUp(self) -> None: + reimport_once_per_class(self) + + def chain(self, layer: 'object') -> 'list[str]': + return str(layer.protochain).split(':') # type: ignore[attr-defined] + + def test_tls(self) -> None: + from pcapkit.protocols.application.tls.protocol import TLS + + alert = _tls(b'\x01\x00', content_type=21) + self.assertEqual(self.chain(TLS(alert + _tls(b'\xa5' * LIMIT))), ['TLS 1.2', 'TLS 1.2']) + self.assertEqual(self.chain(TLS(alert + _tls(b'\xa5' * (LIMIT + 1)))), ['TLS 1.2', 'Raw']) + + def test_dtls(self) -> None: + from pcapkit.protocols.application.dtls.protocol import DTLS + + alert = _dtls(b'\x01\x00', content_type=21) + cases = ( + ('legacy', _dtls(b'\xa5' * LIMIT), _dtls(b'\xa5' * (LIMIT + 1)), 'DTLS 1.2'), + ('unified', _unified(b'\xa5' * UNIFIED_LIMIT), _unified(b'\xa5' * (UNIFIED_LIMIT + 1)), 'DTLS 1.3'), + ('unified, no length', _unified(b'\xa5' * UNIFIED_LIMIT, length=False), + _unified(b'\xa5' * (UNIFIED_LIMIT + 1), length=False), 'DTLS 1.3'), + ) + for (name, at, past, alias) in cases: + with self.subTest(record=name): + self.assertEqual(self.chain(DTLS(alert + at)), ['DTLS 1.2', alias]) + self.assertEqual(self.chain(DTLS(alert + past)), ['DTLS 1.2', 'Raw']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/protocols/application/test_tls_sslv2_fallback_warnings_2525_unit.py b/tests/protocols/application/test_tls_sslv2_fallback_warnings_2525_unit.py index a6ed7d0abf..206f04c610 100644 --- a/tests/protocols/application/test_tls_sslv2_fallback_warnings_2525_unit.py +++ b/tests/protocols/application/test_tls_sslv2_fallback_warnings_2525_unit.py @@ -34,8 +34,9 @@ #: An SSLv2 CLIENT-HELLO cut 4 octets short of its RECORD-LENGTH. CUT_HELLO = (b'\x80\x1c' + b'\x01\x00\x02\x00\x03\x00\x00\x00\x10' + b'\x01\x00\x80' + bytes(12)) -#: A TLS record header declaring a fragment far past the octets that follow it. -LONG_RECORD = b'\x17\x03\x03\xff\xffhello' +#: A TLS record header declaring a fragment far past the octets that follow it, though +#: within the ``2 ** 14 + 2048`` a record may declare (#2938). +LONG_RECORD = b'\x17\x03\x03\x40\x00hello' def _client_hello(version: 'int', *, two_byte_header: 'bool') -> 'bytes': @@ -122,7 +123,7 @@ def test_both_trials_rejected_under_beholder_warn_nothing(self) -> None: parsed, caught = self._tcp(LONG_RECORD, action) self.assertEqual(str(parsed.protochain), 'TCP:Raw') # type: ignore[attr-defined] self.assertEqual(parsed.payload.info.error, # type: ignore[attr-defined] - 'TLS: invalid format: record length 65535 runs past the end of the buffer') + 'TLS: invalid format: record length 16384 runs past the end of the buffer') self.assertEqual([str(item.message) for item in caught], []) def test_both_trials_rejected_outside_beholder_report_tls_alone(self) -> None: @@ -135,13 +136,13 @@ def test_both_trials_rejected_outside_beholder_report_tls_alone(self) -> None: from pcapkit.utilities.contextvars import frame_depth from pcapkit.utilities.exceptions import ProtocolError - for depth, expected in ((1, ['packet length < 0: -65530']), (0, [])): + for depth, expected in ((1, ['packet length < 0: -16379']), (0, [])): with self.subTest(depth=depth): token = frame_depth.set(depth) try: with warnings.catch_warnings(record=True) as caught: warnings.simplefilter('always') - with self.assertRaisesRegex(ProtocolError, 'record length 65535 runs past'): + with self.assertRaisesRegex(ProtocolError, 'record length 16384 runs past'): TLS(LONG_RECORD, len(LONG_RECORD)) finally: frame_depth.reset(token) diff --git a/tests/toolkit/test_pcap_tcp_segment_public_1570_unit.py b/tests/toolkit/test_pcap_tcp_segment_public_1570_unit.py index c17ff1b667..76bd506c5d 100644 --- a/tests/toolkit/test_pcap_tcp_segment_public_1570_unit.py +++ b/tests/toolkit/test_pcap_tcp_segment_public_1570_unit.py @@ -88,8 +88,8 @@ def test_all(self) -> None: from pcapkit.toolkit import pcap self.assertEqual(pcap.__all__, ['ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', - 'dtls_reassembly', 'sctp_reassembly', 'tcp_traceflow', - 'tcp_segment', 'TCPSegment']) + 'dtls_reassembly', 'sctp_reassembly', 'tls_reassembly', + 'tcp_traceflow', 'tcp_segment', 'TCPSegment']) def test_callers_share_the_public_helper(self) -> None: from pcapkit.toolkit import pcap, pcapng diff --git a/tests/utilities/test_seqnum_2938_unit.py b/tests/utilities/test_seqnum_2938_unit.py new file mode 100644 index 0000000000..1f9ad1dade --- /dev/null +++ b/tests/utilities/test_seqnum_2938_unit.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +"""A 32-bit sequence number unwraps to the integer within ``2 ** 31`` of its reference (#2938). + +:func:`pcapkit.utilities.seqnum.unwrap` is the comparison of RFC 9293, section 3.4, that +TCP and TLS reassembly share. + +""" + +import unittest + +#: Test tier (#1958): ``int`` arithmetic at the edges of the 32-bit space. +__tier__ = 'ALL' + + +class UnwrapTests(unittest.TestCase): + """Each case is a wire value, a reference, and the unwrapped value.""" + + CASES = ( + ('at the reference', 1000, 1000, 1000), + ('just ahead', 1500, 1000, 1500), + ('just behind', 500, 1000, 500), + ('ahead across 2 ** 32', 10, 2 ** 32 - 10, 2 ** 32 + 10), + ('behind across 2 ** 32', 2 ** 32 - 10, 2 ** 32 + 10, 2 ** 32 - 10), + ('behind across zero', 2 ** 32 - 10, 10, -10), + ('half the space ahead wraps behind', 2 ** 31, 0, -(2 ** 31)), + ('one short of half ahead', 2 ** 31 - 1, 0, 2 ** 31 - 1), + ('a later wrap', 5, 3 * 2 ** 32 + 2 ** 32 - 5, 4 * 2 ** 32 + 5), + ) + + def test_unwrap(self) -> None: + from pcapkit.utilities.seqnum import unwrap + + for (name, seq, ref, expected) in self.CASES: + with self.subTest(case=name): + self.assertEqual(unwrap(seq, ref), expected) + self.assertEqual(unwrap(seq, ref) % 2 ** 32, seq) + + +if __name__ == '__main__': + unittest.main()