rocket/tls/config.rs
1use std::io;
2use std::sync::Arc;
3
4use futures::TryFutureExt;
5use figment::value::magic::{Either, RelativePathBuf};
6use serde::{Deserialize, Serialize};
7use indexmap::IndexSet;
8use rustls::crypto::{ring, CryptoProvider};
9use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::{PemObject, SectionKind}};
10use rustls::server::{ServerSessionMemoryCache, ServerConfig, WebPkiClientVerifier};
11
12use crate::tls::resolver::DynResolver;
13use crate::tls::error::{Result, Error, KeyError};
14
15/// TLS configuration: certificate chain, key, and ciphersuites.
16///
17/// Four parameters control `tls` configuration:
18///
19/// * `certs`, `key`
20///
21/// Both `certs` and `key` can be configured as a path or as raw bytes.
22/// `certs` must be a DER-encoded X.509 TLS certificate chain, while `key`
23/// must be a DER-encoded ASN.1 key in either PKCS#8, PKCS#1, or SEC1
24/// format. When a path is configured in a file, such as `Rocket.toml`,
25/// relative paths are interpreted as relative to the source file's
26/// directory.
27///
28/// * `ciphers`
29///
30/// A list of supported [`CipherSuite`]s in server-preferred order, from
31/// most to least. It is not required and defaults to
32/// [`CipherSuite::DEFAULT_SET`], the recommended setting.
33///
34/// If the application installs a process-wide default
35/// [`CryptoProvider`], Rocket uses that provider as installed and does not
36/// apply `ciphers`. Clients negotiate from the provider's cipher suites,
37/// and `prefer_server_cipher_order` applies to the provider's order. An
38/// application that wants the configured suites to apply reads them with
39/// [`TlsConfig::ciphers()`] and builds its provider from them.
40///
41/// * `prefer_server_cipher_order`
42///
43/// A boolean that indicates whether the server should regard its own
44/// ciphersuite preferences over the client's. The default and recommended
45/// value is `false`.
46///
47/// Additionally, the `mutual` parameter controls if and how the server
48/// authenticates clients via mutual TLS. It works in concert with the
49/// [`mtls`](crate::mtls) module. See [`MtlsConfig`](crate::mtls::MtlsConfig)
50/// for configuration details.
51///
52/// In `Rocket.toml`, configuration might look like:
53///
54/// ```toml
55/// [default.tls]
56/// certs = "private/rsa_sha256_cert.pem"
57/// key = "private/rsa_sha256_key.pem"
58/// ```
59///
60/// With a custom programmatic configuration, this might look like:
61///
62/// ```rust
63/// # #[macro_use] extern crate rocket;
64/// use rocket::tls::{TlsConfig, CipherSuite};
65/// use rocket::figment::providers::Serialized;
66///
67/// #[launch]
68/// fn rocket() -> _ {
69/// let tls = TlsConfig::from_paths("/ssl/certs.pem", "/ssl/key.pem")
70/// .with_ciphers(CipherSuite::TLS_V13_SET)
71/// .with_preferred_server_cipher_order(true);
72///
73/// rocket::custom(rocket::Config::figment().merge(("tls", tls)))
74/// }
75/// ```
76///
77/// Or by creating a custom figment:
78///
79/// ```rust
80/// use rocket::figment::Figment;
81/// use rocket::tls::TlsConfig;
82///
83/// let figment = Figment::new()
84/// .merge(("certs", "path/to/certs.pem"))
85/// .merge(("key", vec![0; 32]));
86/// #
87/// # let tls_config: TlsConfig = figment.extract().unwrap();
88/// # assert!(tls_config.certs().is_left());
89/// # assert!(tls_config.key().is_right());
90/// # assert_eq!(tls_config.ciphers().count(), 9);
91/// # assert!(!tls_config.prefer_server_cipher_order());
92/// ```
93///
94/// [`CryptoProvider`]: https://docs.rs/rustls/0.23/rustls/crypto/struct.CryptoProvider.html
95#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
96pub struct TlsConfig {
97 /// Path to a PEM file with, or raw bytes for, a DER-encoded X.509 TLS
98 /// certificate chain.
99 pub(crate) certs: Either<RelativePathBuf, Vec<u8>>,
100 /// Path to a PEM file with, or raw bytes for, DER-encoded private key in
101 /// either PKCS#8 or PKCS#1 format.
102 pub(crate) key: Either<RelativePathBuf, Vec<u8>>,
103 /// List of TLS cipher suites in server-preferred order.
104 #[serde(default = "CipherSuite::default_set")]
105 pub(crate) ciphers: IndexSet<CipherSuite>,
106 /// Whether to prefer the server's cipher suite order over the client's.
107 #[serde(default)]
108 pub(crate) prefer_server_cipher_order: bool,
109 /// Configuration for mutual TLS, if any.
110 #[serde(default)]
111 #[cfg(feature = "mtls")]
112 #[cfg_attr(nightly, doc(cfg(feature = "mtls")))]
113 pub(crate) mutual: Option<crate::mtls::MtlsConfig>,
114 #[serde(skip)]
115 pub(crate) resolver: Option<DynResolver>,
116}
117
118/// A supported TLS cipher suite.
119///
120/// See [`TlsConfig`] for when the configured cipher suites apply.
121#[allow(non_camel_case_types)]
122#[derive(PartialEq, Eq, Debug, Copy, Clone, Hash, Deserialize, Serialize)]
123#[non_exhaustive]
124pub enum CipherSuite {
125 /// The TLS 1.3 `TLS_CHACHA20_POLY1305_SHA256` cipher suite.
126 TLS_CHACHA20_POLY1305_SHA256,
127 /// The TLS 1.3 `TLS_AES_256_GCM_SHA384` cipher suite.
128 TLS_AES_256_GCM_SHA384,
129 /// The TLS 1.3 `TLS_AES_128_GCM_SHA256` cipher suite.
130 TLS_AES_128_GCM_SHA256,
131
132 /// The TLS 1.2 `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` cipher suite.
133 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
134 /// The TLS 1.2 `TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256` cipher suite.
135 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
136 /// The TLS 1.2 `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` cipher suite.
137 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
138 /// The TLS 1.2 `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` cipher suite.
139 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
140 /// The TLS 1.2 `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` cipher suite.
141 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
142 /// The TLS 1.2 `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256` cipher suite.
143 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
144}
145
146impl Default for TlsConfig {
147 fn default() -> Self {
148 TlsConfig {
149 certs: Either::Right(vec![]),
150 key: Either::Right(vec![]),
151 ciphers: CipherSuite::default_set(),
152 prefer_server_cipher_order: false,
153 #[cfg(feature = "mtls")]
154 mutual: None,
155 resolver: None,
156 }
157 }
158}
159
160impl TlsConfig {
161 /// Constructs a `TlsConfig` from paths to a `certs` certificate chain
162 /// a `key` private-key. This method does no validation; it simply creates a
163 /// structure suitable for passing into a [`Config`](crate::Config).
164 ///
165 /// # Example
166 ///
167 /// ```rust
168 /// use rocket::tls::TlsConfig;
169 ///
170 /// let tls_config = TlsConfig::from_paths("/ssl/certs.pem", "/ssl/key.pem");
171 /// ```
172 pub fn from_paths<C, K>(certs: C, key: K) -> Self
173 where C: AsRef<std::path::Path>, K: AsRef<std::path::Path>,
174 {
175 TlsConfig {
176 certs: Either::Left(certs.as_ref().to_path_buf().into()),
177 key: Either::Left(key.as_ref().to_path_buf().into()),
178 ..TlsConfig::default()
179 }
180 }
181
182 /// Constructs a `TlsConfig` from byte buffers to a `certs`
183 /// certificate chain a `key` private-key. This method does no validation;
184 /// it simply creates a structure suitable for passing into a
185 /// [`Config`](crate::Config).
186 ///
187 /// # Example
188 ///
189 /// ```rust
190 /// use rocket::tls::TlsConfig;
191 ///
192 /// # let certs_buf = &[];
193 /// # let key_buf = &[];
194 /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf);
195 /// ```
196 pub fn from_bytes(certs: &[u8], key: &[u8]) -> Self {
197 TlsConfig {
198 certs: Either::Right(certs.to_vec()),
199 key: Either::Right(key.to_vec()),
200 ..TlsConfig::default()
201 }
202 }
203
204 /// Sets the cipher suites supported by the server and their order of
205 /// preference from most to least preferred.
206 ///
207 /// If a suite appears more than once in `ciphers`, only the first suite
208 /// (and its relative order) is considered. If all cipher suites for a
209 /// version oF TLS are disabled, the respective protocol itself is disabled
210 /// entirely. See [`TlsConfig`] for when the configured cipher suites apply.
211 ///
212 /// # Example
213 ///
214 /// Disable TLS v1.2 by selecting only TLS v1.3 cipher suites:
215 ///
216 /// ```rust
217 /// use rocket::tls::{TlsConfig, CipherSuite};
218 ///
219 /// # let certs_buf = &[];
220 /// # let key_buf = &[];
221 /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
222 /// .with_ciphers(CipherSuite::TLS_V13_SET);
223 /// ```
224 ///
225 /// Enable only ChaCha20-Poly1305 based TLS v1.2 and TLS v1.3 cipher suites:
226 ///
227 /// ```rust
228 /// use rocket::tls::{TlsConfig, CipherSuite};
229 ///
230 /// # let certs_buf = &[];
231 /// # let key_buf = &[];
232 /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
233 /// .with_ciphers([
234 /// CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
235 /// CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
236 /// CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
237 /// ]);
238 /// ```
239 ///
240 /// Later duplicates are ignored.
241 ///
242 /// ```rust
243 /// use rocket::tls::{TlsConfig, CipherSuite};
244 ///
245 /// # let certs_buf = &[];
246 /// # let key_buf = &[];
247 /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
248 /// .with_ciphers([
249 /// CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
250 /// CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
251 /// CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
252 /// CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
253 /// CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
254 /// ]);
255 ///
256 /// let ciphers: Vec<_> = tls_config.ciphers().collect();
257 /// assert_eq!(ciphers, &[
258 /// CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
259 /// CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
260 /// CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
261 /// ]);
262 /// ```
263 pub fn with_ciphers<C>(mut self, ciphers: C) -> Self
264 where C: IntoIterator<Item = CipherSuite>
265 {
266 self.ciphers = ciphers.into_iter().collect();
267 self
268 }
269
270 /// Whether to prefer the server's cipher suite order and ignore the
271 /// client's preferences (`true`) or choose the first supported ciphersuite
272 /// in the client's preference list (`false`). The default prefer's the
273 /// client's order (`false`).
274 ///
275 /// During TLS cipher suite negotiation, the client presents a set of
276 /// supported ciphers in its preferred order. From this list, the server
277 /// chooses one cipher suite. By default, the server chooses the first
278 /// cipher it supports from the list.
279 ///
280 /// By setting `prefer_server_order` to `true`, the server instead chooses
281 /// the first ciphersuite in it prefers that the client also supports,
282 /// ignoring the client's preferences.
283 ///
284 /// # Example
285 ///
286 /// ```rust
287 /// use rocket::tls::{TlsConfig, CipherSuite};
288 ///
289 /// # let certs_buf = &[];
290 /// # let key_buf = &[];
291 /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
292 /// .with_ciphers(CipherSuite::TLS_V13_SET)
293 /// .with_preferred_server_cipher_order(true);
294 /// ```
295 pub fn with_preferred_server_cipher_order(mut self, prefer_server_order: bool) -> Self {
296 self.prefer_server_cipher_order = prefer_server_order;
297 self
298 }
299
300 /// Set mutual TLS configuration. See
301 /// [`MtlsConfig`](crate::mtls::MtlsConfig) for details.
302 ///
303 /// # Example
304 ///
305 /// ```rust
306 /// use rocket::tls::TlsConfig;
307 /// use rocket::mtls::MtlsConfig;
308 ///
309 /// # let certs = &[];
310 /// # let key = &[];
311 /// let mtls_config = MtlsConfig::from_path("path/to/cert.pem").mandatory(true);
312 /// let tls_config = TlsConfig::from_bytes(certs, key).with_mutual(mtls_config);
313 /// assert!(tls_config.mutual().is_some());
314 /// ```
315 #[cfg(feature = "mtls")]
316 #[cfg_attr(nightly, doc(cfg(feature = "mtls")))]
317 pub fn with_mutual(mut self, config: crate::mtls::MtlsConfig) -> Self {
318 self.mutual = Some(config);
319 self
320 }
321
322 /// Returns the value of the `certs` parameter.
323 ///
324 /// # Example
325 ///
326 /// ```rust
327 /// # use std::path::Path;
328 /// use rocket::tls::TlsConfig;
329 /// use rocket::figment::Figment;
330 ///
331 /// let figment = Figment::new()
332 /// .merge(("certs", "/path/to/certs.pem"))
333 /// .merge(("key", vec![0; 32]));
334 ///
335 /// let tls_config: TlsConfig = figment.extract().unwrap();
336 /// let cert_path = tls_config.certs().left().unwrap();
337 /// assert_eq!(cert_path, Path::new("/path/to/certs.pem"));
338 /// ```
339 pub fn certs(&self) -> either::Either<std::path::PathBuf, &[u8]> {
340 match &self.certs {
341 Either::Left(path) => either::Either::Left(path.relative()),
342 Either::Right(bytes) => either::Either::Right(bytes),
343 }
344 }
345
346 pub fn certs_reader(&self) -> io::Result<Box<dyn io::BufRead + Sync + Send>> {
347 to_reader(&self.certs)
348 }
349
350 /// Returns the value of the `key` parameter.
351 ///
352 /// # Example
353 ///
354 /// ```rust
355 /// # use std::path::Path;
356 /// use rocket::tls::TlsConfig;
357 /// use rocket::figment::Figment;
358 ///
359 /// let figment = Figment::new()
360 /// .merge(("certs", vec![0; 32]))
361 /// .merge(("key", "/etc/ssl/key.pem"));
362 ///
363 /// let tls_config: TlsConfig = figment.extract().unwrap();
364 /// let key_path = tls_config.key().left().unwrap();
365 /// assert_eq!(key_path, Path::new("/etc/ssl/key.pem"));
366 /// ```
367 pub fn key(&self) -> either::Either<std::path::PathBuf, &[u8]> {
368 match &self.key {
369 Either::Left(path) => either::Either::Left(path.relative()),
370 Either::Right(bytes) => either::Either::Right(bytes),
371 }
372 }
373
374 pub fn key_reader(&self) -> io::Result<Box<dyn io::BufRead + Sync + Send>> {
375 to_reader(&self.key)
376 }
377
378 /// Returns an iterator over the configured cipher suites in their order of
379 /// preference from most to least preferred. See [`TlsConfig`] for when
380 /// they apply.
381 ///
382 /// # Example
383 ///
384 /// ```rust
385 /// use rocket::tls::{TlsConfig, CipherSuite};
386 ///
387 /// # let certs_buf = &[];
388 /// # let key_buf = &[];
389 /// // The default set is CipherSuite::DEFAULT_SET.
390 /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf);
391 /// assert_eq!(tls_config.ciphers().count(), 9);
392 /// assert!(tls_config.ciphers().eq(CipherSuite::DEFAULT_SET.iter().copied()));
393 ///
394 /// // Enable only the TLS v1.3 ciphers.
395 /// let tls_v13_config = TlsConfig::from_bytes(certs_buf, key_buf)
396 /// .with_ciphers(CipherSuite::TLS_V13_SET);
397 ///
398 /// assert_eq!(tls_v13_config.ciphers().count(), 3);
399 /// assert!(tls_v13_config.ciphers().eq(CipherSuite::TLS_V13_SET.iter().copied()));
400 /// ```
401 pub fn ciphers(&self) -> impl Iterator<Item = CipherSuite> + '_ {
402 self.ciphers.iter().copied()
403 }
404
405 /// Whether the server's cipher suite ordering is preferred or not.
406 ///
407 /// # Example
408 ///
409 /// ```rust
410 /// use rocket::tls::TlsConfig;
411 ///
412 /// # let certs_buf = &[];
413 /// # let key_buf = &[];
414 /// // The default prefers the client's order.
415 /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf);
416 /// assert!(!tls_config.prefer_server_cipher_order());
417 ///
418 /// // Which can be overridden with the eponymous builder method.
419 /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
420 /// .with_preferred_server_cipher_order(true);
421 ///
422 /// assert!(tls_config.prefer_server_cipher_order());
423 /// ```
424 pub fn prefer_server_cipher_order(&self) -> bool {
425 self.prefer_server_cipher_order
426 }
427
428 /// Returns the value of the `mutual` parameter.
429 ///
430 /// # Example
431 ///
432 /// ```rust
433 /// use std::path::Path;
434 ///
435 /// use rocket::tls::TlsConfig;
436 /// use rocket::mtls::MtlsConfig;
437 ///
438 /// # let certs = &[];
439 /// # let key = &[];
440 /// let mtls_config = MtlsConfig::from_path("path/to/cert.pem").mandatory(true);
441 /// let tls_config = TlsConfig::from_bytes(certs, key).with_mutual(mtls_config);
442 ///
443 /// let mtls = tls_config.mutual().unwrap();
444 /// assert_eq!(mtls.ca_certs().unwrap_left(), Path::new("path/to/cert.pem"));
445 /// assert!(mtls.mandatory);
446 /// ```
447 #[cfg(feature = "mtls")]
448 #[cfg_attr(nightly, doc(cfg(feature = "mtls")))]
449 pub fn mutual(&self) -> Option<&crate::mtls::MtlsConfig> {
450 self.mutual.as_ref()
451 }
452
453 /// Try to convert `self` into a [rustls] [`ServerConfig`].
454 ///
455 /// [`ServerConfig`]: rustls::server::ServerConfig
456 pub async fn server_config(&self) -> Result<rustls::server::ServerConfig> {
457 let this = self.clone();
458 tokio::task::spawn_blocking(move || this._server_config())
459 .map_err(io::Error::other)
460 .await?
461 }
462
463 /// Try to convert `self` into a [rustls] [`ServerConfig`].
464 ///
465 /// [`ServerConfig`]: rustls::server::ServerConfig
466 pub(crate) fn _server_config(&self) -> Result<rustls::server::ServerConfig> {
467 let provider = Arc::new(self.default_crypto_provider());
468
469 #[cfg(feature = "mtls")]
470 let verifier = match self.mutual {
471 Some(ref mtls) => {
472 let ca = Arc::new(mtls.load_ca_certs()?);
473 let verifier = WebPkiClientVerifier::builder_with_provider(ca, provider.clone());
474 match mtls.mandatory {
475 true => verifier.build()?,
476 false => verifier.allow_unauthenticated().build()?,
477 }
478 },
479 None => WebPkiClientVerifier::no_client_auth(),
480 };
481
482 #[cfg(not(feature = "mtls"))]
483 let verifier = WebPkiClientVerifier::no_client_auth();
484
485 let mut tls_config = ServerConfig::builder_with_provider(provider)
486 .with_safe_default_protocol_versions()?
487 .with_client_cert_verifier(verifier)
488 .with_single_cert(self.load_certs()?, self.load_key()?)?;
489
490 tls_config.ignore_client_order = self.prefer_server_cipher_order;
491 tls_config.session_storage = ServerSessionMemoryCache::new(1024);
492 tls_config.ticketer = rustls::crypto::ring::Ticketer::new()?;
493 tls_config.alpn_protocols = vec![b"http/1.1".to_vec()];
494 if cfg!(feature = "http2") {
495 tls_config.alpn_protocols.insert(0, b"h2".to_vec());
496 }
497
498 Ok(tls_config)
499 }
500
501 /// NOTE: This is a blocking function.
502 pub fn validate(&self) -> Result<()> {
503 self._server_config().map(|_| ())
504 }
505}
506
507/// Loads certificates from `reader`.
508impl TlsConfig {
509 pub(crate) fn load_certs(&self) -> Result<Vec<CertificateDer<'static>>> {
510 CertificateDer::pem_reader_iter(self.certs_reader()?)
511 .collect::<Result<_, _>>()
512 .map_err(Error::CertChain)
513 }
514
515 /// Load and decode the private key from `reader`.
516 pub(crate) fn load_key(&self) -> Result<PrivateKeyDer<'static>> {
517 let mut keys = <(SectionKind, Vec<u8>)>::pem_reader_iter(self.key_reader()?)
518 .map(|result| result.map_err(KeyError::Pem)
519 .and_then(|(kind, der)| PrivateKeyDer::from_pem(kind, der)
520 .ok_or(KeyError::BadItem(kind)))
521 )
522 .collect::<Result<Vec<PrivateKeyDer<'static>>, _>>()?;
523
524 if keys.len() != 1 {
525 return Err(KeyError::BadKeyCount(keys.len()).into());
526 }
527
528 // Ensure we can use the key.
529 let key = keys.remove(0);
530 self.default_crypto_provider()
531 .key_provider
532 .load_private_key(key.clone_key())
533 .map_err(KeyError::Unsupported)?;
534
535 Ok(key)
536 }
537
538 pub(crate) fn default_crypto_provider(&self) -> CryptoProvider {
539 CryptoProvider::get_default()
540 .map(|arc| (**arc).clone())
541 .unwrap_or_else(|| rustls::crypto::CryptoProvider {
542 cipher_suites: self.ciphers().map(|cipher| match cipher {
543 CipherSuite::TLS_CHACHA20_POLY1305_SHA256 =>
544 ring::cipher_suite::TLS13_CHACHA20_POLY1305_SHA256,
545 CipherSuite::TLS_AES_256_GCM_SHA384 =>
546 ring::cipher_suite::TLS13_AES_256_GCM_SHA384,
547 CipherSuite::TLS_AES_128_GCM_SHA256 =>
548 ring::cipher_suite::TLS13_AES_128_GCM_SHA256,
549 CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 =>
550 ring::cipher_suite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
551 CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 =>
552 ring::cipher_suite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
553 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 =>
554 ring::cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
555 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 =>
556 ring::cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
557 CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 =>
558 ring::cipher_suite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
559 CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 =>
560 ring::cipher_suite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
561 }).collect(),
562 ..ring::default_provider()
563 })
564 }
565}
566
567impl CipherSuite {
568 /// The default set and order of cipher suites. These are all of the
569 /// variants in [`CipherSuite`] in their declaration order.
570 pub const DEFAULT_SET: [CipherSuite; 9] = [
571 // TLS v1.3 suites...
572 CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
573 CipherSuite::TLS_AES_256_GCM_SHA384,
574 CipherSuite::TLS_AES_128_GCM_SHA256,
575
576 // TLS v1.2 suites...
577 CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
578 CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
579 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
580 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
581 CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
582 CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
583 ];
584
585 /// The TLS v1.3 set and order of cipher suites. These are the TLS 1.3
586 /// variants in [`CipherSuite`] in their declaration order.
587 pub const TLS_V13_SET: [CipherSuite; 3] = [
588 CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
589 CipherSuite::TLS_AES_256_GCM_SHA384,
590 CipherSuite::TLS_AES_128_GCM_SHA256,
591 ];
592
593 /// The TLS v1.2 set and order of cipher suites. These are the TLS 1.2
594 /// variants in [`CipherSuite`] in their declaration order.
595 pub const TLS_V12_SET: [CipherSuite; 6] = [
596 CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
597 CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
598 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
599 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
600 CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
601 CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
602 ];
603
604 /// Used as the `serde` default for `ciphers`.
605 fn default_set() -> IndexSet<Self> {
606 Self::DEFAULT_SET.iter().copied().collect()
607 }
608}
609
610pub(crate) fn to_reader(
611 value: &Either<RelativePathBuf, Vec<u8>>
612) -> io::Result<Box<dyn io::BufRead + Sync + Send>> {
613 match value {
614 Either::Left(path) => {
615 let path = path.relative();
616 let file = std::fs::File::open(&path)
617 .map_err(move |e| {
618 let source = figment::Source::File(path);
619 let msg = format!("error reading TLS file `{source}`: {e}");
620 io::Error::new(e.kind(), msg)
621 })?;
622
623 Ok(Box::new(io::BufReader::new(file)))
624 }
625 Either::Right(vec) => Ok(Box::new(io::Cursor::new(vec.clone()))),
626 }
627}
628
629#[cfg(test)]
630mod tests {
631 use super::*;
632 use figment::{Figment, providers::{Toml, Format}};
633
634 #[test]
635 fn test_tls_config_from_file() {
636 use crate::tls::{TlsConfig, CipherSuite};
637 use pretty_assertions::assert_eq;
638
639 figment::Jail::expect_with(|jail| {
640 jail.create_file("Rocket.toml", r#"
641 [global]
642 shutdown.ctrlc = 0
643 ident = false
644
645 [global.tls]
646 certs = "/ssl/cert.pem"
647 key = "/ssl/key.pem"
648
649 [global.limits]
650 forms = "1mib"
651 json = "10mib"
652 stream = "50kib"
653 "#)?;
654
655 let config: TlsConfig = crate::Config::figment().extract_inner("tls")?;
656 assert_eq!(config, TlsConfig::from_paths("/ssl/cert.pem", "/ssl/key.pem"));
657
658 jail.create_file("Rocket.toml", r#"
659 [global.tls]
660 certs = "cert.pem"
661 key = "key.pem"
662 "#)?;
663
664 let config: TlsConfig = crate::Config::figment().extract_inner("tls")?;
665 assert_eq!(config, TlsConfig::from_paths(
666 jail.directory().join("cert.pem"),
667 jail.directory().join("key.pem")
668 ));
669
670 jail.create_file("TLS.toml", r#"
671 certs = "cert.pem"
672 key = "key.pem"
673 prefer_server_cipher_order = true
674 ciphers = [
675 "TLS_CHACHA20_POLY1305_SHA256",
676 "TLS_AES_256_GCM_SHA384",
677 "TLS_AES_128_GCM_SHA256",
678 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
679 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
680 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
681 ]
682 "#)?;
683
684 let config: TlsConfig = Figment::from(Toml::file("TLS.toml")).extract()?;
685 let cert_path = jail.directory().join("cert.pem");
686 let key_path = jail.directory().join("key.pem");
687 assert_eq!(config, TlsConfig::from_paths(cert_path, key_path)
688 .with_preferred_server_cipher_order(true)
689 .with_ciphers([
690 CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
691 CipherSuite::TLS_AES_256_GCM_SHA384,
692 CipherSuite::TLS_AES_128_GCM_SHA256,
693 CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
694 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
695 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
696 ]));
697
698 jail.create_file("Rocket.toml", r#"
699 [global]
700 shutdown.ctrlc = 0
701 ident = false
702
703 [global.tls]
704 certs = "/ssl/cert.pem"
705 key = "/ssl/key.pem"
706
707 [global.limits]
708 forms = "1mib"
709 json = "10mib"
710 stream = "50kib"
711 "#)?;
712
713 let config: TlsConfig = crate::Config::figment().extract_inner("tls")?;
714 assert_eq!(config, TlsConfig::from_paths("/ssl/cert.pem", "/ssl/key.pem"));
715
716 jail.create_file("Rocket.toml", r#"
717 [global.tls]
718 certs = "cert.pem"
719 key = "key.pem"
720 "#)?;
721
722 let config: TlsConfig = crate::Config::figment().extract_inner("tls")?;
723 assert_eq!(config, TlsConfig::from_paths(
724 jail.directory().join("cert.pem"),
725 jail.directory().join("key.pem")
726 ));
727
728 jail.create_file("Rocket.toml", r#"
729 [global.tls]
730 certs = "cert.pem"
731 key = "key.pem"
732 prefer_server_cipher_order = true
733 ciphers = [
734 "TLS_CHACHA20_POLY1305_SHA256",
735 "TLS_AES_256_GCM_SHA384",
736 "TLS_AES_128_GCM_SHA256",
737 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
738 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
739 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
740 ]
741 "#)?;
742
743 let config: TlsConfig = crate::Config::figment().extract_inner("tls")?;
744 let cert_path = jail.directory().join("cert.pem");
745 let key_path = jail.directory().join("key.pem");
746 assert_eq!(config, TlsConfig::from_paths(cert_path, key_path)
747 .with_preferred_server_cipher_order(true)
748 .with_ciphers([
749 CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
750 CipherSuite::TLS_AES_256_GCM_SHA384,
751 CipherSuite::TLS_AES_128_GCM_SHA256,
752 CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
753 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
754 CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
755 ]));
756
757 Ok(())
758 });
759 }
760
761 macro_rules! tls_example_private_pem {
762 ($k:expr) => {
763 concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/tls/private/", $k)
764 }
765 }
766
767 #[test]
768 fn verify_load_private_keys_of_different_types() -> Result<()> {
769 let key_paths = [
770 tls_example_private_pem!("rsa_sha256_key.pem"),
771 tls_example_private_pem!("ecdsa_nistp256_sha256_key_pkcs8.pem"),
772 tls_example_private_pem!("ecdsa_nistp384_sha384_key_pkcs8.pem"),
773 tls_example_private_pem!("ed25519_key.pem"),
774 ];
775
776 for key in key_paths {
777 TlsConfig::from_paths("", key).load_key()?;
778 }
779
780 Ok(())
781 }
782
783 #[test]
784 fn private_key_files_hold_exactly_one_key() {
785 let keys: [&[u8]; 3] = [
786 include_bytes!(tls_example_private_pem!("ca_key.pem")),
787 include_bytes!(tls_example_private_pem!("ed25519_key.pem")),
788 include_bytes!(tls_example_private_pem!("ecdsa_nistp256_sha256_key_sec1.pem")),
789 ];
790
791 let load_key = |pem: &[u8]| TlsConfig::from_bytes(&[], pem).load_key();
792 let cert = include_bytes!(tls_example_private_pem!("ca_cert.pem"));
793 for (i, first) in keys.iter().enumerate() {
794 load_key(first).unwrap();
795
796 let mut pem = cert.to_vec();
797 pem.extend_from_slice(first);
798 for other in keys.iter().cycle().skip(i + 1).take(2) {
799 pem.extend_from_slice(other);
800 }
801
802 pem.extend_from_slice(cert);
803 let error = load_key(&pem).unwrap_err();
804 assert!(matches!(error, Error::PrivKey(KeyError::BadItem(SectionKind::Certificate))));
805
806 pem.extend_from_slice(first);
807 let error = load_key(&pem).unwrap_err();
808 assert!(matches!(error, Error::PrivKey(KeyError::BadItem(SectionKind::Certificate))));
809
810 let pem = [*first, *first].concat();
811 let error = load_key(&pem).unwrap_err();
812 assert!(matches!(error, Error::PrivKey(KeyError::BadKeyCount(2))));
813 }
814
815 let error = load_key(&keys.concat()).unwrap_err();
816 assert!(matches!(error, Error::PrivKey(KeyError::BadKeyCount(3))));
817 }
818
819 #[test]
820 fn private_key_errors() {
821 let key = include_bytes!(tls_example_private_pem!("ed25519_key.pem"));
822 let load_key = |pem: &[u8]| TlsConfig::from_bytes(&[], pem).load_key();
823 let malformed = b"-----BEGIN CERTIFICATE-----\n?\n-----END CERTIFICATE-----\n";
824 let mut pem = malformed.to_vec();
825 pem.extend_from_slice(key);
826 let error = load_key(&pem).unwrap_err();
827 assert!(matches!(error, Error::PrivKey(KeyError::Pem(_))));
828
829 pem.extend_from_slice(malformed);
830 let error = load_key(&pem).unwrap_err();
831 assert!(matches!(error, Error::PrivKey(KeyError::Pem(_))));
832
833 let pem = b"-----BEGIN PRIVATE KEY-----\n?\n-----END PRIVATE KEY-----\n";
834 let error = load_key(pem).unwrap_err();
835 assert!(matches!(error, Error::PrivKey(KeyError::Pem(_))));
836
837 let error = load_key(malformed).unwrap_err();
838 assert!(matches!(error, Error::PrivKey(KeyError::Pem(_))));
839 }
840
841 #[test]
842 fn verify_load_certs_of_different_types() -> Result<()> {
843 let cert_paths = [
844 tls_example_private_pem!("rsa_sha256_cert.pem"),
845 tls_example_private_pem!("ecdsa_nistp256_sha256_cert.pem"),
846 tls_example_private_pem!("ecdsa_nistp384_sha384_cert.pem"),
847 tls_example_private_pem!("ed25519_cert.pem"),
848 ];
849
850 for cert in cert_paths {
851 TlsConfig::from_paths(cert, "").load_certs()?;
852 }
853
854 Ok(())
855 }
856}