Skip to main content

vault_core/
tls.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Shared TLS client policy — the one place that decides whether a server is
4//! trusted.
5//!
6//! This lived inside `src-tauri/src/lib.rs` until Phase 17, which meant the
7//! desktop app pinned certificates and the CLI did not verify them at all. Two
8//! implementations of a trust decision is how one of them ends up accepting
9//! anything, so there is now exactly one, and both callers build their HTTP
10//! client from it.
11//!
12//! Three policies, and the difference between them is the whole security model:
13//!
14//! * [`TlsPolicy::Ca`] — ordinary CA validation, for a server with a real
15//!   certificate.
16//! * [`TlsPolicy::Pin`] — the leaf certificate must hash to a known SHA-256.
17//!   Enforced **during the handshake**, before any request body is written, so a
18//!   MITM is rejected before the master password reaches the socket.
19//! * [`TlsPolicy::PrivateCa`] — validate against a specific CA and *only* that
20//!   CA. Narrower than adding a root to the system store, and deliberately so: a
21//!   private CA should be able to vouch for your own server, not for the web.
22//!
23//! [`capturing_config`] is separate and is not a policy. It accepts whatever the
24//! server presents and records the fingerprint — the trust-on-first-use
25//! bootstrap, which is only sound because it is confined to one unauthenticated
26//! request that sends no credentials.
27
28use std::sync::{Arc, Mutex};
29
30// The node listener (unv-cli) builds its server side from the same rustls.
31pub use rustls;
32
33use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
34use rustls::crypto::CryptoProvider;
35use rustls::{
36    ClientConfig, DigitallySignedStruct, Error as TlsError, RootCertStore, SignatureScheme,
37};
38use rustls_pki_types::pem::PemObject;
39use rustls_pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
40use sha2::{Digest, Sha256};
41
42/// SHA-256 of a certificate's DER encoding, lower-case hex.
43///
44/// This is the string users compare and pin. It is computed the same way in
45/// every code path on purpose — a fingerprint that is formatted differently in
46/// two places is a pin that silently never matches.
47pub fn fingerprint_of_der(der: &[u8]) -> String {
48    hex::encode(Sha256::digest(der))
49}
50
51/// Normalise a user-supplied fingerprint for comparison.
52///
53/// Accepts the colon-separated form `AB:CD:…` that `openssl x509 -fingerprint`
54/// prints and an optional `sha256:` prefix, because those are what people paste.
55pub fn normalize_fingerprint(input: &str) -> String {
56    input
57        .trim()
58        .trim_start_matches("sha256:")
59        .trim_start_matches("SHA256:")
60        .replace([':', ' '], "")
61        .to_ascii_lowercase()
62}
63
64/// How a client should decide whether to trust the server it reaches.
65#[derive(Debug, Clone)]
66pub enum TlsPolicy {
67    /// Standard CA validation against the platform's trust store.
68    Ca,
69    /// Pin the leaf certificate to this SHA-256 (hex of the DER encoding).
70    Pin(String),
71    /// Validate against these roots and no others.
72    PrivateCa(Vec<CertificateDer<'static>>),
73}
74
75impl TlsPolicy {
76    /// True when this policy verifies the server's identity at all.
77    ///
78    /// There is no variant for "do not verify" and there must never be one:
79    /// `danger_accept_invalid_certs` appears nowhere in this workspace, and an
80    /// unauthenticated probe is a separate function rather than a policy so it
81    /// cannot be selected by accident on a request carrying credentials.
82    pub fn verifies(&self) -> bool {
83        true
84    }
85}
86
87fn provider() -> Arc<CryptoProvider> {
88    Arc::new(rustls::crypto::aws_lc_rs::default_provider())
89}
90
91/// Build a rustls client configuration for `policy`.
92pub fn client_config(policy: &TlsPolicy) -> Result<ClientConfig, String> {
93    client_config_with(policy, false)
94}
95
96/// As [`client_config`], but offering TLS 1.3 only. A node agent runs
97/// unattended on a host nobody is watching and carries rendered config, so it
98/// does not negotiate down (Phase 34).
99pub fn client_config_tls13(policy: &TlsPolicy) -> Result<ClientConfig, String> {
100    client_config_with(policy, true)
101}
102
103fn client_config_with(policy: &TlsPolicy, tls13_only: bool) -> Result<ClientConfig, String> {
104    let versions = |b: rustls::ConfigBuilder<ClientConfig, rustls::WantsVersions>| {
105        if tls13_only {
106            b.with_protocol_versions(&[&rustls::version::TLS13])
107        } else {
108            b.with_safe_default_protocol_versions()
109        }
110        .map_err(|e| e.to_string())
111    };
112    match policy {
113        TlsPolicy::Ca => {
114            let mut roots = RootCertStore::empty();
115            roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
116            Ok(versions(ClientConfig::builder_with_provider(provider()))?
117                .with_root_certificates(roots)
118                .with_no_client_auth())
119        }
120        TlsPolicy::Pin(expected) => {
121            let p = provider();
122            Ok(versions(ClientConfig::builder_with_provider(p.clone()))?
123                .dangerous()
124                .with_custom_certificate_verifier(Arc::new(FingerprintVerifier {
125                    expected: normalize_fingerprint(expected),
126                    provider: p,
127                }))
128                .with_no_client_auth())
129        }
130        TlsPolicy::PrivateCa(certs) => {
131            let mut roots = RootCertStore::empty();
132            for c in certs {
133                roots
134                    .add(c.clone())
135                    .map_err(|e| format!("Not a usable CA certificate: {e}"))?;
136            }
137            if roots.is_empty() {
138                return Err("No certificates found in the supplied CA file".into());
139            }
140            Ok(versions(ClientConfig::builder_with_provider(provider()))?
141                .with_root_certificates(roots)
142                .with_no_client_auth())
143        }
144    }
145}
146
147/// A fresh self-signed certificate for a listener that is reached by pin, not by
148/// name: `(cert_pem, key_pem, fingerprint)`. The names go in the SAN list for
149/// tools that look; the pin ignores them.
150pub fn self_signed(names: Vec<String>) -> Result<(String, String, String), String> {
151    use rcgen::{CertificateParams, KeyPair};
152    let key = KeyPair::generate().map_err(|e| e.to_string())?;
153    let mut params = CertificateParams::new(names).map_err(|e| e.to_string())?;
154    params.not_after = time::OffsetDateTime::now_utc()
155        .checked_add(time::Duration::days(365 * 5))
156        .ok_or("date overflow")?;
157    let cert = params.self_signed(&key).map_err(|e| e.to_string())?;
158    Ok((
159        cert.pem(),
160        key.serialize_pem(),
161        fingerprint_of_der(cert.der().as_ref()),
162    ))
163}
164
165/// The SHA-256 of the first certificate in a PEM file, as the pin form.
166pub fn fingerprint_of_pem(cert_pem: &str) -> Result<String, String> {
167    let certs = certs_from_pem(cert_pem.as_bytes())?;
168    Ok(fingerprint_of_der(certs[0].as_ref()))
169}
170
171/// A server configuration that speaks TLS 1.3 only and asks for no client
172/// certificate: the caller proves itself with a signature on the request.
173pub fn server_config_tls13(cert_pem: &str, key_pem: &str) -> Result<rustls::ServerConfig, String> {
174    let chain = certs_from_pem(cert_pem.as_bytes())?;
175    let key = match PrivateKeyDer::from_pem_slice(key_pem.as_bytes()) {
176        Ok(k) => k,
177        Err(rustls_pki_types::pem::Error::NoItemsFound) => {
178            return Err("The node's TLS key file holds no private key".into())
179        }
180        Err(e) => return Err(format!("Cannot read the node's TLS key: {e}")),
181    };
182    rustls::ServerConfig::builder_with_provider(provider())
183        .with_protocol_versions(&[&rustls::version::TLS13])
184        .map_err(|e| e.to_string())?
185        .with_no_client_auth()
186        .with_single_cert(chain, key)
187        .map_err(|e| e.to_string())
188}
189
190/// Parse a PEM bundle into certificates for [`TlsPolicy::PrivateCa`].
191pub fn certs_from_pem(pem: &[u8]) -> Result<Vec<CertificateDer<'static>>, String> {
192    let certs: Result<Vec<_>, _> = CertificateDer::pem_slice_iter(pem).collect();
193    let certs = certs.map_err(|e| format!("Cannot read CA file: {e}"))?;
194    if certs.is_empty() {
195        return Err("CA file contains no CERTIFICATE block".into());
196    }
197    Ok(certs)
198}
199
200/// What a fingerprint probe hands back: a client configuration, and the slot the
201/// observed fingerprint lands in once the handshake completes.
202pub type ProbeConfig = (ClientConfig, Arc<Mutex<Option<String>>>);
203
204/// Trust-on-first-use bootstrap: accept whatever is presented and record its
205/// fingerprint.
206///
207/// Returns the config and the slot the fingerprint lands in. **The caller must
208/// send no credentials over a connection built from this**, because nothing has
209/// been verified yet — that is the trust decision the user is about to be asked
210/// to make, exactly as with SSH's host-key prompt.
211pub fn capturing_config() -> Result<ProbeConfig, String> {
212    let seen = Arc::new(Mutex::new(None::<String>));
213    let p = provider();
214    let cfg = ClientConfig::builder_with_provider(p.clone())
215        .with_safe_default_protocol_versions()
216        .map_err(|e| e.to_string())?
217        .dangerous()
218        .with_custom_certificate_verifier(Arc::new(CapturingVerifier {
219            seen: seen.clone(),
220            provider: p,
221        }))
222        .with_no_client_auth();
223    Ok((cfg, seen))
224}
225
226/// Pins the leaf certificate to a SHA-256 fingerprint.
227///
228/// Signature verification is delegated to the crypto provider unchanged; only
229/// the identity check is replaced. Getting that backwards — accepting the
230/// identity but skipping the signature — would make the pin decorative.
231#[derive(Debug)]
232struct FingerprintVerifier {
233    expected: String,
234    provider: Arc<CryptoProvider>,
235}
236
237impl ServerCertVerifier for FingerprintVerifier {
238    fn verify_server_cert(
239        &self,
240        end_entity: &CertificateDer<'_>,
241        _intermediates: &[CertificateDer<'_>],
242        _server_name: &ServerName<'_>,
243        _ocsp_response: &[u8],
244        _now: UnixTime,
245    ) -> Result<ServerCertVerified, TlsError> {
246        let actual = fingerprint_of_der(end_entity.as_ref());
247        if actual == self.expected {
248            Ok(ServerCertVerified::assertion())
249        } else {
250            Err(TlsError::General(
251                "TLS certificate fingerprint does not match the pinned value".into(),
252            ))
253        }
254    }
255
256    fn verify_tls12_signature(
257        &self,
258        message: &[u8],
259        cert: &CertificateDer<'_>,
260        dss: &DigitallySignedStruct,
261    ) -> Result<HandshakeSignatureValid, TlsError> {
262        rustls::crypto::verify_tls12_signature(
263            message,
264            cert,
265            dss,
266            &self.provider.signature_verification_algorithms,
267        )
268    }
269
270    fn verify_tls13_signature(
271        &self,
272        message: &[u8],
273        cert: &CertificateDer<'_>,
274        dss: &DigitallySignedStruct,
275    ) -> Result<HandshakeSignatureValid, TlsError> {
276        rustls::crypto::verify_tls13_signature(
277            message,
278            cert,
279            dss,
280            &self.provider.signature_verification_algorithms,
281        )
282    }
283
284    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
285        self.provider
286            .signature_verification_algorithms
287            .supported_schemes()
288    }
289}
290
291/// Records the fingerprint it is shown and accepts unconditionally. See
292/// [`capturing_config`] for why this is confined to one unauthenticated request.
293#[derive(Debug)]
294struct CapturingVerifier {
295    seen: Arc<Mutex<Option<String>>>,
296    provider: Arc<CryptoProvider>,
297}
298
299impl ServerCertVerifier for CapturingVerifier {
300    fn verify_server_cert(
301        &self,
302        end_entity: &CertificateDer<'_>,
303        _intermediates: &[CertificateDer<'_>],
304        _server_name: &ServerName<'_>,
305        _ocsp_response: &[u8],
306        _now: UnixTime,
307    ) -> Result<ServerCertVerified, TlsError> {
308        *self.seen.lock().unwrap() = Some(fingerprint_of_der(end_entity.as_ref()));
309        Ok(ServerCertVerified::assertion())
310    }
311
312    fn verify_tls12_signature(
313        &self,
314        message: &[u8],
315        cert: &CertificateDer<'_>,
316        dss: &DigitallySignedStruct,
317    ) -> Result<HandshakeSignatureValid, TlsError> {
318        rustls::crypto::verify_tls12_signature(
319            message,
320            cert,
321            dss,
322            &self.provider.signature_verification_algorithms,
323        )
324    }
325
326    fn verify_tls13_signature(
327        &self,
328        message: &[u8],
329        cert: &CertificateDer<'_>,
330        dss: &DigitallySignedStruct,
331    ) -> Result<HandshakeSignatureValid, TlsError> {
332        rustls::crypto::verify_tls13_signature(
333            message,
334            cert,
335            dss,
336            &self.provider.signature_verification_algorithms,
337        )
338    }
339
340    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
341        self.provider
342            .signature_verification_algorithms
343            .supported_schemes()
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn fingerprint_is_stable_and_lowercase_hex() {
353        let fp = fingerprint_of_der(b"not really a certificate");
354        assert_eq!(fp.len(), 64);
355        assert_eq!(fp, fp.to_ascii_lowercase());
356        assert_eq!(fp, fingerprint_of_der(b"not really a certificate"));
357        assert_ne!(fp, fingerprint_of_der(b"a different certificate"));
358    }
359
360    #[test]
361    fn normalize_accepts_the_forms_people_paste() {
362        // openssl prints colon-separated upper case; some UIs prefix the algorithm.
363        let canonical = "ab12cd34";
364        for input in [
365            "AB:12:CD:34",
366            "sha256:AB12CD34",
367            " ab12cd34 ",
368            "AB 12 CD 34",
369        ] {
370            assert_eq!(normalize_fingerprint(input), canonical, "input: {input}");
371        }
372    }
373
374    #[test]
375    fn pin_config_builds_and_normalizes_its_expectation() {
376        // A pin given in the pasted form must match a fingerprint we computed,
377        // or every user who copies from openssl gets an unexplained refusal.
378        let cfg = client_config(&TlsPolicy::Pin("AB:CD".into()));
379        assert!(cfg.is_ok());
380    }
381
382    #[test]
383    fn private_ca_rejects_a_file_with_no_certificates() {
384        let err = certs_from_pem(b"-----BEGIN PRIVATE KEY-----\nzzz\n-----END PRIVATE KEY-----\n")
385            .unwrap_err();
386        assert!(err.contains("no CERTIFICATE"), "{err}");
387    }
388
389    /// The hub/node TLS identity load after the move from `rustls-pemfile` to
390    /// `rustls-pki-types`: a good pair loads, and each way a pair can be wrong is
391    /// refused with a message that names the cause.
392    #[test]
393    fn tls_identity_load_refuses_bad_keys_and_certificates() {
394        let (cert, key, _) = self_signed(vec!["node.test".into()]).unwrap();
395        assert!(server_config_tls13(&cert, &key).is_ok());
396
397        // A certificate where the key should be: PEM is fine, but holds no key.
398        let err = server_config_tls13(&cert, &cert).unwrap_err();
399        assert!(err.contains("no private key"), "{err}");
400        // Empty key file.
401        let err = server_config_tls13(&cert, "").unwrap_err();
402        assert!(err.contains("no private key"), "{err}");
403        // Corrupt base64 inside a key block must not load as something plausible.
404        let broken_key = key.replacen("MIG", "M!G", 1).replacen("MC4", "M!4", 1);
405        let broken_key = if broken_key == key {
406            // Fallback: damage the first body line whatever the key type.
407            let mut lines: Vec<String> = key.lines().map(str::to_owned).collect();
408            lines[1] = format!("!!{}", lines[1]);
409            lines.join("\n")
410        } else {
411            broken_key
412        };
413        assert!(server_config_tls13(&cert, &broken_key).is_err());
414        // Corrupt certificate body: refused, not mapped to a wrong fingerprint.
415        let mut lines: Vec<String> = cert.lines().map(str::to_owned).collect();
416        lines[1] = format!("!!{}", lines[1]);
417        let err = certs_from_pem(lines.join("\n").as_bytes()).unwrap_err();
418        assert!(err.contains("Cannot read CA file"), "{err}");
419        // A key and a certificate that do not belong together.
420        let (_, other_key, _) = self_signed(vec!["other.test".into()]).unwrap();
421        assert!(server_config_tls13(&cert, &other_key).is_err());
422    }
423
424    #[test]
425    fn a_pinned_client_reaches_the_listener_only_with_the_right_certificate() {
426        use std::io::{Read, Write};
427        let (cert, key, fp) = self_signed(vec!["node.test".into()]).unwrap();
428        assert_eq!(fingerprint_of_pem(&cert).unwrap(), fp);
429        let cfg = Arc::new(server_config_tls13(&cert, &key).unwrap());
430        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
431        let port = listener.local_addr().unwrap().port();
432        std::thread::spawn(move || {
433            for _ in 0..3 {
434                let Ok((mut tcp, _)) = listener.accept() else {
435                    return;
436                };
437                let mut conn = rustls::ServerConnection::new(cfg.clone()).unwrap();
438                let mut tls = rustls::Stream::new(&mut conn, &mut tcp);
439                let mut buf = [0u8; 4];
440                if tls.read_exact(&mut buf).is_ok() {
441                    let _ = tls.write_all(b"pong");
442                }
443            }
444        });
445        let talk = |pin: &str, tls12: bool| -> Result<Vec<u8>, String> {
446            let cfg = if tls12 {
447                client_config(&TlsPolicy::Pin(pin.into()))
448            } else {
449                client_config_tls13(&TlsPolicy::Pin(pin.into()))
450            }?;
451            let name = ServerName::try_from("node.test").unwrap();
452            let mut conn =
453                rustls::ClientConnection::new(Arc::new(cfg), name).map_err(|e| e.to_string())?;
454            let mut tcp =
455                std::net::TcpStream::connect(("127.0.0.1", port)).map_err(|e| e.to_string())?;
456            let mut tls = rustls::Stream::new(&mut conn, &mut tcp);
457            tls.write_all(b"ping").map_err(|e| e.to_string())?;
458            let mut out = vec![0u8; 4];
459            tls.read_exact(&mut out).map_err(|e| e.to_string())?;
460            Ok(out)
461        };
462        assert_eq!(talk(&fp, false).unwrap(), b"pong");
463        assert!(
464            talk(&"00".repeat(32), false).is_err(),
465            "a wrong pin must not connect"
466        );
467        // The listener refuses to negotiate TLS 1.2 even for a client that offers it.
468        assert_eq!(
469            talk(&fp, true).unwrap(),
470            b"pong",
471            "a client offering 1.2 and 1.3 lands on 1.3"
472        );
473    }
474}