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.
910//! A tiny utility library for making TLS connectors.
1112use 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;
1920macro_rules! bail_generic {
21 ($fmt:expr, $($arg:tt)*) => {
22return Err(TlsError::Generic(anyhow::anyhow!($fmt, $($arg)*)))
23 };
24 ($err:expr $(,)?) => {
25return Err(TlsError::Generic(anyhow::anyhow!($err)))
26 };
27}
2829/// An error representing tls failures.
30#[derive(Debug, thiserror::Error)]
31pub enum TlsError {
32/// Any other error we bail on.
33#[error(transparent)]
34Generic(#[from] anyhow::Error),
35/// Error setting up postgres ssl.
36#[error(transparent)]
37OpenSsl(#[from] openssl::error::ErrorStack),
38}
3940/// Creates a TLS connector for the given [`Config`](tokio_postgres::Config).
41pub fn make_tls(config: &tokio_postgres::Config) -> Result<MakeTlsConnector, TlsError> {
42let 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.
48let (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.
56Some(_) => (SslVerifyMode::PEER, false),
57None => (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 };
6364// Configure peer verification
65builder.set_verify(verify_mode);
6667// Configure certificates
68match (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(_)) => {
74bail_generic!("must provide both sslcert and sslkey, but only provided sslkey")
75 }
76 (Some(_), None) => {
77bail_generic!("must provide both sslcert and sslkey, but only provided sslcert")
78 }
79_ => {}
80 }
81if 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 }
8687let mut tls_connector = MakeTlsConnector::new(builder.build());
8889// Configure hostname verification
90match (verify_mode, verify_hostname) {
91 (SslVerifyMode::PEER, false) => tls_connector.set_callback(|connect, _| {
92 connect.set_verify_hostname(false);
93Ok(())
94 }),
95_ => {}
96 }
9798Ok(tls_connector)
99}
100101pub struct Pkcs12Archive {
102pub der: Vec<u8>,
103pub pass: String,
104}
105106/// 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> {
111let mut buf = Vec::new();
112 buf.extend(key);
113 buf.push(b'\n');
114 buf.extend(cert);
115let pem = buf.as_slice();
116let pkey = PKey::private_key_from_pem(pem)?;
117let mut certs = Stack::new()?;
118119// `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`.
128let mut cert_iter = X509::stack_from_pem(pem)?.into_iter();
129let cert = match cert_iter.next() {
130Some(cert) => cert,
131None => X509::from_pem(pem)?,
132 };
133for 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.
139let pass = String::new();
140let friendly_name = "";
141let der = Pkcs12::builder()
142 .name(friendly_name)
143 .pkey(&pkey)
144 .cert(&cert)
145 .ca(certs)
146 .build2(&pass)?
147.to_der()?;
148Ok(Pkcs12Archive { der, pass })
149}