Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls/src/connection.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 #![allow(clippy::missing_safety_doc)] // TODO add safety docs
5
6 #[cfg(feature = "unstable-cert_authorities")]
7 use crate::cert_authorities::CertRequestState;
8 #[cfg(feature = "unstable-renegotiate")]
9 use crate::renegotiate::RenegotiateState;
10 use crate::{
11 callbacks::*,
12 cert_chain::{CertificateChain, CertificateChainHandle},
13 config::Config,
14 enums::*,
15 error::{Error, Fallible, Pollable},
16 psk::Psk,
17 security,
18 utilities::cstr_to_str,
19 };
20
21 use core::{
22 convert::TryInto,
23 fmt,
24 mem::{self, ManuallyDrop, MaybeUninit},
25 pin::Pin,
26 ptr::NonNull,
27 task::{Poll, Waker},
28 time::Duration,
29 };
30 use libc::c_void;
31 use s2n_tls_sys::*;
32 use std::{
33 any::{Any, TypeId},
34 collections::HashMap,
35 ffi::CStr,
36 };
37
38 mod builder;
39 pub use builder::*;
40
41 /// return a &str scoped to the lifetime of the surrounding function
42 ///
43 /// SAFETY: must be called on a null terminated string
44 ///
45 /// SAFETY: the underlying data must live at least as long as the surrounding scope
46 // We use a macro instead of a function so that the lifetime of the output is
47 // automatically inferred to match the surrounding scope.
48 macro_rules! const_str {
49 ($c_chars:expr) => {
50 CStr::from_ptr($c_chars)
51 .to_str()
52 .map_err(|_| Error::INVALID_INPUT)
53 };
54 }
55
56 #[non_exhaustive]
57 #[derive(Debug, PartialEq)]
58 /// s2n-tls only tracks up to u8::MAX (255) key updates. If any of the fields show
59 /// 255 updates, then more than 255 updates may have occurred.
60 pub struct KeyUpdateCount {
61 pub send_key_updates: u8,
62 pub recv_key_updates: u8,
63 }
64
65 /// Corresponds to [`s2n_connection`].
66 pub struct Connection {
67 connection: NonNull<s2n_connection>,
68 }
69
70 impl fmt::Debug for Connection {
71 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72 let mut debug = f.debug_struct("Connection");
73 if let Ok(handshake) = self.handshake_type() {
74 debug.field("handshake_type", &handshake);
75 }
76 if let Ok(cipher) = self.cipher_suite() {
77 debug.field("cipher_suite", &cipher);
78 }
79 if let Ok(version) = self.actual_protocol_version() {
80 debug.field("actual_protocol_version", &version);
81 }
82 if let Some(group_name) = self.selected_key_exchange_group() {
83 debug.field("selected_key_exchange_group", &group_name);
84 }
85 debug.finish_non_exhaustive()
86 }
87 }
88
89 /// # Safety
90 ///
91 /// s2n_connection objects can be sent across threads
92 unsafe impl Send for Connection {}
93
94 /// # Sync
95 ///
96 /// Although NonNull isn't Sync and allows access to mutable pointers even from
97 /// immutable references, the Connection interface enforces that all mutating
98 /// methods correctly require &mut self.
99 ///
100 /// Developers and reviewers MUST ensure that new methods correctly use
101 /// either &self or &mut self depending on their behavior. No mechanism enforces this.
102 ///
103 /// Note: Although non-mutating methods like getters should be thread-safe by definition,
104 /// technically the only thread safety guarantee provided by the underlying C library
105 /// is that s2n_send and s2n_recv can be called concurrently.
106 ///
107 unsafe impl Sync for Connection {}
108
109 impl Connection {
110 /// # Warning
111 ///
112 /// The newly created connection uses the default security policy.
113 /// Consider changing this depending on your security and compatibility requirements
114 /// by calling [`Connection::set_security_policy`].
115 /// Alternatively, you can use [`crate::config::Builder`], [`crate::config::Builder::set_security_policy`],
116 /// and [`Connection::set_config`] to set the policy on the Config instead of on the Connection.
117 /// See the s2n-tls usage guide:
118 /// <https://aws.github.io/s2n-tls/usage-guide/ch06-security-policies.html>
119 ///
120 /// Corresponds to [`s2n_connection_new`].
121 pub fn new(mode: Mode) -> Self {
122 crate::init::init();
123
124 let connection = unsafe { s2n_connection_new(mode.into()).into_result() }.unwrap();
125
126 unsafe {
127 debug_assert! {
128 s2n_connection_get_config(connection.as_ptr(), &mut core::ptr::null_mut())
129 .into_result()
130 .is_err()
131 }
132 }
133
134 let mut connection = Self { connection };
135 connection.init_context();
136 connection
137 }
138
139 fn init_context(&mut self) {
140 let context = Box::new(Context::new());
141 let context = Box::into_raw(context) as *mut c_void;
142 // allocate a new context object
143 unsafe {
144 // There should never be an existing context
145 debug_assert!(s2n_connection_get_ctx(self.connection.as_ptr())
146 .into_result()
147 .is_err());
148
149 s2n_connection_set_ctx(self.connection.as_ptr(), context)
150 .into_result()
151 .unwrap();
152 }
153 }
154
155 pub fn new_client() -> Self {
156 Self::new(Mode::Client)
157 }
158
159 pub fn new_server() -> Self {
160 Self::new(Mode::Server)
161 }
162
163 pub(crate) fn as_ptr(&mut self) -> *mut s2n_connection {
164 self.connection.as_ptr()
165 }
166
167 /// Returns the underlying `s2n_tls_sys::s2n_connection` pointer associated with the
168 /// `Connection`.
169 ///
170 /// #### Warning:
171 /// This API is unstable, and may be removed in a future s2n-tls release. Applications should
172 /// use the higher level s2n-tls bindings rather than calling the low-level `s2n_tls_sys` APIs
173 /// directly.
174 #[cfg(s2n_tls_external_build)]
175 pub fn unstable_as_ptr(&mut self) -> *mut s2n_connection {
176 self.as_ptr()
177 }
178
179 /// # Safety
180 ///
181 /// Caller must ensure s2n_connection is a valid reference to a [`s2n_connection`] object
182 pub(crate) unsafe fn from_raw(connection: NonNull<s2n_connection>) -> Self {
183 Self { connection }
184 }
185
186 /// Returns the mode (client or server) of this connection.
187 ///
188 /// Corresponds to [`s2n_connection_get_mode`].
189 pub fn mode(&self) -> Mode {
190 let mode = unsafe { s2n_connection_get_mode(self.connection.as_ptr()) };
191 mode.try_into().unwrap()
192 }
193
194 /// can be used to configure s2n to either use built-in blinding (set blinding
195 /// to Blinding::BuiltIn) or self-service blinding (set blinding to
196 /// Blinding::SelfService).
197 ///
198 /// Corresponds to [`s2n_connection_set_blinding`].
199 pub fn set_blinding(&mut self, blinding: Blinding) -> Result<&mut Self, Error> {
200 unsafe {
201 s2n_connection_set_blinding(self.connection.as_ptr(), blinding.into()).into_result()
202 }?;
203 Ok(self)
204 }
205
206 /// Reports the remaining nanoseconds before the connection may be gracefully shutdown.
207 ///
208 /// This method is expected to succeed, but could fail if the
209 /// [underlying C call](`s2n_connection_get_delay`) encounters errors.
210 /// Failure indicates that calls to [`Self::poll_shutdown`] will also fail and
211 /// that a graceful two-way shutdown of the connection will not be possible.
212 ///
213 /// Corresponds to [`s2n_connection_get_delay`].
214 pub fn remaining_blinding_delay(&self) -> Result<Duration, Error> {
215 let nanos = unsafe { s2n_connection_get_delay(self.connection.as_ptr()).into_result() }?;
216 Ok(Duration::from_nanos(nanos))
217 }
218
219 /// Sets whether or not a Client Certificate should be required to complete the TLS Connection.
220 ///
221 /// If this is set to ClientAuthType::Optional the server will request a client certificate
222 /// but allow the client to not provide one. Rejecting a client certificate when using
223 /// ClientAuthType::Optional will terminate the handshake.
224 ///
225 /// Corresponds to [`s2n_connection_set_client_auth_type`].
226 pub fn set_client_auth_type(
227 &mut self,
228 client_auth_type: ClientAuthType,
229 ) -> Result<&mut Self, Error> {
230 unsafe {
231 s2n_connection_set_client_auth_type(self.connection.as_ptr(), client_auth_type.into())
232 .into_result()
233 }?;
234 Ok(self)
235 }
236
237 /// Attempts to drop the config on the connection.
238 ///
239 /// # Safety
240 ///
241 /// The caller must ensure the config associated with the connection was created
242 /// with a [`config::Builder`].
243 unsafe fn drop_config(&mut self) -> Result<(), Error> {
244 let mut prev_config = core::ptr::null_mut();
245
246 // A valid non-null pointer is returned only if the application previously called
247 // [`Self::set_config()`].
248 if s2n_connection_get_config(self.connection.as_ptr(), &mut prev_config)
249 .into_result()
250 .is_ok()
251 {
252 let prev_config = NonNull::new(prev_config).expect(
253 "config should exist since the call to s2n_connection_get_config was successful",
254 );
255 drop(Config::from_raw(prev_config));
256 }
257
258 Ok(())
259 }
260
261 /// Associates a configuration object with a connection.
262 ///
263 /// Corresponds to [`s2n_connection_set_config`].
264 pub fn set_config(&mut self, mut config: Config) -> Result<&mut Self, Error> {
265 unsafe {
266 // attempt to drop the currently set config
267 self.drop_config()?;
268
269 s2n_connection_set_config(self.connection.as_ptr(), config.as_mut_ptr())
270 .into_result()?;
271
272 debug_assert! {
273 s2n_connection_get_config(self.connection.as_ptr(), &mut core::ptr::null_mut()).into_result().is_ok(),
274 "s2n_connection_set_config was successful"
275 };
276
277 // Setting the config on the connection creates one additional reference to the config
278 // so do not drop so prevent Rust from calling `drop()` at the end of this function.
279 mem::forget(config);
280 }
281
282 Ok(self)
283 }
284
285 pub(crate) fn config(&self) -> Option<Config> {
286 let mut raw = core::ptr::null_mut();
287 let config = unsafe {
288 s2n_connection_get_config(self.connection.as_ptr(), &mut raw)
289 .into_result()
290 .ok()?;
291 let raw = NonNull::new(raw)?;
292 Config::from_raw(raw)
293 };
294 // Because the config pointer is still set on the connection, this is a copy,
295 // not the original config. This is fine -- Configs are immutable.
296 let _ = ManuallyDrop::new(config.clone());
297 Some(config)
298 }
299
300 /// Corresponds to [`s2n_connection_set_cipher_preferences`].
301 pub fn set_security_policy(&mut self, policy: &security::Policy) -> Result<&mut Self, Error> {
302 unsafe {
303 s2n_connection_set_cipher_preferences(
304 self.connection.as_ptr(),
305 policy.as_cstr().as_ptr(),
306 )
307 .into_result()
308 }?;
309 Ok(self)
310 }
311
312 /// provides a smooth transition from s2n_connection_prefer_low_latency to s2n_connection_prefer_throughput.
313 ///
314 /// s2n_send uses small TLS records that fit into a single TCP segment for the resize_threshold
315 /// bytes (cap to 8M) of data and reset record size back to a single segment after timeout_threshold
316 /// seconds of inactivity.
317 ///
318 /// Corresponds to [`s2n_connection_set_dynamic_record_threshold`].
319 pub fn set_dynamic_record_threshold(
320 &mut self,
321 resize_threshold: u32,
322 timeout_threshold: u16,
323 ) -> Result<&mut Self, Error> {
324 unsafe {
325 s2n_connection_set_dynamic_record_threshold(
326 self.connection.as_ptr(),
327 resize_threshold,
328 timeout_threshold,
329 )
330 .into_result()
331 }?;
332 Ok(self)
333 }
334
335 /// Signals the connection to do a key_update at the next possible opportunity.
336 /// Note that the resulting key update message will not be sent until `send` is
337 /// called on the connection.
338 ///
339 /// `peer_request` indicates if a key update should also be requested
340 /// of the peer. When set to `KeyUpdateNotRequested`, then only the sending
341 /// key of the connection will be updated. If set to `KeyUpdateRequested`, then
342 /// the sending key of conn will be updated AND the peer will be requested to
343 /// update their sending key. Note that s2n-tls currently only supports
344 /// `peer_request` being set to `KeyUpdateNotRequested` and will return an error
345 /// if any other value is used.
346 ///
347 /// Corresponds to [`s2n_connection_request_key_update`].
348 pub fn request_key_update(&mut self, peer_request: PeerKeyUpdate) -> Result<&mut Self, Error> {
349 unsafe {
350 s2n_connection_request_key_update(self.connection.as_ptr(), peer_request.into())
351 .into_result()
352 }?;
353 Ok(self)
354 }
355
356 /// Reports the number of times sending and receiving keys have been updated.
357 ///
358 /// This only applies to TLS1.3. Earlier versions do not support key updates.
359 ///
360 /// Corresponds to [`s2n_connection_get_key_update_counts`].
361 #[cfg(feature = "unstable-ktls")]
362 pub fn key_update_counts(&self) -> Result<KeyUpdateCount, Error> {
363 let mut send_key_updates = 0;
364 let mut recv_key_updates = 0;
365 unsafe {
366 s2n_connection_get_key_update_counts(
367 self.connection.as_ptr(),
368 &mut send_key_updates,
369 &mut recv_key_updates,
370 )
371 .into_result()?;
372 }
373 Ok(KeyUpdateCount {
374 send_key_updates,
375 recv_key_updates,
376 })
377 }
378
379 /// sets the application protocol preferences on an s2n_connection object.
380 ///
381 /// protocols is a list in order of preference, with most preferred protocol first, and of
382 /// length protocol_count. When acting as a client the protocol list is included in the
383 /// Client Hello message as the ALPN extension. As a server, the list is used to negotiate
384 /// a mutual application protocol with the client. After the negotiation for the connection has
385 /// completed, the agreed upon protocol can be retrieved with s2n_get_application_protocol
386 ///
387 /// Corresponds to [`s2n_connection_set_protocol_preferences`].
388 pub fn set_application_protocol_preference<P: IntoIterator<Item = I>, I: AsRef<[u8]>>(
389 &mut self,
390 protocols: P,
391 ) -> Result<&mut Self, Error> {
392 // reset the list
393 unsafe {
394 s2n_connection_set_protocol_preferences(self.connection.as_ptr(), core::ptr::null(), 0)
395 .into_result()
396 }?;
397
398 for protocol in protocols {
399 self.append_application_protocol_preference(protocol.as_ref())?;
400 }
401
402 Ok(self)
403 }
404
405 /// Corresponds to [`s2n_connection_append_protocol_preference`].
406 pub fn append_application_protocol_preference(
407 &mut self,
408 protocol: &[u8],
409 ) -> Result<&mut Self, Error> {
410 unsafe {
411 s2n_connection_append_protocol_preference(
412 self.connection.as_ptr(),
413 protocol.as_ptr(),
414 protocol
415 .len()
416 .try_into()
417 .map_err(|_| Error::INVALID_INPUT)?,
418 )
419 .into_result()
420 }?;
421 Ok(self)
422 }
423
424 /// may be used to receive data with callbacks defined by the user.
425 ///
426 /// Corresponds to [`s2n_connection_set_recv_cb`].
427 pub fn set_receive_callback(&mut self, callback: s2n_recv_fn) -> Result<&mut Self, Error> {
428 unsafe { s2n_connection_set_recv_cb(self.connection.as_ptr(), callback).into_result() }?;
429 Ok(self)
430 }
431
432 /// # Safety
433 ///
434 /// The `context` pointer must live at least as long as the connection
435 ///
436 /// Corresponds to [`s2n_connection_set_recv_ctx`].
437 pub unsafe fn set_receive_context(&mut self, context: *mut c_void) -> Result<&mut Self, Error> {
438 s2n_connection_set_recv_ctx(self.connection.as_ptr(), context).into_result()?;
439 Ok(self)
440 }
441
442 /// may be used to receive data with callbacks defined by the user.
443 ///
444 /// Corresponds to [`s2n_connection_set_send_cb`].
445 pub fn set_send_callback(&mut self, callback: s2n_send_fn) -> Result<&mut Self, Error> {
446 unsafe { s2n_connection_set_send_cb(self.connection.as_ptr(), callback).into_result() }?;
447 Ok(self)
448 }
449
450 /// # Safety
451 ///
452 /// The `context` pointer must live at least as long as the connection
453 ///
454 /// Corresponds to [`s2n_connection_set_send_ctx`].
455 pub unsafe fn set_send_context(&mut self, context: *mut c_void) -> Result<&mut Self, Error> {
456 s2n_connection_set_send_ctx(self.connection.as_ptr(), context).into_result()?;
457 Ok(self)
458 }
459
460 /// Sets the callback to use for verifying that a hostname from an X.509 certificate is
461 /// trusted.
462 ///
463 /// The callback may be called more than once during certificate validation as each SAN on
464 /// the certificate will be checked.
465 ///
466 /// Corresponds to [`s2n_connection_set_verify_host_callback`].
467 pub fn set_verify_host_callback<T: 'static + VerifyHostNameCallback>(
468 &mut self,
469 handler: T,
470 ) -> Result<&mut Self, Error> {
471 unsafe extern "C" fn verify_host_cb_fn(
472 host_name: *const ::libc::c_char,
473 host_name_len: usize,
474 context: *mut ::libc::c_void,
475 ) -> u8 {
476 let context = &mut *(context as *mut Context);
477 let handler = context.verify_host_callback.as_mut().unwrap();
478 verify_host(host_name, host_name_len, handler)
479 }
480
481 self.context_mut().verify_host_callback = Some(Box::new(handler));
482 unsafe {
483 s2n_connection_set_verify_host_callback(
484 self.connection.as_ptr(),
485 Some(verify_host_cb_fn),
486 self.context_mut() as *mut Context as *mut c_void,
487 )
488 .into_result()
489 }?;
490 Ok(self)
491 }
492
493 /// Connections preferring low latency will be encrypted using small record sizes that
494 /// can be decrypted sooner by the recipient.
495 ///
496 /// Corresponds to [`s2n_connection_prefer_low_latency`].
497 pub fn prefer_low_latency(&mut self) -> Result<&mut Self, Error> {
498 unsafe { s2n_connection_prefer_low_latency(self.connection.as_ptr()).into_result() }?;
499 Ok(self)
500 }
501
502 /// Connections preferring throughput will use large record sizes that minimize overhead.
503 ///
504 /// Corresponds to [`s2n_connection_prefer_throughput`].
505 pub fn prefer_throughput(&mut self) -> Result<&mut Self, Error> {
506 unsafe { s2n_connection_prefer_throughput(self.connection.as_ptr()).into_result() }?;
507 Ok(self)
508 }
509
510 /// Configure the connection to reduce potentially expensive calls to recv.
511 ///
512 /// Corresponds to [`s2n_connection_set_recv_buffering`].
513 pub fn set_receive_buffering(&mut self, enabled: bool) -> Result<&mut Self, Error> {
514 unsafe {
515 s2n_connection_set_recv_buffering(self.connection.as_ptr(), enabled).into_result()
516 }?;
517 Ok(self)
518 }
519
520 /// wipes and free the in and out buffers associated with a connection.
521 ///
522 /// This function may be called when a connection is in keep-alive or idle state to
523 /// reduce memory overhead of long lived connections.
524 ///
525 /// Corresponds to [`s2n_connection_release_buffers`].
526 pub fn release_buffers(&mut self) -> Result<&mut Self, Error> {
527 unsafe { s2n_connection_release_buffers(self.connection.as_ptr()).into_result() }?;
528 Ok(self)
529 }
530
531 /// Corresponds to [`s2n_connection_use_corked_io`].
532 pub fn use_corked_io(&mut self) -> Result<&mut Self, Error> {
533 unsafe { s2n_connection_use_corked_io(self.connection.as_ptr()).into_result() }?;
534 Ok(self)
535 }
536
537 pub(crate) fn wipe_method<F, T>(&mut self, wipe: F) -> Result<(), Error>
538 where
539 F: FnOnce(&mut Self) -> Result<T, Error>,
540 {
541 // Safety:
542 // We re-init the context after the wipe
543 unsafe { self.drop_context()? };
544
545 let result = wipe(self);
546 // We must initialize the context again whether or not wipe succeeds.
547 // A connection without a context is invalid and has undefined behavior.
548 self.init_context();
549 result?;
550
551 Ok(())
552 }
553
554 /// wipes an existing connection and allows it to be reused.
555 ///
556 /// This method erases all data associated with a connection including pending reads.
557 /// This function should be called after all I/O is completed and s2n_shutdown has been
558 /// called. Reusing the same connection handle(s) is more performant than repeatedly
559 /// calling s2n_connection_new and s2n_connection_free
560 ///
561 /// Corresponds to [`s2n_connection_wipe`].
562 pub fn wipe(&mut self) -> Result<&mut Self, Error> {
563 self.wipe_method(|conn| unsafe { s2n_connection_wipe(conn.as_ptr()).into_result() })?;
564 Ok(self)
565 }
566
567 fn trigger_initializer(&mut self) {
568 if !core::mem::replace(&mut self.context_mut().connection_initialized, true) {
569 if let Some(config) = self.config() {
570 if let Some(callback) = config.context().connection_initializer.as_ref() {
571 let future = callback.initialize_connection(self);
572 AsyncCallback::trigger(future, self);
573 }
574 }
575 }
576 }
577
578 // Poll the connection future if it exists.
579 //
580 // If the future returns Pending, then re-set it back on the Connection.
581 fn poll_async_task(&mut self) -> Option<Poll<Result<(), Error>>> {
582 self.take_async_callback().map(|mut callback| {
583 let waker = self.waker().ok_or(Error::MISSING_WAKER)?.clone();
584 let mut ctx = core::task::Context::from_waker(&waker);
585 match Pin::new(&mut callback).poll(self, &mut ctx) {
586 Poll::Ready(result) => Poll::Ready(result),
587 Poll::Pending => {
588 // replace the future if it hasn't completed yet
589 self.set_async_callback(callback);
590 Poll::Pending
591 }
592 }
593 })
594 }
595
596 pub(crate) fn poll_negotiate_method<F, T>(
597 &mut self,
598 mut negotiate: F,
599 ) -> Poll<Result<(), Error>>
600 where
601 F: FnMut(&mut Connection) -> Poll<Result<T, Error>>,
602 {
603 self.trigger_initializer();
604
605 loop {
606 // Check whether renegotiate is blocked by any async callbacks
607 match self.poll_async_task().unwrap_or(Poll::Ready(Ok(()))) {
608 Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
609 Poll::Pending => return Poll::Pending,
610 Poll::Ready(Ok(_)) => {}
611 };
612
613 match negotiate(self) {
614 Poll::Ready(res) => return Poll::Ready(res.map(|_| ())),
615 Poll::Pending => {
616 // If `negotiate` returned `Pending` it could be blocked on a connection future
617 // (i.e. not socket IO) so before we return, we need to make sure we poll
618 // the associated future at least once. Otherwise, we will violate the waker contract.
619 //
620 // See https://github.com/aws/s2n-quic/pull/2248
621 if self.context_mut().async_callback.is_some() {
622 // continuing in the loop will poll the task
623 continue;
624 }
625
626 // we don't have anything else to poll so return `Pending`
627 return Poll::Pending;
628 }
629 }
630 }
631 }
632
633 /// Performs the TLS handshake to completion
634 ///
635 /// Multiple callbacks can be configured for a connection and config, but
636 /// [`Self::poll_negotiate()`] can only execute and block on one callback at a time.
637 /// The handshake is sequential, not concurrent, and stops execution when
638 /// it encounters an async callback.
639 ///
640 /// The handshake does not continue execution (and therefore can't call
641 /// any other callbacks) until the blocking async task reports completion.
642 ///
643 /// Corresponds to [`s2n_negotiate`].
644 pub fn poll_negotiate(&mut self) -> Poll<Result<&mut Self, Error>> {
645 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
646 self.poll_negotiate_method(|conn| unsafe {
647 s2n_negotiate(conn.as_ptr(), &mut blocked).into_poll()
648 })
649 .map_ok(|_| self)
650 }
651
652 /// Encrypts and sends data on a connection where
653 /// [negotiate](`Self::poll_negotiate`) has succeeded.
654 ///
655 /// Returns the number of bytes written, and may indicate a partial write.
656 ///
657 /// Corresponds to [`s2n_send`].
658 #[cfg(not(feature = "unstable-renegotiate"))]
659 pub fn poll_send(&mut self, buf: &[u8]) -> Poll<Result<usize, Error>> {
660 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
661 let buf_len: isize = buf.len().try_into().map_err(|_| Error::INVALID_INPUT)?;
662 let buf_ptr = buf.as_ptr() as *const ::libc::c_void;
663 unsafe { s2n_send(self.connection.as_ptr(), buf_ptr, buf_len, &mut blocked).into_poll() }
664 }
665
666 #[cfg(not(feature = "unstable-renegotiate"))]
667 pub(crate) fn poll_recv_raw(
668 &mut self,
669 buf_ptr: *mut ::libc::c_void,
670 buf_len: isize,
671 ) -> Poll<Result<usize, Error>> {
672 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
673 unsafe { s2n_recv(self.connection.as_ptr(), buf_ptr, buf_len, &mut blocked).into_poll() }
674 }
675
676 /// Reads and decrypts data from a connection where
677 /// [negotiate](`Self::poll_negotiate`) has succeeded.
678 ///
679 /// Returns the number of bytes read, and may indicate a partial read.
680 /// 0 bytes returned indicates EOF due to connection closure.
681 ///
682 /// Corresponds to [`s2n_recv`].
683 pub fn poll_recv(&mut self, buf: &mut [u8]) -> Poll<Result<usize, Error>> {
684 let buf_len: isize = buf.len().try_into().map_err(|_| Error::INVALID_INPUT)?;
685 let buf_ptr = buf.as_ptr() as *mut ::libc::c_void;
686 self.poll_recv_raw(buf_ptr, buf_len)
687 }
688
689 /// Reads and decrypts data from a connection where
690 /// [negotiate](`Self::poll_negotiate`) has succeeded
691 /// to a uninitialized buffer.
692 ///
693 /// Returns the number of bytes read, and may indicate a partial read.
694 /// 0 bytes returned indicates EOF due to connection closure.
695 ///
696 /// Safety: this function is always safe to call, and additionally:
697 /// 1. It will never uninitialize any bytes in `buf`.
698 /// 2. If it returns `Ok(n)`, then the first `n` bytes of `buf`
699 /// will have been initialized by this function.
700 ///
701 /// Corresponds to [`s2n_recv`].
702 pub fn poll_recv_uninitialized(
703 &mut self,
704 buf: &mut [MaybeUninit<u8>],
705 ) -> Poll<Result<usize, Error>> {
706 let buf_len: isize = buf.len().try_into().map_err(|_| Error::INVALID_INPUT)?;
707 let buf_ptr = buf.as_ptr() as *mut ::libc::c_void;
708
709 // Safety:
710 // 1. s2n_recv never writes uninitialized garbage to `buf`.
711 // 2. if s2n_recv returns `+n`, it guarantees that the first
712 // `n` bytes of `buf` have been initialized, which allows this
713 // function to return `Ok(n)`
714 self.poll_recv_raw(buf_ptr, buf_len)
715 }
716
717 /// Attempts to flush any data previously buffered by a call to [send](`Self::poll_send`).
718 ///
719 /// poll_flush can only flush data that s2n-tls has already encrypted and
720 /// buffered for sending. poll_send may need to be called again to fully send
721 /// all data. See the [Usage Guide](https://github.com/aws/s2n-tls/blob/main/docs/usage-guide/topics/ch07-io.md)
722 /// for more details.
723 ///
724 /// Corresponds to [`s2n_flush`].
725 pub fn poll_flush(&mut self) -> Poll<Result<&mut Self, Error>> {
726 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
727 unsafe {
728 s2n_flush(self.connection.as_ptr(), &mut blocked)
729 .into_poll()
730 .map_ok(|_| self)
731 }
732 }
733
734 /// Gets the number of bytes that are currently available in the buffer to be read.
735 ///
736 /// Corresponds to [`s2n_peek`].
737 pub fn peek_len(&self) -> usize {
738 unsafe { s2n_peek(self.connection.as_ptr()) as usize }
739 }
740
741 /// Gets the number of additional ciphertext bytes available to be read.
742 ///
743 /// <div class="warning">
744 ///
745 /// This API is _not_ intuitive, and probably doesn't do what you think
746 /// it does. You should rigorously test your assumptions about its behavior.
747 ///
748 /// </div>
749 ///
750 /// Corresponds to [`s2n_peek_buffered`].
751 pub fn peek_buffered_len(&self) -> usize {
752 unsafe { s2n_peek_buffered(self.connection.as_ptr()) as usize }
753 }
754
755 /// Attempts a graceful shutdown of the TLS connection.
756 ///
757 /// The shutdown is not complete until the necessary shutdown messages
758 /// have been successfully sent and received. If the peer does not respond
759 /// correctly, the graceful shutdown may fail.
760 ///
761 /// Corresponds to [`s2n_shutdown`].
762 pub fn poll_shutdown(&mut self) -> Poll<Result<&mut Self, Error>> {
763 if !self.remaining_blinding_delay()?.is_zero() {
764 return Poll::Pending;
765 }
766 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
767 unsafe {
768 s2n_shutdown(self.connection.as_ptr(), &mut blocked)
769 .into_poll()
770 .map_ok(|_| self)
771 }
772 }
773
774 /// Attempts a graceful shutdown of the write side of a TLS connection.
775 ///
776 /// Unlike Self::poll_shutdown, no response from the peer is necessary.
777 /// If using TLS1.3, the connection can continue to be used for reading afterwards.
778 ///
779 /// Corresponds to [`s2n_shutdown_send`].
780 pub fn poll_shutdown_send(&mut self) -> Poll<Result<&mut Self, Error>> {
781 if !self.remaining_blinding_delay()?.is_zero() {
782 return Poll::Pending;
783 }
784 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
785 unsafe {
786 s2n_shutdown_send(self.connection.as_ptr(), &mut blocked)
787 .into_poll()
788 .map_ok(|_| self)
789 }
790 }
791
792 /// Returns the TLS alert code, if any
793 ///
794 /// Corresponds to [`s2n_connection_get_alert`].
795 pub fn alert(&self) -> Option<u8> {
796 let alert =
797 unsafe { s2n_connection_get_alert(self.connection.as_ptr()).into_result() }.ok()?;
798 Some(alert as u8)
799 }
800
801 /// Sets the server name value for the connection
802 ///
803 /// Corresponds to [`s2n_set_server_name`].
804 pub fn set_server_name(&mut self, server_name: &str) -> Result<&mut Self, Error> {
805 let server_name = std::ffi::CString::new(server_name).map_err(|_| Error::INVALID_INPUT)?;
806 unsafe {
807 s2n_set_server_name(self.connection.as_ptr(), server_name.as_ptr()).into_result()
808 }?;
809 Ok(self)
810 }
811
812 /// Get the server name associated with the connection client hello.
813 ///
814 /// Corresponds to [`s2n_get_server_name`].
815 pub fn server_name(&self) -> Option<&str> {
816 unsafe {
817 let server_name = s2n_get_server_name(self.connection.as_ptr());
818 match server_name.into_result() {
819 Ok(server_name) => CStr::from_ptr(server_name).to_str().ok(),
820 Err(_) => None,
821 }
822 }
823 }
824
825 /// Adds a session ticket from a previous TLS connection to create a resumed session
826 ///
827 /// Corresponds to [`s2n_connection_set_session`].
828 pub fn set_session_ticket(&mut self, session: &[u8]) -> Result<&mut Self, Error> {
829 unsafe {
830 s2n_connection_set_session(self.connection.as_ptr(), session.as_ptr(), session.len())
831 .into_result()
832 }?;
833 Ok(self)
834 }
835
836 /// Retrieves the size of the session ticket.
837 ///
838 /// Corresponds to [`s2n_connection_get_session_length`].
839 pub fn session_ticket_length(&self) -> Result<usize, Error> {
840 let len =
841 unsafe { s2n_connection_get_session_length(self.connection.as_ptr()).into_result()? };
842 Ok(len.try_into().unwrap())
843 }
844
845 /// Serializes the session state from the connection into `output` and returns
846 /// the length of the session ticket.
847 ///
848 /// If the buffer does not have the size for the session_ticket,
849 /// `Error::INVALID_INPUT` is returned.
850 ///
851 /// Note: This function is not recommended for > TLS1.2 because in TLS1.3
852 /// servers can send multiple session tickets and this will return only
853 /// the most recently received ticket.
854 ///
855 /// Corresponds to [`s2n_connection_get_session`].
856 pub fn session_ticket(&self, output: &mut [u8]) -> Result<usize, Error> {
857 if output.len() < self.session_ticket_length()? {
858 return Err(Error::INVALID_INPUT);
859 }
860 let written = unsafe {
861 s2n_connection_get_session(self.connection.as_ptr(), output.as_mut_ptr(), output.len())
862 .into_result()?
863 };
864 Ok(written.try_into().unwrap())
865 }
866
867 /// Sets a Waker on the connection context or clears it if `None` is passed.
868 pub fn set_waker(&mut self, waker: Option<&Waker>) -> Result<&mut Self, Error> {
869 let ctx = self.context_mut();
870
871 if let Some(waker) = waker {
872 if let Some(prev_waker) = ctx.waker.as_mut() {
873 // only replace the Waker if they don't reference the same task
874 if !prev_waker.will_wake(waker) {
875 prev_waker.clone_from(waker);
876 }
877 } else {
878 ctx.waker = Some(waker.clone());
879 }
880 } else {
881 ctx.waker = None;
882 }
883 Ok(self)
884 }
885
886 /// Returns the Waker set on the connection context.
887 pub fn waker(&self) -> Option<&Waker> {
888 let ctx = self.context();
889 ctx.waker.as_ref()
890 }
891
892 /// Takes the [`Option::take`] the connection_future stored on the
893 /// connection context.
894 ///
895 /// If the Future returns `Poll::Pending` and has not completed, then it
896 /// should be re-set using [`Self::set_connection_future()`]
897 fn take_async_callback(&mut self) -> Option<AsyncCallback> {
898 let ctx = self.context_mut();
899 ctx.async_callback.take()
900 }
901
902 /// Sets a `connection_future` on the connection context.
903 pub(crate) fn set_async_callback(&mut self, callback: AsyncCallback) {
904 let ctx = self.context_mut();
905 debug_assert!(ctx.async_callback.is_none());
906 ctx.async_callback = Some(callback);
907 }
908
909 /// Retrieve a mutable reference to the [`Context`] stored on the connection.
910 fn context_mut(&mut self) -> &mut Context {
911 unsafe {
912 let ctx = s2n_connection_get_ctx(self.connection.as_ptr())
913 .into_result()
914 .unwrap();
915 &mut *(ctx.as_ptr() as *mut Context)
916 }
917 }
918
919 /// Retrieve a reference to the [`Context`] stored on the connection.
920 fn context(&self) -> &Context {
921 unsafe {
922 let ctx = s2n_connection_get_ctx(self.connection.as_ptr())
923 .into_result()
924 .unwrap();
925 &*(ctx.as_ptr() as *mut Context)
926 }
927 }
928
929 /// Drop the context
930 ///
931 /// SAFETY:
932 /// A connection without a context is invalid. After calling this method
933 /// from anywhere other than Drop, you must reinitialize the context.
934 unsafe fn drop_context(&mut self) -> Result<(), Error> {
935 let ctx = s2n_connection_get_ctx(self.connection.as_ptr()).into_result();
936 if let Ok(ctx) = ctx {
937 drop(Box::from_raw(ctx.as_ptr() as *mut Context));
938 }
939 // Setting a NULL context is important: if we don't also remove the context
940 // from the connection, then the invalid memory is still accessible and
941 // may even be double-freed.
942 s2n_connection_set_ctx(self.connection.as_ptr(), core::ptr::null_mut()).into_result()?;
943 Ok(())
944 }
945
946 /// Mark that the server_name extension was used to configure the connection.
947 ///
948 /// Corresponds to [`s2n_connection_server_name_extension_used`].
949 pub fn server_name_extension_used(&mut self) {
950 // TODO: requiring the application to call this method is a pretty sharp edge.
951 // Figure out if its possible to automatically call this from the Rust bindings.
952 unsafe {
953 s2n_connection_server_name_extension_used(self.connection.as_ptr())
954 .into_result()
955 .unwrap();
956 }
957 }
958
959 /// Check if client auth was used for a connection.
960 ///
961 /// This is especially useful when the server has [`ClientAuthType::Optional`] configured.
962 ///
963 /// Corresponds to [`s2n_connection_client_cert_used`].
964 pub fn client_cert_used(&self) -> bool {
965 unsafe { s2n_connection_client_cert_used(self.connection.as_ptr()) == 1 }
966 }
967
968 /// Retrieves the raw bytes of the client cert chain received from the peer, if present.
969 ///
970 /// Corresponds to [`s2n_connection_get_client_cert_chain`].
971 pub fn client_cert_chain_bytes(&self) -> Result<Option<&[u8]>, Error> {
972 if !self.client_cert_used() {
973 return Ok(None);
974 }
975
976 let mut chain = std::ptr::null_mut();
977 let mut len = 0;
978 unsafe {
979 s2n_connection_get_client_cert_chain(self.connection.as_ptr(), &mut chain, &mut len)
980 .into_result()?;
981 }
982
983 if chain.is_null() || len == 0 {
984 return Ok(None);
985 }
986
987 unsafe { Ok(Some(std::slice::from_raw_parts(chain, len as usize))) }
988 }
989
990 // The memory backing the ClientHello is owned by the Connection, so we
991 // tie the ClientHello to the lifetime of the Connection. This is validated
992 // with a doc test that ensures the ClientHello is invalid once the
993 // connection has gone out of scope.
994 //
995 /// Returns a reference to the ClientHello associated with the connection.
996 /// ```compile_fail
997 /// use s2n_tls::client_hello::ClientHello;
998 /// use s2n_tls::connection::Connection;
999 /// use s2n_tls::enums::Mode;
1000 ///
1001 /// let mut conn = Connection::new(Mode::Server);
1002 /// let mut client_hello: &ClientHello = conn.client_hello().unwrap();
1003 /// drop(conn);
1004 /// client_hello.raw_message();
1005 /// ```
1006 ///
1007 /// The compilation could be failing for a variety of reasons, so make sure
1008 /// that the test case is actually good.
1009 /// ```no_run
1010 /// use s2n_tls::client_hello::ClientHello;
1011 /// use s2n_tls::connection::Connection;
1012 /// use s2n_tls::enums::Mode;
1013 ///
1014 /// let mut conn = Connection::new(Mode::Server);
1015 /// let mut client_hello: &ClientHello = conn.client_hello().unwrap();
1016 /// client_hello.raw_message();
1017 /// drop(conn);
1018 /// ```
1019 ///
1020 /// Corresponds to [`s2n_connection_get_client_hello`].
1021 pub fn client_hello(&self) -> Result<&crate::client_hello::ClientHello, Error> {
1022 let mut handle =
1023 unsafe { s2n_connection_get_client_hello(self.connection.as_ptr()).into_result()? };
1024 Ok(crate::client_hello::ClientHello::from_ptr(unsafe {
1025 handle.as_mut()
1026 }))
1027 }
1028
1029 /// Corresponds to [`s2n_client_hello_cb_done`].
1030 pub(crate) fn mark_client_hello_cb_done(&mut self) -> Result<(), Error> {
1031 unsafe {
1032 s2n_client_hello_cb_done(self.connection.as_ptr()).into_result()?;
1033 }
1034 Ok(())
1035 }
1036
1037 /// Access the protocol version selected for the connection.
1038 ///
1039 /// Corresponds to [`s2n_connection_get_actual_protocol_version`].
1040 pub fn actual_protocol_version(&self) -> Result<Version, Error> {
1041 let version = unsafe {
1042 s2n_connection_get_actual_protocol_version(self.connection.as_ptr()).into_result()?
1043 };
1044 version.try_into()
1045 }
1046
1047 /// Detects if the client hello is using the SSLv2 format.
1048 ///
1049 /// s2n-tls will not negotiate SSLv2, but will accept SSLv2 ClientHellos
1050 /// advertising a higher protocol version like SSLv3 or TLS1.0.
1051 /// [Connection::actual_protocol_version()] can be used to retrieve the
1052 /// protocol version that is actually used on the connection.
1053 ///
1054 /// Corresponds to [`s2n_connection_get_client_hello_version`], but only checks
1055 /// for SSLv2.
1056 pub fn client_hello_is_sslv2(&self) -> Result<bool, Error> {
1057 let version = unsafe {
1058 s2n_connection_get_client_hello_version(self.connection.as_ptr()).into_result()?
1059 };
1060 let version: Version = version.try_into()?;
1061 Ok(version == Version::SSLV2)
1062 }
1063
1064 /// Corresponds to [`s2n_connection_get_handshake_type_name`].
1065 pub fn handshake_type(&self) -> Result<&str, Error> {
1066 let handshake = unsafe {
1067 s2n_connection_get_handshake_type_name(self.connection.as_ptr()).into_result()?
1068 };
1069 unsafe {
1070 // SAFETY: Constructed strings have a null byte appended to them.
1071 // SAFETY: The data has a 'static lifetime, because it resides in a
1072 // static char array, and is never modified after its initial
1073 // creation.
1074 const_str!(handshake)
1075 }
1076 }
1077
1078 /// Corresponds to [`s2n_connection_get_cipher`].
1079 pub fn cipher_suite(&self) -> Result<&str, Error> {
1080 let cipher = unsafe { s2n_connection_get_cipher(self.connection.as_ptr()).into_result()? };
1081 unsafe {
1082 // SAFETY: The data is null terminated because it is declared as a C
1083 // string literal.
1084 // SAFETY: cipher has a static lifetime because it lives on s2n_cipher_suite,
1085 // a static struct.
1086 const_str!(cipher)
1087 }
1088 }
1089
1090 /// Corresponds to [`s2n_connection_get_kem_name`].
1091 #[deprecated = "PQ TLS 1.2 KEM Names are no longer supported. Use kem_group_name() to retrieve PQ TLS 1.3 Group name."]
1092 pub fn kem_name(&self) -> Option<&str> {
1093 let name_bytes = {
1094 let name = unsafe { s2n_connection_get_kem_name(self.connection.as_ptr()) };
1095 if name.is_null() {
1096 return None;
1097 }
1098 name
1099 };
1100
1101 let name_str = unsafe {
1102 // SAFETY: The data is null terminated because it is declared as a C
1103 // string literal.
1104 // SAFETY: kem_name has a static lifetime because it lives on a const
1105 // struct s2n_kem with file scope.
1106 const_str!(name_bytes)
1107 };
1108
1109 match name_str {
1110 Ok("NONE") => None,
1111 Ok(name) => Some(name),
1112 Err(_) => {
1113 // Unreachable: This would indicate a non-utf-8 string literal in
1114 // the s2n-tls C codebase.
1115 None
1116 }
1117 }
1118 }
1119
1120 /// Corresponds to [`s2n_connection_get_kem_group_name`].
1121 pub fn kem_group_name(&self) -> Option<&str> {
1122 let name_bytes = {
1123 let name = unsafe { s2n_connection_get_kem_group_name(self.connection.as_ptr()) };
1124 if name.is_null() {
1125 return None;
1126 }
1127 name
1128 };
1129
1130 let name_str = unsafe {
1131 // SAFETY: The data is null terminated because it is declared as a C
1132 // string literal.
1133 // SAFETY: kem_name has a static lifetime because it lives on a const
1134 // struct s2n_kem with file scope.
1135 const_str!(name_bytes)
1136 };
1137
1138 match name_str {
1139 Ok("NONE") => None,
1140 Ok(name) => Some(name),
1141 Err(_) => {
1142 // Unreachable: This would indicate a non-utf-8 string literal in
1143 // the s2n-tls C codebase.
1144 None
1145 }
1146 }
1147 }
1148
1149 /// Corresponds to [`s2n_connection_get_curve`].
1150 #[deprecated = "Use selected_key_exchange_group instead"]
1151 pub fn selected_curve(&self) -> Result<&str, Error> {
1152 let curve = unsafe { s2n_connection_get_curve(self.connection.as_ptr()).into_result()? };
1153 unsafe {
1154 // SAFETY: The data is null terminated because it is declared as a C
1155 // string literal.
1156 // SAFETY: curve has a static lifetime because it lives on s2n_ecc_named_curve,
1157 // which is a static const struct.
1158 const_str!(curve)
1159 }
1160 }
1161
1162 /// Corresponds to [`s2n_connection_get_key_exchange_group`].
1163 pub fn selected_key_exchange_group(&self) -> Option<&str> {
1164 let mut group_name = core::ptr::null();
1165 unsafe {
1166 s2n_connection_get_key_exchange_group(self.connection.as_ptr(), &mut group_name)
1167 .into_result()
1168 .ok()
1169 }?;
1170
1171 unsafe {
1172 // SAFETY: The data is null terminated because it is declared as a C
1173 // string literal.
1174 // SAFETY: group_name has a static lifetime because it lives on either
1175 // s2n_ecc_named_curve or s2n_kem, both of which are static
1176 // const structs.
1177 const_str!(group_name).ok()
1178 }
1179 }
1180
1181 /// Corresponds to [`s2n_connection_get_selected_signature_algorithm`].
1182 pub fn selected_signature_algorithm(&self) -> Result<SignatureAlgorithm, Error> {
1183 let mut sig_alg = s2n_tls_signature_algorithm::ANONYMOUS;
1184 unsafe {
1185 s2n_connection_get_selected_signature_algorithm(self.connection.as_ptr(), &mut sig_alg)
1186 .into_result()?;
1187 }
1188 sig_alg.try_into()
1189 }
1190
1191 /// Return the negotiated signature scheme, e.g. "rsa_pss_rsae_sha256".
1192 ///
1193 /// Note that this does not strictly follow IANA naming conventions for ECDSA
1194 /// signatures and legacy SHA224/SHA1 signatures.
1195 ///
1196 /// This will be `None` in the case of session resumption or RSA key exchange.
1197 ///
1198 /// Corresponds to [`s2n_connection_get_signature_scheme`].
1199 pub fn signature_scheme(&self) -> Option<&'static str> {
1200 let mut sig_alg: *const std::ffi::c_char = std::ptr::null();
1201 unsafe {
1202 s2n_connection_get_signature_scheme(self.connection.as_ptr(), &mut sig_alg)
1203 .into_result()
1204 .ok()?;
1205 }
1206 let result = unsafe {
1207 // Safety: signature schemes are C string literals in the s2n-tls codebase,
1208 // so they are null-terminated and static.
1209 cstr_to_str(sig_alg)
1210 };
1211 if result == "none" {
1212 None
1213 } else {
1214 Some(result)
1215 }
1216 }
1217
1218 /// Corresponds to [`s2n_connection_get_selected_digest_algorithm`].
1219 pub fn selected_hash_algorithm(&self) -> Result<HashAlgorithm, Error> {
1220 let mut hash_alg = s2n_tls_hash_algorithm::NONE;
1221 unsafe {
1222 s2n_connection_get_selected_digest_algorithm(self.connection.as_ptr(), &mut hash_alg)
1223 .into_result()?;
1224 }
1225 hash_alg.try_into()
1226 }
1227
1228 /// Corresponds to [`s2n_connection_get_certificate_match`].
1229 pub fn certificate_match(&self) -> Result<CertSNIMatch, Error> {
1230 let mut cert_match = s2n_cert_sni_match::SNI_NO_MATCH;
1231 unsafe {
1232 s2n_connection_get_certificate_match(self.connection.as_ptr(), &mut cert_match)
1233 .into_result()?;
1234 }
1235 cert_match.try_into()
1236 }
1237
1238 /// Corresponds to [`s2n_connection_get_selected_client_cert_signature_algorithm`].
1239 pub fn selected_client_signature_algorithm(&self) -> Result<Option<SignatureAlgorithm>, Error> {
1240 let mut sig_alg = s2n_tls_signature_algorithm::ANONYMOUS;
1241 unsafe {
1242 s2n_connection_get_selected_client_cert_signature_algorithm(
1243 self.connection.as_ptr(),
1244 &mut sig_alg,
1245 )
1246 .into_result()?;
1247 }
1248 Ok(match sig_alg {
1249 s2n_tls_signature_algorithm::ANONYMOUS => None,
1250 sig_alg => Some(sig_alg.try_into()?),
1251 })
1252 }
1253
1254 /// Corresponds to [`s2n_connection_get_selected_client_cert_digest_algorithm`].
1255 pub fn selected_client_hash_algorithm(&self) -> Result<Option<HashAlgorithm>, Error> {
1256 let mut hash_alg = s2n_tls_hash_algorithm::NONE;
1257 unsafe {
1258 s2n_connection_get_selected_client_cert_digest_algorithm(
1259 self.connection.as_ptr(),
1260 &mut hash_alg,
1261 )
1262 .into_result()?;
1263 }
1264 Ok(match hash_alg {
1265 s2n_tls_hash_algorithm::NONE => None,
1266 hash_alg => Some(hash_alg.try_into()?),
1267 })
1268 }
1269
1270 /// Corresponds to [`s2n_get_application_protocol`].
1271 pub fn application_protocol(&self) -> Option<&[u8]> {
1272 let protocol = unsafe { s2n_get_application_protocol(self.connection.as_ptr()) };
1273 if protocol.is_null() {
1274 return None;
1275 }
1276 Some(unsafe { CStr::from_ptr(protocol).to_bytes() })
1277 }
1278
1279 /// Provides access to the TLS-Exporter functionality.
1280 ///
1281 /// See https://datatracker.ietf.org/doc/html/rfc5705 and https://www.rfc-editor.org/rfc/rfc8446.
1282 ///
1283 /// This is currently only available with TLS 1.3 connections which have finished a handshake.
1284 ///
1285 /// Corresponds to [`s2n_connection_tls_exporter`].
1286 pub fn tls_exporter(
1287 &self,
1288 label: &[u8],
1289 context: &[u8],
1290 output: &mut [u8],
1291 ) -> Result<(), Error> {
1292 unsafe {
1293 s2n_connection_tls_exporter(
1294 self.connection.as_ptr(),
1295 label.as_ptr(),
1296 label.len().try_into().map_err(|_| Error::INVALID_INPUT)?,
1297 context.as_ptr(),
1298 context.len().try_into().map_err(|_| Error::INVALID_INPUT)?,
1299 output.as_mut_ptr(),
1300 output.len().try_into().map_err(|_| Error::INVALID_INPUT)?,
1301 )
1302 .into_result()
1303 .map(|_| ())
1304 }
1305 }
1306
1307 /// Returns the validated peer certificate chain.
1308 // 'static lifetime is because this copies the certificate chain from the connection into a new
1309 // chain, so the lifetime is independent of the connection.
1310 ///
1311 /// Corresponds to [`s2n_connection_get_peer_cert_chain`].
1312 pub fn peer_cert_chain(&self) -> Result<CertificateChain<'static>, Error> {
1313 unsafe {
1314 let chain_handle = CertificateChainHandle::allocate()?;
1315 s2n_connection_get_peer_cert_chain(
1316 self.connection.as_ptr(),
1317 chain_handle.cert.as_ptr(),
1318 )
1319 .into_result()
1320 .map(|_| ())?;
1321 Ok(CertificateChain::from_allocated(chain_handle))
1322 }
1323 }
1324
1325 /// Get the certificate used during the TLS handshake
1326 ///
1327 /// - If `self` is a server connection, the certificate selected will depend on the
1328 /// ServerName sent by the client and supported ciphers.
1329 /// - If `self` is a client connection, the certificate sent in response to a CertificateRequest
1330 /// message is returned. Currently s2n-tls supports loading only one certificate in client mode. Note that
1331 /// not all TLS endpoints will request a certificate.
1332 ///
1333 /// Corresponds to [`s2n_connection_get_selected_cert`].
1334 pub fn selected_cert(&self) -> Option<CertificateChain<'_>> {
1335 unsafe {
1336 // The API only returns null, no error is actually set.
1337 // Clippy doesn't realize from_ptr_reference is unsafe.
1338 #[allow(clippy::manual_map)]
1339 if let Some(ptr) =
1340 NonNull::new(s2n_connection_get_selected_cert(self.connection.as_ptr()))
1341 {
1342 Some(CertificateChain::from_ptr_reference(ptr))
1343 } else {
1344 None
1345 }
1346 }
1347 }
1348
1349 /// Corresponds to [`s2n_connection_get_master_secret`].
1350 pub fn master_secret(&self) -> Result<Vec<u8>, Error> {
1351 // TLS1.2 master secrets are always 48 bytes
1352 let mut secret = vec![0; 48];
1353 unsafe {
1354 s2n_connection_get_master_secret(
1355 self.connection.as_ptr(),
1356 secret.as_mut_ptr(),
1357 secret.len(),
1358 )
1359 .into_result()?;
1360 }
1361 Ok(secret)
1362 }
1363
1364 /// Retrieves the size of the serialized connection
1365 ///
1366 /// Corresponds to [`s2n_connection_serialization_length`].
1367 pub fn serialization_length(&self) -> Result<usize, Error> {
1368 unsafe {
1369 let mut length = 0;
1370 s2n_connection_serialization_length(self.connection.as_ptr(), &mut length)
1371 .into_result()?;
1372 Ok(length.try_into().unwrap())
1373 }
1374 }
1375
1376 /// Serializes the TLS connection into the provided buffer
1377 ///
1378 /// Corresponds to [`s2n_connection_serialize`].
1379 pub fn serialize(&self, output: &mut [u8]) -> Result<(), Error> {
1380 unsafe {
1381 s2n_connection_serialize(
1382 self.connection.as_ptr(),
1383 output.as_mut_ptr(),
1384 output.len().try_into().map_err(|_| Error::INVALID_INPUT)?,
1385 )
1386 .into_result()?;
1387 Ok(())
1388 }
1389 }
1390
1391 /// Deserializes the input buffer into a new TLS connection that can send/recv
1392 /// data from the original peer.
1393 ///
1394 /// Corresponds to [`s2n_connection_deserialize`].
1395 pub fn deserialize(&mut self, input: &[u8]) -> Result<(), Error> {
1396 let size = input.len();
1397 /* This is not ideal, we know that s2n_connection_deserialize will not mutate the
1398 * input value, however, the mut is needed to use the stuffer functions. */
1399 let input = input.as_ptr() as *mut u8;
1400 unsafe {
1401 s2n_connection_deserialize(
1402 self.as_ptr(),
1403 input,
1404 size.try_into().map_err(|_| Error::INVALID_INPUT)?,
1405 )
1406 .into_result()?;
1407 Ok(())
1408 }
1409 }
1410
1411 /// Determines whether the connection was resumed from an earlier handshake.
1412 ///
1413 /// Corresponds to [`s2n_connection_is_session_resumed`].
1414 pub fn resumed(&self) -> bool {
1415 unsafe { s2n_connection_is_session_resumed(self.connection.as_ptr()) == 1 }
1416 }
1417
1418 /// Append an external psk to a connection.
1419 ///
1420 /// This may be called repeatedly to support multiple PSKs.
1421 ///
1422 /// Corresponds to [`s2n_connection_append_psk`].
1423 pub fn append_psk(&mut self, psk: &Psk) -> Result<(), Error> {
1424 unsafe {
1425 // SAFETY: retrieving a *mut s2n_psk from &Psk: s2n-tls does not treat
1426 // the pointer as mutable, and only holds the reference to copy the
1427 // PSK onto the connection.
1428 s2n_connection_append_psk(self.as_ptr(), psk.ptr.as_ptr()).into_result()?
1429 };
1430 Ok(())
1431 }
1432
1433 /// Corresponds to [`s2n_connection_get_negotiated_psk_identity_length`].
1434 pub fn negotiated_psk_identity_length(&self) -> Result<usize, Error> {
1435 let mut length = 0;
1436 unsafe {
1437 s2n_connection_get_negotiated_psk_identity_length(self.connection.as_ptr(), &mut length)
1438 .into_result()?
1439 };
1440 Ok(length as usize)
1441 }
1442
1443 /// Retrieve the negotiated psk identity. Use [Connection::negotiated_psk_identity_length]
1444 /// to retrieve the length of the psk identity.
1445 ///
1446 /// Corresponds to [`s2n_connection_get_negotiated_psk_identity`].
1447 pub fn negotiated_psk_identity(&self, destination: &mut [u8]) -> Result<(), Error> {
1448 unsafe {
1449 s2n_connection_get_negotiated_psk_identity(
1450 self.connection.as_ptr(),
1451 destination.as_mut_ptr(),
1452 destination.len().min(u16::MAX as usize) as u16,
1453 )
1454 .into_result()?;
1455 }
1456 Ok(())
1457 }
1458
1459 /// Associates arbitrary application contexts with the Connection to be later retrieved via
1460 /// the [`Self::application_context()`] and [`Self::application_context_mut()`] APIs.
1461 ///
1462 /// While multiple application contexts of different types may be set, previous values of the same type will be overridden.
1463 ///
1464 /// Corresponds to [`s2n_connection_set_ctx`].
1465 pub fn set_application_context<T: Send + Sync + 'static>(&mut self, app_context: T) {
1466 let context_type_id = TypeId::of::<T>();
1467 self.context_mut()
1468 .app_context
1469 .insert(context_type_id, Box::new(app_context));
1470 }
1471
1472 /// Removes an application context set on the Connection.
1473 ///
1474 /// Returns Some containing the removed context if it exists, or None if no context
1475 /// of the specified type was previously set.
1476 pub fn remove_application_context<T: Send + Sync + 'static>(
1477 &mut self,
1478 ) -> Option<Box<dyn Any + Send + Sync>> {
1479 let context_type_id = TypeId::of::<T>();
1480 self.context_mut().app_context.remove(&context_type_id)
1481 }
1482
1483 /// Retrieves a reference to the application context associated with the Connection.
1484 ///
1485 /// Returns None if the provided type T does not match the type of any application context set on the Connection.
1486 ///
1487 /// To set a context on the connection, use [`Self::set_application_context()`]. To retrieve a
1488 /// mutable reference to the context, use [`Self::application_context_mut()`].
1489 ///
1490 /// Corresponds to [`s2n_connection_get_ctx`].
1491 pub fn application_context<T: Send + Sync + 'static>(&self) -> Option<&T> {
1492 let context_type_id = TypeId::of::<T>();
1493 // The Any trait keeps track of the application context's type. downcast_ref() returns
1494 // Some only if the correct type is provided:
1495 // https://doc.rust-lang.org/std/any/trait.Any.html#method.downcast_ref
1496 self.context()
1497 .app_context
1498 .get(&context_type_id)
1499 .and_then(|app_context| app_context.downcast_ref::<T>())
1500 }
1501
1502 /// Retrieves a mutable reference to the application context associated with the Connection.
1503 ///
1504 /// Returns None if the provided type T does not match the type of any application context set on the Connection.
1505 ///
1506 /// To set a context on the connection, use [`Self::set_application_context()`]. To retrieve an
1507 /// immutable reference to the context, use [`Self::application_context()`].
1508 ///
1509 /// Corresponds to [`s2n_connection_get_ctx`].
1510 pub fn application_context_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
1511 let context_type_id = TypeId::of::<T>();
1512 self.context_mut()
1513 .app_context
1514 .get_mut(&context_type_id)
1515 .and_then(|app_context| app_context.downcast_mut::<T>())
1516 }
1517
1518 #[cfg(feature = "unstable-cert_authorities")]
1519 pub(crate) fn cert_request_state(&mut self) -> &mut CertRequestState {
1520 &mut self.context_mut().cert_request_state
1521 }
1522
1523 #[cfg(feature = "unstable-renegotiate")]
1524 pub(crate) fn renegotiate_state_mut(&mut self) -> &mut RenegotiateState {
1525 &mut self.context_mut().renegotiate_state
1526 }
1527
1528 #[cfg(feature = "unstable-renegotiate")]
1529 pub(crate) fn renegotiate_state(&self) -> &RenegotiateState {
1530 &self.context().renegotiate_state
1531 }
1532 }
1533
1534 struct Context {
1535 waker: Option<Waker>,
1536 async_callback: Option<AsyncCallback>,
1537 verify_host_callback: Option<Box<dyn VerifyHostNameCallback>>,
1538 connection_initialized: bool,
1539 app_context: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
1540 #[cfg(feature = "unstable-renegotiate")]
1541 pub(crate) renegotiate_state: RenegotiateState,
1542 #[cfg(feature = "unstable-cert_authorities")]
1543 pub(crate) cert_request_state: CertRequestState,
1544 }
1545
1546 impl Context {
1547 fn new() -> Self {
1548 Context {
1549 waker: None,
1550 async_callback: None,
1551 verify_host_callback: None,
1552 connection_initialized: false,
1553 app_context: HashMap::new(),
1554 #[cfg(feature = "unstable-renegotiate")]
1555 renegotiate_state: RenegotiateState::default(),
1556 #[cfg(feature = "unstable-cert_authorities")]
1557 cert_request_state: CertRequestState::default(),
1558 }
1559 }
1560 }
1561
1562 #[cfg(feature = "quic")]
1563 impl Connection {
1564 /// Corresponds to [`s2n_connection_enable_quic`].
1565 pub fn enable_quic(&mut self) -> Result<&mut Self, Error> {
1566 unsafe { s2n_connection_enable_quic(self.connection.as_ptr()).into_result() }?;
1567 Ok(self)
1568 }
1569
1570 /// Corresponds to [`s2n_connection_set_quic_transport_parameters`].
1571 pub fn set_quic_transport_parameters(&mut self, buffer: &[u8]) -> Result<&mut Self, Error> {
1572 unsafe {
1573 s2n_connection_set_quic_transport_parameters(
1574 self.connection.as_ptr(),
1575 buffer.as_ptr(),
1576 buffer.len().try_into().map_err(|_| Error::INVALID_INPUT)?,
1577 )
1578 .into_result()
1579 }?;
1580 Ok(self)
1581 }
1582
1583 /// Corresponds to [`s2n_connection_get_quic_transport_parameters`].
1584 pub fn quic_transport_parameters(&mut self) -> Result<&[u8], Error> {
1585 let mut ptr = core::ptr::null();
1586 let mut len = 0;
1587 unsafe {
1588 s2n_connection_get_quic_transport_parameters(
1589 self.connection.as_ptr(),
1590 &mut ptr,
1591 &mut len,
1592 )
1593 .into_result()
1594 }?;
1595 let buffer = unsafe { core::slice::from_raw_parts(ptr, len as _) };
1596 Ok(buffer)
1597 }
1598
1599 /// # Safety
1600 ///
1601 /// The `context` pointer must live at least as long as the connection
1602 ///
1603 /// Corresponds to [`s2n_connection_set_secret_callback`].
1604 pub unsafe fn set_secret_callback(
1605 &mut self,
1606 callback: s2n_secret_cb,
1607 context: *mut c_void,
1608 ) -> Result<&mut Self, Error> {
1609 s2n_connection_set_secret_callback(self.connection.as_ptr(), callback, context)
1610 .into_result()?;
1611 Ok(self)
1612 }
1613
1614 /// Corresponds to [`s2n_recv_quic_post_handshake_message`].
1615 pub fn quic_process_post_handshake_message(&mut self) -> Result<&mut Self, Error> {
1616 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
1617 unsafe {
1618 s2n_recv_quic_post_handshake_message(self.connection.as_ptr(), &mut blocked)
1619 .into_result()
1620 }?;
1621 Ok(self)
1622 }
1623
1624 /// Allows the quic library to check if session tickets are expected
1625 ///
1626 /// Corresponds to [`s2n_connection_are_session_tickets_enabled`].
1627 pub fn are_session_tickets_enabled(&self) -> bool {
1628 unsafe { s2n_connection_are_session_tickets_enabled(self.connection.as_ptr()) }
1629 }
1630 }
1631
1632 impl AsRef<Connection> for Connection {
1633 fn as_ref(&self) -> &Connection {
1634 self
1635 }
1636 }
1637
1638 impl AsMut<Connection> for Connection {
1639 fn as_mut(&mut self) -> &mut Connection {
1640 self
1641 }
1642 }
1643
1644 impl Drop for Connection {
1645 /// Corresponds to [`s2n_connection_free`].
1646 fn drop(&mut self) {
1647 // ignore failures since there's not much we can do about it
1648 unsafe {
1649 // clean up context
1650 let _ = self.drop_context();
1651
1652 // cleanup config
1653 let _ = self.drop_config();
1654
1655 // cleanup connection
1656 let _ = s2n_connection_free(self.connection.as_ptr()).into_result();
1657 }
1658 }
1659 }
1660
1661 #[cfg(test)]
1662 mod tests {
1663 use futures_test::task::noop_waker;
1664
1665 use super::*;
1666 use crate::{
1667 security::Policy,
1668 testing::{build_config, config_builder, LIFOSessionResumption, SniTestCerts, TestPair},
1669 };
1670 use std::{
1671 net::{IpAddr, Ipv4Addr, SocketAddr},
1672 time::SystemTime,
1673 };
1674
1675 // ensure the connection context is send
1676 #[test]
1677 fn context_send_test() {
1678 fn assert_send<T: 'static + Send>() {}
1679 assert_send::<Context>();
1680 }
1681
1682 // ensure the connection context is sync
1683 #[test]
1684 fn context_sync_test() {
1685 fn assert_sync<T: 'static + Sync>() {}
1686 assert_sync::<Context>();
1687 }
1688
1689 /// Test that an application context can be set and retrieved.
1690 #[test]
1691 fn test_app_context_set_and_retrieve() {
1692 let mut connection = Connection::new_server();
1693
1694 let test_value: u32 = 1142;
1695
1696 // Before a context is set, None is returned.
1697 assert!(connection.application_context::<u32>().is_none());
1698
1699 connection.set_application_context(test_value);
1700
1701 // After a context is set, the application data is returned.
1702 assert_eq!(*connection.application_context::<u32>().unwrap(), 1142);
1703 }
1704
1705 /// Test that an application context can be modified.
1706 #[test]
1707 fn test_app_context_modify() {
1708 let test_value: u64 = 0;
1709
1710 let mut connection = Connection::new_server();
1711 connection.set_application_context(test_value);
1712
1713 let context_value = connection.application_context_mut::<u64>().unwrap();
1714 *context_value += 1;
1715
1716 assert_eq!(*connection.application_context::<u64>().unwrap(), 1);
1717 }
1718
1719 /// Test that an application context can be overridden.
1720 #[test]
1721 fn test_app_context_override() {
1722 let mut connection = Connection::new_server();
1723
1724 let test_value: u16 = 1142;
1725 connection.set_application_context(test_value);
1726
1727 assert_eq!(*connection.application_context::<u16>().unwrap(), 1142);
1728
1729 // Override the context with a new value.
1730 let test_value: u16 = 10;
1731 connection.set_application_context(test_value);
1732
1733 assert_eq!(*connection.application_context::<u16>().unwrap(), 10);
1734
1735 // Override the context with a new type.
1736 let test_value: i16 = -20;
1737 connection.set_application_context(test_value);
1738
1739 assert_eq!(*connection.application_context::<i16>().unwrap(), -20);
1740 }
1741
1742 /// Test that multiple application contexts can be set in a connection
1743 #[test]
1744 fn test_multiple_app_contexts() {
1745 let mut connection = Connection::new_server();
1746
1747 let first_test_value: u16 = 1142;
1748 connection.set_application_context(first_test_value);
1749
1750 assert_eq!(*connection.application_context::<u16>().unwrap(), 1142);
1751
1752 // Insert the second application context to the connection
1753 let second_test_value: SocketAddr =
1754 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
1755 connection.set_application_context(second_test_value);
1756
1757 assert_eq!(
1758 *connection.application_context::<SocketAddr>().unwrap(),
1759 second_test_value
1760 );
1761
1762 // Remove the second application context
1763 assert_eq!(
1764 second_test_value,
1765 *connection
1766 .remove_application_context::<SocketAddr>()
1767 .unwrap()
1768 .downcast::<SocketAddr>()
1769 .unwrap()
1770 );
1771
1772 assert!(connection.application_context::<SocketAddr>().is_none());
1773 }
1774
1775 /// Test that a context of another type can't be retrieved.
1776 #[test]
1777 fn test_app_context_invalid_type() {
1778 let mut connection = Connection::new_server();
1779
1780 let test_value: u32 = 0;
1781 connection.set_application_context(test_value);
1782
1783 // A context type that wasn't set shouldn't be returned.
1784 assert!(connection.application_context::<i16>().is_none());
1785
1786 // Retrieving the correct type succeeds.
1787 assert!(connection.application_context::<u32>().is_some());
1788 }
1789
1790 /// Test that the `certificate_match` Rust wrapper returns expected enum variant
1791 /// for different SNI scenarios (None, NoMatch, ExactMatch)
1792 #[test]
1793 fn test_certificate_match_variants() -> Result<(), Box<dyn std::error::Error>> {
1794 let scenarios = vec![
1795 (None, CertSNIMatch::NoSNI),
1796 (Some("nonmatching_sni"), CertSNIMatch::NoMatch),
1797 (Some("127.0.0.1"), CertSNIMatch::ExactMatch),
1798 ];
1799
1800 for (sni_opt, expected) in scenarios {
1801 let config = build_config(&security::DEFAULT_TLS13)?;
1802 let mut pair = TestPair::from_config(&config);
1803
1804 if let Some(sni) = sni_opt {
1805 pair.client.set_server_name(sni)?;
1806 }
1807
1808 pair.handshake()?;
1809 let cert_match = pair.server.certificate_match()?;
1810
1811 assert_eq!(cert_match, expected,);
1812 }
1813
1814 Ok(())
1815 }
1816
1817 /// Test that the `certificate_match` Rust wrapper returns WildcardMatch enum
1818 #[test]
1819 fn test_certificate_match_returns_wildcard_match() -> Result<(), Box<dyn std::error::Error>> {
1820 let wildcard_cert = SniTestCerts::WildcardInsectRsa.get();
1821
1822 let mut builder = crate::config::Builder::new();
1823 builder.load_pem(wildcard_cert.cert(), wildcard_cert.key())?;
1824 let server_config = builder.build()?;
1825
1826 let mut client_builder = crate::config::Builder::new();
1827 client_builder.trust_pem(wildcard_cert.cert())?;
1828 let client_config = client_builder.build()?;
1829
1830 let mut pair = TestPair::from_configs(&client_config, &server_config);
1831
1832 pair.client.set_server_name("anything.insect.hexapod")?;
1833 pair.handshake()?;
1834
1835 let cert_match = pair.server.certificate_match()?;
1836 assert_eq!(cert_match, CertSNIMatch::WildcardMatch);
1837
1838 Ok(())
1839 }
1840
1841 /// Test that `unstable_as_ptr()` can be used to call an s2n_tls_sys API.
1842 #[cfg(s2n_tls_external_build)]
1843 #[test]
1844 fn test_unstable_as_ptr() -> Result<(), Error> {
1845 let mut connection = Connection::new_client();
1846
1847 let test_server_name = "test-server-name";
1848 connection.set_server_name(test_server_name)?;
1849
1850 let server_name = unsafe {
1851 let server_name = s2n_get_server_name(connection.unstable_as_ptr());
1852 CStr::from_ptr(server_name).to_str().unwrap()
1853 };
1854
1855 assert_eq!(server_name, test_server_name);
1856 Ok(())
1857 }
1858
1859 #[test]
1860 fn signature_scheme_before_handshake() {
1861 let connection = Connection::new_server();
1862 assert_eq!(connection.signature_scheme(), None);
1863 }
1864
1865 #[test]
1866 fn signature_scheme_after_handshake() -> Result<(), Box<dyn std::error::Error>> {
1867 let server_config = {
1868 // arbitrary policy that negotiates a cipher suite with a signature scheme
1869 let policy = Policy::from_version("20240503")?;
1870 let mut builder = config_builder(&policy).unwrap();
1871 builder.add_session_ticket_key(
1872 b"a key name",
1873 b"good enough bytes for test",
1874 SystemTime::UNIX_EPOCH,
1875 )?;
1876 builder.build()?
1877 };
1878
1879 let client_config = {
1880 let session_tickets = LIFOSessionResumption::default();
1881 let mut builder = config_builder(&security::DEFAULT).unwrap();
1882 builder.enable_session_tickets(true)?;
1883 builder.set_session_ticket_callback(session_tickets.clone())?;
1884 builder.set_connection_initializer(session_tickets.clone())?;
1885 builder.build()?
1886 };
1887
1888 // full handshake: signature is reported
1889 {
1890 let mut test_pair = TestPair::from_configs(&client_config, &server_config);
1891 test_pair.client.set_waker(Some(&noop_waker()))?;
1892 test_pair.handshake().unwrap();
1893 // read in session_ticket
1894 assert!(test_pair.client.poll_recv(&mut [0]).is_pending());
1895
1896 for conn in [&test_pair.client, &test_pair.server] {
1897 assert_eq!(conn.signature_scheme(), Some("rsa_pss_rsae_sha256"))
1898 }
1899 }
1900
1901 // session resumption: signature is not reported
1902 {
1903 let mut test_pair = TestPair::from_configs(&client_config, &server_config);
1904 test_pair.client.set_waker(Some(&noop_waker()))?;
1905 test_pair.handshake().unwrap();
1906 assert!(test_pair.client.resumed());
1907 assert_eq!(test_pair.client.signature_scheme(), None);
1908 assert_eq!(test_pair.server.signature_scheme(), None);
1909 }
1910 Ok(())
1911 }
1912 }