Skip to main content

s2_kit/connect/
tls.rs

1//! The TLS half of S2 Connect, which is where its trust model actually lives.
2//!
3//! # Why this module exists at all
4//!
5//! In a LAN there is no certificate authority. A heat pump discovered over DNS-SD answers
6//! on `https://EVSE1038.local` with a certificate it minted itself, and no amount of
7//! public PKI will ever say anything useful about it. S2 Connect's answer is not to
8//! weaken TLS but to move the authentication somewhere else: the pairing token, which the
9//! end user carried from one device to the other, and which is mixed with the server's
10//! **leaf certificate fingerprint** to produce the challenge response
11//! (`S2C §Challenge response process`).
12//!
13//! That inverts the usual order. The certificate is not trusted and then used; it is used
14//! and then, if the HMAC comes out right, trusted:
15//!
16//! > `S2C §4. HTTPS Client checks clientHmacChallengeResponse`: "in case of a local
17//! > server, the TLS certificate fingerprint is part of the challenge. So if the challenge
18//! > succeeds, the certificate fingerprint is correct, and the certificate can be trusted.
19//! > The client **must** pin the self-signed CA (root) certificate, and trust this
20//! > certificate for the remainder of the pairing relation."
21//!
22//! So exactly one operation in this crate talks to a server whose certificate has not been
23//! verified — LAN pairing — and it is the operation whose whole purpose is to find out
24//! whether that certificate is the right one. Everything afterwards runs against a pinned
25//! CA. [`TlsPolicy`] is that distinction made structural, so a driver cannot accidentally
26//! carry the pairing posture into a session.
27//!
28//! # Two fingerprints that are not the same fingerprint
29//!
30//! The HMAC binds the **leaf**; `ConnectionDetails.certificateFingerprint` pins the **CA**
31//! (erratum E19). They are a paragraph apart in the specification and
32//! named almost identically. Conflating them yields a pairing that verifies and a
33//! connection that does not, so they are kept apart here: [`CapturedIdentity::leaf`] is the
34//! first and [`CapturedIdentity::root`] — what [`TlsPolicy::Pinned`] holds — the second.
35//!
36//! # A pin is 32 bytes
37//!
38//! [`TlsPolicy::Pinned`] holds a fingerprint, not a certificate: the same type serves the
39//! CA captured during a LAN pairing (`S2C §4`) and the `certificateFingerprint` a 6B
40//! client posts (`S2C §8B`), and it is what a host persists beside the access token. A
41//! handshake passes when the presented leaf *is* the pinned certificate, or when a
42//! certificate in the presented chain is, and the leaf validates against it as the only
43//! trust anchor — names, validity and signatures included.
44
45use alloc::string::String;
46use alloc::sync::Arc;
47// `Vec` comes from the `std` prelude: both features that enable this module imply `std`.
48
49#[cfg(feature = "tokio")]
50use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
51use rustls::crypto::CryptoProvider;
52#[cfg(feature = "tokio")]
53use rustls::crypto::{verify_tls12_signature, verify_tls13_signature};
54use rustls::pki_types::CertificateDer;
55#[cfg(feature = "tokio")]
56use rustls::pki_types::{ServerName, UnixTime};
57#[cfg(feature = "tokio")]
58use rustls::{DigitallySignedStruct, Error as TlsError, RootCertStore, SignatureScheme};
59
60use super::proto::HmacBinding;
61
62/// A SHA-256 certificate fingerprint: the 32 bytes, not the string.
63///
64/// Kept as bytes because that is what goes into the HMAC. The specification writes them
65/// as hexadecimal, usually with colons, and "must be decoded as hexadecimal string before
66/// it can be used as input" — a step that is easy to skip and produces a response that is
67/// wrong in a way nothing else reports.
68#[derive(Clone, Copy, PartialEq, Eq, Hash)]
69pub struct Fingerprint([u8; 32]);
70
71impl Fingerprint {
72    /// The fingerprint of a DER-encoded certificate.
73    #[must_use]
74    pub fn of(der: &CertificateDer<'_>) -> Self {
75        use sha2::Digest as _;
76        let digest = sha2::Sha256::digest(der.as_ref());
77        let mut bytes = [0u8; 32];
78        bytes.copy_from_slice(&digest);
79        Self(bytes)
80    }
81
82    /// Parse one written as hexadecimal, with or without colons.
83    pub fn parse(hex: &str) -> Result<Self, Error> {
84        match HmacBinding::from_hex_fingerprint(hex)? {
85            HmacBinding::LeafFingerprint(bytes) => {
86                let mut out = [0u8; 32];
87                if bytes.len() != 32 {
88                    return Err(Error::Fingerprint);
89                }
90                out.copy_from_slice(&bytes);
91                Ok(Self(out))
92            }
93            HmacBinding::DomainName(_) => Err(Error::Fingerprint),
94        }
95    }
96
97    /// A fingerprint from its 32 bytes, as stored or as read from
98    /// [`ConnectionDetails::ca_fingerprint`](super::proto::ConnectionDetails::ca_fingerprint).
99    #[must_use]
100    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
101        Self(bytes)
102    }
103
104    /// The bytes.
105    #[must_use]
106    pub const fn as_bytes(&self) -> &[u8; 32] {
107        &self.0
108    }
109
110    /// Lowercase hexadecimal with no separators: the form that goes on the wire.
111    ///
112    /// `S2C §Challenge response process`: "SHA256 certificate fingerprints are encoded
113    /// into a hexadecimal string". No colons — `s2energy-connection` refuses them — and
114    /// [`parse`](Self::parse) still reads a fingerprint written either way.
115    #[must_use]
116    pub fn to_hex(&self) -> String {
117        use core::fmt::Write as _;
118        let mut out = String::with_capacity(64);
119        for b in &self.0 {
120            // Writing into a String cannot fail.
121            let _ = write!(out, "{b:02x}");
122        }
123        out
124    }
125
126    /// The HMAC binding this fingerprint makes, for a LAN pairing server.
127    #[must_use]
128    pub fn binding(&self) -> HmacBinding {
129        HmacBinding::LeafFingerprint(self.0.to_vec())
130    }
131
132    /// Whether two fingerprints match, compared in constant time.
133    ///
134    /// A fingerprint is not a secret, but comparing it in constant time costs nothing and
135    /// removes the question.
136    #[must_use]
137    pub fn matches(&self, other: &Self) -> bool {
138        use subtle::ConstantTimeEq as _;
139        self.0.ct_eq(&other.0).into()
140    }
141}
142
143impl core::fmt::Debug for Fingerprint {
144    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
145        write!(f, "Fingerprint({})", self.to_hex())
146    }
147}
148
149impl core::fmt::Display for Fingerprint {
150    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
151        f.write_str(&self.to_hex())
152    }
153}
154
155#[cfg(feature = "tokio")]
156#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
157/// What a handshake revealed about the server.
158#[derive(Debug, Clone)]
159pub struct CapturedIdentity {
160    /// The leaf certificate's fingerprint — the one the HMAC binds to.
161    pub leaf: Fingerprint,
162    /// The fingerprint of the topmost certificate the server presented, which is what
163    /// gets pinned afterwards ([`TlsPolicy::Pinned`]).
164    ///
165    /// For the usual LAN arrangement — a self-signed CA and one leaf it signed, both sent —
166    /// this is the CA. A server may leave its root out of the chain (RFC 8446 §4.4.2
167    /// allows it); for one that presented only a leaf, this is that leaf, and for one that
168    /// sent a leaf and an intermediate, the intermediate. Both are still sound — it is
169    /// what the HMAC-verified leaf chains to — but they need re-pairing when that
170    /// certificate rotates, which a pinned self-signed CA does not.
171    ///
172    /// Taking it from **this** chain matters. The specification says to pin "the
173    /// self-signed CA (root) certificate" once the challenge succeeds, but the challenge
174    /// binds the *leaf* — so a certificate obtained any other way would be pinned on no
175    /// evidence at all (erratum E22).
176    pub root: Fingerprint,
177    /// The whole chain, leaf first, for a caller that wants to look at it.
178    pub chain: Vec<CertificateDer<'static>>,
179}
180
181#[cfg(feature = "tokio")]
182#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
183/// How a connection decides whether to trust the server.
184#[derive(Debug, Clone)]
185pub enum TlsPolicy {
186    /// The public PKI, through the **platform's own trust store**. For WAN endpoints.
187    ///
188    /// Not a bundled root list: a WAN endpoint may well be behind a corporate middlebox
189    /// whose CA the operating system trusts and Mozilla's bundle has never heard of, and
190    /// an administrator who has distributed a root expects it to be used. Revocation and
191    /// local policy come with it for free, which a static list can never provide.
192    Web,
193    /// Exactly one certificate, by fingerprint. For every LAN connection after pairing,
194    /// and for a 6B communication client holding the `certificateFingerprint` it was sent.
195    Pinned(Fingerprint),
196    /// **Trust nothing, record everything.** For LAN *pairing* and nothing else.
197    ///
198    /// The handshake is allowed to succeed against any certificate, because at this point
199    /// in the protocol there is nothing to check it against; the challenge response that
200    /// follows is what decides whether the server was genuine, and it fails closed. See
201    /// the module documentation.
202    ///
203    /// Using this for anything other than the four pairing requests is a security bug: it
204    /// is an unauthenticated channel until the HMAC says otherwise, and the HMAC only says
205    /// anything during pairing.
206    LanPairingOnly,
207}
208
209#[cfg(feature = "tokio")]
210impl TlsPolicy {
211    /// Whether this policy actually authenticates the peer.
212    #[must_use]
213    pub const fn authenticates(&self) -> bool {
214        !matches!(self, TlsPolicy::LanPairingOnly)
215    }
216}
217
218#[cfg(feature = "tokio")]
219#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
220/// A `rustls` client configuration, and the identity the handshake captured.
221///
222/// The capture is shared with the verifier, so it fills in during the handshake and is
223/// readable afterwards without threading anything through the HTTP client.
224#[derive(Debug, Clone)]
225pub struct TlsClient {
226    config: Arc<rustls::ClientConfig>,
227    captured: Arc<Capture>,
228}
229
230#[cfg(feature = "tokio")]
231impl TlsClient {
232    /// Build a client configuration for a policy.
233    pub fn new(policy: &TlsPolicy) -> Result<Self, Error> {
234        let provider = default_provider()?;
235        let captured = Arc::new(Capture::default());
236
237        let builder = rustls::ClientConfig::builder_with_provider(provider.clone())
238            .with_safe_default_protocol_versions()
239            .map_err(|e| Error::Tls(e.to_string()))?;
240
241        let config = match policy {
242            TlsPolicy::Web => {
243                let inner = rustls_platform_verifier::Verifier::new(provider)
244                    .map_err(|e| Error::Tls(e.to_string()))?;
245                builder
246                    .dangerous()
247                    .with_custom_certificate_verifier(Arc::new(Recording {
248                        inner: Verifier::Real(Arc::new(inner)),
249                        captured: captured.clone(),
250                    }))
251                    .with_no_client_auth()
252            }
253            TlsPolicy::Pinned(pin) => builder
254                .dangerous()
255                .with_custom_certificate_verifier(Arc::new(Recording {
256                    inner: Verifier::Pinned {
257                        pin: *pin,
258                        provider,
259                    },
260                    captured: captured.clone(),
261                }))
262                .with_no_client_auth(),
263            TlsPolicy::LanPairingOnly => builder
264                .dangerous()
265                .with_custom_certificate_verifier(Arc::new(Recording {
266                    inner: Verifier::AcceptAnything(provider),
267                    captured: captured.clone(),
268                }))
269                .with_no_client_auth(),
270        };
271
272        Ok(Self {
273            config: Arc::new(config),
274            captured,
275        })
276    }
277
278    /// The configuration, to hand to `reqwest` or `tokio-rustls`.
279    #[must_use]
280    pub fn config(&self) -> Arc<rustls::ClientConfig> {
281        self.config.clone()
282    }
283
284    /// What the last handshake revealed, if one has happened.
285    #[must_use]
286    pub fn captured(&self) -> Option<CapturedIdentity> {
287        self.captured.get()
288    }
289
290    /// The leaf fingerprint the last handshake presented, as an HMAC binding.
291    ///
292    /// This is the `F` of `R = HMAC(C, T ‖ F)`, and it is available only after a request
293    /// has actually been made — which is why a pairing driver does the first request
294    /// before it can check anything.
295    #[must_use]
296    pub fn binding(&self) -> Option<HmacBinding> {
297        self.captured.get().map(|c| c.leaf.binding())
298    }
299
300    /// Whether every handshake so far presented the same leaf.
301    ///
302    /// A LAN pairing runs four requests against a connection pool. If the fingerprint
303    /// changes between them, something has moved underneath us and the attempt must not
304    /// continue — the HMAC was computed against a certificate that is no longer the one
305    /// answering.
306    #[must_use]
307    pub fn identity_is_stable(&self) -> bool {
308        !self.captured.changed()
309    }
310}
311
312#[cfg(feature = "tokio")]
313#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
314#[derive(Debug, Default)]
315struct Capture {
316    inner: std::sync::Mutex<Option<CapturedIdentity>>,
317    changed: core::sync::atomic::AtomicBool,
318}
319
320#[cfg(feature = "tokio")]
321impl Capture {
322    fn set(&self, identity: CapturedIdentity) {
323        let Ok(mut slot) = self.inner.lock() else {
324            // A poisoned lock means another thread panicked mid-capture. Treat the
325            // identity as unstable rather than pretending we know it.
326            self.changed
327                .store(true, core::sync::atomic::Ordering::Relaxed);
328            return;
329        };
330        if let Some(previous) = slot.as_ref()
331            && !previous.leaf.matches(&identity.leaf)
332        {
333            self.changed
334                .store(true, core::sync::atomic::Ordering::Relaxed);
335        }
336        *slot = Some(identity);
337    }
338
339    fn get(&self) -> Option<CapturedIdentity> {
340        self.inner.lock().ok()?.clone()
341    }
342
343    fn changed(&self) -> bool {
344        self.changed.load(core::sync::atomic::Ordering::Relaxed)
345    }
346}
347
348#[cfg(feature = "tokio")]
349#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
350#[derive(Debug)]
351enum Verifier {
352    Real(Arc<dyn ServerCertVerifier>),
353    Pinned {
354        pin: Fingerprint,
355        provider: Arc<CryptoProvider>,
356    },
357    AcceptAnything(Arc<CryptoProvider>),
358}
359
360#[cfg(feature = "tokio")]
361impl Verifier {
362    /// The provider whose signature algorithms check the handshake, for the two verifiers
363    /// that do not delegate to a real one.
364    fn provider(&self) -> Option<&Arc<CryptoProvider>> {
365        match self {
366            Verifier::Real(_) => None,
367            Verifier::Pinned { provider, .. } | Verifier::AcceptAnything(provider) => {
368                Some(provider)
369            }
370        }
371    }
372}
373
374/// The pinned-certificate check: the leaf is the pin, or a presented certificate is and the
375/// leaf validates against it as the only trust anchor.
376#[cfg(feature = "tokio")]
377fn verify_pinned(
378    pin: &Fingerprint,
379    provider: &Arc<CryptoProvider>,
380    end_entity: &CertificateDer<'_>,
381    intermediates: &[CertificateDer<'_>],
382    server_name: &ServerName<'_>,
383    ocsp_response: &[u8],
384    now: UnixTime,
385) -> Result<ServerCertVerified, TlsError> {
386    // The exact certificate that was pinned: nothing to chain, and the handshake signature
387    // (checked separately, against this certificate's key) proves the server holds it.
388    if Fingerprint::of(end_entity).matches(pin) {
389        return Ok(ServerCertVerified::assertion());
390    }
391    let Some(anchor) = intermediates
392        .iter()
393        .find(|cert| Fingerprint::of(cert).matches(pin))
394    else {
395        return Err(TlsError::InvalidCertificate(
396            rustls::CertificateError::UnknownIssuer,
397        ));
398    };
399    let mut roots = RootCertStore::empty();
400    roots
401        .add(anchor.clone().into_owned())
402        .map_err(|_| TlsError::InvalidCertificate(rustls::CertificateError::BadEncoding))?;
403    let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(
404        Arc::new(roots),
405        provider.clone(),
406    )
407    .build()
408    .map_err(|e| TlsError::General(e.to_string()))?;
409    verifier.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
410}
411
412#[cfg(feature = "tokio")]
413#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
414/// Wraps a verifier so that the chain is recorded whatever the verdict.
415#[derive(Debug)]
416struct Recording {
417    inner: Verifier,
418    captured: Arc<Capture>,
419}
420
421#[cfg(feature = "tokio")]
422impl ServerCertVerifier for Recording {
423    fn verify_server_cert(
424        &self,
425        end_entity: &CertificateDer<'_>,
426        intermediates: &[CertificateDer<'_>],
427        server_name: &ServerName<'_>,
428        ocsp_response: &[u8],
429        now: UnixTime,
430    ) -> Result<ServerCertVerified, TlsError> {
431        let leaf = end_entity.clone().into_owned();
432        let mut chain = alloc::vec![leaf.clone()];
433        chain.extend(intermediates.iter().map(|c| c.clone().into_owned()));
434        // Record before verifying: a driver that wants to report *which* certificate was
435        // refused needs it even when the verdict is no. A server that sent only a leaf
436        // roots at that leaf, which is what a self-signed single certificate means.
437        self.captured.set(CapturedIdentity {
438            leaf: Fingerprint::of(end_entity),
439            root: Fingerprint::of(chain.last().unwrap_or(&leaf)),
440            chain,
441        });
442
443        match &self.inner {
444            Verifier::Real(inner) => {
445                inner.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
446            }
447            Verifier::Pinned { pin, provider } => verify_pinned(
448                pin,
449                provider,
450                end_entity,
451                intermediates,
452                server_name,
453                ocsp_response,
454                now,
455            ),
456            // The whole point: no trust anchor exists yet, and the HMAC that follows is
457            // what decides. See `TlsPolicy::LanPairingOnly`.
458            Verifier::AcceptAnything(_) => Ok(ServerCertVerified::assertion()),
459        }
460    }
461
462    fn verify_tls12_signature(
463        &self,
464        message: &[u8],
465        cert: &CertificateDer<'_>,
466        dss: &DigitallySignedStruct,
467    ) -> Result<HandshakeSignatureValid, TlsError> {
468        match (&self.inner, self.inner.provider()) {
469            (Verifier::Real(inner), _) => inner.verify_tls12_signature(message, cert, dss),
470            // Still a real signature check: an attacker must at least hold the key for
471            // the certificate he presented, so he cannot replay somebody else's.
472            (_, Some(provider)) => verify_tls12_signature(
473                message,
474                cert,
475                dss,
476                &provider.signature_verification_algorithms,
477            ),
478            (_, None) => Err(TlsError::General("no signature verifier".into())),
479        }
480    }
481
482    fn verify_tls13_signature(
483        &self,
484        message: &[u8],
485        cert: &CertificateDer<'_>,
486        dss: &DigitallySignedStruct,
487    ) -> Result<HandshakeSignatureValid, TlsError> {
488        match (&self.inner, self.inner.provider()) {
489            (Verifier::Real(inner), _) => inner.verify_tls13_signature(message, cert, dss),
490            // Still a real signature check: an attacker must at least hold the key for
491            // the certificate he presented, so he cannot replay somebody else's.
492            (_, Some(provider)) => verify_tls13_signature(
493                message,
494                cert,
495                dss,
496                &provider.signature_verification_algorithms,
497            ),
498            (_, None) => Err(TlsError::General("no signature verifier".into())),
499        }
500    }
501
502    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
503        match (&self.inner, self.inner.provider()) {
504            (Verifier::Real(inner), _) => inner.supported_verify_schemes(),
505            (_, Some(provider)) => provider
506                .signature_verification_algorithms
507                .supported_schemes(),
508            (_, None) => Vec::new(),
509        }
510    }
511}
512
513/// The crypto provider, installed if the process has not installed one.
514///
515/// `rustls` requires a process-wide default before any configuration can be built and
516/// panics if two are installed. Doing it here, once, keeps that out of every consumer's
517/// `main`.
518pub fn default_provider() -> Result<Arc<CryptoProvider>, Error> {
519    // The application's choice always wins. A library that installs a provider over one
520    // the application already chose would give it two crypto stacks and silently use the
521    // wrong one; `install_default` also panics on a second call, which is why this is a
522    // read first and a write second.
523    if let Some(provider) = CryptoProvider::get_default() {
524        return Ok(provider.clone());
525    }
526
527    // Otherwise fall back to whichever this build bundled. `aws-lc-rs` wins when both are
528    // enabled, because a build that went to the trouble of asking for it wanted it.
529    #[cfg(feature = "tls-aws-lc-rs")]
530    let bundled = Some(rustls::crypto::aws_lc_rs::default_provider());
531    #[cfg(all(feature = "tls-ring", not(feature = "tls-aws-lc-rs")))]
532    let bundled = Some(rustls::crypto::ring::default_provider());
533    #[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc-rs")))]
534    let bundled: Option<CryptoProvider> = None;
535
536    let Some(provider) = bundled else {
537        return Err(Error::Tls(
538            "no TLS crypto provider: build with the `tls-ring` or `tls-aws-lc-rs` feature, \
539             or install one yourself with rustls::crypto::CryptoProvider::install_default"
540                .to_string(),
541        ));
542    };
543    // Racing with another thread is fine: whoever wins, we read back the winner.
544    let _ = provider.install_default();
545    CryptoProvider::get_default()
546        .cloned()
547        .ok_or_else(|| Error::Tls("no crypto provider could be installed".to_string()))
548}
549
550/// A self-signed CA and the leaf it signed: what a LAN endpoint needs to serve HTTPS.
551///
552/// S2 Connect expects LAN endpoints to mint their own, because there is no authority that
553/// could issue a certificate for `EVSE1038.local`. The pairing HMAC is what makes that
554/// safe, so generating one is not a shortcut — it is the specified arrangement.
555/// Minting a key pair needs a cryptography backend, so this type exists only when one is
556/// compiled in — `tls-ring` (the default) or `tls-aws-lc-rs`. An application that installs
557/// its own `rustls` provider and brings its own certificates does not need it.
558#[cfg(all(
559    feature = "connect-server",
560    any(feature = "tls-ring", feature = "tls-aws-lc-rs")
561))]
562#[cfg_attr(
563    docsrs,
564    doc(cfg(all(
565        feature = "connect-server",
566        any(feature = "tls-ring", feature = "tls-aws-lc-rs")
567    )))
568)]
569#[derive(Debug)]
570pub struct SelfSignedEndpoint {
571    /// The CA certificate, which a paired client pins.
572    pub ca: CertificateDer<'static>,
573    /// The chain to serve: leaf first, then the CA.
574    pub chain: Vec<CertificateDer<'static>>,
575    /// The leaf's private key.
576    pub key: rustls::pki_types::PrivateKeyDer<'static>,
577    /// The leaf's fingerprint — the `F` of the challenge response.
578    pub leaf: Fingerprint,
579}
580
581#[cfg(all(
582    feature = "connect-server",
583    any(feature = "tls-ring", feature = "tls-aws-lc-rs")
584))]
585impl SelfSignedEndpoint {
586    /// Mint a CA and a leaf valid for the given names.
587    ///
588    /// Names are whatever a client will dial: `EVSE1038.local`, `127.0.0.1`, an IPv6
589    /// literal. A name the certificate does not carry will fail once the client has
590    /// pinned the CA, even though it passed during pairing — which is a confusing failure
591    /// to debug later, so pass every name the endpoint answers on.
592    pub fn generate(names: impl IntoIterator<Item = String>) -> Result<Self, Error> {
593        use rcgen::{
594            BasicConstraints, CertificateParams, DnType, IsCa, KeyPair, KeyUsagePurpose, SanType,
595        };
596
597        let names: Vec<String> = names.into_iter().collect();
598        let Some(primary) = names.first().cloned() else {
599            return Err(Error::Tls(
600                "a certificate needs at least one name".to_string(),
601            ));
602        };
603
604        let ca_key = KeyPair::generate().map_err(|e| Error::Tls(e.to_string()))?;
605        let mut ca_params = CertificateParams::default();
606        ca_params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
607        ca_params.key_usages = alloc::vec![
608            KeyUsagePurpose::KeyCertSign,
609            KeyUsagePurpose::CrlSign,
610            KeyUsagePurpose::DigitalSignature,
611        ];
612        ca_params
613            .distinguished_name
614            .push(DnType::CommonName, "s2-kit LAN endpoint CA");
615        let ca_cert = ca_params
616            .self_signed(&ca_key)
617            .map_err(|e| Error::Tls(e.to_string()))?;
618
619        let leaf_key = KeyPair::generate().map_err(|e| Error::Tls(e.to_string()))?;
620        let mut leaf_params = CertificateParams::default();
621        leaf_params
622            .distinguished_name
623            .push(DnType::CommonName, primary);
624        for name in &names {
625            let san = match name.parse::<core::net::IpAddr>() {
626                Ok(ip) => SanType::IpAddress(ip),
627                Err(_) => SanType::DnsName(
628                    name.clone()
629                        .try_into()
630                        .map_err(|_| Error::Tls(alloc::format!("{name} is not a usable name")))?,
631                ),
632            };
633            leaf_params.subject_alt_names.push(san);
634        }
635        let issuer = rcgen::Issuer::new(ca_params, ca_key);
636        let leaf_cert = leaf_params
637            .signed_by(&leaf_key, &issuer)
638            .map_err(|e| Error::Tls(e.to_string()))?;
639
640        let leaf_der = leaf_cert.der().clone();
641        let ca_der = ca_cert.der().clone();
642        Ok(Self {
643            leaf: Fingerprint::of(&leaf_der),
644            chain: alloc::vec![leaf_der, ca_der.clone()],
645            ca: ca_der,
646            key: rustls::pki_types::PrivateKeyDer::Pkcs8(leaf_key.serialize_der().into()),
647        })
648    }
649
650    /// A `rustls` server configuration serving this chain.
651    pub fn server_config(&self) -> Result<Arc<rustls::ServerConfig>, Error> {
652        let provider = default_provider()?;
653        let config = rustls::ServerConfig::builder_with_provider(provider)
654            .with_safe_default_protocol_versions()
655            .map_err(|e| Error::Tls(e.to_string()))?
656            .with_no_client_auth()
657            .with_single_cert(self.chain.clone(), self.key.clone_key())
658            .map_err(|e| Error::Tls(e.to_string()))?;
659        Ok(Arc::new(config))
660    }
661}
662
663/// Something went wrong setting up or inspecting TLS.
664#[derive(Debug, thiserror::Error)]
665#[non_exhaustive]
666pub enum Error {
667    /// The fingerprint is not 32 bytes of hexadecimal.
668    #[error("not a SHA-256 certificate fingerprint")]
669    Fingerprint,
670    /// `rustls` refused the configuration, or no provider could be installed.
671    #[error("TLS: {0}")]
672    Tls(String),
673}
674
675impl From<super::proto::ConnectError> for Error {
676    fn from(_: super::proto::ConnectError) -> Self {
677        Error::Fingerprint
678    }
679}
680
681use alloc::string::ToString as _;
682
683#[cfg(test)]
684mod tests {
685    use super::*;
686
687    #[test]
688    fn a_fingerprint_round_trips_through_the_form_tools_print() {
689        let der = CertificateDer::from(alloc::vec![1u8, 2, 3, 4]);
690        let fp = Fingerprint::of(&der);
691        let text = fp.to_hex();
692        assert_eq!(text.len(), 64, "32 bytes, plain hexadecimal");
693        assert_eq!(text, text.to_lowercase());
694        assert_eq!(Fingerprint::parse(&text).unwrap(), fp);
695        // And with colons and in capitals, which is how openssl prints them.
696        let colons = text
697            .as_bytes()
698            .chunks(2)
699            .map(|pair| core::str::from_utf8(pair).unwrap().to_uppercase())
700            .collect::<Vec<_>>()
701            .join(":");
702        assert_eq!(Fingerprint::parse(&colons).unwrap(), fp);
703        assert!(fp.matches(&Fingerprint::of(&der)));
704    }
705
706    #[test]
707    fn a_fingerprint_is_the_binding_the_hmac_takes() {
708        let der = CertificateDer::from(alloc::vec![9u8; 64]);
709        let fp = Fingerprint::of(&der);
710        let HmacBinding::LeafFingerprint(bytes) = fp.binding() else {
711            panic!("a leaf fingerprint binds as a leaf fingerprint");
712        };
713        // Not the hex string: "must be decoded as hexadecimal string before it can be
714        // used as input".
715        assert_eq!(bytes.len(), 32);
716        assert_eq!(&bytes[..], fp.as_bytes());
717    }
718
719    #[test]
720    fn something_that_is_not_a_fingerprint_is_refused() {
721        assert!(Fingerprint::parse("").is_err());
722        assert!(Fingerprint::parse("AA:BB").is_err());
723        assert!(Fingerprint::parse("not hexadecimal at all").is_err());
724        // The right length of the wrong thing.
725        assert!(Fingerprint::parse(&"zz".repeat(32)).is_err());
726    }
727
728    #[cfg(feature = "tokio")]
729    #[test]
730    fn only_one_policy_declines_to_authenticate_and_it_says_so() {
731        assert!(TlsPolicy::Web.authenticates());
732        assert!(!TlsPolicy::LanPairingOnly.authenticates());
733        let der = CertificateDer::from(alloc::vec![1u8, 2, 3]);
734        assert!(TlsPolicy::Pinned(Fingerprint::of(&der)).authenticates());
735    }
736
737    /// Every configuration this crate builds names its provider, so `rustls`'s own
738    /// implicit lookup — which panics when the crate features are empty or ambiguous — is
739    /// never reached, and a build with no provider gets an `Err` instead (D52).
740    #[cfg(feature = "tokio")]
741    #[test]
742    fn a_provider_is_chosen_explicitly_and_never_by_the_library() {
743        // A default build bundles one, so this must resolve without the application
744        // having installed anything — this is the assertion that fails if `tls-ring` ever
745        // stops reaching the `rustls` in the graph.
746        #[cfg(any(feature = "tls-ring", feature = "tls-aws-lc-rs"))]
747        {
748            let first = default_provider().expect("a bundled provider");
749            // Idempotent, and the second call reads back the first rather than racing to
750            // install a second one.
751            let second = default_provider().expect("the same provider again");
752            assert!(Arc::ptr_eq(&first, &second));
753            assert!(
754                CryptoProvider::get_default().is_some(),
755                "and it is the process-wide default afterwards"
756            );
757        }
758        // Without one it is an error a caller can report, not a panic inside rustls.
759        #[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc-rs")))]
760        {
761            if CryptoProvider::get_default().is_none() {
762                assert!(matches!(default_provider(), Err(Error::Tls(_))));
763            }
764        }
765    }
766
767    #[cfg(all(
768        feature = "tokio",
769        any(feature = "tls-ring", feature = "tls-aws-lc-rs")
770    ))]
771    #[test]
772    fn every_policy_builds_a_usable_configuration() {
773        assert!(TlsClient::new(&TlsPolicy::Web).is_ok());
774        assert!(TlsClient::new(&TlsPolicy::LanPairingOnly).is_ok());
775        // Nothing has been captured before a handshake, which is why a pairing driver
776        // must make its first request before it can check anything.
777        let client = TlsClient::new(&TlsPolicy::LanPairingOnly).unwrap();
778        assert!(client.captured().is_none());
779        assert!(client.binding().is_none());
780        assert!(client.identity_is_stable());
781    }
782
783    /// A build with no provider is supported: it is what an application that installs its
784    /// own asks for. Until it does, every policy fails the same way — an `Error::Tls`
785    /// naming the two features and `install_default`, at the call site.
786    #[cfg(all(
787        feature = "tokio",
788        not(any(feature = "tls-ring", feature = "tls-aws-lc-rs"))
789    ))]
790    #[test]
791    fn with_no_provider_every_policy_fails_the_same_readable_way() {
792        if CryptoProvider::get_default().is_some() {
793            return; // another test in this binary installed one first
794        }
795        for policy in [TlsPolicy::Web, TlsPolicy::LanPairingOnly] {
796            match TlsClient::new(&policy) {
797                Err(Error::Tls(message)) => {
798                    assert!(message.contains("tls-ring"), "unhelpful message: {message}");
799                    assert!(message.contains("install_default"), "{message}");
800                }
801                other => panic!("expected a readable TLS error, got {:?}", other.is_ok()),
802            }
803        }
804    }
805
806    #[cfg(feature = "tokio")]
807    #[test]
808    fn a_changed_leaf_mid_attempt_is_noticed() {
809        let capture = Capture::default();
810        let one = CertificateDer::from(alloc::vec![1u8; 32]);
811        let two = CertificateDer::from(alloc::vec![2u8; 32]);
812        let identity = |der: &CertificateDer<'static>| CapturedIdentity {
813            leaf: Fingerprint::of(der),
814            root: Fingerprint::of(der),
815            chain: alloc::vec![der.clone()],
816        };
817        capture.set(identity(&one));
818        assert!(!capture.changed());
819        capture.set(identity(&one));
820        assert!(!capture.changed(), "the same certificate twice is fine");
821        capture.set(identity(&two));
822        assert!(capture.changed(), "a different one is not");
823    }
824
825    #[cfg(feature = "connect-server")]
826    #[test]
827    fn a_lan_endpoint_can_mint_the_certificate_the_specification_expects() {
828        let endpoint =
829            SelfSignedEndpoint::generate(["EVSE1038.local".to_string(), "127.0.0.1".to_string()])
830                .expect("a self-signed CA and leaf");
831
832        // Leaf first, then the CA it was signed by — the order a server sends them.
833        assert_eq!(endpoint.chain.len(), 2);
834        assert_eq!(endpoint.chain[1], endpoint.ca);
835        // The fingerprint the HMAC binds to is the leaf's, not the CA's.
836        assert_eq!(endpoint.leaf, Fingerprint::of(&endpoint.chain[0]));
837        assert_ne!(endpoint.leaf, Fingerprint::of(&endpoint.ca));
838        assert!(endpoint.server_config().is_ok());
839
840        // A client that pins this CA builds.
841        #[cfg(feature = "tokio")]
842        assert!(TlsClient::new(&TlsPolicy::Pinned(Fingerprint::of(&endpoint.ca))).is_ok());
843    }
844
845    #[cfg(feature = "connect-server")]
846    #[test]
847    fn a_certificate_needs_a_name() {
848        assert!(SelfSignedEndpoint::generate([]).is_err());
849    }
850}