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

fix: feature flag rustls client auth #756

Merged
merged 8 commits into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
1 change: 1 addition & 0 deletions rumqttd/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Removed

### Fixed
- Feature flag rustls client auth

### Security
- Update tungstenite and dependencies to fix [CVE](https://rustsec.org/advisories/RUSTSEC-2023-0065).
Expand Down
3 changes: 2 additions & 1 deletion rumqttd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ default = ["use-rustls", "websocket"]
use-rustls = ["dep:tokio-rustls", "dep:rustls-webpki", "dep:rustls-pemfile", "dep:x509-parser"]
use-native-tls = ["dep:tokio-native-tls", "dep:x509-parser"]
websocket = ["dep:async-tungstenite", "dep:tokio-util", "dep:futures-util", "dep:ws_stream_tungstenite"]
validate-tenant-prefix = []
verify-client-cert = []
swanandx marked this conversation as resolved.
Show resolved Hide resolved
validate-tenant-prefix = ["verify-client-cert"]
allow-duplicate-clientid = []

[dev-dependencies]
Expand Down
10 changes: 6 additions & 4 deletions rumqttd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub struct PrometheusSetting {
#[serde(untagged)]
pub enum TlsConfig {
Rustls {
capath: String,
capath: Option<String>,
certpath: String,
keypath: String,
},
Expand All @@ -86,9 +86,11 @@ impl TlsConfig {
capath,
certpath,
keypath,
} => [capath, certpath, keypath]
.iter()
.all(|v| Path::new(v).exists()),
} => {
let ca = capath.is_none() || capath.as_ref().is_some_and(|v| Path::new(v).exists());

ca && [certpath, keypath].iter().all(|v| Path::new(v).exists())
}
TlsConfig::NativeTls { pkcs12path, .. } => Path::new(pkcs12path).exists(),
}
}
Expand Down
63 changes: 44 additions & 19 deletions rumqttd/src/server/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,18 @@ use {
tokio_native_tls::native_tls::Error as NativeTlsError,
};

use crate::TlsConfig;
#[cfg(feature = "verify-client-cert")]
use tokio_rustls::rustls::{server::AllowAnyAuthenticatedClient, RootCertStore};
#[cfg(feature = "use-rustls")]
use {
rustls_pemfile::Item,
std::{io::BufReader, sync::Arc},
tokio_rustls::rustls::{
server::AllowAnyAuthenticatedClient, Certificate, Error as RustlsError, PrivateKey,
RootCertStore, ServerConfig,
},
tokio_rustls::rustls::{Certificate, Error as RustlsError, PrivateKey, ServerConfig},
tracing::error,
};

use crate::link::network::N;
use crate::TlsConfig;

#[derive(Debug, thiserror::Error)]
#[error("Acceptor error")]
Expand Down Expand Up @@ -60,7 +59,7 @@ pub enum Error {
CertificateParse,
}

#[cfg(feature = "use-rustls")]
#[cfg(feature = "verify-client-cert")]
/// Extract uid from certificate's subject organization field
fn extract_tenant_id(der: &[u8]) -> Result<Option<String>, Error> {
let (_, cert) =
Expand Down Expand Up @@ -100,10 +99,15 @@ impl TLSAcceptor {
match config {
#[cfg(feature = "use-rustls")]
TlsConfig::Rustls {
capath,
capath: _capath,
certpath,
keypath,
} => Self::rustls(capath, certpath, keypath),
} => Self::rustls(
#[cfg(feature = "verify-client-cert")]
_capath,
certpath,
keypath,
),
#[cfg(feature = "use-native-tls")]
TlsConfig::NativeTls {
pkcs12path,
Expand All @@ -121,11 +125,18 @@ impl TLSAcceptor {
#[cfg(feature = "use-rustls")]
TLSAcceptor::Rustls { acceptor } => {
let stream = acceptor.accept(stream).await?;
let (_, session) = stream.get_ref();
let peer_certificates = session
.peer_certificates()
.ok_or(Error::NoPeerCertificate)?;
let tenant_id = extract_tenant_id(&peer_certificates[0].0)?;

#[cfg(feature = "verify-client-cert")]
let tenant_id = {
let (_, session) = stream.get_ref();
let peer_certificates = session
.peer_certificates()
.ok_or(Error::NoPeerCertificate)?;
extract_tenant_id(&peer_certificates[0].0)?
};
#[cfg(not(feature = "verify-client-cert"))]
let tenant_id: Option<String> = None;

let network = Box::new(stream);
Ok((tenant_id, network))
}
Expand Down Expand Up @@ -172,10 +183,19 @@ impl TLSAcceptor {

#[cfg(feature = "use-rustls")]
fn rustls(
ca_path: &String,
#[cfg(feature = "verify-client-cert")] ca_path: &Option<String>,
cert_path: &String,
key_path: &String,
) -> Result<TLSAcceptor, Error> {
#[cfg(feature = "verify-client-cert")]
let Some(ca_path) = ca_path
else {
return Err(Error::CaFileNotFound(
"capath must be specified in config when verify-client-cert is enabled."
.to_string(),
));
};

let (certs, key) = {
// Get certificates
let cert_file = File::open(cert_path);
Expand All @@ -193,8 +213,11 @@ impl TLSAcceptor {
(certs, key)
};

let builder = ServerConfig::builder().with_safe_defaults();

// client authentication with a CA. CA isn't required otherwise
let server_config = {
#[cfg(feature = "verify-client-cert")]
let builder = {
let ca_file = File::open(ca_path);
let ca_file = ca_file.map_err(|_| Error::CaFileNotFound(ca_path.clone()))?;
let ca_file = &mut BufReader::new(ca_file);
Expand All @@ -209,12 +232,14 @@ impl TLSAcceptor {
.add(&ca_cert)
.map_err(|_| Error::InvalidCACert(ca_path.to_string()))?;

ServerConfig::builder()
.with_safe_defaults()
.with_client_cert_verifier(Arc::new(AllowAnyAuthenticatedClient::new(store)))
.with_single_cert(certs, key)?
builder.with_client_cert_verifier(Arc::new(AllowAnyAuthenticatedClient::new(store)))
};

#[cfg(not(feature = "verify-client-cert"))]
let builder = builder.with_no_client_auth();

let server_config = builder.with_single_cert(certs, key)?;

let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config));
Ok(TLSAcceptor::Rustls { acceptor })
}
Expand Down