Skip to main content

universal_exports/
tls.rs

1//! The gateway on TLS of its own, without a reverse proxy in front: it asks each client for a
2//! certificate and admits one without. A certificate's key is proven in the handshake, and the
3//! chain is handed to the page routes ([`ClientCertificates`]), where the configured page
4//! authenticator (coqui-access `mtls`) decides whether it names a person. No `/v1` route reads
5//! it.
6
7use std::future::Future;
8use std::net::SocketAddr;
9use std::sync::Arc;
10
11use axum::Router;
12use axum::extract::ConnectInfo;
13use rustls::DistinguishedName;
14use rustls::client::danger::HandshakeSignatureValid;
15use rustls::crypto::{CryptoProvider, verify_tls12_signature, verify_tls13_signature};
16use rustls::pki_types::pem::PemObject;
17use rustls::pki_types::{CertificateDer, PrivateKeyDer, UnixTime};
18use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
19use rustls::{DigitallySignedStruct, ServerConfig, SignatureScheme};
20use tower::ServiceExt;
21
22use crate::Gateway;
23
24/// The certificates a client proved it holds the leaf key of, DER, leaf first; empty when it
25/// sent none.
26#[derive(Debug, Clone, Default, PartialEq, Eq)]
27pub(crate) struct ClientCertificates(pub(crate) Vec<Vec<u8>>);
28
29/// Takes any client certificate whose key the client proves, and a client with none: trust is
30/// the page authenticator's to decide, by pin or by CA.
31#[derive(Debug)]
32struct AnyClientCertificate {
33    provider: Arc<CryptoProvider>,
34}
35
36impl ClientCertVerifier for AnyClientCertificate {
37    fn offer_client_auth(&self) -> bool {
38        true
39    }
40
41    fn client_auth_mandatory(&self) -> bool {
42        false
43    }
44
45    fn root_hint_subjects(&self) -> &[DistinguishedName] {
46        &[]
47    }
48
49    fn verify_client_cert(
50        &self,
51        _end_entity: &CertificateDer<'_>,
52        _intermediates: &[CertificateDer<'_>],
53        _now: UnixTime,
54    ) -> Result<ClientCertVerified, rustls::Error> {
55        Ok(ClientCertVerified::assertion())
56    }
57
58    fn verify_tls12_signature(
59        &self,
60        message: &[u8],
61        cert: &CertificateDer<'_>,
62        dss: &DigitallySignedStruct,
63    ) -> Result<HandshakeSignatureValid, rustls::Error> {
64        verify_tls12_signature(
65            message,
66            cert,
67            dss,
68            &self.provider.signature_verification_algorithms,
69        )
70    }
71
72    fn verify_tls13_signature(
73        &self,
74        message: &[u8],
75        cert: &CertificateDer<'_>,
76        dss: &DigitallySignedStruct,
77    ) -> Result<HandshakeSignatureValid, rustls::Error> {
78        verify_tls13_signature(
79            message,
80            cert,
81            dss,
82            &self.provider.signature_verification_algorithms,
83        )
84    }
85
86    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
87        self.provider
88            .signature_verification_algorithms
89            .supported_schemes()
90    }
91}
92
93/// The TLS configuration of a gateway that presents the certificate chain and key in the PEM
94/// texts `chain` and `key`, and asks for a client certificate it does not require.
95///
96/// # Errors
97///
98/// What is wrong with the PEM or the key, in words.
99pub fn tls_server_config(chain: &[u8], key: &[u8]) -> Result<ServerConfig, String> {
100    let certificates = CertificateDer::pem_slice_iter(chain)
101        .collect::<Result<Vec<_>, _>>()
102        .map_err(|error| format!("the certificate: {error}"))?;
103    if certificates.is_empty() {
104        return Err("the certificate file holds no certificate".to_owned());
105    }
106    let key = PrivateKeyDer::from_pem_slice(key).map_err(|error| format!("the key: {error}"))?;
107    let provider = Arc::new(rustls::crypto::ring::default_provider());
108    let verifier = Arc::new(AnyClientCertificate {
109        provider: provider.clone(),
110    });
111    let mut config = ServerConfig::builder_with_provider(provider)
112        .with_safe_default_protocol_versions()
113        .map_err(|error| error.to_string())?
114        .with_client_cert_verifier(verifier)
115        .with_single_cert(certificates, key)
116        .map_err(|error| error.to_string())?;
117    config.alpn_protocols = vec![b"http/1.1".to_vec()];
118    Ok(config)
119}
120
121impl Gateway {
122    /// Serves the gateway on `listener` over TLS with `config` (see [`tls_server_config`]) until
123    /// `shutdown`: each request carries the client's address and the certificates it proved.
124    ///
125    /// # Errors
126    ///
127    /// The listener fails to accept.
128    pub async fn serve_tls<F>(
129        self,
130        listener: tokio::net::TcpListener,
131        config: Arc<ServerConfig>,
132        shutdown: F,
133    ) -> std::io::Result<()>
134    where
135        F: Future<Output = ()> + Send + 'static,
136    {
137        let assistant = self.assistant.clone();
138        let router: Router = self.router();
139        let acceptor = tokio_rustls::TlsAcceptor::from(config);
140        tokio::pin!(shutdown);
141        loop {
142            let (stream, address) = tokio::select! {
143                () = &mut shutdown => break,
144                accepted = listener.accept() => accepted?,
145            };
146            let (acceptor, router) = (acceptor.clone(), router.clone());
147            tokio::spawn(async move {
148                let Ok(stream) = acceptor.accept(stream).await else {
149                    return;
150                };
151                let certificates = ClientCertificates(
152                    stream
153                        .get_ref()
154                        .1
155                        .peer_certificates()
156                        .map(|chain| chain.iter().map(|der| der.to_vec()).collect())
157                        .unwrap_or_default(),
158                );
159                let service = router.map_request(
160                    move |mut request: axum::http::Request<hyper::body::Incoming>| {
161                        request
162                            .extensions_mut()
163                            .insert(ConnectInfo::<SocketAddr>(address));
164                        request.extensions_mut().insert(certificates.clone());
165                        // What a front door would say, and the client's own copy is replaced:
166                        // the sign-in routes take a browser's request only over HTTPS.
167                        request.headers_mut().insert(
168                            "x-forwarded-proto",
169                            axum::http::HeaderValue::from_static("https"),
170                        );
171                        request
172                    },
173                );
174                let _ = hyper::server::conn::http1::Builder::new()
175                    .serve_connection(
176                        hyper_util::rt::TokioIo::new(stream),
177                        hyper_util::service::TowerToHyperService::new(service),
178                    )
179                    .with_upgrades()
180                    .await;
181            });
182        }
183        if let Some(assistant) = assistant {
184            assistant.flush_log().await;
185        }
186        Ok(())
187    }
188}