diff options
Diffstat (limited to 'openssl/src/ssl')
| -rw-r--r-- | openssl/src/ssl/callbacks.rs | 95 | ||||
| -rw-r--r-- | openssl/src/ssl/connector.rs | 43 | ||||
| -rw-r--r-- | openssl/src/ssl/mod.rs | 338 | ||||
| -rw-r--r-- | openssl/src/ssl/test.rs | 96 |
4 files changed, 481 insertions, 91 deletions
diff --git a/openssl/src/ssl/callbacks.rs b/openssl/src/ssl/callbacks.rs index 7d884b4e..2fc43ac0 100644 --- a/openssl/src/ssl/callbacks.rs +++ b/openssl/src/ssl/callbacks.rs @@ -4,15 +4,20 @@ use std::ffi::CStr; use std::ptr; use std::slice; use std::mem; +#[cfg(all(feature = "v111", ossl111))] +use std::str; use foreign_types::ForeignTypeRef; +use foreign_types::ForeignType; use error::ErrorStack; use dh::Dh; #[cfg(any(all(feature = "v101", ossl101), all(feature = "v102", ossl102)))] use ec::EcKey; use pkey::Params; -use ssl::{get_callback_idx, get_ssl_callback_idx, SniError, SslAlert, SslRef}; -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +use ssl::{get_callback_idx, get_ssl_callback_idx, SniError, SslAlert, SslContextRef, SslRef, + SslSession, SslSessionRef}; +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] use ssl::AlpnError; use x509::X509StoreContextRef; @@ -107,7 +112,8 @@ where } } -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] pub extern "C" fn raw_alpn_select<F>( ssl: *mut ffi::SSL, out: *mut *const c_uchar, @@ -272,3 +278,86 @@ where } } } + +pub unsafe extern "C" fn raw_new_session<F>( + ssl: *mut ffi::SSL, + session: *mut ffi::SSL_SESSION, +) -> c_int +where + F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send, +{ + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::<F>()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr_mut(ssl); + let session = SslSession::from_ptr(session); + + callback(ssl, session); + + // the return code doesn't indicate error vs success, but whether or not we consumed the session + 1 +} + +pub unsafe extern "C" fn raw_remove_session<F>( + ctx: *mut ffi::SSL_CTX, + session: *mut ffi::SSL_SESSION, +) where + F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send, +{ + let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::<F>()); + let callback = &*(callback as *mut F); + + let ctx = SslContextRef::from_ptr(ctx); + let session = SslSessionRef::from_ptr(session); + + callback(ctx, session) +} + +#[cfg(any(ossl110, ossl111))] +type DataPtr = *const c_uchar; +#[cfg(not(any(ossl110, ossl111)))] +type DataPtr = *mut c_uchar; + +pub unsafe extern "C" fn raw_get_session<F>( + ssl: *mut ffi::SSL, + data: DataPtr, + len: c_int, + copy: *mut c_int, +) -> *mut ffi::SSL_SESSION +where + F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send, +{ + let ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::<F>()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr_mut(ssl); + let data = slice::from_raw_parts(data as *const u8, len as usize); + + match callback(ssl, data) { + Some(session) => { + let p = session.as_ptr(); + mem::forget(p); + *copy = 0; + p + } + None => ptr::null_mut(), + } +} + +#[cfg(all(feature = "v111", ossl111))] +pub unsafe extern "C" fn raw_keylog<F>(ssl: *const ffi::SSL, line: *const c_char) +where + F: Fn(&SslRef, &str) + 'static + Sync + Send, +{ + let ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::<F>()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr(ssl as *mut _); + let line = CStr::from_ptr(line).to_bytes(); + let line = str::from_utf8_unchecked(line); + + callback(ssl, line); +} diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 9e485ab9..c0414706 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -7,18 +7,6 @@ use ssl::{HandshakeError, Ssl, SslContext, SslContextBuilder, SslMethod, SslMode SslRef, SslStream, SslVerifyMode}; use version; -// ffdhe2048 from https://wiki.mozilla.org/Security/Server_Side_TLS#ffdhe2048 -const DHPARAM_PEM: &'static str = " ------BEGIN DH PARAMETERS----- -MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz -+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a -87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7 -YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi -7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD -ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg== ------END DH PARAMETERS----- -"; - fn ctx(method: SslMethod) -> Result<SslContextBuilder, ErrorStack> { let mut ctx = SslContextBuilder::new(method)?; @@ -61,11 +49,8 @@ impl SslConnector { pub fn builder(method: SslMethod) -> Result<SslConnectorBuilder, ErrorStack> { let mut ctx = ctx(method)?; ctx.set_default_verify_paths()?; - // From https://github.com/python/cpython/blob/a170fa162dc03f0a014373349e548954fff2e567/Lib/ssl.py#L193 ctx.set_cipher_list( - "TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:\ - ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:ECDH+AES128:\ - DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:!aNULL:!eNULL:!MD5:!3DES", + "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK", )?; setup_verify(&mut ctx); @@ -206,7 +191,24 @@ impl SslAcceptor { /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_intermediate(method: SslMethod) -> Result<SslAcceptorBuilder, ErrorStack> { let mut ctx = ctx(method)?; - let dh = Dh::params_from_pem(DHPARAM_PEM.as_bytes())?; + #[cfg(ossl111)] + { + ctx.set_options(SslOptions { + bits: ::ffi::SSL_OP_NO_TLSv1_3, + }); + } + let dh = Dh::params_from_pem( + b" +-----BEGIN DH PARAMETERS----- +MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz ++8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a +87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7 +YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi +7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD +ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg== +-----END DH PARAMETERS----- +", + )?; ctx.set_tmp_dh(&dh)?; setup_curves(&mut ctx)?; ctx.set_cipher_list( @@ -232,6 +234,13 @@ impl SslAcceptor { /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_modern(method: SslMethod) -> Result<SslAcceptorBuilder, ErrorStack> { let mut ctx = ctx(method)?; + ctx.set_options(SslOptions::NO_TLSV1 | SslOptions::NO_TLSV1_1); + #[cfg(ossl111)] + { + ctx.set_options(SslOptions { + bits: ::ffi::SSL_OP_NO_TLSv1_3, + }); + } setup_curves(&mut ctx)?; ctx.set_cipher_list( "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 2474c2ab..69d38f44 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -85,7 +85,8 @@ use ec::EcKeyRef; use ec::EcKey; use x509::{X509, X509Name, X509Ref, X509StoreContextRef, X509VerifyResult}; use x509::store::{X509StoreBuilderRef, X509StoreRef}; -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] use x509::store::X509Store; #[cfg(any(ossl102, ossl110))] use verify::X509VerifyParamRef; @@ -177,22 +178,30 @@ bitflags! { /// Disables the use of TLSv1.2. const NO_TLSV1_2 = ffi::SSL_OP_NO_TLSv1_2; + /// Disables the use of TLSv1.3. + /// + /// Requires the `v111` feature and OpenSSL 1.1.1. + #[cfg(all(feature = "v111", ossl111))] + const NO_TLSV1_3 = ffi::SSL_OP_NO_TLSv1_3; + /// Disables the use of DTLSv1.0 /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] const NO_DTLSV1 = ffi::SSL_OP_NO_DTLSv1; /// Disables the use of DTLSv1.2. - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] const NO_DTLSV1_2 = ffi::SSL_OP_NO_DTLSv1_2; /// Disables the use of all (D)TLS protocol versions. /// /// This can be used as a mask when whitelisting protocol versions. /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. /// /// # Examples /// @@ -203,7 +212,8 @@ bitflags! { /// /// let options = SslOptions::NO_SSL_MASK & !SslOptions::NO_TLSV1_2; /// ``` - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] const NO_SSL_MASK = ffi::SSL_OP_NO_SSL_MASK; } } @@ -295,19 +305,55 @@ bitflags! { /// Verifies that the peer's certificate is trusted. /// /// On the server side, this will cause OpenSSL to request a certificate from the client. - const PEER = ::ffi::SSL_VERIFY_PEER; + const PEER = ffi::SSL_VERIFY_PEER; /// Disables verification of the peer's certificate. /// /// On the server side, this will cause OpenSSL to not request a certificate from the /// client. On the client side, the certificate will be checked for validity, but the /// negotiation will continue regardless of the result of that check. - const NONE = ::ffi::SSL_VERIFY_NONE; + const NONE = ffi::SSL_VERIFY_NONE; /// On the server side, abort the handshake if the client did not send a certificate. /// /// This should be paired with `SSL_VERIFY_PEER`. It has no effect on the client side. - const FAIL_IF_NO_PEER_CERT = ::ffi::SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + const FAIL_IF_NO_PEER_CERT = ffi::SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + } +} + +bitflags! { + /// Options controlling the behavior of session caching. + pub struct SslSessionCacheMode: c_long { + /// No session caching for the client or server takes place. + const OFF = ffi::SSL_SESS_CACHE_OFF; + + /// Enable session caching on the client side. + /// + /// OpenSSL has no way of identifying the proper session to reuse automatically, so the + /// application is responsible for setting it explicitly via [`SslRef::set_session`]. + /// + /// [`SslRef::set_session`]: struct.SslRef.html#method.set_session + const CLIENT = ffi::SSL_SESS_CACHE_CLIENT; + + /// Enable session caching on the server side. + /// + /// This is the default mode. + const SERVER = ffi::SSL_SESS_CACHE_SERVER; + + /// Enable session caching on both the client and server side. + const BOTH = ffi::SSL_SESS_CACHE_BOTH; + + /// Disable automatic removal of expired sessions from the session cache. + const NO_AUTO_CLEAR = ffi::SSL_SESS_CACHE_NO_AUTO_CLEAR; + + /// Disable use of the internal session cache for session lookups. + const NO_INTERNAL_LOOKUP = ffi::SSL_SESS_CACHE_NO_INTERNAL_LOOKUP; + + /// Disable use of the internal session cache for session storage. + const NO_INTERNAL_STORE = ffi::SSL_SESS_CACHE_NO_INTERNAL_STORE; + + /// Disable use of the internal session cache for storage and lookup. + const NO_INTERNAL = ffi::SSL_SESS_CACHE_NO_INTERNAL; } } @@ -429,7 +475,7 @@ fn get_new_ssl_idx<T>() -> c_int { } /// An error returned from the SNI callback. -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct SniError(c_int); impl SniError { @@ -443,7 +489,7 @@ impl SniError { } /// An SSL/TLS alert. -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct SslAlert(c_int); impl SslAlert { @@ -453,23 +499,49 @@ impl SslAlert { /// An error returned from an ALPN selection callback. /// -/// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -#[derive(Debug, Copy, Clone)] +/// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct AlpnError(c_int); -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] impl AlpnError { /// Terminate the handshake with a fatal alert. /// - /// Requires the `v110` feature and OpenSSL 1.1.0. - #[cfg(all(feature = "v110", ossl110))] + /// Requires OpenSSL 1.1.0 or 1.1.1 and the corresponding Cargo feature. + #[cfg(any(all(feature = "v110", ossl110), all(feature = "v111", ossl111)))] pub const ALERT_FATAL: AlpnError = AlpnError(ffi::SSL_TLSEXT_ERR_ALERT_FATAL); /// Do not select a protocol, but continue the handshake. pub const NOACK: AlpnError = AlpnError(ffi::SSL_TLSEXT_ERR_NOACK); } +/// An SSL/TLS protocol version. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct SslVersion(c_int); + +impl SslVersion { + /// SSLv3 + pub const SSL3: SslVersion = SslVersion(ffi::SSL3_VERSION); + + /// TLSv1.0 + pub const TLS1: SslVersion = SslVersion(ffi::TLS1_VERSION); + + /// TLSv1.1 + pub const TLS1_1: SslVersion = SslVersion(ffi::TLS1_1_VERSION); + + /// TLSv1.2 + pub const TLS1_2: SslVersion = SslVersion(ffi::TLS1_2_VERSION); + + /// TLSv1.3 + /// + /// Requires OpenSSL 1.1.1 and the corresponding Cargo feature. + #[cfg(all(feature = "v111", ossl111))] + pub const TLS1_3: SslVersion = SslVersion(ffi::TLS1_3_VERSION); +} + /// A standard implementation of protocol selection for Application Layer Protocol Negotiation /// (ALPN). /// @@ -610,17 +682,17 @@ impl SslContextBuilder { /// Sets a custom certificate store for verifying peer certificates. /// - /// Requires the `v102` feature and OpenSSL 1.0.2, or the `v110` feature and OpenSSL 1.1.0. + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. /// /// This corresponds to [`SSL_CTX_set0_verify_cert_store`]. /// /// [`SSL_CTX_set0_verify_cert_store`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set0_verify_cert_store.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] pub fn set_verify_cert_store(&mut self, cert_store: X509Store) -> Result<(), ErrorStack> { unsafe { let ptr = cert_store.as_ptr(); - cvt(ffi::SSL_CTX_set0_verify_cert_store(self.as_ptr(), ptr) - as c_int)?; + cvt(ffi::SSL_CTX_set0_verify_cert_store(self.as_ptr(), ptr) as c_int)?; mem::forget(cert_store); Ok(()) @@ -650,8 +722,8 @@ impl SslContextBuilder { /// [`SSL_CTX_set_mode`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_mode.html pub fn set_mode(&mut self, mode: SslMode) -> SslMode { unsafe { - let mode = ffi::SSL_CTX_set_mode(self.as_ptr(), mode.bits()); - SslMode::from_bits(mode).unwrap() + let bits = ffi::SSL_CTX_set_mode(self.as_ptr(), mode.bits()); + SslMode { bits } } } @@ -694,11 +766,7 @@ impl SslContextBuilder { /// /// This corresponds to `SSL_CTX_set_tmp_ecdh`. pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef<Params>) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) - as c_int) - .map(|_| ()) - } + unsafe { cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) } } /// Sets the callback which will generate parameters to be used during ephemeral elliptic curve @@ -942,8 +1010,8 @@ impl SslContextBuilder { /// /// [`SSL_CTX_set_options`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_options.html pub fn set_options(&mut self, option: SslOptions) -> SslOptions { - let ret = unsafe { compat::SSL_CTX_set_options(self.as_ptr(), option.bits()) }; - SslOptions::from_bits(ret).unwrap() + let bits = unsafe { compat::SSL_CTX_set_options(self.as_ptr(), option.bits()) }; + SslOptions { bits } } /// Returns the options used by the context. @@ -952,8 +1020,8 @@ impl SslContextBuilder { /// /// [`SSL_CTX_get_options`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_options.html pub fn options(&self) -> SslOptions { - let ret = unsafe { compat::SSL_CTX_get_options(self.as_ptr()) }; - SslOptions::from_bits(ret).unwrap() + let bits = unsafe { compat::SSL_CTX_get_options(self.as_ptr()) }; + SslOptions { bits } } /// Clears the options used by the context, returning the old set. @@ -962,8 +1030,8 @@ impl SslContextBuilder { /// /// [`SSL_CTX_clear_options`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_options.html pub fn clear_options(&mut self, option: SslOptions) -> SslOptions { - let ret = unsafe { compat::SSL_CTX_clear_options(self.as_ptr(), option.bits()) }; - SslOptions::from_bits(ret).unwrap() + let bits = unsafe { compat::SSL_CTX_clear_options(self.as_ptr(), option.bits()) }; + SslOptions { bits } } /// Sets the protocols to sent to the server for Application Layer Protocol Negotiation (ALPN). @@ -975,10 +1043,11 @@ impl SslContextBuilder { /// /// This corresponds to [`SSL_CTX_set_alpn_protos`]. /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. /// /// [`SSL_CTX_set_alpn_protos`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_alpn_protos.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] pub fn set_alpn_protos(&mut self, protocols: &[u8]) -> Result<(), ErrorStack> { unsafe { assert!(protocols.len() <= c_uint::max_value() as usize); @@ -1006,12 +1075,13 @@ impl SslContextBuilder { /// /// This corresponds to [`SSL_CTX_set_alpn_select_cb`]. /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. /// /// [`SslContextBuilder::set_alpn_protos`]: struct.SslContextBuilder.html#method.set_alpn_protos /// [`select_next_proto`]: fn.select_next_proto.html /// [`SSL_CTX_set_alpn_select_cb`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_alpn_protos.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] pub fn set_alpn_select_callback<F>(&mut self, callback: F) where F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send, @@ -1086,9 +1156,7 @@ impl SslContextBuilder { Box::into_raw(callback) as *mut c_void, ); let f: unsafe extern "C" fn(_, _) -> _ = raw_tlsext_status::<F>; - cvt(ffi::SSL_CTX_set_tlsext_status_cb(self.as_ptr(), Some(f)) - as c_int) - .map(|_| ()) + cvt(ffi::SSL_CTX_set_tlsext_status_cb(self.as_ptr(), Some(f)) as c_int).map(|_| ()) } } @@ -1120,6 +1188,130 @@ impl SslContextBuilder { } } + /// Sets the callback which is called when new sessions are negotiated. + /// + /// This can be used by clients to implement session caching. While in TLSv1.2 the session is + /// available to access via [`SslRef::session`] immediately after the handshake completes, this + /// is not the case for TLSv1.3. There, a session is not generally available immediately, and + /// the server may provide multiple session tokens to the client over a single session. The new + /// session callback is a portable way to deal with both cases. + /// + /// Note that session caching must be enabled for the callback to be invoked, and it defaults + /// off for clients. [`set_session_cache_mode`] controls that behavior. + /// + /// This corresponds to [`SSL_CTX_sess_set_new_cb`]. + /// + /// [`SslRef::session`]: struct.SslRef.html#method.session + /// [`set_session_cache_mode`]: #method.set_session_cache_mode + /// [`SSL_CTX_sess_set_new_cb`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_sess_set_new_cb.html + pub fn set_new_session_callback<F>(&mut self, callback: F) + where + F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::<F>(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_sess_set_new_cb(self.as_ptr(), Some(callbacks::raw_new_session::<F>)); + } + } + + /// Sets the callback which is called when sessions are removed from the context. + /// + /// Sessions can be removed because they have timed out or because they are considered faulty. + /// + /// This corresponds to [`SSL_CTX_sess_set_remove_cb`]. + /// + /// [`SSL_CTX_sess_set_remove_cb`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_sess_set_new_cb.html + pub fn set_remove_session_callback<F>(&mut self, callback: F) + where + F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::<F>(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_sess_set_remove_cb( + self.as_ptr(), + Some(callbacks::raw_remove_session::<F>), + ); + } + } + + /// Sets the callback which is called when a client proposed to resume a session but it was not + /// found in the internal cache. + /// + /// The callback is passed a reference to the session ID provided by the client. It should + /// return the session corresponding to that ID if available. This is only used for servers, not + /// clients. + /// + /// This corresponds to [`SSL_CTX_sess_set_get_cb`]. + /// + /// # Safety + /// + /// 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, + { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::<F>(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_sess_set_get_cb(self.as_ptr(), Some(callbacks::raw_get_session::<F>)); + } + + /// Sets the TLS key logging callback. + /// + /// The callback is invoked whenever TLS key material is generated, and is passed a line of NSS + /// SSLKEYLOGFILE-formatted text. This can be used by tools like Wireshark to decrypt message + /// traffic. The line does not contain a trailing newline. + /// + /// Requires OpenSSL 1.1.1 and the corresponding Cargo feature. + /// + /// This corresponds to [`SSL_CTX_set_keylog_callback`]. + /// + /// [`SSL_CTX_set_keylog_callback`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_keylog_callback.html + #[cfg(all(feature = "v111", ossl111))] + pub fn set_keylog_callback<F>(&mut self, callback: F) + where + F: Fn(&SslRef, &str) + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::<F>(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_set_keylog_callback(self.as_ptr(), Some(callbacks::raw_keylog::<F>)); + } + } + + /// Sets the session caching mode use for connections made with the context. + /// + /// Returns the previous session caching mode. + /// + /// This corresponds to [`SSL_CTX_set_session_cache_mode`]. + /// + /// [`SSL_CTX_set_session_cache_mode`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_get_session_cache_mode.html + pub fn set_session_cache_mode(&mut self, mode: SslSessionCacheMode) -> SslSessionCacheMode { + unsafe { + let bits = ffi::SSL_CTX_set_session_cache_mode(self.as_ptr(), mode.bits()); + SslSessionCacheMode { bits } + } + } + /// Sets the extra data at the specified index. /// /// This can be used to provide data to callbacks registered with the context. Use the @@ -1206,12 +1398,13 @@ impl SslContext { impl SslContextRef { /// Returns the certificate associated with this `SslContext`, if present. /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. /// /// This corresponds to [`SSL_CTX_get0_certificate`]. /// /// [`SSL_CTX_get0_certificate`]: https://www.openssl.org/docs/man1.1.0/ssl/ssl.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] pub fn certificate(&self) -> Option<&X509Ref> { unsafe { let ptr = ffi::SSL_CTX_get0_certificate(self.as_ptr()); @@ -1225,12 +1418,13 @@ impl SslContextRef { /// Returns the private key associated with this `SslContext`, if present. /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. /// /// This corresponds to [`SSL_CTX_get0_privatekey`]. /// /// [`SSL_CTX_get0_privatekey`]: https://www.openssl.org/docs/man1.1.0/ssl/ssl.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] pub fn private_key(&self) -> Option<&PKeyRef<Private>> { unsafe { let ptr = ffi::SSL_CTX_get0_privatekey(self.as_ptr()); @@ -1410,7 +1604,7 @@ unsafe impl Send for SslSession {} impl Clone for SslSession { fn clone(&self) -> SslSession { - self.to_owned() + SslSessionRef::to_owned(self) } } @@ -1450,7 +1644,7 @@ impl SslSessionRef { /// Copies the master key into the provided buffer. /// - /// Returns the number of bytes written. + /// Returns the number of bytes written, or the size of the master key if the buffer is empty. /// /// This corresponds to [`SSL_SESSION_get_master_key`]. /// @@ -1782,12 +1976,13 @@ impl SslRef { /// The protocol's name is returned is an opaque sequence of bytes. It is up to the client /// to interpret it. /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. /// /// This corresponds to [`SSL_get0_alpn_selected`]. /// /// [`SSL_get0_alpn_selected`]: https://www.openssl.org/docs/manmaster/man3/SSL_get0_next_proto_negotiated.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] pub fn selected_alpn_protocol(&self) -> Option<&[u8]> { unsafe { let mut data: *const c_uchar = ptr::null(); @@ -1857,12 +2052,13 @@ impl SslRef { /// Returns a mutable reference to the X509 verification configuration. /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. + /// Requires OpenSSL 1.0.2, 1.1.0, or 1.1.1 and the corresponding Cargo feature. /// /// This corresponds to [`SSL_get0_param`]. /// /// [`SSL_get0_param`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_get0_param.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] pub fn param_mut(&mut self) -> &mut X509VerifyParamRef { self._param_mut() } @@ -1897,6 +2093,40 @@ impl SslRef { } } + /// Copies the client_random value sent by the client in the TLS handshake into a buffer. + /// + /// Returns the number of bytes copied, or if the buffer is empty, the size of the client_random + /// value. + /// + /// Requires OpenSSL 1.1.0 or 1.1.1 and the corresponding Cargo feature. + /// + /// This corresponds to [`SSL_get_client_random`]. + /// + /// [`SSL_get_client_random`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_client_random.html + #[cfg(any(all(feature = "v110", ossl110), all(feature = "v111", ossl111)))] + pub fn client_random(&self, buf: &mut [u8]) -> usize { + unsafe { + ffi::SSL_get_client_random(self.as_ptr(), buf.as_mut_ptr() as *mut c_uchar, buf.len()) + } + } + + /// Copies the server_random value sent by the server in the TLS handshake into a buffer. + /// + /// Returns the number of bytes copied, or if the buffer is empty, the size of the server_random + /// value. + /// + /// Requires OpenSSL 1.1.0 or 1.1.1 and the corresponding Cargo feature. + /// + /// This corresponds to [`SSL_get_server_random`]. + /// + /// [`SSL_get_server_random`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_client_random.html + #[cfg(any(all(feature = "v110", ossl110), all(feature = "v111", ossl111)))] + pub fn server_random(&self, buf: &mut [u8]) -> usize { + unsafe { + ffi::SSL_get_server_random(self.as_ptr(), buf.as_mut_ptr() as *mut c_uchar, buf.len()) + } + } + /// Sets the session to be used. /// /// This should be called before the handshake to attempt to reuse a previously established @@ -1937,7 +2167,7 @@ impl SslRef { /// Returns the server's OCSP response, if present. /// - /// This corresponds to [`SSL_get_tlsext_status_oscp_resp`]. + /// This corresponds to [`SSL_get_tlsext_status_ocsp_resp`]. /// /// [`SSL_get_tlsext_status_ocsp_resp`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html pub fn ocsp_status(&self) -> Option<&[u8]> { @@ -1955,7 +2185,7 @@ impl SslRef { /// Sets the OCSP response to be returned to the client. /// - /// This corresponds to [`SSL_set_tlsext_status_oscp_resp`]. + /// This corresponds to [`SSL_set_tlsext_status_ocsp_resp`]. /// /// [`SSL_set_tlsext_status_ocsp_resp`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html pub fn set_ocsp_status(&mut self, response: &[u8]) -> Result<(), ErrorStack> { diff --git a/openssl/src/ssl/test.rs b/openssl/src/ssl/test.rs index dc58c4fa..1913d835 100644 --- a/openssl/src/ssl/test.rs +++ b/openssl/src/ssl/test.rs @@ -19,9 +19,10 @@ use hash::MessageDigest; use ocsp::{OcspResponse, OcspResponseStatus}; use ssl; use ssl::{Error, HandshakeError, ShutdownResult, Ssl, SslAcceptor, SslConnector, SslContext, - SslFiletype, SslMethod, SslStream, SslVerifyMode, StatusType}; + SslFiletype, SslMethod, SslSessionCacheMode, SslStream, SslVerifyMode, StatusType}; use x509::{X509, X509Name, X509StoreContext, X509VerifyResult}; -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] use x509::verify::X509CheckFlags; use pkey::PKey; @@ -135,14 +136,17 @@ macro_rules! run_test( use ssl::{SslContext, Ssl, SslStream, SslVerifyMode, SslOptions}; use hash::MessageDigest; use x509::{X509StoreContext, X509VerifyResult}; - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] use x509::X509; - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] use x509::store::X509StoreBuilder; use hex::FromHex; use foreign_types::ForeignTypeRef; use super::Server; - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] use super::ROOT_CERT; #[test] @@ -182,7 +186,8 @@ run_test!(verify_trusted, |method, stream| { } }); -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] run_test!(verify_trusted_with_set_cert, |method, stream| { let x509 = X509::from_pem(ROOT_CERT).unwrap(); let mut store = X509StoreBuilder::new().unwrap(); @@ -477,7 +482,8 @@ fn test_state() { /// Tests that connecting with the client using ALPN, but the server not does not /// break the existing connection behavior. #[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] fn test_connect_with_unilateral_alpn() { let (_s, stream) = Server::new(); let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); @@ -499,7 +505,8 @@ fn test_connect_with_unilateral_alpn() { /// Tests that when both the client as well as the server use ALPN and their /// lists of supported protocols have an overlap, the correct protocol is chosen. #[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] fn test_connect_with_alpn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); @@ -522,7 +529,8 @@ fn test_connect_with_alpn_successful_multiple_matching() { /// lists of supported protocols have an overlap -- with only ONE protocol /// being valid for both. #[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] fn test_connect_with_alpn_successful_single_match() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); @@ -544,7 +552,8 @@ fn test_connect_with_alpn_successful_single_match() { /// Tests that when the `SslStream` is created as a server stream, the protocols /// are correctly advertised to the client. #[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] fn test_alpn_server_advertise_multiple() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); @@ -586,7 +595,7 @@ fn test_alpn_server_advertise_multiple() { } #[test] -#[cfg(all(feature = "v110", ossl110))] +#[cfg(any(all(feature = "v110", ossl110), all(feature = "v111", ossl111)))] fn test_alpn_server_select_none_fatal() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); @@ -620,7 +629,8 @@ fn test_alpn_server_select_none_fatal() { } #[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] fn test_alpn_server_select_none() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); @@ -763,8 +773,11 @@ fn default_verify_paths() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SslVerifyMode::PEER); + let ctx = ctx.build(); let s = TcpStream::connect("google.com:443").unwrap(); - let mut socket = Ssl::new(&ctx.build()).unwrap().connect(s).unwrap(); + let mut ssl = Ssl::new(&ctx).unwrap(); + ssl.set_hostname("google.com").unwrap(); + let mut socket = ssl.connect(s).unwrap(); socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); let mut result = vec![]; @@ -784,7 +797,8 @@ fn add_extra_chain_cert() { } #[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] fn verify_valid_hostname() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); @@ -794,6 +808,7 @@ fn verify_valid_hostname() { ssl.param_mut() .set_hostflags(X509CheckFlags::NO_PARTIAL_WILDCARDS); ssl.param_mut().set_host("google.com").unwrap(); + ssl.set_hostname("google.com").unwrap(); let s = TcpStream::connect("google.com:443").unwrap(); let mut socket = ssl.connect(s).unwrap(); @@ -808,7 +823,8 @@ fn verify_valid_hostname() { } #[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110), + all(feature = "v111", ossl111)))] fn verify_invalid_hostname() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); @@ -855,7 +871,6 @@ fn connector_invalid_no_hostname_verification() { connector .configure() .unwrap() - .use_server_name_indication(false) .verify_hostname(false) .connect("foobar.com", s) .unwrap(); @@ -895,7 +910,7 @@ fn connector_no_hostname_can_disable_verify() { #[test] fn connector_client_server_mozilla_intermediate() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let listener = TcpListener::bind("127.0.0.1:1234").unwrap(); let port = listener.local_addr().unwrap().port(); let t = thread::spawn(move || { @@ -1038,6 +1053,13 @@ fn tmp_dh_callback() { let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + // TLS 1.3 has no DH suites, and openssl isn't happy if the max version has no suites :( + #[cfg(ossl111)] + { + ctx.set_options(super::SslOptions { + bits: ::ffi::SSL_OP_NO_TLSv1_3, + }); + } ctx.set_cipher_list("EDH").unwrap(); let ssl = Ssl::new(&ctx.build()).unwrap(); ssl.connect(stream).unwrap(); @@ -1106,6 +1128,13 @@ fn tmp_dh_callback_ssl() { let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + // TLS 1.3 has no DH suites, and openssl isn't happy if the max version has no suites :( + #[cfg(ossl111)] + { + ctx.set_options(super::SslOptions { + bits: ::ffi::SSL_OP_NO_TLSv1_3, + }); + } ctx.set_cipher_list("EDH").unwrap(); let ssl = Ssl::new(&ctx.build()).unwrap(); ssl.connect(stream).unwrap(); @@ -1216,6 +1245,39 @@ fn status_callbacks() { guard.join().unwrap(); } +#[test] +fn new_session_callback() { + static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_session_id_context(b"foo").unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + let mut stream = ssl.accept(stream).unwrap(); + stream.write_all(&[0]).unwrap(); + }); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_session_cache_mode(SslSessionCacheMode::CLIENT | SslSessionCacheMode::NO_INTERNAL); + ctx.set_new_session_callback(|_, _| CALLED_BACK.store(true, Ordering::SeqCst)); + let ssl = Ssl::new(&ctx.build()).unwrap(); + let mut stream = ssl.connect(stream).unwrap(); + // read 1 byte to make sure the session is received for TLSv1.3 + let mut buf = [0]; + stream.read_exact(&mut buf).unwrap(); + + assert!(CALLED_BACK.load(Ordering::SeqCst)); +} + fn _check_kinds() { fn is_send<T: Send>() {} fn is_sync<T: Sync>() {} |