Skip to main content

osmflow_sync/
tls.rs

1//! TLS for database connections, as libpq's `sslmode` and `sslrootcert` in the connection string ask, with rustls.
2//!
3//! The `postgres` crate knows only `disable`, `prefer` and `require`, does not check certificates itself, and rejects
4//! parameters it does not know, so both are taken out of the connection string before it parses the rest.
5
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use percent_encoding::percent_decode_str;
10use postgres::config::SslMode as PgSslMode;
11use postgres::{Client, Config};
12use rustls::client::WebPkiServerVerifier;
13use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
14use rustls::crypto::{
15    WebPkiSupportedAlgorithms, ring, verify_tls12_signature, verify_tls13_signature,
16};
17use rustls::pki_types::pem::PemObject as _;
18use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
19use rustls::{
20    CertificateError, ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme,
21};
22use tokio_postgres_rustls::MakeRustlsConnect;
23
24use crate::SyncError;
25
26/// The TLS settings of a connection string cannot be used.
27#[derive(Debug, thiserror::Error)]
28#[non_exhaustive]
29pub enum TlsError {
30    /// `sslmode` is none of those supported; libpq's `allow` is not.
31    #[error("sslmode={0} is not supported: use disable, prefer, require, verify-ca or verify-full")]
32    SslMode(String),
33    /// `sslmode=verify-ca` without `sslrootcert`: `verify-ca` checks no host name, so the system's authorities, which
34    /// issue certificates for any host, would accept any server.
35    #[error(
36        "sslmode=verify-ca needs sslrootcert, a PEM file of the certificate authorities to trust"
37    )]
38    NoRootCert,
39    /// The `sslrootcert` file cannot be read, holds no PEM certificate, or holds one rustls cannot use.
40    #[error("sslrootcert {path}: {reason}", path = .path.display())]
41    RootCert {
42        /// The file.
43        path: PathBuf,
44        /// What is wrong with it.
45        reason: String,
46    },
47    /// `sslmode=verify-full` without `sslrootcert`, and the system's trusted certificates cannot be loaded: give the
48    /// server's certificate authorities in `sslrootcert`.
49    #[error(
50        "no system certificate authorities to verify the server with; give them in sslrootcert: {0}"
51    )]
52    SystemRoots(String),
53}
54
55/// What to check of the server, from libpq's `sslmode`.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57enum SslMode {
58    /// No TLS.
59    Disable,
60    /// TLS if the server has it, without checking its certificate; libpq's default.
61    Prefer,
62    /// TLS, without checking the certificate, unless `sslrootcert` is given: then as `VerifyCa`.
63    Require,
64    /// TLS with a certificate issued by a trusted authority, for any host name.
65    VerifyCa,
66    /// TLS with a certificate issued by a trusted authority, for the host connected to.
67    VerifyFull,
68}
69
70impl SslMode {
71    fn parse(value: &str) -> Result<Self, TlsError> {
72        Ok(match value {
73            "disable" => Self::Disable,
74            "prefer" => Self::Prefer,
75            "require" => Self::Require,
76            "verify-ca" => Self::VerifyCa,
77            "verify-full" => Self::VerifyFull,
78            _ => return Err(TlsError::SslMode(value.to_owned())),
79        })
80    }
81}
82
83/// Connects as `url` asks, `sslmode` and `sslrootcert` included.
84pub(crate) fn connect(url: &str) -> Result<Client, SyncError> {
85    let (config, mode, root_cert) = parse(url)?;
86    // With `disable`, it reads no file, and `postgres` does not use it
87    let tls = MakeRustlsConnect::new(client_config(mode, root_cert.as_deref())?);
88    Ok(config.connect(tls)?)
89}
90
91/// The connection string without `sslmode` and `sslrootcert`, parsed, with the mode `postgres` is to use, and both.
92fn parse(url: &str) -> Result<(Config, SslMode, Option<PathBuf>), SyncError> {
93    let mut mode = None;
94    let mut root_cert = None;
95    let rest = split(url, |key, value| match key {
96        "sslmode" => {
97            mode = Some(SslMode::parse(&value)?);
98            Ok(true)
99        }
100        "sslrootcert" => {
101            root_cert = Some(PathBuf::from(value));
102            Ok(true)
103        }
104        _ => Ok(false),
105    })?;
106    let mode = mode.unwrap_or(SslMode::Prefer);
107    let mut config: Config = rest.parse()?;
108    config.ssl_mode(match mode {
109        SslMode::Disable => PgSslMode::Disable,
110        SslMode::Prefer => PgSslMode::Prefer,
111        SslMode::Require | SslMode::VerifyCa | SslMode::VerifyFull => PgSslMode::Require,
112    });
113    Ok((config, mode, root_cert))
114}
115
116/// The connection string without the parameters `take` takes: it gets each key and decoded value, and returns whether
117/// to take it out.
118///
119/// A URL's parameters are in its query, `?key=value&…`, percent-encoded. Otherwise they are `key=value` pairs apart by
120/// spaces, the value in `'` if it has spaces, and `\` escaping the next character, as `postgres` reads them.
121fn split(
122    url: &str,
123    mut take: impl FnMut(&str, String) -> Result<bool, TlsError>,
124) -> Result<String, TlsError> {
125    let mut kept = Vec::new();
126    if url.starts_with("postgres://") || url.starts_with("postgresql://") {
127        let Some((base, query)) = url.split_once('?') else {
128            return Ok(url.to_owned());
129        };
130        for pair in query.split('&') {
131            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
132            let value = percent_decode_str(value).decode_utf8_lossy().into_owned();
133            if !take(key, value)? {
134                kept.push(pair);
135            }
136        }
137        return Ok(if kept.is_empty() {
138            base.to_owned()
139        } else {
140            format!("{base}?{}", kept.join("&"))
141        });
142    }
143    let mut s = url.trim_start();
144    while !s.is_empty() {
145        let key_len = s
146            .find(|c: char| c == '=' || c.is_whitespace())
147            .unwrap_or(s.len());
148        let Some(value) = s[key_len..].trim_start().strip_prefix('=') else {
149            // Not `key=value`: left for `postgres` to report
150            kept.push(s);
151            break;
152        };
153        let value = value.trim_start();
154        let Some((decoded, value_len)) = unquote(value) else {
155            // A quote without its end: left for `postgres` to report
156            kept.push(s);
157            break;
158        };
159        let len = s.len() - value.len() + value_len;
160        if !take(&s[..key_len], decoded)? {
161            kept.push(&s[..len]);
162        }
163        s = s[len..].trim_start();
164    }
165    Ok(kept.join(" "))
166}
167
168/// A `key=value` value, in `'` or up to a space, with `\` escaping the next character, and its length in `s`; none if
169/// the quote does not end.
170fn unquote(s: &str) -> Option<(String, usize)> {
171    let quoted = s.starts_with('\'');
172    let mut value = String::new();
173    let mut chars = s.char_indices().skip(usize::from(quoted));
174    while let Some((i, c)) = chars.next() {
175        match c {
176            '\\' => value.extend(chars.next().map(|(_, c)| c)),
177            '\'' if quoted => return Some((value, i + 1)),
178            c if !quoted && c.is_whitespace() => return Some((value, i)),
179            c => value.push(c),
180        }
181    }
182    (!quoted).then_some((value, s.len()))
183}
184
185/// The rustls configuration for `mode`, trusting the authorities in `root_cert`, or the system's.
186fn client_config(mode: SslMode, root_cert: Option<&Path>) -> Result<ClientConfig, TlsError> {
187    let provider = Arc::new(ring::default_provider());
188    let builder = ClientConfig::builder_with_provider(Arc::clone(&provider))
189        .with_safe_default_protocol_versions()
190        .expect("ring has TLS 1.2 and 1.3");
191    // As libpq: `require` checks the issuer when `sslrootcert` is given, and `prefer` never checks
192    let check_name = match (mode, root_cert) {
193        (SslMode::Disable | SslMode::Prefer, _) | (SslMode::Require, None) => {
194            let verifier = AnyCertificate(provider.signature_verification_algorithms);
195            return Ok(builder
196                .dangerous()
197                .with_custom_certificate_verifier(Arc::new(verifier))
198                .with_no_client_auth());
199        }
200        (SslMode::VerifyCa, None) => return Err(TlsError::NoRootCert),
201        (SslMode::Require | SslMode::VerifyCa, Some(_)) => false,
202        (SslMode::VerifyFull, _) => true,
203    };
204    let roots = Arc::new(match root_cert {
205        Some(path) => file_roots(path)?,
206        None => system_roots()?,
207    });
208    let verifier = WebPkiServerVerifier::builder_with_provider(roots, provider)
209        .build()
210        .expect("the roots are not empty");
211    let verifier: Arc<dyn ServerCertVerifier> = if check_name {
212        verifier
213    } else {
214        Arc::new(AnyName(verifier))
215    };
216    Ok(builder
217        .dangerous()
218        .with_custom_certificate_verifier(verifier)
219        .with_no_client_auth())
220}
221
222/// The certificates in the PEM file at `path`.
223fn file_roots(path: &Path) -> Result<RootCertStore, TlsError> {
224    let error = |reason: String| TlsError::RootCert {
225        path: path.to_path_buf(),
226        reason,
227    };
228    let mut roots = RootCertStore::empty();
229    for cert in CertificateDer::pem_file_iter(path).map_err(|e| error(e.to_string()))? {
230        let cert = cert.map_err(|e| error(e.to_string()))?;
231        roots.add(cert).map_err(|e| error(e.to_string()))?;
232    }
233    if roots.is_empty() {
234        return Err(error("no PEM certificate in it".to_owned()));
235    }
236    Ok(roots)
237}
238
239/// The system's trusted certificates, skipping those it cannot read.
240fn system_roots() -> Result<RootCertStore, TlsError> {
241    let found = rustls_native_certs::load_native_certs();
242    let mut roots = RootCertStore::empty();
243    let (_added, _skipped) = roots.add_parsable_certificates(found.certs);
244    if roots.is_empty() {
245        let errors: Vec<_> = found.errors.iter().map(ToString::to_string).collect();
246        return Err(TlsError::SystemRoots(if errors.is_empty() {
247            "none found".to_owned()
248        } else {
249            errors.join("; ")
250        }));
251    }
252    Ok(roots)
253}
254
255/// Trusts any certificate, for `prefer` and `require`: the connection is encrypted, but the server is not known to be
256/// the one asked for. The handshake's signatures are still checked, with the server's certificate's key.
257#[derive(Debug)]
258struct AnyCertificate(WebPkiSupportedAlgorithms);
259
260impl ServerCertVerifier for AnyCertificate {
261    fn verify_server_cert(
262        &self,
263        _end_entity: &CertificateDer<'_>,
264        _intermediates: &[CertificateDer<'_>],
265        _server_name: &ServerName<'_>,
266        _ocsp_response: &[u8],
267        _now: UnixTime,
268    ) -> Result<ServerCertVerified, rustls::Error> {
269        Ok(ServerCertVerified::assertion())
270    }
271
272    fn verify_tls12_signature(
273        &self,
274        message: &[u8],
275        cert: &CertificateDer<'_>,
276        dss: &DigitallySignedStruct,
277    ) -> Result<HandshakeSignatureValid, rustls::Error> {
278        verify_tls12_signature(message, cert, dss, &self.0)
279    }
280
281    fn verify_tls13_signature(
282        &self,
283        message: &[u8],
284        cert: &CertificateDer<'_>,
285        dss: &DigitallySignedStruct,
286    ) -> Result<HandshakeSignatureValid, rustls::Error> {
287        verify_tls13_signature(message, cert, dss, &self.0)
288    }
289
290    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
291        self.0.supported_schemes()
292    }
293}
294
295/// Checks the certificate's chain to a trusted authority, but not that it is for the host connected to, for
296/// `verify-ca`, and `require` with `sslrootcert`.
297#[derive(Debug)]
298struct AnyName(Arc<WebPkiServerVerifier>);
299
300impl ServerCertVerifier for AnyName {
301    fn verify_server_cert(
302        &self,
303        end_entity: &CertificateDer<'_>,
304        intermediates: &[CertificateDer<'_>],
305        server_name: &ServerName<'_>,
306        ocsp_response: &[u8],
307        now: UnixTime,
308    ) -> Result<ServerCertVerified, rustls::Error> {
309        match self
310            .0
311            .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
312        {
313            Err(rustls::Error::InvalidCertificate(
314                CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
315            )) => Ok(ServerCertVerified::assertion()),
316            other => other,
317        }
318    }
319
320    fn verify_tls12_signature(
321        &self,
322        message: &[u8],
323        cert: &CertificateDer<'_>,
324        dss: &DigitallySignedStruct,
325    ) -> Result<HandshakeSignatureValid, rustls::Error> {
326        self.0.verify_tls12_signature(message, cert, dss)
327    }
328
329    fn verify_tls13_signature(
330        &self,
331        message: &[u8],
332        cert: &CertificateDer<'_>,
333        dss: &DigitallySignedStruct,
334    ) -> Result<HandshakeSignatureValid, rustls::Error> {
335        self.0.verify_tls13_signature(message, cert, dss)
336    }
337
338    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
339        self.0.supported_verify_schemes()
340    }
341}
342
343#[cfg(test)]
344mod tests {
345    use std::error::Error;
346    use std::{env, fs, iter};
347
348    use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
349    use postgres::config::Host;
350
351    use super::*;
352
353    /// What `split` leaves, and the `sslmode` and `sslrootcert` it took.
354    fn split_ssl(url: &str) -> (String, Option<String>, Option<String>) {
355        let (mut mode, mut root_cert) = (None, None);
356        let rest = split(url, |key, value| {
357            Ok(match key {
358                "sslmode" => mode.replace(value).is_none(),
359                "sslrootcert" => root_cert.replace(value).is_none(),
360                _ => false,
361            })
362        })
363        .unwrap();
364        (rest, mode, root_cert)
365    }
366
367    #[test]
368    fn splits_urls() {
369        let url = "postgresql://user:pass@host:5432/db";
370        assert_eq!(split_ssl(url), (url.to_owned(), None, None));
371        assert_eq!(
372            split_ssl(
373                "postgres://h/db?sslmode=verify-full&sslrootcert=%2Fcerts%2Fmy%20ca.pem&connect_timeout=5"
374            ),
375            (
376                "postgres://h/db?connect_timeout=5".to_owned(),
377                Some("verify-full".to_owned()),
378                Some("/certs/my ca.pem".to_owned()),
379            ),
380        );
381        assert_eq!(
382            split_ssl("postgresql://h/db?application_name=a&sslmode=require"),
383            (
384                "postgresql://h/db?application_name=a".to_owned(),
385                Some("require".to_owned()),
386                None
387            ),
388        );
389        assert_eq!(
390            split_ssl("postgresql://h/db?sslrootcert=ca.pem"),
391            (
392                "postgresql://h/db".to_owned(),
393                None,
394                Some("ca.pem".to_owned())
395            ),
396        );
397    }
398
399    #[test]
400    fn splits_key_values() {
401        assert_eq!(
402            split_ssl("host=h sslmode = require   sslrootcert='/certs/my ca.pem' dbname=d"),
403            (
404                "host=h dbname=d".to_owned(),
405                Some("require".to_owned()),
406                Some("/certs/my ca.pem".to_owned()),
407            ),
408        );
409        assert_eq!(
410            split_ssl(r"  password='it\'s a b' sslrootcert=a\ b.pem user=u\ v"),
411            (
412                r"password='it\'s a b' user=u\ v".to_owned(),
413                None,
414                Some("a b.pem".to_owned())
415            ),
416        );
417        assert_eq!(
418            split_ssl("sslmode=disable"),
419            (String::new(), Some("disable".to_owned()), None)
420        );
421        // Not `key=value`, and a quote without its end: kept for `postgres` to report
422        assert_eq!(
423            split_ssl("host=h oops"),
424            ("host=h oops".to_owned(), None, None)
425        );
426        assert_eq!(
427            split_ssl("host=h sslmode='require dbname=d"),
428            ("host=h sslmode='require dbname=d".to_owned(), None, None),
429        );
430    }
431
432    #[test]
433    fn parses_modes() {
434        for (url, mode, pg_mode) in [
435            ("host=h", SslMode::Prefer, PgSslMode::Prefer),
436            (
437                "host=h sslmode=disable",
438                SslMode::Disable,
439                PgSslMode::Disable,
440            ),
441            ("host=h sslmode=prefer", SslMode::Prefer, PgSslMode::Prefer),
442            (
443                "postgresql://h?sslmode=require",
444                SslMode::Require,
445                PgSslMode::Require,
446            ),
447            (
448                "host=h sslmode=verify-ca",
449                SslMode::VerifyCa,
450                PgSslMode::Require,
451            ),
452            (
453                "postgresql://h/db?sslmode=verify-full",
454                SslMode::VerifyFull,
455                PgSslMode::Require,
456            ),
457        ] {
458            let (config, parsed, root_cert) = parse(url).unwrap();
459            assert_eq!(
460                (parsed, config.get_ssl_mode(), root_cert),
461                (mode, pg_mode, None),
462                "{url}"
463            );
464        }
465        let (config, _, root_cert) = parse("host=h dbname=d sslrootcert=/ca.pem").unwrap();
466        assert_eq!(config.get_dbname(), Some("d"));
467        assert_eq!(root_cert, Some(PathBuf::from("/ca.pem")));
468
469        let err = parse("host=h sslmode=allow").unwrap_err();
470        assert!(
471            matches!(err, SyncError::Tls(TlsError::SslMode(ref m)) if m == "allow"),
472            "{err}"
473        );
474        // What `postgres` does not know is still its error
475        let err = parse("host=h sslcert=client.pem").unwrap_err();
476        assert!(matches!(err, SyncError::Db(_)), "{err}");
477    }
478
479    #[test]
480    fn rejects_unusable_roots() {
481        let err = client_config(SslMode::VerifyCa, None).unwrap_err();
482        assert!(matches!(err, TlsError::NoRootCert), "{err}");
483
484        let dir = tempfile::tempdir().unwrap();
485        let missing = dir.path().join("missing.pem");
486        let err = client_config(SslMode::VerifyFull, Some(&missing)).unwrap_err();
487        assert!(
488            matches!(err, TlsError::RootCert { ref path, .. } if *path == missing),
489            "{err}"
490        );
491
492        let empty = dir.path().join("empty.pem");
493        fs::write(&empty, "not a certificate\n").unwrap();
494        let err = client_config(SslMode::Require, Some(&empty)).unwrap_err();
495        assert!(err.to_string().contains("no PEM certificate"), "{err}");
496
497        // Not read when not needed, as libpq
498        client_config(SslMode::Disable, Some(&missing)).unwrap();
499        client_config(SslMode::Prefer, Some(&missing)).unwrap();
500        client_config(SslMode::Require, None).unwrap();
501    }
502
503    /// The modes against the TLS server of `just test-db-up`, whose certificates are in the directory
504    /// `OSMFLOW_SYNC_TEST_TLS` names, and whose role `osmflow_tls` may connect only with TLS.
505    #[test]
506    fn connects_with_tls() {
507        let (Ok(url), Ok(certs)) = (
508            env::var("OSMFLOW_SYNC_TEST_DB"),
509            env::var("OSMFLOW_SYNC_TEST_TLS"),
510        ) else {
511            return;
512        };
513        let config: Config = url.parse().unwrap();
514        // Windows has no `Host::Unix`
515        let host = match &config.get_hosts()[0] {
516            Host::Tcp(host) => host,
517            #[cfg(unix)]
518            Host::Unix(_) => panic!("{url} is not on TCP"),
519        };
520        let port = config.get_ports()[0];
521        let ca = Path::new(&certs).join("ca.crt");
522        let other = Path::new(&certs).join("other.crt");
523        let (ca, other) = (ca.display(), other.display());
524        let connect_to = |host: &str, params: &str| {
525            connect(&format!(
526                "host={host} port={port} user=osmflow_tls dbname=postgres {params}"
527            ))
528        };
529        let encrypted = |client: Result<Client, SyncError>| {
530            let row = client
531                .unwrap()
532                .query_one(
533                    "SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()",
534                    &[],
535                )
536                .unwrap();
537            assert!(row.get::<_, bool>(0));
538        };
539        let fails = |client: Result<Client, SyncError>, error: &str| {
540            let err = client.err().unwrap();
541            let chain: Vec<_> =
542                iter::successors(Some(&err as &dyn Error), |e| (*e).source()).collect();
543            let text = chain
544                .iter()
545                .map(ToString::to_string)
546                .collect::<Vec<_>>()
547                .join(": ");
548            assert!(text.contains(error), "{text}");
549        };
550
551        fails(connect_to(host, "sslmode=disable"), "no encryption");
552        encrypted(connect_to(host, ""));
553        encrypted(connect_to(host, "sslmode=prefer"));
554        encrypted(connect_to(host, "sslmode=require"));
555        encrypted(connect_to(
556            host,
557            &format!("sslmode=require sslrootcert={ca}"),
558        ));
559        encrypted(connect_to(
560            host,
561            &format!("sslmode=verify-ca sslrootcert={ca}"),
562        ));
563        encrypted(connect_to(
564            host,
565            &format!("sslmode=verify-full sslrootcert={ca}"),
566        ));
567
568        // Another authority's certificates: `require` with them checks the issuer too
569        for mode in ["require", "verify-ca", "verify-full"] {
570            fails(
571                connect_to(host, &format!("sslmode={mode} sslrootcert={other}")),
572                "UnknownIssuer",
573            );
574        }
575        // The server's certificate is for localhost: by its IP address, the issuer is right but the name is not
576        encrypted(connect_to(
577            "127.0.0.1",
578            &format!("sslmode=verify-ca sslrootcert={ca}"),
579        ));
580        fails(
581            connect_to(
582                "127.0.0.1",
583                &format!("sslmode=verify-full sslrootcert={ca}"),
584            ),
585            "not valid for name",
586        );
587
588        // The same in a URL
589        let ca = utf8_percent_encode(&certs, NON_ALPHANUMERIC).to_string() + "%2Fca.crt";
590        let sep = if url.contains('?') { '&' } else { '?' };
591        encrypted(connect(&format!(
592            "{url}{sep}user=osmflow_tls&sslmode=verify-full&sslrootcert={ca}"
593        )));
594    }
595}