Skip to main content

schedr_tls/
material.rs

1//! The certificate files and the rustls configurations built from them.
2//!
3//! - **Servers** (the master's gRPC, a worker's log endpoint) present their certificate and
4//!   require a client certificate signed by the CA.
5//! - **The webserver's UI port** (`[webserver] ui_port`) requires, beyond that, a client
6//!   certificate naming `[tls] ui_name`: only `schedr ui` may pass users' names on there
7//!   (decision 36); any other certificate fails the handshake.
8//! - **Clients** present their certificate. A worker checks that the master's certificate
9//!   names the host of `[worker] master_url`; the webserver checks that a worker's names
10//!   `[tls] worker_name`, whatever address it reached the worker at (workers are reached by
11//!   pod IP or pod DNS name, which a shared certificate can't list).
12//!
13//! Only TLS 1.3, with the aws-lc-rs provider.
14
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use rustls::client::WebPkiServerVerifier;
19use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
20use rustls::crypto::CryptoProvider;
21use rustls::pki_types::pem::PemObject;
22use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
23use rustls::server::WebPkiClientVerifier;
24use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
25use rustls::{ClientConfig, DigitallySignedStruct, RootCertStore, ServerConfig, SignatureScheme};
26
27#[cfg(test)]
28mod tests;
29
30/// The ALPN protocol of gRPC.
31pub const ALPN_H2: &[u8] = b"h2";
32
33/// The ALPN protocol of the log endpoint.
34pub const ALPN_HTTP1: &[u8] = b"http/1.1";
35
36/// Where a role's certificate material is (`[tls] ca`, `cert`, `key`).
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct TlsFiles {
39    /// The CA certificates peers must be signed by (PEM, one or more).
40    pub ca: PathBuf,
41    /// This role's certificate, followed by any intermediates (PEM).
42    pub cert: PathBuf,
43    /// This role's private key (PEM: PKCS#8, PKCS#1 or SEC1).
44    pub key: PathBuf,
45}
46
47/// The files' bytes, as read (compared to notice a change).
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Contents {
50    /// The CA file.
51    pub ca: Vec<u8>,
52    /// The certificate file.
53    pub cert: Vec<u8>,
54    /// The key file.
55    pub key: Vec<u8>,
56}
57
58/// Why the material can't be used.
59#[derive(Debug, thiserror::Error)]
60pub enum TlsError {
61    /// A file can't be read.
62    #[error("can't read [tls] {key} `{}`: {source}", path.display())]
63    Read {
64        /// The configuration key naming the file.
65        key: &'static str,
66        /// The file.
67        path: PathBuf,
68        /// Why.
69        source: std::io::Error,
70    },
71    /// A file holds nothing usable.
72    #[error("[tls] {key} `{}` {reason}", path.display())]
73    Invalid {
74        /// The configuration key naming the file.
75        key: &'static str,
76        /// The file.
77        path: PathBuf,
78        /// What is wrong with it.
79        reason: String,
80    },
81    /// The certificate and the key don't go together, or rustls refuses them.
82    #[error("[tls] cert `{}` and key `{}` can't be used together: {reason}", cert.display(), key.display())]
83    Pair {
84        /// The certificate file.
85        cert: PathBuf,
86        /// The key file.
87        key: PathBuf,
88        /// Why.
89        reason: String,
90    },
91    /// `[tls] worker_name` isn't a DNS name or an IP address.
92    #[error("[tls] worker_name `{0}` isn't a DNS name or an IP address")]
93    WorkerName(String),
94    /// `[tls] ui_name` isn't a DNS name or an IP address.
95    #[error("[tls] ui_name `{0}` isn't a DNS name or an IP address")]
96    UiName(String),
97}
98
99impl TlsFiles {
100    /// Reads the three files.
101    ///
102    /// # Errors
103    ///
104    /// [`TlsError::Read`] naming the file that can't be read.
105    pub fn read(&self) -> Result<Contents, TlsError> {
106        let read = |key: &'static str, path: &Path| {
107            std::fs::read(path).map_err(|source| TlsError::Read {
108                key,
109                path: path.to_owned(),
110                source,
111            })
112        };
113        Ok(Contents {
114            ca: read("ca", &self.ca)?,
115            cert: read("cert", &self.cert)?,
116            key: read("key", &self.key)?,
117        })
118    }
119}
120
121/// The rustls configurations of a role, built from one set of files.
122#[derive(Debug, Clone)]
123pub struct Configs {
124    /// The master's gRPC server (ALPN `h2`).
125    pub grpc_server: Arc<ServerConfig>,
126    /// A worker's log endpoint (ALPN `http/1.1`).
127    pub http_server: Arc<ServerConfig>,
128    /// A worker's connection to the master (ALPN `h2`; the master's name is the URL's host).
129    pub grpc_client: Arc<ClientConfig>,
130    /// The webserver's connections to workers (ALPN `http/1.1`; the name checked is
131    /// `[tls] worker_name`).
132    pub worker_client: Arc<ClientConfig>,
133    /// The webserver's UI port (ALPN `http/1.1`; the client's certificate must name
134    /// `[tls] ui_name`).
135    pub ui_server: Arc<ServerConfig>,
136    /// `schedr ui`'s connections to webservers' UI ports (ALPN `http/1.1`; the webserver's
137    /// name is the URL's host).
138    pub api_client: Arc<ClientConfig>,
139}
140
141/// The aws-lc-rs provider every configuration uses.
142#[must_use]
143pub fn provider() -> Arc<CryptoProvider> {
144    Arc::new(rustls::crypto::aws_lc_rs::default_provider())
145}
146
147/// Builds the configurations from `contents` (read from `files`, named in errors); workers'
148/// certificates must name `worker_name`.
149///
150/// # Errors
151///
152/// [`TlsError`] when a file holds no certificate or key, the key doesn't match the
153/// certificate, or `worker_name` isn't a name.
154pub fn build(
155    contents: &Contents,
156    files: &TlsFiles,
157    (worker_name, ui_name): (&str, &str),
158) -> Result<Configs, TlsError> {
159    let worker_name = ServerName::try_from(worker_name.to_owned())
160        .map_err(|_| TlsError::WorkerName(worker_name.to_owned()))?;
161    let ui_name = ServerName::try_from(ui_name.to_owned())
162        .map_err(|_| TlsError::UiName(ui_name.to_owned()))?;
163    let roots = Arc::new(roots(&contents.ca, &files.ca)?);
164    let chain = certificates(&contents.cert, "cert", &files.cert)?;
165    let key = PrivateKeyDer::from_pem_slice(&contents.key).map_err(|e| TlsError::Invalid {
166        key: "key",
167        path: files.key.clone(),
168        reason: format!("holds no usable private key ({e})"),
169    })?;
170    let pair = |e: rustls::Error| TlsError::Pair {
171        cert: files.cert.clone(),
172        key: files.key.clone(),
173        reason: e.to_string(),
174    };
175    let provider = provider();
176    let client_verifier =
177        WebPkiClientVerifier::builder_with_provider(roots.clone(), provider.clone())
178            .build()
179            .map_err(|e| TlsError::Invalid {
180                key: "ca",
181                path: files.ca.clone(),
182                reason: e.to_string(),
183            })?;
184    let server_verifier = WebPkiServerVerifier::builder_with_provider(roots, provider.clone())
185        .build()
186        .map_err(|e| TlsError::Invalid {
187            key: "ca",
188            path: files.ca.clone(),
189            reason: e.to_string(),
190        })?;
191    let server = |alpn: &[u8], verifier: Arc<dyn ClientCertVerifier>| {
192        let mut config = ServerConfig::builder_with_provider(provider.clone())
193            .with_protocol_versions(&[&rustls::version::TLS13])
194            .map_err(pair)?
195            .with_client_cert_verifier(verifier)
196            .with_single_cert(chain.clone(), key.clone_key())
197            .map_err(pair)?;
198        config.alpn_protocols = vec![alpn.to_vec()];
199        Ok::<_, TlsError>(Arc::new(config))
200    };
201    let client = |alpn: &[u8], verifier: Arc<dyn ServerCertVerifier>| {
202        let mut config = ClientConfig::builder_with_provider(provider.clone())
203            .with_protocol_versions(&[&rustls::version::TLS13])
204            .map_err(pair)?
205            .dangerous()
206            .with_custom_certificate_verifier(verifier)
207            .with_client_auth_cert(chain.clone(), key.clone_key())
208            .map_err(pair)?;
209        config.alpn_protocols = vec![alpn.to_vec()];
210        Ok::<_, TlsError>(Arc::new(config))
211    };
212    let named = Arc::new(FixedName {
213        inner: server_verifier.clone(),
214        name: worker_name,
215    });
216    let ui_only = Arc::new(NamedClient {
217        inner: client_verifier.clone(),
218        name: ui_name,
219    });
220    Ok(Configs {
221        grpc_server: server(ALPN_H2, client_verifier.clone())?,
222        http_server: server(ALPN_HTTP1, client_verifier)?,
223        grpc_client: client(ALPN_H2, server_verifier.clone())?,
224        worker_client: client(ALPN_HTTP1, named)?,
225        ui_server: server(ALPN_HTTP1, ui_only)?,
226        api_client: client(ALPN_HTTP1, server_verifier)?,
227    })
228}
229
230fn certificates(
231    pem: &[u8],
232    key: &'static str,
233    path: &Path,
234) -> Result<Vec<CertificateDer<'static>>, TlsError> {
235    let invalid = |reason: String| TlsError::Invalid {
236        key,
237        path: path.to_owned(),
238        reason,
239    };
240    let certificates = CertificateDer::pem_slice_iter(pem)
241        .collect::<Result<Vec<_>, _>>()
242        .map_err(|e| invalid(format!("isn't PEM ({e})")))?;
243    if certificates.is_empty() {
244        return Err(invalid("holds no certificate".to_owned()));
245    }
246    Ok(certificates)
247}
248
249fn roots(pem: &[u8], path: &Path) -> Result<RootCertStore, TlsError> {
250    let mut roots = RootCertStore::empty();
251    for certificate in certificates(pem, "ca", path)? {
252        roots.add(certificate).map_err(|e| TlsError::Invalid {
253            key: "ca",
254            path: path.to_owned(),
255            reason: format!("holds a certificate that can't be a CA ({e})"),
256        })?;
257    }
258    Ok(roots)
259}
260
261/// Checks a client's certificate as the CA's verifier does, and that it names `name`.
262#[derive(Debug)]
263struct NamedClient {
264    inner: Arc<dyn ClientCertVerifier>,
265    name: ServerName<'static>,
266}
267
268impl ClientCertVerifier for NamedClient {
269    fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] {
270        self.inner.root_hint_subjects()
271    }
272
273    fn verify_client_cert(
274        &self,
275        end_entity: &CertificateDer<'_>,
276        intermediates: &[CertificateDer<'_>],
277        now: UnixTime,
278    ) -> Result<ClientCertVerified, rustls::Error> {
279        let verified = self
280            .inner
281            .verify_client_cert(end_entity, intermediates, now)?;
282        let certificate = webpki::EndEntityCert::try_from(end_entity)
283            .map_err(|e| rustls::Error::General(format!("the client's certificate: {e}")))?;
284        certificate
285            .verify_is_valid_for_subject_name(&self.name)
286            .map_err(|_| {
287                rustls::Error::InvalidCertificate(rustls::CertificateError::NotValidForName)
288            })?;
289        Ok(verified)
290    }
291
292    fn verify_tls12_signature(
293        &self,
294        message: &[u8],
295        cert: &CertificateDer<'_>,
296        dss: &DigitallySignedStruct,
297    ) -> Result<HandshakeSignatureValid, rustls::Error> {
298        self.inner.verify_tls12_signature(message, cert, dss)
299    }
300
301    fn verify_tls13_signature(
302        &self,
303        message: &[u8],
304        cert: &CertificateDer<'_>,
305        dss: &DigitallySignedStruct,
306    ) -> Result<HandshakeSignatureValid, rustls::Error> {
307        self.inner.verify_tls13_signature(message, cert, dss)
308    }
309
310    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
311        self.inner.supported_verify_schemes()
312    }
313}
314
315/// Checks a server's certificate against a fixed name instead of the one connected to.
316#[derive(Debug)]
317struct FixedName {
318    inner: Arc<WebPkiServerVerifier>,
319    name: ServerName<'static>,
320}
321
322impl ServerCertVerifier for FixedName {
323    fn verify_server_cert(
324        &self,
325        end_entity: &CertificateDer<'_>,
326        intermediates: &[CertificateDer<'_>],
327        _server_name: &ServerName<'_>,
328        ocsp_response: &[u8],
329        now: UnixTime,
330    ) -> Result<ServerCertVerified, rustls::Error> {
331        self.inner
332            .verify_server_cert(end_entity, intermediates, &self.name, ocsp_response, now)
333    }
334
335    fn verify_tls12_signature(
336        &self,
337        message: &[u8],
338        cert: &CertificateDer<'_>,
339        dss: &DigitallySignedStruct,
340    ) -> Result<HandshakeSignatureValid, rustls::Error> {
341        self.inner.verify_tls12_signature(message, cert, dss)
342    }
343
344    fn verify_tls13_signature(
345        &self,
346        message: &[u8],
347        cert: &CertificateDer<'_>,
348        dss: &DigitallySignedStruct,
349    ) -> Result<HandshakeSignatureValid, rustls::Error> {
350        self.inner.verify_tls13_signature(message, cert, dss)
351    }
352
353    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
354        self.inner.supported_verify_schemes()
355    }
356}