Hello PostgreSQL Hackers,
This proposal suggests implementing OCSP Stapling in PostgreSQL as an
alternative and more efficient method for checking certificate
revocation, aligning with the trend shift from Certificate Revocation
Lists (CRL).
1. benefits
OCSP Stapling offers several advantages over traditional CRL checks,
including:
*) enhances user trust and real-time certificate verification without
relying on potentially outdated CRLs.
*) helps address privacy concerns associated with traditional OCSP
checks, where the client contacts the OCSP responder directly.
*) reduces latency by eliminating the need for the client to perform an
additional round-trip to the OCSP responder.
*) efficient resource utilization by allowing the server to cache and
reuse OCSP responses.
2. a POC patch with below changes:
*) a new configuration option 'ssl_ocsp_file' to enable/disable OCSP
Stapling and specify OCSP responses for PostgreSQL servers. For
instance, ssl_ocsp_file = '_server.resp'
*) a server-side callback function responsible for generating OCSP
stapling responses. This function comes into play only when a client
requests the server's certificate status during the SSL/TLS handshake.
*) a new connection parameter 'ssl_ocsp_stapling' on the client side.
For example, when 'ssl_ocsp_stapling=1', the psql client will send a
certificate status request to the PostgreSQL server.
*) a client-side callback function within the libpq interface to
validate and check the stapled OCSP response received from the server.
If the server's certificate status is valid, the TLS handshake
continues; otherwise, the connection is rejected.
3. test cases for 'make check' are not yet ready as they could be
complicated, but basic tests can be performed as demonstrated below:
To run the tests, OpenSSL tools are required to simulate the OCSP
responder for generating OCSP responses. Additionally, initial
certificate generation, including a self-signed root CA, OCSP response
signing certificate, and PostgreSQL server certificate, is needed.
*) add ocsp atrributes to openssl.cnf
$ openssl version
OpenSSL 3.0.2 15 Mar 2022 (Library: OpenSSL 3.0.2 15 Mar 2022)
$ diff openssl-ocsp.cnf /etc/ssl/openssl.cnf
204d203
< authorityInfoAccess = OCSP;URI:http://127.0.0.1:6655
232,235d230
< [ v3_ocsp ]
< basicConstraints = CA:FALSE
< keyUsage = nonRepudiation, digitalSignature, keyEncipherment
< extendedKeyUsage = OCSPSigning
255c250
< keyUsage = critical, cRLSign, digitalSignature, keyCertSign
---
>
*) prepare OCSP responder for generating OCSP response
$ mkdir -p demoCA/newcerts
$ touch demoCA/index.txt
$ echo '01' > demoCA/serial
# create a self-signed root CA
$ openssl req -new -nodes -out rootCA.csr -keyout rootCA.key -subj
"/C=CA/ST=BC/L=VAN/O=IDO/OU=DEV/CN=rootCA"
$ openssl x509 -req -in rootCA.csr -days 3650 -extfile openssl-ocsp.cnf
-extensions v3_ca -signkey rootCA.key -out rootCA.crt
# create a certificate for OCSP responder
$ openssl req -new -nodes -out ocspSigning.csr -keyout ocspSigning.key
-subj "/C=CA/ST=BC/L=VAN/O=IDO/OU=DEV/CN=ocspSigner"
$ openssl ca -keyfile rootCA.key -cert rootCA.crt -in ocspSigning.csr
-out ocspSigning.crt -config openssl-ocsp.cnf -extensions v3_ocsp
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
# create a certificate for PostgreSQL server
$ openssl req -new -nodes -out server.csr -keyout server.key -subj
"/C=CA/ST=BC/L=VAN/O=IDO/OU=DEV/CN=server"
$ openssl ca -batch -days 365 -keyfile rootCA.key -cert rootCA.crt
-config openssl-ocsp.cnf -out server.crt -infiles server.csr
# start OCSP responder
$ openssl ocsp -index demoCA/index.txt -port 6655 -rsigner
ocspSigning.crt -rkey ocspSigning.key -CA rootCA.crt -text
# make sure PostgreSQL server's certificate is 'good'
$ openssl ocsp -issuer rootCA.crt -url http://127.0.0.1:6655 -resp_text
-noverify -cert server.crt
# generate OCSP response when certificate status is 'good' and save as
_server.resp-good:
$ openssl ocsp -issuer rootCA.crt -cert server.crt -url
http://127.0.0.1:6655 -respout _server.resp-good
# revoke PostgreSQL server's certificate
$ openssl ca -keyfile rootCA.key -cert rootCA.crt -revoke server.crt
# make sure PostgreSQL server's certificate is 'revoked'
$ openssl ocsp -issuer rootCA.crt -url http://127.0.0.1:6655 -resp_text
-noverify -cert server.crt
### generate OCSP response when certificate status is 'revoked' and save
as _server.resp-revoked:
$ openssl ocsp -issuer rootCA.crt -cert server.crt -url
http://127.0.0.1:6655 -respout _server.resp-revoked
*) setup OCSP stapling on PostgreSQL server side
copy 'rootCA.crt, server.key, server.crt, _server.resp-good, and
_server.resp-revoked' to pgdata folder and update PostgreSQL server
configuration by specifying ssl_ocsp_file = '_server.resp', where
'_server.resp' is either a copy of '_server.resp-good' or
'_server.resp-revoked' depending on the test case, for example:
listen_addresses = '*'
ssl = on
ssl_ca_file = 'rootCA.crt'
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
ssl_ocsp_file = '_server.resp'
*) test with psql client
3.1) PostgreSQL server's certificate status is 'good'
$ cp -pr _server.resp-good _server.resp
$ psql -d "sslmode=verify-ca sslrootcert=rootCA.crt user=david
dbname=postgres ssl_ocsp_stapling=1" -h 127.0.0.1 -p 5432
psql (17devel)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384,
compression: off)
Type "help" for help.
postgres=#
3.2) PostgreSQL server's certificate status is 'revoked'
$ cp -pr _server.resp-revoked _server.resp
$ psql -d "sslmode=verify-ca sslrootcert=rootCA.crt user=david
dbname=postgres ssl_ocsp_stapling=1" -h 127.0.0.1 -p 5432
psql: error: connection to server at "127.0.0.1", port 5432 failed: SSL
error: ocsp callback failure
3.3) PostgreSQL server's certificate status is 'revoked' but OCSP
stapling is not required by psql client:
$ psql -d "sslmode=verify-ca sslrootcert=rootCA.crt user=david
dbname=postgres ssl_ocsp_stapling=0" -h 127.0.0.1 -p 5432
psql (17devel)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384,
compression: off)
Type "help" for help.
postgres=#
This is a highly experimental proof of concept, and any comments or
feedback would be greatly appreciated!
Best regards,
David Zhang
===============
Highgo Software Canada
www.highgo.ca
#
# OpenSSL example configuration file.
# See doc/man5/config.pod for more info.
#
# This is mostly being used for generation of certificate requests,
# but may be used for auto loading of providers
# Note that you can include other files from the main configuration
# file using the .include directive.
#.include filename
# This definition stops the following lines choking if HOME isn't
# defined.
HOME = .
# Use this in order to automatically load providers.
openssl_conf = openssl_init
# Comment out the next line to ignore configuration errors
config_diagnostics = 1
# Extra OBJECT IDENTIFIER info:
# oid_file = $ENV::HOME/.oid
oid_section = new_oids
# To use this configuration file with the "-extfile" option of the
# "openssl x509" utility, name here the section containing the
# X.509v3 extensions to use:
# extensions =
# (Alternatively, use a configuration file that has only
# X.509v3 extensions in its main [= default] section.)
[ new_oids ]
# We can add new OIDs in here for use by 'ca', 'req' and 'ts'.
# Add a simple OID like this:
# testoid1=1.2.3.4
# Or use config file substitution like this:
# testoid2=${testoid1}.5.6
# Policies used by the TSA examples.
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7
# For FIPS
# Optionally include a file that is generated by the OpenSSL fipsinstall
# application. This file contains configuration data required by the OpenSSL
# fips provider. It contains a named section e.g. [fips_sect] which is
# referenced from the [provider_sect] below.
# Refer to the OpenSSL security policy for more information.
# .include fipsmodule.cnf
[openssl_init]
providers = provider_sect
ssl_conf = ssl_sect
# List of providers to load
[provider_sect]
default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
# fips = fips_sect
# If no providers are activated explicitly, the default one is activated
implicitly.
# See man 7 OSSL_PROVIDER-default for more details.
#
# If you add a section explicitly activating any other provider(s), you most
# probably need to explicitly activate the default provider, otherwise it
# becomes unavailable in openssl. As a consequence applications depending on
# OpenSSL may not work correctly which could lead to significant system
# problems including inability to remotely access the system.
[default_sect]
# activate = 1
####################################################################
[ ca ]
default_ca = CA_default # The default ca section
####################################################################
[ CA_default ]
dir = ./demoCA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
#unique_subject = no # Set to 'no' to allow creation of
# several certs with same subject.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crlnumber = $dir/crlnumber # the current crl number
# must be commented out to leave a V1
CRL
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem# The private key
x509_extensions = usr_cert # The extensions to add to the cert
# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
# Extension copying option: use with caution.
# copy_extensions = copy
# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crlnumber must also be commented out to leave a V1 CRL.
# crl_extensions = crl_ext
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = default # use public key default MD
preserve = no # keep passed DN ordering
# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy = policy_match
# For the CA policy
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca # The extensions to add to the self signed cert
# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret
# This sets a mask for permitted string types. There are several options.
# default: PrintableString, T61String, BMPString.
# pkix : PrintableString, BMPString (PKIX recommendation before 2004)
# utf8only: only UTF8Strings (PKIX recommendation after 2004).
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
string_mask = utf8only
# req_extensions = v3_req # The extensions to add to a certificate request
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = AU
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Some-State
localityName = Locality Name (eg, city)
0.organizationName = Organization Name (eg, company)
0.organizationName_default = Internet Widgits Pty Ltd
# we can do this but it is not needed normally :-)
#1.organizationName = Second Organization Name (eg, company)
#1.organizationName_default = World Wide Web Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
#organizationalUnitName_default =
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 64
# SET-ex3 = SET extension number 3
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
unstructuredName = An optional company name
[ usr_cert ]
authorityInfoAccess = OCSP;URI:http://127.0.0.1:6655
# These extensions are added when 'ca' signs a request.
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints=CA:FALSE
# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move
# Copy subject details
# issuerAltName=issuer:copy
# This is required for TSA certificates.
# extendedKeyUsage = critical,timeStamping
[ v3_ocsp ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = OCSPSigning
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
[ v3_ca ]
# Extensions for a typical CA
# PKIX recommendation.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
keyUsage = critical, cRLSign, digitalSignature, keyCertSign
basicConstraints = critical,CA:true
# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign
# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy
# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF
[ crl_ext ]
# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always
[ proxy_cert_ext ]
# These extensions should be added when creating a proxy certificate
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints=CA:FALSE
# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move
# Copy subject details
# issuerAltName=issuer:copy
# This really needs to be in place for it to be a proxy certificate.
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo
####################################################################
[ tsa ]
default_tsa = tsa_config1 # the default TSA section
[ tsa_config1 ]
# These are used by the TSA reply generation only.
dir = ./demoCA # TSA root directory
serial = $dir/tsaserial # The current serial number (mandatory)
crypto_device = builtin # OpenSSL engine to use for signing
signer_cert = $dir/tsacert.pem # The TSA signing certificate
# (optional)
certs = $dir/cacert.pem # Certificate chain to include in reply
# (optional)
signer_key = $dir/private/tsakey.pem # The TSA private key (optional)
signer_digest = sha256 # Signing digest to use. (Optional)
default_policy = tsa_policy1 # Policy if request did not specify it
# (optional)
other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional)
digests = sha1, sha256, sha384, sha512 # Acceptable message digests
(mandatory)
accuracy = secs:1, millisecs:500, microsecs:100 # (optional)
clock_precision_digits = 0 # number of digits after dot. (optional)
ordering = yes # Is ordering defined for timestamps?
# (optional, default: no)
tsa_name = yes # Must the TSA name be included in the reply?
# (optional, default: no)
ess_cert_id_chain = no # Must the ESS cert id chain be included?
# (optional, default: no)
ess_cert_id_alg = sha1 # algorithm to compute certificate
# identifier (optional, default: sha1)
[insta] # CMP using Insta Demo CA
# Message transfer
server = pki.certificate.fi:8700
# proxy = # set this as far as needed, e.g., http://192.168.1.1:8080
# tls_use = 0
path = pkix/
# Server authentication
recipient = "/C=FI/O=Insta Demo/CN=Insta Demo CA" # or set srvcert or issuer
ignore_keyusage = 1 # potentially needed quirk
unprotected_errors = 1 # potentially needed quirk
extracertsout = insta.extracerts.pem
# Client authentication
ref = 3078 # user identification
secret = pass:insta # can be used for both client and server side
# Generic message options
cmd = ir # default operation, can be overridden on cmd line with, e.g., kur
# Certificate enrollment
subject = "/CN=openssl-cmp-test"
newkey = insta.priv.pem
out_trusted = insta.ca.crt
certout = insta.cert.pem
[pbm] # Password-based protection for Insta CA
# Server and client authentication
ref = $insta::ref # 3078
secret = $insta::secret # pass:insta
[signature] # Signature-based protection for Insta CA
# Server authentication
trusted = insta.ca.crt # does not include keyUsage digitalSignature
# Client authentication
secret = # disable PBM
key = $insta::newkey # insta.priv.pem
cert = $insta::certout # insta.cert.pem
[ir]
cmd = ir
[cr]
cmd = cr
[kur]
# Certificate update
cmd = kur
oldcert = $insta::certout # insta.cert.pem
[rr]
# Certificate revocation
cmd = rr
oldcert = $insta::certout # insta.cert.pem
[ssl_sect]
system_default = system_default_sect
[system_default_sect]
CipherString = DEFAULT:@SECLEVEL=2
From 6eb920de994ed6822494f29c141ba913547f7ee4 Mon Sep 17 00:00:00 2001
From: David Zhang <idraw...@gmail.com>
Date: Fri, 2 Feb 2024 10:11:43 -0800
Subject: [PATCH] support certificate status check using OCSP stapling
---
src/backend/libpq/be-secure-openssl.c | 87 +++++++++++
src/backend/libpq/be-secure.c | 1 +
src/backend/utils/misc/guc_tables.c | 10 ++
src/backend/utils/misc/postgresql.conf.sample | 1 +
src/include/libpq/libpq.h | 1 +
src/interfaces/libpq/fe-connect.c | 37 +++++
src/interfaces/libpq/fe-secure-openssl.c | 137 ++++++++++++++++++
src/interfaces/libpq/libpq-int.h | 1 +
8 files changed, 275 insertions(+)
diff --git a/src/backend/libpq/be-secure-openssl.c
b/src/backend/libpq/be-secure-openssl.c
index e12b1cc9e3..c727634dfa 100644
--- a/src/backend/libpq/be-secure-openssl.c
+++ b/src/backend/libpq/be-secure-openssl.c
@@ -50,6 +50,7 @@
#include <openssl/ec.h>
#endif
#include <openssl/x509v3.h>
+#include <openssl/ocsp.h>
/* default init hook can be overridden by a shared library */
@@ -81,6 +82,8 @@ static bool ssl_is_server_start;
static int ssl_protocol_version_to_openssl(int v);
static const char *ssl_protocol_version_to_string(int v);
+static int ocsp_stapling_cb(SSL *ssl);
+
/* for passing data back from verify_cb() */
static const char *cert_errdetail;
@@ -429,6 +432,9 @@ be_tls_open_server(Port *port)
return -1;
}
+ /* set up OCSP stapling callback */
+ SSL_CTX_set_tlsext_status_cb(SSL_context, ocsp_stapling_cb);
+
/* set up debugging/info callback */
SSL_CTX_set_info_callback(SSL_context, info_cb);
@@ -1653,3 +1659,84 @@ default_openssl_tls_init(SSL_CTX *context, bool
isServerStart)
SSL_CTX_set_default_passwd_cb(context,
dummy_ssl_passwd_cb);
}
}
+
+/*
+ * OCSP stapling callback function for the server side.
+ *
+ * This function is responsible for providing the OCSP stapling response to
+ * the client during the SSL/TLS handshake, based on the client's request.
+ *
+ * Parameters:
+ * - ssl: SSL/TLS connection object.
+ *
+ * Returns:
+ * - SSL_TLSEXT_ERR_OK: OCSP stapling response successfully provided.
+ * - SSL_TLSEXT_ERR_NOACK: OCSP stapling response not provided due to errors.
+ *
+ * Steps:
+ * 1. Check if the server-side OCSP stapling feature is enabled.
+ * 2. Read OCSP response from file if client requested OCSP stapling.
+ * 3. Set the OCSP stapling response in the SSL/TLS connection.
+ */
+static int ocsp_stapling_cb(SSL *ssl)
+{
+ int resp_len = -1;
+ BIO *bio = NULL;
+ OCSP_RESPONSE *resp = NULL;
+ unsigned char *rspder = NULL;
+
+ /* return, if ssl_ocsp_file not enabled on server */
+ if (ssl_ocsp_file == NULL)
+ {
+ ereport(WARNING,
+ (errcode(ERRCODE_CONFIG_FILE_ERROR),
+ errmsg("could not find ssl_ocsp_file")));
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+
+ /* whether the client requested OCSP stapling */
+ if (SSL_get_tlsext_status_type(ssl) == TLSEXT_STATUSTYPE_ocsp)
+ {
+ bio = BIO_new_file(ssl_ocsp_file, "r");
+ if (bio == NULL)
+ {
+ ereport(WARNING,
+ (errcode(ERRCODE_CONFIG_FILE_ERROR),
+ errmsg("could not read
ssl_ocsp_file")));
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+
+ resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
+ BIO_free(bio);
+ if (resp == NULL)
+ {
+ ereport(WARNING,
+ (errcode(ERRCODE_PROTOCOL_VIOLATION),
+ errmsg("could not convert OCSP
response to intarnal format")));
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+
+ resp_len = i2d_OCSP_RESPONSE(resp, &rspder);
+ OCSP_RESPONSE_free(resp);
+ if (resp_len <= 0)
+ {
+ ereport(WARNING,
+ (errcode(ERRCODE_PROTOCOL_VIOLATION),
+ errmsg("could not convert OCSP
response to der format")));
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+
+ /* set up the OCSP stapling response */
+ if (SSL_set_tlsext_status_ocsp_resp(ssl, rspder, resp_len) != 1)
+ {
+ ereport(WARNING,
+ (errcode(ERRCODE_PROTOCOL_VIOLATION),
+ errmsg("could not set up OCSP stapling
response")));
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+
+ return SSL_TLSEXT_ERR_OK;
+ }
+
+ return SSL_TLSEXT_ERR_NOACK;
+}
diff --git a/src/backend/libpq/be-secure.c b/src/backend/libpq/be-secure.c
index 6923c241b9..c57ea4ff33 100644
--- a/src/backend/libpq/be-secure.c
+++ b/src/backend/libpq/be-secure.c
@@ -37,6 +37,7 @@
char *ssl_library;
char *ssl_cert_file;
+char *ssl_ocsp_file;
char *ssl_key_file;
char *ssl_ca_file;
char *ssl_crl_file;
diff --git a/src/backend/utils/misc/guc_tables.c
b/src/backend/utils/misc/guc_tables.c
index 7fe58518d7..83a49c6144 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -4479,6 +4479,16 @@ struct config_string ConfigureNamesString[] =
NULL, NULL, NULL
},
+ {
+ {"ssl_ocsp_file", PGC_SIGHUP, CONN_AUTH_SSL,
+ gettext_noop("Location of the SSL certificate OCSP
stapling file."),
+ NULL
+ },
+ &ssl_ocsp_file,
+ "",
+ NULL, NULL, NULL
+ },
+
{
{"synchronous_standby_names", PGC_SIGHUP, REPLICATION_PRIMARY,
gettext_noop("Number of synchronous standbys and list
of names of potential synchronous ones."),
diff --git a/src/backend/utils/misc/postgresql.conf.sample
b/src/backend/utils/misc/postgresql.conf.sample
index da10b43dac..608dead52b 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -107,6 +107,7 @@
#ssl = off
#ssl_ca_file = ''
#ssl_cert_file = 'server.crt'
+#ssl_ocsp_file = 'server.resp'
#ssl_crl_file = ''
#ssl_crl_dir = ''
#ssl_key_file = 'server.key'
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index 6171a0d17a..edef65fd39 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -89,6 +89,7 @@ extern bool pq_check_connection(void);
*/
extern PGDLLIMPORT char *ssl_library;
extern PGDLLIMPORT char *ssl_cert_file;
+extern PGDLLIMPORT char *ssl_ocsp_file;
extern PGDLLIMPORT char *ssl_key_file;
extern PGDLLIMPORT char *ssl_ca_file;
extern PGDLLIMPORT char *ssl_crl_file;
diff --git a/src/interfaces/libpq/fe-connect.c
b/src/interfaces/libpq/fe-connect.c
index c0dea144a0..e8878df4fb 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -324,6 +324,10 @@ static const internalPQconninfoOption PQconninfoOptions[]
= {
"SSL-Maximum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") ==
8 */
offsetof(struct pg_conn, ssl_max_protocol_version)},
+ {"ssl_ocsp_stapling", "PGSSLOCSPSTAPLING", "0", NULL,
+ "SSL-OCSP-Stapling", "", 1,
+ offsetof(struct pg_conn, ssl_ocsp_stapling)},
+
/*
* As with SSL, all GSS options are exposed even in builds that don't
have
* support.
@@ -443,6 +447,7 @@ static void pgpassfileWarning(PGconn *conn);
static void default_threadlock(int acquire);
static bool sslVerifyProtocolVersion(const char *version);
static bool sslVerifyProtocolRange(const char *min, const char *max);
+static bool sslVerifyOcspStapling(const char *stapling);
/* global variable because fe-auth.c needs to access it */
@@ -1581,6 +1586,18 @@ connectOptions2(PGconn *conn)
return false;
}
+ /*
+ * Validate ssl_ocsp_stapling settings
+ */
+ if (!sslVerifyOcspStapling(conn->ssl_ocsp_stapling))
+ {
+ conn->status = CONNECTION_BAD;
+ libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
+
"ssl_ocsp_stapling",
+
conn->ssl_ocsp_stapling);
+ return false;
+ }
+
/*
* validate sslcertmode option
*/
@@ -4405,6 +4422,7 @@ freePGconn(PGconn *conn)
free(conn->require_auth);
free(conn->ssl_min_protocol_version);
free(conn->ssl_max_protocol_version);
+ free(conn->ssl_ocsp_stapling);
free(conn->gssencmode);
free(conn->krbsrvname);
free(conn->gsslib);
@@ -7318,6 +7336,25 @@ sslVerifyProtocolRange(const char *min, const char *max)
return true;
}
+/*
+ * Check ssl_ocsp_stapling is set properly
+ */
+static bool
+sslVerifyOcspStapling(const char *stapling)
+{
+ /*
+ * An empty string or a NULL value is considered valid
+ */
+ if (!stapling || strlen(stapling) == 0)
+ return true;
+
+ if (pg_strcasecmp(stapling, "0") == 0 ||
+ pg_strcasecmp(stapling, "1") == 0)
+ return true;
+
+ /* anything else is wrong */
+ return false;
+}
/*
* Obtain user's home directory, return in given buffer
diff --git a/src/interfaces/libpq/fe-secure-openssl.c
b/src/interfaces/libpq/fe-secure-openssl.c
index 6bc216956d..aa0b1bf130 100644
--- a/src/interfaces/libpq/fe-secure-openssl.c
+++ b/src/interfaces/libpq/fe-secure-openssl.c
@@ -62,6 +62,7 @@
#include <openssl/engine.h>
#endif
#include <openssl/x509v3.h>
+#include <openssl/ocsp.h>
static int verify_cb(int ok, X509_STORE_CTX *ctx);
@@ -100,6 +101,9 @@ static long win32_ssl_create_mutex = 0;
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook = NULL;
static int ssl_protocol_version_to_openssl(const char *protocol);
+static int ocsp_response_check_cb(SSL *ssl);
+#define OCSP_CERT_STATUS_OK 1
+#define OCSP_CERT_STATUS_NOK (-1)
/* ------------------------------------------------------------ */
/* Procedures common to all secure sessions
*/
@@ -1202,6 +1206,36 @@ initialize_SSL(PGconn *conn)
have_cert = true;
}
+ /* Enable OCSP stapling for certificate status check */
+ if (conn->ssl_ocsp_stapling &&
+ strlen(conn->ssl_ocsp_stapling) != 0 &&
+ (strcmp(conn->ssl_ocsp_stapling, "1") == 0))
+ {
+ /* set up certificate status request */
+ if (SSL_CTX_set_tlsext_status_type(SSL_context,
+ TLSEXT_STATUSTYPE_ocsp) != 1)
+ {
+ char *err = SSLerrmessage(ERR_get_error());
+ libpq_append_conn_error(conn,
+ "could not set up certificate status
request: %s", err);
+ SSLerrfree(err);
+ SSL_CTX_free(SSL_context);
+ return -1;
+ }
+
+ /* set up OCSP response callback */
+ if (SSL_CTX_set_tlsext_status_cb(SSL_context,
+ ocsp_response_check_cb) <= 0)
+ {
+ char *err = SSLerrmessage(ERR_get_error());
+ libpq_append_conn_error(conn,
+ "could not set up OCSP response
callback: %s", err);
+ SSLerrfree(err);
+ SSL_CTX_free(SSL_context);
+ return -1;
+ }
+ }
+
/*
* The SSL context is now loaded with the correct root and client
* certificates. Create a connection-specific SSL object. The private
key
@@ -2063,3 +2097,106 @@ ssl_protocol_version_to_openssl(const char *protocol)
return -1;
}
+
+
+/*
+ * Verify OCSP stapling response in the context of an SSL/TLS connection.
+ *
+ * This function checks whether the server provided an OCSP response
+ * as part of the TLS handshake, verifies its integrity, and checks the
+ * revocation status of the presented certificates.
+ *
+ * Parameters:
+ * - ssl: SSL/TLS connection object.
+ *
+ * Returns:
+ * - OCSP_CERT_STATUS_OK: OCSP stapling was not requested or status is OK.
+ * - OCSP_CERT_STATUS_NOK: OCSP verification failed or status is not OK.
+ *
+ * Steps:
+ * 1. Retrieve OCSP response during handshake.
+ * 2. Perform basic OCSP response verification.
+ * 3. Verify each revocation status in the OCSP response.
+ *
+ * Cleanup:
+ * - Free allocated memory for the OCSP response and basic response.
+ */
+static int ocsp_response_check_cb(SSL *ssl)
+{
+ const unsigned char *resp;
+ long resp_len = 0;
+ int cert_index = 0;
+ int num_of_resp = 0;
+ OCSP_RESPONSE *ocsp_resp = NULL;
+ OCSP_BASICRESP *basic_resp = NULL;
+ OCSP_SINGLERESP *single_resp = NULL;
+ int status = OCSP_CERT_STATUS_NOK;
+
+ /*
+ * step-1: retrieve OCSP response
+ * refer to 'ocsp_resp_cb' in openssl/apps/s_client.c
+ */
+ /* check if requested certificate status */
+ if (SSL_get_tlsext_status_type(ssl) != TLSEXT_STATUSTYPE_ocsp)
+ return OCSP_CERT_STATUS_OK;
+
+ /* check if got OCSP response */
+ resp_len = SSL_get_tlsext_status_ocsp_resp(ssl, &resp);
+ if (resp == NULL)
+ goto cleanup; /* no OCSP response */
+
+ /* convert OCSP response to internal format */
+ ocsp_resp = d2i_OCSP_RESPONSE(NULL, &resp, resp_len);
+ if (ocsp_resp == NULL)
+ goto cleanup; /* failed to convert OCSP response */
+
+ /*
+ * step-2: verify the basic of OCSP response
+ * refer to 'ocsp_main' in openssl/apps/ocsp.c
+ */
+ if (OCSP_response_status(ocsp_resp) != OCSP_RESPONSE_STATUS_SUCCESSFUL)
+ goto cleanup; /* OCSP response not successful */
+
+ /* get OCSP basic response structure */
+ basic_resp = OCSP_response_get1_basic(ocsp_resp);
+ if (basic_resp == NULL)
+ goto cleanup; /* failed to get basic OCSP response */
+
+ /* perform basic OCSP response verify */
+ if (OCSP_basic_verify(basic_resp, SSL_get_peer_cert_chain(ssl),
+ SSL_CTX_get_cert_store(SSL_get_SSL_CTX(ssl)), 0) != 1)
+ goto cleanup; /* basic verification failed */
+
+ /*
+ * step-3: verify each revocation status
+ * ref to 'ct_extract_ocsp_response_scts' in openssl/ssl/ssl_lib.c
+ */
+ num_of_resp = OCSP_resp_count(basic_resp);
+ for (cert_index = 0; cert_index < num_of_resp; cert_index ++)
+ {
+ single_resp = OCSP_resp_get0(basic_resp, cert_index);
+ if (single_resp == NULL)
+ goto cleanup; /* failed to get single response */
+
+ if (OCSP_single_get0_status(single_resp, NULL, NULL, NULL, NULL)
+ == V_OCSP_CERTSTATUS_GOOD)
+ continue; /* status is good */
+ else
+ {
+ /* status is revoked or unknown */
+ status = OCSP_CERT_STATUS_NOK;
+ break;
+ }
+ }
+ if (cert_index == num_of_resp)
+ status = OCSP_CERT_STATUS_OK;
+
+cleanup:
+ if (ocsp_resp != NULL)
+ OCSP_RESPONSE_free(ocsp_resp);
+
+ if (basic_resp != NULL)
+ OCSP_BASICRESP_free(basic_resp);
+
+ return status;
+}
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index ff8e0dce77..a2ac07b64d 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -405,6 +405,7 @@ struct pg_conn
char *gssdelegation; /* Try to delegate GSS credentials? (0
or 1) */
char *ssl_min_protocol_version; /* minimum TLS protocol version
*/
char *ssl_max_protocol_version; /* maximum TLS protocol version
*/
+ char *ssl_ocsp_stapling; /* request ocsp stapling from server */
char *target_session_attrs; /* desired session properties */
char *require_auth; /* name of the expected auth method */
char *load_balance_hosts; /* load balance over hosts */
--
2.34.1