TLS Record Reassembly

pcapkit.foundation.reassembly.tls.reassembly contains TLS only, which reconstructs the TLS records of a TCP stream, a record split across segments included (RFC 9846 Section 5).

Added in version 1.9.0.

class pcapkit.foundation.reassembly.tls.reassembly.TLS[_PT: Info, _DT: Info, _IT: tuple, _BT: Info](*, strict=True, store=True, timeout=None)[source]

Bases: ReassemblyBase[Packet, Datagram[_AT], tuple[_AT, int, _AT, int], Buffer], Generic[_AT]

Reassembly for TLS records.

Parameters:
  • strict (bool) – if 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 (bool) – if store reassembled datagram in memory, i.e., self._dtgram (if not, datagram will be discarded after callback)

  • timeout (float | None) – reassembly timeout in seconds, on the capture’s own clock; None selects __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 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 Extractor feeds it TCP reassembly’s reasm.tcp.packet of every segment on a port TCP.__proto__ binds to TLS, through pcapkit.toolkit.pcap.tls_reassembly() and its siblings, and tls_record() decodes what it reassembles. A complete record’s packet holds the same decode, run on first read; both call the protocol’s analyze_record(), the packet that of __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 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

Defaults

__protocol_name__: str = 'TLS'

Protocol name of current reassembly object.

__protocol_type__: Type[ProtocolBase] = <class 'pcapkit.protocols.application.tls.protocol.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 TLS.record_header and TLS.analyze_record.

Methods

reassembly(info)[source]

Reassembly procedure.

Parameters:

info (Packet) – 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.

submit(buf, *, bufid, expired=False, store=False)[source]

Submit reassembled payload.

Parameters:
  • buf (Buffer) – buffer of the stream

  • bufid (tuple[_AT, int, _AT, int]) – buffer identifier

  • expired (bool) – whether this buffer is being submitted because expire() abandoned it under the reassembly timeout

  • store (bool) – whether buf has left _buffer for good, so its records join _dtgram before the callbacks run, and one that raises cannot lose them

Return type:

list[Datagram[_AT]]

Returns:

Every record still held in buf whose header is, in sequence order up to the first hole a header lies in, each reported COMPLETE if its fragment is whole, otherwise TIMEOUT or PARTIAL.

Utilities

_read_header(data)[source]

Read the header of the record data opens.

Parameters:

data (bytes | bytearray) – octets from a record boundary on

Returns:

meth:TLS.record_header <pcapkit.protocols.application.tls.protocol.TLS.record_header> of __protocol_type__ returns it.

Return type:

tuple[ContentType, int, int, int] | None

Raises:

ProtocolError – If the header opens no record, constructed quietly, since the caller handles it.

_opens_record(data)[source]

Whether a segment’s payload opens a record header.

Parameters:

data (bytes | bytearray) – the segment’s payload

Return type:

bool

Returns:

Whether a whole record header opens data.

static _close_runs(buf, end)[source]

Drop the octets held at or past the FIN.

Parameters:
  • buf (Buffer) – buffer of the stream

  • end (int) – unwrapped sequence number the stream ends at, its fin

static _hold_segment(buf, first, payload, num)[source]

Hold the octets of a segment that no earlier segment brought.

Parameters:
  • buf (Buffer) – buffer of the stream

  • first (int) – unwrapped sequence number of the segment’s first octet

  • payload (bytes) – the segment’s payload

  • num (int) – the segment’s packet number

Octets before boundary were cut into records already, and octets at or past 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).

static _hold_octets(runs, first, octets)[source]

Add octets no run holds to the runs, merging the runs they adjoin.

Parameters:
  • runs (list[Run]) – runs held, in sequence order, mutated in place

  • first (int) – unwrapped sequence number of the first octet

  • octets (bytes) – the octets

_cut_records(buf, bufid)[source]

Cut the whole records held from boundary on off the stream.

Parameters:
Return type:

tuple[list[Datagram[_AT]], bool]

Returns:

The records cut, each COMPLETE, and whether the octets after them can still be cut: False once they open no record.

static _stream_whole(buf)[source]

Whether a stream has seen its FIN and every octet before it.

Parameters:

buf (Buffer) – buffer of the stream

Return type:

bool

Returns:

True once a FIN has been seen and every octet from boundary up to it is held.

_make_datagram(buf, bufid, start, header, completion, fragment)[source]

Build a Datagram for a record.

Parameters:
Return type:

Datagram[_AT]

Returns:

