oxedyne/fe2o3/fe2o3_net/src/tls/mod.rs
45.6 KiB, 14 runs
created by r1870400018:76016, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Client-side TLS plumbing shared by the protocol clients. |
| 2 | //! |
| 3 | //! Every outbound protocol client in this crate faces the same two |
| 4 | //! problems: it must be able to speak plain TCP and TLS over one socket |
| 5 | //! (because STARTTLS upgrades in place), and it must validate the peer |
| 6 | //! against the host's trust anchors. [`ClientStream`] solves the first |
| 7 | //! and [`default_client_config`] the second, so SMTP, IMAP and anything |
| 8 | //! that follows share one implementation rather than each carrying its |
| 9 | //! own copy. |
| 10 | //! |
| 11 | //! Server-side TLS is a different concrete type -- `tokio_rustls` |
| 12 | //! distinguishes the client and server halves of a `TlsStream` -- so the |
| 13 | //! SMTP and IMAP servers keep their own `MaybeTls` and are unaffected. |
| 14 | //! |
| 15 | //! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\ |
| 16 | //! Anthropic Claude |
| 17 | |
| 18 | use oxedyne_fe2o3_core::prelude::*; |
| 19 | use oxedyne_fe2o3_jdat::prelude::*; |
| 20 | |
| 21 | use std::{ |
| 22 | collections::BTreeMap, |
| 23 | ffi::OsString, |
| 24 | path::{ |
| 25 | Path, |
| 26 | PathBuf, |
| 27 | }, |
| 28 | pin::Pin, |
| 29 | sync::Arc, |
| 30 | task::{ |
| 31 | Context, |
| 32 | Poll, |
| 33 | }, |
| 34 | }; |
| 35 | |
| 36 | use std::time::Duration; |
| 37 | |
| 38 | use tokio::{ |
| 39 | io::{ |
| 40 | AsyncRead, |
| 41 | AsyncWrite, |
| 42 | ReadBuf, |
| 43 | }, |
| 44 | net::TcpStream, |
| 45 | sync::Semaphore, |
| 46 | }; |
| 47 | use tokio_rustls::{ |
| 48 | rustls::{ |
| 49 | AlertDescription, |
| 50 | ClientConfig, |
| 51 | pki_types::{ |
| 52 | CertificateDer, |
| 53 | ServerName, |
| 54 | }, |
| 55 | RootCertStore, |
| 56 | }, |
| 57 | TlsAcceptor, |
| 58 | TlsConnector, |
| 59 | }; |
| 60 | |
| 61 | pub mod mint; |
| 62 | pub use mint::{ |
| 63 | Mint, |
| 64 | NameRule, |
| 65 | }; |
| 66 | |
| 67 | |
| 68 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 69 | // │ BOUNDED SERVER-SIDE TLS ACCEPTOR │ |
| 70 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 71 | |
| 72 | /// The result of a bounded handshake, distinguishing the ways it can fail. |
| 73 | /// |
| 74 | /// A `TimedOut` is an admission event -- the permit wait or the handshake ran |
| 75 | /// past the deadline -- and a caller that keeps admission counters records it as |
| 76 | /// a drop. A `PeerFailed` is a handshake that the peer ended or could not make |
| 77 | /// work: a client that hung up, spoke nonsense, or offered no protocol version, |
| 78 | /// cipher suite or application protocol this server serves. Every scanner and |
| 79 | /// old client on a public port produces one, so a caller should log it below |
| 80 | /// `ERROR`. A `Failed` is everything else, which may be the server's own fault |
| 81 | /// -- no certificate to serve, a peer rejecting the certificate it was shown -- |
| 82 | /// and is the one to log loudly. A cause that cannot be told is a `Failed`, so |
| 83 | /// reading it as the peer's fault never hides a fault of ours. |
| 84 | pub enum Handshake<IO> { |
| 85 | Ok(tokio_rustls::server::TlsStream<IO>), |
| 86 | TimedOut, |
| 87 | PeerFailed(Error<ErrTag>), |
| 88 | Failed(Error<ErrTag>), |
| 89 | } |
| 90 | |
| 91 | /// Did the peer, and not this server, end the handshake? |
| 92 | /// |
| 93 | /// An `io::Error` that wraps a rustls error is judged by that error; any other |
| 94 | /// is judged by its kind, a transport that went away. The rustls match is an |
| 95 | /// allowlist of the peer's own faults, so a variant added to that non-exhaustive |
| 96 | /// enum is treated as ours until someone says otherwise. |
| 97 | fn peer_ended(e: &std::io::Error) -> bool { |
| 98 | use tokio_rustls::rustls::Error as Tls; |
| 99 | match e.get_ref().and_then(|inner| inner.downcast_ref::<Tls>()) { |
| 100 | Some(Tls::PeerIncompatible(_)) |
| 101 | | Some(Tls::PeerMisbehaved(_)) |
| 102 | | Some(Tls::InvalidMessage(_)) |
| 103 | | Some(Tls::InappropriateMessage { .. }) |
| 104 | | Some(Tls::InappropriateHandshakeMessage { .. }) |
| 105 | | Some(Tls::PeerSentOversizedRecord) |
| 106 | | Some(Tls::NoApplicationProtocol) |
| 107 | | Some(Tls::UnsupportedNameType) |
| 108 | | Some(Tls::DecryptError) => true, |
| 109 | // An alert is the peer's word, and a rejected certificate is the one it |
| 110 | // can say about us: an expired or mismatched certificate reaches the |
| 111 | // server only this way, so it is never read as a scanner's doing. |
| 112 | Some(Tls::AlertReceived(a)) => !rejects_certificate(a), |
| 113 | Some(_) => false, |
| 114 | None => is_dropped(e), |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Did the transport go away under us -- reset, aborted, or ended mid-exchange -- rather than |
| 119 | /// carry a fault either end could name? A fresh connection may well succeed where this one did |
| 120 | /// not. An error wrapping a rustls error is a protocol or certificate fault, and never a drop. |
| 121 | pub fn is_dropped(e: &std::io::Error) -> bool { |
| 122 | use std::io::ErrorKind; |
| 123 | use tokio_rustls::rustls::Error as Tls; |
| 124 | if e.get_ref().and_then(|inner| inner.downcast_ref::<Tls>()).is_some() { |
| 125 | return false; |
| 126 | } |
| 127 | matches!(e.kind(), |
| 128 | ErrorKind::ConnectionReset |
| 129 | | ErrorKind::ConnectionAborted |
| 130 | | ErrorKind::BrokenPipe |
| 131 | | ErrorKind::UnexpectedEof) |
| 132 | } |
| 133 | |
| 134 | /// Did a connection attempt find nothing that would take it -- refused, or no route to the host? |
| 135 | pub fn is_unreachable(e: &std::io::Error) -> bool { |
| 136 | use std::io::ErrorKind; |
| 137 | matches!(e.kind(), |
| 138 | ErrorKind::ConnectionRefused |
| 139 | | ErrorKind::HostUnreachable |
| 140 | | ErrorKind::NetworkUnreachable |
| 141 | | ErrorKind::AddrNotAvailable) |
| 142 | } |
| 143 | |
| 144 | /// A failed dial, tagged by cause: `Unreachable` where nothing would take the connection, |
| 145 | /// `Interrupted` where it dropped as it was made. |
| 146 | pub fn dial_fault(e: std::io::Error, what: String) -> Error<ErrTag> { |
| 147 | if is_unreachable(&e) { |
| 148 | err!(e, "{}: nothing would take the connection.", what; IO, Network, Unreachable) |
| 149 | } else if is_dropped(&e) { |
| 150 | err!(e, "{}: the connection dropped.", what; IO, Network, Interrupted) |
| 151 | } else { |
| 152 | err!(e, "{}.", what; IO, Network) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// A transport fault on the open connection, tagged `Interrupted` where the connection went away. |
| 157 | pub fn wire_fault(e: std::io::Error, what: String, write: bool) -> Error<ErrTag> { |
| 158 | match (is_dropped(&e), write) { |
| 159 | (true, false) => err!(e, "{}: the connection dropped.", what; IO, Network, Read, Interrupted), |
| 160 | (true, true) => err!(e, "{}: the connection dropped.", what; IO, Network, Write, Interrupted), |
| 161 | (false, false) => err!(e, "{}.", what; IO, Network, Read), |
| 162 | (false, true) => err!(e, "{}.", what; IO, Network, Write), |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// Did a client handshake fail because a certificate was not accepted, whether ours by the peer |
| 167 | /// or the peer's by us? |
| 168 | fn refuses_certificate(e: &std::io::Error) -> bool { |
| 169 | use tokio_rustls::rustls::Error as Tls; |
| 170 | match e.get_ref().and_then(|inner| inner.downcast_ref::<Tls>()) { |
| 171 | Some(Tls::InvalidCertificate(_)) |
| 172 | | Some(Tls::NoCertificatesPresented) => true, |
| 173 | Some(Tls::AlertReceived(a)) => rejects_certificate(a), |
| 174 | _ => false, |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// Does an alert from the peer say that it will not accept our certificate? |
| 179 | fn rejects_certificate(a: &AlertDescription) -> bool { |
| 180 | matches!(a, |
| 181 | AlertDescription::BadCertificate |
| 182 | | AlertDescription::UnsupportedCertificate |
| 183 | | AlertDescription::CertificateRevoked |
| 184 | | AlertDescription::CertificateExpired |
| 185 | | AlertDescription::CertificateUnknown |
| 186 | | AlertDescription::UnknownCA |
| 187 | | AlertDescription::BadCertificateStatusResponse |
| 188 | | AlertDescription::BadCertificateHashValue) |
| 189 | } |
| 190 | |
| 191 | /// Sorts a failed handshake by whose fault it was. |
| 192 | fn failed<IO>(e: std::io::Error) -> Handshake<IO> { |
| 193 | if peer_ended(&e) { |
| 194 | Handshake::PeerFailed(err!(e, "TLS handshake failed."; IO, Network, Init)) |
| 195 | } else { |
| 196 | Handshake::Failed(err!(e, "TLS handshake failed."; IO, Network, Init)) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | /// A `TlsAcceptor` with a shared cap on how many handshakes run at once and a |
| 201 | /// deadline on each. |
| 202 | /// |
| 203 | /// The same rustls server configuration serves HTTPS and the mail listeners |
| 204 | /// (SMTP STARTTLS, implicit-TLS IMAP), so the bound lives here, once, and every |
| 205 | /// listener shares one `BoundedTlsAcceptor` rather than each carrying its own. |
| 206 | /// Two shapes are closed together: a flood of concurrent handshakes exhausting |
| 207 | /// the CPU on a single-vCPU box (the semaphore), and a drip-fed handshake that |
| 208 | /// pins a permit indefinitely and turns the semaphore itself into a slowloris |
| 209 | /// amplifier (the deadline, which covers both the wait for a permit and the |
| 210 | /// handshake it guards). Both bounds are optional: a zero permit count or an |
| 211 | /// absent deadline disables that half, which is the inert default. |
| 212 | #[derive(Clone)] |
| 213 | pub struct BoundedTlsAcceptor { |
| 214 | acceptor: TlsAcceptor, |
| 215 | sem: Option<std::sync::Arc<Semaphore>>, // None disables the concurrency bound |
| 216 | deadline: Option<Duration>, // None disables the handshake deadline |
| 217 | } |
| 218 | |
| 219 | impl BoundedTlsAcceptor { |
| 220 | |
| 221 | /// `max_handshakes` of 0 leaves handshake concurrency unbounded; a `None` |
| 222 | /// deadline leaves each handshake untimed. Both are the inert defaults, so a |
| 223 | /// caller that opts into neither gets exactly a bare `TlsAcceptor`'s behaviour. |
| 224 | pub fn new( |
| 225 | acceptor: TlsAcceptor, |
| 226 | max_handshakes: usize, |
| 227 | deadline: Option<Duration>, |
| 228 | ) |
| 229 | -> Self |
| 230 | { |
| 231 | let sem = if max_handshakes == 0 { |
| 232 | None |
| 233 | } else { |
| 234 | Some(std::sync::Arc::new(Semaphore::new(max_handshakes))) |
| 235 | }; |
| 236 | Self { acceptor, sem, deadline } |
| 237 | } |
| 238 | |
| 239 | /// An acceptor with neither bound, for a caller that wants the plain thing. |
| 240 | pub fn unbounded(acceptor: TlsAcceptor) -> Self { |
| 241 | Self { acceptor, sem: None, deadline: None } |
| 242 | } |
| 243 | |
| 244 | /// The per-handshake deadline, so a caller can time an adjacent step (a peek |
| 245 | /// before the handshake, say) to the same bound. |
| 246 | pub fn deadline(&self) -> Option<Duration> { |
| 247 | self.deadline |
| 248 | } |
| 249 | |
| 250 | /// Complete one server-side handshake within the shared concurrency cap and |
| 251 | /// the deadline. |
| 252 | /// |
| 253 | /// A permit is taken immediately before the handshake and released the moment |
| 254 | /// it returns, so it bounds only the expensive handshake and never the whole |
| 255 | /// session that follows. The deadline wraps both the wait for a permit and |
| 256 | /// the handshake, so no single connection can hold a slot open indefinitely. |
| 257 | pub async fn accept<IO>(&self, stream: IO) -> Handshake<IO> |
| 258 | where |
| 259 | IO: AsyncRead + AsyncWrite + Unpin, |
| 260 | { |
| 261 | // A permit, bounded by the deadline. Held across the handshake below and |
| 262 | // dropped when this function returns. |
| 263 | let _permit = match &self.sem { |
| 264 | Some(sem) => match self.deadline { |
| 265 | Some(d) => match tokio::time::timeout(d, sem.acquire()).await { |
| 266 | Ok(Ok(p)) => Some(p), |
| 267 | Ok(Err(_)) => return Handshake::Failed(err!( |
| 268 | "The TLS handshake semaphore was closed."; Bug, Network)), |
| 269 | Err(_) => return Handshake::TimedOut, |
| 270 | }, |
| 271 | None => match sem.acquire().await { |
| 272 | Ok(p) => Some(p), |
| 273 | Err(_) => return Handshake::Failed(err!( |
| 274 | "The TLS handshake semaphore was closed."; Bug, Network)), |
| 275 | }, |
| 276 | }, |
| 277 | None => None, |
| 278 | }; |
| 279 | match self.deadline { |
| 280 | Some(d) => match tokio::time::timeout(d, self.acceptor.accept(stream)).await { |
| 281 | Ok(Ok(tls)) => Handshake::Ok(tls), |
| 282 | Ok(Err(e)) => failed(e), |
| 283 | Err(_) => Handshake::TimedOut, |
| 284 | }, |
| 285 | None => match self.acceptor.accept(stream).await { |
| 286 | Ok(tls) => Handshake::Ok(tls), |
| 287 | Err(e) => failed(e), |
| 288 | }, |
| 289 | } |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | |
| 294 | /// Either a plain TCP stream or a client-side TLS-wrapped TCP stream. |
| 295 | /// |
| 296 | /// A protocol client holds one of these and can replace a `Plain` with a |
| 297 | /// `Tls` in place, which is exactly what a STARTTLS upgrade is. |
| 298 | pub enum ClientStream { |
| 299 | Plain(TcpStream), |
| 300 | Tls(Box<tokio_rustls::client::TlsStream<TcpStream>>), |
| 301 | } |
| 302 | |
| 303 | impl ClientStream { |
| 304 | |
| 305 | /// `None` once TLS has wrapped it, there being nothing plain left to take. |
| 306 | pub fn into_plain(self) -> Option<TcpStream> { |
| 307 | match self { |
| 308 | Self::Plain(s) => Some(s), |
| 309 | Self::Tls(_) => None, |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | pub fn is_tls(&self) -> bool { |
| 314 | matches!(self, Self::Tls(_)) |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | impl AsyncRead for ClientStream { |
| 319 | fn poll_read( |
| 320 | self: Pin<&mut Self>, |
| 321 | cx: &mut Context<'_>, |
| 322 | buf: &mut ReadBuf<'_>, |
| 323 | ) |
| 324 | -> Poll<std::io::Result<()>> |
| 325 | { |
| 326 | match self.get_mut() { |
| 327 | Self::Plain(s) => Pin::new(s).poll_read(cx, buf), |
| 328 | Self::Tls(s) => Pin::new(s.as_mut()).poll_read(cx, buf), |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | impl AsyncWrite for ClientStream { |
| 334 | fn poll_write( |
| 335 | self: Pin<&mut Self>, |
| 336 | cx: &mut Context<'_>, |
| 337 | buf: &[u8], |
| 338 | ) |
| 339 | -> Poll<std::io::Result<usize>> |
| 340 | { |
| 341 | match self.get_mut() { |
| 342 | Self::Plain(s) => Pin::new(s).poll_write(cx, buf), |
| 343 | Self::Tls(s) => Pin::new(s.as_mut()).poll_write(cx, buf), |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | fn poll_flush( |
| 348 | self: Pin<&mut Self>, |
| 349 | cx: &mut Context<'_>, |
| 350 | ) |
| 351 | -> Poll<std::io::Result<()>> |
| 352 | { |
| 353 | match self.get_mut() { |
| 354 | Self::Plain(s) => Pin::new(s).poll_flush(cx), |
| 355 | Self::Tls(s) => Pin::new(s.as_mut()).poll_flush(cx), |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | fn poll_shutdown( |
| 360 | self: Pin<&mut Self>, |
| 361 | cx: &mut Context<'_>, |
| 362 | ) |
| 363 | -> Poll<std::io::Result<()>> |
| 364 | { |
| 365 | match self.get_mut() { |
| 366 | Self::Plain(s) => Pin::new(s).poll_shutdown(cx), |
| 367 | Self::Tls(s) => Pin::new(s.as_mut()).poll_shutdown(cx), |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | /// The peer certificate is validated against `cfg` for the name `host`, and the handshake must |
| 373 | /// finish within `deadline`. A peer that takes the connection and never answers the hello would |
| 374 | /// otherwise hold the caller for as long as the socket lived. |
| 375 | pub async fn upgrade( |
| 376 | plain: TcpStream, |
| 377 | host: &str, |
| 378 | cfg: Arc<ClientConfig>, |
| 379 | deadline: Duration, |
| 380 | ) |
| 381 | -> Outcome<ClientStream> |
| 382 | { |
| 383 | match tokio::time::timeout(deadline, handshake(plain, host, cfg)).await { |
| 384 | Ok(result) => result, |
| 385 | Err(_) => Err(err!( |
| 386 | "The TLS handshake to {} did not finish within {:?}.", host, deadline; |
| 387 | IO, Network, Init, Timeout)), |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | /// As [`upgrade`], with nothing bounding the handshake, for a caller that bounds a longer |
| 392 | /// exchange as a whole. |
| 393 | pub async fn handshake( |
| 394 | plain: TcpStream, |
| 395 | host: &str, |
| 396 | cfg: Arc<ClientConfig>, |
| 397 | ) |
| 398 | -> Outcome<ClientStream> |
| 399 | { |
| 400 | let name = match ServerName::try_from(host.to_string()) { |
| 401 | Ok(n) => n, |
| 402 | Err(_) => return Err(err!( |
| 403 | "Cannot construct a TLS server name from '{}'.", host; |
| 404 | Invalid, Input)), |
| 405 | }; |
| 406 | let connector = TlsConnector::from(cfg); |
| 407 | match connector.connect(name, plain).await { |
| 408 | Ok(s) => Ok(ClientStream::Tls(Box::new(s))), |
| 409 | // Sorted by cause, because a caller explaining the failure to a person must not tell them |
| 410 | // a certificate was refused when the connection merely dropped (D-20261006-09). The |
| 411 | // words of both mention TLS and the handshake, so only the tags can tell them apart. |
| 412 | Err(e) if refuses_certificate(&e) => Err(err!(e, |
| 413 | "TLS handshake to {}: the certificate was not accepted.", host; |
| 414 | IO, Network, Init, Security)), |
| 415 | Err(e) if is_dropped(&e) => Err(err!(e, |
| 416 | "TLS handshake to {}: the connection dropped.", host; |
| 417 | IO, Network, Init, Interrupted)), |
| 418 | Err(e) => Err(err!(e, |
| 419 | "TLS handshake to {}.", host; |
| 420 | IO, Network, Init)), |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | /// Ensure rustls has a process-wide crypto provider. |
| 425 | /// |
| 426 | /// rustls resolves its provider from process-global state, and its builders |
| 427 | /// **panic** when they cannot pick one unambiguously -- either because none |
| 428 | /// is installed, or because the build enabled more than one and so has no |
| 429 | /// default. An application is expected to install one in `main`, and the |
| 430 | /// Steel binary does; but a library that panics because its *caller's* |
| 431 | /// `main` omitted a line is a landmine, and it goes off deep inside a |
| 432 | /// request path rather than at start-up. |
| 433 | /// |
| 434 | /// So install one here if nobody has. `install_default` fails when a |
| 435 | /// provider is already installed, which is not an error -- whichever one |
| 436 | /// the application chose is the one we want to keep. |
| 437 | pub fn ensure_crypto_provider() { |
| 438 | if tokio_rustls::rustls::crypto::CryptoProvider::get_default().is_some() { |
| 439 | return; |
| 440 | } |
| 441 | let _ = tokio_rustls::rustls::crypto::ring::default_provider() |
| 442 | .install_default(); |
| 443 | } |
| 444 | |
| 445 | /// Where the host keeps its CA bundle. The list varies by distribution and container, so it is |
| 446 | /// config; the first path that exists is read. |
| 447 | #[derive(Clone, Debug, Eq, PartialEq, FromDatMap, ToDatMap)] |
| 448 | pub struct TrustConfig { |
| 449 | #[optional] |
| 450 | pub ca_bundle_paths: Vec<String>, |
| 451 | } |
| 452 | |
| 453 | impl Default for TrustConfig { |
| 454 | fn default() -> Self { |
| 455 | Self { |
| 456 | ca_bundle_paths: vec![ |
| 457 | fmt!("/etc/ssl/certs/ca-certificates.crt"), // Debian/Ubuntu |
| 458 | fmt!("/etc/pki/tls/certs/ca-bundle.crt"), // Fedora/RHEL |
| 459 | fmt!("/etc/ssl/cert.pem"), // Alpine/macOS |
| 460 | ], |
| 461 | } |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | /// The roots a client trusts, gathered before the `ClientConfig` is built, so a caller can add a |
| 466 | /// private CA to what the operating system trusts rather than build the store itself. |
| 467 | #[derive(Clone, Debug)] |
| 468 | pub struct ClientRoots { |
| 469 | store: RootCertStore, |
| 470 | } |
| 471 | |
| 472 | impl ClientRoots { |
| 473 | |
| 474 | pub fn empty() -> Self { |
| 475 | Self { store: RootCertStore::empty() } |
| 476 | } |
| 477 | |
| 478 | /// What the operating system trusts, read as OpenSSL reads it: see [`Self::openssl`] for |
| 479 | /// `SSL_CERT_FILE` and `SSL_CERT_DIR`, the bundle searched for along `trust.ca_bundle_paths`. |
| 480 | pub fn system(trust: &TrustConfig) -> Outcome<Self> { |
| 481 | Self::openssl(trust, std::env::var_os("SSL_CERT_FILE"), std::env::var_os("SSL_CERT_DIR")) |
| 482 | } |
| 483 | |
| 484 | /// The roots OpenSSL would trust given these two environment values. `file` replaces the |
| 485 | /// system bundle (the first of `trust.ca_bundle_paths` that exists), and a file it names |
| 486 | /// that cannot be read is an error, not an empty trust. `dir` is a colon-separated list of directories whose every file is read for certificates, |
| 487 | /// a file holding none and a directory that does not exist passed over, as OpenSSL passes |
| 488 | /// over a hashed name it does not find. An empty value is an unset one. No usable root at |
| 489 | /// all is an error. |
| 490 | pub fn openssl( |
| 491 | trust: &TrustConfig, |
| 492 | file: Option<OsString>, |
| 493 | dir: Option<OsString>, |
| 494 | ) |
| 495 | -> Outcome<Self> |
| 496 | { |
| 497 | let mut roots = Self::empty(); |
| 498 | match file.filter(|f| !f.is_empty()) { |
| 499 | Some(f) => { res!(roots.add_pem_file(PathBuf::from(f))); }, |
| 500 | None => { |
| 501 | let paths = &trust.ca_bundle_paths; |
| 502 | let bundle = match paths.iter().find(|p| Path::new(p).exists()) { |
| 503 | Some(p) => p, |
| 504 | None => return Err(err!( |
| 505 | "No system CA bundle found. Tried: {:?}", paths; |
| 506 | Init, Missing, File)), |
| 507 | }; |
| 508 | res!(roots.add_pem_file(bundle)); |
| 509 | }, |
| 510 | } |
| 511 | if let Some(d) = dir.filter(|d| !d.is_empty()) { |
| 512 | for one in std::env::split_paths(&d) { |
| 513 | if one.is_dir() { |
| 514 | res!(roots.add_pem_dir(&one)); |
| 515 | } |
| 516 | } |
| 517 | } |
| 518 | if roots.len() == 0 { |
| 519 | return Err(err!("No usable root certificate was found."; Init, Missing, File)); |
| 520 | } |
| 521 | Ok(roots) |
| 522 | } |
| 523 | |
| 524 | /// Adds every certificate in a PEM text, returning how many. None usable is an error, because |
| 525 | /// a caller handing over a CA means it to be trusted. |
| 526 | pub fn add_pem(&mut self, pem: &[u8]) -> Outcome<usize> { |
| 527 | let n = self.add_pem_quietly(pem); |
| 528 | if n == 0 { |
| 529 | return Err(err!("The PEM text held no usable certificate."; Invalid, Input)); |
| 530 | } |
| 531 | Ok(n) |
| 532 | } |
| 533 | |
| 534 | fn add_pem_quietly(&mut self, pem: &[u8]) -> usize { |
| 535 | let mut n = 0usize; |
| 536 | for der in parse_pem_certificates(pem) { |
| 537 | if self.store.add(CertificateDer::from(der)).is_ok() { |
| 538 | n += 1; |
| 539 | } |
| 540 | } |
| 541 | n |
| 542 | } |
| 543 | |
| 544 | pub fn add_pem_file<P: AsRef<Path>>(&mut self, path: P) -> Outcome<usize> { |
| 545 | let path = path.as_ref(); |
| 546 | let pem = res!(std::fs::read(path).map_err(|e| err!(e, |
| 547 | "Reading CA certificates from '{}'.", path.display(); IO, File, Read))); |
| 548 | match self.add_pem(&pem) { |
| 549 | Ok(n) => Ok(n), |
| 550 | Err(e) => Err(err!(e, |
| 551 | "'{}' held no usable certificate.", path.display(); Init, Invalid, File)), |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | /// Every regular file in `dir`, a file holding no certificate passed over. |
| 556 | pub fn add_pem_dir<P: AsRef<Path>>(&mut self, dir: P) -> Outcome<usize> { |
| 557 | let dir = dir.as_ref(); |
| 558 | let entries = res!(std::fs::read_dir(dir).map_err(|e| err!(e, |
| 559 | "Reading the CA directory '{}'.", dir.display(); IO, File, Read))); |
| 560 | let mut n = 0usize; |
| 561 | for entry in entries { |
| 562 | let path = res!(entry.map_err(|e| err!(e, |
| 563 | "Reading the CA directory '{}'.", dir.display(); IO, File, Read))).path(); |
| 564 | if !path.is_file() { |
| 565 | continue; |
| 566 | } |
| 567 | if let Ok(pem) = std::fs::read(&path) { |
| 568 | n += self.add_pem_quietly(&pem); |
| 569 | } |
| 570 | } |
| 571 | Ok(n) |
| 572 | } |
| 573 | |
| 574 | pub fn len(&self) -> usize { |
| 575 | self.store.len() |
| 576 | } |
| 577 | |
| 578 | pub fn client_config(self) -> ClientConfig { |
| 579 | ensure_crypto_provider(); |
| 580 | ClientConfig::builder() |
| 581 | .with_root_certificates(self.store) |
| 582 | .with_no_client_auth() |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | /// What the operating system trusts, as [`ClientRoots::system`] reads it with the default |
| 587 | /// [`TrustConfig`], and nothing else: the default every public-internet client wants. |
| 588 | pub fn default_client_config() -> Outcome<ClientConfig> { |
| 589 | client_config(&TrustConfig::default()) |
| 590 | } |
| 591 | |
| 592 | /// As [`default_client_config`], with the CA bundle searched for along `trust.ca_bundle_paths`. |
| 593 | pub fn client_config(trust: &TrustConfig) -> Outcome<ClientConfig> { |
| 594 | Ok(res!(ClientRoots::system(trust)).client_config()) |
| 595 | } |
| 596 | |
| 597 | /// What the operating system trusts plus every certificate in `pem`, for a server vouched for by |
| 598 | /// a private CA. |
| 599 | pub fn client_config_trusting(trust: &TrustConfig, pem: &[u8]) -> Outcome<ClientConfig> { |
| 600 | let mut roots = res!(ClientRoots::system(trust)); |
| 601 | res!(roots.add_pem(pem)); |
| 602 | Ok(roots.client_config()) |
| 603 | } |
| 604 | |
| 605 | /// A DER certificate as one PEM `CERTIFICATE` block, base64 in 64-column lines. |
| 606 | pub fn pem_certificate(der: &[u8]) -> String { |
| 607 | let b64 = base64::encode(der); |
| 608 | let mut out = String::with_capacity(b64.len() + b64.len() / 64 + 64); |
| 609 | out.push_str("-----BEGIN CERTIFICATE-----\n"); |
| 610 | for line in b64.as_bytes().chunks(64) { |
| 611 | out.push_str(&String::from_utf8_lossy(line)); |
| 612 | out.push('\n'); |
| 613 | } |
| 614 | out.push_str("-----END CERTIFICATE-----\n"); |
| 615 | out |
| 616 | } |
| 617 | |
| 618 | /// The decoded DER of every `-----BEGIN CERTIFICATE-----` block. A tiny in-tree |
| 619 | /// substitute for `rustls_pemfile::certs`, so the crate need not carry it. |
| 620 | pub fn parse_pem_certificates(pem: &[u8]) -> Vec<Vec<u8>> { |
| 621 | const BEGIN: &str = "-----BEGIN CERTIFICATE-----"; |
| 622 | const END: &str = "-----END CERTIFICATE-----"; |
| 623 | let text = String::from_utf8_lossy(pem); |
| 624 | let mut out: Vec<Vec<u8>> = Vec::new(); |
| 625 | let mut search_from = 0usize; |
| 626 | while let Some(b) = text[search_from..].find(BEGIN) { |
| 627 | let start = search_from + b + BEGIN.len(); |
| 628 | let e = match text[start..].find(END) { |
| 629 | Some(i) => i, |
| 630 | None => break, |
| 631 | }; |
| 632 | let block = &text[start..start + e]; |
| 633 | let stripped: String = block.chars().filter(|c| !c.is_whitespace()).collect(); |
| 634 | if let Ok(der) = base64::decode(&stripped) { |
| 635 | out.push(der); |
| 636 | } |
| 637 | search_from = start + e + END.len(); |
| 638 | } |
| 639 | out |
| 640 | } |
| 641 | |
| 642 | |
| 643 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 644 | // │ CERTIFICATE EXPIRY │ |
| 645 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 646 | |
| 647 | /// When the first certificate in a PEM chain expires, as Unix seconds. |
| 648 | /// |
| 649 | /// A server that renews its own certificate has to know when the one it holds |
| 650 | /// runs out. The obvious shortcut -- ask the filesystem how old the file is -- |
| 651 | /// is wrong in the one case that matters: a certificate restored from a backup, |
| 652 | /// or copied from another host, has a fresh mtime and an old expiry, and a |
| 653 | /// server trusting the mtime will serve an expired certificate and never notice. |
| 654 | /// The certificate itself is the only thing that knows. |
| 655 | /// |
| 656 | /// This walks just enough DER to reach the field. An X.509 certificate is |
| 657 | /// |
| 658 | /// ```text |
| 659 | /// Certificate ::= SEQUENCE { tbsCertificate TBSCertificate, ... } |
| 660 | /// TBSCertificate ::= SEQUENCE { |
| 661 | /// version [0] EXPLICIT Version DEFAULT v1, -- optional |
| 662 | /// serialNumber INTEGER, |
| 663 | /// signature AlgorithmIdentifier, -- SEQUENCE |
| 664 | /// issuer Name, -- SEQUENCE |
| 665 | /// validity Validity, -- SEQUENCE <- here |
| 666 | /// ... } |
| 667 | /// Validity ::= SEQUENCE { notBefore Time, notAfter Time } |
| 668 | /// ``` |
| 669 | /// |
| 670 | /// so the walk is: into the certificate, into the TBS, skip the optional |
| 671 | /// version and the serial and the two SEQUENCEs before it, and take the second |
| 672 | /// time in the validity. |
| 673 | pub fn certificate_not_after(pem: &[u8]) -> Outcome<i64> { |
| 674 | let der = match parse_pem_certificates(pem).into_iter().next() { |
| 675 | Some(d) => d, |
| 676 | None => return Err(err!( |
| 677 | "No certificate found in the PEM data."; |
| 678 | Invalid, Input, Missing)), |
| 679 | }; |
| 680 | |
| 681 | let (tbs, _) = res!(der_expect(&der, 0, TAG_SEQUENCE)); // Certificate |
| 682 | let (fields, _) = res!(der_expect(tbs, 0, TAG_SEQUENCE)); // TBSCertificate |
| 683 | |
| 684 | let mut pos = 0usize; |
| 685 | // The version is [0] EXPLICIT and only present for v2 and v3. Every |
| 686 | // certificate a public CA issues today is v3, but a v1 certificate is legal |
| 687 | // and simply omits it. |
| 688 | if fields.get(pos) == Some(&TAG_VERSION) { |
| 689 | let (_, next) = res!(der_element(fields, pos)); |
| 690 | pos = next; |
| 691 | } |
| 692 | for tag in [TAG_INTEGER, TAG_SEQUENCE, TAG_SEQUENCE] { // serial, sig alg, issuer |
| 693 | let (_, next) = res!(der_expect(fields, pos, tag)); |
| 694 | pos = next; |
| 695 | } |
| 696 | let (validity, _) = res!(der_expect(fields, pos, TAG_SEQUENCE)); |
| 697 | |
| 698 | // notBefore, then notAfter. Only the second is wanted. |
| 699 | let (_, after_nb) = res!(der_element(validity, 0)); |
| 700 | let tag = match validity.get(after_nb) { |
| 701 | Some(t) => *t, |
| 702 | None => return Err(err!( |
| 703 | "Certificate validity has a notBefore but no notAfter."; |
| 704 | Invalid, Input, Missing)), |
| 705 | }; |
| 706 | let (not_after, _) = res!(der_element(validity, after_nb)); |
| 707 | |
| 708 | parse_asn1_time(not_after, tag) |
| 709 | } |
| 710 | |
| 711 | /// Every DNS name the first certificate in a PEM chain is valid for, read from |
| 712 | /// its `subjectAltName` extension. |
| 713 | /// |
| 714 | /// A renewer needs this as much as it needs the expiry: a certificate that is |
| 715 | /// years from expiring still cannot serve a host it does not name, so adding a |
| 716 | /// virtual host must force a reissue even though nothing has aged. |
| 717 | /// |
| 718 | /// Walks the TBS to the `[3] EXPLICIT Extensions`, finds the extension whose OID |
| 719 | /// is 2.5.29.17, and collects the `[2] IMPLICIT IA5String` entries -- the |
| 720 | /// `dNSName` form of a `GeneralName`. Other forms (IP, email, URI) are skipped: |
| 721 | /// a caller asking this question is asking about names. |
| 722 | pub fn certificate_dns_names(pem: &[u8]) -> Outcome<Vec<String>> { |
| 723 | let der = match parse_pem_certificates(pem).into_iter().next() { |
| 724 | Some(d) => d, |
| 725 | None => return Err(err!( |
| 726 | "No certificate found in the PEM data."; |
| 727 | Invalid, Input, Missing)), |
| 728 | }; |
| 729 | let (tbs, _) = res!(der_expect(&der, 0, TAG_SEQUENCE)); |
| 730 | let (fields, _) = res!(der_expect(tbs, 0, TAG_SEQUENCE)); |
| 731 | |
| 732 | let mut pos = 0usize; |
| 733 | if fields.get(pos) == Some(&TAG_VERSION) { |
| 734 | let (_, next) = res!(der_element(fields, pos)); |
| 735 | pos = next; |
| 736 | } |
| 737 | // serial, signature, issuer, validity, subject, subjectPublicKeyInfo. |
| 738 | for tag in [TAG_INTEGER, TAG_SEQUENCE, TAG_SEQUENCE, TAG_SEQUENCE, |
| 739 | TAG_SEQUENCE, TAG_SEQUENCE] { |
| 740 | let (_, next) = res!(der_expect(fields, pos, tag)); |
| 741 | pos = next; |
| 742 | } |
| 743 | // The unique-id fields are legal and vanishingly rare; skip them if present. |
| 744 | for tag in [TAG_ISSUER_UID, TAG_SUBJECT_UID] { |
| 745 | if fields.get(pos) == Some(&tag) { |
| 746 | let (_, next) = res!(der_element(fields, pos)); |
| 747 | pos = next; |
| 748 | } |
| 749 | } |
| 750 | let exts = match fields.get(pos) { |
| 751 | Some(t) if *t == TAG_EXTENSIONS => { |
| 752 | let (inner, _) = res!(der_element(fields, pos)); |
| 753 | let (list, _) = res!(der_expect(inner, 0, TAG_SEQUENCE)); |
| 754 | list |
| 755 | } |
| 756 | // A v1 certificate has no extensions, and so no subject alternative |
| 757 | // names. That is not an error; it simply names nothing. |
| 758 | _ => return Ok(Vec::new()), |
| 759 | }; |
| 760 | |
| 761 | let mut at = 0usize; |
| 762 | while at < exts.len() { |
| 763 | let (ext, next) = res!(der_expect(exts, at, TAG_SEQUENCE)); |
| 764 | at = next; |
| 765 | |
| 766 | let (oid, mut p) = res!(der_expect(ext, 0, TAG_OID)); |
| 767 | if oid != OID_SUBJECT_ALT_NAME { |
| 768 | continue; |
| 769 | } |
| 770 | // `critical` is optional and defaults to false. |
| 771 | if ext.get(p) == Some(&TAG_BOOLEAN) { |
| 772 | let (_, n) = res!(der_element(ext, p)); |
| 773 | p = n; |
| 774 | } |
| 775 | let (value, _) = res!(der_expect(ext, p, TAG_OCTET_STRING)); |
| 776 | let (names, _) = res!(der_expect(value, 0, TAG_SEQUENCE)); |
| 777 | |
| 778 | let mut out = Vec::new(); |
| 779 | let mut q = 0usize; |
| 780 | while q < names.len() { |
| 781 | let tag = match names.get(q) { |
| 782 | Some(t) => *t, |
| 783 | None => break, |
| 784 | }; |
| 785 | let (bytes, n) = res!(der_element(names, q)); |
| 786 | q = n; |
| 787 | if tag == TAG_DNS_NAME { |
| 788 | out.push(String::from_utf8_lossy(bytes).into_owned()); |
| 789 | } |
| 790 | } |
| 791 | return Ok(out); |
| 792 | } |
| 793 | Ok(Vec::new()) |
| 794 | } |
| 795 | |
| 796 | /// Whether the certificate expires within `lead` seconds of now -- which is the |
| 797 | /// question a renewer is actually asking. An unparseable or unreadable |
| 798 | /// certificate is treated as expiring, because a server that cannot tell should |
| 799 | /// renew rather than gamble. |
| 800 | pub fn certificate_expires_within(pem: &[u8], lead_secs: i64) -> bool { |
| 801 | let not_after = match certificate_not_after(pem) { |
| 802 | Ok(t) => t, |
| 803 | Err(_) => return true, |
| 804 | }; |
| 805 | let now = match std::time::SystemTime::now() |
| 806 | .duration_since(std::time::UNIX_EPOCH) |
| 807 | { |
| 808 | Ok(d) => d.as_secs() as i64, |
| 809 | Err(_) => return true, |
| 810 | }; |
| 811 | not_after - now <= lead_secs |
| 812 | } |
| 813 | |
| 814 | |
| 815 | const TAG_BOOLEAN: u8 = 0x01; |
| 816 | const TAG_INTEGER: u8 = 0x02; |
| 817 | const TAG_OCTET_STRING: u8 = 0x04; |
| 818 | const TAG_OID: u8 = 0x06; |
| 819 | const TAG_SEQUENCE: u8 = 0x30; |
| 820 | const TAG_UTCTIME: u8 = 0x17; |
| 821 | const TAG_GENTIME: u8 = 0x18; |
| 822 | const TAG_VERSION: u8 = 0xa0; // `[0] EXPLICIT`, which the version carries |
| 823 | // `[1]` and `[2] IMPLICIT`, the deprecated unique identifiers. |
| 824 | const TAG_ISSUER_UID: u8 = 0x81; |
| 825 | const TAG_SUBJECT_UID: u8 = 0x82; |
| 826 | const TAG_EXTENSIONS: u8 = 0xa3; // `[3] EXPLICIT Extensions` |
| 827 | const TAG_DNS_NAME: u8 = 0x82; // `[2] IMPLICIT IA5String`, a dNSName GeneralName |
| 828 | const OID_SUBJECT_ALT_NAME: &[u8] = &[0x55, 0x1d, 0x11]; // subjectAltName, 2.5.29.17 |
| 829 | |
| 830 | /// The element's contents, and the offset just past it. Only the length |
| 831 | /// encodings a certificate actually uses are handled -- an indefinite length is |
| 832 | /// not legal in DER anyway. |
| 833 | fn der_element(buf: &[u8], pos: usize) -> Outcome<(&[u8], usize)> { |
| 834 | if pos + 2 > buf.len() { |
| 835 | return Err(err!( |
| 836 | "DER element at {} runs past the end of the buffer.", pos; |
| 837 | Invalid, Input, Decode)); |
| 838 | } |
| 839 | let first = buf[pos + 1]; |
| 840 | let (len, header) = if first < 0x80 { |
| 841 | (first as usize, 2usize) |
| 842 | } else { |
| 843 | let n = (first & 0x7f) as usize; |
| 844 | if n == 0 || n > 4 || pos + 2 + n > buf.len() { |
| 845 | return Err(err!( |
| 846 | "DER element at {} has an unsupported length encoding.", pos; |
| 847 | Invalid, Input, Decode)); |
| 848 | } |
| 849 | let mut len = 0usize; |
| 850 | for i in 0..n { |
| 851 | len = (len << 8) | buf[pos + 2 + i] as usize; |
| 852 | } |
| 853 | (len, 2 + n) |
| 854 | }; |
| 855 | let start = pos + header; |
| 856 | let end = match start.checked_add(len) { |
| 857 | Some(e) if e <= buf.len() => e, |
| 858 | _ => return Err(err!( |
| 859 | "DER element at {} claims {} bytes, past the end of the buffer.", |
| 860 | pos, len; |
| 861 | Invalid, Input, Decode)), |
| 862 | }; |
| 863 | Ok((&buf[start..end], end)) |
| 864 | } |
| 865 | |
| 866 | /// As [`der_element`], but insisting on a tag. A certificate whose shape |
| 867 | /// departs from X.509 is not one to guess about. |
| 868 | fn der_expect(buf: &[u8], pos: usize, tag: u8) -> Outcome<(&[u8], usize)> { |
| 869 | match buf.get(pos) { |
| 870 | Some(t) if *t == tag => der_element(buf, pos), |
| 871 | Some(t) => Err(err!( |
| 872 | "Expected DER tag {:#04x} at {}, found {:#04x}.", tag, pos, t; |
| 873 | Invalid, Input, Decode)), |
| 874 | None => Err(err!( |
| 875 | "Expected DER tag {:#04x} at {}, found the end of the buffer.", |
| 876 | tag, pos; |
| 877 | Invalid, Input, Decode)), |
| 878 | } |
| 879 | } |
| 880 | |
| 881 | /// Parse an ASN.1 `UTCTime` (`YYMMDDHHMMSSZ`) or `GeneralizedTime` |
| 882 | /// (`YYYYMMDDHHMMSSZ`) into Unix seconds. |
| 883 | fn parse_asn1_time(bytes: &[u8], tag: u8) -> Outcome<i64> { |
| 884 | let s = match std::str::from_utf8(bytes) { |
| 885 | Ok(s) => s.trim_end_matches('Z'), |
| 886 | Err(e) => return Err(err!(e, |
| 887 | "Certificate time is not valid UTF-8."; |
| 888 | Invalid, Input, Decode)), |
| 889 | }; |
| 890 | let num = |a: usize, b: usize| -> Outcome<i64> { |
| 891 | match s.get(a..b).and_then(|t| t.parse::<i64>().ok()) { |
| 892 | Some(n) => Ok(n), |
| 893 | None => Err(err!( |
| 894 | "Certificate time '{}' is malformed.", s; |
| 895 | Invalid, Input, Decode)), |
| 896 | } |
| 897 | }; |
| 898 | let (year, off) = match tag { |
| 899 | TAG_UTCTIME => { |
| 900 | // Two digits, so the century is inferred: RFC 5280 §4.1.2.5.1 puts |
| 901 | // 50-99 in the 1900s and 00-49 in the 2000s. |
| 902 | let yy = res!(num(0, 2)); |
| 903 | (if yy >= 50 { 1900 + yy } else { 2000 + yy }, 2usize) |
| 904 | } |
| 905 | TAG_GENTIME => (res!(num(0, 4)), 4usize), |
| 906 | other => return Err(err!( |
| 907 | "Certificate validity has tag {:#04x}, which is neither a UTCTime \ |
| 908 | nor a GeneralizedTime.", other; |
| 909 | Invalid, Input, Decode)), |
| 910 | }; |
| 911 | let month = res!(num(off, off + 2)); |
| 912 | let day = res!(num(off + 2, off + 4)); |
| 913 | let hour = res!(num(off + 4, off + 6)); |
| 914 | let min = res!(num(off + 6, off + 8)); |
| 915 | // Seconds are optional in a UTCTime, though every CA emits them. |
| 916 | let sec = if s.len() >= off + 10 { res!(num(off + 8, off + 10)) } else { 0 }; |
| 917 | |
| 918 | Ok(days_from_civil(year, month, day) * 86_400 + hour * 3_600 + min * 60 + sec) |
| 919 | } |
| 920 | |
| 921 | /// Days since the Unix epoch for a proleptic-Gregorian date. Howard Hinnant's |
| 922 | /// `days_from_civil`, which is exact and needs no table. |
| 923 | fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { |
| 924 | let y = if m <= 2 { y - 1 } else { y }; |
| 925 | let era = if y >= 0 { y } else { y - 399 } / 400; |
| 926 | let yoe = y - era * 400; // [0, 399] |
| 927 | let mp = (m + 9) % 12; // March = 0 |
| 928 | let doy = (153 * mp + 2) / 5 + d - 1; // [0, 365] |
| 929 | let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] |
| 930 | era * 146_097 + doe - 719_468 |
| 931 | } |
| 932 | |
| 933 | |
| 934 | #[cfg(test)] |
| 935 | mod upgrade_tests { |
| 936 | use super::*; |
| 937 | |
| 938 | use std::net::SocketAddr; |
| 939 | |
| 940 | use tokio::net::TcpListener; |
| 941 | use tokio_rustls::rustls::{ |
| 942 | ServerConfig, |
| 943 | pki_types::{ |
| 944 | CertificateDer, |
| 945 | PrivateKeyDer, |
| 946 | PrivatePkcs8KeyDer, |
| 947 | }, |
| 948 | }; |
| 949 | |
| 950 | /// A server whose certificate no public root vouches for. The client must call that a refused |
| 951 | /// certificate, and not a dropped connection. |
| 952 | #[tokio::test] |
| 953 | async fn test_a_refused_certificate_is_tagged_security_not_interrupted_00() -> Outcome<()> { |
| 954 | ensure_crypto_provider(); |
| 955 | let cert = res!(rcgen::generate_simple_self_signed(vec![fmt!("localhost")]) |
| 956 | .map_err(|e| err!(e, "Making a test certificate."; Test, Init))); |
| 957 | let der = res!(cert.serialize_der() |
| 958 | .map_err(|e| err!(e, "Serialising the test certificate."; Test, Encode))); |
| 959 | let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert.serialize_private_key_der())); |
| 960 | let scfg = res!(ServerConfig::builder() |
| 961 | .with_no_client_auth() |
| 962 | .with_single_cert(vec![CertificateDer::from(der)], key) |
| 963 | .map_err(|e| err!(e, "Building the test server config."; Test, Init))); |
| 964 | let acceptor = TlsAcceptor::from(Arc::new(scfg)); |
| 965 | |
| 966 | let listener = res!(TcpListener::bind("127.0.0.1:0").await |
| 967 | .map_err(|e| err!(e, "Binding the test server."; Test, IO))); |
| 968 | let addr = res!(listener.local_addr() |
| 969 | .map_err(|e| err!(e, "Reading its address."; Test, IO))); |
| 970 | tokio::spawn(async move { |
| 971 | if let Ok((sock, _)) = listener.accept().await { |
| 972 | let _ = acceptor.accept(sock).await; |
| 973 | } |
| 974 | }); |
| 975 | |
| 976 | let plain = res!(TcpStream::connect(addr).await |
| 977 | .map_err(|e| err!(e, "Dialling the test server."; Test, IO))); |
| 978 | let ccfg = Arc::new(res!(default_client_config())); |
| 979 | match upgrade(plain, "localhost", ccfg, Duration::from_secs(10)).await { |
| 980 | Ok(_) => return Err(err!("A self-signed certificate was accepted."; Test, Invalid)), |
| 981 | Err(e) => { |
| 982 | req!(true, e.tags().contains(&ErrTag::Security), |
| 983 | "a refused certificate was not tagged Security: {:?}", e.tags()); |
| 984 | req!(false, e.tags().contains(&ErrTag::Interrupted), |
| 985 | "a refused certificate read as a dropped connection: {:?}", e.tags()); |
| 986 | }, |
| 987 | } |
| 988 | Ok(()) |
| 989 | } |
| 990 | |
| 991 | // ── Trusted roots ──────────────────────────────────────────── |
| 992 | |
| 993 | const PRIVATE_HOST: &str = "mail.world.test"; |
| 994 | |
| 995 | /// A server vouched for by a private CA of its own, answering `n` handshakes. |
| 996 | async fn private_server(n: usize) -> Outcome<(SocketAddr, String)> { |
| 997 | let mint = res!(Mint::new(&[NameRule::Exact(fmt!("{}", PRIVATE_HOST))], 1)); |
| 998 | let ca = mint.ca_pem(); |
| 999 | let scfg = ServerConfig::builder() |
| 1000 | .with_no_client_auth() |
| 1001 | .with_cert_resolver(Arc::new(mint)); |
| 1002 | let acceptor = TlsAcceptor::from(Arc::new(scfg)); |
| 1003 | let listener = res!(TcpListener::bind("127.0.0.1:0").await |
| 1004 | .map_err(|e| err!(e, "Binding the test server."; Test, IO))); |
| 1005 | let addr = res!(listener.local_addr() |
| 1006 | .map_err(|e| err!(e, "Reading its address."; Test, IO))); |
| 1007 | tokio::spawn(async move { |
| 1008 | for _ in 0..n { |
| 1009 | if let Ok((sock, _)) = listener.accept().await { |
| 1010 | let _ = acceptor.accept(sock).await; |
| 1011 | } |
| 1012 | } |
| 1013 | }); |
| 1014 | Ok((addr, ca)) |
| 1015 | } |
| 1016 | |
| 1017 | async fn handshake(addr: SocketAddr, ccfg: ClientConfig) -> Outcome<ClientStream> { |
| 1018 | let plain = res!(TcpStream::connect(addr).await |
| 1019 | .map_err(|e| err!(e, "Dialling the test server."; Test, IO))); |
| 1020 | upgrade(plain, PRIVATE_HOST, Arc::new(ccfg), Duration::from_secs(10)).await |
| 1021 | } |
| 1022 | |
| 1023 | /// The system roots do not vouch for a private CA; the same roots with it added do. |
| 1024 | #[tokio::test] |
| 1025 | async fn test_a_private_root_is_trusted_only_once_added_00() -> Outcome<()> { |
| 1026 | ensure_crypto_provider(); |
| 1027 | let (addr, ca) = res!(private_server(2).await); |
| 1028 | match handshake(addr, res!(default_client_config())).await { |
| 1029 | Ok(_) => return Err(err!("A private CA was trusted unasked."; Test, Invalid)), |
| 1030 | Err(e) => req!(true, e.tags().contains(&ErrTag::Security), |
| 1031 | "the refusal was not tagged Security: {:?}", e.tags()), |
| 1032 | } |
| 1033 | let mut roots = res!(ClientRoots::system(&TrustConfig::default())); |
| 1034 | let before = roots.len(); |
| 1035 | req!(1, res!(roots.add_pem(ca.as_bytes())), "the CA was not added"); |
| 1036 | req!(before + 1, roots.len()); |
| 1037 | res!(handshake(addr, roots.client_config()).await); |
| 1038 | Ok(()) |
| 1039 | } |
| 1040 | |
| 1041 | /// As OpenSSL reads them: `SSL_CERT_FILE` replaces the bundle, and every file in each |
| 1042 | /// `SSL_CERT_DIR` directory (colon separated) is added. |
| 1043 | #[tokio::test] |
| 1044 | async fn test_ssl_cert_file_and_dir_are_honoured_as_openssl_does_00() -> Outcome<()> { |
| 1045 | ensure_crypto_provider(); |
| 1046 | let (addr, ca) = res!(private_server(1).await); |
| 1047 | let other = res!(Mint::new(&[NameRule::Exact(fmt!("other.world.test"))], 1)); |
| 1048 | let root = std::env::temp_dir().join(fmt!("fe2o3_roots_{}", std::process::id())); |
| 1049 | let dir = root.join("dir"); |
| 1050 | res!(std::fs::create_dir_all(&dir).map_err(|e| err!(e, "Making the test dir."; Test, IO))); |
| 1051 | let file = root.join("ca.pem"); |
| 1052 | res!(std::fs::write(&file, &ca).map_err(|e| err!(e, "Writing the CA."; Test, IO))); |
| 1053 | res!(std::fs::write(dir.join("other.pem"), other.ca_pem()) |
| 1054 | .map_err(|e| err!(e, "Writing the CA."; Test, IO))); |
| 1055 | res!(std::fs::write(dir.join("README"), "no certificate here") |
| 1056 | .map_err(|e| err!(e, "Writing a stray file."; Test, IO))); |
| 1057 | |
| 1058 | let only_file = res!(ClientRoots::openssl(&TrustConfig::default(), Some(file.clone().into()), None)); |
| 1059 | req!(1, only_file.len(), "SSL_CERT_FILE did not replace the bundle"); |
| 1060 | let both = res!(ClientRoots::openssl( |
| 1061 | &TrustConfig::default(), |
| 1062 | Some(file.clone().into()), |
| 1063 | Some(fmt!("{}:{}", root.join("absent").display(), dir.display()).into()), |
| 1064 | )); |
| 1065 | req!(2, both.len(), "SSL_CERT_DIR was not added to SSL_CERT_FILE"); |
| 1066 | res!(handshake(addr, both.client_config()).await); |
| 1067 | |
| 1068 | let missing = ClientRoots::openssl(&TrustConfig::default(), Some(root.join("absent.pem").into()), None); |
| 1069 | req!(true, missing.is_err(), "a missing SSL_CERT_FILE was passed over in silence"); |
| 1070 | let _ = std::fs::remove_dir_all(&root); |
| 1071 | Ok(()) |
| 1072 | } |
| 1073 | } |
| 1074 | |
| 1075 | #[cfg(test)] |
| 1076 | mod cert_tests { |
| 1077 | use super::*; |
| 1078 | |
| 1079 | /// A certificate whose expiry we choose, so the parser is checked against a |
| 1080 | /// known answer rather than against itself. |
| 1081 | fn cert_expiring(year: i32, month: u8, day: u8) -> Vec<u8> { |
| 1082 | use rcgen::{Certificate, CertificateParams}; |
| 1083 | let mut params = CertificateParams::new(vec![fmt!("example.com")]); |
| 1084 | params.not_after = rcgen::date_time_ymd(year, month, day); |
| 1085 | let cert = Certificate::from_params(params).expect("test cert"); |
| 1086 | cert.serialize_pem().expect("test cert pem").into_bytes() |
| 1087 | } |
| 1088 | |
| 1089 | #[test] |
| 1090 | fn test_not_after_is_read_from_the_certificate() { |
| 1091 | let pem = cert_expiring(2031, 3, 14); |
| 1092 | let t = certificate_not_after(&pem).expect("parse"); |
| 1093 | assert_eq!(t, 1_931_212_800, "2031-03-14T00:00:00Z, got {}", t); |
| 1094 | |
| 1095 | // A GeneralizedTime, which is what a CA must use past 2049. |
| 1096 | let pem = cert_expiring(2060, 12, 31); |
| 1097 | let t = certificate_not_after(&pem).expect("parse"); |
| 1098 | assert_eq!(t, 2_871_676_800, "2060-12-31T00:00:00Z, got {}", t); |
| 1099 | } |
| 1100 | |
| 1101 | #[test] |
| 1102 | fn test_expiry_is_the_question_a_renewer_asks() { |
| 1103 | let soon = cert_expiring(2026, 7, 20); // in the past by the time this ages |
| 1104 | let far = cert_expiring(2099, 1, 1); |
| 1105 | assert!(certificate_expires_within(&soon, 30 * 24 * 3600)); |
| 1106 | assert!(!certificate_expires_within(&far, 30 * 24 * 3600)); |
| 1107 | } |
| 1108 | |
| 1109 | #[test] |
| 1110 | fn test_dns_names_are_read_from_the_san() { |
| 1111 | use rcgen::{Certificate, CertificateParams}; |
| 1112 | let params = CertificateParams::new(vec![ |
| 1113 | fmt!("example.com"), |
| 1114 | fmt!("www.example.com"), |
| 1115 | fmt!("api.example.com"), |
| 1116 | ]); |
| 1117 | let cert = Certificate::from_params(params).expect("test cert"); |
| 1118 | let pem = cert.serialize_pem().expect("test pem").into_bytes(); |
| 1119 | |
| 1120 | let names = certificate_dns_names(&pem).expect("parse"); |
| 1121 | assert_eq!(names, vec![ |
| 1122 | fmt!("example.com"), |
| 1123 | fmt!("www.example.com"), |
| 1124 | fmt!("api.example.com"), |
| 1125 | ]); |
| 1126 | } |
| 1127 | |
| 1128 | #[test] |
| 1129 | fn test_a_certificate_that_names_one_host_does_not_name_another() { |
| 1130 | // The case that matters: a vhost is added, the certificate is nowhere |
| 1131 | // near expiry, and it still cannot serve the new name. |
| 1132 | let pem = cert_expiring(2099, 1, 1); // names example.com only |
| 1133 | let names = certificate_dns_names(&pem).expect("parse"); |
| 1134 | assert!(names.iter().any(|n| n == "example.com")); |
| 1135 | assert!(!names.iter().any(|n| n == "new.example.com")); |
| 1136 | assert!(!certificate_expires_within(&pem, 30 * 24 * 3600)); |
| 1137 | } |
| 1138 | |
| 1139 | #[test] |
| 1140 | fn test_rubbish_is_treated_as_expiring() { |
| 1141 | // A server that cannot tell must renew, not gamble. |
| 1142 | assert!(certificate_expires_within(b"not a certificate", 0)); |
| 1143 | assert!(certificate_not_after(b"not a certificate").is_err()); |
| 1144 | } |
| 1145 | |
| 1146 | #[test] |
| 1147 | fn test_days_from_civil_epoch_and_leap_years() { |
| 1148 | assert_eq!(days_from_civil(1970, 1, 1), 0); |
| 1149 | assert_eq!(days_from_civil(2000, 3, 1), 11_017); |
| 1150 | assert_eq!(days_from_civil(2026, 7, 12), 20_646); |
| 1151 | } |
| 1152 | } |