rocket/mtls/config.rs
1use std::io;
2
3use figment::value::magic::{RelativePathBuf, Either};
4use rustls::pki_types::{CertificateDer, pem::PemObject};
5use serde::{Serialize, Deserialize};
6
7use crate::tls::{Result, Error};
8
9/// Mutual TLS configuration.
10///
11/// Configuration works in concert with the [`mtls`](crate::mtls) module, which
12/// provides a request guard to validate, verify, and retrieve client
13/// certificates in routes.
14///
15/// By default, mutual TLS is disabled and client certificates are not required,
16/// validated or verified. To enable mutual TLS, the `mtls` feature must be
17/// enabled and support configured via two `tls.mutual` parameters:
18///
19/// * `ca_certs`
20///
21/// A required path to a PEM file or raw bytes to a DER-encoded X.509 TLS
22/// certificate chain for the certificate authority to verify client
23/// certificates against. When a path is configured in a file, such as
24/// `Rocket.toml`, relative paths are interpreted as relative to the source
25/// file's directory.
26///
27/// * `mandatory`
28///
29/// An optional boolean that control whether client authentication is
30/// required.
31///
32/// When `true`, client authentication is required. TLS connections where
33/// the client does not present a certificate are immediately terminated.
34/// When `false`, the client is not required to present a certificate. In
35/// either case, if a certificate _is_ presented, it must be valid or the
36/// connection is terminated.
37///
38/// In a `Rocket.toml`, configuration might look like:
39///
40/// ```toml
41/// [default.tls.mutual]
42/// ca_certs = "/ssl/ca_cert.pem"
43/// mandatory = true # when absent, defaults to false
44/// ```
45///
46/// Programmatically, configuration might look like:
47///
48/// ```rust
49/// # #[macro_use] extern crate rocket;
50/// use rocket::mtls::MtlsConfig;
51/// use rocket::figment::providers::Serialized;
52///
53/// #[launch]
54/// fn rocket() -> _ {
55/// let mtls = MtlsConfig::from_path("/ssl/ca_cert.pem");
56/// rocket::custom(rocket::Config::figment().merge(("tls.mutual", mtls)))
57/// }
58/// ```
59///
60/// Once mTLS is configured, the [`mtls::Certificate`](crate::mtls::Certificate)
61/// request guard can be used to retrieve client certificates in routes.
62#[derive(PartialEq, Debug, Clone, Deserialize, Serialize)]
63pub struct MtlsConfig {
64 /// Path to a PEM file with, or raw bytes for, DER-encoded Certificate
65 /// Authority certificates which will be used to verify client-presented
66 /// certificates.
67 // TODO: Support more than one CA root.
68 pub(crate) ca_certs: Either<RelativePathBuf, Vec<u8>>,
69 /// Whether the client is required to present a certificate.
70 ///
71 /// When `true`, the client is required to present a valid certificate to
72 /// proceed with TLS. When `false`, the client is not required to present a
73 /// certificate. In either case, if a certificate _is_ presented, it must be
74 /// valid or the connection is terminated.
75 #[serde(default)]
76 #[serde(deserialize_with = "figment::util::bool_from_str_or_int")]
77 pub mandatory: bool,
78}
79
80impl MtlsConfig {
81 /// Constructs a `MtlsConfig` from a path to a PEM file with a certificate
82 /// authority `ca_certs` DER-encoded X.509 TLS certificate chain. This
83 /// method does no validation; it simply creates an [`MtlsConfig`] for later
84 /// use.
85 ///
86 /// These certificates will be used to verify client-presented certificates
87 /// in TLS connections.
88 ///
89 /// # Example
90 ///
91 /// ```rust
92 /// use rocket::mtls::MtlsConfig;
93 ///
94 /// let tls_config = MtlsConfig::from_path("/ssl/ca_certs.pem");
95 /// ```
96 pub fn from_path<C: AsRef<std::path::Path>>(ca_certs: C) -> Self {
97 MtlsConfig {
98 ca_certs: Either::Left(ca_certs.as_ref().to_path_buf().into()),
99 mandatory: Default::default()
100 }
101 }
102
103 /// Constructs a `MtlsConfig` from a byte buffer to a certificate authority
104 /// `ca_certs` DER-encoded X.509 TLS certificate chain. This method does no
105 /// validation; it simply creates an [`MtlsConfig`] for later use.
106 ///
107 /// These certificates will be used to verify client-presented certificates
108 /// in TLS connections.
109 ///
110 /// # Example
111 ///
112 /// ```rust
113 /// use rocket::mtls::MtlsConfig;
114 ///
115 /// # let ca_certs_buf = &[];
116 /// let mtls_config = MtlsConfig::from_bytes(ca_certs_buf);
117 /// ```
118 pub fn from_bytes(ca_certs: &[u8]) -> Self {
119 MtlsConfig {
120 ca_certs: Either::Right(ca_certs.to_vec()),
121 mandatory: Default::default()
122 }
123 }
124
125 /// Sets whether client authentication is required. Disabled by default.
126 ///
127 /// When `true`, client authentication will be required. TLS connections
128 /// where the client does not present a certificate will be immediately
129 /// terminated. When `false`, the client is not required to present a
130 /// certificate. In either case, if a certificate _is_ presented, it must be
131 /// valid or the connection is terminated.
132 ///
133 /// # Example
134 ///
135 /// ```rust
136 /// use rocket::mtls::MtlsConfig;
137 ///
138 /// # let ca_certs_buf = &[];
139 /// let mtls_config = MtlsConfig::from_bytes(ca_certs_buf).mandatory(true);
140 /// ```
141 pub fn mandatory(mut self, mandatory: bool) -> Self {
142 self.mandatory = mandatory;
143 self
144 }
145
146 /// Returns the value of the `ca_certs` parameter.
147 ///
148 /// # Example
149 ///
150 /// ```rust
151 /// use rocket::mtls::MtlsConfig;
152 ///
153 /// # let ca_certs_buf = &[];
154 /// let mtls_config = MtlsConfig::from_bytes(ca_certs_buf).mandatory(true);
155 /// assert_eq!(mtls_config.ca_certs().unwrap_right(), ca_certs_buf);
156 /// ```
157 pub fn ca_certs(&self) -> either::Either<std::path::PathBuf, &[u8]> {
158 match &self.ca_certs {
159 Either::Left(path) => either::Either::Left(path.relative()),
160 Either::Right(bytes) => either::Either::Right(bytes),
161 }
162 }
163
164 #[inline(always)]
165 pub fn ca_certs_reader(&self) -> io::Result<Box<dyn io::BufRead + Sync + Send>> {
166 crate::tls::config::to_reader(&self.ca_certs)
167 }
168
169 /// Load and decode CA certificates from `reader`.
170 pub(crate) fn load_ca_certs(&self) -> Result<rustls::RootCertStore> {
171 let mut roots = rustls::RootCertStore::empty();
172 for cert in CertificateDer::pem_reader_iter(self.ca_certs_reader()?) {
173 roots.add(cert?).map_err(Error::CertAuth)?;
174 }
175
176 Ok(roots)
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use std::path::Path;
183 use figment::{Figment, providers::{Toml, Format}};
184
185 use crate::mtls::MtlsConfig;
186
187 #[test]
188 fn test_mtls_config() {
189 figment::Jail::expect_with(|jail| {
190 jail.create_file("MTLS.toml", r#"
191 certs = "/ssl/cert.pem"
192 key = "/ssl/key.pem"
193 "#)?;
194
195 let figment = || Figment::from(Toml::file("MTLS.toml"));
196 figment().extract::<MtlsConfig>().expect_err("no ca");
197
198 jail.create_file("MTLS.toml", r#"
199 ca_certs = "/ssl/ca.pem"
200 "#)?;
201
202 let mtls: MtlsConfig = figment().extract()?;
203 assert_eq!(mtls.ca_certs().unwrap_left(), Path::new("/ssl/ca.pem"));
204 assert!(!mtls.mandatory);
205
206 jail.create_file("MTLS.toml", r#"
207 ca_certs = "/ssl/ca.pem"
208 mandatory = true
209 "#)?;
210
211 let mtls: MtlsConfig = figment().extract()?;
212 assert_eq!(mtls.ca_certs().unwrap_left(), Path::new("/ssl/ca.pem"));
213 assert!(mtls.mandatory);
214
215 jail.create_file("MTLS.toml", r#"
216 ca_certs = "relative/ca.pem"
217 "#)?;
218
219 let mtls: MtlsConfig = figment().extract()?;
220 assert_eq!(mtls.ca_certs().unwrap_left(), jail.directory().join("relative/ca.pem"));
221
222 Ok(())
223 });
224 }
225}