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