1/*-------------------------------------------------------------------------
4 * functions for OpenSSL support in the backend.
7 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * src/backend/libpq/be-secure-openssl.c
14 *-------------------------------------------------------------------------
40 * These SSL-related #includes must come after all system-provided headers.
41 * This ensures that OpenSSL can take care of conflicts with Windows'
42 * <wincrypt.h> by #undef'ing the conflicting macros. (We don't directly
43 * include <wincrypt.h>, but some other Windows headers do.)
46#include <openssl/bn.h>
47#include <openssl/conf.h>
48#include <openssl/dh.h>
49#ifndef OPENSSL_NO_ECDH
50#include <openssl/ec.h>
52#include <openssl/x509v3.h>
55/* default init hook can be overridden by a shared library */
68static int verify_cb(
int ok, X509_STORE_CTX *ctx);
71 const unsigned char **out,
72 unsigned char *outlen,
73 const unsigned char *in,
76static bool initialize_dh(SSL_CTX *context,
bool isServerStart);
78static const char *
SSLerrmessageExt(
unsigned long ecode,
const char *replacement);
90/* for passing data back from verify_cb() */
93/* ------------------------------------------------------------ */
95/* ------------------------------------------------------------ */
101 int ssl_ver_min = -1;
102 int ssl_ver_max = -1;
105 * Create a new SSL context into which we'll load all the configuration
106 * settings. If we fail partway through, we can avoid memory leakage by
107 * freeing this context; we don't install it as active until the end.
109 * We use SSLv23_method() because it can negotiate use of the highest
110 * mutually supported protocol version, while alternatives like
111 * TLSv1_2_method() permit only one specific version. Note that we don't
112 * actually allow SSL v2 or v3, only TLS protocols (see below).
114 context = SSL_CTX_new(SSLv23_method());
118 (
errmsg(
"could not create SSL context: %s",
124 * Disable OpenSSL's moving-write-buffer sanity check, because it causes
125 * unnecessary failures in nonblocking send cases.
127 SSL_CTX_set_mode(context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
130 * Call init hook (usually to set password callback)
132 (*openssl_tls_init_hook) (context, isServerStart);
134 /* used by the callback */
138 * Load and verify server's certificate and private key
140 if (SSL_CTX_use_certificate_chain_file(context,
ssl_cert_file) != 1)
143 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
144 errmsg(
"could not load server certificate file \"%s\": %s",
153 * OK, try to load the private key file.
157 if (SSL_CTX_use_PrivateKey_file(context,
159 SSL_FILETYPE_PEM) != 1)
163 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
164 errmsg(
"private key file \"%s\" cannot be reloaded because it requires a passphrase",
168 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
169 errmsg(
"could not load private key file \"%s\": %s",
174 if (SSL_CTX_check_private_key(context) != 1)
177 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
178 errmsg(
"check of private key failed: %s",
187 if (ssl_ver_min == -1)
190 /*- translator: first %s is a GUC option name, second %s is its value */
191 (
errmsg(
"\"%s\" setting \"%s\" not supported by this build",
192 "ssl_min_protocol_version",
198 if (!SSL_CTX_set_min_proto_version(context, ssl_ver_min))
201 (
errmsg(
"could not set minimum SSL protocol version")));
210 if (ssl_ver_max == -1)
213 /*- translator: first %s is a GUC option name, second %s is its value */
214 (
errmsg(
"\"%s\" setting \"%s\" not supported by this build",
215 "ssl_max_protocol_version",
221 if (!SSL_CTX_set_max_proto_version(context, ssl_ver_max))
224 (
errmsg(
"could not set maximum SSL protocol version")));
229 /* Check compatibility of min/max protocols */
234 * No need to check for invalid values (-1) for each protocol number
235 * as the code above would have already generated an error.
237 if (ssl_ver_min > ssl_ver_max)
240 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
241 errmsg(
"could not set SSL protocol version range"),
242 errdetail(
"\"%s\" cannot be higher than \"%s\"",
243 "ssl_min_protocol_version",
244 "ssl_max_protocol_version")));
250 * Disallow SSL session tickets. OpenSSL use both stateful and stateless
251 * tickets for TLSv1.3, and stateless ticket for TLSv1.2. SSL_OP_NO_TICKET
252 * is available since 0.9.8f but only turns off stateless tickets. In
253 * order to turn off stateful tickets we need SSL_CTX_set_num_tickets,
254 * which is available since OpenSSL 1.1.1. LibreSSL 3.5.4 (from OpenBSD
255 * 7.1) introduced this API for compatibility, but doesn't support session
256 * tickets at all so it's a no-op there.
258#ifdef HAVE_SSL_CTX_SET_NUM_TICKETS
259 SSL_CTX_set_num_tickets(context, 0);
261 SSL_CTX_set_options(context, SSL_OP_NO_TICKET);
263 /* disallow SSL session caching, too */
264 SSL_CTX_set_session_cache_mode(context, SSL_SESS_CACHE_OFF);
266 /* disallow SSL compression */
267 SSL_CTX_set_options(context, SSL_OP_NO_COMPRESSION);
270 * Disallow SSL renegotiation. This concerns only TLSv1.2 and older
271 * protocol versions, as TLSv1.3 has no support for renegotiation.
272 * SSL_OP_NO_RENEGOTIATION is available in OpenSSL since 1.1.0h (via a
273 * backport from 1.1.1). SSL_OP_NO_CLIENT_RENEGOTIATION is available in
274 * LibreSSL since 2.5.1 disallowing all client-initiated renegotiation
275 * (this is usually on by default).
277#ifdef SSL_OP_NO_RENEGOTIATION
278 SSL_CTX_set_options(context, SSL_OP_NO_RENEGOTIATION);
280#ifdef SSL_OP_NO_CLIENT_RENEGOTIATION
281 SSL_CTX_set_options(context, SSL_OP_NO_CLIENT_RENEGOTIATION);
284 /* set up ephemeral DH and ECDH keys */
290 /* set up the allowed cipher list for TLSv1.2 and below */
294 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
295 errmsg(
"could not set the TLSv1.2 cipher list (no valid ciphers available)")));
300 * Set up the allowed cipher suites for TLSv1.3. If the GUC is an empty
301 * string we leave the allowed suites to be the OpenSSL default value.
305 /* set up the allowed cipher suites */
309 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
310 errmsg(
"could not set the TLSv1.3 cipher suites (no valid ciphers available)")));
315 /* Let server choose order */
317 SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
320 * Load CA store, so we can verify client certificates if needed.
324 STACK_OF(X509_NAME) * root_cert_list;
326 if (SSL_CTX_load_verify_locations(context,
ssl_ca_file, NULL) != 1 ||
327 (root_cert_list = SSL_load_client_CA_file(
ssl_ca_file)) == NULL)
330 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
331 errmsg(
"could not load root certificate file \"%s\": %s",
337 * Tell OpenSSL to send the list of root certs we trust to clients in
338 * CertificateRequests. This lets a client with a keystore select the
339 * appropriate client certificate to send to us. Also, this ensures
340 * that the SSL context will "own" the root_cert_list and remember to
341 * free it when no longer needed.
343 SSL_CTX_set_client_CA_list(context, root_cert_list);
346 * Always ask for SSL client cert, but don't fail if it's not
347 * presented. We might fail such connections later, depending on what
348 * we find in pg_hba.conf.
350 SSL_CTX_set_verify(context,
352 SSL_VERIFY_CLIENT_ONCE),
357 * Load the Certificate Revocation List (CRL).
358 * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
363 X509_STORE *cvstore = SSL_CTX_get_cert_store(context);
367 /* Set the flags to check against the complete CRL chain */
368 if (X509_STORE_load_locations(cvstore,
373 X509_STORE_set_flags(cvstore,
374 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
379 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
380 errmsg(
"could not load SSL certificate revocation list file \"%s\": %s",
387 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
388 errmsg(
"could not load SSL certificate revocation list directory \"%s\": %s",
395 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
396 errmsg(
"could not load SSL certificate revocation list file \"%s\" or directory \"%s\": %s",
405 * Success! Replace any existing SSL_context.
413 * Set flag to remember whether CA store has been loaded into SSL_context.
416 ssl_loaded_verify_locations =
true;
418 ssl_loaded_verify_locations =
false;
422 /* Clean up by releasing working context. */
425 SSL_CTX_free(context);
435 ssl_loaded_verify_locations =
false;
445 bool give_proto_hint;
453 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
454 errmsg(
"could not initialize SSL connection: SSL context not set up")));
458 /* set up debugging/info callback */
467 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
468 errmsg(
"could not initialize SSL connection: %s",
475 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
476 errmsg(
"could not set SSL socket: %s",
480 port->ssl_in_use =
true;
485 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
486 * queue. In general, the current thread's error queue must be empty
487 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
488 * not work reliably. An extension may have failed to clear the
489 * per-thread error queue following another call to an OpenSSL I/O
494 r = SSL_accept(
port->ssl);
497 err = SSL_get_error(
port->ssl, r);
500 * Other clients of OpenSSL in the backend may fail to call
501 * ERR_get_error(), but we always do, so as to not cause problems for
502 * OpenSSL clients that don't call ERR_clear_error() defensively. Be
503 * sure that this happens by calling now. SSL_get_error() relies on
504 * the OpenSSL per-thread error queue being intact, so this is the
505 * earliest possible point ERR_get_error() may be called.
507 ecode = ERR_get_error();
510 case SSL_ERROR_WANT_READ:
511 case SSL_ERROR_WANT_WRITE:
512 /* not allowed during connection establishment */
516 * No need to care about timeouts/interrupts here. At this
517 * point authentication_timeout still employs
518 * StartupPacketTimeoutHandler() which directly exits.
520 if (
err == SSL_ERROR_WANT_READ)
526 WAIT_EVENT_SSL_OPEN_SERVER);
528 case SSL_ERROR_SYSCALL:
529 if (r < 0 && errno != 0)
532 errmsg(
"could not accept SSL connection: %m")));
535 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
536 errmsg(
"could not accept SSL connection: EOF detected")));
539 switch (ERR_GET_REASON(ecode))
542 * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
543 * TLSV1_ALERT_PROTOCOL_VERSION have been observed
544 * when trying to communicate with an old OpenSSL
545 * library, or when the client and server specify
546 * disjoint protocol ranges. NO_PROTOCOLS_AVAILABLE
547 * occurs if there's a local misconfiguration (which
548 * can happen despite our checks, if openssl.cnf
549 * injects a limit we didn't account for). It's not
550 * very clear what would make OpenSSL return the other
551 * codes listed here, but a hint about protocol
552 * versions seems like it's appropriate for all.
554 case SSL_R_NO_PROTOCOLS_AVAILABLE:
555 case SSL_R_UNSUPPORTED_PROTOCOL:
556 case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
557 case SSL_R_UNKNOWN_PROTOCOL:
558 case SSL_R_UNKNOWN_SSL_VERSION:
559 case SSL_R_UNSUPPORTED_SSL_VERSION:
560 case SSL_R_WRONG_SSL_VERSION:
561 case SSL_R_WRONG_VERSION_NUMBER:
562 case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
563#ifdef SSL_R_VERSION_TOO_HIGH
564 case SSL_R_VERSION_TOO_HIGH:
566#ifdef SSL_R_VERSION_TOO_LOW
567 case SSL_R_VERSION_TOO_LOW:
569 give_proto_hint =
true;
572 give_proto_hint =
false;
576 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
577 errmsg(
"could not accept SSL connection: %s",
581 errhint(
"This may indicate that the client does not support any SSL protocol version between %s and %s.",
584 MIN_OPENSSL_TLS_VERSION,
587 MAX_OPENSSL_TLS_VERSION) : 0));
590 case SSL_ERROR_ZERO_RETURN:
592 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
593 errmsg(
"could not accept SSL connection: EOF detected")));
597 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
598 errmsg(
"unrecognized SSL error code: %d",
605 /* Get the protocol selected by ALPN */
606 port->alpn_used =
false;
608 const unsigned char *selected;
611 SSL_get0_alpn_selected(
port->ssl, &selected, &
len);
613 /* If ALPN is used, check that we negotiated the expected protocol */
614 if (selected != NULL)
619 port->alpn_used =
true;
623 /* shouldn't happen */
625 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
626 errmsg(
"received SSL connection request with unexpected ALPN protocol")));
631 /* Get client certificate, if available. */
632 port->peer = SSL_get_peer_certificate(
port->ssl);
634 /* and extract the Common Name and Distinguished Name from it. */
635 port->peer_cn = NULL;
636 port->peer_dn = NULL;
637 port->peer_cert_valid =
false;
638 if (
port->peer != NULL)
641 X509_NAME *x509name = X509_get_subject_name(
port->peer);
644 BUF_MEM *bio_buf = NULL;
646 len = X509_NAME_get_text_by_NID(x509name, NID_commonName, NULL, 0);
652 r = X509_NAME_get_text_by_NID(x509name, NID_commonName, peer_cn,
657 /* shouldn't happen */
663 * Reject embedded NULLs in certificate common name to prevent
664 * attacks like CVE-2009-4034.
666 if (
len != strlen(peer_cn))
669 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
670 errmsg(
"SSL certificate's common name contains embedded null")));
675 port->peer_cn = peer_cn;
678 bio = BIO_new(BIO_s_mem());
681 if (
port->peer_cn != NULL)
684 port->peer_cn = NULL;
690 * RFC2253 is the closest thing to an accepted standard format for
691 * DNs. We have documented how to produce this format from a
692 * certificate. It uses commas instead of slashes for delimiters,
693 * which make regular expression matching a bit easier. Also note that
694 * it prints the Subject fields in reverse order.
696 if (X509_NAME_print_ex(bio, x509name, 0, XN_FLAG_RFC2253) == -1 ||
697 BIO_get_mem_ptr(bio, &bio_buf) <= 0)
700 if (
port->peer_cn != NULL)
703 port->peer_cn = NULL;
708 memcpy(peer_dn, bio_buf->data, bio_buf->length);
709 len = bio_buf->length;
712 if (
len != strlen(peer_dn))
715 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
716 errmsg(
"SSL certificate's distinguished name contains embedded null")));
718 if (
port->peer_cn != NULL)
721 port->peer_cn = NULL;
726 port->peer_dn = peer_dn;
728 port->peer_cert_valid =
true;
739 SSL_shutdown(
port->ssl);
742 port->ssl_in_use =
false;
747 X509_free(
port->peer);
754 port->peer_cn = NULL;
760 port->peer_dn = NULL;
773 n = SSL_read(
port->ssl, ptr,
len);
774 err = SSL_get_error(
port->ssl, n);
775 ecode = (
err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
781 case SSL_ERROR_WANT_READ:
786 case SSL_ERROR_WANT_WRITE:
791 case SSL_ERROR_SYSCALL:
792 /* leave it to caller to ereport the value of errno */
793 if (n != -1 || errno == 0)
801 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
806 case SSL_ERROR_ZERO_RETURN:
807 /* connection was cleanly shut down by peer */
812 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
813 errmsg(
"unrecognized SSL error code: %d",
832 n = SSL_write(
port->ssl, ptr,
len);
833 err = SSL_get_error(
port->ssl, n);
834 ecode = (
err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
840 case SSL_ERROR_WANT_READ:
845 case SSL_ERROR_WANT_WRITE:
850 case SSL_ERROR_SYSCALL:
853 * Leave it to caller to ereport the value of errno. However, if
854 * errno is still zero then assume it's a read EOF situation, and
855 * report ECONNRESET. (This seems possible because SSL_write can
858 if (n != -1 || errno == 0)
866 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
871 case SSL_ERROR_ZERO_RETURN:
874 * the SSL connection was closed, leave it to the caller to
882 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
883 errmsg(
"unrecognized SSL error code: %d",
893/* ------------------------------------------------------------ */
894/* Internal functions */
895/* ------------------------------------------------------------ */
898 * Private substitute BIO: this does the sending and receiving using send() and
899 * recv() instead. This is so that we can enable and disable interrupts
900 * just while calling recv(). We cannot have interrupts occurring while
901 * the bulk of OpenSSL runs, because it uses malloc() and possibly other
902 * non-reentrant libc facilities. We also need to call send() and recv()
903 * directly so it gets passed through the socket/signals layer on Win32.
905 * These functions are closely modelled on the standard socket BIO in OpenSSL;
906 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
920 BIO_clear_retry_flags(h);
921 port->last_read_was_eof = res == 0;
924 /* If we were interrupted, tell caller to retry */
927 BIO_set_retry_read(h);
941 BIO_clear_retry_flags(h);
944 /* If we were interrupted, tell caller to retry */
947 BIO_set_retry_write(h);
965 * This should not be needed. port_bio_read already has a way to
966 * signal EOF to OpenSSL. However, OpenSSL made an undocumented,
967 * backwards-incompatible change and now expects EOF via BIO_ctrl.
968 * See https://github.com/openssl/openssl/issues/8208
970 res =
port->last_read_was_eof;
973 /* libssl expects all BIOs to support BIO_flush. */
991 my_bio_index = BIO_get_new_index();
992 if (my_bio_index == -1)
994 my_bio_index |= BIO_TYPE_SOURCE_SINK;
1014 BIO_METHOD *bio_method;
1017 if (bio_method == NULL)
1020 bio = BIO_new(bio_method);
1024 BIO_set_data(bio,
port);
1025 BIO_set_init(bio, 1);
1027 SSL_set_bio(
port->ssl, bio, bio);
1032 * Load precomputed DH parameters.
1034 * To prevent "downgrade" attacks, we perform a number of checks
1035 * to verify that the DBA-generated DH parameters file contains
1036 * what we expect it to contain.
1045 /* attempt to open file. It's not an error if it doesn't exist. */
1050 errmsg(
"could not open DH parameters file \"%s\": %m",
1055 dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
1061 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
1062 errmsg(
"could not load DH parameters file: %s",
1067 /* make sure the DH parameters are usable */
1068 if (DH_check(dh, &codes) == 0)
1071 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
1072 errmsg(
"invalid DH parameters: %s",
1077 if (codes & DH_CHECK_P_NOT_PRIME)
1080 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
1081 errmsg(
"invalid DH parameters: p is not prime")));
1085 if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
1086 (codes & DH_CHECK_P_NOT_SAFE_PRIME))
1089 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
1090 errmsg(
"invalid DH parameters: neither suitable generator or safe prime")));
1099 * Load hardcoded DH parameters.
1101 * If DH parameters cannot be loaded from a specified file, we can load
1102 * the hardcoded DH parameters supplied with the backend to prevent
1111 bio = BIO_new_mem_buf(buffer,
len);
1114 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1125 * Passphrase collection callback using ssl_passphrase_command
1130 /* same prompt as OpenSSL uses internally */
1131 const char *prompt =
"Enter PEM pass phrase:";
1139 * Dummy passphrase callback
1141 * If OpenSSL is told to use a passphrase-protected server key, by default
1142 * it will issue a prompt on /dev/tty and try to read a key from there.
1143 * That's no good during a postmaster SIGHUP cycle, not to mention SSL context
1144 * reload in an EXEC_BACKEND postmaster child. So override it with this dummy
1145 * function that just returns an empty passphrase, guaranteeing failure.
1150 /* Set flag to change the error message we'll report */
1152 /* And return empty string */
1159 * Examines the provided certificate name, and if it's too long to log or
1160 * contains unprintable ASCII, escapes and truncates it. The return value is
1161 * always a new palloc'd string. (The input string is still modified in place,
1162 * for ease of implementation.)
1167 size_t namelen = strlen(
name);
1168 char *truncated =
name;
1171 * Common Names are 64 chars max, so for a common case where the CN is the
1172 * last field, we can still print the longest possible CN with a
1173 * 7-character prefix (".../CN=[64 chars]"), for a reasonable limit of 71
1181 * Keep the end of the name, not the beginning, since the most
1182 * specific field is likely to give users the most information.
1185 truncated[0] = truncated[1] = truncated[2] =
'.';
1195 * Certificate verification callback
1197 * This callback allows us to examine intermediate problems during
1198 * verification, for later logging.
1200 * This callback also allows us to override the default acceptance
1201 * criteria (e.g., accepting self-signed or expired certs), but
1202 * for now we accept the default checks.
1209 const char *errstring;
1215 /* Nothing to do for the successful case. */
1219 /* Pull all the information we have on the verification failure. */
1220 depth = X509_STORE_CTX_get_error_depth(ctx);
1221 errcode = X509_STORE_CTX_get_error(ctx);
1222 errstring = X509_verify_cert_error_string(
errcode);
1226 _(
"Client certificate verification failed at depth %d: %s."),
1229 cert = X509_STORE_CTX_get_current_cert(ctx);
1241 * Get the Subject and Issuer for logging, but don't let maliciously
1242 * huge certs flood the logs, and don't reflect non-ASCII bytes into
1254 * Pull the serial number, too, in case a Subject is still ambiguous.
1255 * This mirrors be_tls_get_peer_serial().
1257 sn = X509_get_serialNumber(cert);
1258 b = ASN1_INTEGER_to_BN(sn, NULL);
1259 serialno = BN_bn2dec(
b);
1263 _(
"Failed certificate data (unverified): subject \"%s\", serial number %s, issuer \"%s\"."),
1264 sub_prepared, serialno ? serialno :
_(
"unknown"),
1268 OPENSSL_free(serialno);
1269 pfree(iss_prepared);
1270 pfree(sub_prepared);
1273 /* Store our detail message to be logged later. */
1280 * This callback is used to copy SSL information messages
1281 * into the PostgreSQL log.
1288 desc = SSL_state_string_long(ssl);
1292 case SSL_CB_HANDSHAKE_START:
1296 case SSL_CB_HANDSHAKE_DONE:
1300 case SSL_CB_ACCEPT_LOOP:
1304 case SSL_CB_ACCEPT_EXIT:
1308 case SSL_CB_CONNECT_LOOP:
1312 case SSL_CB_CONNECT_EXIT:
1316 case SSL_CB_READ_ALERT:
1320 case SSL_CB_WRITE_ALERT:
1327/* See pqcomm.h comments on OpenSSL implementation of ALPN (RFC 7301) */
1331 * Server callback for ALPN negotiation. We use the standard "helper" function
1332 * even though currently we only accept one value.
1336 const unsigned char **out,
1337 unsigned char *outlen,
1338 const unsigned char *in,
1343 * Why does OpenSSL provide a helper function that requires a nonconst
1344 * vector when the callback is declared to take a const vector? What are
1345 * we to do with that?
1349 Assert(userdata != NULL);
1354 retval = SSL_select_next_proto((
unsigned char **) out, outlen,
1357 if (*out == NULL || *outlen >
sizeof(
alpn_protos) || *outlen <= 0)
1358 return SSL_TLSEXT_ERR_NOACK;
/* can't happen */
1360 if (retval == OPENSSL_NPN_NEGOTIATED)
1361 return SSL_TLSEXT_ERR_OK;
1365 * The client doesn't support our protocol. Reject the connection
1366 * with TLS "no_application_protocol" alert, per RFC 7301.
1368 return SSL_TLSEXT_ERR_ALERT_FATAL;
1374 * Set DH parameters for generating ephemeral DH keys. The
1375 * DH parameters can take a long time to compute, so they must be
1378 * Since few sites will bother to create a parameter file, we also
1379 * provide a fallback to the parameters provided by the OpenSSL
1382 * These values can be static (once loaded or computed) since the
1383 * OpenSSL library can efficiently generate random keys from the
1384 * information provided.
1391 SSL_CTX_set_options(context, SSL_OP_SINGLE_DH_USE);
1400 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
1401 errmsg(
"DH: could not load DH parameters")));
1405 if (SSL_CTX_set_tmp_dh(context, dh) != 1)
1408 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
1409 errmsg(
"DH: could not set DH parameters: %s",
1420 * Set ECDH parameters for generating ephemeral Elliptic Curve DH
1421 * keys. This is much simpler than the DH parameters, as we just
1422 * need to provide the name of the curve to OpenSSL.
1427#ifndef OPENSSL_NO_ECDH
1428 if (SSL_CTX_set1_groups_list(context,
SSLECDHCurve) != 1)
1431 * OpenSSL 3.3.0 introduced proper error messages for group parsing
1432 * errors, earlier versions returns "no SSL error reported" which is
1433 * far from helpful. For older versions, we replace with a better
1434 * error message. Injecting the error into the OpenSSL error queue
1435 * need APIs from OpenSSL 3.0.
1438 errcode(ERRCODE_CONFIG_FILE_ERROR),
1439 errmsg(
"could not set group names specified in ssl_groups: %s",
1441 _(
"No valid groups found"))),
1442 errhint(
"Ensure that each group name is spelled correctly and supported by the installed version of OpenSSL."));
1451 * Obtain reason string for passed SSL errcode with replacement
1453 * The error message supplied in replacement will be used in case the error
1454 * code from OpenSSL is 0, else the error message from SSLerrmessage() will
1457 * Not all versions of OpenSSL place an error on the queue even for failing
1458 * operations, which will yield "no SSL error reported" by SSLerrmessage. This
1459 * function can be used to ensure that a proper error message is displayed for
1460 * versions reporting no error, while using the OpenSSL error via SSLerrmessage
1461 * for versions where there is one.
1473 * Obtain reason string for passed SSL errcode
1475 * ERR_get_error() is used by caller to get errcode to pass here.
1477 * Some caution is needed here since ERR_reason_error_string will return NULL
1478 * if it doesn't recognize the error code, or (in OpenSSL >= 3) if the code
1479 * represents a system errno value. We don't want to return NULL ever.
1484 const char *errreason;
1485 static char errbuf[36];
1488 return _(
"no SSL error reported");
1489 errreason = ERR_reason_error_string(ecode);
1490 if (errreason != NULL)
1494 * In OpenSSL 3.0.0 and later, ERR_reason_error_string does not map system
1495 * errno values anymore. (See OpenSSL source code for the explanation.)
1496 * We can cover that shortcoming with this bit of code. Older OpenSSL
1497 * versions don't have the ERR_SYSTEM_ERROR macro, but that's okay because
1498 * they don't have the shortcoming either.
1500#ifdef ERR_SYSTEM_ERROR
1501 if (ERR_SYSTEM_ERROR(ecode))
1502 return strerror(ERR_GET_REASON(ecode));
1505 /* No choice but to report the numeric ecode */
1506 snprintf(errbuf,
sizeof(errbuf),
_(
"SSL error code %lu"), ecode);
1517 SSL_get_cipher_bits(
port->ssl, &bits);
1528 return SSL_get_version(
port->ssl);
1537 return SSL_get_cipher(
port->ssl);
1565 ASN1_INTEGER *serial;
1569 serial = X509_get_serialNumber(
port->peer);
1570 b = ASN1_INTEGER_to_BN(serial, NULL);
1586 const EVP_MD *algo_type = NULL;
1587 unsigned char hash[EVP_MAX_MD_SIZE];
/* size for SHA-512 */
1588 unsigned int hash_size;
1592 server_cert = SSL_get_certificate(
port->ssl);
1593 if (server_cert == NULL)
1597 * Get the signature algorithm of the certificate to determine the hash
1598 * algorithm to use for the result. Prefer X509_get_signature_info(),
1599 * introduced in OpenSSL 1.1.1, which can handle RSA-PSS signatures.
1601#if HAVE_X509_GET_SIGNATURE_INFO
1602 if (!X509_get_signature_info(server_cert, &algo_nid, NULL, NULL, NULL))
1604 if (!OBJ_find_sigid_algs(X509_get_signature_nid(server_cert),
1607 elog(
ERROR,
"could not determine server certificate signature algorithm");
1610 * The TLS server's certificate bytes need to be hashed with SHA-256 if
1611 * its signature algorithm is MD5 or SHA-1 as per RFC 5929
1612 * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
1613 * is used, the same hash as the signature algorithm is used.
1619 algo_type = EVP_sha256();
1622 algo_type = EVP_get_digestbynid(algo_nid);
1623 if (algo_type == NULL)
1624 elog(
ERROR,
"could not find digest for NID %s",
1625 OBJ_nid2sn(algo_nid));
1629 /* generate and save the certificate hash */
1630 if (!X509_digest(server_cert, algo_type,
hash, &hash_size))
1631 elog(
ERROR,
"could not generate server certificate hash");
1633 cert_hash =
palloc(hash_size);
1634 memcpy(cert_hash,
hash, hash_size);
1641 * Convert an X509 subject name to a cstring.
1647 BIO *membuf = BIO_new(BIO_s_mem());
1650 count = X509_NAME_entry_count(
name);
1653 const char *field_name;
1662 (
errcode(ERRCODE_OUT_OF_MEMORY),
1663 errmsg(
"could not create BIO")));
1665 (void) BIO_set_close(membuf, BIO_CLOSE);
1666 for (
i = 0;
i < count;
i++)
1668 e = X509_NAME_get_entry(
name,
i);
1669 nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(
e));
1670 if (nid == NID_undef)
1672 (
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1673 errmsg(
"could not get NID for ASN1_OBJECT object")));
1674 v = X509_NAME_ENTRY_get_data(
e);
1675 field_name = OBJ_nid2sn(nid);
1676 if (field_name == NULL)
1677 field_name = OBJ_nid2ln(nid);
1678 if (field_name == NULL)
1680 (
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1681 errmsg(
"could not convert NID %d to an ASN1_OBJECT structure", nid)));
1682 BIO_printf(membuf,
"/%s=", field_name);
1683 ASN1_STRING_print_ex(membuf, v,
1684 ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
1685 | ASN1_STRFLGS_UTF8_CONVERT));
1688 /* ensure null termination of the BIO's content */
1690 BIO_write(membuf, &nullterm, 1);
1691 size = BIO_get_mem_data(membuf, &sp);
1697 if (BIO_free(membuf) != 1)
1698 elog(
ERROR,
"could not free OpenSSL BIO structure");
1704 * Convert TLS protocol version GUC enum to OpenSSL values
1706 * This is a straightforward one-to-one mapping, but doing it this way makes
1707 * the definitions of ssl_min_protocol_version and ssl_max_protocol_version
1708 * independent of OpenSSL availability and version.
1710 * If a version is passed that is not supported by the current OpenSSL
1711 * version, then we return -1. If a nonnegative value is returned,
1712 * subsequent code can assume it's working with a supported version.
1714 * Note: this is rather similar to libpq's routine in fe-secure-openssl.c,
1715 * so make sure to update both routines if changing this one.
1725 return TLS1_VERSION;
1727#ifdef TLS1_1_VERSION
1728 return TLS1_1_VERSION;
1733#ifdef TLS1_2_VERSION
1734 return TLS1_2_VERSION;
1739#ifdef TLS1_3_VERSION
1740 return TLS1_3_VERSION;
1750 * Likewise provide a mapping to strings.
1769 return "(unrecognized)";
1788 * If reloading and no external command is configured, override
1789 * OpenSSL's default handling of passphrase-protected files,
1790 * because we don't want to prompt for a passphrase in an
1791 * already-running server.
bool check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
int run_ssl_passphrase_command(const char *prompt, bool is_server_start, char *buf, int size)
const char * be_tls_get_version(Port *port)
static const char * ssl_protocol_version_to_string(int v)
static const char * cert_errdetail
static void info_cb(const SSL *ssl, int type, int args)
static const char * SSLerrmessage(unsigned long ecode)
ssize_t be_tls_write(Port *port, const void *ptr, size_t len, int *waitfor)
void be_tls_destroy(void)
int be_tls_init(bool isServerStart)
static long port_bio_ctrl(BIO *h, int cmd, long num, void *ptr)
openssl_tls_init_hook_typ openssl_tls_init_hook
int be_tls_get_cipher_bits(Port *port)
int be_tls_open_server(Port *port)
char * be_tls_get_certificate_hash(Port *port, size_t *len)
static int alpn_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *userdata)
const char * be_tls_get_cipher(Port *port)
static const char * SSLerrmessageExt(unsigned long ecode, const char *replacement)
static DH * load_dh_buffer(const char *buffer, size_t len)
static int dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
static void default_openssl_tls_init(SSL_CTX *context, bool isServerStart)
static int ssl_set_port_bio(Port *port)
void be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
static int ssl_protocol_version_to_openssl(int v)
static bool initialize_dh(SSL_CTX *context, bool isServerStart)
void be_tls_close(Port *port)
void be_tls_get_peer_issuer_name(Port *port, char *ptr, size_t len)
ssize_t be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
static char * X509_NAME_to_cstring(X509_NAME *name)
static BIO_METHOD * port_bio_method(void)
static int ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata)
static char * prepare_cert_name(char *name)
static SSL_CTX * SSL_context
static bool ssl_is_server_start
static int verify_cb(int ok, X509_STORE_CTX *ctx)
static BIO_METHOD * port_bio_method_ptr
static bool initialize_ecdh(SSL_CTX *context, bool isServerStart)
static int port_bio_read(BIO *h, char *buf, int size)
static int port_bio_write(BIO *h, const char *buf, int size)
static bool dummy_ssl_passwd_cb_called
static DH * load_dh_file(char *filename, bool isServerStart)
static const unsigned char alpn_protos[]
void be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len)
char * ssl_dh_params_file
int ssl_min_protocol_version
ssize_t secure_raw_read(Port *port, void *ptr, size_t len)
bool SSLPreferServerCiphers
int ssl_max_protocol_version
char * ssl_passphrase_command
bool ssl_passphrase_command_supports_reload
ssize_t secure_raw_write(Port *port, const void *ptr, size_t len)
int errcode_for_socket_access(void)
int errmsg_internal(const char *fmt,...)
int errdetail_internal(const char *fmt,...)
int errcode_for_file_access(void)
int errdetail(const char *fmt,...)
int errhint(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
void err(int eval, const char *fmt,...)
FILE * AllocateFile(const char *name, const char *mode)
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Assert(PointerIsAligned(start, uint64))
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
char * pg_any_to_server(const char *s, int len, int encoding)
void * MemoryContextAlloc(MemoryContext context, Size size)
char * pstrdup(const char *in)
void pfree(void *pointer)
MemoryContext TopMemoryContext
size_t strlcpy(char *dst, const char *src, size_t siz)
#define PG_ALPN_PROTOCOL_VECTOR
static unsigned hash(unsigned *uv, int n)
char * pg_clean_ascii(const char *str, int alloc_flags)
void appendStringInfo(StringInfo str, const char *fmt,...)
void appendStringInfoChar(StringInfo str, char ch)
void initStringInfo(StringInfo str)
#define WL_SOCKET_READABLE
#define WL_EXIT_ON_PM_DEATH
#define WL_SOCKET_WRITEABLE