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

Allow ECC Key Configuration with rustls #743

Merged
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
1 change: 1 addition & 0 deletions rumqttd/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added
- Log warning if websocket config is getting ignored
- Add support for ECC keys when configuring TLS in rumqttd

### Changed
- Console endpoint /config prints Router Config instead of returning console settings
Expand Down
20 changes: 9 additions & 11 deletions rumqttd/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::net::SocketAddr;
use std::path::PathBuf;
use std::{collections::HashMap, path::Path};

use segments::Storage;
use serde::{Deserialize, Serialize};
use tracing_subscriber::{
filter::EnvFilter,
Expand All @@ -14,7 +14,14 @@ use tracing_subscriber::{
Registry,
};

use std::net::SocketAddr;
pub use link::alerts;
pub use link::local;
pub use link::meters;
pub use router::{Alert, IncomingMeter, Meter, Notification, OutgoingMeter};
use segments::Storage;
pub use server::Broker;

use self::router::shared_subs::Strategy;

mod link;
pub mod protocol;
Expand All @@ -31,15 +38,6 @@ pub type TopicId = usize;
pub type Offset = (u64, u64);
pub type Cursor = (u64, u64);

pub use link::alerts;
pub use link::local;
pub use link::meters;

pub use router::{Alert, IncomingMeter, Meter, Notification, OutgoingMeter};
pub use server::Broker;

use self::router::shared_subs::Strategy;

#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct Config {
pub id: usize,
Expand Down
4 changes: 4 additions & 0 deletions rumqttd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use config::FileFormat;
use rumqttd::Broker;

use clap::Parser;
use tracing::trace;

static RUMQTTD_DEFAULT_CONFIG: &str = include_str!("../rumqttd.toml");

Expand Down Expand Up @@ -97,6 +98,7 @@ fn validate_config(configs: &rumqttd::Config) {
if !tls_config.validate_paths() {
panic!("Certificate path not valid for server v4.{name}.")
}
trace!("Validated certificate paths for server v4.{name}.");
}
}
}
Expand All @@ -107,6 +109,7 @@ fn validate_config(configs: &rumqttd::Config) {
if !tls_config.validate_paths() {
panic!("Certificate path not valid for server v5.{name}.")
}
trace!("Validated certificate paths for server v5.{name}.");
}
}
}
Expand All @@ -117,6 +120,7 @@ fn validate_config(configs: &rumqttd::Config) {
if !tls_config.validate_paths() {
panic!("Certificate path not valid for server ws.{name}.")
}
trace!("Validated certificate paths for server ws.{name}.");
}
}
}
Expand Down
69 changes: 45 additions & 24 deletions rumqttd/src/server/tls.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
use std::fs::File;

#[cfg(feature = "use-native-tls")]
use std::io::Read;
use tokio::net::TcpStream;
#[cfg(feature = "use-native-tls")]
use tokio_native_tls::native_tls;
#[cfg(feature = "use-native-tls")]
use tokio_native_tls::native_tls::Error as NativeTlsError;

#[cfg(feature = "use-rustls")]
use tokio_rustls::rustls::{
server::AllowAnyAuthenticatedClient, Certificate, Error as RustlsError, PrivateKey,
RootCertStore, ServerConfig,
#[cfg(feature = "use-native-tls")]
use {
std::io::Read, tokio_native_tls::native_tls,
tokio_native_tls::native_tls::Error as NativeTlsError,
};

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

use crate::link::network::N;
use crate::TlsConfig;
Expand Down Expand Up @@ -187,18 +188,9 @@ impl TLSAcceptor {
.collect();

// Get private key
let key_file = File::open(key_path);
let key_file = key_file.map_err(|_| Error::ServerKeyNotFound(key_path.clone()))?;
let keys = rustls_pemfile::rsa_private_keys(&mut BufReader::new(key_file));
let keys = keys.map_err(|_| Error::InvalidServerKey(key_path.clone()))?;

// Get the first key
let key = match keys.first() {
Some(k) => k.clone(),
None => return Err(Error::InvalidServerKey(key_path.clone())),
};

(certs, PrivateKey(key))
let key = first_private_key_in_pemfile(key_path)?;

(certs, key)
};

// client authentication with a CA. CA isn't required otherwise
Expand Down Expand Up @@ -227,3 +219,32 @@ impl TLSAcceptor {
Ok(TLSAcceptor::Rustls { acceptor })
}
}

#[cfg(feature = "use-rustls")]
/// Get the first private key in a PEM file
fn first_private_key_in_pemfile(key_path: &String) -> Result<PrivateKey, Error> {
// Get private key
let key_file = File::open(key_path);
let key_file = key_file.map_err(|_| Error::ServerKeyNotFound(key_path.clone()))?;

let rd = &mut BufReader::new(key_file);

// keep reading Items one by one to find a Key, return error if none found.
loop {
let item = rustls_pemfile::read_one(rd).map_err(|err| {
error!("Error reading key file: {:?}", err);
Error::InvalidServerKey(key_path.clone())
})?;
swanandx marked this conversation as resolved.
Show resolved Hide resolved

match item {
Some(Item::ECKey(key) | Item::RSAKey(key) | Item::PKCS8Key(key)) => {
return Ok(PrivateKey(key));
}
None => {
error!("No private key found in {:?}", key_path);
return Err(Error::InvalidServerKey(key_path.clone()));
}
_ => {}
}
}
}