Debian Codegraph @

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

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! Methods to perform renegotiation.
5 //!
6 //! The use of renegotiation is strongly discouraged.
7 //! See [the C API documentation](https://github.com/aws/s2n-tls/blob/main/api/unstable/renegotiate.h)
8 //! for the primary documentation of the feature.
9 //!
10 //! # Scheduled renegotiation
11 //!
12 //! The Rust client can automatically renegotiate in response to a server renegotiation
13 //! request, if an application does not require support for concurrent reads and writes.
14 //! This feature is intended for applications that follow a standard request/response model.
15 //!
16 //! To use scheduled renegotiation, your must set a [`RenegotiateCallback`] that
17 //! returns [`RenegotiateResponse::Schedule`].
18 //!
19 //! If all renegotiation requests will be accepted and no connection-level
20 //! configuration is required, then [`RenegotiateResponse`] can be used as the
21 //! RenegotiateCallback. For example:
22 //! ```
23 //! use s2n_tls::config::Builder;
24 //! use s2n_tls::renegotiate::RenegotiateResponse;
25 //!
26 //! let mut builder = Builder::new();
27 //! builder.set_renegotiate_callback(RenegotiateResponse::Schedule);
28 //! ```
29 //!
30 //! If an application needs to conditionally accept renegotiation requests or
31 //! uses connection-level configuration that will need to be reset after the
32 //! connection is wiped for renegotiation, then the application will need to
33 //! implement a custom `RenegotiateCallback`:
34 //! ```
35 //! use s2n_tls::config::Builder;
36 //! use s2n_tls::connection::Connection;
37 //! use s2n_tls::error::Error;
38 //! use s2n_tls::renegotiate::{RenegotiateCallback, RenegotiateResponse};
39 //!
40 //! struct Callback { };
41 //!
42 //! impl RenegotiateCallback for Callback {
43 //! fn on_renegotiate_request(
44 //! &self,
45 //! conn: &mut Connection,
46 //! ) -> Option<RenegotiateResponse> {
47 //! let response = match conn.server_name() {
48 //! Some("allowed_to_renegotiate") => RenegotiateResponse::Schedule,
49 //! _ => RenegotiateResponse::Reject,
50 //! };
51 //! Some(response)
52 //! }
53 //!
54 //! fn on_renegotiate_wipe(&self, conn: &mut Connection) -> Result<(), Error> {
55 //! conn.set_application_protocol_preference(Some("http"))?;
56 //! Ok(())
57 //! }
58 //! }
59 //!
60 //! let mut builder = Builder::new();
61 //! builder.set_renegotiate_callback(Callback{});
62 //! ```
63 //! #### Warning:
64 //!
65 //! If you are using s2n-tls via a higher level wrapper like s2n-tls-tokio or
66 //! s2n-tls-hyper, that wrapper may automatically set connection-level configuration
67 //! for you. As such wrappers are unlikely to be aware of renegotiation, they will
68 //! not automatically reset their configuration after the connection is wiped for
69 //! renegotiation. You may need to handle resetting the configuration yourself
70 //! via `on_renegotiate_wipe`. If that is not possible, please open an issue.
71 //!
72 //! ## How it works
73 //!
74 //! When a call to `poll_recv` receives a renegotiation request, `on_renegotiate_request`
75 //! will be invoked for the connection's `RenegotiateCallback`. If `on_renegotiate_request`
76 //! returns `RenegotiateResponse::Schedule`, then s2n-tls will automatically schedule
77 //! renegotiation. Once renegotiation begins, calls to `poll_recv` will attempt
78 //! to renegotiate by wiping the connection, which will trigger `on_renegotiate_wipe`
79 //! from the connection's `RenegotiateCallback`. After wiping, `poll_recv` will
80 //! perform a new handshake.
81 //!
82 //! #### Warning:
83 //! While performing the new handshake, `poll_recv` will write, not just read.
84 //! This may violate assumptions your application is making about IO operations.
85 //!
86 //! ## Detailed limitations
87 //!
88 //! Specifically, scheduled renegotiation will fail if `poll_send`:
89 //! 1. is called after the renegotiation request is received from the server.
90 //! 2. returned `Pending` and has not yet returned `Ready` before the renegotiation
91 //! request is received from the server.
92 //!
93 //! These limitations are a blocker for an application that supports concurrent
94 //! reads and writes, or which must support an arbitrary ordering of reads and
95 //! writes. Custom renegotiation will be required for those use cases.
96 //!
97 //! # Custom renegotiation
98 //!
99 //! The bindings also provide [`Connection::wipe_for_renegotiate()`] and [`Connection::poll_renegotiate()`]
100 //! as direct mappings of the C `s2n_renegotiate_wipe` and `s2n_renegotiate` methods.
101 //! If scheduled renegotiation is insufficient for your use case, you can manually
102 //! integrate with renegotiation according to the instructions in
103 //! [the C API documentation](https://github.com/aws/s2n-tls/blob/main/api/unstable/renegotiate.h).
104 //! Your `on_renegotiate_request` method would return `RenegotiateResponse::Accept`
105 //! rather than `RenegotiateResponse::Schedule`.
106 //!
107
108 use s2n_tls_sys::*;
109
110 use crate::{
111 callbacks::with_context,
112 config,
113 connection::Connection,
114 enums::CallbackResult,
115 error::{Error, ErrorType, Fallible, Pollable},
116 };
117 use std::task::Poll::{self, Pending, Ready};
118
119 /// How to handle a renegotiation request.
120 ///
121 /// Corresponds to [`s2n_renegotiate_response`].
122 #[derive(Debug, PartialEq, Copy, Clone)]
123 pub enum RenegotiateResponse {
124 Ignore,
125 Reject,
126 Accept,
127 /// The same as `Accept`, but also automatically perform renegotiation
128 /// when `poll_recv` is called.
129 Schedule,
130 }
131
132 impl From<RenegotiateResponse> for s2n_renegotiate_response::Type {
133 fn from(input: RenegotiateResponse) -> s2n_renegotiate_response::Type {
134 match input {
135 RenegotiateResponse::Ignore => s2n_renegotiate_response::RENEGOTIATE_IGNORE,
136 RenegotiateResponse::Reject => s2n_renegotiate_response::RENEGOTIATE_REJECT,
137 RenegotiateResponse::Accept => s2n_renegotiate_response::RENEGOTIATE_ACCEPT,
138 RenegotiateResponse::Schedule => s2n_renegotiate_response::RENEGOTIATE_ACCEPT,
139 }
140 }
141 }
142
143 /// Callbacks related to the renegotiation TLS feature.
144 pub trait RenegotiateCallback: 'static + Send + Sync {
145 /// A callback that triggers when the client receives a renegotiation request
146 /// (a HelloRequest message) from the server.
147 ///
148 /// Returning `Some(RenegotiateResponse::Schedule)` will trigger s2n-tls
149 /// to automatically wipe the connection and renegotiate.
150 ///
151 /// Returning "None" will result in the C callback returning an error,
152 /// canceling the connection.
153 ///
154 /// See [`s2n_renegotiate_request_cb`].
155 //
156 // This method returns Option instead of Result because the callback has no mechanism
157 // for surfacing errors to the application, so Result would be somewhat deceptive.
158 fn on_renegotiate_request(&self, connection: &mut Connection) -> Option<RenegotiateResponse>;
159
160 /// A callback that triggers after the connection is wiped for renegotiation.
161 ///
162 /// Because renegotiation requires wiping the connection, connection-level
163 /// configuration will need to be set again via this callback.
164 /// See [`Connection::wipe_for_renegotiate()`] for more information.
165 fn on_renegotiate_wipe(&self, _connection: &mut Connection) -> Result<(), Error> {
166 Ok(())
167 }
168 }
169
170 impl RenegotiateCallback for RenegotiateResponse {
171 fn on_renegotiate_request(&self, _conn: &mut Connection) -> Option<RenegotiateResponse> {
172 Some(*self)
173 }
174 }
175
176 #[derive(Clone, Debug, Default, PartialEq)]
177 pub(crate) struct RenegotiateState {
178 needs_handshake: bool,
179 needs_wipe: bool,
180 send_pending: bool,
181 }
182
183 impl Connection {
184 fn schedule_renegotiate(&mut self) {
185 let state = self.renegotiate_state_mut();
186 if !state.needs_handshake {
187 state.needs_handshake = true;
188 state.needs_wipe = true;
189 }
190 }
191
192 fn is_renegotiating(&self) -> bool {
193 self.renegotiate_state().needs_handshake
194 }
195
196 /// Reset the connection so that it can be renegotiated.
197 ///
198 /// Corresponds to [`s2n_renegotiate_wipe`].
199 /// The Rust equivalent of the listed connection-specific methods that are NOT wiped are:
200 /// - Methods to set the file descriptors: not currently supported by rust bindings
201 /// - Methods to set the send callback:
202 /// [Connection::set_send_callback()], [Connection::set_send_context()]
203 /// - Methods to set the recv callback:
204 /// [Connection::set_receive_callback()], [Connection::set_receive_context()]
205 ///
206 /// In addition, the Rust bindings do not wipe:
207 /// - The server name: [Connection::set_server_name()]. The s2n-tls-tokio
208 /// TlsConnector sets the server name automatically, so preserving it across
209 /// wipes prevents all users of s2n-tls-tokio from needing a custom callback
210 /// just to maintain consistent behavior.
211 /// - The waker: [Connection::set_waker()]. Wiping the waker during a call
212 /// to `poll_send` or `poll_recv` can break IO.
213 ///
214 /// The set of configuration values that are not wiped may change in the future.
215 /// Therefore if you specifically need certain connection configuration values
216 /// wiped during renegotiation, then you should wipe them yourself in
217 /// [RenegotiateCallback::on_renegotiate_wipe()].
218 pub fn wipe_for_renegotiate(&mut self) -> Result<(), Error> {
219 // Check for buffered data in order to surface more specific
220 // error messages to the application.
221 if self.renegotiate_state().send_pending {
222 return Err(Error::bindings(
223 ErrorType::UsageError,
224 "RenegotiateError",
225 "Unexpected buffered send data during renegotiate",
226 ));
227 }
228
229 // Save any state that needs to be preserved.
230 // The only real cost of saving state here is complexity. We can't save all
231 // connection configuration automatically because in the C library, connection
232 // configuration is indistinguishable from C connection state.
233 let renegotiate_state = self.renegotiate_state().clone();
234 let waker = self.waker().cloned();
235 let server_name = self.server_name().map(|name| name.to_owned());
236
237 self.wipe_method(|conn| unsafe { s2n_renegotiate_wipe(conn.as_ptr()).into_result() })?;
238
239 // Restore the saved state
240 *self.renegotiate_state_mut() = renegotiate_state;
241 self.set_waker(waker.as_ref())?;
242 if let Some(server_name) = server_name {
243 self.set_server_name(&server_name)?;
244 }
245
246 // We trigger the callback last so that the application can modify any
247 // preserved configuration (like the server name or waker) if necessary.
248 if let Some(config) = self.config() {
249 if let Some(callback) = config.context().renegotiate.as_ref() {
250 callback.on_renegotiate_wipe(self)?;
251 }
252 }
253
254 self.renegotiate_state_mut().needs_wipe = false;
255 Ok(())
256 }
257
258 fn poll_renegotiate_raw(
259 &mut self,
260 buf_ptr: *mut libc::c_void,
261 buf_len: isize,
262 ) -> (Poll<Result<(), Error>>, usize) {
263 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
264 let mut read: isize = 0;
265 let r = self.poll_negotiate_method(|conn| {
266 unsafe {
267 s2n_renegotiate(
268 conn.as_ptr(),
269 buf_ptr as *mut u8,
270 buf_len,
271 &mut read,
272 &mut blocked,
273 )
274 }
275 .into_poll()
276 });
277 if let Ready(Ok(())) = r {
278 self.renegotiate_state_mut().needs_handshake = false;
279 }
280 (r, read.try_into().unwrap())
281 }
282
283 /// Perform a new handshake on an already established connection.
284 ///
285 /// The first element of the returned pair represents progress on the new
286 /// handshake, like [Connection::poll_negotiate()].
287 ///
288 /// If any application data is received during the new handshake, the number
289 /// of bytes received is returned as the second element of the returned pair,
290 /// and the data is written to `buf`.
291 ///
292 /// Corresponds to [`s2n_renegotiate`].
293 pub fn poll_renegotiate(&mut self, buf: &mut [u8]) -> (Poll<Result<(), Error>>, usize) {
294 let buf_len: isize = buf.len().try_into().unwrap_or(0);
295 let buf_ptr = buf.as_ptr() as *mut ::libc::c_void;
296 self.poll_renegotiate_raw(buf_ptr, buf_len)
297 }
298
299 /// Encrypts and sends data on a connection where
300 /// [negotiate](`Self::poll_negotiate`) has succeeded.
301 ///
302 /// Returns the number of bytes written, and may indicate a partial write.
303 ///
304 /// Corresponds to [`s2n_send`].
305 pub fn poll_send(&mut self, buf: &[u8]) -> Poll<Result<usize, Error>> {
306 if self.is_renegotiating() {
307 return Ready(Err(Error::bindings(
308 ErrorType::Blocked,
309 "RenegotiateError",
310 "Cannot send application data while renegotiating",
311 )));
312 }
313 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
314 let buf_len: isize = buf.len().try_into().map_err(|_| Error::INVALID_INPUT)?;
315 let buf_ptr = buf.as_ptr() as *const libc::c_void;
316 let result = unsafe { s2n_send(self.as_ptr(), buf_ptr, buf_len, &mut blocked) }.into_poll();
317 self.renegotiate_state_mut().send_pending = result.is_pending();
318 result
319 }
320
321 pub(crate) fn poll_recv_raw(
322 &mut self,
323 buf_ptr: *mut libc::c_void,
324 buf_len: isize,
325 ) -> Poll<Result<usize, Error>> {
326 if !self.is_renegotiating() {
327 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
328 let result =
329 unsafe { s2n_recv(self.as_ptr(), buf_ptr, buf_len, &mut blocked).into_poll() };
330 // A call to s2n_recv that initiates renegotiation is blocked on
331 // renegotiation, not on application data.
332 // If we just return Pending, we may never start the handshake so
333 // may never receive any more data from the server.
334 // Instead, attempt to renegotiate at least once.
335 return if self.is_renegotiating() && result.is_pending() {
336 // We call poll_recv_raw instead of poll_renegotiate because we
337 // could theoretically complete the entire handshake and read the
338 // application data originally requested.
339 // This also makes ensuring the wipe easier.
340 self.poll_recv_raw(buf_ptr, buf_len)
341 } else {
342 result
343 };
344 }
345
346 // Check to see if we need to drain any application bytes before
347 // kicking off the renegotiation
348 if self.peek_len() > 0 {
349 let buf_len = std::cmp::min(self.peek_len() as isize, buf_len);
350 let mut blocked = s2n_blocked_status::NOT_BLOCKED;
351 return unsafe { s2n_recv(self.as_ptr(), buf_ptr, buf_len, &mut blocked).into_poll() };
352 }
353
354 // Wipe if starting renegotiation
355 if self.renegotiate_state().needs_wipe {
356 self.wipe_for_renegotiate()?;
357 }
358
359 match self.poll_renegotiate_raw(buf_ptr, buf_len) {
360 (Ready(Err(err)), _) => Ready(Err(err)),
361 // If renegotiate succeeds with no data read, we need to return
362 // some result:
363 // - We can't return Ready(Ok(0)), because that would indicate
364 // end-of-stream.
365 // - We can't return Pending, because we are not actually blocked
366 // on anything so there would be no guarantee of another poll.
367 // Instead, re-attempt to perform the original receive call
368 // and return that result.
369 (Ready(Ok(())), 0) => self.poll_recv_raw(buf_ptr, buf_len),
370 (Pending, 0) => Pending,
371 (_, bytes) => Ready(Ok(bytes)),
372 }
373 }
374 }
375
376 impl config::Builder {
377 /// Sets a method to be called when the client receives a request to renegotiate.
378 ///
379 /// Corresponds to [`s2n_config_set_renegotiate_request_cb`].
380 pub fn set_renegotiate_callback<T: 'static + RenegotiateCallback>(
381 &mut self,
382 handler: T,
383 ) -> Result<&mut Self, Error> {
384 unsafe extern "C" fn renegotiate_cb(
385 conn_ptr: *mut s2n_connection,
386 _context: *mut libc::c_void,
387 response: *mut s2n_renegotiate_response::Type,
388 ) -> libc::c_int {
389 with_context(conn_ptr, |conn, context| {
390 let callback = context.renegotiate.as_ref();
391 if let Some(callback) = callback {
392 if let Some(result) = callback.on_renegotiate_request(conn) {
393 // If the callback indicates renegotiation, schedule it.
394 // This doesn't actually do any work related to renegotiation,
395 // It just indicates that work needs to be done later.
396 if result == RenegotiateResponse::Schedule {
397 conn.schedule_renegotiate();
398 }
399 *response = result.into();
400 return CallbackResult::Success.into();
401 }
402 }
403 CallbackResult::Failure.into()
404 })
405 }
406
407 let handler = Box::new(handler);
408 let context = unsafe {
409 // SAFETY: usage of context_mut is safe in the builder, because while
410 // it is being built, the Builder is the only reference to the config.
411 self.config.context_mut()
412 };
413 context.renegotiate = Some(handler);
414 unsafe {
415 s2n_config_set_renegotiate_request_cb(
416 self.as_mut_ptr(),
417 Some(renegotiate_cb),
418 std::ptr::null_mut(),
419 )
420 .into_result()?;
421 }
422 Ok(self)
423 }
424 }
425
426 #[cfg(test)]
427 mod tests {
428 use super::*;
429 use crate::{
430 callbacks::{
431 ConnectionFuture, ConnectionFutureResult, PrivateKeyCallback, PrivateKeyOperation,
432 },
433 config::ConnectionInitializer,
434 error::{ErrorSource, ErrorType},
435 testing::{CertKeyPair, InsecureAcceptAllCertificatesHandler, TestPair, TestPairIO},
436 };
437 use foreign_types::ForeignTypeRef;
438 use futures_test::task::new_count_waker;
439 use openssl::ssl::{
440 ErrorCode, Ssl, SslContext, SslFiletype, SslMethod, SslStream, SslVerifyMode, SslVersion,
441 };
442 use std::{
443 error::Error,
444 io::{Read, Write},
445 pin::Pin,
446 task::Poll::{Pending, Ready},
447 };
448
449 // The partial word is intentional to match variations:
450 // "renegotiate", "renegotiating", "renegotiation"
451 const RENEG_ERR_MARKER: &str = "renegotiat";
452
453 // Currently renegotiation is not available from the openssl-sys bindings
454 extern "C" {
455 fn SSL_renegotiate(s: *mut openssl_sys::SSL) -> libc::size_t;
456 fn SSL_renegotiate_pending(s: *mut openssl_sys::SSL) -> libc::size_t;
457 fn SSL_in_init(s: *mut openssl_sys::SSL) -> libc::size_t;
458 }
459
460 // std::task::ready is unstable
461 fn unwrap_poll<T>(
462 poll: Poll<Result<T, crate::error::Error>>,
463 ) -> Result<T, crate::error::Error> {
464 if let Ready(value) = poll {
465 return value;
466 }
467 panic!("Poll not Ready");
468 }
469
470 #[derive(Debug)]
471 struct ServerTestStream(TestPairIO);
472
473 // For server testing purposes, we read from the client output stream
474 impl Read for ServerTestStream {
475 fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
476 let result = self.0.client_tx_stream.borrow_mut().read(buf);
477 if let Ok(0) = result {
478 // Treat no data as blocking instead of EOF
479 Err(std::io::Error::new(
480 std::io::ErrorKind::WouldBlock,
481 "blocking",
482 ))
483 } else {
484 result
485 }
486 }
487 }
488
489 // For server testing purposes, we write to the server output stream
490 impl Write for ServerTestStream {
491 fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
492 self.0.server_tx_stream.borrow_mut().write(buf)
493 }
494
495 fn flush(&mut self) -> Result<(), std::io::Error> {
496 self.0.server_tx_stream.borrow_mut().flush()
497 }
498 }
499
500 // s2n-tls doesn't support sending client hello requests.
501 // This makes it impossible to test renegotiation without direct access to
502 // s2n-tls internals like the methods for sending arbitrary records.
503 // Instead, we need to use openssl as our server.
504 //
505 // The openssl SslStream::new method requires an owned Stream,
506 // so the openssl server owns the TestPairIO. This is possible because the
507 // s2n-tls client only references the TestPairIO via C callbacks.
508 struct RenegotiateTestPair {
509 client: Connection,
510 server: SslStream<ServerTestStream>,
511 }
512
513 impl RenegotiateTestPair {
514 fn from(mut builder: config::Builder) -> Result<Self, Box<dyn Error>> {
515 // openssl and s2n-tls must be configured to accept each other's
516 // certificates. Some tests will require client auth.
517 //
518 // openssl also requires a properly configured CA cert, which the
519 // default TestPair does not include.
520 let certs = CertKeyPair::from_path(
521 "permutations/rsae_pkcs_4096_sha384/",
522 "server-chain",
523 "server-key",
524 "ca-cert",
525 );
526
527 // Build the s2n-tls client.
528 builder.load_pem(certs.cert(), certs.key())?;
529 builder.trust_pem(certs.cert())?;
530 builder.set_verify_host_callback(InsecureAcceptAllCertificatesHandler {})?;
531 let config = builder.build()?;
532 let s2n_pair = TestPair::from_config(&config);
533 let client = s2n_pair.client;
534
535 // Build the openssl server.
536 let mut ctx_builder = SslContext::builder(SslMethod::tls_server())?;
537 ctx_builder.set_max_proto_version(Some(SslVersion::TLS1_2))?;
538 ctx_builder.set_min_proto_version(Some(SslVersion::TLS1_2))?;
539 ctx_builder.set_certificate_chain_file(certs.cert_path())?;
540 ctx_builder.set_private_key_file(certs.key_path(), SslFiletype::PEM)?;
541 ctx_builder.set_ca_file(certs.ca_path())?;
542 ctx_builder.set_verify(SslVerifyMode::PEER);
543 let openssl_ctx = ctx_builder.build();
544 let openssl_ssl = Ssl::new(&openssl_ctx)?;
545
546 // Connect the openssl server to the same IO that the s2n-tls
547 // client was constructed to use.
548 let server_stream = ServerTestStream(s2n_pair.io);
549 let server = SslStream::new(openssl_ssl, server_stream)?;
550
551 Ok(Self { client, server })
552 }
553
554 // Translate the output of openssl's `accept` to match s2n-tls's `poll_negotiate`.
555 fn poll_openssl_negotiate(
556 server: &mut SslStream<ServerTestStream>,
557 ) -> Poll<Result<(), Box<dyn Error>>> {
558 match server.accept() {
559 Ok(_) => Ready(Ok(())),
560 Err(err) if err.code() == ErrorCode::WANT_READ => Pending,
561 Err(err) => Ready(Err(err.into())),
562 }
563 }
564
565 // Perform a handshake with the s2n-tls client and openssl server
566 fn handshake(&mut self) -> Result<(), Box<dyn Error>> {
567 loop {
568 match (
569 self.client.poll_negotiate(),
570 Self::poll_openssl_negotiate(&mut self.server),
571 ) {
572 (Poll::Ready(Ok(_)), Poll::Ready(Ok(_))) => return Ok(()),
573 // Error on the server
574 (_, Poll::Ready(Err(e))) => return Err(e),
575 // Error on the client
576 (Poll::Ready(Err(e)), _) => return Err(Box::new(e)),
577 _ => continue,
578 }
579 }
580 }
581
582 // Send a renegotiation HelloRequest and drain the 1-byte flush
583 // payload so callers don't have to deal with it.
584 fn send_renegotiate_request(&mut self) -> Result<(), crate::error::Error> {
585 let openssl_ptr = self.server.ssl().as_ptr();
586
587 // Sanity check that renegotiation is not initially scheduled
588 let requested = unsafe { SSL_renegotiate_pending(openssl_ptr) };
589 assert_eq!(requested, 0, "Renegotiation should not be pending");
590
591 // Schedule renegotiation
592 unsafe { SSL_renegotiate(openssl_ptr) };
593
594 // Verify that openssl scheduled the renegotiation
595 let requested = unsafe { SSL_renegotiate_pending(openssl_ptr) };
596 assert_eq!(requested, 1, "Renegotiation should be pending");
597
598 // SSL_renegotiate only schedules the HelloRequest internally.
599 // A subsequent SSL_write flushes it. OpenSSL 3.6.1 changed
600 // this behavior such that zero-length writes are now no-ops,
601 // so we now write a single byte to force the flush.
602 assert_eq!(
603 self.server
604 .write(&[0])
605 .expect("Failed to write hello request"),
606 1
607 );
608
609 // Drain the 1-byte flush payload
610 match self.client.poll_recv(&mut [0; 1]) {
611 Ready(Ok(1)) => Ok(()),
612 Ready(Err(e)) => Err(e),
613 other => panic!("Expected to drain flush byte, got {:?}", other),
614 }
615 }
616
617 // Send and receive application data.
618 // We have to ensure that application data continues to work during / after
619 // the renegotiate.
620 fn send_and_receive(&mut self) -> Result<(), Box<dyn Error>> {
621 let to_send = [0; 1];
622 let mut recv_buffer = [0; 1];
623 self.server.write_all(&to_send)?;
624 unwrap_poll(self.client.poll_recv(&mut recv_buffer))?;
625 unwrap_poll(self.client.poll_send(&to_send))?;
626 self.server.read_exact(&mut recv_buffer)?;
627 Ok(())
628 }
629
630 // This indicates that openssl is performing a handshake, but not
631 // specifically a renegotiation handshake. Ensure that the initial
632 // handshake is complete before assuming that this indicates renegotiation.
633 fn openssl_is_handshaking(&self) -> bool {
634 (unsafe { SSL_in_init(self.server.ssl().as_ptr()) } == 1)
635 }
636
637 // The client drives renegotiation via poll_recv in order to read
638 // application data written by the server after the new handshake.
639 fn assert_renegotiate(&mut self) -> Result<(), Box<dyn Error>> {
640 const APP_DATA: &[u8] = b"Renegotiation complete";
641
642 // Complete the renegotiation handshake first.
643 self.finish_renegotiate();
644
645 // Now send and receive application data to confirm the
646 // renegotiated connection works.
647 self.server
648 .write_all(APP_DATA)
649 .expect("server app data after renegotiation");
650
651 let mut buffer = [0; APP_DATA.len()];
652 let bytes_read = unwrap_poll(self.client.poll_recv(&mut buffer))?;
653 assert_eq!(bytes_read, APP_DATA.len());
654 assert_eq!(&buffer, APP_DATA);
655
656 assert!(
657 !self.client.is_renegotiating(),
658 "s2n-tls renegotiation not complete"
659 );
660 assert!(
661 !self.openssl_is_handshaking(),
662 "openssl renegotiation not complete"
663 );
664 Ok(())
665 }
666
667 // Drive both sides until the renegotiation handshake completes,
668 // without sending or expecting application data.
669 fn finish_renegotiate(&mut self) {
670 while self.client.is_renegotiating() || self.openssl_is_handshaking() {
671 let _ = self.client.poll_recv(&mut [0; 1]);
672 // Use a non-zero-length buffer so SSL_read actually
673 // processes incoming handshake messages from the client.
674 let _ = self.server.read(&mut [0; 1]);
675 }
676 }
677 }
678
679 #[test]
680 fn ignore_callback() -> Result<(), Box<dyn Error>> {
681 let mut builder = config::Builder::new();
682 builder.set_renegotiate_callback(RenegotiateResponse::Ignore)?;
683 let mut pair = RenegotiateTestPair::from(builder)?;
684
685 pair.handshake().expect("Initial handshake");
686
687 // Expect receiving the hello request to be successful
688 pair.send_renegotiate_request()
689 .expect("Server sends request");
690 pair.send_and_receive().expect("Application data");
691 assert!(!pair.client.is_renegotiating(), "Unexpected renegotiation");
692
693 Ok(())
694 }
695
696 // In practice, "accept" behaves just like "ignore".
697 // The only current difference is application intention.
698 #[test]
699 fn accept_callback() -> Result<(), Box<dyn Error>> {
700 let mut builder = config::Builder::new();
701 builder.set_renegotiate_callback(RenegotiateResponse::Accept)?;
702 let mut pair = RenegotiateTestPair::from(builder)?;
703
704 pair.handshake().expect("Initial handshake");
705
706 // Expect receiving the hello request to be successful
707 pair.send_renegotiate_request()
708 .expect("Server sends request");
709 pair.send_and_receive().expect("Application data");
710 assert!(!pair.client.is_renegotiating(), "Unexpected renegotiation");
711
712 Ok(())
713 }
714
715 #[test]
716 fn error_callback() -> Result<(), Box<dyn Error>> {
717 struct ErrorRenegotiateCallback {}
718 impl RenegotiateCallback for ErrorRenegotiateCallback {
719 fn on_renegotiate_request(&self, _: &mut Connection) -> Option<RenegotiateResponse> {
720 None
721 }
722 }
723
724 let mut builder = config::Builder::new();
725 builder.set_renegotiate_callback(ErrorRenegotiateCallback {})?;
726 let mut pair = RenegotiateTestPair::from(builder)?;
727
728 pair.handshake().expect("Initial handshake");
729 // send_renegotiate_request() returns Err if the client's renegotiate
730 // callback errors when processing the HelloRequest during the drain.
731 let error = pair.send_renegotiate_request().unwrap_err();
732 assert_eq!(error.name(), "S2N_ERR_CANCELLED");
733
734 Ok(())
735 }
736
737 #[test]
738 fn reject_callback() -> Result<(), Box<dyn Error>> {
739 let mut builder = config::Builder::new();
740 builder.set_renegotiate_callback(RenegotiateResponse::Reject)?;
741 let mut pair = RenegotiateTestPair::from(builder)?;
742
743 pair.handshake().expect("Initial handshake");
744 pair.send_renegotiate_request()
745 .expect("Server sends request");
746 // s2n-tls doesn't fail when it rejects renegotiation, it just sends
747 // a warning alert. The peer chooses how to handle that alert.
748 // The openssl server receives the alert on its next read.
749 // Openssl considers the alert an error.
750 let openssl_error = pair.send_and_receive().unwrap_err();
751 assert!(openssl_error.to_string().contains("no renegotiation"));
752
753 Ok(())
754 }
755
756 #[test]
757 fn scheduled_renegotiate_basic() -> Result<(), Box<dyn Error>> {
758 let mut builder = config::Builder::new();
759 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
760 let mut pair = RenegotiateTestPair::from(builder)?;
761
762 pair.handshake().expect("Initial handshake");
763 pair.send_and_receive()
764 .expect("Application data before renegotiate");
765 pair.send_renegotiate_request()
766 .expect("Server sends request");
767 pair.assert_renegotiate().expect("Renegotiate");
768 pair.send_and_receive()
769 .expect("Application data after renegotiate");
770
771 Ok(())
772 }
773
774 #[test]
775 fn scheduled_renegotiate_repeatedly() -> Result<(), Box<dyn Error>> {
776 let mut builder = config::Builder::new();
777 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
778 let mut pair = RenegotiateTestPair::from(builder)?;
779
780 pair.handshake().expect("Initial handshake");
781
782 for _ in 0..10 {
783 pair.send_and_receive()
784 .expect("Application data before renegotiate");
785 pair.send_renegotiate_request()
786 .expect("Server sends request");
787 pair.assert_renegotiate().expect("Renegotiate");
788 pair.send_and_receive()
789 .expect("Application data after renegotiate");
790 }
791
792 Ok(())
793 }
794
795 // Application data received immediately after the hello request message
796 // is handled by the initial s2n_recv call rather than s2n_renegotiate
797 #[test]
798 fn scheduled_renegotiate_with_immediate_app_data() -> Result<(), Box<dyn Error>> {
799 let mut builder = config::Builder::new();
800 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
801 let mut pair = RenegotiateTestPair::from(builder)?;
802 pair.handshake().expect("Initial handshake");
803
804 // Server sends app data immediately after hello request
805 let server_data = b"server_data";
806 pair.send_renegotiate_request()
807 .expect("server hello request");
808 pair.server
809 .write_all(server_data)
810 .expect("server app data after hello request");
811
812 // First poll reads both the hello request and the app data
813 let mut buffer = [0; 100];
814 let read = unwrap_poll(pair.client.poll_recv(&mut buffer))?;
815 assert_eq!(read, server_data.len());
816 assert_eq!(&buffer[0..read], server_data);
817 assert!(pair.client.is_renegotiating());
818
819 pair.assert_renegotiate().expect("Renegotiate");
820 Ok(())
821 }
822
823 // Application data received some time after the hello request is handled
824 // by s2n_renegotiate rather than s2n_recv.
825 #[test]
826 fn scheduled_renegotiate_with_delayed_app_data() -> Result<(), Box<dyn Error>> {
827 let mut builder = config::Builder::new();
828 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
829 let mut pair = RenegotiateTestPair::from(builder)?;
830 pair.handshake().expect("Initial handshake");
831
832 // Server sends hello request, but initially no app data
833 pair.send_renegotiate_request()
834 .expect("server hello request");
835
836 // Client can read the hello request
837 let mut buffer = [0; 100];
838 let poll = pair.client.poll_recv(&mut buffer);
839 assert!(poll.is_pending());
840 assert!(pair.client.is_renegotiating());
841
842 // Server sends app data
843 let server_data = b"server_data";
844 pair.server
845 .write_all(server_data)
846 .expect("server app data after hello request");
847
848 // Client reads app data
849 let mut buffer = [0; 100];
850 let read = unwrap_poll(pair.client.poll_recv(&mut buffer))?;
851 assert_eq!(read, server_data.len());
852 assert_eq!(&buffer[0..read], server_data);
853 assert!(pair.client.is_renegotiating());
854
855 pair.assert_renegotiate().expect("Renegotiate");
856 Ok(())
857 }
858
859 // assert_renegotiate sends application data for the client to receive
860 // as soon as the handshake completes. Also test with no final application data.
861 #[test]
862 fn scheduled_renegotiate_without_final_app_data() -> Result<(), Box<dyn Error>> {
863 let mut builder = config::Builder::new();
864 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
865 let mut pair = RenegotiateTestPair::from(builder)?;
866 pair.handshake().expect("Initial handshake");
867
868 // Server sends hello request, but initially no app data
869 pair.send_renegotiate_request()
870 .expect("server hello request");
871
872 // Client and server renegotiate while never reading app data
873 pair.finish_renegotiate();
874
875 // Send and receive application data after renegotiation
876 pair.send_and_receive()
877 .expect("Application data after renegotiate");
878
879 Ok(())
880 }
881
882 // Renegotiation should be able to clear buffered receive data before wiping
883 #[test]
884 fn scheduled_renegotiate_with_buffered_recv() -> Result<(), Box<dyn Error>> {
885 let mut builder = config::Builder::new();
886 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
887 let mut pair = RenegotiateTestPair::from(builder)?;
888 pair.handshake().expect("Initial handshake");
889
890 pair.send_renegotiate_request()
891 .expect("Server sends request");
892 let server_data = b"server_data";
893 assert_eq!(
894 pair.server.write(server_data).expect("server app data"),
895 server_data.len()
896 );
897
898 // Read only the first byte of the server data
899 let mut buffer = [0; 100];
900 let read = unwrap_poll(pair.client.poll_recv(&mut buffer[..1]))
901 .expect("Read first byte of server data");
902 assert_eq!(read, 1);
903 assert_eq!(buffer[0], server_data[0]);
904 assert!(pair.client.is_renegotiating());
905
906 // Read the rest of the server data
907 let read = unwrap_poll(pair.client.poll_recv(&mut buffer[1..]))
908 .expect("Drain buffered receive data");
909 assert_eq!(read, server_data.len() - 1);
910 assert_eq!(&buffer[..server_data.len()], server_data);
911 assert!(pair.client.is_renegotiating());
912
913 pair.assert_renegotiate().expect("Renegotiate");
914 Ok(())
915 }
916
917 // Renegotiation will fail if there is a pending call to poll_send
918 #[test]
919 fn scheduled_renegotiate_with_buffered_send() -> Result<(), Box<dyn Error>> {
920 unsafe extern "C" fn blocking_send_cb(
921 _: *mut libc::c_void,
922 _: *const u8,
923 _: u32,
924 ) -> libc::c_int {
925 errno::set_errno(errno::Errno(libc::EWOULDBLOCK));
926 -1
927 }
928
929 let mut builder = config::Builder::new();
930 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
931 let mut pair = RenegotiateTestPair::from(builder)?;
932 pair.handshake().expect("Initial handshake");
933
934 // The client needs to initially block on send.
935 let client_data = b"client data";
936 pair.client.set_send_callback(Some(blocking_send_cb))?;
937 assert!(pair.client.poll_send(client_data).is_pending());
938 assert!(pair.client.renegotiate_state().send_pending);
939
940 // The client fails to start renegotiation due to pending send.
941 pair.send_renegotiate_request()
942 .expect("Server sends request");
943 let error = unwrap_poll(pair.client.poll_recv(&mut [0; 1])).unwrap_err();
944 assert_eq!(error.kind(), ErrorType::UsageError);
945 assert!(error.message().contains(RENEG_ERR_MARKER));
946 assert!(error.message().contains("buffered send data"));
947 assert!(pair.client.is_renegotiating());
948
949 Ok(())
950 }
951
952 // poll_send is not currently supported during renegotiation
953 #[test]
954 fn scheduled_renegotiate_with_poll_send() -> Result<(), Box<dyn Error>> {
955 let mut builder = config::Builder::new();
956 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
957 let mut pair = RenegotiateTestPair::from(builder)?;
958 pair.handshake().expect("Initial handshake");
959
960 // Read the hello request and start renegotiation
961 pair.send_renegotiate_request()
962 .expect("server HELLO_REQUEST");
963 assert!(pair.client.poll_recv(&mut [0; 1]).is_pending());
964 assert!(pair.client.is_renegotiating());
965
966 // Calls to poll_send now fail
967 let error = unwrap_poll(pair.client.poll_send(&[0; 1])).unwrap_err();
968 assert_eq!(error.kind(), ErrorType::Blocked);
969 assert!(error.message().contains(RENEG_ERR_MARKER));
970 assert!(error.message().contains("send application data"));
971 assert!(pair.client.is_renegotiating());
972
973 Ok(())
974 }
975
976 #[test]
977 fn scheduled_renegotiate_with_async_callback() -> Result<(), Box<dyn Error>> {
978 // To test how renegotiate handles blocking on async callbacks,
979 // we need an async callback that triggers on the client.
980 // Currently our only option is the async pkey callback.
981 struct TestAsyncCallback {
982 count: usize,
983 op: Option<PrivateKeyOperation>,
984 }
985 impl PrivateKeyCallback for TestAsyncCallback {
986 fn handle_operation(
987 &self,
988 _: &mut Connection,
989 operation: PrivateKeyOperation,
990 ) -> ConnectionFutureResult {
991 Ok(Some(Box::pin(TestAsyncCallback {
992 count: self.count,
993 op: Some(operation),
994 })))
995 }
996 }
997 impl ConnectionFuture for TestAsyncCallback {
998 fn poll(
999 self: Pin<&mut Self>,
1000 conn: &mut Connection,
1001 ctx: &mut core::task::Context,
1002 ) -> Poll<Result<(), crate::error::Error>> {
1003 ctx.waker().wake_by_ref();
1004 let this = self.get_mut();
1005 if this.count > 1 {
1006 // Repeatedly block the handshake in order to verify
1007 // that renegotiate can handle Pending callbacks.
1008 this.count -= 1;
1009 Pending
1010 } else {
1011 // Perform the pkey operation with the selected cert / key pair.
1012 let op = this.op.take().unwrap();
1013 let opt_ptr = op.as_ptr();
1014 let chain_ptr = conn.selected_cert().unwrap().as_ptr();
1015 unsafe {
1016 // SAFETY, mut cast: get_private_key does not modify the
1017 // chain, and it is invalid to modify key through `key_ptr`
1018 let key_ptr = s2n_cert_chain_and_key_get_private_key(chain_ptr as *mut _)
1019 .into_result()?
1020 .as_ptr();
1021 s2n_async_pkey_op_perform(opt_ptr, key_ptr).into_result()?;
1022 s2n_async_pkey_op_apply(opt_ptr, conn.as_ptr()).into_result()?;
1023 }
1024 Ready(Ok(()))
1025 }
1026 }
1027 }
1028
1029 let count_per_handshake = 10;
1030 let async_callback = TestAsyncCallback {
1031 count: count_per_handshake,
1032 op: None,
1033 };
1034
1035 let mut builder = config::Builder::new();
1036 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
1037 builder.set_private_key_callback(async_callback)?;
1038 let mut pair = RenegotiateTestPair::from(builder)?;
1039
1040 let (waker, wake_count) = new_count_waker();
1041 pair.client.set_waker(Some(&waker))?;
1042
1043 pair.handshake().expect("Initial handshake");
1044 assert_eq!(wake_count, count_per_handshake);
1045 pair.send_renegotiate_request()
1046 .expect("Server sends request");
1047 pair.assert_renegotiate()?;
1048
1049 assert_eq!(wake_count, count_per_handshake * 2);
1050 Ok(())
1051 }
1052
1053 #[test]
1054 fn scheduled_renegotiate_with_async_init() -> Result<(), Box<dyn Error>> {
1055 // To test that the initializer method triggers again on the second
1056 // handshake, we need to set an easily verified connection-level value.
1057 #[derive(Clone)]
1058 struct TestInitializer {
1059 count: usize,
1060 context: String,
1061 }
1062 impl ConnectionInitializer for TestInitializer {
1063 fn initialize_connection(
1064 &self,
1065 _: &mut crate::connection::Connection,
1066 ) -> ConnectionFutureResult {
1067 Ok(Some(Box::pin(self.clone())))
1068 }
1069 }
1070 impl ConnectionFuture for TestInitializer {
1071 fn poll(
1072 self: Pin<&mut Self>,
1073 conn: &mut Connection,
1074 ctx: &mut core::task::Context,
1075 ) -> Poll<Result<(), crate::error::Error>> {
1076 ctx.waker().wake_by_ref();
1077 let this = self.get_mut();
1078 // Assert that nothing is currently set
1079 assert!(conn.application_context::<String>().is_none());
1080 if this.count > 1 {
1081 // Repeatedly block the handshake in order to verify
1082 // that renegotiate can handle Pending callbacks.
1083 this.count -= 1;
1084 Pending
1085 } else {
1086 conn.set_application_context(this.context.clone());
1087 Ready(Ok(()))
1088 }
1089 }
1090 }
1091
1092 let count_per_handshake = 10;
1093 let expected_context = "helloworld".to_owned();
1094 let initializer = TestInitializer {
1095 count: count_per_handshake,
1096 context: expected_context.clone(),
1097 };
1098
1099 let mut builder = config::Builder::new();
1100 builder.set_renegotiate_callback(RenegotiateResponse::Schedule)?;
1101 builder.set_connection_initializer(initializer)?;
1102 let mut pair = RenegotiateTestPair::from(builder)?;
1103
1104 let (waker, wake_count) = new_count_waker();
1105 pair.client.set_waker(Some(&waker))?;
1106
1107 pair.handshake().expect("Initial handshake");
1108 assert_eq!(wake_count, count_per_handshake);
1109 pair.send_renegotiate_request()
1110 .expect("Server sends request");
1111 pair.assert_renegotiate()?;
1112 assert_eq!(wake_count, count_per_handshake * 2);
1113
1114 let context: Option<&String> = pair.client.application_context();
1115 assert_eq!(Some(&expected_context), context);
1116
1117 Ok(())
1118 }
1119
1120 #[test]
1121 fn wipe_for_renegotiate_failure() -> Result<(), Box<dyn Error>> {
1122 let mut connection = Connection::new_server();
1123 // Servers can't renegotiate
1124 let error = connection.wipe_for_renegotiate().unwrap_err();
1125 assert_eq!(error.source(), ErrorSource::Library);
1126 assert_eq!(error.name(), "S2N_ERR_NO_RENEGOTIATION");
1127 Ok(())
1128 }
1129 }