Skip to main content

rocket/config/
tls.rs

1use figment::value::magic::{Either, RelativePathBuf};
2use serde::{Deserialize, Serialize};
3use indexmap::IndexSet;
4
5/// TLS configuration: certificate chain, key, and ciphersuites.
6///
7/// Four parameters control `tls` configuration:
8///
9///   * `certs`, `key`
10///
11///     Both `certs` and `key` can be configured as a path or as raw bytes.
12///     `certs` must be a DER-encoded X.509 TLS certificate chain, while `key`
13///     must be a DER-encoded ASN.1 key in either PKCS#8, PKCS#1, or SEC1
14///     format. When a path is configured in a file, such as `Rocket.toml`,
15///     relative paths are interpreted as relative to the source file's
16///     directory.
17///
18///   * `ciphers`
19///
20///     A list of supported [`CipherSuite`]s in server-preferred order, from
21///     most to least. It is not required and defaults to
22///     [`CipherSuite::DEFAULT_SET`], the recommended setting.
23///
24///   * `prefer_server_cipher_order`
25///
26///     A boolean that indicates whether the server should regard its own
27///     ciphersuite preferences over the client's. The default and recommended
28///     value is `false`.
29///
30/// Additionally, the `mutual` parameter controls if and how the server
31/// authenticates clients via mutual TLS. It works in concert with the
32/// [`mtls`](crate::mtls) module. See [`MutualTls`] for configuration details.
33///
34/// The certificate chain and private key must match. Malformed certificate or
35/// key data, unsupported keys, and mismatched keys cause launch to fail with a
36/// bind error.
37///
38/// In `Rocket.toml`, configuration might look like:
39///
40/// ```toml
41/// [default.tls]
42/// certs = "private/rsa_sha256_cert.pem"
43/// key = "private/rsa_sha256_key.pem"
44/// ```
45///
46/// With a custom programmatic configuration, this might look like:
47///
48/// ```rust
49/// # #[macro_use] extern crate rocket;
50/// use rocket::config::{Config, TlsConfig, CipherSuite};
51///
52/// #[launch]
53/// fn rocket() -> _ {
54///     let tls_config = TlsConfig::from_paths("/ssl/certs.pem", "/ssl/key.pem")
55///         .with_ciphers(CipherSuite::TLS_V13_SET)
56///         .with_preferred_server_cipher_order(true);
57///
58///     let config = Config {
59///         tls: Some(tls_config),
60///         ..Default::default()
61///     };
62///
63///     rocket::custom(config)
64/// }
65/// ```
66///
67/// Or by creating a custom figment:
68///
69/// ```rust
70/// use rocket::config::Config;
71///
72/// let figment = Config::figment()
73///     .merge(("tls.certs", "path/to/certs.pem"))
74///     .merge(("tls.key", vec![0; 32]));
75/// #
76/// # let config = rocket::Config::from(figment);
77/// # let tls_config = config.tls.as_ref().unwrap();
78/// # assert!(tls_config.certs().is_left());
79/// # assert!(tls_config.key().is_right());
80/// # assert_eq!(tls_config.ciphers().count(), 9);
81/// # assert!(!tls_config.prefer_server_cipher_order());
82/// ```
83#[derive(PartialEq, Debug, Clone, Deserialize, Serialize)]
84#[cfg_attr(nightly, doc(cfg(feature = "tls")))]
85pub struct TlsConfig {
86    /// Path to a PEM file with, or raw bytes for, a DER-encoded X.509 TLS
87    /// certificate chain.
88    pub(crate) certs: Either<RelativePathBuf, Vec<u8>>,
89    /// Path to a PEM file with, or raw bytes for, DER-encoded private key in
90    /// either PKCS#8 or PKCS#1 format.
91    pub(crate) key: Either<RelativePathBuf, Vec<u8>>,
92    /// List of TLS cipher suites in server-preferred order.
93    #[serde(default = "CipherSuite::default_set")]
94    pub(crate) ciphers: IndexSet<CipherSuite>,
95    /// Whether to prefer the server's cipher suite order over the client's.
96    #[serde(default)]
97    pub(crate) prefer_server_cipher_order: bool,
98    /// Configuration for mutual TLS, if any.
99    #[serde(default)]
100    #[cfg(feature = "mtls")]
101    #[cfg_attr(nightly, doc(cfg(feature = "mtls")))]
102    pub(crate) mutual: Option<MutualTls>,
103}
104
105/// Mutual TLS configuration.
106///
107/// Configuration works in concert with the [`mtls`](crate::mtls) module, which
108/// provides a request guard to validate, verify, and retrieve client
109/// certificates in routes.
110///
111/// By default, mutual TLS is disabled and client certificates are not required,
112/// validated or verified. To enable mutual TLS, the `mtls` feature must be
113/// enabled and support configured via two `tls.mutual` parameters:
114///
115///   * `ca_certs`
116///
117///     A required path to a PEM file or raw bytes to a DER-encoded X.509 TLS
118///     certificate chain for the certificate authority to verify client
119///     certificates against. When a path is configured in a file, such as
120///     `Rocket.toml`, relative paths are interpreted as relative to the source
121///     file's directory.
122///
123///   * `mandatory`
124///
125///     An optional boolean that control whether client authentication is
126///     required.
127///
128///     When `true`, client authentication is required. TLS connections where
129///     the client does not present a certificate are immediately terminated.
130///     When `false`, the client is not required to present a certificate. In
131///     either case, if a certificate _is_ presented, it must be valid or the
132///     connection is terminated.
133///
134/// At least one valid CA certificate is required, even when `mandatory` is
135/// `false`. An empty or invalid CA certificate store causes launch to fail with
136/// a bind error.
137///
138/// In a `Rocket.toml`, configuration might look like:
139///
140/// ```toml
141/// [default.tls.mutual]
142/// ca_certs = "/ssl/ca_cert.pem"
143/// mandatory = true                # when absent, defaults to false
144/// ```
145///
146/// Programmatically, configuration might look like:
147///
148/// ```rust
149/// # #[macro_use] extern crate rocket;
150/// use rocket::config::{Config, TlsConfig, MutualTls};
151///
152/// #[launch]
153/// fn rocket() -> _ {
154///     let tls_config = TlsConfig::from_paths("/ssl/certs.pem", "/ssl/key.pem")
155///         .with_mutual(MutualTls::from_path("/ssl/ca_cert.pem"));
156///
157///     let config = Config {
158///         tls: Some(tls_config),
159///         ..Default::default()
160///     };
161///
162///     rocket::custom(config)
163/// }
164/// ```
165///
166/// Once mTLS is configured, the [`mtls::Certificate`](crate::mtls::Certificate)
167/// request guard can be used to retrieve client certificates in routes.
168#[derive(PartialEq, Debug, Clone, Deserialize, Serialize)]
169#[cfg(feature = "mtls")]
170#[cfg_attr(nightly, doc(cfg(feature = "mtls")))]
171pub struct MutualTls {
172    /// Path to a PEM file with, or raw bytes for, DER-encoded Certificate
173    /// Authority certificates which will be used to verify client-presented
174    /// certificates.
175    // TODO: We should support more than one root.
176    pub(crate) ca_certs: Either<RelativePathBuf, Vec<u8>>,
177    /// Whether the client is required to present a certificate.
178    ///
179    /// When `true`, the client is required to present a valid certificate to
180    /// proceed with TLS. When `false`, the client is not required to present a
181    /// certificate. In either case, if a certificate _is_ presented, it must be
182    /// valid or the connection is terminated.
183    #[serde(default)]
184    #[serde(deserialize_with = "figment::util::bool_from_str_or_int")]
185    pub mandatory: bool,
186}
187
188/// A supported TLS cipher suite.
189#[allow(non_camel_case_types)]
190#[derive(PartialEq, Eq, Debug, Copy, Clone, Hash, Deserialize, Serialize)]
191#[cfg_attr(nightly, doc(cfg(feature = "tls")))]
192#[non_exhaustive]
193pub enum CipherSuite {
194    /// The TLS 1.3 `TLS_CHACHA20_POLY1305_SHA256` cipher suite.
195    TLS_CHACHA20_POLY1305_SHA256,
196    /// The TLS 1.3 `TLS_AES_256_GCM_SHA384` cipher suite.
197    TLS_AES_256_GCM_SHA384,
198    /// The TLS 1.3 `TLS_AES_128_GCM_SHA256` cipher suite.
199    TLS_AES_128_GCM_SHA256,
200
201    /// The TLS 1.2 `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` cipher suite.
202    TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
203    /// The TLS 1.2 `TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256` cipher suite.
204    TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
205    /// The TLS 1.2 `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` cipher suite.
206    TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
207    /// The TLS 1.2 `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` cipher suite.
208    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
209    /// The TLS 1.2 `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` cipher suite.
210    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
211    /// The TLS 1.2 `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256` cipher suite.
212    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
213}
214
215impl CipherSuite {
216    /// The default set and order of cipher suites. These are all of the
217    /// variants in [`CipherSuite`] in their declaration order.
218    pub const DEFAULT_SET: [CipherSuite; 9] = [
219        // TLS v1.3 suites...
220        CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
221        CipherSuite::TLS_AES_256_GCM_SHA384,
222        CipherSuite::TLS_AES_128_GCM_SHA256,
223
224        // TLS v1.2 suites...
225        CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
226        CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
227        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
228        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
229        CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
230        CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
231    ];
232
233    /// The default set and order of cipher suites. These are the TLS 1.3
234    /// variants in [`CipherSuite`] in their declaration order.
235    pub const TLS_V13_SET: [CipherSuite; 3] = [
236        CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
237        CipherSuite::TLS_AES_256_GCM_SHA384,
238        CipherSuite::TLS_AES_128_GCM_SHA256,
239    ];
240
241    /// The default set and order of cipher suites. These are the TLS 1.2
242    /// variants in [`CipherSuite`] in their declaration order.
243    pub const TLS_V12_SET: [CipherSuite; 6] = [
244        CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
245        CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
246        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
247        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
248        CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
249        CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
250    ];
251
252    /// Used as the `serde` default for `ciphers`.
253    fn default_set() -> IndexSet<Self> {
254        Self::DEFAULT_SET.iter().copied().collect()
255    }
256}
257
258impl TlsConfig {
259    fn default() -> Self {
260        TlsConfig {
261            certs: Either::Right(vec![]),
262            key: Either::Right(vec![]),
263            ciphers: CipherSuite::default_set(),
264            prefer_server_cipher_order: false,
265            #[cfg(feature = "mtls")]
266            mutual: None,
267        }
268    }
269
270    /// Constructs a `TlsConfig` from paths to a `certs` certificate chain
271    /// a `key` private-key. This method does no validation; it simply creates a
272    /// structure suitable for passing into a [`Config`](crate::Config).
273    ///
274    /// # Example
275    ///
276    /// ```rust
277    /// use rocket::config::TlsConfig;
278    ///
279    /// let tls_config = TlsConfig::from_paths("/ssl/certs.pem", "/ssl/key.pem");
280    /// ```
281    pub fn from_paths<C, K>(certs: C, key: K) -> Self
282        where C: AsRef<std::path::Path>, K: AsRef<std::path::Path>
283    {
284        TlsConfig {
285            certs: Either::Left(certs.as_ref().to_path_buf().into()),
286            key: Either::Left(key.as_ref().to_path_buf().into()),
287            ..TlsConfig::default()
288        }
289    }
290
291    /// Constructs a `TlsConfig` from byte buffers to a `certs`
292    /// certificate chain a `key` private-key. This method does no validation;
293    /// it simply creates a structure suitable for passing into a
294    /// [`Config`](crate::Config).
295    ///
296    /// # Example
297    ///
298    /// ```rust
299    /// use rocket::config::TlsConfig;
300    ///
301    /// # let certs_buf = &[];
302    /// # let key_buf = &[];
303    /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf);
304    /// ```
305    pub fn from_bytes(certs: &[u8], key: &[u8]) -> Self {
306        TlsConfig {
307            certs: Either::Right(certs.to_vec()),
308            key: Either::Right(key.to_vec()),
309            ..TlsConfig::default()
310        }
311    }
312
313    /// Sets the cipher suites supported by the server and their order of
314    /// preference from most to least preferred.
315    ///
316    /// If a suite appears more than once in `ciphers`, only the first suite
317    /// (and its relative order) is considered. If all cipher suites for a
318    /// version oF TLS are disabled, the respective protocol itself is disabled
319    /// entirely.
320    ///
321    /// # Example
322    ///
323    /// Disable TLS v1.2 by selecting only TLS v1.3 cipher suites:
324    ///
325    /// ```rust
326    /// use rocket::config::{TlsConfig, CipherSuite};
327    ///
328    /// # let certs_buf = &[];
329    /// # let key_buf = &[];
330    /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
331    ///     .with_ciphers(CipherSuite::TLS_V13_SET);
332    /// ```
333    ///
334    /// Enable only ChaCha20-Poly1305 based TLS v1.2 and TLS v1.3 cipher suites:
335    ///
336    /// ```rust
337    /// use rocket::config::{TlsConfig, CipherSuite};
338    ///
339    /// # let certs_buf = &[];
340    /// # let key_buf = &[];
341    /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
342    ///     .with_ciphers([
343    ///         CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
344    ///         CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
345    ///         CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
346    ///     ]);
347    /// ```
348    ///
349    /// Later duplicates are ignored.
350    ///
351    /// ```rust
352    /// use rocket::config::{TlsConfig, CipherSuite};
353    ///
354    /// # let certs_buf = &[];
355    /// # let key_buf = &[];
356    /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
357    ///     .with_ciphers([
358    ///         CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
359    ///         CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
360    ///         CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
361    ///         CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
362    ///         CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
363    ///     ]);
364    ///
365    /// let ciphers: Vec<_> = tls_config.ciphers().collect();
366    /// assert_eq!(ciphers, &[
367    ///     CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
368    ///     CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
369    ///     CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
370    /// ]);
371    /// ```
372    pub fn with_ciphers<I>(mut self, ciphers: I) -> Self
373        where I: IntoIterator<Item = CipherSuite>
374    {
375        self.ciphers = ciphers.into_iter().collect();
376        self
377    }
378
379    /// Whether to prefer the server's cipher suite order and ignore the
380    /// client's preferences (`true`) or choose the first supported ciphersuite
381    /// in the client's preference list (`false`). The default prefer's the
382    /// client's order (`false`).
383    ///
384    /// During TLS cipher suite negotiation, the client presents a set of
385    /// supported ciphers in its preferred order. From this list, the server
386    /// chooses one cipher suite. By default, the server chooses the first
387    /// cipher it supports from the list.
388    ///
389    /// By setting `prefer_server_order` to `true`, the server instead chooses
390    /// the first ciphersuite in it prefers that the client also supports,
391    /// ignoring the client's preferences.
392    ///
393    /// # Example
394    ///
395    /// ```rust
396    /// use rocket::config::{TlsConfig, CipherSuite};
397    ///
398    /// # let certs_buf = &[];
399    /// # let key_buf = &[];
400    /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
401    ///     .with_ciphers(CipherSuite::TLS_V13_SET)
402    ///     .with_preferred_server_cipher_order(true);
403    /// ```
404    pub fn with_preferred_server_cipher_order(mut self, prefer_server_order: bool) -> Self {
405        self.prefer_server_cipher_order = prefer_server_order;
406        self
407    }
408
409    /// Configures mutual TLS. See [`MutualTls`] for details.
410    ///
411    /// # Example
412    ///
413    /// ```rust
414    /// use rocket::config::{TlsConfig, MutualTls};
415    ///
416    /// # let certs = &[];
417    /// # let key = &[];
418    /// let mtls_config = MutualTls::from_path("path/to/cert.pem").mandatory(true);
419    /// let tls_config = TlsConfig::from_bytes(certs, key).with_mutual(mtls_config);
420    /// assert!(tls_config.mutual().is_some());
421    /// ```
422    #[cfg(feature = "mtls")]
423    #[cfg_attr(nightly, doc(cfg(feature = "mtls")))]
424    pub fn with_mutual(mut self, config: MutualTls) -> Self {
425        self.mutual = Some(config);
426        self
427    }
428
429    /// Returns the value of the `certs` parameter.
430    ///
431    /// # Example
432    ///
433    /// ```rust
434    /// use rocket::Config;
435    ///
436    /// let figment = Config::figment()
437    ///     .merge(("tls.certs", vec![0; 32]))
438    ///     .merge(("tls.key", "/etc/ssl/key.pem"));
439    ///
440    /// let config = rocket::Config::from(figment);
441    /// let tls_config = config.tls.as_ref().unwrap();
442    /// let cert_bytes = tls_config.certs().right().unwrap();
443    /// assert!(cert_bytes.iter().all(|&b| b == 0));
444    /// ```
445    pub fn certs(&self) -> either::Either<std::path::PathBuf, &[u8]> {
446        match &self.certs {
447            Either::Left(path) => either::Either::Left(path.relative()),
448            Either::Right(bytes) => either::Either::Right(&bytes),
449        }
450    }
451
452    /// Returns the value of the `key` parameter.
453    ///
454    /// # Example
455    ///
456    /// ```rust
457    /// use std::path::Path;
458    /// use rocket::Config;
459    ///
460    /// let figment = Config::figment()
461    ///     .merge(("tls.certs", vec![0; 32]))
462    ///     .merge(("tls.key", "/etc/ssl/key.pem"));
463    ///
464    /// let config = rocket::Config::from(figment);
465    /// let tls_config = config.tls.as_ref().unwrap();
466    /// let key_path = tls_config.key().left().unwrap();
467    /// assert_eq!(key_path, Path::new("/etc/ssl/key.pem"));
468    /// ```
469    pub fn key(&self) -> either::Either<std::path::PathBuf, &[u8]> {
470        match &self.key {
471            Either::Left(path) => either::Either::Left(path.relative()),
472            Either::Right(bytes) => either::Either::Right(&bytes),
473        }
474    }
475
476    /// Returns an iterator over the enabled cipher suites in their order of
477    /// preference from most to least preferred.
478    ///
479    /// # Example
480    ///
481    /// ```rust
482    /// use rocket::config::{TlsConfig, CipherSuite};
483    ///
484    /// # let certs_buf = &[];
485    /// # let key_buf = &[];
486    /// // The default set is CipherSuite::DEFAULT_SET.
487    /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf);
488    /// assert_eq!(tls_config.ciphers().count(), 9);
489    /// assert!(tls_config.ciphers().eq(CipherSuite::DEFAULT_SET.iter().copied()));
490    ///
491    /// // Enable only the TLS v1.3 ciphers.
492    /// let tls_v13_config = TlsConfig::from_bytes(certs_buf, key_buf)
493    ///     .with_ciphers(CipherSuite::TLS_V13_SET);
494    ///
495    /// assert_eq!(tls_v13_config.ciphers().count(), 3);
496    /// assert!(tls_v13_config.ciphers().eq(CipherSuite::TLS_V13_SET.iter().copied()));
497    /// ```
498    pub fn ciphers(&self) -> impl Iterator<Item = CipherSuite> + '_ {
499        self.ciphers.iter().copied()
500    }
501
502    /// Whether the server's cipher suite ordering is preferred or not.
503    ///
504    /// # Example
505    ///
506    /// ```rust
507    /// use rocket::config::TlsConfig;
508    ///
509    /// # let certs_buf = &[];
510    /// # let key_buf = &[];
511    /// // The default prefers the server's order.
512    /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf);
513    /// assert!(!tls_config.prefer_server_cipher_order());
514    ///
515    /// // Which can be overridden with the eponymous builder method.
516    /// let tls_config = TlsConfig::from_bytes(certs_buf, key_buf)
517    ///     .with_preferred_server_cipher_order(true);
518    ///
519    /// assert!(tls_config.prefer_server_cipher_order());
520    /// ```
521    pub fn prefer_server_cipher_order(&self) -> bool {
522        self.prefer_server_cipher_order
523    }
524
525    /// Returns the value of the `mutual` parameter.
526    ///
527    /// # Example
528    ///
529    /// ```rust
530    /// use std::path::Path;
531    /// use rocket::config::{TlsConfig, MutualTls};
532    ///
533    /// # let certs = &[];
534    /// # let key = &[];
535    /// let mtls_config = MutualTls::from_path("path/to/cert.pem").mandatory(true);
536    /// let tls_config = TlsConfig::from_bytes(certs, key).with_mutual(mtls_config);
537    ///
538    /// let mtls = tls_config.mutual().unwrap();
539    /// assert_eq!(mtls.ca_certs().unwrap_left(), Path::new("path/to/cert.pem"));
540    /// assert!(mtls.mandatory);
541    /// ```
542    #[cfg(feature = "mtls")]
543    #[cfg_attr(nightly, doc(cfg(feature = "mtls")))]
544    pub fn mutual(&self) -> Option<&MutualTls> {
545        self.mutual.as_ref()
546    }
547}
548
549#[cfg(feature = "mtls")]
550impl MutualTls {
551    /// Constructs a `MutualTls` from a path to a PEM file with a certificate
552    /// authority `ca_certs` DER-encoded X.509 TLS certificate chain. This
553    /// method does no validation; it simply creates a structure suitable for
554    /// passing into a [`TlsConfig`].
555    ///
556    /// These certificates will be used to verify client-presented certificates
557    /// in TLS connections.
558    ///
559    /// # Example
560    ///
561    /// ```rust
562    /// use rocket::config::MutualTls;
563    ///
564    /// let tls_config = MutualTls::from_path("/ssl/ca_certs.pem");
565    /// ```
566    pub fn from_path<C: AsRef<std::path::Path>>(ca_certs: C) -> Self {
567        MutualTls {
568            ca_certs: Either::Left(ca_certs.as_ref().to_path_buf().into()),
569            mandatory: Default::default()
570        }
571    }
572
573    /// Constructs a `MutualTls` from a byte buffer to a certificate authority
574    /// `ca_certs` DER-encoded X.509 TLS certificate chain. This method does no
575    /// validation; it simply creates a structure suitable for passing into a
576    /// [`TlsConfig`].
577    ///
578    /// These certificates will be used to verify client-presented certificates
579    /// in TLS connections.
580    ///
581    /// # Example
582    ///
583    /// ```rust
584    /// use rocket::config::MutualTls;
585    ///
586    /// # let ca_certs_buf = &[];
587    /// let mtls_config = MutualTls::from_bytes(ca_certs_buf);
588    /// ```
589    pub fn from_bytes(ca_certs: &[u8]) -> Self {
590        MutualTls {
591            ca_certs: Either::Right(ca_certs.to_vec()),
592            mandatory: Default::default()
593        }
594    }
595
596    /// Sets whether client authentication is required. Disabled by default.
597    ///
598    /// When `true`, client authentication will be required. TLS connections
599    /// where the client does not present a certificate will be immediately
600    /// terminated. When `false`, the client is not required to present a
601    /// certificate. In either case, if a certificate _is_ presented, it must be
602    /// valid or the connection is terminated.
603    ///
604    /// # Example
605    ///
606    /// ```rust
607    /// use rocket::config::MutualTls;
608    ///
609    /// # let ca_certs_buf = &[];
610    /// let mtls_config = MutualTls::from_bytes(ca_certs_buf).mandatory(true);
611    /// ```
612    pub fn mandatory(mut self, mandatory: bool) -> Self {
613        self.mandatory = mandatory;
614        self
615    }
616
617    /// Returns the value of the `ca_certs` parameter.
618    /// # Example
619    ///
620    /// ```rust
621    /// use rocket::config::MutualTls;
622    ///
623    /// # let ca_certs_buf = &[];
624    /// let mtls_config = MutualTls::from_bytes(ca_certs_buf).mandatory(true);
625    /// assert_eq!(mtls_config.ca_certs().unwrap_right(), ca_certs_buf);
626    /// ```
627    pub fn ca_certs(&self) -> either::Either<std::path::PathBuf, &[u8]> {
628        match &self.ca_certs {
629            Either::Left(path) => either::Either::Left(path.relative()),
630            Either::Right(bytes) => either::Either::Right(&bytes),
631        }
632    }
633}
634
635#[cfg(feature = "tls")]
636mod with_tls_feature {
637    use std::fs;
638    use std::io::{self, Error};
639
640    use crate::http::tls::Config;
641    use crate::http::tls::rustls::SupportedCipherSuite as RustlsCipher;
642    use crate::http::tls::rustls::crypto::ring::cipher_suite;
643
644    use yansi::Paint;
645
646    use super::{Either, RelativePathBuf, TlsConfig, CipherSuite};
647
648    type Reader = Box<dyn std::io::BufRead + Sync + Send>;
649
650    fn to_reader(value: &Either<RelativePathBuf, Vec<u8>>) -> io::Result<Reader> {
651        match value {
652            Either::Left(path) => {
653                let path = path.relative();
654                let file = fs::File::open(&path).map_err(move |e| {
655                    let source = figment::Source::File(path);
656                    let msg = format!("error reading TLS file `{}`: {}", source.primary(), e);
657                    Error::new(e.kind(), msg)
658                })?;
659
660                Ok(Box::new(io::BufReader::new(file)))
661            }
662            Either::Right(vec) => Ok(Box::new(io::Cursor::new(vec.clone()))),
663        }
664    }
665
666    impl TlsConfig {
667        /// This is only called when TLS is enabled.
668        pub(crate) fn to_native_config(&self) -> io::Result<Config<Reader>> {
669            Ok(Config {
670                cert_chain: to_reader(&self.certs)?,
671                private_key: to_reader(&self.key)?,
672                ciphersuites: self.rustls_ciphers().collect(),
673                prefer_server_order: self.prefer_server_cipher_order,
674                http2: cfg!(feature = "http2"),
675                #[cfg(not(feature = "mtls"))]
676                mandatory_mtls: false,
677                #[cfg(not(feature = "mtls"))]
678                ca_certs: None,
679                #[cfg(feature = "mtls")]
680                mandatory_mtls: self.mutual.as_ref().map_or(false, |m| m.mandatory),
681                #[cfg(feature = "mtls")]
682                ca_certs: match self.mutual {
683                    Some(ref mtls) => Some(to_reader(&mtls.ca_certs)?),
684                    None => None
685                },
686            })
687        }
688
689        fn rustls_ciphers(&self) -> impl Iterator<Item = RustlsCipher> + '_ {
690            self.ciphers().map(|ciphersuite| match ciphersuite {
691                CipherSuite::TLS_CHACHA20_POLY1305_SHA256 =>
692                    cipher_suite::TLS13_CHACHA20_POLY1305_SHA256,
693                CipherSuite::TLS_AES_256_GCM_SHA384 =>
694                    cipher_suite::TLS13_AES_256_GCM_SHA384,
695                CipherSuite::TLS_AES_128_GCM_SHA256 =>
696                    cipher_suite::TLS13_AES_128_GCM_SHA256,
697                CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 =>
698                    cipher_suite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
699                CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 =>
700                    cipher_suite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
701                CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 =>
702                    cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
703                CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 =>
704                    cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
705                CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 =>
706                    cipher_suite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
707                CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 =>
708                    cipher_suite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
709            })
710        }
711    }
712}