Skip to main content

isothrum_runner/
tls.rs

1//! How a TLS client trusts a server: by the system's trust store (the chain to a trusted
2//! authority, and the name in it), or by one certificate's SHA-256 fingerprint alone, for a server
3//! whose certificate is self-signed. A pinned certificate is still made to prove it holds its key:
4//! the handshake's signatures are checked against it as for any certificate; only the chain and
5//! the name are replaced by the fingerprint.
6//!
7//! [`Tls::new`] gives the `rustls` configuration of either, and, for a pinned one, the certificate
8//! the server offered once it was refused ([`Tls::refused`]): what an embedder shows a user asked
9//! to confirm a certificate, or told it changed.
10
11use std::fmt;
12use std::str::FromStr;
13use std::sync::{Arc, Mutex, PoisonError};
14
15use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
16use rustls::crypto::WebPkiSupportedAlgorithms;
17use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
18use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
19use sha2::{Digest, Sha256};
20
21/// A certificate's SHA-256 fingerprint. Written as upper-case hex pairs joined by colons (as
22/// Proxmox VE's web interface and `openssl x509 -fingerprint -sha256` show it); read with or
23/// without the colons, in any case.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub struct Fingerprint([u8; 32]);
26
27impl Fingerprint {
28    /// The fingerprint of the certificate `der` (its DER bytes).
29    #[must_use]
30    pub fn of(der: &[u8]) -> Fingerprint {
31        Fingerprint(Sha256::digest(der).into())
32    }
33
34    /// A fingerprint as typed or stored: 64 hex digits, with or without colons and spaces, in any
35    /// case; none for anything else.
36    #[must_use]
37    pub fn parse(text: &str) -> Option<Fingerprint> {
38        let mut digits = text.chars().filter(|c| *c != ':' && !c.is_whitespace()).map(|c| c.to_digit(16));
39        let mut bytes = [0u8; 32];
40        for byte in &mut bytes {
41            let (high, low) = (digits.next()??, digits.next()??);
42            *byte = u8::try_from(high * 16 + low).ok()?;
43        }
44        digits.next().is_none().then_some(Fingerprint(bytes))
45    }
46}
47
48impl fmt::Display for Fingerprint {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        for (i, byte) in self.0.iter().enumerate() {
51            if i > 0 {
52                f.write_str(":")?;
53            }
54            write!(f, "{byte:02X}")?;
55        }
56        Ok(())
57    }
58}
59
60impl FromStr for Fingerprint {
61    type Err = NotAFingerprint;
62
63    fn from_str(text: &str) -> Result<Fingerprint, NotAFingerprint> {
64        Fingerprint::parse(text).ok_or(NotAFingerprint)
65    }
66}
67
68impl serde::Serialize for Fingerprint {
69    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
70        s.collect_str(self)
71    }
72}
73
74impl<'de> serde::Deserialize<'de> for Fingerprint {
75    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Fingerprint, D::Error> {
76        let text = String::deserialize(d)?;
77        Fingerprint::parse(&text).ok_or_else(|| serde::de::Error::custom(NotAFingerprint))
78    }
79}
80
81/// Text that isn't a SHA-256 certificate fingerprint.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
83#[error("not a SHA-256 certificate fingerprint (64 hex digits, colons optional)")]
84pub struct NotAFingerprint;
85
86/// How a server's certificate is trusted.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum Trust {
89    /// By the system's trust store, as any HTTPS site.
90    System,
91    /// By its fingerprint alone; none before one was confirmed (every certificate is then
92    /// refused, and the one offered is told: [`Tls::refused`]).
93    Pinned(Option<Fingerprint>),
94}
95
96/// Why a pinned configuration refused a server's certificate.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum Refusal {
99    /// No certificate was confirmed for the server yet: this is the one it offers.
100    Unconfirmed {
101        /// The certificate the server offered.
102        presented: Fingerprint,
103    },
104    /// The server offered another certificate than the one pinned.
105    Changed {
106        /// The certificate pinned for it.
107        pinned: Fingerprint,
108        /// The one it offered.
109        presented: Fingerprint,
110    },
111}
112
113impl fmt::Display for Refusal {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        match self {
116            Refusal::Unconfirmed { presented } => write!(f, "the server's certificate (SHA-256 {presented}) isn't confirmed yet"),
117            Refusal::Changed { pinned, presented } => {
118                write!(f, "the server's certificate (SHA-256 {presented}) isn't the one pinned for it ({pinned})")
119            }
120        }
121    }
122}
123
124/// TLS couldn't be set up (the crypto provider refused the protocol versions or the verifier).
125#[derive(Debug, Clone, thiserror::Error)]
126#[error("TLS couldn't be set up: {0}")]
127pub struct TlsSetupError(String);
128
129/// The certificate a pinned connection was last offered.
130type Seen = Arc<Mutex<Option<Fingerprint>>>;
131
132/// A client's TLS configuration for one server, trusted as [`Trust`] says, and, pinned, the
133/// certificate that server last offered.
134#[derive(Debug, Clone)]
135pub struct Tls {
136    config: Arc<ClientConfig>,
137    pin: Option<Fingerprint>,
138    /// What a pinned configuration's verifier saw; none for the system's trust store.
139    seen: Option<Seen>,
140}
141
142impl Tls {
143    /// The configuration trusting the server as `trust` says (ring's crypto, TLS 1.2 and 1.3,
144    /// HTTP/1.1 offered by ALPN).
145    ///
146    /// # Errors
147    ///
148    /// The provider refuses the protocol versions, or the system's verifier can't be made.
149    pub fn new(trust: Trust) -> Result<Tls, TlsSetupError> {
150        let provider = Arc::new(rustls::crypto::ring::default_provider());
151        let builder = ClientConfig::builder_with_provider(Arc::clone(&provider))
152            .with_safe_default_protocol_versions()
153            .map_err(|e| TlsSetupError(e.to_string()))?;
154        let (mut config, pin, seen) = match trust {
155            Trust::System => {
156                let verifier = rustls_platform_verifier::Verifier::new(provider).map_err(|e| TlsSetupError(e.to_string()))?;
157                let config = builder.dangerous().with_custom_certificate_verifier(Arc::new(verifier)).with_no_client_auth();
158                (config, None, None)
159            }
160            Trust::Pinned(pin) => {
161                let seen = Seen::default();
162                let verifier = PinVerifier {
163                    pin,
164                    seen: Arc::clone(&seen),
165                    algorithms: provider.signature_verification_algorithms,
166                };
167                let config = builder.dangerous().with_custom_certificate_verifier(Arc::new(verifier)).with_no_client_auth();
168                (config, pin, Some(seen))
169            }
170        };
171        config.alpn_protocols = vec![b"http/1.1".to_vec()];
172        Ok(Tls {
173            config: Arc::new(config),
174            pin,
175            seen,
176        })
177    }
178
179    /// The `rustls` client configuration.
180    #[must_use]
181    pub fn config(&self) -> &ClientConfig {
182        &self.config
183    }
184
185    /// Why a connection made with this configuration failed on the server's certificate: none
186    /// confirmed yet, or not the pinned one. None when the certificate isn't why (or none was
187    /// offered, or the system's trust store judged it).
188    #[must_use]
189    pub fn refused(&self) -> Option<Refusal> {
190        refusal(self.pin, self.seen.as_ref()?)
191    }
192}
193
194/// Why a verifier pinned to `pin` refused the certificate it last saw (`seen`); none when it saw
195/// none, or the pinned one.
196fn refusal(pin: Option<Fingerprint>, seen: &Seen) -> Option<Refusal> {
197    let presented = (*seen.lock().unwrap_or_else(PoisonError::into_inner))?;
198    match pin {
199        None => Some(Refusal::Unconfirmed { presented }),
200        Some(pinned) if pinned != presented => Some(Refusal::Changed { pinned, presented }),
201        Some(_) => None,
202    }
203}
204
205/// Accepts the one certificate whose fingerprint is `pin` (none before one was confirmed), and
206/// records every certificate it is offered in `seen`.
207#[derive(Debug)]
208struct PinVerifier {
209    pin: Option<Fingerprint>,
210    seen: Seen,
211    algorithms: WebPkiSupportedAlgorithms,
212}
213
214impl ServerCertVerifier for PinVerifier {
215    fn verify_server_cert(
216        &self,
217        end_entity: &CertificateDer<'_>,
218        _intermediates: &[CertificateDer<'_>],
219        _server_name: &ServerName<'_>,
220        _ocsp: &[u8],
221        _now: UnixTime,
222    ) -> Result<ServerCertVerified, rustls::Error> {
223        let presented = Fingerprint::of(end_entity.as_ref());
224        *self.seen.lock().unwrap_or_else(PoisonError::into_inner) = Some(presented);
225        if self.pin == Some(presented) {
226            Ok(ServerCertVerified::assertion())
227        } else {
228            Err(rustls::Error::General("the server's certificate isn't the one pinned for it".to_owned()))
229        }
230    }
231
232    fn verify_tls12_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
233        rustls::crypto::verify_tls12_signature(message, cert, dss, &self.algorithms)
234    }
235
236    fn verify_tls13_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
237        rustls::crypto::verify_tls13_signature(message, cert, dss, &self.algorithms)
238    }
239
240    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
241        self.algorithms.supported_schemes()
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    const HEX: &str = "AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89";
250
251    #[test]
252    fn a_fingerprint_reads_as_typed_and_writes_as_proxmox_shows_it() {
253        let fp = Fingerprint::parse(HEX).unwrap();
254        assert_eq!(fp.to_string(), HEX);
255        assert_eq!(Fingerprint::parse(&HEX.replace(':', "").to_lowercase()), Some(fp));
256        assert_eq!(Fingerprint::parse(&format!(" {} ", HEX.replace(':', " "))), Some(fp));
257        assert_eq!(HEX.parse::<Fingerprint>(), Ok(fp));
258        for bad in ["", "AB:CD", &format!("{HEX}:00"), &HEX.replace('A', "G"), &HEX.replacen("AB", "ÀB", 1)] {
259            assert_eq!(Fingerprint::parse(bad), None, "{bad}");
260        }
261        let json = serde_json::to_string(&fp).unwrap();
262        assert_eq!(json, format!("\"{HEX}\""));
263        assert_eq!(serde_json::from_str::<Fingerprint>(&json).unwrap(), fp);
264        assert!(serde_json::from_str::<Fingerprint>("\"nope\"").is_err());
265    }
266
267    #[test]
268    fn a_fingerprint_is_the_certificates_sha256() {
269        // SHA-256 of the empty input.
270        assert_eq!(
271            Fingerprint::of(b"").to_string(),
272            "E3:B0:C4:42:98:FC:1C:14:9A:FB:F4:C8:99:6F:B9:24:27:AE:41:E4:64:9B:93:4C:A4:95:99:1B:78:52:B8:55"
273        );
274    }
275
276    /// Whether a verifier pinned to `pin` accepts certificate `der`, and the refusal it then tells.
277    fn offered(pin: Option<Fingerprint>, der: &[u8]) -> (bool, Option<Refusal>) {
278        let seen = Seen::default();
279        let verifier = PinVerifier {
280            pin,
281            seen: Arc::clone(&seen),
282            algorithms: rustls::crypto::ring::default_provider().signature_verification_algorithms,
283        };
284        let name = ServerName::try_from("server.example").unwrap();
285        let accepted = verifier
286            .verify_server_cert(&CertificateDer::from(der), &[], &name, &[], UnixTime::now())
287            .is_ok();
288        (accepted, refusal(pin, &seen))
289    }
290
291    #[test]
292    fn only_the_pinned_certificate_is_accepted_and_the_one_offered_is_told() {
293        let (mine, other) = (b"the pinned certificate".as_slice(), b"another one".as_slice());
294        let pin = Some(Fingerprint::of(mine));
295        assert_eq!(offered(pin, mine), (true, None));
296        let changed = Refusal::Changed {
297            pinned: Fingerprint::of(mine),
298            presented: Fingerprint::of(other),
299        };
300        assert_eq!(offered(pin, other), (false, Some(changed)));
301        let unconfirmed = Refusal::Unconfirmed {
302            presented: Fingerprint::of(mine),
303        };
304        assert_eq!(offered(None, mine), (false, Some(unconfirmed)), "nothing is accepted before a pin");
305        assert!(changed.to_string().contains(&Fingerprint::of(other).to_string()), "{changed}");
306    }
307
308    #[test]
309    fn the_system_trust_store_tells_no_pin_refusal() {
310        let tls = Tls::new(Trust::System).unwrap();
311        assert_eq!(tls.refused(), None);
312        assert_eq!(tls.config().alpn_protocols, [b"http/1.1".to_vec()]);
313    }
314}