Skip to main content

coqui_peer_tls/
config.rs

1use alloc::sync::Arc;
2use core::fmt;
3use core::net::SocketAddr;
4
5use rustls::client::danger::ServerCertVerifier;
6use rustls::client::{AlwaysResolvesClientRawPublicKeys, Resumption};
7use rustls::crypto::CryptoProvider;
8use rustls::server::danger::ClientCertVerifier;
9use rustls::server::{
10    AlwaysResolvesServerRawPublicKeys, NoServerSessionStorage, ProducesTickets, ResolvesServerCert,
11    StoresServerSessions,
12};
13use rustls::{ClientConfig, ServerConfig, SupportedProtocolVersion};
14
15use crate::connection::{Client, Keeping, ServerConfigs, Slot};
16use crate::error::PeerError;
17use crate::identity::Identity;
18use crate::policy::{CertificateType, Policy};
19use crate::settings::TlsSettings;
20use crate::trust::{PeerServerVerifier, Trust};
21use coqui_builder::builder::BuildError;
22use coqui_builder::{Builder, Configured};
23
24/// rustls's ring provider with its defaults. The configurations built here take the provider a
25/// [`Policy`] selects ([`Policy::crypto_provider`]); nothing in this crate installs a
26/// process-wide default.
27pub fn crypto_provider() -> Arc<CryptoProvider> {
28    Arc::new(rustls::crypto::ring::default_provider())
29}
30
31/// A built configuration and the [`Policy`] it was built under, so a host can surface the
32/// settings that differ from the default policy's with [`non_defaults`](Self::non_defaults).
33/// Nothing is printed by this crate.
34#[derive(Debug, Configured)]
35#[non_exhaustive]
36pub struct Built<T> {
37    /// The configuration.
38    pub config: T,
39    /// The policy the configuration was built under. Its settings that differ from the default
40    /// policy's are `non_defaults()`, named as [`Policy::non_defaults`] names them
41    /// (`tls_versions`); empty under the default policy.
42    #[configured]
43    pub policy: Policy,
44}
45
46/// How a server treats the client's certificate.
47///
48/// A value the [`ServerBuilder`] takes, so no default hides the choice.
49#[derive(Clone)]
50#[non_exhaustive]
51pub enum ClientAuth {
52    /// Ask for no client certificate: the server proves itself, the client does not at the TLS
53    /// layer.
54    ///
55    /// **The application must authenticate the client inside the encrypted channel** (a key
56    /// proof, a token) before trusting it. A handshake with this configuration finishes with no
57    /// peer certificate: see
58    /// [`TlsHandshake::finish_unauthenticated`](crate::TlsHandshake::finish_unauthenticated).
59    None,
60    /// Require a client certificate this trust accepts.
61    Required(Trust),
62    /// Verify clients with a verifier of the host's own (one of this crate's wrapped, for
63    /// example).
64    ///
65    /// A verifier whose client authentication is optional
66    /// (`ClientCertVerifier::client_auth_mandatory` is false) admits a client without a
67    /// certificate; under an access control list such a client is decided by address alone, as
68    /// one that proves no identity, so a rule naming a fingerprint never admits it.
69    Verifier(Arc<dyn ClientCertVerifier>),
70}
71
72impl fmt::Debug for ClientAuth {
73    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
74        match self {
75            Self::None => formatter.write_str("None"),
76            Self::Required(trust) => formatter.debug_tuple("Required").field(trust).finish(),
77            Self::Verifier(_) => formatter.write_str("Verifier(..)"),
78        }
79    }
80}
81
82/// How a client verifies the server.
83///
84/// The value [`ClientBuilder::new`] takes: a [`Trust`] converts into it, so no default hides the
85/// choice.
86#[derive(Clone)]
87#[non_exhaustive]
88pub enum ServerAuth {
89    /// Verify the server by this trust: pinned, by [`Roots`](crate::Roots) for the name dialled
90    /// ([`dial_named`](crate::dial_named)), pinned or roots, or any certificate with key proof.
91    Trust(Trust),
92    /// Verify the server with a verifier of the host's own.
93    Verifier(Arc<dyn ServerCertVerifier>),
94}
95
96impl From<Trust> for ServerAuth {
97    fn from(trust: Trust) -> Self {
98        Self::Trust(trust)
99    }
100}
101
102impl fmt::Debug for ServerAuth {
103    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            Self::Trust(trust) => formatter.debug_tuple("Trust").field(trust).finish(),
106            Self::Verifier(_) => formatter.write_str("Verifier(..)"),
107        }
108    }
109}
110
111/// What a [`ServerBuilder`] collects: the [`TlsSettings`] and the two inputs, the identity to
112/// present and how client certificates are treated. Start with [`ServerBuilder::new`].
113///
114/// Session resumption is off unless [`Policy::allow_resumption`] is set, which then keeps
115/// rustls's default session cache and TLS 1.3 tickets. A policy's access control list reads each
116/// connection's addresses from the scope this crate's accept helpers set
117/// ([`accept`](crate::accept), [`with_addresses`](crate::with_addresses)); a host whose
118/// connections reach rustls another way (quinn) takes [`configs`](ServerBuilder::configs).
119///
120/// The builder's `non_defaults()` is over the [`TlsSettings`], so its keys carry the `policy.`
121/// prefix (`policy.tls_versions`) and `alpn` is listed when set; [`Built::non_defaults`] reports
122/// the [`Policy`]'s own (`tls_versions`).
123#[derive(Builder, Debug)]
124#[builder(build = Built<ServerConfig>, name = "ServerBuilder", entry = "new", fallible)]
125pub struct ServerParts<'a> {
126    settings: TlsSettings,
127    #[builder(input)]
128    identity: &'a Identity,
129    #[builder(input)]
130    client_auth: ClientAuth,
131}
132
133impl TryFrom<ServerParts<'_>> for Built<ServerConfig> {
134    type Error = PeerError;
135
136    /// The configuration, shared by every connection it accepts.
137    ///
138    /// # Errors
139    ///
140    /// [`PeerError::Certificate`], [`PeerError::TrustPattern`], [`PeerError::CaFile`],
141    /// [`PeerError::Unsupported`] for trust only clients apply, [`PeerError::Policy`] or
142    /// [`PeerError::Tls`] when the configuration cannot be built.
143    fn try_from(parts: ServerParts<'_>) -> Result<Self, PeerError> {
144        let ServerParts {
145            settings,
146            identity,
147            client_auth,
148        } = parts;
149        let alpn = settings.alpn_bytes();
150        let policy = settings.policy;
151        let verifier = match &client_auth {
152            ClientAuth::None => None,
153            ClientAuth::Required(trust) => {
154                Some(Arc::new(trust.client_verifier(&policy, None)?) as Arc<dyn ClientCertVerifier>)
155            }
156            ClientAuth::Verifier(verifier) => Some(Arc::clone(verifier)),
157        };
158        let base = Base::new(identity, &alpn, &policy)?;
159        Ok(Built {
160            config: base.config(verifier, None, None)?,
161            policy,
162        })
163    }
164}
165
166impl ServerBuilder<'_> {
167    /// The configurations of a listener, one per connection: for a host such as quinn, whose
168    /// connections reach rustls without this crate's accept helpers. See [`ServerConfigs`].
169    ///
170    /// # Errors
171    ///
172    /// As [`build`](Self::build).
173    pub fn configs(self) -> Result<ServerConfigs, BuildError<PeerError>> {
174        let ServerParts {
175            settings,
176            identity,
177            client_auth,
178        } = self.parts().map_err(BuildError::Missing)?;
179        let alpn = settings.alpn_bytes();
180        let policy = settings.policy;
181        let non_defaults = policy.non_defaults();
182        let configs = || {
183            let client = match client_auth {
184                ClientAuth::None => Client::None,
185                ClientAuth::Required(trust) => {
186                    Client::Trust(Arc::new(trust.client_verifier(&policy, None)?))
187                }
188                ClientAuth::Verifier(verifier) => Client::Verifier(verifier),
189            };
190            Ok(ServerConfigs::from_parts(
191                Base::new(identity, &alpn, &policy)?,
192                client,
193                non_defaults,
194            ))
195        };
196        configs().map_err(BuildError::Failed)
197    }
198}
199
200/// What a [`ClientBuilder`] collects: the [`TlsSettings`], how the server is verified and the
201/// identity to present, if any. Start with [`ClientBuilder::new`].
202///
203/// The server is verified as the [`ServerAuth`] given says (a [`Trust`] converts). Without an
204/// identity this side presents no certificate: it proves itself, if at all, inside the
205/// encrypted channel, and a server that requires a client certificate refuses it. Session
206/// resumption is off unless [`Policy::allow_resumption`] is set, which then keeps rustls's
207/// default session cache.
208///
209/// As for the server, the builder's `non_defaults()` carries the `policy.` prefix and lists
210/// `alpn` when set; [`Built::non_defaults`] reports the [`Policy`]'s own.
211#[derive(Builder, Debug)]
212#[builder(build = Built<ClientConfig>, name = "ClientBuilder", entry = "new", fallible)]
213pub struct ClientParts<'a> {
214    settings: TlsSettings,
215    #[builder(input)]
216    server: ServerAuth,
217    #[builder(input)]
218    identity: Option<&'a Identity>,
219}
220
221impl TryFrom<ClientParts<'_>> for Built<ClientConfig> {
222    type Error = PeerError;
223
224    /// The configuration.
225    ///
226    /// # Errors
227    ///
228    /// [`PeerError::Unsupported`] for CA trust; [`PeerError::Policy`] when the policy asks for
229    /// something the ring provider or this build cannot do; [`PeerError::Io`] or
230    /// [`PeerError::Certificate`] when the roots cannot be loaded; [`PeerError::Certificate`] or
231    /// [`PeerError::Tls`] when the configuration cannot be built.
232    fn try_from(parts: ClientParts<'_>) -> Result<Self, PeerError> {
233        let ClientParts {
234            settings,
235            server,
236            identity,
237        } = parts;
238        let alpn = settings.alpn_bytes();
239        let policy = settings.policy;
240        let verifier: Arc<dyn ServerCertVerifier> = match server {
241            ServerAuth::Trust(trust) => PeerServerVerifier::new(&trust, &policy)?,
242            ServerAuth::Verifier(verifier) => verifier,
243        };
244        let selection = policy.selection()?;
245        let builder = ClientConfig::builder_with_provider(Arc::clone(&selection.provider))
246            .with_protocol_versions(&selection.versions)
247            .map_err(|_| PeerError::Tls)?
248            .dangerous()
249            .with_custom_certificate_verifier(verifier);
250        let mut config = match (identity, policy.certificate) {
251            (Some(identity), CertificateType::RawPublicKey) => {
252                builder.with_client_cert_resolver(Arc::new(AlwaysResolvesClientRawPublicKeys::new(
253                    identity.raw_public_key(&selection.provider)?,
254                )))
255            }
256            (Some(identity), CertificateType::X509) => builder
257                .with_client_auth_cert(identity.certificate_chain(), identity.private_key_der())
258                .map_err(|_| PeerError::Certificate)?,
259            (None, _) => builder.with_no_client_auth(),
260        };
261        config.alpn_protocols = alpn;
262        config.require_ems = policy.require_ems;
263        if !policy.allow_resumption {
264            config.resumption = Resumption::disabled();
265        }
266        crate::profiles::require_fips(&selection, config.fips())?;
267        Ok(Built { config, policy })
268    }
269}
270
271/// A build failure as the crate's own error, for the places that supply every input: a missing
272/// one is a programming error, reported as a policy refusal naming it.
273pub(crate) fn failed(error: BuildError<PeerError>) -> PeerError {
274    match error {
275        BuildError::Failed(error) => error,
276        other => PeerError::Policy(other.to_string()),
277    }
278}
279
280/// What every server configuration under one identity, ALPN list and policy shares: built and
281/// checked once, then a configuration per call, all sharing one session cache and ticketer.
282#[derive(Debug, Clone)]
283pub(crate) struct Base {
284    versions: Vec<&'static SupportedProtocolVersion>,
285    provider: Arc<CryptoProvider>,
286    resolver: Arc<dyn ResolvesServerCert>,
287    alpn: Vec<Vec<u8>>,
288    require_ems: bool,
289    resumption: bool,
290    session_storage: Arc<dyn StoresServerSessions>,
291    ticketer: Arc<dyn ProducesTickets>,
292    #[cfg(feature = "acl")]
293    acl: Option<Arc<coqui_net_acl::Acl>>,
294}
295
296impl Base {
297    pub(crate) fn new(
298        identity: &Identity,
299        alpn: &[Vec<u8>],
300        policy: &Policy,
301    ) -> Result<Self, PeerError> {
302        let selection = policy.selection()?;
303        let (versions, provider) = (selection.versions.clone(), Arc::clone(&selection.provider));
304        // Built once to check the key against the certificate and to take the resolver and
305        // rustls's session state from.
306        let builder = ServerConfig::builder_with_provider(Arc::clone(&provider))
307            .with_protocol_versions(&versions)
308            .map_err(|_| PeerError::Tls)?
309            .with_no_client_auth();
310        let mut template = match policy.certificate {
311            CertificateType::RawPublicKey => builder.with_cert_resolver(Arc::new(
312                AlwaysResolvesServerRawPublicKeys::new(identity.raw_public_key(&provider)?),
313            )),
314            CertificateType::X509 => builder
315                .with_single_cert(identity.certificate_chain(), identity.private_key_der())
316                .map_err(|_| PeerError::Certificate)?,
317        };
318        template.require_ems = policy.require_ems;
319        crate::profiles::require_fips(&selection, template.fips())?;
320        let session_storage: Arc<dyn StoresServerSessions> = if policy.allow_resumption {
321            template.session_storage
322        } else {
323            // No cache for TLS 1.2 session ids or TLS 1.3 stateful tickets.
324            Arc::new(NoServerSessionStorage {})
325        };
326        Ok(Self {
327            versions,
328            provider,
329            resolver: template.cert_resolver,
330            alpn: alpn.to_vec(),
331            require_ems: policy.require_ems,
332            resumption: policy.allow_resumption,
333            session_storage,
334            ticketer: template.ticketer,
335            #[cfg(feature = "acl")]
336            acl: match &policy.acl {
337                Some(acl) => Some(Arc::new(crate::gate::canonical(acl)?)),
338                None => None,
339            },
340        })
341    }
342
343    /// A configuration around `verifier` (none: server TLS). With an access control list,
344    /// `verifier` is wrapped to decide each certificate and the certificate resolver to decide
345    /// each `ClientHello`, from `addresses`, or from the accept helpers' scope when `None`;
346    /// a refusal at the `ClientHello` goes to `refused` when given.
347    pub(crate) fn config(
348        &self,
349        verifier: Option<Arc<dyn ClientCertVerifier>>,
350        addresses: Option<(SocketAddr, SocketAddr)>,
351        refused: Option<Arc<Slot>>,
352    ) -> Result<ServerConfig, PeerError> {
353        #[cfg(feature = "acl")]
354        let gate = self
355            .acl
356            .as_ref()
357            .map(|acl| crate::gate::Gate::new(Arc::clone(acl), addresses, refused.clone()));
358        #[cfg(not(feature = "acl"))]
359        let _ = addresses;
360        #[cfg(feature = "acl")]
361        let verifier = match (&gate, verifier) {
362            (Some(gate), Some(inner)) => Some(Arc::new(crate::gate::PeerGate {
363                inner,
364                gate: gate.clone(),
365            }) as Arc<dyn ClientCertVerifier>),
366            (_, verifier) => verifier,
367        };
368        let verifier = match (refused, verifier) {
369            (Some(slot), Some(inner)) => {
370                Some(Arc::new(Keeping { inner, slot }) as Arc<dyn ClientCertVerifier>)
371            }
372            (_, verifier) => verifier,
373        };
374        #[cfg(feature = "acl")]
375        let identified = verifier
376            .as_ref()
377            .is_some_and(|verifier| verifier.client_auth_mandatory());
378        let builder = ServerConfig::builder_with_provider(Arc::clone(&self.provider))
379            .with_protocol_versions(&self.versions)
380            .map_err(|_| PeerError::Tls)?;
381        let builder = match verifier {
382            Some(verifier) => builder.with_client_cert_verifier(verifier),
383            None => builder.with_no_client_auth(),
384        };
385        let mut config = builder.with_cert_resolver(Arc::clone(&self.resolver));
386        config.alpn_protocols.clone_from(&self.alpn);
387        config.require_ems = self.require_ems;
388        config.session_storage = Arc::clone(&self.session_storage);
389        config.ticketer = Arc::clone(&self.ticketer);
390        if !self.resumption {
391            config.send_tls13_tickets = 0;
392        }
393        #[cfg(feature = "acl")]
394        if let Some(gate) = gate {
395            config.cert_resolver = Arc::new(crate::gate::AddressGate {
396                inner: Arc::clone(&config.cert_resolver),
397                gate,
398                identified,
399            });
400        }
401        Ok(config)
402    }
403}