Skip to main content

gitpoulpi_hosting/trust/
tls.rs

1//! The certificate verifier of every hosting and AI connection.
2//!
3//! [`GuardedVerifier`] wraps rustls' own `WebPkiServerVerifier` (webpki roots
4//! plus the system roots: the same set as before) and adds one thing: an
5//! optional key pin per host.
6//!
7//! - no pin for the host: webpki decides, exactly as it always did;
8//! - [`TlsPolicy::Tofu`]: webpki decides, **except** that a chain failing only
9//!   on issuer, self-signature or name is accepted when the leaf's key is the
10//!   recorded one (a private CA, a self-signed server);
11//! - [`TlsPolicy::Strict`]: the leaf's key must be the recorded one *and* the
12//!   chain must validate or fail only in that way.
13//!
14//! The handshake signatures (`verify_tls12_signature`, `verify_tls13_signature`
15//! and the supported schemes) are **always** webpki's: that signature is what
16//! proves the server holds the key the pin names. Skipping it would turn a
17//! pin into "anyone who has seen the certificate".
18
19use std::collections::HashMap;
20use std::sync::{Arc, Mutex, OnceLock};
21
22use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
23use rustls::client::WebPkiServerVerifier;
24use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
25use rustls::{
26    CertificateError, DigitallySignedStruct, Error as TlsError, RootCertStore, SignatureScheme,
27};
28
29use super::store::CertInfo;
30use super::{TrustProblem, TrustSubject};
31
32/// What a host's certificate is held to.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum TlsPolicy {
35    Tofu { spki: String },
36    Strict { spki: String },
37}
38
39impl TlsPolicy {
40    pub fn spki(&self) -> &str {
41        match self {
42            Self::Tofu { spki } | Self::Strict { spki } => spki,
43        }
44    }
45}
46
47/// Why the verifier refused a host's certificate (read back by the
48/// transport to build a [`TrustProblem`]).
49#[derive(Debug, Clone)]
50pub struct Rejection {
51    pub new: CertInfo,
52    /// The pinned key, when the host had a policy.
53    pub pinned: Option<String>,
54}
55
56fn lock<T>(m: &'static Mutex<T>) -> std::sync::MutexGuard<'static, T> {
57    m.lock().unwrap_or_else(|p| p.into_inner())
58}
59
60static POLICIES: OnceLock<Mutex<HashMap<String, TlsPolicy>>> = OnceLock::new();
61static OBSERVED: OnceLock<Mutex<HashMap<String, CertInfo>>> = OnceLock::new();
62static REJECTED: OnceLock<Mutex<HashMap<String, Rejection>>> = OnceLock::new();
63
64fn policies() -> &'static Mutex<HashMap<String, TlsPolicy>> {
65    POLICIES.get_or_init(Default::default)
66}
67fn observed_map() -> &'static Mutex<HashMap<String, CertInfo>> {
68    OBSERVED.get_or_init(Default::default)
69}
70fn rejected_map() -> &'static Mutex<HashMap<String, Rejection>> {
71    REJECTED.get_or_init(Default::default)
72}
73
74/// Sets (or, with `None`, clears) the policy of `host`. `TrustGate` calls it
75/// whenever it builds a client from a record.
76pub fn set_policy(host: &str, policy: Option<TlsPolicy>) {
77    let host = host.to_ascii_lowercase();
78    let mut map = lock(policies());
79    match policy {
80        Some(p) => map.insert(host, p),
81        None => map.remove(&host),
82    };
83}
84
85pub fn policy_of(host: &str) -> Option<TlsPolicy> {
86    lock(policies()).get(&host.to_ascii_lowercase()).cloned()
87}
88
89/// The certificate the last handshake with `host` presented.
90pub fn observed(host: &str) -> Option<CertInfo> {
91    lock(observed_map())
92        .get(&host.to_ascii_lowercase())
93        .cloned()
94}
95
96/// Takes (and forgets) the verifier's refusal of `host`, if it just refused.
97pub fn take_rejection(host: &str) -> Option<Rejection> {
98    lock(rejected_map()).remove(&host.to_ascii_lowercase())
99}
100
101/// The problem a refused handshake with `host` is, subject still unbound.
102pub fn problem_for(host: &str) -> Option<TrustProblem> {
103    let rejection = take_rejection(host)?;
104    let subject = TrustSubject::Host(host.to_ascii_lowercase());
105    Some(match rejection.pinned {
106        Some(spki) => TrustProblem::CertificateChanged {
107            subject,
108            old: Box::new(CertInfo {
109                spki_sha256: spki,
110                ..CertInfo::default()
111            }),
112            new: Box::new(rejection.new),
113        },
114        None => TrustProblem::UntrustedCertificate {
115            subject,
116            new: Box::new(rejection.new),
117        },
118    })
119}
120
121/// Whether a webpki failure is one a pinned key may stand in for: the chain
122/// does not lead to a known root (or is signed by a key that is not one), or
123/// the name is not the one on the certificate. Expiry, revocation, a wrong
124/// purpose and the like are never excused by a pin.
125pub fn pin_can_excuse(error: &TlsError) -> bool {
126    matches!(
127        error,
128        TlsError::InvalidCertificate(
129            CertificateError::UnknownIssuer
130                | CertificateError::BadSignature
131                | CertificateError::NotValidForName
132                | CertificateError::NotValidForNameContext { .. }
133        )
134    )
135}
136
137/// The decision, separated from rustls so it can be tested as a table.
138#[derive(Debug, PartialEq, Eq)]
139pub enum Decision {
140    Accept,
141    /// Refuse with the webpki error, or (`pin_mismatch`) because the key is
142    /// not the pinned one.
143    Reject {
144        pin_mismatch: bool,
145    },
146}
147
148pub fn decide(
149    webpki_ok: bool,
150    excusable: bool,
151    policy: Option<&TlsPolicy>,
152    spki: &str,
153) -> Decision {
154    match policy {
155        None => {
156            if webpki_ok {
157                Decision::Accept
158            } else {
159                Decision::Reject {
160                    pin_mismatch: false,
161                }
162            }
163        }
164        Some(TlsPolicy::Tofu { spki: pinned }) => {
165            if webpki_ok || (excusable && pinned == spki) {
166                Decision::Accept
167            } else {
168                Decision::Reject {
169                    pin_mismatch: excusable && pinned != spki,
170                }
171            }
172        }
173        Some(TlsPolicy::Strict { spki: pinned }) => {
174            if pinned != spki {
175                Decision::Reject { pin_mismatch: true }
176            } else if webpki_ok || excusable {
177                Decision::Accept
178            } else {
179                Decision::Reject {
180                    pin_mismatch: false,
181                }
182            }
183        }
184    }
185}
186
187#[derive(Debug)]
188pub struct GuardedVerifier {
189    inner: Arc<WebPkiServerVerifier>,
190}
191
192impl GuardedVerifier {
193    /// A verifier over `roots`.
194    pub fn new(roots: RootCertStore) -> Result<Self, String> {
195        let provider = Arc::new(rustls::crypto::ring::default_provider());
196        let inner = WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider)
197            .build()
198            .map_err(|e| e.to_string())?;
199        Ok(Self { inner })
200    }
201
202    /// The process-wide verifier over the webpki roots plus the system's.
203    pub fn system() -> Result<Arc<Self>, String> {
204        static SHARED: OnceLock<Result<Arc<GuardedVerifier>, String>> = OnceLock::new();
205        SHARED
206            .get_or_init(|| {
207                let mut roots = RootCertStore::empty();
208                roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
209                for cert in rustls_native_certs::load_native_certs().certs {
210                    let _ = roots.add(cert);
211                }
212                GuardedVerifier::new(roots).map(Arc::new)
213            })
214            .clone()
215    }
216}
217
218fn host_of(name: &ServerName<'_>) -> String {
219    name.to_str().to_ascii_lowercase()
220}
221
222impl ServerCertVerifier for GuardedVerifier {
223    fn verify_server_cert(
224        &self,
225        end_entity: &CertificateDer<'_>,
226        intermediates: &[CertificateDer<'_>],
227        server_name: &ServerName<'_>,
228        ocsp_response: &[u8],
229        now: UnixTime,
230    ) -> Result<ServerCertVerified, TlsError> {
231        let host = host_of(server_name);
232        let info = CertInfo::from_der(end_entity.as_ref()).unwrap_or_default();
233        lock(observed_map()).insert(host.clone(), info.clone());
234        let webpki = self.inner.verify_server_cert(
235            end_entity,
236            intermediates,
237            server_name,
238            ocsp_response,
239            now,
240        );
241        let policy = policy_of(&host);
242        let decision = decide(
243            webpki.is_ok(),
244            webpki.as_ref().err().is_some_and(pin_can_excuse),
245            policy.as_ref(),
246            &info.spki_sha256,
247        );
248        match decision {
249            Decision::Accept => {
250                lock(rejected_map()).remove(&host);
251                Ok(webpki.unwrap_or_else(|_| ServerCertVerified::assertion()))
252            }
253            Decision::Reject { .. } => {
254                lock(rejected_map()).insert(
255                    host,
256                    Rejection {
257                        new: info,
258                        pinned: policy.map(|p| p.spki().to_string()),
259                    },
260                );
261                // The pin refused a chain webpki accepted: say so with the
262                // closest standard error.
263                Err(webpki.err().unwrap_or(TlsError::InvalidCertificate(
264                    CertificateError::ApplicationVerificationFailure,
265                )))
266            }
267        }
268    }
269
270    fn verify_tls12_signature(
271        &self,
272        message: &[u8],
273        cert: &CertificateDer<'_>,
274        dss: &DigitallySignedStruct,
275    ) -> Result<HandshakeSignatureValid, TlsError> {
276        self.inner.verify_tls12_signature(message, cert, dss)
277    }
278
279    fn verify_tls13_signature(
280        &self,
281        message: &[u8],
282        cert: &CertificateDer<'_>,
283        dss: &DigitallySignedStruct,
284    ) -> Result<HandshakeSignatureValid, TlsError> {
285        self.inner.verify_tls13_signature(message, cert, dss)
286    }
287
288    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
289        self.inner.supported_verify_schemes()
290    }
291}
292
293/// The `rustls` client configuration every real transport uses.
294pub fn client_config() -> Result<rustls::ClientConfig, String> {
295    let provider = Arc::new(rustls::crypto::ring::default_provider());
296    let verifier = GuardedVerifier::system()?;
297    Ok(rustls::ClientConfig::builder_with_provider(provider)
298        .with_safe_default_protocol_versions()
299        .map_err(|e| e.to_string())?
300        .dangerous()
301        .with_custom_certificate_verifier(verifier)
302        .with_no_client_auth())
303}
304
305#[cfg(test)]
306mod tests {
307    use super::super::fixtures::*;
308    use super::*;
309
310    fn der(hex: &str) -> CertificateDer<'static> {
311        let bytes: Vec<u8> = (0..hex.len())
312            .step_by(2)
313            .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
314            .collect();
315        CertificateDer::from(bytes)
316    }
317
318    /// 2027-01-01: after every fixture's `notBefore`, long before its end.
319    fn now() -> UnixTime {
320        UnixTime::since_unix_epoch(std::time::Duration::from_secs(1_798_761_600))
321    }
322
323    fn verifier() -> GuardedVerifier {
324        let mut roots = RootCertStore::empty();
325        roots.add(der(CA)).unwrap();
326        GuardedVerifier::new(roots).unwrap()
327    }
328
329    fn check(v: &GuardedVerifier, leaf: &str, host: &'static str) -> Result<(), TlsError> {
330        v.verify_server_cert(
331            &der(leaf),
332            &[],
333            &ServerName::try_from(host).unwrap(),
334            &[],
335            now(),
336        )
337        .map(|_| ())
338    }
339
340    #[test]
341    fn cert_fields_are_read_and_the_key_fingerprint_matches_openssl() {
342        let info = CertInfo::from_der(der(SELF).as_ref()).unwrap();
343        assert_eq!(info.spki_sha256, SELF_SPKI);
344        assert_eq!(info.subject, "CN=self.test, O=Fixture Self");
345        assert_eq!(info.issuer, info.subject);
346        assert!(
347            info.not_before.starts_with("2026-11-"),
348            "{}",
349            info.not_before
350        );
351        assert!(info.not_after.starts_with("2126-"), "{}", info.not_after);
352        assert!(CertInfo::from_der(&[1, 2, 3]).is_none());
353    }
354
355    #[test]
356    fn a_chain_to_a_known_root_passes_with_no_policy() {
357        let v = verifier();
358        assert!(check(&v, GOOD, "good.test").is_ok());
359        // The name is still checked: webpki says no.
360        assert!(check(&v, GOOD, "other.test").is_err());
361    }
362
363    #[test]
364    fn self_signed_is_refused_until_its_key_is_pinned_and_then_only_for_that_key() {
365        let v = verifier();
366        let spki = CertInfo::from_der(der(SELF).as_ref()).unwrap().spki_sha256;
367        // First use: refused, and the refusal carries what was presented.
368        assert!(check(&v, SELF, "self.test").is_err());
369        let problem = problem_for("self.test").expect("a refusal was recorded");
370        match problem {
371            TrustProblem::UntrustedCertificate { new, .. } => assert_eq!(new.spki_sha256, spki),
372            other => panic!("{other:?}"),
373        }
374        // Pinned (TOFU): accepted.
375        set_policy("self.test", Some(TlsPolicy::Tofu { spki: spki.clone() }));
376        assert!(check(&v, SELF, "self.test").is_ok());
377        // A different key under the same name: refused, reported as a change.
378        set_policy(
379            "self.test",
380            Some(TlsPolicy::Tofu {
381                spki: "00".repeat(32),
382            }),
383        );
384        assert!(check(&v, SELF, "self.test").is_err());
385        assert!(matches!(
386            problem_for("self.test"),
387            Some(TrustProblem::CertificateChanged { .. })
388        ));
389        set_policy("self.test", None);
390    }
391
392    #[test]
393    fn strict_requires_the_pinned_key_even_when_the_chain_validates() {
394        let v = verifier();
395        let good = CertInfo::from_der(der(GOOD).as_ref()).unwrap().spki_sha256;
396        set_policy("good.test", Some(TlsPolicy::Strict { spki: good }));
397        assert!(check(&v, GOOD, "good.test").is_ok());
398        // The CA re-issued the name on a new key: valid chain, wrong pin.
399        assert!(check(&v, ROTATED, "good.test").is_err());
400        assert!(matches!(
401            problem_for("good.test"),
402            Some(TrustProblem::CertificateChanged { .. })
403        ));
404        // Under TOFU the same rotation is fine: the chain validates.
405        let old = CertInfo::from_der(der(GOOD).as_ref()).unwrap().spki_sha256;
406        set_policy("good.test", Some(TlsPolicy::Tofu { spki: old }));
407        assert!(check(&v, ROTATED, "good.test").is_ok());
408        set_policy("good.test", None);
409    }
410
411    #[test]
412    fn the_decision_table() {
413        let tofu = TlsPolicy::Tofu { spki: "aa".into() };
414        let strict = TlsPolicy::Strict { spki: "aa".into() };
415        use Decision::*;
416        assert_eq!(decide(true, false, None, "aa"), Accept);
417        assert_eq!(
418            decide(false, true, None, "aa"),
419            Reject {
420                pin_mismatch: false
421            }
422        );
423        assert_eq!(decide(false, true, Some(&tofu), "aa"), Accept);
424        assert_eq!(
425            decide(false, true, Some(&tofu), "bb"),
426            Reject { pin_mismatch: true }
427        );
428        // Expiry and the like are never excused by a pin.
429        assert_eq!(
430            decide(false, false, Some(&tofu), "aa"),
431            Reject {
432                pin_mismatch: false
433            }
434        );
435        assert_eq!(
436            decide(true, false, Some(&strict), "bb"),
437            Reject { pin_mismatch: true }
438        );
439        assert_eq!(decide(false, true, Some(&strict), "aa"), Accept);
440        assert_eq!(
441            decide(false, false, Some(&strict), "aa"),
442            Reject {
443                pin_mismatch: false
444            }
445        );
446    }
447
448    /// Runs a TLS handshake between a client using `verifier` and a server
449    /// presenting `cert_hex` but signing with `key_hex`, entirely in memory.
450    fn handshake(
451        verifier: GuardedVerifier,
452        host: &'static str,
453        cert_hex: &str,
454        key_hex: &str,
455    ) -> Result<(), String> {
456        use rustls::pki_types::PrivatePkcs8KeyDer;
457        use rustls::sign::CertifiedKey;
458        let provider = Arc::new(rustls::crypto::ring::default_provider());
459        let key_bytes: Vec<u8> = (0..key_hex.len())
460            .step_by(2)
461            .map(|i| u8::from_str_radix(&key_hex[i..i + 2], 16).unwrap())
462            .collect();
463        let signing = provider
464            .key_provider
465            .load_private_key(PrivatePkcs8KeyDer::from(key_bytes).into())
466            .unwrap();
467        // `CertifiedKey::new` does not check that the key belongs to the
468        // certificate: a server that holds the wrong key is exactly the case.
469        let certified = Arc::new(CertifiedKey::new(vec![der(cert_hex)], signing));
470        #[derive(Debug)]
471        struct One(Arc<CertifiedKey>);
472        impl rustls::server::ResolvesServerCert for One {
473            fn resolve(&self, _: rustls::server::ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
474                Some(self.0.clone())
475            }
476        }
477        let server_cfg = rustls::ServerConfig::builder_with_provider(provider.clone())
478            .with_safe_default_protocol_versions()
479            .unwrap()
480            .with_no_client_auth()
481            .with_cert_resolver(Arc::new(One(certified)));
482        let client_cfg = rustls::ClientConfig::builder_with_provider(provider)
483            .with_safe_default_protocol_versions()
484            .unwrap()
485            .dangerous()
486            .with_custom_certificate_verifier(Arc::new(verifier))
487            .with_no_client_auth();
488        let mut client = rustls::ClientConnection::new(
489            Arc::new(client_cfg),
490            ServerName::try_from(host).unwrap(),
491        )
492        .unwrap();
493        let mut server = rustls::ServerConnection::new(Arc::new(server_cfg)).unwrap();
494        for _ in 0..20 {
495            let mut buf = Vec::new();
496            while client.wants_write() {
497                client.write_tls(&mut buf).unwrap();
498            }
499            if !buf.is_empty() {
500                server.read_tls(&mut buf.as_slice()).unwrap();
501                server
502                    .process_new_packets()
503                    .map_err(|e| format!("server: {e}"))?;
504            }
505            let mut buf = Vec::new();
506            while server.wants_write() {
507                server.write_tls(&mut buf).unwrap();
508            }
509            if !buf.is_empty() {
510                client.read_tls(&mut buf.as_slice()).unwrap();
511                client
512                    .process_new_packets()
513                    .map_err(|e| format!("client: {e}"))?;
514            }
515            if !client.is_handshaking() && !server.is_handshaking() {
516                return Ok(());
517            }
518        }
519        Err("handshake did not finish".into())
520    }
521
522    #[test]
523    fn the_handshake_signature_is_still_checked_so_a_pin_is_not_a_bearer_token() {
524        // The pin matches the certificate presented, and the certificate
525        // passes `verify_server_cert` -- but the server cannot sign with the
526        // key it names. Only the delegated signature check catches that.
527        let spki = CertInfo::from_der(der(SELF).as_ref()).unwrap().spki_sha256;
528        set_policy("sig.test", Some(TlsPolicy::Tofu { spki }));
529        // Same certificate, key that is not its own: fails.
530        let forged = handshake(verifier(), "sig.test", SELF, GOOD_KEY);
531        // The owner of the key: succeeds.
532        let honest = handshake(verifier(), "sig.test", SELF, SELF_KEY);
533        set_policy("sig.test", None);
534        let err = forged.expect_err("a certificate replayed without its key must fail");
535        assert!(err.contains("client"), "{err}");
536        honest.expect("the real key completes the handshake");
537    }
538}