Debian Codegraph @

crt/s2n/bindings/rust/standard/s2n-tls-metrics-subscriber/src/parsing/mod.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! This module holds the parsing logic that we need to pull interesting bits out
5 //! of the client hello
6
7 // These deny lints are used out of an abundance of caution in our parsing code
8 // which is accepting untrusted input.
9 #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
10 #![cfg_attr(not(test), deny(clippy::unwrap_used))]
11 #![cfg_attr(not(test), deny(clippy::expect_used))]
12 #![cfg_attr(not(test), deny(clippy::string_slice))]
13 #![cfg_attr(not(test), deny(clippy::panic))]
14
15 use std::ffi::c_uint;
16
17 use s2n_codec::DecoderBuffer;
18 use s2n_tls::{client_hello::ClientHello as S2NClientHello, error::Fallible};
19 use s2n_tls_sys::{s2n_client_hello_get_extension_by_id, s2n_client_hello_get_extension_length};
20
21 use crate::parsing::messages::{
22 ClientHello, SignatureSchemeList, SupportedGroups, SupportedVersionsClientHello,
23 };
24 use s2n_tls_metrics_schema::static_lists::{Cipher, Group, Signature, Version};
25
26 pub mod cert;
27 mod messages;
28
29 /// View of the supported-parameter lists from a `ClientHello`.
30 ///
31 /// Constructed eagerly (FFI extension copies + decode); accessors return
32 /// slices into the cached lists. Each handshake hits these accessors
33 /// multiple times, so caching avoids re-parsing the same bytes.
34 pub(crate) struct ClientHelloSupportedParameters {
35 versions: Vec<Version>,
36 ciphers: Vec<Cipher>,
37 groups: Option<Vec<Group>>,
38 signatures: Option<Vec<Signature>>,
39 }
40
41 impl ClientHelloSupportedParameters {
42 /// https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#tls-extensiontype-values-1
43 const SUPPORTED_GROUPS_ID: u16 = 10;
44 const SUPPORTED_VERSIONS_ID: u16 = 43;
45 const SIGNATURE_ALGORITHMS_ID: u16 = 13;
46
47 /// Parse all four supported-parameter lists up front. Subsequent
48 /// accessor calls return slices into these owned `Vec`s and do not
49 /// allocate.
50 pub fn new(client_hello: &S2NClientHello) -> Result<Self, Box<dyn std::error::Error>> {
51 // Parse the ClientHello body once: we need both the cipher list
52 // and the legacy protocol_version (used as the versions fallback
53 // when the supported_versions extension is absent).
54 let ch_bytes = client_hello.raw_message()?;
55 let parsed_ch = DecoderBuffer::new(ch_bytes.as_ref()).decode_exact::<ClientHello>()?;
56 let ciphers = parsed_ch.cipher_suites.list.to_vec();
57 let fallback_version = parsed_ch.protocol_version;
58
59 let versions = match client_hello.get_extension(Self::SUPPORTED_VERSIONS_ID)? {
60 Some(buffer) => {
61 let parsed =
62 DecoderBuffer::new(&buffer).decode_exact::<SupportedVersionsClientHello>()?;
63 parsed.versions.list.to_vec()
64 }
65 None => vec![fallback_version],
66 };
67
68 let groups = match client_hello.get_extension(Self::SUPPORTED_GROUPS_ID)? {
69 Some(buffer) => {
70 let parsed = DecoderBuffer::new(&buffer).decode_exact::<SupportedGroups>()?;
71 Some(parsed.named_group_list.list.to_vec())
72 }
73 None => None,
74 };
75
76 let signatures = match client_hello.get_extension(Self::SIGNATURE_ALGORITHMS_ID)? {
77 Some(buffer) => {
78 let parsed = DecoderBuffer::new(&buffer).decode_exact::<SignatureSchemeList>()?;
79 Some(parsed.supported_signature_algorithms.list.to_vec())
80 }
81 None => None,
82 };
83
84 Ok(Self {
85 versions,
86 ciphers,
87 groups,
88 signatures,
89 })
90 }
91
92 pub fn supported_versions(&self) -> &[Version] {
93 &self.versions
94 }
95
96 pub fn supported_ciphers(&self) -> &[Cipher] {
97 &self.ciphers
98 }
99
100 pub fn supported_groups(&self) -> Option<&[Group]> {
101 self.groups.as_deref()
102 }
103
104 pub fn supported_signatures(&self) -> Option<&[Signature]> {
105 self.signatures.as_deref()
106 }
107 }
108
109 /// We generally discourage the use of direct extension retrieval so it isn't exposed
110 /// in the s2n-tls crate.
111 trait S2NClientHelloExtension {
112 fn get_extension(&self, extension_id: u16) -> Result<Option<Vec<u8>>, s2n_tls::error::Error>;
113 }
114
115 impl S2NClientHelloExtension for s2n_tls::client_hello::ClientHello {
116 /// Retrieve the extension_data from some particular extension
117 ///
118 /// The extension ID should be one of the values from this list:
119 /// https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#tls-extensiontype-values-1
120 fn get_extension(&self, extension_id: u16) -> Result<Option<Vec<u8>>, s2n_tls::error::Error> {
121 // we are depending on an internal implementation detail, where ClientHello
122 // is aliased to the raw s2n_tls_sys type. Below is a compile-time assertion
123 // that this hasn't changed. Even if the change isn't run through
124 // s2n-tls CI, customers will fail to build instead of
125 // encountering a runtime error.
126 static_assertions::assert_eq_size!(
127 s2n_tls::client_hello::ClientHello,
128 s2n_tls_sys::s2n_client_hello
129 );
130
131 let raw_ch =
132 self as *const s2n_tls::client_hello::ClientHello as *mut s2n_tls_sys::s2n_client_hello;
133 let extension_length = unsafe {
134 s2n_client_hello_get_extension_length(raw_ch, extension_id as c_uint).into_result()
135 }?;
136 if extension_length == 0 {
137 return Ok(None);
138 }
139
140 let mut extension_data = vec![0; extension_length];
141 let written_length = unsafe {
142 s2n_client_hello_get_extension_by_id(
143 raw_ch,
144 extension_id as c_uint,
145 extension_data.as_mut_ptr(),
146 extension_data.len() as u32,
147 )
148 .into_result()
149 }?;
150
151 debug_assert_eq!(extension_length, written_length);
152
153 Ok(Some(extension_data))
154 }
155 }
156
157 #[cfg(test)]
158 mod tests {
159 use super::*;
160 use std::ffi::CStr;
161
162 use s2n_codec::{DecoderBuffer, zerocopy::U16};
163 use s2n_tls::{
164 security::Policy,
165 testing::{TestPair, build_config},
166 };
167
168 use crate::{
169 parsing::{ClientHelloSupportedParameters, messages::ClientHello},
170 test_utils::ARBITRARY_POLICY_1,
171 };
172 use s2n_tls::error::Error as S2NError;
173
174 struct SecurityPolicySupportedParameters {
175 cipher: Vec<Cipher>,
176 groups: Vec<Group>,
177 signatures: Vec<Signature>,
178 }
179
180 impl SecurityPolicySupportedParameters {
181 fn new(policy_name: &'static str) -> Self {
182 let sp = s2n_tls_sys_internal::security_policy_table()
183 .iter()
184 .find(|security_policy| {
185 let current_name = unsafe { CStr::from_ptr(security_policy.version) };
186 current_name.to_str().unwrap() == policy_name
187 })
188 .map(|sp| unsafe { &*sp.security_policy })
189 .unwrap();
190
191 let cipher: Vec<Cipher> = sp.ciphers().iter().map(|c| Cipher(c.iana_value)).collect();
192
193 let groups: Vec<Group> = sp
194 .curves()
195 .iter()
196 .map(|c| Group(U16::new(c.iana_id)))
197 .chain(sp.kems().iter().map(|k| Group(U16::new(k.iana_id))))
198 .collect();
199
200 let signatures: Vec<Signature> = sp
201 .signatures()
202 .iter()
203 .map(|s| Signature(U16::new(s.iana_value)))
204 .collect();
205
206 Self {
207 cipher,
208 groups,
209 signatures,
210 }
211 }
212 }
213
214 /// Return a server connection that has handshaken with a client using `policy`.
215 fn server_connection(policy: &s2n_tls::security::Policy) -> s2n_tls::connection::Connection {
216 let config = build_config(policy).unwrap();
217 let mut pair = TestPair::from_config(&config);
218 pair.handshake().unwrap();
219 pair.server
220 }
221
222 #[test]
223 fn client_hello_parsing_sanity_check() -> Result<(), S2NError> {
224 let sp = server_connection(&ARBITRARY_POLICY_1);
225 let client_hello = sp.client_hello()?;
226 let client_hello_bytes = client_hello.raw_message()?;
227 let buffer = DecoderBuffer::new(&client_hello_bytes);
228 let parsed_client_hello = buffer.decode_exact::<ClientHello>().unwrap();
229 assert_eq!(
230 parsed_client_hello.legacy_session_id.blob,
231 client_hello.session_id()?.as_slice()
232 );
233
234 Ok(())
235 }
236
237 /// iterate through s2n-tls security policy structs and send a client hello
238 /// for each one. Then confirm that [`ClientHelloSupportedParameters`] detects
239 /// all of the parameters in the underlying security policy.
240 #[test]
241 fn expected_supported_parameters() {
242 let mut tested_policies = 0;
243
244 for entry in s2n_tls_sys_internal::security_policy_table() {
245 let policy_name = unsafe { CStr::from_ptr(entry.version) }.to_str().unwrap();
246 let policy = Policy::from_version(policy_name).unwrap();
247
248 let expected = SecurityPolicySupportedParameters::new(policy_name);
249
250 // some policies are incompatible with the default test certs
251 let pair = std::panic::catch_unwind(|| {
252 let config = build_config(&policy).unwrap();
253 let mut pair = TestPair::from_config(&config);
254 pair.handshake().unwrap();
255 pair
256 });
257 let pair = match pair {
258 Ok(p) => p,
259 Err(_) => continue,
260 };
261 let client_hello = pair.server.client_hello().unwrap();
262 let parsed = ClientHelloSupportedParameters::new(client_hello).unwrap();
263
264 let offered_ciphers = parsed.supported_ciphers();
265 for cipher in &expected.cipher {
266 assert!(offered_ciphers.contains(cipher));
267 }
268
269 if let Some(offered_groups) = parsed.supported_groups() {
270 for group in &expected.groups {
271 assert!(offered_groups.contains(group));
272 }
273 }
274
275 if let Some(offered_sigs) = parsed.supported_signatures() {
276 for sig in &expected.signatures {
277 assert!(offered_sigs.contains(sig),);
278 }
279 }
280 tested_policies += 1;
281 }
282
283 // This test is a bit "fuzzy" because the security policy might not support
284 // our cert, etc. So just assert that we tested on a decent number of security
285 // policies
286 assert!(tested_policies > 100);
287 }
288
289 /// the list of supported protocol versions is not directly contained in the
290 /// security policy so instead use a number of known security policies.
291 #[test]
292 fn expected_protocol_version() {
293 let test_cases = vec![
294 // only TLS 1.3 - we should correctly ignore the fake "TLS 1.2" value in
295 // the ClientHello `protocol_version` field.
296 ("AWS-CRT-SDK-TLSv1.3-2023", vec![Version::TLS_1_3]),
297 // TLS 1.3 -> TLS 1.0
298 (
299 "20190802",
300 vec![
301 Version::TLS_1_3,
302 Version::TLS_1_2,
303 Version::TLS_1_1,
304 Version::TLS_1_0,
305 ],
306 ),
307 // TLS 1.2 -> TLS 1.0 - we only report the one value because the
308 // supported_versions extension isn't present
309 ("20190214", vec![Version::TLS_1_2]),
310 ];
311
312 for (policy, expected_result) in test_cases {
313 let policy = Policy::from_version(policy).unwrap();
314 let connection = server_connection(&policy);
315 let client_hello = connection.client_hello().unwrap();
316 let supported_parameters = ClientHelloSupportedParameters::new(client_hello).unwrap();
317 assert_eq!(
318 supported_parameters.supported_versions(),
319 expected_result.as_slice()
320 );
321 }
322 }
323 }