s2n-tls 0.3.38

A C99 implementation of the TLS/SSL protocols
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::{ffi::CStr, fmt::Debug, time::Duration};

use crate::connection::Connection;

pub struct HandshakeEvent<'a>(&'a s2n_tls_sys::s2n_event_handshake);

/// The outcome of a handshake: either success with negotiated parameters,
/// or failure with error information.
pub enum HandshakeResult<'a> {
    Success(HandshakeSuccess<'a>),
    Failure(HandshakeFailure<'a>),
}

/// Negotiated parameters available after a successful handshake.
pub struct HandshakeSuccess<'a>(&'a s2n_tls_sys::s2n_event_handshake);

/// Error information available after a failed handshake.
pub struct HandshakeFailure<'a>(&'a s2n_tls_sys::s2n_event_handshake);

impl<'a> HandshakeEvent<'a> {
    pub(crate) fn new(event: &'a s2n_tls_sys::s2n_event_handshake) -> Self {
        Self(event)
    }

    /// The security policy label for the connection.
    pub fn security_policy_label(&self) -> &'static str {
        maybe_string(self.0.security_policy_label).unwrap_or("unknown")
    }

    /// Handshake duration, which includes network latency and waiting for the peer.
    pub fn duration(&self) -> Duration {
        Duration::from_nanos(self.0.handshake_end_ns - self.0.handshake_start_ns)
    }

    /// Handshake time, which is just the amount of time synchronously spent in s2n_negotiate.
    ///
    /// This is roughly the "cpu cost" of the handshake.
    pub fn synchronous_time(&self) -> Duration {
        Duration::from_nanos(self.0.handshake_time_ns)
    }

    /// Returns the outcome of the handshake, providing access to either the
    /// negotiated parameters (on success) or error information (on failure).
    pub fn result(&self) -> HandshakeResult<'a> {
        if self.0.error_code == 0 {
            HandshakeResult::Success(HandshakeSuccess(self.0))
        } else {
            HandshakeResult::Failure(HandshakeFailure(self.0))
        }
    }
}

impl HandshakeSuccess<'_> {
    /// Return the negotiated protocol version on the connection.
    pub fn protocol_version(&self) -> crate::enums::Version {
        self.0.protocol_version.try_into().unwrap()
    }

    /// The negotiated cipher, in IANA format.
    pub fn cipher(&self) -> &'static str {
        maybe_string(self.0.cipher).unwrap()
    }

    /// The negotiated key exchange group, in IANA format.
    ///
    /// None in the case of RSA key exchange or TLS 1.2 session resumption.
    pub fn group(&self) -> Option<&'static str> {
        let group = maybe_string(self.0.group)?;
        if group == "NONE" {
            None
        } else {
            Some(group)
        }
    }
}

impl HandshakeFailure<'_> {
    /// The s2n error code for the handshake failure.
    pub fn error_code(&self) -> i32 {
        self.0.error_code
    }
}

impl Debug for HandshakeEvent<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("HandshakeEvent");
        s.field("security_policy_label", &self.security_policy_label())
            .field("duration", &self.duration())
            .field("synchronous_time", &self.synchronous_time());
        match self.result() {
            HandshakeResult::Success(success) => {
                s.field("protocol_version", &success.protocol_version())
                    .field("cipher", &success.cipher())
                    .field("group", &success.group());
            }
            HandshakeResult::Failure(failure) => {
                s.field("error_code", &failure.error_code());
            }
        }
        s.finish()
    }
}

fn maybe_string(string: *const libc::c_char) -> Option<&'static str> {
    if string.is_null() {
        None
    } else {
        unsafe { CStr::from_ptr(string).to_str().ok() }
    }
}

impl<A: EventSubscriber, B: EventSubscriber> EventSubscriber for (A, B) {
    fn on_handshake_event(&self, connection: &Connection, event: &HandshakeEvent) {
        self.0.on_handshake_event(connection, event);
        self.1.on_handshake_event(connection, event);
    }
}

pub trait EventSubscriber: 'static + Send + Sync {
    fn on_handshake_event(&self, connection: &Connection, event: &HandshakeEvent);
}

#[cfg(test)]
mod tests {
    use futures_test::task::noop_waker;
    use std::ffi::CStr;

    use crate::{
        enums::Version, error::Error as S2NError, security::DEFAULT_TLS13,
        testing::LIFOSessionResumption,
    };
    use std::{
        sync::{
            atomic::{AtomicU64, Ordering},
            Arc, Mutex,
        },
        task::Poll,
        time::SystemTime,
    };

    use super::*;
    use crate::{
        security::{self, Policy},
        testing::{build_config, config_builder, TestPair},
    };

    #[derive(Debug)]
    struct ExpectedSuccess {
        cipher: &'static str,
        group: Option<&'static str>,
        protocol: crate::enums::Version,
        security_policy_label: &'static str,
    }

