Skip to main content

coqui_peer_tls/
connection.rs

1//! Server configurations built for one connection each, from one listener's settings.
2
3use alloc::sync::Arc;
4use alloc::vec::Vec;
5use core::fmt;
6use core::net::SocketAddr;
7use std::sync::{Mutex, PoisonError};
8
9use rustls::client::danger::HandshakeSignatureValid;
10use rustls::pki_types::{CertificateDer, UnixTime};
11use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
12use rustls::{DigitallySignedStruct, DistinguishedName, ServerConfig, SignatureScheme};
13
14use crate::config::Base;
15use crate::error::{PeerError, Refusal};
16use crate::trust::PeerClientVerifier;
17use coqui_builder::NonDefault;
18
19/// The server configurations of one listener whose connections reach rustls without this
20/// crate's accept helpers, such as quinn, which runs the verifier on threads of its own and
21/// takes a configuration per incoming connection.
22///
23/// Built once, by [`ServerBuilder::configs`](crate::ServerBuilder::configs), from the identity, ALPN list and [`Policy`](crate::Policy)
24/// (checked then), it gives a
25/// configuration for each connection's addresses with [`for_connection`](Self::for_connection).
26/// Those configurations share one session cache and ticketer, so with
27/// [`Policy::allow_resumption`](crate::Policy::allow_resumption) a client resumes across connections; waiting entries are
28/// recorded under the connection's source, and a policy's access control list is decided from
29/// its addresses. Cloning is cheap and shares the session state.
30#[derive(Clone)]
31pub struct ServerConfigs {
32    base: Base,
33    client: Client,
34    non_defaults: Vec<NonDefault>,
35}
36
37#[derive(Clone)]
38pub(crate) enum Client {
39    Trust(Arc<PeerClientVerifier>),
40    Verifier(Arc<dyn ClientCertVerifier>),
41    None,
42}
43
44impl fmt::Debug for ServerConfigs {
45    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46        let client = match self.client {
47            Client::Trust(_) => "trust",
48            Client::Verifier(_) => "verifier",
49            Client::None => "none",
50        };
51        formatter
52            .debug_struct("ServerConfigs")
53            .field("client", &client)
54            .field("non_defaults", &self.non_defaults)
55            .finish_non_exhaustive()
56    }
57}
58
59impl ServerConfigs {
60    pub(crate) fn from_parts(base: Base, client: Client, non_defaults: Vec<NonDefault>) -> Self {
61        Self {
62            base,
63            client,
64            non_defaults,
65        }
66    }
67
68    /// Every setting of the policy that differs from the default, as the configuration builders
69    /// report it.
70    pub fn non_defaults(&self) -> &[NonDefault] {
71        &self.non_defaults
72    }
73
74    /// The configuration of one connection from `source` to `local`.
75    ///
76    /// Waiting entries are recorded under `source`; a policy's access control list is decided
77    /// from these addresses, by address when the `ClientHello` arrives and by the client
78    /// certificate's fingerprint before the trust store is consulted. The first refusal of
79    /// the handshake is kept in the returned [`ConnectionConfig`], since a host such as quinn
80    /// reports a failed server handshake only by its alert.
81    ///
82    /// # Errors
83    ///
84    /// [`PeerError::Tls`] when rustls refuses the configuration, which the checks at
85    /// construction rule out.
86    pub fn for_connection(
87        &self,
88        source: SocketAddr,
89        local: SocketAddr,
90    ) -> Result<ConnectionConfig, PeerError> {
91        let slot = Arc::new(Slot::default());
92        let verifier: Option<Arc<dyn ClientCertVerifier>> = match &self.client {
93            Client::Trust(verifier) => Some(Arc::new(verifier.for_source(source))),
94            Client::Verifier(verifier) => Some(Arc::clone(verifier)),
95            Client::None => None,
96        };
97        let config = self
98            .base
99            .config(verifier, Some((source, local)), Some(Arc::clone(&slot)))?;
100        Ok(ConnectionConfig {
101            config: Arc::new(config),
102            refused: slot,
103        })
104    }
105}
106
107/// The server configuration of one connection, and the refusal its handshake ended with.
108#[derive(Debug, Clone)]
109pub struct ConnectionConfig {
110    config: Arc<ServerConfig>,
111    refused: Arc<Slot>,
112}
113
114impl ConnectionConfig {
115    /// The configuration, to hand to the connection (for quinn,
116    /// `QuicServerConfig::try_from(config)`).
117    pub fn config(&self) -> Arc<ServerConfig> {
118        Arc::clone(&self.config)
119    }
120
121    /// Why this side refused the client, once the handshake failed on a [`Refusal`]: by
122    /// address at the `ClientHello`, or by the client verifier. `None` before, after a
123    /// success, or when the handshake failed for another reason.
124    pub fn refusal(&self) -> Option<Refusal> {
125        self.refused.get()
126    }
127}
128
129/// The first refusal of one connection's handshake.
130#[derive(Debug, Default)]
131pub(crate) struct Slot(Mutex<Option<Refusal>>);
132
133impl Slot {
134    pub(crate) fn keep(&self, refusal: Refusal) {
135        self.0
136            .lock()
137            .unwrap_or_else(PoisonError::into_inner)
138            .get_or_insert(refusal);
139    }
140
141    fn get(&self) -> Option<Refusal> {
142        *self.0.lock().unwrap_or_else(PoisonError::into_inner)
143    }
144}
145
146/// A client verifier that keeps the first [`Refusal`] its inner verifier returns.
147#[derive(Debug)]
148pub(crate) struct Keeping {
149    pub(crate) inner: Arc<dyn ClientCertVerifier>,
150    pub(crate) slot: Arc<Slot>,
151}
152
153impl Keeping {
154    fn kept<T>(&self, result: Result<T, rustls::Error>) -> Result<T, rustls::Error> {
155        if let Err(error) = &result
156            && let Some(refusal) = Refusal::from_rustls(error)
157        {
158            self.slot.keep(refusal);
159        }
160        result
161    }
162}
163
164impl ClientCertVerifier for Keeping {
165    fn offer_client_auth(&self) -> bool {
166        self.inner.offer_client_auth()
167    }
168
169    fn client_auth_mandatory(&self) -> bool {
170        self.inner.client_auth_mandatory()
171    }
172
173    fn root_hint_subjects(&self) -> &[DistinguishedName] {
174        self.inner.root_hint_subjects()
175    }
176
177    fn verify_client_cert(
178        &self,
179        certificate: &CertificateDer<'_>,
180        intermediates: &[CertificateDer<'_>],
181        now: UnixTime,
182    ) -> Result<ClientCertVerified, rustls::Error> {
183        self.kept(
184            self.inner
185                .verify_client_cert(certificate, intermediates, now),
186        )
187    }
188
189    fn verify_tls12_signature(
190        &self,
191        message: &[u8],
192        certificate: &CertificateDer<'_>,
193        signed: &DigitallySignedStruct,
194    ) -> Result<HandshakeSignatureValid, rustls::Error> {
195        self.kept(
196            self.inner
197                .verify_tls12_signature(message, certificate, signed),
198        )
199    }
200
201    fn verify_tls13_signature(
202        &self,
203        message: &[u8],
204        certificate: &CertificateDer<'_>,
205        signed: &DigitallySignedStruct,
206    ) -> Result<HandshakeSignatureValid, rustls::Error> {
207        self.kept(
208            self.inner
209                .verify_tls13_signature(message, certificate, signed),
210        )
211    }
212
213    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
214        self.inner.supported_verify_schemes()
215    }
216
217    fn requires_raw_public_keys(&self) -> bool {
218        self.inner.requires_raw_public_keys()
219    }
220}