The record. Its packet is the decode tls_record() runs, by this reassembly’s own protocol, deferred to its first read, if the record is complete, and None otherwise, as that function returns.

Algorithm

See also

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:

        flowchart TD
    SEG["a segment, as TCP reassembly records it"]
    SYN{"SYN?"}
    OPEN["a fresh buffer, its boundary<br/>the octet after the SYN"]
    HAS{"a buffer?"}
    SYNC{"its payload opens<br/>a record header?"}
    DROP["ignored"]
    HOLD["hold the octets no earlier<br/>segment brought"]
    HEAD{"a header held<br/>at the boundary?"}
    BAD{"it opens a record?"}
    GONE["the buffer is dropped"]
    WHOLE{"the record whole?"}
    CUT["report it COMPLETE, and<br/>move the boundary past it"]
    END{"an RST, or a FIN with<br/>every octet before it?"}
    CLOSE["submit the buffer, and<br/>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 TLS.record_header narrows but cannot make safe; the class’s warning above says what it rules out.

submit() reports what a buffer still holds, record by record from the boundary: one whose fragment is whole COMPLETE, and one with a hole PARTIAL, or TIMEOUT once expired. It stops at the first hole a header lies in.

Terminology

The reassembly is fed reasm.tcp.packet, TCP reassembly’s record of a segment.

reasm.tls.datagram

Data structure for reassembled TLS record (element of TLS.datagram) is 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 bytes, or – under strict=True and an incomplete record – a tuple of the octet runs actually received), and packet, what tls_record() decodes the record to. packet is decoded on first read, as a DTLS message’s is, and is None for an incomplete record.

reasm.tls.buffer

Data structure for internal buffering (TLS._buffer) is Buffer – one direction of a TCP connection, keyed by its BufferID: the next record’s boundary, the octets held past it as Run objects, the octets each packet added, and where the stream ends.

Data Models

pcapkit.foundation.reassembly.tls.data.BufferID

Buffer ID – one direction of a TCP connection, its source address and port and its destination address and port, as for TCP reassembly.

alias of tuple[_AT, int, _AT, int]

class pcapkit.foundation.reassembly.tls.data.DatagramID[_AT: (IPv4Address, IPv6Address)](src, dst, seq)[source]

Bases: Info, Generic[_AT]

Data model for TLS original record identifier.

src: tuple[_AT, int]

Source address and port.

dst: tuple[_AT, int]

Destination address and port.

seq: int

TCP sequence number of the record’s first octet.

class pcapkit.foundation.reassembly.tls.data.Datagram[_AT: (IPv4Address, IPv6Address)](completed, id, index, content_type, version, length, fragment, packet)[source]

Bases: DeferredPacket, Info, Generic[_AT]

Data model for TLS reassembled record.

completed: Completion

How completely the record was reassembled, and why reassembly stopped; see Completion.

id: DatagramID[_AT]

Original record identifier.

index: tuple[int, ...]

Numbers of the packets that carried the record’s octets.

content_type: ContentType

Record content type.

version: int

Legacy record version.

length: int

Fragment length the record header declares.

fragment: bytes | tuple[bytes, ...]

Reassembled fragment, undecoded.

packet: ProtocolBase | None

Decoded record, as tls_record() returns it unless the reassembly’s __protocol_type__ names another protocol, whose analyze_record then decodes it. Decoded on first read, and None for an incomplete record. A Deferred may be passed in its place, and reading this attribute then runs it and keeps the result.

class pcapkit.foundation.reassembly.tls.data.Run(first, raw)[source]

Bases: Info

Data model for TLS run of contiguous octets held.

first: int

Unwrapped sequence number of the octet held in raw[0].

raw: bytearray

Octets held, in sequence order.

class pcapkit.foundation.reassembly.tls.data.Buffer(boundary, runs, ind, fin, closed, timestamp)[source]

Bases: Info

Data model for TLS buffer entry – one direction of a TCP connection, followed from a record boundary.

boundary: int

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.

runs: list[Run]

Octets held at or past boundary, in sequence order, none adjacent to or overlapping another.

ind: list[tuple[int, int, int]]

Octets each packet added. Each entry is (num, first, stop), its number and the unwrapped sequence range, stop exclusive, in the order they arrived.

fin: int | None

Unwrapped sequence number the stream ends at, once its FIN is seen.

closed: bool

Whether the stream has ended, at its FIN or an RST, so that only a SYN opens it again.

timestamp: float

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.

Type Variables

pcapkit.foundation.reassembly.tls.data._AT: ipaddress.IPv4Address | ipaddress.IPv6Address

IP address type.