Debian Codegraph @

crt/s2n/tests/pcap/src/handshake_message.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use anyhow::*;
5 use rtshark::RTSharkBuilder;
6 use std::collections::HashMap;
7
8 use crate::packet::Packet;
9 use crate::packet::PacketId;
10 use crate::packet::PacketIterator;
11
12 /// TLS handshake message type, as defined in the TLS RFC.
13 ///
14 /// See https://datatracker.ietf.org/doc/html/rfc8446#section-4
15 pub type MessageType = u8;
16
17 /// A TLS handshake message, as defined in the TLS RFC.
18 ///
19 /// See https://datatracker.ietf.org/doc/html/rfc8446#section-4
20 #[derive(Debug, Clone, Default)]
21 pub struct HandshakeMessage {
22 /// TLS handshake message type, as defined in the TLS RFC.
23 ///
24 /// See https://datatracker.ietf.org/doc/html/rfc8446#section-4
25 pub message_type: MessageType,
26
27 /// Packet containing handshake message metadata.
28 pub packet: Packet,
29
30 /// List of TLS records containing the TLS handshake message.
31 ///
32 /// TLS handshake messages can be fragmented across multiple TLS records.
33 /// Each record is represented as a Vec<u8>, and includes the record header.
34 ///
35 /// See https://datatracker.ietf.org/doc/html/rfc8446#section-5
36 pub records: Vec<Vec<u8>>,
37 }
38
39 impl HandshakeMessage {
40 const FRAGMENT: &'static str = "tls.handshake.fragment";
41 const FRAGMENTS_COUNT: &'static str = "tls.handshake.fragment.count";
42
43 /// Returns the complete handshake message in bytes.
44 pub fn bytes(&self) -> Vec<u8> {
45 let mut bytes = Vec::new();
46 for record in &self.records {
47 // Each record starts with a 5-byte header.
48 // To join the record payloads into a complete valid message,
49 // we have to strip off those headers first.
50 bytes.extend_from_slice(&record[5..])
51 }
52 bytes
53 }
54
55 fn parse_fields(packet: Packet, tcp_packets: &HashMap<PacketId, Packet>) -> Result<Self> {
56 let message_type = packet
57 .metadata(Builder::MESSAGE_TYPE)
58 .context("Missing handshake message type")?
59 .parse::<u8>()?;
60
61 // TLS handshake messages may be fragmented across multiple TLS records.
62 // tshark only associates the handshake message metadata with the final record,
63 // but we must retrieve all the records to fully capture the raw message bytes.
64 //
65 // 'fragment_ids' here is a list of the packets containing
66 // TLS records which contain fragments of this handshake message.
67 //
68 // Note: `all_metadata` uses the tshark "value" field. For Self::FRAGMENT,
69 // the "value" field is the id of the packet containing the fragment.
70 // The "raw_value" field is the fragment payload. However, the "raw_value"
71 // field does not contain the TLS record header, only the TLS handshake
72 // message. TLS record headers could be useful for later replaying the
73 // handshake, so we continue to use "value" and manually reassemble the
74 // TLS handshake messages from the fragment packets.
75 // See https://github.com/CrabeDeFrance/rtshark/pull/17
76 let fragment_ids = packet.all_metadata(Self::FRAGMENT);
77 let fragment_ids = if fragment_ids.is_empty() {
78 vec![packet.id()]
79 } else {
80 fragment_ids
81 .into_iter()
82 .map(|s| s.parse::<PacketId>().context("Bad fragment id"))
83 .collect::<Result<Vec<_>>>()?
84 };
85
86 // For each fragment, we must retrieve the associated packet.
87 // The TLS record is the TCP payload of that packet.
88 let mut records = Vec::new();
89 for fragment_id in fragment_ids {
90 let fragment = tcp_packets
91 .get(&fragment_id)
92 .context("Missing handshake message fragment record")?;
93 // TCP payloads can also be fragmented, so check for a reassembled payload first.
94 let tcp_payload = fragment
95 .metadata(Builder::TCP_REASSEMBLED)
96 .or_else(|| fragment.metadata(Builder::TCP_PAYLOAD))
97 .context("Missing handshake message tcp payload")?;
98 // The TCP payload is a hex string. However, rtshark formats hex strings
99 // like "AB:CD:EF:12" instead of "ABCDEF12".
100 let hex = tcp_payload.replace(':', "");
101 let bytes = hex::decode(hex)?;
102 records.push(bytes);
103 }
104
105 let count = packet
106 .metadata(Self::FRAGMENTS_COUNT)
107 .unwrap_or("1")
108 .parse::<usize>()?;
109 if count != records.len() {
110 bail!("Unable to find all tls records for tls message")
111 }
112
113 Ok(Self {
114 message_type,
115 packet,
116 records,
117 })
118 }
119
120 fn from_packet(packet: Packet, tcp_packets: &HashMap<PacketId, Packet>) -> Result<Self> {
121 let packet_id = packet.id();
122 Self::parse_fields(packet, tcp_packets)
123 .with_context(|| format!("Failed to parse frame {packet_id}"))
124 }
125
126 pub fn builder() -> Builder {
127 Builder::default()
128 }
129 }
130
131 #[derive(Debug, Clone, Default)]
132 pub struct Builder {
133 message_type: Option<u8>,
134 capture_file: Option<String>,
135 }
136
137 impl Builder {
138 const TCP_PAYLOAD: &'static str = "tcp.payload";
139 const TCP_REASSEMBLED: &'static str = "tcp.reassembled.data";
140
141 // Note: sslv2 uses "tls.ssl2.handshake.type" instead. If we want to support
142 // sslv2 ClientHellos, we will need to search for both variants.
143 const MESSAGE_TYPE: &'static str = "tls.handshake.type";
144
145 pub(crate) fn set_type(&mut self, message_type: u8) -> &mut Self {
146 self.message_type = Some(message_type);
147 self
148 }
149
150 pub fn set_capture_file(&mut self, file: &str) -> &mut Self {
151 self.capture_file = Some(file.to_string());
152 self
153 }
154
155 fn build_from_capture(
156 self,
157 capture: rtshark::RTSharkBuilderReady,
158 ) -> Result<Vec<HandshakeMessage>> {
159 // We are either looking for a specific type of TLS handshake message,
160 // or all TLS handshake messages.
161 let filter = if let Some(message_type) = self.message_type {
162 format!("{} == {}", Self::MESSAGE_TYPE, message_type)
163 } else {
164 Self::MESSAGE_TYPE.to_string()
165 };
166
167 // We currently don't support QUIC
168 let filter = filter + " && !quic";
169
170 // tshark associates a LOT of metadata with each packet. Filtering that
171 // metadata (like by using `metadata_whitelist`) significantly improves
172 // both performance and memory usage.
173 //
174 // We potentially need all available metadata for the TLS handshake
175 // messages that we're interested in, but we only need the TCP payloads
176 // for any packets that don't contain TLS handshake messages.
177 let message_capture = capture.display_filter(&filter).spawn()?;
178 let tcp_capture = capture
179 .display_filter(Self::TCP_PAYLOAD)
180 .metadata_whitelist(Self::TCP_PAYLOAD)
181 .metadata_whitelist(Self::TCP_REASSEMBLED)
182 .metadata_whitelist(Packet::PACKET_ID)
183 .spawn()?;
184
185 let tcp_packets = PacketIterator(tcp_capture).into_lookup();
186 let messages = PacketIterator(message_capture)
187 .map(|packet| HandshakeMessage::from_packet(packet, &tcp_packets))
188 .collect::<Result<Vec<_>>>()?;
189 Ok(messages)
190 }
191
192 pub(crate) fn build(mut self) -> Result<Vec<HandshakeMessage>> {
193 let file = self
194 .capture_file
195 .take()
196 .context("No capture file provided")?;
197 let capture = RTSharkBuilder::builder().input_path(&file);
198 self.build_from_capture(capture)
199 .with_context(|| format!("Failed to parse capture file {}", &file))
200 }
201 }
202
203 #[cfg(test)]
204 mod tests {
205 use super::*;
206
207 #[test]
208 fn tls_fragmentation() -> Result<()> {
209 let mut builder = Builder::default();
210 builder.set_capture_file("data/fragmented_ch.pcap");
211 let messages = builder.build()?;
212
213 let first = messages.first().unwrap();
214 assert_eq!(first.records.len(), 3);
215 let bytes = first.bytes();
216 // Correct length read from wireshark
217 assert_eq!(bytes.len(), 16262);
218
219 Ok(())
220 }
221
222 #[test]
223 fn tcp_fragmentation() -> Result<()> {
224 let mut builder = Builder::default();
225 builder.set_capture_file("data/tcp_fragmentation.pcap");
226 let messages = builder.build()?;
227
228 let first = messages.first().unwrap();
229 assert_eq!(first.records.len(), 1);
230 let bytes = first.bytes();
231 // Correct length read from wireshark
232 assert_eq!(bytes.len(), 271);
233
234 Ok(())
235 }
236
237 #[test]
238 fn multiple_handshakes() -> Result<()> {
239 let mut builder = Builder::default();
240 builder.set_capture_file("data/multiple_hellos.pcap");
241 let messages = builder.build()?;
242
243 // Only one ServerHello can appear per handshake, so count the number
244 // of ServerHello messages to count the number of handshakes.
245 let server_hello_type = 2;
246 let count = messages
247 .iter()
248 .filter(|m| m.message_type == server_hello_type)
249 .count();
250 assert_eq!(count, 5);
251 Ok(())
252 }
253
254 #[test]
255 fn from_pcaps() -> Result<()> {
256 let pcaps = crate::all_pcaps();
257
258 for pcap in pcaps {
259 let pcap: String = pcap;
260
261 let mut builder = Builder::default();
262 builder.set_capture_file(&pcap);
263 let messages = builder.build().unwrap();
264 assert!(!messages.is_empty())
265 }
266
267 Ok(())
268 }
269 }