| 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| 4 | //! Utilities to handle passing Rust code to s2n-tls's C callbacks. |
| 5 | //! |
| 6 | //! s2n-tls uses callbacks to temporarily return control to the application |
| 7 | //! and allow the application to execute custom code. |
| 8 | //! |
| 9 | //! To use a callback in your application, just implement the trait for the |
| 10 | //! target callback type and pass your implementation to the appropriate |
| 11 | //! connection or config method. For example, you can implement |
| 12 | //! [`ClientHelloCallback`] and pass that implementation to |
| 13 | //! [config::Builder::set_client_hello_callback()](`crate::config::Builder::set_client_hello_callback()`) |
| 14 | //! in order to execute custom logic after an s2n-tls server receives a client hello. |
| 15 | //! |
| 16 | //! s2n-tls callbacks come in two flavors: |
| 17 | //! * "sync" callbacks return an immediate result and will block the task |
| 18 | //! performing the handshake until they return success or failure. See |
| 19 | //! [`VerifyHostNameCallback`] as an example. |
| 20 | //! * "async" callbacks return a [Poll](`core::task::Poll`) and should not block the task performing the handshake. |
| 21 | //! They will be polled until they return [Poll::Ready](`core::task::Poll::Ready`). |
| 22 | //! [Connection::waker()](`crate::connection::Connection::waker()`) |
| 23 | //! can be used to register the task for wakeup. See [`ClientHelloCallback`] as an example. |
| 24 | |
| 25 | use crate::{config::Context, connection::Connection}; |
| 26 | use core::{mem::ManuallyDrop, ptr::NonNull, time::Duration}; |
| 27 | use s2n_tls_sys::s2n_connection; |
| 28 | |
| 29 | mod async_cb; |
| 30 | pub use async_cb::*; |
| 31 | |
| 32 | mod client_hello; |
| 33 | pub use client_hello::*; |
| 34 | |
| 35 | mod session_ticket; |
| 36 | pub use session_ticket::*; |
| 37 | |
| 38 | mod pkey; |
| 39 | pub use pkey::*; |
| 40 | |
| 41 | #[cfg(feature = "unstable-crl")] |
| 42 | mod cert_validation; |
| 43 | #[cfg(feature = "unstable-crl")] |
| 44 | pub use cert_validation::*; |
| 45 | |
| 46 | /// Convert the connection pointer provided to a callback into a Connection |
| 47 | /// and Context useable with the Rust bindings. |
| 48 | /// |
| 49 | /// # Safety |
| 50 | /// |
| 51 | /// This must ONLY be used for connection pointers provided to callbacks, |
| 52 | /// which can be assumed to point to valid Connections because the |
| 53 | /// callbacks were configured through the Rust bindings. |
| 54 | pub(crate) unsafe fn with_context<F, T>(conn_ptr: *mut s2n_connection, action: F) -> T |
| 55 | where |
| 56 | F: FnOnce(&mut Connection, &Context) -> T, |
| 57 | { |
| 58 | let raw = NonNull::new(conn_ptr).expect("connection should not be null"); |
| 59 | // Since this is a callback, it receives a pointer to the connection |
| 60 | // but doesn't own that connection or control its lifecycle. |
| 61 | // Do not drop / free the connection. |
| 62 | // We must make the connection `ManuallyDrop` before `action`, otherwise a panic |
| 63 | // in `action` would cause the unwind mechanism to drop the connection. |
| 64 | let mut conn = ManuallyDrop::new(Connection::from_raw(raw)); |
| 65 | let config = conn.config().expect("config should not be null"); |
| 66 | let context = config.context(); |
| 67 | action(&mut conn, context) |
| 68 | } |
| 69 | |
| 70 | /// A trait for the callback used to verify host name(s) during X509 |
| 71 | /// verification. |
| 72 | /// |
| 73 | /// The implementation should verify the certificate host name and return `true` |
| 74 | /// if the name is valid, `false` otherwise. |
| 75 | pub trait VerifyHostNameCallback: 'static + Send + Sync { |
| 76 | fn verify_host_name(&self, host_name: &str) -> bool; |
| 77 | } |
| 78 | |
| 79 | /// A trait for the callback used to retrieve the system / wall clock time. |
| 80 | pub trait WallClock: 'static + Send + Sync { |
| 81 | fn get_time_since_epoch(&self) -> Duration; |
| 82 | } |
| 83 | |
| 84 | /// A trait for the callback used to retrieve the monotonic time. |
| 85 | pub trait MonotonicClock: 'static + Send + Sync { |
| 86 | fn get_time(&self) -> Duration; |
| 87 | } |
| 88 | |
| 89 | /// Invoke the user provided VerifyHostNameCallback on the host_name. |
| 90 | /// |
| 91 | /// # Safety |
| 92 | /// |
| 93 | /// The caller must ensure that the memory underlying host_name is a valid |
| 94 | /// slice. |
| 95 | pub(crate) unsafe fn verify_host( |
| 96 | host_name: *const ::libc::c_char, |
| 97 | host_name_len: usize, |
| 98 | handler: &mut Box<dyn VerifyHostNameCallback>, |
| 99 | ) -> u8 { |
| 100 | let host_name = host_name as *const u8; |
| 101 | let host_name = core::slice::from_raw_parts(host_name, host_name_len); |
| 102 | |
| 103 | match core::str::from_utf8(host_name) { |
| 104 | Ok(host_name_str) => handler.verify_host_name(host_name_str) as u8, |
| 105 | Err(_) => 0, // If the host name can't be parsed, fail closed. |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | #[cfg(test)] |
| 110 | mod tests { |
| 111 | use crate::{callbacks::with_context, config::Config, connection::Builder, enums::Mode}; |
| 112 | |
| 113 | // The temporary connection created in `with_context` should never be freed, |
| 114 | // even if customer code panics. |
| 115 | #[test] |
| 116 | fn panic_does_not_free_connection() -> Result<(), crate::error::Error> { |
| 117 | let config = Config::new(); |
| 118 | let mut connection = config.build_connection(Mode::Server)?; |
| 119 | |
| 120 | // 1 connection + 1 self reference |
| 121 | assert_eq!(config.test_get_refcount()?, 2); |
| 122 | |
| 123 | let conn_ptr = connection.as_ptr(); |
| 124 | let unwind_result = std::panic::catch_unwind(|| { |
| 125 | unsafe { |
| 126 | with_context(conn_ptr, |_conn, _context| { |
| 127 | panic!("force unwind"); |
| 128 | }) |
| 129 | }; |
| 130 | }); |
| 131 | |
| 132 | // a panic happened |
| 133 | assert!(unwind_result.is_err()); |
| 134 | |
| 135 | // the connection hasn't been freed yet |
| 136 | assert_eq!(config.test_get_refcount()?, 2); |
| 137 | |
| 138 | drop(connection); |
| 139 | assert_eq!(config.test_get_refcount()?, 1); |
| 140 | |
| 141 | Ok(()) |
| 142 | } |
| 143 | } |