mz_tls_util/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! A tiny utility library for making TLS connectors.
11
12use openssl::pkcs12::Pkcs12;
13use openssl::pkey::PKey;
14use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
15use openssl::stack::Stack;
16use openssl::x509::X509;
17use postgres_openssl::MakeTlsConnector;
18use tokio_postgres::config::SslMode;
19
20macro_rules! bail_generic {
21    ($fmt:expr, $($arg:tt)*) => {
22        return Err(TlsError::Generic(anyhow::anyhow!($fmt, $($arg)*)))
23    };
24    ($err:expr $(,)?) => {
25        return Err(TlsError::Generic(anyhow::anyhow!($err)))
26    };
27}
28
29/// An error representing tls failures.
30#[derive(Debug, thiserror::Error)]
31pub enum TlsError {
32    /// Any other error we bail on.
33    #[error(transparent)]
34    Generic(#[from] anyhow::Error),
35    /// Error setting up postgres ssl.
36    #[error(transparent)]
37    OpenSsl(#[from] openssl::error::ErrorStack),
38}
39
40/// Creates a TLS connector for the given [`Config`](tokio_postgres::Config).
41pub fn make_tls(config: &tokio_postgres::Config) -> Result<MakeTlsConnector, TlsError> {
42    let mut builder = SslConnector::builder(SslMethod::tls_client())?;
43    // The mode dictates whether we verify peer certs and hostnames. By default, Postgres is
44    // pretty relaxed and recommends SslMode::VerifyCa or SslMode::VerifyFull for security.
45    //
46    // For more details, check out Table 33.1. SSL Mode Descriptions in
47    // https://postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-PROTECTION.
48    let (verify_mode, verify_hostname) = match config.get_ssl_mode() {
49        SslMode::Disable | SslMode::Prefer => (SslVerifyMode::NONE, false),
50        SslMode::Require => match config.get_ssl_root_cert() {
51            // If a root CA file exists, the behavior of sslmode=require will be the same as
52            // that of verify-ca, meaning the server certificate is validated against the CA.
53            //
54            // For more details, check out the note about backwards compatibility in
55            // https://postgresql.org/docs/current/libpq-ssl.html#LIBQ-SSL-CERTIFICATES.
56            Some(_) => (SslVerifyMode::PEER, false),
57            None => (SslVerifyMode::NONE, false),
58        },
59        SslMode::VerifyCa => (SslVerifyMode::PEER, false),
60        SslMode::VerifyFull => (SslVerifyMode::PEER, true),
61        _ => panic!("unexpected sslmode {:?}", config.get_ssl_mode()),
62    };
63
64    // Configure peer verification
65    builder.set_verify(verify_mode);
66
67    // Configure certificates
68    match (config.get_ssl_cert(), config.get_ssl_key()) {
69        (Some(ssl_cert), Some(ssl_key)) => {
70            builder.set_certificate(&*X509::from_pem(ssl_cert)?)?;
71            builder.set_private_key(&*PKey::private_key_from_pem(ssl_key)?)?;
72        }
73        (None, Some(_)) => {
74            bail_generic!("must provide both sslcert and sslkey, but only provided sslkey")
75        }
76        (Some(_), None) => {
77            bail_generic!("must provide both sslcert and sslkey, but only provided sslcert")
78        }
79        _ => {}
80    }
81    if let Some(ssl_root_cert) = config.get_ssl_root_cert() {
82        builder
83            .cert_store_mut()
84            .add_cert(X509::from_pem(ssl_root_cert)?)?;
85    }
86
87    let mut tls_connector = MakeTlsConnector::new(builder.build());
88
89    // Configure hostname verification
90    match (verify_mode, verify_hostname) {
91        (SslVerifyMode::PEER, false) => tls_connector.set_callback(|connect, _| {
92            connect.set_verify_hostname(false);
93            Ok(())
94        }),
95        _ => {}
96    }
97
98    Ok(tls_connector)
99}
100
101pub struct Pkcs12Archive {
102    pub der: Vec<u8>,
103    pub pass: String,
104}
105
106/// Constructs an identity from a PEM-formatted key and certificate using OpenSSL.
107pub fn pkcs12der_from_pem(
108    key: &[u8],
109    cert: &[u8],
110) -> Result<Pkcs12Archive, openssl::error::ErrorStack> {
111    let mut buf = Vec::new();
112    buf.extend(key);
113    buf.push(b'\n');
114    buf.extend(cert);
115    let pem = buf.as_slice();
116    let pkey = PKey::private_key_from_pem(pem)?;
117    let mut certs = Stack::new()?;
118
119    // `X509::stack_from_pem` in openssl as of at least versions <= 0.10.48
120    // does not guarantee that it will either error or return at least 1
121    // element; in fact, it doesn't if the `pem` is not a well-formed
122    // representation of a PEM file. For example, if the represented file
123    // contains a well-formed key but a malformed certificate.
124    //
125    // To circumvent this issue, if `X509::stack_from_pem` returns no
126    // certificates, rely on getting the error message from
127    // `X509::from_pem`.
128    let mut cert_iter = X509::stack_from_pem(pem)?.into_iter();
129    let cert = match cert_iter.next() {
130        Some(cert) => cert,
131        None => X509::from_pem(pem)?,
132    };
133    for cert in cert_iter {
134        certs.push(cert)?;
135    }
136    // We build a PKCS #12 archive solely to have something to pass to
137    // `reqwest::Identity::from_pkcs12_der`, so the password and friendly
138    // name don't matter.
139    let pass = String::new();
140    let friendly_name = "";
141    let der = Pkcs12::builder()
142        .name(friendly_name)
143        .pkey(&pkey)
144        .cert(&cert)
145        .ca(certs)
146        .build2(&pass)?
147        .to_der()?;
148    Ok(Pkcs12Archive { der, pass })
149}