Skip to content

Commit a1d732a

Browse files
committed
fix(toolkit): trace and reassemble a TCP segment whose header the snapshot cut (#1518)
The TCP parser rejects a header whose Data Offset runs past the captured octets (#1404), so on a capture snapped inside the TCP header the segment is Raw and the default engine's PCAP and PCAP-NG adapters skipped it: tcp.pcap snapped by 4 octets traced (3,5) (6,) where dpkt, scapy and Wireshark trace (1,2,6,7) (3,4,5). - pcapkit/toolkit/pcap.py: a shared _tcp_segment helper reports the parsed TCP layer, or else reads the fixed 20-octet header of a Raw IP payload the TCP parser rejected (protocol TCP, not a later fragment, at least 20 octets, Data Offset >= 5), with the captured octets as header/payload. - tcp_reassembly and tcp_traceflow in pcap.py and pcapng.py use it. - tests: the snapped tcp.pcap as PCAP and PCAP-NG traces, reassembles and writes trace PCAPs as dpkt/scapy do; unit cases pin each gate.
1 parent 16fbea0 commit a1d732a

5 files changed

Lines changed: 574 additions & 80 deletions

File tree

‎pcapkit/toolkit/pcap.py‎

Lines changed: 144 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,136 @@
1010
cannot be used for it.
1111
1212
"""
13-
from typing import TYPE_CHECKING, cast
13+
from typing import TYPE_CHECKING, NamedTuple, cast
1414

1515
from pcapkit.const.ipv6.extension_header import ExtensionHeader as Enum_ExtensionHeader
16+
from pcapkit.const.reg.transtype import TransType as Enum_TransType
1617
from pcapkit.foundation.reassembly.data.ip import Packet as IP_Packet
1718
from pcapkit.foundation.reassembly.data.tcp import Packet as TCP_Packet
1819
from pcapkit.foundation.traceflow.data.tcp import Packet as TF_TCP_Packet
20+
from pcapkit.protocols.misc.raw import Raw
1921

2022
if TYPE_CHECKING:
2123
from ipaddress import IPv4Address, IPv6Address
24+
from typing import Optional
2225

2326
from pcapkit.const.reg.linktype import LinkType
27+
from pcapkit.protocols.data.internet.ipv4 import IPv4 as Data_IPv4
28+
from pcapkit.protocols.data.internet.ipv6 import IPv6 as Data_IPv6
2429
from pcapkit.protocols.internet.ipv4 import IPv4
2530
from pcapkit.protocols.internet.ipv6 import IPv6
2631
from pcapkit.protocols.internet.ipv6_frag import IPv6_Frag
2732
from pcapkit.protocols.misc.pcap import Frame
33+
from pcapkit.protocols.protocol import ProtocolBase
2834
from pcapkit.protocols.transport.tcp import TCP
2935

3036
__all__ = ['ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tcp_traceflow']
3137

3238

39+
class _TCPSegment(NamedTuple):
40+
"""The fields of a TCP segment that the reassembly and flow tracing records take."""
41+
42+
#: Info of the IP layer carrying the segment.
43+
ip: 'Data_IPv4 | Data_IPv6'
44+
#: TCP source port.
45+
srcport: 'int'
46+
#: TCP destination port.
47+
dstport: 'int'
48+
#: TCP sequence number.
49+
seq: 'int'
50+
#: TCP acknowledgement number.
51+
ack: 'int'
52+
#: TCP synchronise (SYN) flag.
53+
syn: 'bool'
54+
#: TCP finish (FIN) flag.
55+
fin: 'bool'
56+
#: TCP reset (RST) flag.
57+
rst: 'bool'
58+
#: Raw TCP header, as captured.
59+
header: 'bytes'
60+
#: Raw TCP payload, as captured.
61+
payload: 'bytes'
62+
63+
64+
def _tcp_segment(frame: 'ProtocolBase') -> 'Optional[_TCPSegment]':
65+
"""The TCP segment ``frame`` carries, or :data:`None` if it carries none.
66+
67+
Args:
68+
frame: PCAP frame or PCAP-NG block.
69+
70+
Returns:
71+
The fields of the TCP layer if :mod:`pcapkit` parsed one. Otherwise, the
72+
fields of the fixed 20-octet TCP header (:rfc:`9293#section-3.1`) if the
73+
IP payload is a :class:`~pcapkit.protocols.misc.raw.Raw` the TCP parser
74+
rejected, of protocol TCP, from a datagram that is not a later fragment,
75+
with at least those 20 octets captured; else :data:`None`.
76+
77+
Note:
78+
A capture snapped inside the TCP header leaves a Data Offset that runs
79+
past the captured octets, and the TCP parser rejects such a header by
80+
design (:issue:`1404`), so the segment arrives as
81+
:class:`~pcapkit.protocols.misc.raw.Raw`. The ports, numbers and flags
82+
are all in the fixed header, so the segment still belongs to its flow,
83+
as it does for :mod:`dpkt`, :mod:`scapy` and Wireshark (:issue:`1518`).
84+
The header and payload are then the captured octets either side of the
85+
Data Offset.
86+
87+
"""
88+
if 'TCP' in frame:
89+
tcp = cast('TCP', frame['TCP'])
90+
tcp_info = tcp.info
91+
return _TCPSegment(
92+
ip=cast('IPv4 | IPv6', frame['IP']).info,
93+
srcport=tcp_info.srcport.port,
94+
dstport=tcp_info.dstport.port,
95+
seq=tcp_info.seq,
96+
ack=tcp_info.ack,
97+
syn=tcp_info.flags.syn,
98+
fin=tcp_info.flags.fin,
99+
rst=tcp_info.flags.rst,
100+
header=tcp.packet.header,
101+
payload=tcp.packet.payload,
102+
)
103+
104+
if 'IP' not in frame:
105+
return None
106+
ip = cast('IPv4 | IPv6', frame['IP'])
107+
ip_info = ip.info
108+
raw = ip.payload
109+
# NOTE: a Raw with no error is one the caller asked for, by stopping the
110+
# dissection at a ``layer`` or ``protocol``, not a segment TCP rejected.
111+
if (not isinstance(raw, Raw) or raw.info.error is None
112+
or ip_info.protocol != Enum_TransType.TCP):
113+
return None
114+
115+
# A later fragment's payload starts mid-datagram, with no TCP header in it.
116+
if ip_info.version == 4:
117+
offset = ip_info.offset
118+
else:
119+
frag = cast('IPv6', ip).extension_headers.get(Enum_ExtensionHeader.IPv6_Frag) # type: ignore[call-overload]
120+
offset = 0 if frag is None else cast('IPv6_Frag', frag).info.offset
121+
if offset:
122+
return None
123+
124+
octets = bytes(raw.packet.payload)
125+
hdr_len = (octets[12] >> 4) * 4 if len(octets) >= 20 else 0
126+
if hdr_len < 20:
127+
return None
128+
flags = octets[13]
129+
return _TCPSegment(
130+
ip=ip_info,
131+
srcport=int.from_bytes(octets[0:2], 'big'),
132+
dstport=int.from_bytes(octets[2:4], 'big'),
133+
seq=int.from_bytes(octets[4:8], 'big'),
134+
ack=int.from_bytes(octets[8:12], 'big'),
135+
syn=bool(flags & 0x02),
136+
fin=bool(flags & 0x01),
137+
rst=bool(flags & 0x04),
138+
header=octets[:hdr_len],
139+
payload=octets[hdr_len:],
140+
)
141+
142+
33143
def ipv4_reassembly(frame: 'Frame') -> 'IP_Packet[IPv4Address] | None':
34144
"""Make data for IPv4 reassembly.
35145
@@ -150,38 +260,35 @@ def tcp_reassembly(frame: 'Frame') -> 'TCP_Packet | None':
150260
A tuple of data for TCP reassembly.
151261
152262
* If the ``frame`` can be used for TCP reassembly. A frame can be reassembled
153-
if it contains TCP layer (:class:`~pcapkit.protocols.transport.tcp.TCP`).
263+
if it contains TCP layer (:class:`~pcapkit.protocols.transport.tcp.TCP`),
264+
or a TCP segment whose header the TCP parser rejected, as it does one the
265+
snapshot length cut short (:issue:`1518`).
154266
* If the ``frame`` can be reassembled, then the :obj:`dict` mapping of data for TCP
155267
reassembly (:term:`reasm.tcp.packet`) will be returned; otherwise, returns :data:`None`.
156268
157269
See Also:
158270
:class:`pcapkit.foundation.reassembly.tcp.TCP`
159271
160272
"""
161-
if 'TCP' in frame:
162-
ip = cast('IPv4 | IPv6', frame['IP'])
163-
ip_info = ip.info
164-
tcp = cast('TCP', frame['TCP'])
165-
tcp_info = tcp.info
166-
167-
raw_len = len(tcp.packet.payload)
273+
if (segment := _tcp_segment(frame)) is not None:
274+
raw_len = len(segment.payload)
168275
data = TCP_Packet(
169276
bufid=(
170-
ip_info.src, # source IP address
171-
tcp_info.srcport.port, # source port
172-
ip_info.dst, # destination IP address
173-
tcp_info.dstport.port, # destination port
277+
segment.ip.src, # source IP address
278+
segment.srcport, # source port
279+
segment.ip.dst, # destination IP address
280+
segment.dstport, # destination port
174281
),
175282
num=frame.info.number, # original packet range number
176-
ack=tcp_info.ack, # acknowledgement
177-
dsn=tcp_info.seq, # data sequence number
178-
syn=tcp_info.flags.syn, # synchronise flag
179-
fin=tcp_info.flags.fin, # finish flag
180-
rst=tcp_info.flags.rst, # reset connection flag
181-
header=tcp.packet.header, # raw bytes type header
182-
payload=bytearray(tcp.packet.payload), # raw bytearray type payload
183-
first=tcp_info.seq, # first sequence number of payload
184-
last=tcp_info.seq + raw_len - 1, # last sequence number of payload
283+
ack=segment.ack, # acknowledgement
284+
dsn=segment.seq, # data sequence number
285+
syn=segment.syn, # synchronise flag
286+
fin=segment.fin, # finish flag
287+
rst=segment.rst, # reset connection flag
288+
header=segment.header, # raw bytes type header
289+
payload=bytearray(segment.payload), # raw bytearray type payload
290+
first=segment.seq, # first sequence number of payload
291+
last=segment.seq + raw_len - 1, # last sequence number of payload
185292
len=raw_len, # payload length, header excludes
186293
timestamp=float(frame.info.time_epoch), # capture timestamp
187294
)
@@ -200,36 +307,33 @@ def tcp_traceflow(frame: 'Frame', *, data_link: 'LinkType') -> 'TF_TCP_Packet |
200307
Data for TCP reassembly.
201308
202309
* If the ``packet`` can be used for TCP flow tracing. A frame can be reassembled
203-
if it contains TCP layer (:class:`~pcapkit.protocols.transport.tcp.TCP`).
310+
if it contains TCP layer (:class:`~pcapkit.protocols.transport.tcp.TCP`),
311+
or a TCP segment whose header the TCP parser rejected, as it does one the
312+
snapshot length cut short (:issue:`1518`).
204313
* If the ``frame`` can be reassembled, then the :obj:`dict` mapping of data for TCP
205314
flow tracing (:term:`trace.tcp.packet`) will be returned; otherwise, returns :data:`None`.
206315
207316
See Also:
208317
:class:`pcapkit.foundation.traceflow.tcp.TCP`
209318
210319
"""
211-
if 'TCP' in frame:
212-
ip = cast('IPv4 | IPv6', frame['IP'])
213-
ip_info = ip.info
214-
tcp = cast('TCP', frame['TCP'])
215-
tcp_info = tcp.info
216-
320+
if (segment := _tcp_segment(frame)) is not None:
217321
data = TF_TCP_Packet( # type: ignore[type-var]
218322
protocol=data_link, # data link type from global header
219323
index=frame.info.number, # frame number
220324
frame=frame.info, # extracted frame info
221-
syn=tcp_info.flags.syn, # TCP synchronise (SYN) flag
222-
fin=tcp_info.flags.fin, # TCP finish (FIN) flag
223-
rst=tcp_info.flags.rst, # TCP reset (RST) flag
224-
src=ip_info.src, # source IP
225-
dst=ip_info.dst, # destination IP
226-
srcport=tcp_info.srcport.port, # TCP source port
227-
dstport=tcp_info.dstport.port, # TCP destination port
325+
syn=segment.syn, # TCP synchronise (SYN) flag
326+
fin=segment.fin, # TCP finish (FIN) flag
327+
rst=segment.rst, # TCP reset (RST) flag
328+
src=segment.ip.src, # source IP
329+
dst=segment.ip.dst, # destination IP
330+
srcport=segment.srcport, # TCP source port
331+
dstport=segment.dstport, # TCP destination port
228332
timestamp=float(frame.info.time_epoch), # frame timestamp
229-
seq=tcp_info.seq, # TCP sequence number
230-
ack=tcp_info.ack, # TCP acknowledgement number
231-
header=tcp.packet.header, # raw bytes type header
232-
payload=bytearray(tcp.packet.payload), # raw bytearray type payload
333+
seq=segment.seq, # TCP sequence number
334+
ack=segment.ack, # TCP acknowledgement number
335+
header=segment.header, # raw bytes type header
336+
payload=bytearray(segment.payload), # raw bytearray type payload
233337
)
234338
return data
235339
return None

‎pcapkit/toolkit/pcapng.py‎

Lines changed: 34 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from pcapkit.foundation.traceflow.data.tcp import Packet as TF_TCP_Packet
1919
from pcapkit.protocols.data.misc.pcap.frame import Frame as Data_Frame
2020
from pcapkit.protocols.data.misc.pcap.frame import FrameInfo as Data_FrameInfo
21+
from pcapkit.toolkit.pcap import _tcp_segment
2122

2223
if TYPE_CHECKING:
2324
from ipaddress import IPv4Address, IPv6Address
@@ -26,7 +27,6 @@
2627
from pcapkit.protocols.internet.ipv6 import IPv6
2728
from pcapkit.protocols.internet.ipv6_frag import IPv6_Frag
2829
from pcapkit.protocols.misc.pcapng import PCAPNG, Packet
29-
from pcapkit.protocols.transport.tcp import TCP
3030

3131
__all__ = ['ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly',
3232
'tcp_traceflow', 'block2frame']
@@ -154,40 +154,37 @@ def tcp_reassembly(frame: 'PCAPNG') -> 'TCP_Packet | None':
154154
A tuple of data for TCP reassembly.
155155
156156
* If the ``frame`` can be used for TCP reassembly. A frame can be reassembled
157-
if it contains TCP layer (:class:`~pcapkit.protocols.transport.tcp.TCP`).
157+
if it contains TCP layer (:class:`~pcapkit.protocols.transport.tcp.TCP`),
158+
or a TCP segment whose header the TCP parser rejected, as it does one the
159+
snapshot length cut short (:issue:`1518`).
158160
* If the ``frame`` can be reassembled, then the :obj:`dict` mapping of data for TCP
159161
reassembly (:term:`reasm.tcp.packet`) will be returned; otherwise, returns :data:`None`.
160162
161163
See Also:
162164
:class:`pcapkit.foundation.reassembly.tcp.TCP`
163165
164166
"""
165-
if 'TCP' in frame:
166-
ip = cast('IPv4 | IPv6', frame['IP'])
167-
ip_info = ip.info
168-
tcp = cast('TCP', frame['TCP'])
169-
tcp_info = tcp.info
170-
171-
raw_len = len(tcp.packet.payload)
167+
if (segment := _tcp_segment(frame)) is not None:
168+
raw_len = len(segment.payload)
172169
frame_info = cast('Packet', frame.info)
173170

174171
data = TCP_Packet(
175172
bufid=(
176-
ip_info.src, # source IP address
177-
tcp_info.srcport.port, # source port
178-
ip_info.dst, # destination IP address
179-
tcp_info.dstport.port, # destination port
173+
segment.ip.src, # source IP address
174+
segment.srcport, # source port
175+
segment.ip.dst, # destination IP address
176+
segment.dstport, # destination port
180177
),
181178
num=frame_info.number, # original packet range number
182-
ack=tcp_info.ack, # acknowledgement
183-
dsn=tcp_info.seq, # data sequence number
184-
syn=tcp_info.flags.syn, # synchronise flag
185-
fin=tcp_info.flags.fin, # finish flag
186-
rst=tcp_info.flags.rst, # reset connection flag
187-
header=tcp.packet.header, # raw bytes type header
188-
payload=bytearray(tcp.packet.payload), # raw bytearray type payload
189-
first=tcp_info.seq, # first sequence number of payload
190-
last=tcp_info.seq + raw_len - 1, # last sequence number of payload
179+
ack=segment.ack, # acknowledgement
180+
dsn=segment.seq, # data sequence number
181+
syn=segment.syn, # synchronise flag
182+
fin=segment.fin, # finish flag
183+
rst=segment.rst, # reset connection flag
184+
header=segment.header, # raw bytes type header
185+
payload=bytearray(segment.payload), # raw bytearray type payload
186+
first=segment.seq, # first sequence number of payload
187+
last=segment.seq + raw_len - 1, # last sequence number of payload
191188
len=raw_len, # payload length, header excludes
192189
timestamp=float(frame_info.timestamp_epoch), # capture timestamp
193190
)
@@ -206,38 +203,35 @@ def tcp_traceflow(frame: 'PCAPNG', *, nanosecond: 'bool' = False) -> 'TF_TCP_Pac
206203
Data for TCP reassembly.
207204
208205
* If the ``packet`` can be used for TCP flow tracing. A frame can be reassembled
209-
if it contains TCP layer (:class:`~pcapkit.protocols.transport.tcp.TCP`).
206+
if it contains TCP layer (:class:`~pcapkit.protocols.transport.tcp.TCP`),
207+
or a TCP segment whose header the TCP parser rejected, as it does one the
208+
snapshot length cut short (:issue:`1518`).
210209
* If the ``frame`` can be reassembled, then the :obj:`dict` mapping of data for TCP
211210
flow tracing (:term:`trace.tcp.packet`) will be returned; otherwise, returns :data:`None`.
212211
213212
See Also:
214213
:class:`pcapkit.foundation.traceflow.tcp.TCP`
215214
216215
"""
217-
if 'TCP' in frame:
218-
ip = cast('IPv4 | IPv6', frame['IP'])
219-
ip_info = ip.info
220-
tcp = cast('TCP', frame['TCP'])
221-
tcp_info = tcp.info
222-
216+
if (segment := _tcp_segment(frame)) is not None:
223217
frame_info = cast('Packet', frame.info)
224218
data = TF_TCP_Packet( # type: ignore[type-var]
225219
protocol=frame.linktype, # data link type from global header
226220
index=frame_info.number, # frame number
227221
frame=block2frame(frame_info, nanosecond=nanosecond),
228222
# extracted frame info
229-
syn=tcp_info.flags.syn, # TCP synchronise (SYN) flag
230-
fin=tcp_info.flags.fin, # TCP finish (FIN) flag
231-
rst=tcp_info.flags.rst, # TCP reset (RST) flag
232-
src=ip_info.src, # source IP
233-
dst=ip_info.dst, # destination IP
234-
srcport=tcp_info.srcport.port, # TCP source port
235-
dstport=tcp_info.dstport.port, # TCP destination port
223+
syn=segment.syn, # TCP synchronise (SYN) flag
224+
fin=segment.fin, # TCP finish (FIN) flag
225+
rst=segment.rst, # TCP reset (RST) flag
226+
src=segment.ip.src, # source IP
227+
dst=segment.ip.dst, # destination IP
228+
srcport=segment.srcport, # TCP source port
229+
dstport=segment.dstport, # TCP destination port
236230
timestamp=float(frame_info.timestamp_epoch), # frame timestamp
237-
seq=tcp_info.seq, # TCP sequence number
238-
ack=tcp_info.ack, # TCP acknowledgement number
239-
header=tcp.packet.header, # raw bytes type header
240-
payload=bytearray(tcp.packet.payload), # raw bytearray type payload
231+
seq=segment.seq, # TCP sequence number
232+
ack=segment.ack, # TCP acknowledgement number
233+
header=segment.header, # raw bytes type header
234+
payload=bytearray(segment.payload), # raw bytearray type payload
241235
)
242236
return data
243237
return None

0 commit comments

Comments
 (0)