Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce set_async_get_session_callback #174

Merged
merged 5 commits into from
Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions boring/src/ssl/callbacks.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#![forbid(unsafe_op_in_unsafe_fn)]

use super::{
AlpnError, ClientHello, PrivateKeyMethod, PrivateKeyMethodError, SelectCertError, SniError,
Ssl, SslAlert, SslContext, SslContextRef, SslRef, SslSession, SslSessionRef,
SslSignatureAlgorithm, SESSION_CTX_INDEX,
AlpnError, ClientHello, GetSessionPendingError, PrivateKeyMethod, PrivateKeyMethodError,
SelectCertError, SniError, Ssl, SslAlert, SslContext, SslContextRef, SslRef, SslSession,
SslSessionRef, SslSignatureAlgorithm, SESSION_CTX_INDEX,
};
use crate::error::ErrorStack;
use crate::ffi;
Expand All @@ -13,7 +13,6 @@ use foreign_types::ForeignTypeRef;
use libc::c_char;
use libc::{c_int, c_uchar, c_uint, c_void};
use std::ffi::CStr;
use std::mem;
use std::ptr;
use std::slice;
use std::str;
Expand Down Expand Up @@ -323,7 +322,10 @@ pub(super) unsafe extern "C" fn raw_get_session<F>(
copy: *mut c_int,
) -> *mut ffi::SSL_SESSION
where
F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send,
F: Fn(&mut SslRef, &[u8]) -> Result<Option<SslSession>, GetSessionPendingError>
+ 'static
+ Sync
+ Send,
{
// SAFETY: boring provides valid inputs.
let ssl = unsafe { SslRef::from_ptr_mut(ssl) };
Expand All @@ -342,13 +344,15 @@ where
let callback = unsafe { &*(callback as *const F) };

match callback(ssl, data) {
Some(session) => {
let p = session.as_ptr();
mem::forget(session);
Ok(Some(session)) => {
let p = session.into_ptr();

*copy = 0;

p
}
None => ptr::null_mut(),
Ok(None) => ptr::null_mut(),
Err(GetSessionPendingError) => unsafe { ffi::SSL_magic_pending_session_ptr() },
}
}

Expand Down
14 changes: 12 additions & 2 deletions boring/src/ssl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1599,12 +1599,15 @@ impl SslContextBuilder {
///
/// # Safety
///
/// The returned `SslSession` must not be associated with a different `SslContext`.
/// The returned [`SslSession`] must not be associated with a different [`SslContext`].
///
/// [`SSL_CTX_sess_set_get_cb`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_sess_set_new_cb.html
pub unsafe fn set_get_session_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send,
F: Fn(&mut SslRef, &[u8]) -> Result<Option<SslSession>, GetSessionPendingError>
+ 'static
+ Sync
+ Send,
{
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_sess_set_get_cb(self.as_ptr(), Some(callbacks::raw_get_session::<F>));
Expand Down Expand Up @@ -1978,6 +1981,13 @@ impl SslContextRef {
}
}

/// Error returned by the callback to get a session when operation
/// could not complete and should be retried later.
///
/// See [`SslContextBuilder::set_get_session_callback`].
#[derive(Debug)]
pub struct GetSessionPendingError;

#[cfg(not(any(feature = "fips", feature = "fips-link-precompiled")))]
type ProtosLen = usize;
#[cfg(any(feature = "fips", feature = "fips-link-precompiled"))]
Expand Down
113 changes: 12 additions & 101 deletions boring/src/ssl/test/mod.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
#![allow(unused_imports)]

use hex;
use std::cell::Cell;
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::io::{self, BufReader};
use std::iter;
use std::mem;
use std::net::UdpSocket;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::net::{TcpListener, TcpStream};
use std::path::Path;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;

use crate::dh::Dh;
use crate::error::ErrorStack;
use crate::hash::MessageDigest;
use crate::pkey::PKey;
Expand All @@ -25,17 +15,16 @@ use crate::ssl;
use crate::ssl::test::server::Server;
use crate::ssl::SslVersion;
use crate::ssl::{
Error, ExtensionType, HandshakeError, MidHandshakeSslStream, ShutdownResult, ShutdownState,
Ssl, SslAcceptor, SslAcceptorBuilder, SslConnector, SslContext, SslContextBuilder, SslFiletype,
SslMethod, SslOptions, SslSessionCacheMode, SslStream, SslStreamBuilder, SslVerifyMode,
StatusType,
ExtensionType, ShutdownResult, ShutdownState, Ssl, SslAcceptor, SslAcceptorBuilder,
SslConnector, SslContext, SslFiletype, SslMethod, SslOptions, SslStream, SslVerifyMode,
};
use crate::x509::store::X509StoreBuilder;
use crate::x509::verify::X509CheckFlags;
use crate::x509::{X509Name, X509StoreContext, X509};
use crate::x509::{X509Name, X509};

mod private_key_method;
mod server;
mod session;

static ROOT_CERT: &[u8] = include_bytes!("../../../test/root-ca.pem");
static CERT: &[u8] = include_bytes!("../../../test/cert.pem");
Expand Down Expand Up @@ -894,80 +883,6 @@ fn cert_store() {
client.connect();
}

#[test]
fn idle_session() {
let ctx = SslContext::builder(SslMethod::tls()).unwrap().build();
let ssl = Ssl::new(&ctx).unwrap();
assert!(ssl.session().is_none());
}

#[test]
fn active_session() {
let server = Server::builder().build();

let s = server.client().connect();

let session = s.ssl().session().unwrap();
let len = session.master_key_len();
let mut buf = vec![0; len - 1];
let copied = session.master_key(&mut buf);
assert_eq!(copied, buf.len());
let mut buf = vec![0; len + 1];
let copied = session.master_key(&mut buf);
assert_eq!(copied, len);
}

#[test]
fn new_session_callback() {
static CALLED_BACK: AtomicBool = AtomicBool::new(false);

let mut server = Server::builder();
server.ctx().set_session_id_context(b"foo").unwrap();

let server = server.build();

let mut client = server.client();

client
.ctx()
.set_session_cache_mode(SslSessionCacheMode::CLIENT | SslSessionCacheMode::NO_INTERNAL);
client
.ctx()
.set_new_session_callback(|_, _| CALLED_BACK.store(true, Ordering::SeqCst));

client.connect();

assert!(CALLED_BACK.load(Ordering::SeqCst));
}

#[test]
fn new_session_callback_swapped_ctx() {
static CALLED_BACK: AtomicBool = AtomicBool::new(false);

let mut server = Server::builder();
server.ctx().set_session_id_context(b"foo").unwrap();

let server = server.build();

let mut client = server.client();

client
.ctx()
.set_session_cache_mode(SslSessionCacheMode::CLIENT | SslSessionCacheMode::NO_INTERNAL);
client
.ctx()
.set_new_session_callback(|_, _| CALLED_BACK.store(true, Ordering::SeqCst));

let mut client = client.build().builder();

let ctx = SslContextBuilder::new(SslMethod::tls()).unwrap().build();
client.ssl().set_ssl_context(&ctx).unwrap();

client.connect();

assert!(CALLED_BACK.load(Ordering::SeqCst));
}

#[test]
fn keying_export() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
Expand Down Expand Up @@ -1106,18 +1021,12 @@ fn sni_callback_swapped_ctx() {
assert!(CALLED_BACK.load(Ordering::SeqCst));
}

#[test]
fn session_cache_size() {
let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
ctx.set_session_cache_size(1234);
let ctx = ctx.build();
assert_eq!(ctx.session_cache_size(), 1234);
}

#[cfg(feature = "kx-safe-default")]
#[test]
fn client_set_default_curves_list() {
let ssl_ctx = SslContextBuilder::new(SslMethod::tls()).unwrap().build();
let ssl_ctx = crate::ssl::SslContextBuilder::new(SslMethod::tls())
.unwrap()
.build();
let mut ssl = Ssl::new(&ssl_ctx).unwrap();

// Panics if Kyber768 missing in boringSSL.
Expand All @@ -1127,7 +1036,9 @@ fn client_set_default_curves_list() {
#[cfg(feature = "kx-safe-default")]
#[test]
fn server_set_default_curves_list() {
let ssl_ctx = SslContextBuilder::new(SslMethod::tls()).unwrap().build();
let ssl_ctx = crate::ssl::SslContextBuilder::new(SslMethod::tls())
.unwrap()
.build();
let mut ssl = Ssl::new(&ssl_ctx).unwrap();

// Panics if Kyber768 missing in boringSSL.
Expand Down
6 changes: 2 additions & 4 deletions boring/src/ssl/test/private_key_method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@ use once_cell::sync::OnceCell;

use super::server::{Builder, Server};
use super::KEY;
use crate::hash::{Hasher, MessageDigest};
use crate::hash::MessageDigest;
use crate::pkey::PKey;
use crate::rsa::Padding;
use crate::sign::{RsaPssSaltlen, Signer};
use crate::ssl::{
ErrorCode, HandshakeError, PrivateKeyMethod, PrivateKeyMethodError, SslRef,
SslSignatureAlgorithm,
};
use crate::x509::X509;
use std::cmp;
use std::io::{Read, Write};
use std::io::Write;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;

Expand Down
38 changes: 26 additions & 12 deletions boring/src/ssl/test/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ use std::net::{SocketAddr, TcpListener, TcpStream};
use std::thread::{self, JoinHandle};

use crate::ssl::{
HandshakeError, MidHandshakeSslStream, Ssl, SslContext, SslContextBuilder, SslFiletype,
SslMethod, SslRef, SslStream,
HandshakeError, Ssl, SslContext, SslContextBuilder, SslFiletype, SslMethod, SslRef, SslStream,
};

pub struct Server {
Expand Down Expand Up @@ -33,6 +32,7 @@ impl Server {
io_cb: Box::new(|_| {}),
err_cb: Box::new(|_| {}),
should_error: false,
expected_connections_count: 1,
}
}

Expand Down Expand Up @@ -62,6 +62,7 @@ pub struct Builder {
io_cb: Box<dyn FnMut(SslStream<TcpStream>) + Send>,
err_cb: Box<dyn FnMut(HandshakeError<TcpStream>) + Send>,
should_error: bool,
expected_connections_count: usize,
}

impl Builder {
Expand Down Expand Up @@ -93,6 +94,10 @@ impl Builder {
self.should_error = true;
}

pub fn expected_connections_count(&mut self, count: usize) {
self.expected_connections_count = count;
}

pub fn build(self) -> Server {
let ctx = self.ctx.build();
let socket = TcpListener::bind("127.0.0.1:0").unwrap();
Expand All @@ -101,18 +106,27 @@ impl Builder {
let mut io_cb = self.io_cb;
let mut err_cb = self.err_cb;
let should_error = self.should_error;
let mut count = self.expected_connections_count;

let handle = thread::spawn(move || {
let socket = socket.accept().unwrap().0;
let mut ssl = Ssl::new(&ctx).unwrap();
ssl_cb(&mut ssl);
let r = ssl.accept(socket);
if should_error {
err_cb(r.unwrap_err());
} else {
let mut socket = r.unwrap();
socket.write_all(&[0]).unwrap();
io_cb(socket);
while count > 0 {
let socket = socket.accept().unwrap().0;
let mut ssl = Ssl::new(&ctx).unwrap();

ssl_cb(&mut ssl);

let r = ssl.accept(socket);

if should_error {
err_cb(r.unwrap_err());
} else {
let mut socket = r.unwrap();

socket.write_all(&[0]).unwrap();
io_cb(socket);
}

count -= 1;
}
});

Expand Down
Loading
Loading