Skip to main content

postgres_mcp/pg/
tls.rs

1//! SSL modes and the rustls client configuration used for PostgreSQL connections.
2// WireError::Db holds DbError by value (fixed by the interface), so Result<_, WireError> is large.
3#![allow(clippy::result_large_err)]
4
5use std::borrow::Cow;
6use std::fmt;
7use std::io;
8use std::path::{Path, PathBuf};
9use std::str::FromStr;
10use std::sync::Arc;
11
12use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
13use rustls::client::{WebPkiServerVerifier, verify_server_cert_signed_by_trust_anchor};
14use rustls::crypto::CryptoProvider;
15use rustls::pki_types::pem::PemObject;
16use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
17use rustls::{
18    CertificateError, ClientConfig, DigitallySignedStruct, Error as TlsError, InconsistentKeys,
19    RootCertStore, SignatureScheme,
20};
21use x509_parser::parse_x509_certificate;
22
23use crate::pg::wire::WireError;
24
25/// libpq-style SSL modes.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum SslMode {
28    Disable,
29    Prefer,
30    Require,
31    VerifyCa,
32    VerifyFull,
33}
34
35impl SslMode {
36    /// The libpq name of the mode, as the configuration spells it.
37    pub fn as_str(self) -> &'static str {
38        match self {
39            SslMode::Disable => "disable",
40            SslMode::Prefer => "prefer",
41            SslMode::Require => "require",
42            SslMode::VerifyCa => "verify-ca",
43            SslMode::VerifyFull => "verify-full",
44        }
45    }
46}
47
48impl FromStr for SslMode {
49    type Err = String;
50
51    fn from_str(s: &str) -> Result<Self, Self::Err> {
52        match s {
53            "disable" => Ok(SslMode::Disable),
54            "prefer" => Ok(SslMode::Prefer),
55            "require" => Ok(SslMode::Require),
56            "verify-ca" => Ok(SslMode::VerifyCa),
57            "verify-full" => Ok(SslMode::VerifyFull),
58            other => Err(format!("invalid ssl mode \"{other}\"")),
59        }
60    }
61}
62
63/// Where one PEM item comes from: a file read at startup, or PEM text given inline. Inline text is never printed.
64#[derive(Clone)]
65pub enum PemSource {
66    File(PathBuf),
67    Inline(String),
68}
69
70impl fmt::Debug for PemSource {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            PemSource::File(path) => f.debug_tuple("File").field(path).finish(),
74            PemSource::Inline(_) => f.write_str("Inline(<redacted>)"),
75        }
76    }
77}
78
79/// The TLS items of one database: the trusted roots, and a client certificate chain with its key.
80#[derive(Clone, Debug, Default)]
81pub struct TlsSources {
82    pub root: Option<PemSource>,
83    pub client_cert: Option<PemSource>,
84    pub client_key: Option<PemSource>,
85}
86
87/// A client certificate chain (leaf first) and its private key.
88type Identity = (Vec<CertificateDer<'static>>, PrivateKeyDer<'static>);
89
90/// Builds the rustls client configuration for `mode`, with roots from `root_cert` (a PEM file) when given.
91pub fn client_config(
92    mode: SslMode,
93    root_cert: Option<&Path>,
94) -> Result<Arc<ClientConfig>, WireError> {
95    if mode == SslMode::VerifyCa && root_cert.is_none() {
96        return Err(WireError::Tls("sslmode=verify-ca needs sslrootcert".into()));
97    }
98    let roots = match root_cert {
99        Some(path) => read_roots_file(path).map_err(|e| e.wire(path))?,
100        None => bundled_roots(),
101    };
102    build_config(mode, roots, None).map_err(WireError::Tls)
103}
104
105/// The configuration for a database at startup, read once and then shared. Every error names the setting
106/// (`sslrootcert`, `sslcert_pem` and so on) and never the file path's contents or any key material.
107pub fn startup_client_config(
108    mode: SslMode,
109    sources: &TlsSources,
110) -> Result<Arc<ClientConfig>, String> {
111    if mode == SslMode::VerifyCa && sources.root.is_none() {
112        return Err("sslmode=verify-ca needs sslrootcert".to_owned());
113    }
114    let roots = match &sources.root {
115        Some(source) => startup_roots(source)?,
116        None => bundled_roots(),
117    };
118    let identity = client_identity(sources)?;
119    build_config(mode, roots, identity)
120}
121
122/// The trusted roots, and the certificates they were read from. The latter are pinned (see `Verifier`).
123struct Roots {
124    store: RootCertStore,
125    pinned: Vec<CertificateDer<'static>>,
126}
127
128fn bundled_roots() -> Roots {
129    let mut store = RootCertStore::empty();
130    store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
131    Roots {
132        store,
133        pinned: Vec::new(),
134    }
135}
136
137/// The setting name in a message: `base` for a file, `base_pem` for inline text.
138fn item_name(source: &PemSource, base: &str) -> String {
139    match source {
140        PemSource::File(_) => base.to_owned(),
141        PemSource::Inline(_) => format!("{base}_pem"),
142    }
143}
144
145/// The PEM bytes of one item. A file that cannot be read gives `cannot read <item>: <io reason>`.
146fn pem_bytes<'a>(source: &'a PemSource, item: &str) -> Result<Cow<'a, [u8]>, String> {
147    match source {
148        PemSource::File(path) => std::fs::read(path)
149            .map(Cow::Owned)
150            .map_err(|e| format!("cannot read {item}: {e}")),
151        PemSource::Inline(text) => Ok(Cow::Borrowed(text.as_bytes())),
152    }
153}
154
155/// Why a root certificate cannot be used. The variants hold the cause, never the file contents.
156enum RootsError {
157    Open(io::Error),
158    Read(String),
159    Empty,
160    Add(String),
161}
162
163impl RootsError {
164    /// The text the wire client reports for a connection that cannot load its root file.
165    fn wire(self, path: &Path) -> WireError {
166        let shown = path.display();
167        WireError::Tls(match self {
168            RootsError::Open(e) => format!("cannot open {shown}: {e}"),
169            RootsError::Read(m) => format!("cannot read {shown}: {m}"),
170            RootsError::Empty => format!("no certificates found in {shown}"),
171            RootsError::Add(m) => m,
172        })
173    }
174
175    /// The text the startup check reports for the setting `item`; PEM syntax errors are not echoed.
176    fn startup(self, item: &str) -> String {
177        match self {
178            RootsError::Open(e) => format!("cannot read {item}: {e}"),
179            RootsError::Read(_) => format!("{item} is not valid PEM"),
180            RootsError::Empty => format!("{item} holds no certificate"),
181            RootsError::Add(m) => format!("cannot read {item}: {m}"),
182        }
183    }
184}
185
186fn read_roots_file(path: &Path) -> Result<Roots, RootsError> {
187    let bytes = std::fs::read(path).map_err(RootsError::Open)?;
188    roots_from_pem(&bytes)
189}
190
191fn startup_roots(source: &PemSource) -> Result<Roots, String> {
192    let item = item_name(source, "sslrootcert");
193    let bytes = pem_bytes(source, &item)?;
194    roots_from_pem(&bytes).map_err(|e| e.startup(&item))
195}
196
197fn roots_from_pem(bytes: &[u8]) -> Result<Roots, RootsError> {
198    let mut store = RootCertStore::empty();
199    let mut pinned = Vec::new();
200    for cert in CertificateDer::pem_slice_iter(bytes) {
201        let cert = cert.map_err(|e| RootsError::Read(e.to_string()))?;
202        store
203            .add(cert.clone())
204            .map_err(|e| RootsError::Add(e.to_string()))?;
205        pinned.push(cert);
206    }
207    if store.is_empty() {
208        return Err(RootsError::Empty);
209    }
210    Ok(Roots { store, pinned })
211}
212
213/// The client identity from the certificate and key sources: both or neither. None when neither is set.
214fn client_identity(sources: &TlsSources) -> Result<Option<Identity>, String> {
215    let (cert_source, key_source) = match (&sources.client_cert, &sources.client_key) {
216        (None, None) => return Ok(None),
217        (Some(cert), Some(key)) => (cert, key),
218        _ => return Err("sslcert and sslkey must be set together".to_owned()),
219    };
220    let cert_item = item_name(cert_source, "sslcert");
221    let chain = {
222        let bytes = pem_bytes(cert_source, &cert_item)?;
223        CertificateDer::pem_slice_iter(&bytes)
224            .collect::<Result<Vec<_>, _>>()
225            .map_err(|_| format!("{cert_item} is not valid PEM"))?
226    };
227    if chain.is_empty() {
228        return Err(format!("{cert_item} holds no certificate"));
229    }
230    let key_item = item_name(key_source, "sslkey");
231    let key = {
232        let bytes = pem_bytes(key_source, &key_item)?;
233        if is_encrypted_pem(&bytes) {
234            return Err(format!(
235                "{key_item} is encrypted; provide an unencrypted PEM key"
236            ));
237        }
238        match PrivateKeyDer::pem_slice_iter(&bytes).next() {
239            None => return Err(format!("{key_item} holds no private key")),
240            Some(Err(_)) => return Err(format!("{key_item} is not valid PEM")),
241            Some(Ok(key)) => key,
242        }
243    };
244    Ok(Some((chain, key)))
245}
246
247/// True for PKCS#8 encrypted armour and for the PEM `Proc-Type: 4,ENCRYPTED` header. Only the labels are read.
248fn is_encrypted_pem(bytes: &[u8]) -> bool {
249    String::from_utf8_lossy(bytes).lines().any(|line| {
250        let line = line.trim();
251        line == "-----BEGIN ENCRYPTED PRIVATE KEY-----"
252            || (line.starts_with("Proc-Type:") && line.contains("ENCRYPTED"))
253    })
254}
255
256fn build_config(
257    mode: SslMode,
258    roots: Roots,
259    identity: Option<Identity>,
260) -> Result<Arc<ClientConfig>, String> {
261    let store = Arc::new(roots.store);
262    let provider = Arc::new(rustls::crypto::ring::default_provider());
263    let webpki = WebPkiServerVerifier::builder_with_provider(store.clone(), provider.clone())
264        .build()
265        .map_err(|e| e.to_string())?;
266    let verifier = Verifier {
267        mode,
268        provider: provider.clone(),
269        roots: store,
270        pinned: roots.pinned,
271        webpki,
272    };
273    let builder = ClientConfig::builder_with_provider(provider)
274        .with_safe_default_protocol_versions()
275        .map_err(|e| e.to_string())?
276        .dangerous()
277        .with_custom_certificate_verifier(Arc::new(verifier));
278    let config = match identity {
279        None => builder.with_no_client_auth(),
280        Some((chain, key)) => builder
281            .with_client_auth_cert(chain, key)
282            .map_err(client_key_error)?,
283    };
284    Ok(Arc::new(config))
285}
286
287/// rustls refuses a key that does not belong to the certificate; any other refusal means the key is unusable.
288fn client_key_error(error: TlsError) -> String {
289    match error {
290        TlsError::InconsistentKeys(InconsistentKeys::KeyMismatch) => {
291            "sslkey does not match sslcert".to_owned()
292        }
293        _ => "sslkey is not a supported private key".to_owned(),
294    }
295}
296
297/// Certificate verifier: Require/Prefer accept any certificate, VerifyCa checks the chain only,
298/// VerifyFull also checks the server name. Handshake signatures are always checked.
299#[derive(Debug)]
300struct Verifier {
301    mode: SslMode,
302    provider: Arc<CryptoProvider>,
303    roots: Arc<RootCertStore>,
304    /// The configured root certificates, compared byte for byte with the server certificate.
305    pinned: Vec<CertificateDer<'static>>,
306    webpki: Arc<WebPkiServerVerifier>,
307}
308
309impl Verifier {
310    /// True when `end_entity` is byte for byte one of the configured root certificates.
311    fn is_pinned(&self, end_entity: &CertificateDer<'_>) -> bool {
312        self.pinned
313            .iter()
314            .any(|der| der.as_ref() == end_entity.as_ref())
315    }
316
317    /// The checks for a pinned certificate, its own trust anchor: validity period, then the server
318    /// name when `server_name` is given (VerifyFull).
319    fn verify_pinned(
320        &self,
321        end_entity: &CertificateDer<'_>,
322        server_name: Option<&ServerName<'_>>,
323        now: UnixTime,
324    ) -> Result<ServerCertVerified, rustls::Error> {
325        check_validity(end_entity, now)?;
326        if let Some(name) = server_name {
327            let parsed = webpki::EndEntityCert::try_from(end_entity)
328                .map_err(|_| CertificateError::BadEncoding)?;
329            parsed
330                .verify_is_valid_for_subject_name(name)
331                .map_err(name_error)?;
332        }
333        Ok(ServerCertVerified::assertion())
334    }
335}
336
337/// The validity period of a pinned certificate: notBefore <= now <= notAfter.
338fn check_validity(end_entity: &CertificateDer<'_>, now: UnixTime) -> Result<(), rustls::Error> {
339    let (_, cert) =
340        parse_x509_certificate(end_entity.as_ref()).map_err(|_| CertificateError::BadEncoding)?;
341    let validity = cert.validity();
342    let now = i64::try_from(now.as_secs()).unwrap_or(i64::MAX);
343    if now < validity.not_before.timestamp() {
344        return Err(CertificateError::NotValidYet.into());
345    }
346    if now > validity.not_after.timestamp() {
347        return Err(CertificateError::Expired.into());
348    }
349    Ok(())
350}
351
352/// The name refusal as rustls reports it, with webpki's context.
353fn name_error(error: webpki::Error) -> rustls::Error {
354    match error {
355        webpki::Error::CertNotValidForName(context) => CertificateError::NotValidForNameContext {
356            expected: context.expected,
357            presented: context.presented,
358        }
359        .into(),
360        _ => CertificateError::NotValidForName.into(),
361    }
362}
363
364impl ServerCertVerifier for Verifier {
365    fn verify_server_cert(
366        &self,
367        end_entity: &CertificateDer<'_>,
368        intermediates: &[CertificateDer<'_>],
369        server_name: &ServerName<'_>,
370        ocsp_response: &[u8],
371        now: UnixTime,
372    ) -> Result<ServerCertVerified, rustls::Error> {
373        match self.mode {
374            SslMode::VerifyFull => match self.webpki.verify_server_cert(
375                end_entity,
376                intermediates,
377                server_name,
378                ocsp_response,
379                now,
380            ) {
381                Err(_) if self.is_pinned(end_entity) => {
382                    self.verify_pinned(end_entity, Some(server_name), now)
383                }
384                verdict => verdict,
385            },
386            SslMode::VerifyCa => {
387                let parsed = end_entity.try_into()?;
388                match verify_server_cert_signed_by_trust_anchor(
389                    &parsed,
390                    &self.roots,
391                    intermediates,
392                    now,
393                    self.provider.signature_verification_algorithms.all,
394                ) {
395                    Ok(()) => Ok(ServerCertVerified::assertion()),
396                    Err(_) if self.is_pinned(end_entity) => {
397                        self.verify_pinned(end_entity, None, now)
398                    }
399                    Err(e) => Err(e),
400                }
401            }
402            SslMode::Disable | SslMode::Prefer | SslMode::Require => {
403                Ok(ServerCertVerified::assertion())
404            }
405        }
406    }
407
408    fn verify_tls12_signature(
409        &self,
410        message: &[u8],
411        cert: &CertificateDer<'_>,
412        dss: &DigitallySignedStruct,
413    ) -> Result<HandshakeSignatureValid, rustls::Error> {
414        self.webpki.verify_tls12_signature(message, cert, dss)
415    }
416
417    fn verify_tls13_signature(
418        &self,
419        message: &[u8],
420        cert: &CertificateDer<'_>,
421        dss: &DigitallySignedStruct,
422    ) -> Result<HandshakeSignatureValid, rustls::Error> {
423        self.webpki.verify_tls13_signature(message, cert, dss)
424    }
425
426    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
427        self.webpki.supported_verify_schemes()
428    }
429}