Skip to main content

passalong_https/
tls.rs

1//! TLS to a passalong-server: the one public key a `tls_pin` names, or the
2//! operating system's trust store. There is no setting that turns
3//! verification off.
4//!
5//! A pin is the SHA-256 of the certificate's SubjectPublicKeyInfo. With a
6//! pin, no authority, name, or date is checked, which is how a self-signed
7//! server is reached; the handshake's signature still is, or the pin would
8//! prove nothing.
9
10use std::sync::Arc;
11
12use passalong_core::config::TlsPin;
13use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
14use rustls::crypto::{
15    CryptoProvider, WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature,
16};
17use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
18use rustls::{CertificateError, DigitallySignedStruct, OtherError, SignatureScheme};
19use sha2::{Digest, Sha256};
20
21/// The `ring` provider, which the SSH backend uses too.
22pub fn provider() -> Arc<CryptoProvider> {
23    Arc::new(rustls::crypto::ring::default_provider())
24}
25
26/// The TLS configuration for a server with `pin`, or without one.
27///
28/// # Errors
29///
30/// When the system's trust store cannot be used.
31pub fn client_config(pin: Option<TlsPin>) -> Result<rustls::ClientConfig, rustls::Error> {
32    let provider = provider();
33    let verifier: Arc<dyn ServerCertVerifier> = match pin {
34        Some(pin) => Arc::new(PinnedVerifier::new(
35            pin,
36            provider.signature_verification_algorithms,
37        )),
38        None => Arc::new(rustls_platform_verifier::Verifier::new(provider.clone())?),
39    };
40    // `dangerous()` is how rustls installs any verifier of one's own, the
41    // system's included; both verify fully.
42    Ok(rustls::ClientConfig::builder_with_provider(provider)
43        .with_safe_default_protocol_versions()?
44        .dangerous()
45        .with_custom_certificate_verifier(verifier)
46        .with_no_client_auth())
47}
48
49/// Trusts the certificate whose public key the pin names, and nothing else.
50#[derive(Debug)]
51pub struct PinnedVerifier {
52    pin: TlsPin,
53    algorithms: WebPkiSupportedAlgorithms,
54}
55
56impl PinnedVerifier {
57    /// A verifier for `pin` that checks handshake signatures with
58    /// `algorithms`.
59    pub fn new(pin: TlsPin, algorithms: WebPkiSupportedAlgorithms) -> Self {
60        Self { pin, algorithms }
61    }
62}
63
64/// The server presented a key other than the pinned one.
65#[derive(Debug)]
66pub struct PinMismatch {
67    /// The pin of the key it presented.
68    pub presented: Option<TlsPin>,
69}
70
71impl std::fmt::Display for PinMismatch {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        match &self.presented {
74            Some(pin) => write!(
75                f,
76                "the server's certificate has the pin {pin}, not the configured tls_pin"
77            ),
78            None => write!(f, "the server's certificate cannot be read"),
79        }
80    }
81}
82
83impl std::error::Error for PinMismatch {}
84
85impl ServerCertVerifier for PinnedVerifier {
86    fn verify_server_cert(
87        &self,
88        end_entity: &CertificateDer<'_>,
89        _intermediates: &[CertificateDer<'_>],
90        _server_name: &ServerName<'_>,
91        _ocsp_response: &[u8],
92        _now: UnixTime,
93    ) -> Result<ServerCertVerified, rustls::Error> {
94        let presented = spki_pin(end_entity).ok();
95        if presented == Some(self.pin) {
96            return Ok(ServerCertVerified::assertion());
97        }
98        Err(rustls::Error::InvalidCertificate(CertificateError::Other(
99            OtherError(Arc::new(PinMismatch { presented })),
100        )))
101    }
102
103    fn verify_tls12_signature(
104        &self,
105        message: &[u8],
106        cert: &CertificateDer<'_>,
107        dss: &DigitallySignedStruct,
108    ) -> Result<HandshakeSignatureValid, rustls::Error> {
109        verify_tls12_signature(message, cert, dss, &self.algorithms)
110    }
111
112    fn verify_tls13_signature(
113        &self,
114        message: &[u8],
115        cert: &CertificateDer<'_>,
116        dss: &DigitallySignedStruct,
117    ) -> Result<HandshakeSignatureValid, rustls::Error> {
118        verify_tls13_signature(message, cert, dss, &self.algorithms)
119    }
120
121    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
122        self.algorithms.supported_schemes()
123    }
124}
125
126/// What a server presents, for `passalong init` to show before anything
127/// is trusted.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub struct Presented {
130    /// The pin of its certificate's public key.
131    pub pin: TlsPin,
132    /// Whether the operating system's certificate authorities vouch for the
133    /// certificate and the name.
134    pub trusted: bool,
135}
136
137/// Records what the server presents, asks the system's verifier about it,
138/// and then refuses the handshake, so nothing is ever sent.
139#[derive(Debug)]
140struct Recorder {
141    system: Arc<dyn ServerCertVerifier>,
142    seen: std::sync::Mutex<Option<Presented>>,
143}
144
145/// The refusal that ends a [`Recorder`]'s handshake.
146#[derive(Debug)]
147struct Recorded;
148
149impl std::fmt::Display for Recorded {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        f.write_str("certificate recorded; the handshake stops here")
152    }
153}
154
155impl std::error::Error for Recorded {}
156
157impl ServerCertVerifier for Recorder {
158    fn verify_server_cert(
159        &self,
160        end_entity: &CertificateDer<'_>,
161        intermediates: &[CertificateDer<'_>],
162        server_name: &ServerName<'_>,
163        ocsp_response: &[u8],
164        now: UnixTime,
165    ) -> Result<ServerCertVerified, rustls::Error> {
166        if let Ok(pin) = spki_pin(end_entity) {
167            let trusted = self
168                .system
169                .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
170                .is_ok();
171            *self
172                .seen
173                .lock()
174                .unwrap_or_else(std::sync::PoisonError::into_inner) =
175                Some(Presented { pin, trusted });
176        }
177        Err(rustls::Error::InvalidCertificate(CertificateError::Other(
178            OtherError(Arc::new(Recorded)),
179        )))
180    }
181
182    fn verify_tls12_signature(
183        &self,
184        message: &[u8],
185        cert: &CertificateDer<'_>,
186        dss: &DigitallySignedStruct,
187    ) -> Result<HandshakeSignatureValid, rustls::Error> {
188        self.system.verify_tls12_signature(message, cert, dss)
189    }
190
191    fn verify_tls13_signature(
192        &self,
193        message: &[u8],
194        cert: &CertificateDer<'_>,
195        dss: &DigitallySignedStruct,
196    ) -> Result<HandshakeSignatureValid, rustls::Error> {
197        self.system.verify_tls13_signature(message, cert, dss)
198    }
199
200    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
201        self.system.supported_verify_schemes()
202    }
203}
204
205/// The certificate the server at `url` presents: its pin, and whether the
206/// system trusts it. The handshake is always refused once the certificate
207/// is seen, so no request, and no API key, reaches the server.
208///
209/// # Errors
210///
211/// [`HttpsError::Transport`] when the server cannot be reached or presents
212/// no certificate that can be read.
213pub async fn presented(url: &str) -> Result<Presented, crate::HttpsError> {
214    let transport = |reason: String| crate::HttpsError::Transport {
215        url: url.to_owned(),
216        reason,
217        retryable: false,
218    };
219    let provider = provider();
220    let system = rustls_platform_verifier::Verifier::new(provider.clone())
221        .map_err(|err| transport(format!("setting up TLS: {err}")))?;
222    let recorder = Arc::new(Recorder {
223        system: Arc::new(system),
224        seen: std::sync::Mutex::new(None),
225    });
226    let config = rustls::ClientConfig::builder_with_provider(provider)
227        .with_safe_default_protocol_versions()
228        .map_err(|err| transport(format!("setting up TLS: {err}")))?
229        .dangerous()
230        .with_custom_certificate_verifier(recorder.clone())
231        .with_no_client_auth();
232    let http = reqwest::Client::builder()
233        .tls_backend_preconfigured(config)
234        .https_only(true)
235        .connect_timeout(crate::client::CONNECT_TIMEOUT)
236        .build()
237        .map_err(|err| transport(err.to_string()))?;
238    let result = http.head(url).send().await;
239    let seen = *recorder
240        .seen
241        .lock()
242        .unwrap_or_else(std::sync::PoisonError::into_inner);
243    match (seen, result) {
244        (Some(presented), _) => Ok(presented),
245        (None, Err(err)) => Err(transport(crate::client::chain(&err))),
246        (None, Ok(_)) => Err(transport("the server presented no certificate".to_owned())),
247    }
248}
249
250/// The pin of the certificate `der`: the SHA-256 of its
251/// SubjectPublicKeyInfo, the seventh element of `tbsCertificate` when the
252/// optional version comes first.
253///
254/// # Errors
255///
256/// A description when `der` is not a DER certificate.
257pub fn spki_pin(der: &[u8]) -> Result<TlsPin, String> {
258    let mut certificate = Der(der).sequence()?;
259    let mut tbs = certificate.sequence()?;
260    // [0] EXPLICIT version, present from X.509 v2 on.
261    if tbs.0.first() == Some(&0xa0) {
262        tbs.next()?;
263    }
264    // serialNumber, signature, issuer, validity, subject.
265    for _ in 0..5 {
266        tbs.next()?;
267    }
268    let (tag, _, whole) = tbs.next()?;
269    if tag != 0x30 {
270        return Err("no SubjectPublicKeyInfo where one belongs".to_owned());
271    }
272    Ok(TlsPin::from_digest(Sha256::digest(whole).into()))
273}
274
275/// Reads DER elements one after another.
276struct Der<'a>(&'a [u8]);
277
278impl<'a> Der<'a> {
279    /// The next element: its tag, its content, and its whole encoding.
280    fn next(&mut self) -> Result<(u8, &'a [u8], &'a [u8]), String> {
281        let bytes = self.0;
282        let (&tag, rest) = bytes.split_first().ok_or("the certificate ends early")?;
283        if tag & 0x1f == 0x1f {
284            return Err("a tag longer than one byte".to_owned());
285        }
286        let (&first, rest) = rest.split_first().ok_or("the certificate ends early")?;
287        let (len, rest) = if first < 0x80 {
288            (usize::from(first), rest)
289        } else {
290            let count = usize::from(first & 0x7f);
291            if count == 0 || count > 4 || rest.len() < count {
292                return Err("a length DER does not allow".to_owned());
293            }
294            let len = rest[..count]
295                .iter()
296                .fold(0_usize, |len, &byte| (len << 8) | usize::from(byte));
297            (len, &rest[count..])
298        };
299        if rest.len() < len {
300            return Err("the certificate ends early".to_owned());
301        }
302        let header = bytes.len() - rest.len();
303        self.0 = &rest[len..];
304        Ok((tag, &rest[..len], &bytes[..header + len]))
305    }
306
307    /// The next element, which must be a SEQUENCE, to read inside.
308    fn sequence(&mut self) -> Result<Der<'a>, String> {
309        match self.next()? {
310            (0x30, content, _) => Ok(Der(content)),
311            _ => Err("a SEQUENCE was expected".to_owned()),
312        }
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use rustls::pki_types::pem::PemObject;
320
321    /// A self-signed certificate for `localhost` and `127.0.0.1`, as
322    /// `passalong-server tls self-signed` made it, and the pin it printed.
323    const CERT: &str = include_str!("../tests/fixtures/self-signed.pem");
324    const CERT_PIN: &str = "sha256/yFchGu73Az8s4FnAfymiO33A6WswijiRgzkEfdjrHYE=";
325
326    fn cert() -> CertificateDer<'static> {
327        CertificateDer::from_pem_slice(CERT.as_bytes()).unwrap()
328    }
329
330    #[test]
331    fn the_pin_of_a_certificate_is_the_one_the_server_prints() {
332        assert_eq!(spki_pin(&cert()).unwrap().to_string(), CERT_PIN);
333    }
334
335    #[test]
336    fn what_is_not_a_certificate_has_no_pin() {
337        let der = cert().to_vec();
338        for bad in [
339            &[][..],
340            &der[..10],
341            &[0x30, 0x84, 0xff, 0xff, 0xff, 0xff],
342            &[0x04, 0x00],
343        ] {
344            assert!(spki_pin(bad).is_err(), "{bad:?}");
345        }
346    }
347
348    fn verifier(pin: &str) -> PinnedVerifier {
349        PinnedVerifier::new(
350            TlsPin::parse(pin).unwrap(),
351            provider().signature_verification_algorithms,
352        )
353    }
354
355    #[test]
356    fn only_the_pinned_key_is_trusted() {
357        let name = ServerName::try_from("localhost").unwrap();
358        let now = UnixTime::now();
359        assert!(
360            verifier(CERT_PIN)
361                .verify_server_cert(&cert(), &[], &name, &[], now)
362                .is_ok()
363        );
364        let other = "sha256/Zmh6rfhivXdsj8GLjp+OIAiXFIVu4jOzkCpZHQ1fKSU=";
365        let err = verifier(other)
366            .verify_server_cert(&cert(), &[], &name, &[], now)
367            .unwrap_err();
368        assert!(err.to_string().contains(CERT_PIN), "{err}");
369    }
370
371    #[test]
372    fn the_verifier_offers_the_provider_s_signature_schemes() {
373        // That the pinned key must still sign the handshake is shown by a
374        // real handshake in `tests/rogue_server.rs`.
375        assert!(!verifier(CERT_PIN).supported_verify_schemes().is_empty());
376    }
377
378    #[test]
379    fn both_kinds_of_configuration_build() {
380        assert!(client_config(Some(TlsPin::parse(CERT_PIN).unwrap())).is_ok());
381        assert!(client_config(None).is_ok());
382    }
383}