Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls/src/events.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 std::{ffi::CStr, fmt::Debug, time::Duration};
5
6 use crate::connection::Connection;
7
8 pub struct HandshakeEvent<'a>(&'a s2n_tls_sys::s2n_event_handshake);
9
10 /// The outcome of a handshake: either success with negotiated parameters,
11 /// or failure with error information.
12 pub enum HandshakeResult<'a> {
13 Success(HandshakeSuccess<'a>),
14 Failure(HandshakeFailure<'a>),
15 }
16
17 /// Negotiated parameters available after a successful handshake.
18 pub struct HandshakeSuccess<'a>(&'a s2n_tls_sys::s2n_event_handshake);
19
20 /// Error information available after a failed handshake.
21 pub struct HandshakeFailure<'a>(&'a s2n_tls_sys::s2n_event_handshake);
22
23 impl<'a> HandshakeEvent<'a> {
24 pub(crate) fn new(event: &'a s2n_tls_sys::s2n_event_handshake) -> Self {
25 Self(event)
26 }
27
28 /// The security policy label for the connection.
29 pub fn security_policy_label(&self) -> &'static str {
30 maybe_string(self.0.security_policy_label).unwrap_or("unknown")
31 }
32
33 /// Handshake duration, which includes network latency and waiting for the peer.
34 pub fn duration(&self) -> Duration {
35 Duration::from_nanos(self.0.handshake_end_ns - self.0.handshake_start_ns)
36 }
37
38 /// Handshake time, which is just the amount of time synchronously spent in s2n_negotiate.
39 ///
40 /// This is roughly the "cpu cost" of the handshake.
41 pub fn synchronous_time(&self) -> Duration {
42 Duration::from_nanos(self.0.handshake_time_ns)
43 }
44
45 /// Returns the outcome of the handshake, providing access to either the
46 /// negotiated parameters (on success) or error information (on failure).
47 pub fn result(&self) -> HandshakeResult<'a> {
48 if self.0.error_code == 0 {
49 HandshakeResult::Success(HandshakeSuccess(self.0))
50 } else {
51 HandshakeResult::Failure(HandshakeFailure(self.0))
52 }
53 }
54
55 #[deprecated(note = "will be removed with the release of subscriber 0.0.5")]
56 pub fn protocol_version(&self) -> crate::enums::Version {
57 HandshakeSuccess(self.0).protocol_version()
58 }
59
60 #[deprecated(note = "will be removed with the release of subscriber 0.0.5")]
61 pub fn cipher(&self) -> &'static str {
62 HandshakeSuccess(self.0).cipher()
63 }
64
65 #[deprecated(note = "will be removed with the release of subscriber 0.0.5")]
66 pub fn group(&self) -> Option<&'static str> {
67 HandshakeSuccess(self.0).group()
68 }
69 }
70
71 impl HandshakeSuccess<'_> {
72 /// Return the negotiated protocol version on the connection.
73 pub fn protocol_version(&self) -> crate::enums::Version {
74 self.0.protocol_version.try_into().unwrap()
75 }
76
77 /// The negotiated cipher, in IANA format.
78 pub fn cipher(&self) -> &'static str {
79 maybe_string(self.0.cipher).unwrap()
80 }
81
82 /// The negotiated key exchange group, in IANA format.
83 ///
84 /// None in the case of RSA key exchange or TLS 1.2 session resumption.
85 pub fn group(&self) -> Option<&'static str> {
86 let group = maybe_string(self.0.group)?;
87 if group == "NONE" {
88 None
89 } else {
90 Some(group)
91 }
92 }
93 }
94
95 impl HandshakeFailure<'_> {
96 /// The s2n error code for the handshake failure.
97 pub fn error_code(&self) -> i32 {
98 self.0.error_code
99 }
100 }
101
102 impl Debug for HandshakeEvent<'_> {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 let mut s = f.debug_struct("HandshakeEvent");
105 s.field("security_policy_label", &self.security_policy_label())
106 .field("duration", &self.duration())
107 .field("synchronous_time", &self.synchronous_time());
108 match self.result() {
109 HandshakeResult::Success(success) => {
110 s.field("protocol_version", &success.protocol_version())
111 .field("cipher", &success.cipher())
112 .field("group", &success.group());
113 }
114 HandshakeResult::Failure(failure) => {
115 s.field("error_code", &failure.error_code());
116 }
117 }
118 s.finish()
119 }
120 }
121
122 fn maybe_string(string: *const libc::c_char) -> Option<&'static str> {
123 if string.is_null() {
124 None
125 } else {
126 unsafe { CStr::from_ptr(string).to_str().ok() }
127 }
128 }
129
130 impl<A: EventSubscriber, B: EventSubscriber> EventSubscriber for (A, B) {
131 fn on_handshake_event(&self, connection: &Connection, event: &HandshakeEvent) {
132 self.0.on_handshake_event(connection, event);
133 self.1.on_handshake_event(connection, event);
134 }
135 }
136
137 pub trait EventSubscriber: 'static + Send + Sync {
138 fn on_handshake_event(&self, connection: &Connection, event: &HandshakeEvent);
139 }
140
141 #[cfg(test)]
142 mod tests {
143 use futures_test::task::noop_waker;
144 use std::ffi::CStr;
145
146 use crate::{
147 enums::Version, error::Error as S2NError, security::DEFAULT_TLS13,
148 testing::LIFOSessionResumption,
149 };
150 use std::{
151 sync::{
152 atomic::{AtomicU64, Ordering},
153 Arc, Mutex,
154 },
155 task::Poll,
156 time::SystemTime,
157 };
158
159 use super::*;
160 use crate::{
161 security::{self, Policy},
162 testing::{build_config, config_builder, TestPair},
163 };
164
165 #[derive(Debug)]
166 struct ExpectedSuccess {
167 cipher: &'static str,
168 group: Option<&'static str>,
169 protocol: crate::enums::Version,
170 security_policy_label: &'static str,
171 }
172
173 #[derive(Debug, Default)]
174 pub struct TestSubscriber {
175 invoked: Arc<AtomicU64>,
176 expected: Arc<Mutex<Option<ExpectedSuccess>>>,
177 }
178
179 impl ExpectedSuccess {
180 fn assert_matches(&self, event: &HandshakeEvent) {
181 let success = match event.result() {
182 HandshakeResult::Success(s) => s,
183 HandshakeResult::Failure(_) => panic!("expected success, got failure"),
184 };
185 assert_eq!(self.cipher, success.cipher());
186 assert_eq!(self.group, success.group());
187 assert_eq!(self.protocol, success.protocol_version());
188 assert_eq!(self.security_policy_label, event.security_policy_label());
189 }
190 }
191
192 impl TestSubscriber {
193 fn set_expected(&self, event: ExpectedSuccess) {
194 *self.expected.lock().unwrap() = Some(event);
195 }
196 }
197
198 impl EventSubscriber for TestSubscriber {
199 fn on_handshake_event(&self, _conn: &Connection, event: &HandshakeEvent) {
200 assert!(event.synchronous_time() <= event.duration());
201 let expected = self.expected.lock().unwrap();
202 if let Some(expected) = expected.as_ref() {
203 expected.assert_matches(event);
204 }
205 self.invoked
206 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
207 }
208 }
209
210 #[test]
211 fn tls13_handshake() -> Result<(), S2NError> {
212 const EXPECTED: ExpectedSuccess = ExpectedSuccess {
213 cipher: "TLS_AES_128_GCM_SHA256",
214 group: Some("X25519MLKEM768"),
215 protocol: Version::TLS13,
216 security_policy_label: "default",
217 };
218
219 let subscriber = TestSubscriber::default();
220 let invoked = subscriber.invoked.clone();
221 subscriber.set_expected(EXPECTED);
222
223 let server_config = {
224 let mut builder = config_builder(&security::DEFAULT).unwrap();
225 builder
226 .set_event_subscriber(subscriber)?
227 .add_session_ticket_key(
228 b"a key name",
229 b"good enough bytes for test",
230 SystemTime::UNIX_EPOCH,
231 )?;
232 builder.build()?
233 };
234
235 let client_config = {
236 let session_tickets = LIFOSessionResumption::default();
237 let mut builder = config_builder(&security::DEFAULT).unwrap();
238 builder.enable_session_tickets(true)?;
239 builder.set_session_ticket_callback(session_tickets.clone())?;
240 builder.set_connection_initializer(session_tickets.clone())?;
241 builder.build()?
242 };
243
244 // full handshake
245 {
246 let mut test_pair = TestPair::from_configs(&client_config, &server_config);
247 test_pair.client.set_waker(Some(&noop_waker()))?;
248 test_pair.handshake().unwrap();
249 // read in session_ticket
250 assert!(test_pair.client.poll_recv(&mut [0]).is_pending());
251 assert_eq!(invoked.load(Ordering::Relaxed), 1);
252 }
253
254 // session resumption: group is still populated
255 {
256 let mut test_pair = TestPair::from_configs(&client_config, &server_config);
257 test_pair.client.set_waker(Some(&noop_waker()))?;
258 test_pair.handshake().unwrap();
259 assert!(test_pair.client.resumed());
260 assert_eq!(invoked.load(Ordering::Relaxed), 2);
261 }
262
263 Ok(())
264 }
265
266 /// When RSA key exchange is negotiated, the group is not recorded in the event
267 #[test]
268 fn rsa_key_exchange() -> Result<(), S2NError> {
269 const EXPECTED: ExpectedSuccess = ExpectedSuccess {
270 cipher: "AES128-SHA256",
271 group: None,
272 protocol: Version::TLS12,
273 security_policy_label: "20140601",
274 };
275 // 20140601 only support DHE and RSA kx. We don't load any DHE params, so
276 // it only supports RSA kx.
277 let rsa_kx_policy = Policy::from_version("20140601")?;
278
279 let subscriber = TestSubscriber::default();
280 let invoked = subscriber.invoked.clone();
281 subscriber.set_expected(EXPECTED);
282
283 let server_config = {
284 let mut builder = config_builder(&rsa_kx_policy).unwrap();
285 builder.set_event_subscriber(subscriber)?;
286 builder.build()?
287 };
288 let client_config = build_config(&rsa_kx_policy).unwrap();
289
290 // full handshake
291 let mut test_pair = TestPair::from_configs(&client_config, &server_config);
292 test_pair.client.set_waker(Some(&noop_waker()))?;
293 test_pair.handshake().unwrap();
294 assert_eq!(invoked.load(Ordering::Relaxed), 1);
295
296 Ok(())
297 }
298
299 #[test]
300 fn tls12_handshake() -> Result<(), S2NError> {
301 const FULL_HS: ExpectedSuccess = ExpectedSuccess {
302 cipher: "ECDHE-RSA-AES128-GCM-SHA256",
303 group: Some("secp256r1"),
304 protocol: Version::TLS12,
305 security_policy_label: "ELBSecurityPolicy-TLS-1-0-2015-04",
306 };
307 const RESUMPTION: ExpectedSuccess = ExpectedSuccess {
308 cipher: "ECDHE-RSA-AES128-GCM-SHA256",
309 group: None,
310 protocol: Version::TLS12,
311 security_policy_label: "ELBSecurityPolicy-TLS-1-0-2015-04",
312 };
313
314 let subscriber = TestSubscriber::default();
315 let invoked = subscriber.invoked.clone();
316 let expected = subscriber.expected.clone();
317 // arbitrary policy which only allows TLS 1.2 and supports ECDHE
318 let tls12_ecdhe_policy = Policy::from_version("ELBSecurityPolicy-TLS-1-0-2015-04")?;
319
320 let server_config = {
321 let mut builder = config_builder(&tls12_ecdhe_policy).unwrap();
322 builder
323 .set_event_subscriber(subscriber)?
324 .add_session_ticket_key(
325 b"a key name",
326 b"good enough bytes for test",
327 SystemTime::UNIX_EPOCH,
328 )?
329 .enable_session_tickets(true)?;
330 builder.build()?
331 };
332
333 let client_config = {
334 let session_tickets = LIFOSessionResumption::default();
335 let mut builder = config_builder(&tls12_ecdhe_policy).unwrap();
336 builder.enable_session_tickets(true)?;
337 builder.set_session_ticket_callback(session_tickets.clone())?;
338 builder.set_connection_initializer(session_tickets.clone())?;
339 builder.build()?
340 };
341
342 // full handshake: ECDHE negotiated, so group is recorded
343 *expected.lock().unwrap() = Some(FULL_HS);
344 {
345 let mut test_pair = TestPair::from_configs(&client_config, &server_config);
346 test_pair.client.set_waker(Some(&noop_waker()))?;
347 test_pair.handshake().unwrap();
348 assert_eq!(invoked.load(Ordering::Relaxed), 1);
349 }
350
351 // session resumption: there is no additional ECDHE in TLS 1.2 session
352 // resumption, so no group is recorded.
353 *expected.lock().unwrap() = Some(RESUMPTION);
354 {
355 let mut test_pair = TestPair::from_configs(&client_config, &server_config);
356 test_pair.client.set_waker(Some(&noop_waker()))?;
357 test_pair.handshake().unwrap();
358 assert!(test_pair.client.resumed());
359 assert_eq!(invoked.load(Ordering::Relaxed), 2);
360 }
361
362 Ok(())
363 }
364
365 /// handshake events are emitted from both servers and clients, and they are
366 /// only emitted once per handshake event if s2n_negotiate is called multiple
367 /// times.
368 #[test]
369 fn client_and_server_event() -> Result<(), S2NError> {
370 let subscriber = TestSubscriber::default();
371 let invoked = subscriber.invoked.clone();
372
373 let subscriber_config = {
374 let mut builder = config_builder(&security::DEFAULT).unwrap();
375 builder.set_event_subscriber(subscriber)?;
376 builder.build()?
377 };
378
379 let mut pair = TestPair::from_config(&subscriber_config);
380 pair.handshake().unwrap();
381 assert_eq!(invoked.load(Ordering::Relaxed), 2);
382
383 // idempotency: calling s2n_negotiate multiple times will not send multiple
384 // events
385 assert!(pair.server.poll_negotiate().is_ready());
386 assert!(pair.server.poll_negotiate().is_ready());
387 assert_eq!(invoked.load(Ordering::Relaxed), 2);
388
389 Ok(())
390 }
391
392 /// A handshake event is emitted in the case of failure, with error information.
393 #[test]
394 fn failure_event() -> Result<(), S2NError> {
395 #[derive(Debug, Default)]
396 struct TestErrorSubscriber {
397 error_code: Arc<Mutex<Option<i32>>>,
398 }
399
400 impl EventSubscriber for TestErrorSubscriber {
401 fn on_handshake_event(&self, _conn: &Connection, event: &HandshakeEvent) {
402 if let HandshakeResult::Failure(failure) = event.result() {
403 *self.error_code.lock().unwrap() = Some(failure.error_code());
404 }
405 }
406 }
407
408 let subscriber = TestErrorSubscriber::default();
409 let error_code = subscriber.error_code.clone();
410
411 let server_config = {
412 // doesn't allow TLS 1.3
413 let mut builder = config_builder(&Policy::from_version("20141001")?).unwrap();
414 builder.set_event_subscriber(subscriber)?;
415 builder.build()?
416 };
417
418 // only allows TLS 1.3
419 let client_config = build_config(&DEFAULT_TLS13).unwrap();
420
421 let mut pair = TestPair::from_configs(&client_config, &server_config);
422 // Drive the client first to send the ClientHello, then the server
423 // to process it and fail.
424 pair.server.set_waker(Some(&noop_waker()))?;
425 let _ = pair.client.poll_negotiate();
426 let server_err = match pair.server.poll_negotiate() {
427 Poll::Ready(Err(e)) => e,
428 other => panic!("expected server failure, got {:?}", other),
429 };
430
431 let code = error_code
432 .lock()
433 .unwrap()
434 .expect("failure event was emitted");
435 let event_error_name = unsafe {
436 CStr::from_ptr(s2n_tls_sys::s2n_strerror_name(code))
437 .to_str()
438 .unwrap()
439 };
440 assert_eq!(event_error_name, server_err.name());
441
442 Ok(())
443 }
444 }