    #[derive(Debug, Default)]
    pub struct TestSubscriber {
        invoked: Arc<AtomicU64>,
        expected: Arc<Mutex<Option<ExpectedSuccess>>>,
    }

    impl ExpectedSuccess {
        fn assert_matches(&self, event: &HandshakeEvent) {
            let success = match event.result() {
                HandshakeResult::Success(s) => s,
                HandshakeResult::Failure(_) => panic!("expected success, got failure"),
            };
            assert_eq!(self.cipher, success.cipher());
            assert_eq!(self.group, success.group());
            assert_eq!(self.protocol, success.protocol_version());
            assert_eq!(self.security_policy_label, event.security_policy_label());
        }
    }

    impl TestSubscriber {
        fn set_expected(&self, event: ExpectedSuccess) {
            *self.expected.lock().unwrap() = Some(event);
        }
    }

    impl EventSubscriber for TestSubscriber {
        fn on_handshake_event(&self, _conn: &Connection, event: &HandshakeEvent) {
            assert!(event.synchronous_time() <= event.duration());
            let expected = self.expected.lock().unwrap();
            if let Some(expected) = expected.as_ref() {
                expected.assert_matches(event);
            }
            self.invoked
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
    }

    #[test]
    fn tls13_handshake() -> Result<(), S2NError> {
        const EXPECTED: ExpectedSuccess = ExpectedSuccess {
            cipher: "TLS_AES_128_GCM_SHA256",
            group: Some("X25519MLKEM768"),
            protocol: Version::TLS13,
            security_policy_label: "default",
        };

        let subscriber = TestSubscriber::default();
        let invoked = subscriber.invoked.clone();
        subscriber.set_expected(EXPECTED);

        let server_config = {
            let mut builder = config_builder(&security::DEFAULT).unwrap();
            builder
                .set_event_subscriber(subscriber)?
                .add_session_ticket_key(
                    b"a key name",
                    b"good enough bytes for test",
                    SystemTime::UNIX_EPOCH,
                )?;
            builder.build()?
        };

        let client_config = {
            let session_tickets = LIFOSessionResumption::default();
            let mut builder = config_builder(&security::DEFAULT).unwrap();
            builder.enable_session_tickets(true)?;
            builder.set_session_ticket_callback(session_tickets.clone())?;
            builder.set_connection_initializer(session_tickets.clone())?;
            builder.build()?
        };

        // full handshake
        {
            let mut test_pair = TestPair::from_configs(&client_config, &server_config);
            test_pair.client.set_waker(Some(&noop_waker()))?;
            test_pair.handshake().unwrap();
            // read in session_ticket
            assert!(test_pair.client.poll_recv(&mut [0]).is_pending());
            assert_eq!(invoked.load(Ordering::Relaxed), 1);
        }

        // session resumption: group is still populated
        {
            let mut test_pair = TestPair::from_configs(&client_config, &server_config);
            test_pair.client.set_waker(Some(&noop_waker()))?;
            test_pair.handshake().unwrap();
            assert!(test_pair.client.resumed());
            assert_eq!(invoked.load(Ordering::Relaxed), 2);
        }

        Ok(())
    }

    /// When RSA key exchange is negotiated, the group is not recorded in the event
    #[test]
    fn rsa_key_exchange() -> Result<(), S2NError> {
        const EXPECTED: ExpectedSuccess = ExpectedSuccess {
            cipher: "AES128-SHA256",
            group: None,
            protocol: Version::TLS12,
            security_policy_label: "20140601",
        };
        // 20140601 only support DHE and RSA kx. We don't load any DHE params, so
        // it only supports RSA kx.
        let rsa_kx_policy = Policy::from_version("20140601")?;

        let subscriber = TestSubscriber::default();
        let invoked = subscriber.invoked.clone();
        subscriber.set_expected(EXPECTED);

        let server_config = {
            let mut builder = config_builder(&rsa_kx_policy).unwrap();
            builder.set_event_subscriber(subscriber)?;
            builder.build()?
        };
        let client_config = build_config(&rsa_kx_policy).unwrap();

        // full handshake
        let mut test_pair = TestPair::from_configs(&client_config, &server_config);
        test_pair.client.set_waker(Some(&noop_waker()))?;
        test_pair.handshake().unwrap();
        assert_eq!(invoked.load(Ordering::Relaxed), 1);

        Ok(())
    }

