From 4ad7ff3083b35948c0efdfba68ea42277f9e1839 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Thu, 20 Jun 2019 17:27:40 -0700 Subject: [PATCH] use openssl directly for the client when that feature is enabled This removes some redundancy and overhead around setting up the connection (the native_tls crate doesn't provide PEM functions, despite every deployment I've ever seen only ever using PEM certs), but more importantly, gives the control needed to make hostname verification work in a PKI setup with unusual CN values. --- src/config.rs | 11 ++++++ src/server/client.rs | 88 ++++++++++++++++++++++++++++++++++++++++-- src/server/listener.rs | 2 +- src/server/pollable.rs | 18 +++++++++ 4 files changed, 115 insertions(+), 4 deletions(-) diff --git a/src/config.rs b/src/config.rs index 5537fc8ff..91816b9fd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -113,6 +113,8 @@ pub struct Config { /// the path to an x509 PEM encoded CA chain file pub mux_client_pem_ca: Option, + pub mux_pem_root_certs: Option>, + /// When using the mux client domain, explicitly control whether /// the client checks that the certificate presented by the /// server matches the hostname portion of mux_server_remote_address. @@ -122,6 +124,13 @@ pub struct Config { /// weakens the security of the TLS channel. pub mux_client_accept_invalid_hostnames: Option, + /// When connecting to a mux server, the hostname string that we + /// expect to match against the common name field in the certificate + /// presented by the server. This defaults to the hostname portion + /// of the `mux_server_bind_address` configuration and you should + /// not normally need to override this value. + pub mux_client_expected_cn: Option, + #[serde(default)] pub keys: Vec, } @@ -384,6 +393,8 @@ impl Default for Config { mux_client_pem_cert: None, mux_client_pem_ca: None, mux_client_accept_invalid_hostnames: None, + mux_client_expected_cn: None, + mux_pem_root_certs: None, keys: vec![], } } diff --git a/src/server/client.rs b/src/server/client.rs index 16805aa0f..24d442964 100644 --- a/src/server/client.rs +++ b/src/server/client.rs @@ -3,17 +3,14 @@ use crate::config::Config; use crate::frontend::gui_executor; use crate::mux::Mux; use crate::server::codec::*; -use crate::server::listener::IdentitySource; use crate::server::pollable::*; use crate::server::tab::ClientTab; use crate::server::UnixStream; use crossbeam_channel::TryRecvError; use failure::{bail, err_msg, format_err, Fallible}; use log::info; -use native_tls::TlsConnector; use promise::{Future, Promise}; use std::collections::HashMap; -use std::convert::TryInto; use std::io::Write; use std::net::TcpStream; use std::path::Path; @@ -159,7 +156,92 @@ impl Client { Ok(Self::new(stream)) } + #[cfg(any(feature = "openssl", all(unix, not(target_os = "macos"))))] pub fn new_tls(config: &Arc) -> Fallible { + use crate::server::listener::read_bytes; + use openssl::ssl::{SslConnector, SslFiletype, SslMethod}; + use openssl::x509::X509; + + let remote_address = config + .mux_server_remote_address + .as_ref() + .ok_or_else(|| err_msg("missing mux_server_remote_address config value"))?; + + let remote_host_name = remote_address.split(':').next().ok_or_else(|| { + format_err!( + "expected mux_server_remote_address to have the form 'host:port', but have {}", + remote_address + ) + })?; + + let mut connector = SslConnector::builder(SslMethod::tls())?; + + if let Some(cert_file) = config.mux_client_pem_cert.as_ref() { + connector.set_certificate_file(cert_file, SslFiletype::PEM)?; + } + if let Some(chain_file) = config.mux_client_pem_ca.as_ref() { + connector.set_certificate_chain_file(chain_file)?; + } + if let Some(key_file) = config.mux_client_pem_private_key.as_ref() { + connector.set_private_key_file(key_file, SslFiletype::PEM)?; + } + if let Some(root_certs) = config.mux_pem_root_certs.as_ref() { + fn load_cert(name: &Path) -> Fallible { + let cert_bytes = read_bytes(name)?; + log::trace!("loaded {}", name.display()); + Ok(X509::from_pem(&cert_bytes)?) + } + for name in root_certs { + if name.is_dir() { + for entry in std::fs::read_dir(name)? { + if let Ok(cert) = load_cert(&entry?.path()) { + connector.cert_store_mut().add_cert(cert).ok(); + } + } + } else { + connector.cert_store_mut().add_cert(load_cert(name)?)?; + } + } + } + + let connector = connector.build(); + let connector = connector + .configure()? + .verify_hostname(!config.mux_client_accept_invalid_hostnames.unwrap_or(false)); + + let stream = TcpStream::connect(remote_address) + .map_err(|e| format_err!("connecting to {}: {}", remote_address, e))?; + stream.set_nodelay(true)?; + + let stream = Box::new( + connector + .connect( + config + .mux_client_expected_cn + .as_ref() + .map(String::as_str) + .unwrap_or(remote_host_name), + stream, + ) + .map_err(|e| { + format_err!( + "SslConnector for {} with host name {}: {} ({:?})", + remote_address, + remote_host_name, + e, + e + ) + })?, + ); + Ok(Self::new(stream)) + } + + #[cfg(not(any(feature = "openssl", all(unix, not(target_os = "macos")))))] + pub fn new_tls(config: &Arc) -> Fallible { + use crate::server::listener::IdentitySource; + use native_tls::TlsConnector; + use std::convert::TryInto; + let remote_address = config .mux_server_remote_address .as_ref() diff --git a/src/server/listener.rs b/src/server/listener.rs index 991c77e3b..7dcfedb82 100644 --- a/src/server/listener.rs +++ b/src/server/listener.rs @@ -70,7 +70,7 @@ pub enum IdentitySource { }, } -fn read_bytes>(path: T) -> Fallible> { +pub fn read_bytes>(path: T) -> Fallible> { let path = path.as_ref(); let mut f = std::fs::File::open(path) .map_err(|e| format_err!("opening file {}: {}", path.display(), e))?; diff --git a/src/server/pollable.rs b/src/server/pollable.rs index 66244671b..8e119885d 100644 --- a/src/server/pollable.rs +++ b/src/server/pollable.rs @@ -29,6 +29,17 @@ impl ReadAndWrite for native_tls::TlsStream { } } +#[cfg(any(feature = "openssl", all(unix, not(target_os = "macos"))))] +impl ReadAndWrite for openssl::ssl::SslStream { + fn set_non_blocking(&self, non_blocking: bool) -> Fallible<()> { + self.get_ref().set_nonblocking(non_blocking)?; + Ok(()) + } + fn has_read_buffered(&self) -> bool { + self.ssl().pending() != 0 + } +} + pub struct PollableSender { sender: Sender, write: RefCell, @@ -116,6 +127,13 @@ impl AsPollFd for native_tls::TlsStream { } } +#[cfg(any(feature = "openssl", all(unix, not(target_os = "macos"))))] +impl AsPollFd for openssl::ssl::SslStream { + fn as_poll_fd(&self) -> pollfd { + self.get_ref().as_socket_descriptor().as_poll_fd() + } +} + impl AsPollFd for UnixStream { fn as_poll_fd(&self) -> pollfd { self.as_socket_descriptor().as_poll_fd()