Skip to main content

coqui_peer_tls/
trust.rs

1use alloc::sync::Arc;
2use core::net::SocketAddr;
3#[cfg(feature = "ca")]
4use core::time::Duration;
5#[cfg(feature = "ca")]
6use std::sync::{Mutex, PoisonError};
7#[cfg(feature = "ca")]
8use std::time::Instant;
9
10use rustls::DigitallySignedStruct;
11use rustls::DistinguishedName;
12use rustls::SignatureScheme;
13use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
14use rustls::crypto::{
15    CryptoProvider, verify_tls12_signature, verify_tls13_signature,
16    verify_tls13_signature_with_raw_key,
17};
18use rustls::pki_types::{CertificateDer, ServerName, SubjectPublicKeyInfoDer, UnixTime};
19use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
20
21use crate::certificate::{key_for, label_of};
22use crate::error::{PeerError, Refusal};
23use crate::policy::{CertificateType, Policy};
24use crate::roots::Roots;
25use coqui_peer::{Digest, PeerId, TrustStore, WaitingLimits};
26
27/// A set of pinned certificate fingerprints: fixed, or the accepted peers of a
28/// [`TrustStore`].
29///
30/// A fixed pin matches a certificate by hashing it with the pin's own digest, and every pin
31/// is compared in constant time whatever its digest. A store holds SHA-256 pins.
32#[derive(Debug, Clone)]
33pub struct Pins(PinsKind);
34
35#[derive(Debug, Clone)]
36enum PinsKind {
37    Fixed(Vec<PeerId>),
38    Store(TrustStore),
39}
40
41impl Pins {
42    /// Exactly these fingerprints.
43    pub fn fixed(fingerprints: impl IntoIterator<Item = PeerId>) -> Self {
44        Self(PinsKind::Fixed(fingerprints.into_iter().collect()))
45    }
46
47    /// The peers accepted in `store`, read at every handshake. A server using this also
48    /// records refused peers that proved their key as waiting in the store.
49    pub fn store(store: TrustStore) -> Self {
50        Self(PinsKind::Store(store))
51    }
52
53    /// Whether the certificate with this DER encoding is pinned.
54    pub fn matches(&self, der: &[u8]) -> bool {
55        self.matches_as(der, CertificateType::X509)
56    }
57
58    /// Whether `der` is pinned, a certificate or a raw public key as `kind` says: a fixed pin
59    /// matches the hash of either, and a store holds each under its own label.
60    pub(crate) fn matches_as(&self, der: &[u8], kind: CertificateType) -> bool {
61        match &self.0 {
62            PinsKind::Fixed(pins) => {
63                // Every pin is compared, in constant time, whatever matches first.
64                let mut found = false;
65                for digest in [Digest::Sha256, Digest::Sha384, Digest::Sha512, Digest::Sha1] {
66                    let mut ours = None;
67                    for pin in pins.iter().filter(|pin| pin.digest() == digest) {
68                        let ours = ours.get_or_insert_with(|| digest.of(der));
69                        found |= pin == ours;
70                    }
71                }
72                found
73            }
74            PinsKind::Store(store) => {
75                let id = PeerId::of(der);
76                store
77                    .accepted_key(&id)
78                    .is_some_and(|key| key.method == crate::METHOD && key.label == label_of(kind))
79            }
80        }
81    }
82
83    /// Whether the certificate is the pending successor of an accepted certificate in a
84    /// store-backed set.
85    fn pending_successor(&self, der: &[u8], kind: CertificateType) -> bool {
86        match &self.0 {
87            PinsKind::Store(store) => store
88                .successor_key(&PeerId::of(der))
89                .is_some_and(|key| key.method == crate::METHOD && key.label == label_of(kind)),
90            PinsKind::Fixed(_) => false,
91        }
92    }
93
94    /// Records that the holder of a pending successor proved it in the handshake, then promotes
95    /// it unless the store's rotation options require approval. Whether it is now accepted.
96    fn prove(&self, der: &[u8]) -> bool {
97        let PinsKind::Store(store) = &self.0 else {
98            return false;
99        };
100        let id = PeerId::of(der);
101        if store.prove_successor(&id).is_err() {
102            return false;
103        }
104        !store.rotation().require_approval && store.promote_successor(&id).is_ok()
105    }
106
107    fn check_digests(&self, policy: &Policy) -> Result<(), PeerError> {
108        if let PinsKind::Fixed(pins) = &self.0 {
109            pins.iter().try_for_each(|pin| policy.check_pin(pin))?;
110        }
111        Ok(())
112    }
113
114    fn with_limits(&self, limits: WaitingLimits) -> Self {
115        match &self.0 {
116            PinsKind::Store(store) => {
117                let mut waiting = store.settings().waiting;
118                waiting.limits = limits;
119                Self(PinsKind::Store(store.clone().waiting_queue(waiting)))
120            }
121            PinsKind::Fixed(_) => self.clone(),
122        }
123    }
124
125    fn records_waiting(&self) -> bool {
126        matches!(self.0, PinsKind::Store(_))
127    }
128
129    /// Why a certificate these pins do not match is refused.
130    fn refusal(&self) -> Refusal {
131        match self.0 {
132            PinsKind::Fixed(_) => Refusal::NotPinned,
133            PinsKind::Store(_) => Refusal::NotAccepted,
134        }
135    }
136
137    fn record_waiting(&self, der: &[u8], source: Option<SocketAddr>, kind: CertificateType) {
138        if let PinsKind::Store(store) = &self.0
139            && let Ok(key) = key_for(kind, der)
140        {
141            store.record_waiting(&key, source);
142        }
143    }
144}
145
146/// A CA trust policy: certificates signed by the CAs in a PEM file whose subject and
147/// subject alternative names match optional globs.
148#[cfg(feature = "ca")]
149#[derive(Debug, Clone)]
150pub struct CaPolicy {
151    /// PEM file with the trusted CA certificates.
152    pub ca_file: std::path::PathBuf,
153    /// Globs matched against the subject, rendered as by `x509-parser`; empty matches any.
154    pub subject: Vec<String>,
155    /// Globs matched against the subject alternative names; empty matches any, otherwise one
156    /// name must match one glob. A glob without a prefix matches a DNS, email, URI or IP name;
157    /// `dns:`, `ip:`, `email:`, `uri:` or `upn:` limits it to that kind. IP addresses are
158    /// matched in canonical text (IPv6 compressed, an IPv4-mapped address as its IPv4 one),
159    /// and a glob that is an IP literal is made canonical too, so `ip:::1` matches
160    /// `0:0:0:0:0:0:0:1`.
161    pub san: Vec<String>,
162    /// Whether a DNS name that is an IP literal also matches as that address (an `ip:` glob,
163    /// in canonical text). Some issuers put an address in a `dNSName` for clients that do not
164    /// read IP SANs. `true` by default; `false` matches an `ip:` glob against `iPAddress`
165    /// names only.
166    pub ip_in_dns: bool,
167}
168
169#[cfg(feature = "ca")]
170impl CaPolicy {
171    /// CAs from the PEM file at `ca_file`, no globs, DNS names holding an IP literal matched
172    /// as addresses.
173    pub fn new(ca_file: impl Into<std::path::PathBuf>) -> Self {
174        Self {
175            ca_file: ca_file.into(),
176            subject: Vec::new(),
177            san: Vec::new(),
178            ip_in_dns: true,
179        }
180    }
181}
182
183#[cfg(feature = "ca")]
184type MaybeCa = Option<crate::ca::Ca>;
185#[cfg(not(feature = "ca"))]
186type MaybeCa = Option<()>;
187
188/// Whom to trust.
189///
190/// Every policy requires the peer to prove it holds the certificate's key in the handshake.
191#[derive(Debug, Clone)]
192#[non_exhaustive]
193pub enum Trust {
194    /// Only pinned certificates.
195    Pinned(Pins),
196    /// Certificates signed by a CA and matching name globs. Server role only.
197    #[cfg(feature = "ca")]
198    Ca(CaPolicy),
199    /// A pinned certificate, or one the CA policy trusts. Server role only.
200    #[cfg(feature = "ca")]
201    PinnedOrCa {
202        /// The pinned certificates.
203        pins: Pins,
204        /// The CA policy.
205        ca: CaPolicy,
206    },
207    /// Any certificate whose key the peer proves; the caller decides from the returned
208    /// [`PeerIdentity`](crate::PeerIdentity) afterwards.
209    AnyWithKeyProof,
210    /// A server certificate that chains to these roots and is valid for the name dialled:
211    /// the web PKI, as a browser trusts a server. Client role only.
212    Roots(Roots),
213    /// A pinned server certificate, or one the roots trust for the name dialled. A pinned
214    /// certificate is taken as [`Pinned`](Trust::Pinned) takes it, whatever its name. Client
215    /// role only.
216    PinnedOrRoots {
217        /// The pinned certificates.
218        pins: Pins,
219        /// The roots.
220        roots: Roots,
221    },
222}
223
224/// What the pinned path additionally requires, from the [`Policy`].
225#[derive(Debug, Clone, Copy)]
226struct PinnedChecks {
227    validity: bool,
228    chain_allowed: bool,
229}
230
231impl PinnedChecks {
232    fn of(policy: &Policy) -> Self {
233        Self {
234            // A raw public key has no dates.
235            validity: policy.check_validity && policy.certificate == CertificateType::X509,
236            chain_allowed: policy.allow_chain_when_pinned,
237        }
238    }
239}
240
241impl Trust {
242    /// Refuses a trust that decides by a certificate's chain or names when the policy's peers
243    /// authenticate with raw public keys, which have neither.
244    fn check_certificate_type(&self, policy: &Policy) -> Result<(), PeerError> {
245        if policy.certificate != CertificateType::RawPublicKey {
246            return Ok(());
247        }
248        match self {
249            Self::Pinned(_) | Self::AnyWithKeyProof => Ok(()),
250            _ => Err(PeerError::Policy(
251                "certificate = raw_public_key has no certificate chain or name for this trust to \
252                 check; use Trust::Pinned or Trust::AnyWithKeyProof"
253                    .to_owned(),
254            )),
255        }
256    }
257
258    /// The client verifier, recording waiting entries under `source` when it is given and
259    /// under the scope's otherwise.
260    pub(crate) fn client_verifier(
261        &self,
262        policy: &Policy,
263        source: Option<SocketAddr>,
264    ) -> Result<PeerClientVerifier, PeerError> {
265        self.check_certificate_type(policy)?;
266        let provider = policy.crypto_provider()?;
267        let (pins, ca, any): (Option<Pins>, MaybeCa, bool) = match self {
268            Self::Pinned(pins) => (Some(pins.clone()), None, false),
269            #[cfg(feature = "ca")]
270            Self::Ca(ca) => (None, Some(crate::ca::Ca::load(ca, &provider)?), false),
271            #[cfg(feature = "ca")]
272            Self::PinnedOrCa { pins, ca } => (
273                Some(pins.clone()),
274                Some(crate::ca::Ca::load(ca, &provider)?),
275                false,
276            ),
277            Self::AnyWithKeyProof => (None, None, true),
278            Self::Roots(_) | Self::PinnedOrRoots { .. } => return Err(PeerError::Unsupported),
279        };
280        if let Some(pins) = &pins {
281            pins.check_digests(policy)?;
282        }
283        let pins = pins.map(|pins| pins.with_limits(policy.waiting));
284        #[cfg(not(feature = "ca"))]
285        let _ = ca;
286        Ok(PeerClientVerifier {
287            parts: Arc::new(ClientParts {
288                pins,
289                #[cfg(feature = "ca")]
290                ca,
291                any,
292                checks: PinnedChecks::of(policy),
293                kind: policy.certificate,
294                provider,
295            }),
296            source,
297            #[cfg(feature = "ca")]
298            ca_trusted: Mutex::default(),
299        })
300    }
301
302    /// Checks a client certificate chain as this trust's client verifier does when the chain
303    /// is presented: pins (`Pinned`), chain to the CA roots with the subject and SAN globs
304    /// (`Ca`), the pin first then the CA (`PinnedOrCa`), and the policy's checks of a pinned
305    /// certificate (no chain unless allowed, validity dates). **No key proof**: use it only
306    /// for a certificate a TLS handshake already proved, such as one a proxy or host hands
307    /// over. A store-backed pin set records nothing as waiting.
308    ///
309    /// # Errors
310    ///
311    /// [`PeerError::Unsupported`] for the other trusts; [`PeerError::Policy`],
312    /// [`PeerError::CaFile`] or [`PeerError::TrustPattern`] when the trust cannot be built
313    /// under `policy`; [`PeerError::Io`] of kind `InvalidData` wrapping the rustls error when
314    /// the chain is refused, from which [`PeerError::refusal`] takes the [`Refusal`]
315    /// (`NotPinned`, `NotAccepted`, `NotTrusted`, `ChainWhenPinned`); an expired or not yet
316    /// valid pinned certificate is rustls's `Expired` / `NotValidYet` there.
317    pub fn verify_client_chain(
318        &self,
319        policy: &Policy,
320        leaf: &[u8],
321        intermediates: &[&[u8]],
322    ) -> Result<(), PeerError> {
323        let refused = |error: rustls::Error| {
324            PeerError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, error))
325        };
326        match self {
327            Self::Pinned(_) => {}
328            #[cfg(feature = "ca")]
329            Self::Ca(_) | Self::PinnedOrCa { .. } => {}
330            _ => return Err(PeerError::Unsupported),
331        }
332        let verifier = self.client_verifier(policy, None)?;
333        let certificate = CertificateDer::from(leaf);
334        let chain: Vec<CertificateDer<'_>> = intermediates
335            .iter()
336            .map(|der| CertificateDer::from(*der))
337            .collect();
338        let now = UnixTime::now();
339        if let Some(pins) = &verifier.parts.pins
340            && pins.matches_as(leaf, verifier.parts.kind)
341        {
342            return check_pinned(&certificate, &chain, now, verifier.parts.checks).map_err(refused);
343        }
344        #[cfg(feature = "ca")]
345        if let Some(ca) = &verifier.parts.ca {
346            return match ca.trusts(&certificate, &chain, now) {
347                Ok(true) => Ok(()),
348                Ok(false) => Err(refused(Refusal::NotTrusted.into_rustls())),
349                Err(error) => Err(refused(error)),
350            };
351        }
352        let refusal = verifier
353            .parts
354            .pins
355            .as_ref()
356            .map_or(Refusal::NotPinned, Pins::refusal);
357        Err(refused(refusal.into_rustls()))
358    }
359}
360
361/// Verifies the certificate a server presents to a dialing client.
362///
363/// A pinned certificate is taken because it is pinned, and because the server proves in the
364/// handshake that it holds the key; its name is not checked. Validity dates and the absence
365/// of a chain are checked as the [`Policy`] says, after the pin matched. With
366/// [`Roots`](Trust::Roots), a certificate no pin matches is taken when its chain, dates and
367/// name verify against the roots for the server name dialled.
368#[derive(Debug)]
369pub struct PeerServerVerifier {
370    pins: Option<Pins>,
371    roots: Option<Arc<dyn ServerCertVerifier>>,
372    any: bool,
373    checks: PinnedChecks,
374    kind: CertificateType,
375    provider: Arc<CryptoProvider>,
376}
377
378impl PeerServerVerifier {
379    /// The verifier a client uses for the server certificate, for `trust` under `policy`.
380    ///
381    /// # Errors
382    ///
383    /// [`PeerError::Unsupported`] for CA policies, which only servers apply;
384    /// [`PeerError::Policy`] when a pin uses a digest the policy refuses;
385    /// [`PeerError::Io`] when a roots bundle file cannot be read, [`PeerError::Certificate`]
386    /// when it holds no certificate or one that cannot be a root, or the platform verifier
387    /// cannot start.
388    pub fn new(trust: &Trust, policy: &Policy) -> Result<Arc<Self>, PeerError> {
389        trust.check_certificate_type(policy)?;
390        let provider = policy.crypto_provider()?;
391        let (pins, roots, any) = match trust {
392            Trust::Pinned(pins) => (Some(pins.clone()), None, false),
393            Trust::AnyWithKeyProof => (None, None, true),
394            Trust::Roots(roots) => (None, Some(roots.verifier(&provider)?), false),
395            Trust::PinnedOrRoots { pins, roots } => {
396                (Some(pins.clone()), Some(roots.verifier(&provider)?), false)
397            }
398            #[cfg(feature = "ca")]
399            Trust::Ca(_) | Trust::PinnedOrCa { .. } => return Err(PeerError::Unsupported),
400        };
401        if let Some(pins) = &pins {
402            pins.check_digests(policy)?;
403        }
404        Ok(Arc::new(Self {
405            pins,
406            roots,
407            any,
408            checks: PinnedChecks::of(policy),
409            kind: policy.certificate,
410            provider,
411        }))
412    }
413
414    /// After a valid signature: a pending successor the server just proved is recorded as
415    /// proven, and promoted unless the store waits for approval, when it is refused.
416    fn settle_successor(&self, certificate: &CertificateDer<'_>) -> Result<(), rustls::Error> {
417        if let Some(pins) = &self.pins
418            && !self.any
419            && !pins.matches_as(certificate.as_ref(), self.kind)
420            && pins.pending_successor(certificate.as_ref(), self.kind)
421            && !pins.prove(certificate.as_ref())
422        {
423            return Err(pins.refusal().into_rustls());
424        }
425        Ok(())
426    }
427}
428
429impl ServerCertVerifier for PeerServerVerifier {
430    fn verify_server_cert(
431        &self,
432        certificate: &CertificateDer<'_>,
433        intermediates: &[CertificateDer<'_>],
434        name: &ServerName<'_>,
435        ocsp_response: &[u8],
436        now: UnixTime,
437    ) -> Result<ServerCertVerified, rustls::Error> {
438        if self.any {
439            return Ok(ServerCertVerified::assertion());
440        }
441        if self
442            .pins
443            .as_ref()
444            .is_some_and(|pins| pins.matches_as(certificate.as_ref(), self.kind))
445        {
446            check_pinned(certificate, intermediates, now, self.checks)?;
447            Ok(ServerCertVerified::assertion())
448        } else if self
449            .pins
450            .as_ref()
451            .is_some_and(|pins| pins.pending_successor(certificate.as_ref(), self.kind))
452        {
453            // Settled only once the signature below proves the server holds its key.
454            check_pinned(certificate, intermediates, now, self.checks)?;
455            Ok(ServerCertVerified::assertion())
456        } else if let Some(roots) = &self.roots {
457            roots
458                .verify_server_cert(certificate, intermediates, name, ocsp_response, now)
459                .map_err(crate::roots::refusal_of)
460        } else {
461            let refusal = self.pins.as_ref().map_or(Refusal::NotPinned, Pins::refusal);
462            Err(refusal.into_rustls())
463        }
464    }
465
466    fn verify_tls12_signature(
467        &self,
468        message: &[u8],
469        certificate: &CertificateDer<'_>,
470        signed: &DigitallySignedStruct,
471    ) -> Result<HandshakeSignatureValid, rustls::Error> {
472        if self.kind == CertificateType::RawPublicKey {
473            return Err(raw_needs_tls13());
474        }
475        let algorithms = &self.provider.signature_verification_algorithms;
476        let verified = verify_tls12_signature(message, certificate, signed, algorithms)?;
477        self.settle_successor(certificate)?;
478        Ok(verified)
479    }
480
481    fn verify_tls13_signature(
482        &self,
483        message: &[u8],
484        certificate: &CertificateDer<'_>,
485        signed: &DigitallySignedStruct,
486    ) -> Result<HandshakeSignatureValid, rustls::Error> {
487        let algorithms = &self.provider.signature_verification_algorithms;
488        let verified = verify_tls13(message, certificate, signed, algorithms, self.kind)?;
489        self.settle_successor(certificate)?;
490        Ok(verified)
491    }
492
493    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
494        self.provider
495            .signature_verification_algorithms
496            .supported_schemes()
497    }
498
499    fn requires_raw_public_keys(&self) -> bool {
500        self.kind == CertificateType::RawPublicKey
501    }
502}
503
504/// Verifies the certificate a client presents to a listening server.
505///
506/// With a store-backed pin set, a certificate that is neither pinned nor trusted by the CA
507/// policy is not refused when it is presented: rustls calls
508/// [`verify_client_cert`](ClientCertVerifier::verify_client_cert) before the client's
509/// `CertificateVerify` signature, so the client has not yet shown it holds the key. The decision
510/// is deferred to the signature check, which records the certificate as waiting only once the
511/// signature verifies, and then refuses the handshake.
512#[derive(Debug)]
513pub struct PeerClientVerifier {
514    parts: Arc<ClientParts>,
515    /// The source waiting entries are recorded under, for a verifier made for one connection;
516    /// `None` reads the scope the accept helpers set.
517    source: Option<SocketAddr>,
518    /// Certificates the CA policy trusted at presentation, whose signature is still to come.
519    /// The signature check receives only the certificate, not the chain the CA policy needed,
520    /// so this is how it tells a trusted certificate from a deferred one.
521    #[cfg(feature = "ca")]
522    ca_trusted: Mutex<Vec<(PeerId, Instant)>>,
523}
524
525/// What a client verifier decides by, shared by the verifiers made for single connections.
526#[derive(Debug)]
527struct ClientParts {
528    pins: Option<Pins>,
529    #[cfg(feature = "ca")]
530    ca: Option<crate::ca::Ca>,
531    any: bool,
532    checks: PinnedChecks,
533    kind: CertificateType,
534    provider: Arc<CryptoProvider>,
535}
536
537/// Builds a [`PeerClientVerifier`]: [`PeerClientVerifier::builder`], the policy and the
538/// addresses, then [`build`](Self::build).
539#[derive(Debug, Clone)]
540#[must_use]
541pub struct PeerClientVerifierBuilder {
542    trust: Trust,
543    policy: Policy,
544    addresses: Option<(SocketAddr, SocketAddr)>,
545}
546
547impl PeerClientVerifierBuilder {
548    /// The policy the verifier decides under. Default [`Policy::default`].
549    pub fn policy(mut self, policy: Policy) -> Self {
550        self.policy = policy;
551        self
552    }
553
554    /// The addresses of one connection, from `source` to `local`, for a host whose
555    /// connections reach rustls without this crate's accept helpers, such as quinn, which runs
556    /// the verifier on threads of its own.
557    ///
558    /// Waiting entries are recorded under `source`. With the `acl` feature, a policy's access
559    /// control list is applied to the certificate's fingerprint from these addresses before
560    /// the pins or the store are consulted ([`Refusal::PeerDenied`]), so a denied client is
561    /// never recorded as waiting. The list's address rules are not applied here; a host checks
562    /// them before the handshake with [`Policy::admits_address`], or uses
563    /// [`ServerConfigs::for_connection`](crate::ServerConfigs::for_connection), which applies
564    /// both. Without addresses, a verifier reads the scope the accept helpers set.
565    pub fn addresses(mut self, source: SocketAddr, local: SocketAddr) -> Self {
566        self.addresses = Some((source, local));
567        self
568    }
569
570    /// The verifier.
571    ///
572    /// # Errors
573    ///
574    /// [`PeerError::Unsupported`] for [`Roots`](Trust::Roots) and
575    /// [`PinnedOrRoots`](Trust::PinnedOrRoots), which only clients apply;
576    /// [`PeerError::CaFile`] / [`PeerError::TrustPattern`] when the CA file or globs
577    /// are unusable; [`PeerError::Policy`] when a pin uses a digest the policy refuses, the
578    /// policy cannot build a crypto provider, a rule of its access control list names something
579    /// that is not a SHA-256 peer id, or it has an access control list and no addresses were
580    /// given: a verifier without addresses cannot apply one, so it is refused rather than
581    /// ignored.
582    pub fn build(self) -> Result<Arc<dyn ClientCertVerifier>, PeerError> {
583        let source = self.addresses.map(|(source, _)| source);
584        #[cfg(feature = "acl")]
585        if self.policy.acl.is_some() && self.addresses.is_none() {
586            return Err(PeerError::Policy(
587                "a client verifier without addresses cannot apply the policy's acl; build a \
588                 server configuration or give the verifier addresses"
589                    .to_owned(),
590            ));
591        }
592        let verifier: Arc<dyn ClientCertVerifier> =
593            Arc::new(self.trust.client_verifier(&self.policy, source)?);
594        #[cfg(feature = "acl")]
595        if let (Some(acl), Some(addresses)) = (&self.policy.acl, self.addresses) {
596            let gate = crate::gate::Gate::new(
597                Arc::new(crate::gate::canonical(acl)?),
598                Some(addresses),
599                None,
600            );
601            return Ok(Arc::new(crate::gate::PeerGate {
602                inner: verifier,
603                gate,
604            }));
605        }
606        Ok(verifier)
607    }
608}
609
610/// How long a CA-trusted certificate waits for its signature before being forgotten.
611#[cfg(feature = "ca")]
612const CA_TRUSTED_TTL: Duration = Duration::from_secs(30);
613/// Bound on certificates awaiting their signature.
614#[cfg(feature = "ca")]
615const CA_TRUSTED_MAX: usize = 4096;
616
617impl PeerClientVerifier {
618    /// A builder for the verifier a server uses for client certificates under `trust`.
619    pub fn builder(trust: &Trust) -> PeerClientVerifierBuilder {
620        PeerClientVerifierBuilder {
621            trust: trust.clone(),
622            policy: Policy::default(),
623            addresses: None,
624        }
625    }
626
627    /// The same verifier for one connection, recording waiting entries under `source`.
628    pub(crate) fn for_source(&self, source: SocketAddr) -> Self {
629        Self {
630            parts: Arc::clone(&self.parts),
631            source: Some(source),
632            #[cfg(feature = "ca")]
633            ca_trusted: Mutex::default(),
634        }
635    }
636
637    /// Whether unpinned, untrusted certificates are deferred to the signature check.
638    fn defers(&self) -> bool {
639        !self.parts.any && self.parts.pins.as_ref().is_some_and(Pins::records_waiting)
640    }
641
642    fn pinned(&self, der: &[u8]) -> bool {
643        self.parts
644            .pins
645            .as_ref()
646            .is_some_and(|pins| pins.matches_as(der, self.parts.kind))
647    }
648
649    /// Why a certificate that is neither pinned nor CA-trusted is refused.
650    fn refusal(&self) -> Refusal {
651        match &self.parts.pins {
652            Some(pins) if pins.records_waiting() => Refusal::NotAccepted,
653            #[cfg(feature = "ca")]
654            _ if self.parts.ca.is_some() => Refusal::NotTrusted,
655            Some(pins) => pins.refusal(),
656            None => Refusal::NotPinned,
657        }
658    }
659
660    #[cfg(feature = "ca")]
661    fn note_ca_trusted(&self, der: &[u8]) {
662        let mut waiting = self
663            .ca_trusted
664            .lock()
665            .unwrap_or_else(PoisonError::into_inner);
666        let now = Instant::now();
667        waiting.retain(|(_, at)| now.duration_since(*at) < CA_TRUSTED_TTL);
668        if waiting.len() < CA_TRUSTED_MAX {
669            waiting.push((PeerId::of(der), now));
670        }
671    }
672
673    /// Consumes one note for `der`; whether there was one.
674    fn take_ca_trusted(&self, der: &[u8]) -> bool {
675        #[cfg(feature = "ca")]
676        {
677            let fingerprint = PeerId::of(der);
678            let mut waiting = self
679                .ca_trusted
680                .lock()
681                .unwrap_or_else(PoisonError::into_inner);
682            let now = Instant::now();
683            waiting.retain(|(_, at)| now.duration_since(*at) < CA_TRUSTED_TTL);
684            if let Some(index) = waiting.iter().position(|(had, _)| *had == fingerprint) {
685                waiting.swap_remove(index);
686                return true;
687            }
688        }
689        #[cfg(not(feature = "ca"))]
690        let _ = der;
691        false
692    }
693
694    /// After the signature check: a valid signature means the peer holds the key, so a
695    /// deferred certificate is recorded as waiting and refused. An invalid one is refused
696    /// without a record.
697    fn settle(
698        &self,
699        certificate: &CertificateDer<'_>,
700        verified: Result<HandshakeSignatureValid, rustls::Error>,
701    ) -> Result<HandshakeSignatureValid, rustls::Error> {
702        if !self.defers() {
703            return verified;
704        }
705        let trusted = self.take_ca_trusted(certificate.as_ref());
706        let verified = verified?;
707        if trusted || self.pinned(certificate.as_ref()) {
708            return Ok(verified);
709        }
710        if let Some(pins) = &self.parts.pins
711            && pins.pending_successor(certificate.as_ref(), self.parts.kind)
712        {
713            // Announced by an accepted peer, and now proven: promoted, or recorded as proven
714            // for the caller to approve. Not a stranger to queue either way.
715            return pins
716                .prove(certificate.as_ref())
717                .then_some(verified)
718                .ok_or_else(|| self.refusal().into_rustls());
719        }
720        if let Some(pins) = &self.parts.pins {
721            pins.record_waiting(
722                certificate.as_ref(),
723                self.source.or_else(crate::source::current),
724                self.parts.kind,
725            );
726        }
727        Err(self.refusal().into_rustls())
728    }
729}
730
731impl ClientCertVerifier for PeerClientVerifier {
732    fn root_hint_subjects(&self) -> &[DistinguishedName] {
733        #[cfg(feature = "ca")]
734        if let Some(ca) = &self.parts.ca {
735            return ca.root_hint_subjects();
736        }
737        &[]
738    }
739
740    fn verify_client_cert(
741        &self,
742        certificate: &CertificateDer<'_>,
743        intermediates: &[CertificateDer<'_>],
744        now: UnixTime,
745    ) -> Result<ClientCertVerified, rustls::Error> {
746        if self.parts.any {
747            return Ok(ClientCertVerified::assertion());
748        }
749        if self.pinned(certificate.as_ref()) {
750            check_pinned(certificate, intermediates, now, self.parts.checks)?;
751            return Ok(ClientCertVerified::assertion());
752        }
753        if self
754            .parts
755            .pins
756            .as_ref()
757            .is_some_and(|pins| pins.pending_successor(certificate.as_ref(), self.parts.kind))
758        {
759            // Settled in `settle`, once the signature proves the client holds its key.
760            check_pinned(certificate, intermediates, now, self.parts.checks)?;
761            return Ok(ClientCertVerified::assertion());
762        }
763        #[cfg(feature = "ca")]
764        if let Some(ca) = &self.parts.ca
765            && ca.trusts(certificate, intermediates, now)?
766        {
767            if self.defers() {
768                self.note_ca_trusted(certificate.as_ref());
769            }
770            return Ok(ClientCertVerified::assertion());
771        }
772        #[cfg(not(feature = "ca"))]
773        let _ = (intermediates, now);
774        if self.defers() {
775            // Not recorded here: the client has not yet proved it holds the key.
776            return Ok(ClientCertVerified::assertion());
777        }
778        Err(self.refusal().into_rustls())
779    }
780
781    fn verify_tls12_signature(
782        &self,
783        message: &[u8],
784        certificate: &CertificateDer<'_>,
785        signed: &DigitallySignedStruct,
786    ) -> Result<HandshakeSignatureValid, rustls::Error> {
787        if self.parts.kind == CertificateType::RawPublicKey {
788            return Err(raw_needs_tls13());
789        }
790        let algorithms = &self.parts.provider.signature_verification_algorithms;
791        let verified = verify_tls12_signature(message, certificate, signed, algorithms);
792        self.settle(certificate, verified)
793    }
794
795    fn verify_tls13_signature(
796        &self,
797        message: &[u8],
798        certificate: &CertificateDer<'_>,
799        signed: &DigitallySignedStruct,
800    ) -> Result<HandshakeSignatureValid, rustls::Error> {
801        let algorithms = &self.parts.provider.signature_verification_algorithms;
802        let verified = verify_tls13(message, certificate, signed, algorithms, self.parts.kind);
803        self.settle(certificate, verified)
804    }
805
806    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
807        self.parts
808            .provider
809            .signature_verification_algorithms
810            .supported_schemes()
811    }
812
813    fn requires_raw_public_keys(&self) -> bool {
814        self.parts.kind == CertificateType::RawPublicKey
815    }
816}
817
818/// The error of a TLS 1.2 signature check under raw public keys, which only TLS 1.3 verifies.
819fn raw_needs_tls13() -> rustls::Error {
820    rustls::Error::General("raw public keys are verified in TLS 1.3 only".to_owned())
821}
822
823/// A TLS 1.3 handshake signature checked against `certificate`: a certificate's key, or, for a
824/// raw public key, the `SubjectPublicKeyInfo` itself.
825fn verify_tls13(
826    message: &[u8],
827    certificate: &CertificateDer<'_>,
828    signed: &DigitallySignedStruct,
829    algorithms: &rustls::crypto::WebPkiSupportedAlgorithms,
830    kind: CertificateType,
831) -> Result<HandshakeSignatureValid, rustls::Error> {
832    match kind {
833        CertificateType::X509 => verify_tls13_signature(message, certificate, signed, algorithms),
834        CertificateType::RawPublicKey => verify_tls13_signature_with_raw_key(
835            message,
836            &SubjectPublicKeyInfoDer::from(certificate.as_ref()),
837            signed,
838            algorithms,
839        ),
840    }
841}
842
843/// What a pinned certificate must also be, checked only after its pin matched: alone (no
844/// chain, since there is no CA to chain to) and within its validity dates. A custom verifier
845/// loses rustls's own date check, and a pin does not change when a certificate expires.
846fn check_pinned(
847    certificate: &CertificateDer<'_>,
848    intermediates: &[CertificateDer<'_>],
849    now: UnixTime,
850    checks: PinnedChecks,
851) -> Result<(), rustls::Error> {
852    if !checks.chain_allowed && !intermediates.is_empty() {
853        return Err(Refusal::ChainWhenPinned.into_rustls());
854    }
855    if !checks.validity {
856        return Ok(());
857    }
858    let (not_before, not_after) = crate::x509::validity(certificate.as_ref())
859        .map_err(|_| rustls::Error::InvalidCertificate(rustls::CertificateError::BadEncoding))?;
860    let now = i64::try_from(now.as_secs()).unwrap_or(i64::MAX);
861    if now < not_before {
862        return Err(rustls::Error::InvalidCertificate(
863            rustls::CertificateError::NotValidYet,
864        ));
865    }
866    if now > not_after {
867        return Err(rustls::Error::InvalidCertificate(
868            rustls::CertificateError::Expired,
869        ));
870    }
871    Ok(())
872}