| 1 |
use std::fmt; |
| 2 |
use std::fs::File; |
| 3 |
use std::future::Future; |
| 4 |
use std::io::{self, BufReader, Cursor, Read}; |
| 5 |
use std::net::SocketAddr; |
| 6 |
use std::path::{Path, PathBuf}; |
| 7 |
use std::pin::Pin; |
| 8 |
use std::sync::Arc; |
| 9 |
use std::task::{Context, Poll}; |
| 10 |
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; |
| 11 |
|
| 12 |
use futures_util::ready; |
| 13 |
use hyper::server::accept::Accept; |
| 14 |
use hyper::server::conn::{AddrIncoming, AddrStream}; |
| 15 |
use tokio_rustls::rustls::server::WebPkiClientVerifier; |
| 16 |
use tokio_rustls::rustls::{Error as TlsError, RootCertStore, ServerConfig}; |
| 17 |
|
| 18 |
use crate::transport::Transport; |
| 19 |
|
| 20 |
/// Represents errors that can occur building the TlsConfig |
| 21 |
#[derive(Debug)] |
| 22 |
pub(crate) enum TlsConfigError { |
| 23 |
Io(io::Error), |
| 24 |
/// An Error parsing the Certificate |
| 25 |
CertParseError, |
| 26 |
/// Identity PEM is invalid |
| 27 |
InvalidIdentityPem, |
| 28 |
/// Identity PEM is missing a private key such as RSA, ECC or PKCS8 |
| 29 |
MissingPrivateKey, |
| 30 |
/// Unknown private key format |
| 31 |
UnknownPrivateKeyFormat, |
| 32 |
/// An error from an empty key |
| 33 |
EmptyKey, |
| 34 |
/// An error from an invalid key |
| 35 |
InvalidKey(TlsError), |
| 36 |
} |
| 37 |
|
| 38 |
impl fmt::Display for TlsConfigError { |
| 39 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 40 |
match self { |
| 41 |
TlsConfigError::Io(err) => err.fmt(f), |
| 42 |
TlsConfigError::CertParseError => write!(f, "certificate parse error"), |
| 43 |
TlsConfigError::UnknownPrivateKeyFormat => write!(f, "unknown private key format"), |
| 44 |
TlsConfigError::MissingPrivateKey => write!( |
| 45 |
f, |
| 46 |
"Identity PEM is missing a private key such as RSA, ECC or PKCS8" |
| 47 |
), |
| 48 |
TlsConfigError::InvalidIdentityPem => write!(f, "identity PEM is invalid"), |
| 49 |
TlsConfigError::EmptyKey => write!(f, "key contains no private key"), |
| 50 |
TlsConfigError::InvalidKey(err) => write!(f, "key contains an invalid key, {}", err), |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
impl std::error::Error for TlsConfigError {} |
| 56 |
|
| 57 |
/// Tls client authentication configuration. |
| 58 |
pub(crate) enum TlsClientAuth { |
| 59 |
/// No client auth. |
| 60 |
Off, |
| 61 |
/// Allow any anonymous or authenticated client. |
| 62 |
Optional(Box<dyn Read + Send + Sync>), |
| 63 |
/// Allow any authenticated client. |
| 64 |
Required(Box<dyn Read + Send + Sync>), |
| 65 |
} |
| 66 |
|
| 67 |
/// Builder to set the configuration for the Tls server. |
| 68 |
pub(crate) struct TlsConfigBuilder { |
| 69 |
cert: Box<dyn Read + Send + Sync>, |
| 70 |
key: Box<dyn Read + Send + Sync>, |
| 71 |
client_auth: TlsClientAuth, |
| 72 |
ocsp_resp: Vec<u8>, |
| 73 |
} |
| 74 |
|
| 75 |
impl fmt::Debug for TlsConfigBuilder { |
| 76 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 77 |
f.debug_struct("TlsConfigBuilder").finish() |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
impl TlsConfigBuilder { |
| 82 |
/// Create a new TlsConfigBuilder |
| 83 |
pub(crate) fn new() -> TlsConfigBuilder { |
| 84 |
TlsConfigBuilder { |
| 85 |
key: Box::new(io::empty()), |
| 86 |
cert: Box::new(io::empty()), |
| 87 |
client_auth: TlsClientAuth::Off, |
| 88 |
ocsp_resp: Vec::new(), |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
/// sets the Tls key via File Path, returns `TlsConfigError::IoError` if the file cannot be open |
| 93 |
pub(crate) fn key_path(mut self, path: impl AsRef<Path>) -> Self { |
| 94 |
self.key = Box::new(LazyFile { |
| 95 |
path: path.as_ref().into(), |
| 96 |
file: None, |
| 97 |
}); |
| 98 |
self |
| 99 |
} |
| 100 |
|
| 101 |
/// sets the Tls key via bytes slice |
| 102 |
pub(crate) fn key(mut self, key: &[u8]) -> Self { |
| 103 |
self.key = Box::new(Cursor::new(Vec::from(key))); |
| 104 |
self |
| 105 |
} |
| 106 |
|
| 107 |
/// Specify the file path for the TLS certificate to use. |
| 108 |
pub(crate) fn cert_path(mut self, path: impl AsRef<Path>) -> Self { |
| 109 |
self.cert = Box::new(LazyFile { |
| 110 |
path: path.as_ref().into(), |
| 111 |
file: None, |
| 112 |
}); |
| 113 |
self |
| 114 |
} |
| 115 |
|
| 116 |
/// sets the Tls certificate via bytes slice |
| 117 |
pub(crate) fn cert(mut self, cert: &[u8]) -> Self { |
| 118 |
self.cert = Box::new(Cursor::new(Vec::from(cert))); |
| 119 |
self |
| 120 |
} |
| 121 |
|
| 122 |
/// Sets the trust anchor for optional Tls client authentication via file path. |
| 123 |
/// |
| 124 |
/// Anonymous and authenticated clients will be accepted. If no trust anchor is provided by any |
| 125 |
/// of the `client_auth_` methods, then client authentication is disabled by default. |
| 126 |
pub(crate) fn client_auth_optional_path(mut self, path: impl AsRef<Path>) -> Self { |
| 127 |
let file = Box::new(LazyFile { |
| 128 |
path: path.as_ref().into(), |
| 129 |
file: None, |
| 130 |
}); |
| 131 |
self.client_auth = TlsClientAuth::Optional(file); |
| 132 |
self |
| 133 |
} |
| 134 |
|
| 135 |
/// Sets the trust anchor for optional Tls client authentication via bytes slice. |
| 136 |
/// |
| 137 |
/// Anonymous and authenticated clients will be accepted. If no trust anchor is provided by any |
| 138 |
/// of the `client_auth_` methods, then client authentication is disabled by default. |
| 139 |
pub(crate) fn client_auth_optional(mut self, trust_anchor: &[u8]) -> Self { |
| 140 |
let cursor = Box::new(Cursor::new(Vec::from(trust_anchor))); |
| 141 |
self.client_auth = TlsClientAuth::Optional(cursor); |
| 142 |
self |
| 143 |
} |
| 144 |
|
| 145 |
/// Sets the trust anchor for required Tls client authentication via file path. |
| 146 |
/// |
| 147 |
/// Only authenticated clients will be accepted. If no trust anchor is provided by any of the |
| 148 |
/// `client_auth_` methods, then client authentication is disabled by default. |
| 149 |
pub(crate) fn client_auth_required_path(mut self, path: impl AsRef<Path>) -> Self { |
| 150 |
let file = Box::new(LazyFile { |
| 151 |
path: path.as_ref().into(), |
| 152 |
file: None, |
| 153 |
}); |
| 154 |
self.client_auth = TlsClientAuth::Required(file); |
| 155 |
self |
| 156 |
} |
| 157 |
|
| 158 |
/// Sets the trust anchor for required Tls client authentication via bytes slice. |
| 159 |
/// |
| 160 |
/// Only authenticated clients will be accepted. If no trust anchor is provided by any of the |
| 161 |
/// `client_auth_` methods, then client authentication is disabled by default. |
| 162 |
pub(crate) fn client_auth_required(mut self, trust_anchor: &[u8]) -> Self { |
| 163 |
let cursor = Box::new(Cursor::new(Vec::from(trust_anchor))); |
| 164 |
self.client_auth = TlsClientAuth::Required(cursor); |
| 165 |
self |
| 166 |
} |
| 167 |
|
| 168 |
/// sets the DER-encoded OCSP response |
| 169 |
pub(crate) fn ocsp_resp(mut self, ocsp_resp: &[u8]) -> Self { |
| 170 |
self.ocsp_resp = Vec::from(ocsp_resp); |
| 171 |
self |
| 172 |
} |
| 173 |
|
| 174 |
pub(crate) fn build(mut self) -> Result<ServerConfig, TlsConfigError> { |
| 175 |
let mut cert_rdr = BufReader::new(self.cert); |
| 176 |
let cert = rustls_pemfile::certs(&mut cert_rdr) |
| 177 |
.collect::<Result<Vec<_>, _>>() |
| 178 |
.map_err(|_e| TlsConfigError::CertParseError)?; |
| 179 |
|
| 180 |
let mut key_vec = Vec::new(); |
| 181 |
self.key |
| 182 |
.read_to_end(&mut key_vec) |
| 183 |
.map_err(TlsConfigError::Io)?; |
| 184 |
|
| 185 |
if key_vec.is_empty() { |
| 186 |
return Err(TlsConfigError::EmptyKey); |
| 187 |
} |
| 188 |
|
| 189 |
let mut key_opt = None; |
| 190 |
let mut key_cur = std::io::Cursor::new(key_vec); |
| 191 |
for item in rustls_pemfile::read_all(&mut key_cur) |
| 192 |
.collect::<Result<Vec<_>, _>>() |
| 193 |
.map_err(|_e| TlsConfigError::InvalidIdentityPem)? |
| 194 |
{ |
| 195 |
match item { |
| 196 |
rustls_pemfile::Item::Pkcs1Key(k) => key_opt = Some(k.into()), |
| 197 |
rustls_pemfile::Item::Pkcs8Key(k) => key_opt = Some(k.into()), |
| 198 |
rustls_pemfile::Item::Sec1Key(k) => key_opt = Some(k.into()), |
| 199 |
_ => return Err(TlsConfigError::UnknownPrivateKeyFormat), |
| 200 |
} |
| 201 |
} |
| 202 |
let key = match key_opt { |
| 203 |
Some(v) => v, |
| 204 |
_ => return Err(TlsConfigError::MissingPrivateKey), |
| 205 |
}; |
| 206 |
|
| 207 |
fn read_trust_anchor( |
| 208 |
trust_anchor: Box<dyn Read + Send + Sync>, |
| 209 |
) -> Result<RootCertStore, TlsConfigError> { |
| 210 |
let trust_anchors = { |
| 211 |
let mut reader = BufReader::new(trust_anchor); |
| 212 |
rustls_pemfile::certs(&mut reader) |
| 213 |
.collect::<Result<Vec<_>, _>>() |
| 214 |
.map_err(TlsConfigError::Io)? |
| 215 |
}; |
| 216 |
|
| 217 |
let mut store = RootCertStore::empty(); |
| 218 |
let (added, _skipped) = store.add_parsable_certificates(trust_anchors); |
| 219 |
if added == 0 { |
| 220 |
return Err(TlsConfigError::CertParseError); |
| 221 |
} |
| 222 |
|
| 223 |
Ok(store) |
| 224 |
} |
| 225 |
|
| 226 |
let config = { |
| 227 |
let builder = ServerConfig::builder(); |
| 228 |
let mut config = match self.client_auth { |
| 229 |
TlsClientAuth::Off => builder.with_no_client_auth(), |
| 230 |
TlsClientAuth::Optional(trust_anchor) => { |
| 231 |
let verifier = |
| 232 |
WebPkiClientVerifier::builder(read_trust_anchor(trust_anchor)?.into()) |
| 233 |
.allow_unauthenticated() |
| 234 |
.build() |
| 235 |
.map_err(|_| TlsConfigError::CertParseError)?; |
| 236 |
builder.with_client_cert_verifier(verifier) |
| 237 |
} |
| 238 |
TlsClientAuth::Required(trust_anchor) => { |
| 239 |
let verifier = |
| 240 |
WebPkiClientVerifier::builder(read_trust_anchor(trust_anchor)?.into()) |
| 241 |
.build() |
| 242 |
.map_err(|_| TlsConfigError::CertParseError)?; |
| 243 |
builder.with_client_cert_verifier(verifier) |
| 244 |
} |
| 245 |
} |
| 246 |
.with_single_cert_with_ocsp(cert, key, self.ocsp_resp) |
| 247 |
.map_err(TlsConfigError::InvalidKey)?; |
| 248 |
config.alpn_protocols = vec!["h2".into(), "http/1.1".into()]; |
| 249 |
config |
| 250 |
}; |
| 251 |
|
| 252 |
Ok(config) |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
struct LazyFile { |
| 257 |
path: PathBuf, |
| 258 |
file: Option<File>, |
| 259 |
} |
| 260 |
|
| 261 |
impl LazyFile { |
| 262 |
fn lazy_read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 263 |
if self.file.is_none() { |
| 264 |
self.file = Some(File::open(&self.path)?); |
| 265 |
} |
| 266 |
|
| 267 |
self.file.as_mut().unwrap().read(buf) |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
impl Read for LazyFile { |
| 272 |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 273 |
self.lazy_read(buf).map_err(|err| { |
| 274 |
let kind = err.kind(); |
| 275 |
io::Error::new( |
| 276 |
kind, |
| 277 |
format!("error reading file ({:?}): {}", self.path.display(), err), |
| 278 |
) |
| 279 |
}) |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
impl Transport for TlsStream { |
| 284 |
fn remote_addr(&self) -> Option<SocketAddr> { |
| 285 |
Some(self.remote_addr) |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
enum State { |
| 290 |
Handshaking(tokio_rustls::Accept<AddrStream>), |
| 291 |
Streaming(tokio_rustls::server::TlsStream<AddrStream>), |
| 292 |
} |
| 293 |
|
| 294 |
// tokio_rustls::server::TlsStream doesn't expose constructor methods, |
| 295 |
// so we have to TlsAcceptor::accept and handshake to have access to it |
| 296 |
// TlsStream implements AsyncRead/AsyncWrite handshaking tokio_rustls::Accept first |
| 297 |
pub(crate) struct TlsStream { |
| 298 |
state: State, |
| 299 |
remote_addr: SocketAddr, |
| 300 |
} |
| 301 |
|
| 302 |
impl TlsStream { |
| 303 |
fn new(stream: AddrStream, config: Arc<ServerConfig>) -> TlsStream { |
| 304 |
let remote_addr = stream.remote_addr(); |
| 305 |
let accept = tokio_rustls::TlsAcceptor::from(config).accept(stream); |
| 306 |
TlsStream { |
| 307 |
state: State::Handshaking(accept), |
| 308 |
remote_addr, |
| 309 |
} |
| 310 |
} |
| 311 |
} |
| 312 |
|
| 313 |
impl AsyncRead for TlsStream { |
| 314 |
fn poll_read( |
| 315 |
self: Pin<&mut Self>, |
| 316 |
cx: &mut Context<'_>, |
| 317 |
buf: &mut ReadBuf<'_>, |
| 318 |
) -> Poll<io::Result<()>> { |
| 319 |
let pin = self.get_mut(); |
| 320 |
match pin.state { |
| 321 |
State::Handshaking(ref mut accept) => match ready!(Pin::new(accept).poll(cx)) { |
| 322 |
Ok(mut stream) => { |
| 323 |
let result = Pin::new(&mut stream).poll_read(cx, buf); |
| 324 |
pin.state = State::Streaming(stream); |
| 325 |
result |
| 326 |
} |
| 327 |
Err(err) => Poll::Ready(Err(err)), |
| 328 |
}, |
| 329 |
State::Streaming(ref mut stream) => Pin::new(stream).poll_read(cx, buf), |
| 330 |
} |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
impl AsyncWrite for TlsStream { |
| 335 |
fn poll_write( |
| 336 |
self: Pin<&mut Self>, |
| 337 |
cx: &mut Context<'_>, |
| 338 |
buf: &[u8], |
| 339 |
) -> Poll<io::Result<usize>> { |
| 340 |
let pin = self.get_mut(); |
| 341 |
match pin.state { |
| 342 |
State::Handshaking(ref mut accept) => match ready!(Pin::new(accept).poll(cx)) { |
| 343 |
Ok(mut stream) => { |
| 344 |
let result = Pin::new(&mut stream).poll_write(cx, buf); |
| 345 |
pin.state = State::Streaming(stream); |
| 346 |
result |
| 347 |
} |
| 348 |
Err(err) => Poll::Ready(Err(err)), |
| 349 |
}, |
| 350 |
State::Streaming(ref mut stream) => Pin::new(stream).poll_write(cx, buf), |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 355 |
match self.state { |
| 356 |
State::Handshaking(_) => Poll::Ready(Ok(())), |
| 357 |
State::Streaming(ref mut stream) => Pin::new(stream).poll_flush(cx), |
| 358 |
} |
| 359 |
} |
| 360 |
|
| 361 |
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 362 |
match self.state { |
| 363 |
State::Handshaking(_) => Poll::Ready(Ok(())), |
| 364 |
State::Streaming(ref mut stream) => Pin::new(stream).poll_shutdown(cx), |
| 365 |
} |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
pub(crate) struct TlsAcceptor { |
| 370 |
config: Arc<ServerConfig>, |
| 371 |
incoming: AddrIncoming, |
| 372 |
} |
| 373 |
|
| 374 |
impl TlsAcceptor { |
| 375 |
pub(crate) fn new(config: ServerConfig, incoming: AddrIncoming) -> TlsAcceptor { |
| 376 |
TlsAcceptor { |
| 377 |
config: Arc::new(config), |
| 378 |
incoming, |
| 379 |
} |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
impl Accept for TlsAcceptor { |
| 384 |
type Conn = TlsStream; |
| 385 |
type Error = io::Error; |
| 386 |
|
| 387 |
fn poll_accept( |
| 388 |
self: Pin<&mut Self>, |
| 389 |
cx: &mut Context<'_>, |
| 390 |
) -> Poll<Option<Result<Self::Conn, Self::Error>>> { |
| 391 |
let pin = self.get_mut(); |
| 392 |
match ready!(Pin::new(&mut pin.incoming).poll_accept(cx)) { |
| 393 |
Some(Ok(sock)) => Poll::Ready(Some(Ok(TlsStream::new(sock, pin.config.clone())))), |
| 394 |
Some(Err(e)) => Poll::Ready(Some(Err(e))), |
| 395 |
None => Poll::Ready(None), |
| 396 |
} |
| 397 |
} |
| 398 |
} |
| 399 |
|
| 400 |
#[cfg(test)] |
| 401 |
mod tests { |
| 402 |
use super::*; |
| 403 |
|
| 404 |
#[test] |
| 405 |
fn file_cert_key() { |
| 406 |
TlsConfigBuilder::new() |
| 407 |
.key_path("examples/tls/key.rsa") |
| 408 |
.cert_path("examples/tls/cert.pem") |
| 409 |
.build() |
| 410 |
.unwrap(); |
| 411 |
} |
| 412 |
|
| 413 |
#[test] |
| 414 |
fn bytes_cert_key() { |
| 415 |
let key = include_str!("../examples/tls/key.rsa"); |
| 416 |
let cert = include_str!("../examples/tls/cert.pem"); |
| 417 |
|
| 418 |
TlsConfigBuilder::new() |
| 419 |
.key(key.as_bytes()) |
| 420 |
.cert(cert.as_bytes()) |
| 421 |
.build() |
| 422 |
.unwrap(); |
| 423 |
} |
| 424 |
|
| 425 |
#[test] |
| 426 |
fn file_ecc_cert_key() { |
| 427 |
TlsConfigBuilder::new() |
| 428 |
.key_path("examples/tls/key.ecc") |
| 429 |
.cert_path("examples/tls/cert.ecc.pem") |
| 430 |
.build() |
| 431 |
.unwrap(); |
| 432 |
} |
| 433 |
|
| 434 |
#[test] |
| 435 |
fn bytes_ecc_cert_key() { |
| 436 |
let key = include_str!("../examples/tls/key.ecc"); |
| 437 |
let cert = include_str!("../examples/tls/cert.ecc.pem"); |
| 438 |
|
| 439 |
TlsConfigBuilder::new() |
| 440 |
.key(key.as_bytes()) |
| 441 |
.cert(cert.as_bytes()) |
| 442 |
.build() |
| 443 |
.unwrap(); |
| 444 |
} |
| 445 |
} |