    #[test]
    fn tls12_handshake() -> Result<(), S2NError> {
        const FULL_HS: ExpectedSuccess = ExpectedSuccess {
            cipher: "ECDHE-RSA-AES128-GCM-SHA256",
            group: Some("secp256r1"),
            protocol: Version::TLS12,
            security_policy_label: "ELBSecurityPolicy-TLS-1-0-2015-04",
        };
        const RESUMPTION: ExpectedSuccess = ExpectedSuccess {
            cipher: "ECDHE-RSA-AES128-GCM-SHA256",
            group: None,
            protocol: Version::TLS12,
            security_policy_label: "ELBSecurityPolicy-TLS-1-0-2015-04",
        };

        let subscriber = TestSubscriber::default();
        let invoked = subscriber.invoked.clone();
        let expected = subscriber.expected.clone();
        // arbitrary policy which only allows TLS 1.2 and supports ECDHE
        let tls12_ecdhe_policy = Policy::from_version("ELBSecurityPolicy-TLS-1-0-2015-04")?;

        let server_config = {
            let mut builder = config_builder(&tls12_ecdhe_policy).unwrap();
            builder
                .set_event_subscriber(subscriber)?
                .add_session_ticket_key(
                    b"a key name",
                    b"good enough bytes for test",
                    SystemTime::UNIX_EPOCH,
                )?
                .enable_session_tickets(true)?;
            builder.build()?
        };

        let client_config = {
            let session_tickets = LIFOSessionResumption::default();
            let mut builder = config_builder(&tls12_ecdhe_policy).unwrap();
            builder.enable_session_tickets(true)?;
            builder.set_session_ticket_callback(session_tickets.clone())?;
            builder.set_connection_initializer(session_tickets.clone())?;
            builder.build()?
        };

        // full handshake: ECDHE negotiated, so group is recorded
        *expected.lock().unwrap() = Some(FULL_HS);
        {
            let mut test_pair = TestPair::from_configs(&client_config, &server_config);
            test_pair.client.set_waker(Some(&noop_waker()))?;
            test_pair.handshake().unwrap();
            assert_eq!(invoked.load(Ordering::Relaxed), 1);
        }

        // session resumption: there is no additional ECDHE in TLS 1.2 session
        // resumption, so no group is recorded.
        *expected.lock().unwrap() = Some(RESUMPTION);
        {
            let mut test_pair = TestPair::from_configs(&client_config, &server_config);
            test_pair.client.set_waker(Some(&noop_waker()))?;
            test_pair.handshake().unwrap();
            assert!(test_pair.client.resumed());
            assert_eq!(invoked.load(Ordering::Relaxed), 2);
        }

        Ok(())
    }

    /// handshake events are emitted from both servers and clients, and they are
    /// only emitted once per handshake event if s2n_negotiate is called multiple
    /// times.
    #[test]
    fn client_and_server_event() -> Result<(), S2NError> {
        let subscriber = TestSubscriber::default();
        let invoked = subscriber.invoked.clone();

        let subscriber_config = {
            let mut builder = config_builder(&security::DEFAULT).unwrap();
            builder.set_event_subscriber(subscriber)?;
            builder.build()?
        };

        let mut pair = TestPair::from_config(&subscriber_config);
        pair.handshake().unwrap();
        assert_eq!(invoked.load(Ordering::Relaxed), 2);

        // idempotency: calling s2n_negotiate multiple times will not send multiple
        // events
        assert!(pair.server.poll_negotiate().is_ready());
        assert!(pair.server.poll_negotiate().is_ready());
        assert_eq!(invoked.load(Ordering::Relaxed), 2);

        Ok(())
    }

    /// A handshake event is emitted in the case of failure, with error information.
    #[test]
    fn failure_event() -> Result<(), S2NError> {
        #[derive(Debug, Default)]
        struct TestErrorSubscriber {
            error_code: Arc<Mutex<Option<i32>>>,
        }

        impl EventSubscriber for TestErrorSubscriber {
            fn on_handshake_event(&self, _conn: &Connection, event: &HandshakeEvent) {
                if let HandshakeResult::Failure(failure) = event.result() {
                    *self.error_code.lock().unwrap() = Some(failure.error_code());
                }
            }
        }

        let subscriber = TestErrorSubscriber::default();
        let error_code = subscriber.error_code.clone();

        let server_config = {
            // doesn't allow TLS 1.3
            let mut builder = config_builder(&Policy::from_version("20141001")?).unwrap();
            builder.set_event_subscriber(subscriber)?;
            builder.build()?
        };

        // only allows TLS 1.3
        let client_config = build_config(&DEFAULT_TLS13).unwrap();

        let mut pair = TestPair::from_configs(&client_config, &server_config);
        // Drive the client first to send the ClientHello, then the server
        // to process it and fail.
        pair.server.set_waker(Some(&noop_waker()))?;
        let _ = pair.client.poll_negotiate();
        let server_err = match pair.server.poll_negotiate() {
            Poll::Ready(Err(e)) => e,
            other => panic!("expected server failure, got {:?}", other),
        };

        let code = error_code
            .lock()
            .unwrap()
            .expect("failure event was emitted");
        let event_error_name = unsafe {
            CStr::from_ptr(s2n_tls_sys::s2n_strerror_name(code))
                .to_str()
                .unwrap()
        };
        assert_eq!(event_error_name, server_err.name());

        Ok(())
    }
}