PostgreSQL Source Code git master
Loading...
Searching...
No Matches
be-secure-openssl.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * be-secure-openssl.c
4 * functions for OpenSSL support in the backend.
5 *
6 *
7 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
9 *
10 *
11 * IDENTIFICATION
12 * src/backend/libpq/be-secure-openssl.c
13 *
14 *-------------------------------------------------------------------------
15 */
16
17#include "postgres.h"
18
19#include <sys/stat.h>
20#include <signal.h>
21#include <fcntl.h>
22#include <ctype.h>
23#include <sys/socket.h>
24#include <unistd.h>
25#include <netdb.h>
26#include <netinet/in.h>
27#include <netinet/tcp.h>
28#include <arpa/inet.h>
29
30#include "common/hashfn.h"
31#include "common/string.h"
32#include "libpq/libpq.h"
33#include "miscadmin.h"
34#include "pgstat.h"
35#include "storage/fd.h"
36#include "storage/latch.h"
37#include "utils/guc.h"
38#include "utils/memutils.h"
39#include "utils/wait_event.h"
40
41/*
42 * These SSL-related #includes must come after all system-provided headers.
43 * This ensures that OpenSSL can take care of conflicts with Windows'
44 * <wincrypt.h> by #undef'ing the conflicting macros. (We don't directly
45 * include <wincrypt.h>, but some other Windows headers do.)
46 */
47#include "common/openssl.h"
48#include <openssl/bn.h>
49#include <openssl/conf.h>
50#include <openssl/dh.h>
51#ifndef OPENSSL_NO_ECDH
52#include <openssl/ec.h>
53#endif
54#include <openssl/x509v3.h>
55
56/*
57 * Simplehash for tracking configured hostnames to guard against duplicate
58 * entries. Each list of hosts is traversed and added to the hash during
59 * parsing and if a duplicate error is detected an error will be thrown.
60 */
61typedef struct
62{
64 const char *hostname;
66static uint32 host_cache_pointer(const char *key);
67#define SH_PREFIX host_cache
68#define SH_ELEMENT_TYPE HostCacheEntry
69#define SH_KEY_TYPE const char *
70#define SH_KEY hostname
71#define SH_HASH_KEY(tb, key) host_cache_pointer(key)
72#define SH_EQUAL(tb, a, b) (pg_strcasecmp(a, b) == 0)
73#define SH_SCOPE static inline
74#define SH_DECLARE
75#define SH_DEFINE
76#include "lib/simplehash.h"
77
78/* default init hook can be overridden by a shared library */
79static void default_openssl_tls_init(SSL_CTX *context, bool isServerStart);
81
82static int port_bio_read(BIO *h, char *buf, int size);
83static int port_bio_write(BIO *h, const char *buf, int size);
84static BIO_METHOD *port_bio_method(void);
85static int ssl_set_port_bio(Port *port);
86
87static DH *load_dh_file(char *filename, bool isServerStart);
88static DH *load_dh_buffer(const char *buffer, size_t len);
89static int ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata);
90static int dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
91static int verify_cb(int ok, X509_STORE_CTX *ctx);
92static void info_cb(const SSL *ssl, int type, int args);
93static int alpn_cb(SSL *ssl,
94 const unsigned char **out,
95 unsigned char *outlen,
96 const unsigned char *in,
97 unsigned int inlen,
98 void *userdata);
99static bool initialize_dh(SSL_CTX *context, bool isServerStart);
100static bool initialize_ecdh(SSL_CTX *context, bool isServerStart);
101static const char *SSLerrmessageExt(unsigned long ecode, const char *replacement);
102static const char *SSLerrmessage(unsigned long ecode);
103static bool init_host_context(HostsLine *host, bool isServerStart);
104static void host_context_cleanup_cb(void *arg);
105#ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
106static int sni_clienthello_cb(SSL *ssl, int *al, void *arg);
107#endif
108
109static char *X509_NAME_to_cstring(X509_NAME *name);
110
113static struct hosts
114{
115 /*
116 * List of HostsLine structures containing SSL configurations for
117 * connections with hostnames defined in the SNI extension.
118 */
120
121 /* The SSL configuration to use for connections without SNI */
123
124 /*
125 * The default SSL configuration to use as a fallback in case no hostname
126 * matches the supplied hostname in the SNI extension.
127 */
130
131static bool dummy_ssl_passwd_cb_called = false;
133
134static int ssl_protocol_version_to_openssl(int v);
135static const char *ssl_protocol_version_to_string(int v);
136
138{
139 /*
140 * Storage for passing certificate verification error logging from the
141 * callback.
142 */
144};
145
146/* ------------------------------------------------------------ */
147/* Public interface */
148/* ------------------------------------------------------------ */
149
150int
152{
153 List *pg_hosts = NIL;
154 ListCell *line;
158 char *err_msg = NULL;
159 int res;
160 struct hosts *new_hosts;
161 SSL_CTX *context = NULL;
162 int ssl_ver_min = -1;
163 int ssl_ver_max = -1;
165
166 /*
167 * Since we don't know which host we're using until the ClientHello is
168 * sent, ssl_loaded_verify_locations *always* starts out as false. The
169 * only place it's set to true is in sni_clienthello_cb().
170 */
172
174 "hosts file parser context",
177
178 /* Allocate a tentative replacement for SSL_hosts. */
180
181 /*
182 * Register a reset callback for the memory context which is responsible
183 * for freeing OpenSSL managed allocations upon context deletion. The
184 * callback is allocated here to make sure it gets cleaned up along with
185 * the memory context it's registered for.
186 */
191
192 /*
193 * If ssl_sni is enabled, attempt to load and parse TLS configuration from
194 * the pg_hosts.conf file with the set of hosts returned as a list. If
195 * there are hosts configured they take precedence over the configuration
196 * in postgresql.conf. Make sure to allocate the parsed rows in their own
197 * memory context so that we can delete them easily in case parsing fails.
198 * If ssl_sni is disabled then set the state accordingly to make sure we
199 * instead parse the config from postgresql.conf.
200 *
201 * The reason for not doing everything in this if-else conditional is that
202 * we want to use the same processing of postgresql.conf for when ssl_sni
203 * is off as well as when it's on but the hostsfile is missing etc. Thus
204 * we set res to the state and continue with a new conditional instead of
205 * duplicating logic and risk it diverging over time.
206 */
207 if (ssl_sni)
208 {
209 /*
210 * The GUC check hook should have already blocked this but to be on
211 * the safe side we doublecheck here.
212 */
213#ifndef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
216 errmsg("ssl_sni is not supported with LibreSSL"));
217 goto error;
218#endif
219
220 /* Attempt to load configuration from pg_hosts.conf */
221 res = load_hosts(&pg_hosts, &err_msg);
222
223 /*
224 * pg_hosts.conf is not required to contain configuration, but if it
225 * does we error out in case it fails to load rather than continue to
226 * try the postgresql.conf configuration to avoid silently falling
227 * back on an undesired configuration.
228 */
229 if (res == HOSTSFILE_LOAD_FAILED)
230 {
233 errmsg("could not load \"%s\": %s", "pg_hosts.conf",
234 err_msg ? err_msg : "unknown error"));
235 goto error;
236 }
237 }
238 else
239 res = HOSTSFILE_DISABLED;
240
241 /*
242 * Loading and parsing the hosts file was successful, create configs for
243 * each host entry and add to the list of hosts to be checked during
244 * login.
245 */
246 if (res == HOSTSFILE_LOAD_OK)
247 {
249
250 foreach(line, pg_hosts)
251 {
252 HostsLine *host = lfirst(line);
253
255 goto error;
256
257 /*
258 * The hostname in the config will be set to NULL for the default
259 * host as well as in configs used for non-SNI connections. Lists
260 * of hostnames in pg_hosts.conf are not allowed to contain the
261 * default '*' entry or a '/no_sni/' entry and this is checked
262 * during parsing. Thus we can inspect the head of the hostnames
263 * list for these since they will never be anywhere else.
264 */
265 if (strcmp(linitial(host->hostnames), "*") == 0)
266 {
267 if (new_hosts->default_host)
268 {
271 errmsg("multiple default hosts specified"),
272 errcontext("line %d of configuration file \"%s\"",
273 host->linenumber, host->sourcefile));
274 goto error;
275 }
276
277 new_hosts->default_host = host;
278 }
279 else if (strcmp(linitial(host->hostnames), "/no_sni/") == 0)
280 {
281 if (new_hosts->no_sni)
282 {
285 errmsg("multiple no_sni hosts specified"),
286 errcontext("line %d of configuration file \"%s\"",
287 host->linenumber, host->sourcefile));
288 goto error;
289 }
290
291 new_hosts->no_sni = host;
292 }
293 else
294 {
295 /* Check the hostnames for duplicates */
296 if (!host_cache)
298
299 foreach_ptr(char, hostname, host->hostnames)
300 {
301 HostCacheEntry *entry;
302 bool found;
303
304 entry = host_cache_insert(host_cache, hostname, &found);
305 if (found)
306 {
309 errmsg("multiple entries for host \"%s\" specified",
310 hostname),
311 errcontext("line %d of configuration file \"%s\"",
312 host->linenumber, host->sourcefile));
313 goto error;
314 }
315 else
316 entry->hostname = pstrdup(hostname);
317 }
318
319 /*
320 * At this point we know we have a configuration with a list
321 * of distinct 1..n hostnames for literal string matching with
322 * the SNI extension from the user.
323 */
324 new_hosts->sni = lappend(new_hosts->sni, host);
325 }
326 }
327 }
328
329 /*
330 * If SNI is disabled, then we load configuration from postgresql.conf. If
331 * SNI is enabled but the pg_hosts.conf file doesn't exist, or is empty,
332 * then we also load the config from postgresql.conf.
333 */
334 else if (res == HOSTSFILE_DISABLED || res == HOSTSFILE_EMPTY || res == HOSTSFILE_MISSING)
335 {
336 HostsLine *pgconf = palloc0(sizeof(HostsLine));
337
338#ifdef USE_ASSERT_CHECKING
339 if (res == HOSTSFILE_DISABLED)
340 Assert(ssl_sni == false);
341#endif
342
343 pgconf->ssl_cert = ssl_cert_file;
344 pgconf->ssl_key = ssl_key_file;
345 pgconf->ssl_ca = ssl_ca_file;
346 pgconf->ssl_passphrase_cmd = ssl_passphrase_command;
347 pgconf->ssl_passphrase_reload = ssl_passphrase_command_supports_reload;
348
350 goto error;
351
352 /*
353 * If postgresql.conf is used to configure SSL then by definition it
354 * will be the default context as we don't have per-host config.
355 */
356 new_hosts->default_host = pgconf;
357 }
358
359 /*
360 * Make sure we have at least one configuration loaded to use, without
361 * that we cannot drive a connection so exit.
362 */
363 if (new_hosts->sni == NIL && !new_hosts->default_host && !new_hosts->no_sni)
364 {
367 errmsg("no SSL configurations loaded"),
368 /*- translator: The two %s contain filenames */
369 errhint("If ssl_sni is enabled then add configuration to \"%s\", else \"%s\"",
370 "pg_hosts.conf", "postgresql.conf"));
371 goto error;
372 }
373
374#ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
375
376 /*
377 * Create a new SSL context into which we'll load all the configuration
378 * settings. If we fail partway through, we can avoid memory leakage by
379 * freeing this context; we don't install it as active until the end.
380 *
381 * We use SSLv23_method() because it can negotiate use of the highest
382 * mutually supported protocol version, while alternatives like
383 * TLSv1_2_method() permit only one specific version. Note that we don't
384 * actually allow SSL v2 or v3, only TLS protocols (see below).
385 */
386 context = SSL_CTX_new(SSLv23_method());
387 if (!context)
388 {
390 (errmsg("could not create SSL context: %s",
392 goto error;
393 }
394#else
395
396 /*
397 * If the client hello callback isn't supported we want to use the default
398 * context as the one to drive the handshake so avoid creating a new one
399 * and use the already existing default one instead.
400 */
401 context = new_hosts->default_host->ssl_ctx;
402
403 /*
404 * Since we don't allocate a new SSL_CTX here like we do when SNI has been
405 * enabled we need to bump the reference count on context to avoid double
406 * free of the context when using the same cleanup logic across the cases.
407 */
408 SSL_CTX_up_ref(context);
409#endif
410
411 /*
412 * Disable OpenSSL's moving-write-buffer sanity check, because it causes
413 * unnecessary failures in nonblocking send cases.
414 */
416
418 {
420
421 if (ssl_ver_min == -1)
422 {
424 /*- translator: first %s is a GUC option name, second %s is its value */
425 (errmsg("\"%s\" setting \"%s\" not supported by this build",
426 "ssl_min_protocol_version",
427 GetConfigOption("ssl_min_protocol_version",
428 false, false))));
429 goto error;
430 }
431
433 {
435 (errmsg("could not set minimum SSL protocol version")));
436 goto error;
437 }
438 }
439
441 {
443
444 if (ssl_ver_max == -1)
445 {
447 /*- translator: first %s is a GUC option name, second %s is its value */
448 (errmsg("\"%s\" setting \"%s\" not supported by this build",
449 "ssl_max_protocol_version",
450 GetConfigOption("ssl_max_protocol_version",
451 false, false))));
452 goto error;
453 }
454
456 {
458 (errmsg("could not set maximum SSL protocol version")));
459 goto error;
460 }
461 }
462
463 /* Check compatibility of min/max protocols */
466 {
467 /*
468 * No need to check for invalid values (-1) for each protocol number
469 * as the code above would have already generated an error.
470 */
472 {
475 errmsg("could not set SSL protocol version range"),
476 errdetail("\"%s\" cannot be higher than \"%s\"",
477 "ssl_min_protocol_version",
478 "ssl_max_protocol_version")));
479 goto error;
480 }
481 }
482
483 /*
484 * Disallow SSL session tickets. OpenSSL use both stateful and stateless
485 * tickets for TLSv1.3, and stateless ticket for TLSv1.2. SSL_OP_NO_TICKET
486 * is available since 0.9.8f but only turns off stateless tickets. In
487 * order to turn off stateful tickets we need SSL_CTX_set_num_tickets,
488 * which is available since OpenSSL 1.1.1. LibreSSL 3.5.4 (from OpenBSD
489 * 7.1) introduced this API for compatibility, but doesn't support session
490 * tickets at all so it's a no-op there.
491 */
492#ifdef HAVE_SSL_CTX_SET_NUM_TICKETS
493 SSL_CTX_set_num_tickets(context, 0);
494#endif
496
497 /* disallow SSL session caching, too */
499
500 /* disallow SSL compression */
502
503 /*
504 * Disallow SSL renegotiation. This concerns only TLSv1.2 and older
505 * protocol versions, as TLSv1.3 has no support for renegotiation.
506 * SSL_OP_NO_RENEGOTIATION is available in OpenSSL since 1.1.0h (via a
507 * backport from 1.1.1). SSL_OP_NO_CLIENT_RENEGOTIATION is available in
508 * LibreSSL since 2.5.1 disallowing all client-initiated renegotiation
509 * (this is usually on by default).
510 */
511#ifdef SSL_OP_NO_RENEGOTIATION
513#endif
514#ifdef SSL_OP_NO_CLIENT_RENEGOTIATION
516#endif
517
518 /* set up ephemeral DH and ECDH keys */
519 if (!initialize_dh(context, isServerStart))
520 goto error;
521 if (!initialize_ecdh(context, isServerStart))
522 goto error;
523
524 /* set up the allowed cipher list for TLSv1.2 and below */
525 if (SSL_CTX_set_cipher_list(context, SSLCipherList) != 1)
526 {
529 errmsg("could not set the TLSv1.2 cipher list (no valid ciphers available)")));
530 goto error;
531 }
532
533 /*
534 * Set up the allowed cipher suites for TLSv1.3. If the GUC is an empty
535 * string we leave the allowed suites to be the OpenSSL default value.
536 */
537 if (SSLCipherSuites[0])
538 {
539 /* set up the allowed cipher suites */
540 if (SSL_CTX_set_ciphersuites(context, SSLCipherSuites) != 1)
541 {
544 errmsg("could not set the TLSv1.3 cipher suites (no valid ciphers available)")));
545 goto error;
546 }
547 }
548
549 /* Let server choose order */
552
553 /*
554 * Success! Replace any existing SSL_context and host configurations.
555 */
556 if (SSL_context)
557 {
560 }
561
563
566
569 SSL_context = context;
570
571 return 0;
572
573 /*
574 * Clean up by releasing working SSL contexts as well as allocations
575 * performed during parsing. Since all our allocations are done in a
576 * local memory context all we need to do is delete it.
577 */
578error:
579 if (context)
580 SSL_CTX_free(context);
581
584 return -1;
585}
586
587/*
588 * host_context_cleanup_cb
589 *
590 * Memory context reset callback for clearing OpenSSL managed resources when
591 * hosts are reloaded and the previous set of configured hosts are freed. As
592 * all hosts are allocated in a single context we don't need to free each host
593 * individually, just resources managed by OpenSSL.
594 */
595static void
597{
598 struct hosts *hosts = arg;
599
601 {
602 if (host->ssl_ctx != NULL)
603 SSL_CTX_free(host->ssl_ctx);
604 }
605
606 if (hosts->no_sni && hosts->no_sni->ssl_ctx)
608
611}
612
613static bool
615{
617 static bool init_warned = false;
618
619 if (!ctx)
620 {
622 (errmsg("could not create SSL context: %s",
624 goto error;
625 }
626
627 /*
628 * Call init hook (usually to set password callback) in case SNI hasn't
629 * been enabled. If SNI is enabled the hook won't operate on the actual
630 * TLS context used so it cannot function properly; we warn if one has
631 * been installed.
632 *
633 * If SNI is enabled, we set password callback based what was configured.
634 */
635 if (!ssl_sni)
636 (*openssl_tls_init_hook) (ctx, isServerStart);
637 else
638 {
640 {
643 errmsg("SNI is enabled; installed TLS init hook will be ignored"),
644 /*- translator: first %s is a GUC, second %s contains a filename */
645 errhint("TLS init hooks are incompatible with SNI. "
646 "Set \"%s\" to \"off\" to make use of the hook "
647 "that is currently installed, or remove the hook "
648 "and use per-host passphrase commands in \"%s\".",
649 "ssl_sni", "pg_hosts.conf"));
650 init_warned = true;
651 }
652
653 /*
654 * Set up the password callback, if configured.
655 */
656 if (isServerStart)
657 {
658 if (host->ssl_passphrase_cmd && host->ssl_passphrase_cmd[0])
659 {
662 }
663 }
664 else
665 {
666 /*
667 * If ssl_passphrase_reload is true then ssl_passphrase_cmd cannot
668 * be NULL due to their parsing order, but just in case and to
669 * self-document the code we replicate the nullness checks.
670 */
671 if (host->ssl_passphrase_reload &&
672 (host->ssl_passphrase_cmd && host->ssl_passphrase_cmd[0]))
673 {
676 }
677 else
678 {
679 /*
680 * If reloading and no external command is configured,
681 * override OpenSSL's default handling of passphrase-protected
682 * files, because we don't want to prompt for a passphrase in
683 * an already-running server.
684 */
686 }
687 }
688 }
689
690 /*
691 * Load and verify server's certificate and private key
692 */
693 if (SSL_CTX_use_certificate_chain_file(ctx, host->ssl_cert) != 1)
694 {
697 errmsg("could not load server certificate file \"%s\": %s",
699 goto error;
700 }
701
703 goto error;
704
705
706 /* used by the callback */
708
709 /*
710 * OK, try to load the private key file.
711 */
713
715 host->ssl_key,
716 SSL_FILETYPE_PEM) != 1)
717 {
721 errmsg("private key file \"%s\" cannot be reloaded because it requires a passphrase",
722 host->ssl_key)));
723 else
726 errmsg("could not load private key file \"%s\": %s",
728 goto error;
729 }
730
731 if (SSL_CTX_check_private_key(ctx) != 1)
732 {
735 errmsg("check of private key failed: %s",
737 goto error;
738 }
739
740 /*
741 * Load CA store, so we can verify client certificates if needed.
742 */
743 if (host->ssl_ca && host->ssl_ca[0])
744 {
746
747 if (SSL_CTX_load_verify_locations(ctx, host->ssl_ca, NULL) != 1 ||
749 {
752 errmsg("could not load root certificate file \"%s\": %s",
754 goto error;
755 }
756
757 /*
758 * Tell OpenSSL to send the list of root certs we trust to clients in
759 * CertificateRequests. This lets a client with a keystore select the
760 * appropriate client certificate to send to us. Also, this ensures
761 * that the SSL context will "own" the root_cert_list and remember to
762 * free it when no longer needed.
763 */
765 }
766
767 /*----------
768 * Load the Certificate Revocation List (CRL).
769 * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
770 *----------
771 */
772 if (ssl_crl_file[0] || ssl_crl_dir[0])
773 {
775
776 if (cvstore)
777 {
778 /* Set the flags to check against the complete CRL chain */
782 == 1)
783 {
786 }
787 else if (ssl_crl_dir[0] == 0)
788 {
791 errmsg("could not load SSL certificate revocation list file \"%s\": %s",
793 goto error;
794 }
795 else if (ssl_crl_file[0] == 0)
796 {
799 errmsg("could not load SSL certificate revocation list directory \"%s\": %s",
801 goto error;
802 }
803 else
804 {
807 errmsg("could not load SSL certificate revocation list file \"%s\" or directory \"%s\": %s",
810 goto error;
811 }
812 }
813 }
814
815 host->ssl_ctx = ctx;
816 return true;
817
818error:
819 if (ctx)
820 SSL_CTX_free(ctx);
821 return false;
822}
823
824void
832
833int
835{
836 int r;
837 int err;
838 int waitfor;
839 unsigned long ecode;
840 bool give_proto_hint;
841 static struct CallbackErr err_context;
842
843 Assert(!port->ssl);
844 Assert(!port->peer);
845
846 if (!SSL_context)
847 {
850 errmsg("could not initialize SSL connection: SSL context not set up")));
851 return -1;
852 }
853
854 /* set up debugging/info callback */
856
857 /* enable ALPN */
859
860 if (!(port->ssl = SSL_new(SSL_context)))
861 {
864 errmsg("could not initialize SSL connection: %s",
866 return -1;
867 }
869 {
872 errmsg("could not set SSL socket: %s",
874 return -1;
875 }
876
877 /*
878 * If the underlying TLS library supports the client hello callback we use
879 * that in order to support host based configuration using the SNI TLS
880 * extension. If the user has disabled SNI via the ssl_sni GUC we still
881 * make use of the callback in order to have consistent handling of
882 * OpenSSL contexts, except in that case the callback will install the
883 * default configuration regardless of the hostname sent by the user in
884 * the handshake.
885 *
886 * In case the TLS library does not support the client hello callback, as
887 * of this writing LibreSSL does not, we need to install the client cert
888 * verification callback here (if the user configured a CA) since we
889 * cannot use the OpenSSL context update functionality.
890 */
891#ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
893#else
895 {
896 /*
897 * Always ask for SSL client cert, but don't fail if it's not
898 * presented. We might fail such connections later, depending on what
899 * we find in pg_hba.conf.
900 */
901 SSL_set_verify(port->ssl,
903 verify_cb);
904
906 }
907#endif
908
909 err_context.cert_errdetail = NULL;
911
912 port->ssl_in_use = true;
913
914aloop:
915
916 /*
917 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
918 * queue. In general, the current thread's error queue must be empty
919 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
920 * not work reliably. An extension may have failed to clear the
921 * per-thread error queue following another call to an OpenSSL I/O
922 * routine.
923 */
924 errno = 0;
926 r = SSL_accept(port->ssl);
927 if (r <= 0)
928 {
929 err = SSL_get_error(port->ssl, r);
930
931 /*
932 * Other clients of OpenSSL in the backend may fail to call
933 * ERR_get_error(), but we always do, so as to not cause problems for
934 * OpenSSL clients that don't call ERR_clear_error() defensively. Be
935 * sure that this happens by calling now. SSL_get_error() relies on
936 * the OpenSSL per-thread error queue being intact, so this is the
937 * earliest possible point ERR_get_error() may be called.
938 */
940 switch (err)
941 {
944 /* not allowed during connection establishment */
945 Assert(!port->noblock);
946
947 /*
948 * No need to care about timeouts/interrupts here. At this
949 * point authentication_timeout still employs
950 * StartupPacketTimeoutHandler() which directly exits.
951 */
954 else
956
959 goto aloop;
961 if (r < 0 && errno != 0)
964 errmsg("could not accept SSL connection: %m")));
965 else
968 errmsg("could not accept SSL connection: EOF detected")));
969 break;
970 case SSL_ERROR_SSL:
971 switch (ERR_GET_REASON(ecode))
972 {
973 /*
974 * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
975 * TLSV1_ALERT_PROTOCOL_VERSION have been observed
976 * when trying to communicate with an old OpenSSL
977 * library, or when the client and server specify
978 * disjoint protocol ranges. NO_PROTOCOLS_AVAILABLE
979 * occurs if there's a local misconfiguration (which
980 * can happen despite our checks, if openssl.cnf
981 * injects a limit we didn't account for). It's not
982 * very clear what would make OpenSSL return the other
983 * codes listed here, but a hint about protocol
984 * versions seems like it's appropriate for all.
985 */
995#ifdef SSL_R_VERSION_TOO_HIGH
997#endif
998#ifdef SSL_R_VERSION_TOO_LOW
1000#endif
1001 give_proto_hint = true;
1002 break;
1003 default:
1004 give_proto_hint = false;
1005 break;
1006 }
1009 errmsg("could not accept SSL connection: %s",
1011 err_context.cert_errdetail ? errdetail_internal("%s", err_context.cert_errdetail) : 0,
1013 errhint("This may indicate that the client does not support any SSL protocol version between %s and %s.",
1020 if (err_context.cert_errdetail)
1021 pfree(err_context.cert_errdetail);
1022 break;
1026 errmsg("could not accept SSL connection: EOF detected")));
1027 break;
1028 default:
1031 errmsg("unrecognized SSL error code: %d",
1032 err)));
1033 break;
1034 }
1035 return -1;
1036 }
1037
1038 /* Get the protocol selected by ALPN */
1039 port->alpn_used = false;
1040 {
1041 const unsigned char *selected;
1042 unsigned int len;
1043
1044 SSL_get0_alpn_selected(port->ssl, &selected, &len);
1045
1046 /* If ALPN is used, check that we negotiated the expected protocol */
1047 if (selected != NULL)
1048 {
1049 if (len == strlen(PG_ALPN_PROTOCOL) &&
1051 {
1052 port->alpn_used = true;
1053 }
1054 else
1055 {
1056 /* shouldn't happen */
1059 errmsg("received SSL connection request with unexpected ALPN protocol")));
1060 }
1061 }
1062 }
1063
1064 /* Get client certificate, if available. */
1065 port->peer = SSL_get_peer_certificate(port->ssl);
1066
1067 /* and extract the Common Name and Distinguished Name from it. */
1068 port->peer_cn = NULL;
1069 port->peer_dn = NULL;
1070 port->peer_cert_valid = false;
1071 if (port->peer != NULL)
1072 {
1073 int len;
1075 char *peer_dn;
1076 BIO *bio = NULL;
1077 BUF_MEM *bio_buf = NULL;
1078
1080 if (len != -1)
1081 {
1082 char *peer_cn;
1083
1084 peer_cn = MemoryContextAlloc(TopMemoryContext, len + 1);
1086 len + 1);
1087 peer_cn[len] = '\0';
1088 if (r != len)
1089 {
1090 /* shouldn't happen */
1091 pfree(peer_cn);
1092 return -1;
1093 }
1094
1095 /*
1096 * Reject embedded NULLs in certificate common name to prevent
1097 * attacks like CVE-2009-4034.
1098 */
1099 if (len != strlen(peer_cn))
1100 {
1103 errmsg("SSL certificate's common name contains embedded null")));
1104 pfree(peer_cn);
1105 return -1;
1106 }
1107
1108 port->peer_cn = peer_cn;
1109 }
1110
1111 bio = BIO_new(BIO_s_mem());
1112 if (!bio)
1113 {
1114 if (port->peer_cn != NULL)
1115 {
1116 pfree(port->peer_cn);
1117 port->peer_cn = NULL;
1118 }
1119 return -1;
1120 }
1121
1122 /*
1123 * RFC2253 is the closest thing to an accepted standard format for
1124 * DNs. We have documented how to produce this format from a
1125 * certificate. It uses commas instead of slashes for delimiters,
1126 * which make regular expression matching a bit easier. Also note that
1127 * it prints the Subject fields in reverse order.
1128 */
1130 BIO_get_mem_ptr(bio, &bio_buf) <= 0)
1131 {
1132 BIO_free(bio);
1133 if (port->peer_cn != NULL)
1134 {
1135 pfree(port->peer_cn);
1136 port->peer_cn = NULL;
1137 }
1138 return -1;
1139 }
1140 peer_dn = MemoryContextAlloc(TopMemoryContext, bio_buf->length + 1);
1141 memcpy(peer_dn, bio_buf->data, bio_buf->length);
1142 len = bio_buf->length;
1143 BIO_free(bio);
1144 peer_dn[len] = '\0';
1145 if (len != strlen(peer_dn))
1146 {
1149 errmsg("SSL certificate's distinguished name contains embedded null")));
1150 pfree(peer_dn);
1151 if (port->peer_cn != NULL)
1152 {
1153 pfree(port->peer_cn);
1154 port->peer_cn = NULL;
1155 }
1156 return -1;
1157 }
1158
1159 port->peer_dn = peer_dn;
1160
1161 port->peer_cert_valid = true;
1162 }
1163
1164 return 0;
1165}
1166
1167void
1169{
1170 if (port->ssl)
1171 {
1172 SSL_shutdown(port->ssl);
1173 SSL_free(port->ssl);
1174 port->ssl = NULL;
1175 port->ssl_in_use = false;
1176 }
1177
1178 if (port->peer)
1179 {
1180 X509_free(port->peer);
1181 port->peer = NULL;
1182 }
1183
1184 if (port->peer_cn)
1185 {
1186 pfree(port->peer_cn);
1187 port->peer_cn = NULL;
1188 }
1189
1190 if (port->peer_dn)
1191 {
1192 pfree(port->peer_dn);
1193 port->peer_dn = NULL;
1194 }
1195}
1196
1197ssize_t
1198be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
1199{
1200 ssize_t n;
1201 int err;
1202 unsigned long ecode;
1203
1204 errno = 0;
1206 n = SSL_read(port->ssl, ptr, len);
1207 err = SSL_get_error(port->ssl, n);
1208 ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
1209 switch (err)
1210 {
1211 case SSL_ERROR_NONE:
1212 /* a-ok */
1213 break;
1217 n = -1;
1218 break;
1222 n = -1;
1223 break;
1224 case SSL_ERROR_SYSCALL:
1225 /* leave it to caller to ereport the value of errno */
1226 if (n != -1 || errno == 0)
1227 {
1228 errno = ECONNRESET;
1229 n = -1;
1230 }
1231 break;
1232 case SSL_ERROR_SSL:
1235 errmsg("SSL error: %s", SSLerrmessage(ecode))));
1236 errno = ECONNRESET;
1237 n = -1;
1238 break;
1240 /* connection was cleanly shut down by peer */
1241 n = 0;
1242 break;
1243 default:
1246 errmsg("unrecognized SSL error code: %d",
1247 err)));
1248 errno = ECONNRESET;
1249 n = -1;
1250 break;
1251 }
1252
1253 return n;
1254}
1255
1256ssize_t
1257be_tls_write(Port *port, const void *ptr, size_t len, int *waitfor)
1258{
1259 ssize_t n;
1260 int err;
1261 unsigned long ecode;
1262
1263 errno = 0;
1265 n = SSL_write(port->ssl, ptr, len);
1266 err = SSL_get_error(port->ssl, n);
1267 ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
1268 switch (err)
1269 {
1270 case SSL_ERROR_NONE:
1271 /* a-ok */
1272 break;
1276 n = -1;
1277 break;
1281 n = -1;
1282 break;
1283 case SSL_ERROR_SYSCALL:
1284
1285 /*
1286 * Leave it to caller to ereport the value of errno. However, if
1287 * errno is still zero then assume it's a read EOF situation, and
1288 * report ECONNRESET. (This seems possible because SSL_write can
1289 * also do reads.)
1290 */
1291 if (n != -1 || errno == 0)
1292 {
1293 errno = ECONNRESET;
1294 n = -1;
1295 }
1296 break;
1297 case SSL_ERROR_SSL:
1300 errmsg("SSL error: %s", SSLerrmessage(ecode))));
1301 errno = ECONNRESET;
1302 n = -1;
1303 break;
1305
1306 /*
1307 * the SSL connection was closed, leave it to the caller to
1308 * ereport it
1309 */
1310 errno = ECONNRESET;
1311 n = -1;
1312 break;
1313 default:
1316 errmsg("unrecognized SSL error code: %d",
1317 err)));
1318 errno = ECONNRESET;
1319 n = -1;
1320 break;
1321 }
1322
1323 return n;
1324}
1325
1326/* ------------------------------------------------------------ */
1327/* Internal functions */
1328/* ------------------------------------------------------------ */
1329
1330/*
1331 * Private substitute BIO: this does the sending and receiving using send() and
1332 * recv() instead. This is so that we can enable and disable interrupts
1333 * just while calling recv(). We cannot have interrupts occurring while
1334 * the bulk of OpenSSL runs, because it uses malloc() and possibly other
1335 * non-reentrant libc facilities. We also need to call send() and recv()
1336 * directly so it gets passed through the socket/signals layer on Win32.
1337 *
1338 * These functions are closely modelled on the standard socket BIO in OpenSSL;
1339 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1340 */
1341
1343
1344static int
1345port_bio_read(BIO *h, char *buf, int size)
1346{
1347 int res = 0;
1348 Port *port = (Port *) BIO_get_data(h);
1349
1350 if (buf != NULL)
1351 {
1352 res = secure_raw_read(port, buf, size);
1354 port->last_read_was_eof = res == 0;
1355 if (res <= 0)
1356 {
1357 /* If we were interrupted, tell caller to retry */
1358 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
1359 {
1361 }
1362 }
1363 }
1364
1365 return res;
1366}
1367
1368static int
1369port_bio_write(BIO *h, const char *buf, int size)
1370{
1371 int res = 0;
1372
1373 res = secure_raw_write(((Port *) BIO_get_data(h)), buf, size);
1375 if (res <= 0)
1376 {
1377 /* If we were interrupted, tell caller to retry */
1378 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
1379 {
1381 }
1382 }
1383
1384 return res;
1385}
1386
1387static long
1388port_bio_ctrl(BIO *h, int cmd, long num, void *ptr)
1389{
1390 long res;
1391 Port *port = (Port *) BIO_get_data(h);
1392
1393 switch (cmd)
1394 {
1395 case BIO_CTRL_EOF:
1396
1397 /*
1398 * This should not be needed. port_bio_read already has a way to
1399 * signal EOF to OpenSSL. However, OpenSSL made an undocumented,
1400 * backwards-incompatible change and now expects EOF via BIO_ctrl.
1401 * See https://github.com/openssl/openssl/issues/8208
1402 */
1403 res = port->last_read_was_eof;
1404 break;
1405 case BIO_CTRL_FLUSH:
1406 /* libssl expects all BIOs to support BIO_flush. */
1407 res = 1;
1408 break;
1409 default:
1410 res = 0;
1411 break;
1412 }
1413
1414 return res;
1415}
1416
1417static BIO_METHOD *
1419{
1421 {
1422 int my_bio_index;
1423
1425 if (my_bio_index == -1)
1426 return NULL;
1428 port_bio_method_ptr = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
1430 return NULL;
1434 {
1437 return NULL;
1438 }
1439 }
1440 return port_bio_method_ptr;
1441}
1442
1443static int
1445{
1446 BIO *bio;
1448
1450 if (bio_method == NULL)
1451 return 0;
1452
1454 if (bio == NULL)
1455 return 0;
1456
1458 BIO_set_init(bio, 1);
1459
1460 SSL_set_bio(port->ssl, bio, bio);
1461 return 1;
1462}
1463
1464/*
1465 * Load precomputed DH parameters.
1466 *
1467 * To prevent "downgrade" attacks, we perform a number of checks
1468 * to verify that the DBA-generated DH parameters file contains
1469 * what we expect it to contain.
1470 */
1471static DH *
1473{
1474 FILE *fp;
1475 DH *dh = NULL;
1476 int codes;
1477
1478 /* attempt to open file. It's not an error if it doesn't exist. */
1479 if ((fp = AllocateFile(filename, "r")) == NULL)
1480 {
1483 errmsg("could not open DH parameters file \"%s\": %m",
1484 filename)));
1485 return NULL;
1486 }
1487
1489 FreeFile(fp);
1490
1491 if (dh == NULL)
1492 {
1495 errmsg("could not load DH parameters file: %s",
1497 return NULL;
1498 }
1499
1500 /* make sure the DH parameters are usable */
1501 if (DH_check(dh, &codes) == 0)
1502 {
1505 errmsg("invalid DH parameters: %s",
1507 DH_free(dh);
1508 return NULL;
1509 }
1511 {
1514 errmsg("invalid DH parameters: p is not prime")));
1515 DH_free(dh);
1516 return NULL;
1517 }
1520 {
1523 errmsg("invalid DH parameters: neither suitable generator or safe prime")));
1524 DH_free(dh);
1525 return NULL;
1526 }
1527
1528 return dh;
1529}
1530
1531/*
1532 * Load hardcoded DH parameters.
1533 *
1534 * If DH parameters cannot be loaded from a specified file, we can load
1535 * the hardcoded DH parameters supplied with the backend to prevent
1536 * problems.
1537 */
1538static DH *
1539load_dh_buffer(const char *buffer, size_t len)
1540{
1541 BIO *bio;
1542 DH *dh = NULL;
1543
1544 bio = BIO_new_mem_buf(buffer, len);
1545 if (bio == NULL)
1546 return NULL;
1548 if (dh == NULL)
1550 (errmsg_internal("DH load buffer: %s",
1552 BIO_free(bio);
1553
1554 return dh;
1555}
1556
1557/*
1558 * Passphrase collection callback using ssl_passphrase_command
1559 */
1560static int
1561ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1562{
1563 /* same prompt as OpenSSL uses internally */
1564 const char *prompt = "Enter PEM pass phrase:";
1565 const char *cmd = userdata;
1566
1567 Assert(rwflag == 0);
1568
1570}
1571
1572/*
1573 * Dummy passphrase callback
1574 *
1575 * If OpenSSL is told to use a passphrase-protected server key, by default
1576 * it will issue a prompt on /dev/tty and try to read a key from there.
1577 * That's no good during a postmaster SIGHUP cycle, not to mention SSL context
1578 * reload in an EXEC_BACKEND postmaster child. So override it with this dummy
1579 * function that just returns an empty passphrase, guaranteeing failure.
1580 */
1581static int
1582dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1583{
1584 /* Set flag to change the error message we'll report */
1586 /* And return empty string */
1587 Assert(size > 0);
1588 buf[0] = '\0';
1589 return 0;
1590}
1591
1592/*
1593 * Examines the provided certificate name, and if it's too long to log or
1594 * contains unprintable ASCII, escapes and truncates it. The return value is
1595 * always a new palloc'd string. (The input string is still modified in place,
1596 * for ease of implementation.)
1597 */
1598static char *
1600{
1601 size_t namelen = strlen(name);
1602 char *truncated = name;
1603
1604 /*
1605 * Common Names are 64 chars max, so for a common case where the CN is the
1606 * last field, we can still print the longest possible CN with a
1607 * 7-character prefix (".../CN=[64 chars]"), for a reasonable limit of 71
1608 * characters.
1609 */
1610#define MAXLEN 71
1611
1612 if (namelen > MAXLEN)
1613 {
1614 /*
1615 * Keep the end of the name, not the beginning, since the most
1616 * specific field is likely to give users the most information.
1617 */
1618 truncated = name + namelen - MAXLEN;
1619 truncated[0] = truncated[1] = truncated[2] = '.';
1620 namelen = MAXLEN;
1621 }
1622
1623#undef MAXLEN
1624
1625 return pg_clean_ascii(truncated, 0);
1626}
1627
1628/*
1629 * Certificate verification callback
1630 *
1631 * This callback allows us to examine intermediate problems during
1632 * verification, for later logging.
1633 *
1634 * This callback also allows us to override the default acceptance
1635 * criteria (e.g., accepting self-signed or expired certs), but
1636 * for now we accept the default checks.
1637 */
1638static int
1640{
1641 int depth;
1642 int errcode;
1643 const char *errstring;
1645 X509 *cert;
1646 SSL *ssl;
1647 struct CallbackErr *cb_err;
1648
1649 if (ok)
1650 {
1651 /* Nothing to do for the successful case. */
1652 return ok;
1653 }
1654
1655 /* Pull all the information we have on the verification failure. */
1656 depth = X509_STORE_CTX_get_error_depth(ctx);
1659
1660 /*
1661 * Extract the current SSL and CallbackErr object to use for passing error
1662 * detail back from the callback.
1663 */
1665 cb_err = (struct CallbackErr *) SSL_get_ex_data(ssl, 0);
1666
1669 _("Client certificate verification failed at depth %d: %s."),
1670 depth, errstring);
1671
1673 if (cert)
1674 {
1675 char *subject,
1676 *issuer;
1677 char *sub_prepared,
1678 *iss_prepared;
1679 char *serialno;
1680 ASN1_INTEGER *sn;
1681 BIGNUM *b;
1682
1683 /*
1684 * Get the Subject and Issuer for logging, but don't let maliciously
1685 * huge certs flood the logs, and don't reflect non-ASCII bytes into
1686 * it either.
1687 */
1690 pfree(subject);
1691
1694 pfree(issuer);
1695
1696 /*
1697 * Pull the serial number, too, in case a Subject is still ambiguous.
1698 * This mirrors be_tls_get_peer_serial().
1699 */
1701 b = ASN1_INTEGER_to_BN(sn, NULL);
1702 serialno = BN_bn2dec(b);
1703
1704 appendStringInfoChar(&str, '\n');
1706 _("Failed certificate data (unverified): subject \"%s\", serial number %s, issuer \"%s\"."),
1707 sub_prepared, serialno ? serialno : _("unknown"),
1708 iss_prepared);
1709
1710 BN_free(b);
1714 }
1715
1716 /* Store our detail message to be logged later. */
1717 cb_err->cert_errdetail = str.data;
1718
1719 return ok;
1720}
1721
1722/*
1723 * This callback is used to copy SSL information messages
1724 * into the PostgreSQL log.
1725 */
1726static void
1727info_cb(const SSL *ssl, int type, int args)
1728{
1729 const char *desc;
1730
1731 desc = SSL_state_string_long(ssl);
1732
1733 switch (type)
1734 {
1737 (errmsg_internal("SSL: handshake start: \"%s\"", desc)));
1738 break;
1741 (errmsg_internal("SSL: handshake done: \"%s\"", desc)));
1742 break;
1743 case SSL_CB_ACCEPT_LOOP:
1745 (errmsg_internal("SSL: accept loop: \"%s\"", desc)));
1746 break;
1747 case SSL_CB_ACCEPT_EXIT:
1749 (errmsg_internal("SSL: accept exit (%d): \"%s\"", args, desc)));
1750 break;
1753 (errmsg_internal("SSL: connect loop: \"%s\"", desc)));
1754 break;
1757 (errmsg_internal("SSL: connect exit (%d): \"%s\"", args, desc)));
1758 break;
1759 case SSL_CB_READ_ALERT:
1761 (errmsg_internal("SSL: read alert (0x%04x): \"%s\"", args, desc)));
1762 break;
1763 case SSL_CB_WRITE_ALERT:
1765 (errmsg_internal("SSL: write alert (0x%04x): \"%s\"", args, desc)));
1766 break;
1767 }
1768}
1769
1770/* See pqcomm.h comments on OpenSSL implementation of ALPN (RFC 7301) */
1771static const unsigned char alpn_protos[] = PG_ALPN_PROTOCOL_VECTOR;
1772
1773/*
1774 * Server callback for ALPN negotiation. We use the standard "helper" function
1775 * even though currently we only accept one value.
1776 */
1777static int
1779 const unsigned char **out,
1780 unsigned char *outlen,
1781 const unsigned char *in,
1782 unsigned int inlen,
1783 void *userdata)
1784{
1785 /*
1786 * Why does OpenSSL provide a helper function that requires a nonconst
1787 * vector when the callback is declared to take a const vector? What are
1788 * we to do with that?
1789 */
1790 int retval;
1791
1792 Assert(userdata != NULL);
1793 Assert(out != NULL);
1794 Assert(outlen != NULL);
1795 Assert(in != NULL);
1796
1797 retval = SSL_select_next_proto((unsigned char **) out, outlen,
1798 alpn_protos, sizeof(alpn_protos),
1799 in, inlen);
1800 if (*out == NULL || *outlen > sizeof(alpn_protos) || *outlen <= 0)
1801 return SSL_TLSEXT_ERR_NOACK; /* can't happen */
1802
1803 if (retval == OPENSSL_NPN_NEGOTIATED)
1804 return SSL_TLSEXT_ERR_OK;
1805 else
1806 {
1807 /*
1808 * The client doesn't support our protocol. Reject the connection
1809 * with TLS "no_application_protocol" alert, per RFC 7301.
1810 */
1812 }
1813}
1814
1815#ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
1816/*
1817 * ssl_update_ssl
1818 *
1819 * Replace certificate/key and CA in an SSL object to match the, via the SNI
1820 * extension, selected host configuration for the connection. The SSL_CTX
1821 * object to use should be passed in as ctx. This function will update the
1822 * SSL object in-place.
1823 */
1824static bool
1826{
1827 SSL_CTX *ctx = host_config->ssl_ctx;
1828
1829 X509 *cert;
1830 EVP_PKEY *key;
1831
1832 STACK_OF(X509) * chain;
1833
1834 Assert(ctx != NULL);
1835 /*-
1836 * Make use of the already-loaded certificate chain and key. At first
1837 * glance, SSL_set_SSL_CTX() looks like the easiest way to do this, but
1838 * beware -- it has very odd behavior:
1839 *
1840 * https://github.com/openssl/openssl/issues/6109
1841 */
1844
1845 Assert(cert && key);
1846
1847 if (!SSL_CTX_get0_chain_certs(ctx, &chain)
1848 || !SSL_use_cert_and_key(ssl, cert, key, chain, 1 /* override */ )
1849 || !SSL_check_private_key(ssl))
1850 {
1851 /*
1852 * This shouldn't really be possible, since the inputs came from a
1853 * SSL_CTX that was already populated by OpenSSL.
1854 */
1857 errmsg_internal("could not update certificate chain: %s",
1859 return false;
1860 }
1861
1862 if (host_config->ssl_ca && host_config->ssl_ca[0])
1863 {
1864 /*
1865 * Copy the trust store and list of roots over from the SSL_CTX.
1866 */
1868
1870
1871 /*
1872 * The trust store appears to be the only setting that this function
1873 * can't override via the (SSL *) pointer directly. Instead, share it
1874 * with the active SSL_CTX (this should always be SSL_context).
1875 */
1878
1879 /*
1880 * SSL_set_client_CA_list() will take ownership of its argument, so we
1881 * need to duplicate it.
1882 */
1883 if ((roots = SSL_CTX_get_client_CA_list(ctx)) == NULL
1884 || (roots = SSL_dup_CA_list(roots)) == NULL)
1885 {
1888 errmsg_internal("could not duplicate SSL_CTX CA list: %s",
1890 return false;
1891 }
1892
1894
1895 /*
1896 * Always ask for SSL client cert, but don't fail if it's not
1897 * presented. We might fail such connections later, depending on what
1898 * we find in pg_hba.conf.
1899 */
1900 SSL_set_verify(ssl,
1902 verify_cb);
1903
1905 }
1906
1907 return true;
1908}
1909
1910/*
1911 * sni_clienthello_cb
1912 *
1913 * Callback for extracting the servername extension from the TLS handshake
1914 * during ClientHello. There is a callback in OpenSSL for the servername
1915 * specifically but OpenSSL themselves advice against using it as it is more
1916 * dependent on ordering for execution.
1917 */
1918static int
1919sni_clienthello_cb(SSL *ssl, int *al, void *arg)
1920{
1921 const char *tlsext_hostname;
1922 const unsigned char *tlsext;
1923 size_t left,
1924 len;
1926
1927 if (!ssl_sni)
1928 {
1930 goto found;
1931 }
1932
1934 {
1935 if (left <= 2)
1936 {
1938 return 0;
1939 }
1940 len = (*(tlsext++) << 8);
1941 len += *(tlsext)++;
1942 if (len + 2 != left)
1943 {
1945 return 0;
1946 }
1947
1948 left = len;
1949
1950 if (left == 0 || *tlsext++ != TLSEXT_NAMETYPE_host_name)
1951 {
1953 return 0;
1954 }
1955
1956 left--;
1957
1958 /*
1959 * Now we can finally pull out the byte array with the actual
1960 * hostname.
1961 */
1962 if (left <= 2)
1963 {
1965 return 0;
1966 }
1967 len = (*(tlsext++) << 8);
1968 len += *(tlsext++);
1969 if (len + 2 > left)
1970 {
1972 return 0;
1973 }
1974 left = len;
1975 tlsext_hostname = (const char *) tlsext;
1976
1977 /*
1978 * We have a requested hostname from the client, match against all
1979 * entries in the pg_hosts configuration and attempt to find a match.
1980 * Matching is done case insensitive as per RFC 952 and RFC 921.
1981 */
1983 {
1984 foreach_ptr(char, hostname, host->hostnames)
1985 {
1986 if (strlen(hostname) == len &&
1988 {
1989 install_config = host;
1990 goto found;
1991 }
1992 }
1993 }
1994
1995 /*
1996 * If no host specific match was found, and there is a default config,
1997 * then fall back to using that.
1998 */
2001 }
2002
2003 /*
2004 * No hostname TLS extension in the handshake, use the default or no_sni
2005 * configurations if available.
2006 */
2007 else
2008 {
2010
2011 if (SSL_hosts->no_sni)
2013 else if (SSL_hosts->default_host)
2015 else
2016 {
2017 /*
2018 * Reaching here means that we didn't get a hostname in the TLS
2019 * extension and the server has been configured to not allow any
2020 * connections without a specified hostname.
2021 *
2022 * The error message for a missing server_name should, according
2023 * to RFC 8446, be missing_extension. This isn't entirely ideal
2024 * since the user won't be able to tell which extension the server
2025 * considered missing. Sending unrecognized_name would be a more
2026 * helpful error, but for now we stick to the RFC.
2027 */
2029
2032 errmsg("no hostname provided in callback, and no fallback configured")));
2034 }
2035 }
2036
2037 /*
2038 * If we reach here without a context chosen as the session context then
2039 * fail the handshake and terminate the connection.
2040 */
2041 if (install_config == NULL)
2042 {
2043 if (tlsext_hostname)
2045 else
2048 }
2049
2050found:
2051 if (!ssl_update_ssl(ssl, install_config))
2052 {
2056 errmsg("failed to switch to SSL configuration for host, terminating connection"));
2058 }
2059
2061}
2062#endif /* HAVE_SSL_CTX_SET_CLIENT_HELLO_CB */
2063
2064/*
2065 * Set DH parameters for generating ephemeral DH keys. The
2066 * DH parameters can take a long time to compute, so they must be
2067 * precomputed.
2068 *
2069 * Since few sites will bother to create a parameter file, we also
2070 * provide a fallback to the parameters provided by the OpenSSL
2071 * project.
2072 *
2073 * These values can be static (once loaded or computed) since the
2074 * OpenSSL library can efficiently generate random keys from the
2075 * information provided.
2076 */
2077static bool
2079{
2080 DH *dh = NULL;
2081
2083
2084 if (ssl_dh_params_file[0])
2086 if (!dh)
2088 if (!dh)
2089 {
2092 errmsg("DH: could not load DH parameters")));
2093 return false;
2094 }
2095
2096 if (SSL_CTX_set_tmp_dh(context, dh) != 1)
2097 {
2100 errmsg("DH: could not set DH parameters: %s",
2102 DH_free(dh);
2103 return false;
2104 }
2105
2106 DH_free(dh);
2107 return true;
2108}
2109
2110/*
2111 * Set ECDH parameters for generating ephemeral Elliptic Curve DH
2112 * keys. This is much simpler than the DH parameters, as we just
2113 * need to provide the name of the curve to OpenSSL.
2114 */
2115static bool
2117{
2118#ifndef OPENSSL_NO_ECDH
2119 if (SSL_CTX_set1_groups_list(context, SSLECDHCurve) != 1)
2120 {
2121 /*
2122 * OpenSSL 3.3.0 introduced proper error messages for group parsing
2123 * errors, earlier versions returns "no SSL error reported" which is
2124 * far from helpful. For older versions, we replace with a better
2125 * error message. Injecting the error into the OpenSSL error queue
2126 * need APIs from OpenSSL 3.0.
2127 */
2130 errmsg("could not set group names specified in ssl_groups: %s",
2132 _("No valid groups found"))),
2133 errhint("Ensure that each group name is spelled correctly and supported by the installed version of OpenSSL."));
2134 return false;
2135 }
2136#endif
2137
2138 return true;
2139}
2140
2141/*
2142 * Obtain reason string for passed SSL errcode with replacement
2143 *
2144 * The error message supplied in replacement will be used in case the error
2145 * code from OpenSSL is 0, else the error message from SSLerrmessage() will
2146 * be returned.
2147 *
2148 * Not all versions of OpenSSL place an error on the queue even for failing
2149 * operations, which will yield "no SSL error reported" by SSLerrmessage. This
2150 * function can be used to ensure that a proper error message is displayed for
2151 * versions reporting no error, while using the OpenSSL error via SSLerrmessage
2152 * for versions where there is one.
2153 */
2154static const char *
2155SSLerrmessageExt(unsigned long ecode, const char *replacement)
2156{
2157 if (ecode == 0)
2158 return replacement;
2159 else
2160 return SSLerrmessage(ecode);
2161}
2162
2163/*
2164 * Obtain reason string for passed SSL errcode
2165 *
2166 * ERR_get_error() is used by caller to get errcode to pass here.
2167 *
2168 * Some caution is needed here since ERR_reason_error_string will return NULL
2169 * if it doesn't recognize the error code, or (in OpenSSL >= 3) if the code
2170 * represents a system errno value. We don't want to return NULL ever.
2171 */
2172static const char *
2173SSLerrmessage(unsigned long ecode)
2174{
2175 const char *errreason;
2176 static char errbuf[36];
2177
2178 if (ecode == 0)
2179 return _("no SSL error reported");
2180 errreason = ERR_reason_error_string(ecode);
2181 if (errreason != NULL)
2182 return errreason;
2183
2184 /*
2185 * In OpenSSL 3.0.0 and later, ERR_reason_error_string does not map system
2186 * errno values anymore. (See OpenSSL source code for the explanation.)
2187 * We can cover that shortcoming with this bit of code. Older OpenSSL
2188 * versions don't have the ERR_SYSTEM_ERROR macro, but that's okay because
2189 * they don't have the shortcoming either.
2190 */
2191#ifdef ERR_SYSTEM_ERROR
2193 return strerror(ERR_GET_REASON(ecode));
2194#endif
2195
2196 /* No choice but to report the numeric ecode */
2197 snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), ecode);
2198 return errbuf;
2199}
2200
2201int
2203{
2204 int bits;
2205
2206 if (port->ssl)
2207 {
2208 SSL_get_cipher_bits(port->ssl, &bits);
2209 return bits;
2210 }
2211 else
2212 return 0;
2213}
2214
2215const char *
2217{
2218 if (port->ssl)
2219 return SSL_get_version(port->ssl);
2220 else
2221 return NULL;
2222}
2223
2224const char *
2226{
2227 if (port->ssl)
2228 return SSL_get_cipher(port->ssl);
2229 else
2230 return NULL;
2231}
2232
2233void
2235{
2236 if (port->peer)
2238 else
2239 ptr[0] = '\0';
2240}
2241
2242void
2244{
2245 if (port->peer)
2247 else
2248 ptr[0] = '\0';
2249}
2250
2251void
2253{
2254 if (port->peer)
2255 {
2257 BIGNUM *b;
2258 char *decimal;
2259
2262 decimal = BN_bn2dec(b);
2263
2264 BN_free(b);
2265 strlcpy(ptr, decimal, len);
2267 }
2268 else
2269 ptr[0] = '\0';
2270}
2271
2272char *
2274{
2276 char *cert_hash;
2277 const EVP_MD *algo_type = NULL;
2278 unsigned char hash[EVP_MAX_MD_SIZE]; /* size for SHA-512 */
2279 unsigned int hash_size;
2280 int algo_nid;
2281
2282 *len = 0;
2284 if (server_cert == NULL)
2285 return NULL;
2286
2287 /*
2288 * Get the signature algorithm of the certificate to determine the hash
2289 * algorithm to use for the result. Prefer X509_get_signature_info(),
2290 * introduced in OpenSSL 1.1.1, which can handle RSA-PSS signatures.
2291 */
2292#if HAVE_X509_GET_SIGNATURE_INFO
2294#else
2296 &algo_nid, NULL))
2297#endif
2298 elog(ERROR, "could not determine server certificate signature algorithm");
2299
2300 /*
2301 * The TLS server's certificate bytes need to be hashed with SHA-256 if
2302 * its signature algorithm is MD5 or SHA-1 as per RFC 5929
2303 * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
2304 * is used, the same hash as the signature algorithm is used.
2305 */
2306 switch (algo_nid)
2307 {
2308 case NID_md5:
2309 case NID_sha1:
2311 break;
2312 default:
2314 if (algo_type == NULL)
2315 elog(ERROR, "could not find digest for NID %s",
2317 break;
2318 }
2319
2320 /* generate and save the certificate hash */
2322 elog(ERROR, "could not generate server certificate hash");
2323
2326 *len = hash_size;
2327
2328 return cert_hash;
2329}
2330
2331/*
2332 * Convert an X509 subject name to a cstring.
2333 *
2334 */
2335static char *
2337{
2339 int i,
2340 nid,
2341 count = X509_NAME_entry_count(name);
2343 ASN1_STRING *v;
2344 const char *field_name;
2345 size_t size;
2346 char nullterm;
2347 char *sp;
2348 char *dp;
2349 char *result;
2350
2351 if (membuf == NULL)
2352 ereport(ERROR,
2354 errmsg("could not create BIO")));
2355
2357 for (i = 0; i < count; i++)
2358 {
2361 if (nid == NID_undef)
2362 ereport(ERROR,
2364 errmsg("could not get NID for ASN1_OBJECT object")));
2367 if (field_name == NULL)
2369 if (field_name == NULL)
2370 ereport(ERROR,
2372 errmsg("could not convert NID %d to an ASN1_OBJECT structure", nid)));
2373 BIO_printf(membuf, "/%s=", field_name);
2377 }
2378
2379 /* ensure null termination of the BIO's content */
2380 nullterm = '\0';
2382 size = BIO_get_mem_data(membuf, &sp);
2383 dp = pg_any_to_server(sp, size - 1, PG_UTF8);
2384
2385 result = pstrdup(dp);
2386 if (dp != sp)
2387 pfree(dp);
2388 if (BIO_free(membuf) != 1)
2389 elog(ERROR, "could not free OpenSSL BIO structure");
2390
2391 return result;
2392}
2393
2394/*
2395 * Convert TLS protocol version GUC enum to OpenSSL values
2396 *
2397 * This is a straightforward one-to-one mapping, but doing it this way makes
2398 * the definitions of ssl_min_protocol_version and ssl_max_protocol_version
2399 * independent of OpenSSL availability and version.
2400 *
2401 * If a version is passed that is not supported by the current OpenSSL
2402 * version, then we return -1. If a nonnegative value is returned,
2403 * subsequent code can assume it's working with a supported version.
2404 *
2405 * Note: this is rather similar to libpq's routine in fe-secure-openssl.c,
2406 * so make sure to update both routines if changing this one.
2407 */
2408static int
2410{
2411 switch (v)
2412 {
2413 case PG_TLS_ANY:
2414 return 0;
2415 case PG_TLS1_VERSION:
2416 return TLS1_VERSION;
2417 case PG_TLS1_1_VERSION:
2418#ifdef TLS1_1_VERSION
2419 return TLS1_1_VERSION;
2420#else
2421 break;
2422#endif
2423 case PG_TLS1_2_VERSION:
2424#ifdef TLS1_2_VERSION
2425 return TLS1_2_VERSION;
2426#else
2427 break;
2428#endif
2429 case PG_TLS1_3_VERSION:
2430#ifdef TLS1_3_VERSION
2431 return TLS1_3_VERSION;
2432#else
2433 break;
2434#endif
2435 }
2436
2437 return -1;
2438}
2439
2440/*
2441 * Likewise provide a mapping to strings.
2442 */
2443static const char *
2445{
2446 switch (v)
2447 {
2448 case PG_TLS_ANY:
2449 return "any";
2450 case PG_TLS1_VERSION:
2451 return "TLSv1";
2452 case PG_TLS1_1_VERSION:
2453 return "TLSv1.1";
2454 case PG_TLS1_2_VERSION:
2455 return "TLSv1.2";
2456 case PG_TLS1_3_VERSION:
2457 return "TLSv1.3";
2458 }
2459
2460 return "(unrecognized)";
2461}
2462
2463static uint32
2464host_cache_pointer(const char *key)
2465{
2466 uint32 hash;
2467 char *lkey = pstrdup(key);
2468 int len = strlen(key);
2469
2470 for (int i = 0; i < len; i++)
2471 lkey[i] = pg_tolower(lkey[i]);
2472
2473 hash = string_hash((const void *) lkey, len);
2474 pfree(lkey);
2475 return hash;
2476}
2477
2478static void
2480{
2481 if (isServerStart)
2482 {
2484 {
2487 }
2488 }
2489 else
2490 {
2492 {
2495 }
2496 else
2497
2498 /*
2499 * If reloading and no external command is configured, override
2500 * OpenSSL's default handling of passphrase-protected files,
2501 * because we don't want to prompt for a passphrase in an
2502 * already-running server.
2503 */
2505 }
2506}
bool check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
int load_hosts(List **hosts, char **err_msg)
int run_ssl_passphrase_command(const char *cmd, const char *prompt, bool is_server_start, char *buf, int size)
const char * be_tls_get_version(Port *port)
static bool init_host_context(HostsLine *host, bool isServerStart)
static const char * ssl_protocol_version_to_string(int v)
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 void host_context_cleanup_cb(void *arg)
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 MemoryContext SSL_hosts_memcxt
static SSL_CTX * SSL_context
static bool ssl_is_server_start
static int verify_cb(int ok, X509_STORE_CTX *ctx)
static uint32 host_cache_pointer(const char *key)
static BIO_METHOD * port_bio_method_ptr
static struct hosts * SSL_hosts
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
#define MAXLEN
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_crl_dir
Definition be-secure.c:42
char * ssl_dh_params_file
Definition be-secure.c:43
int ssl_min_protocol_version
Definition be-secure.c:61
ssize_t secure_raw_read(Port *port, void *ptr, size_t len)
Definition be-secure.c:272
char * ssl_cert_file
Definition be-secure.c:38
bool SSLPreferServerCiphers
Definition be-secure.c:59
bool ssl_sni
Definition be-secure.c:65
int ssl_max_protocol_version
Definition be-secure.c:62
char * ssl_passphrase_command
Definition be-secure.c:44
bool ssl_passphrase_command_supports_reload
Definition be-secure.c:45
char * SSLCipherSuites
Definition be-secure.c:52
char * SSLECDHCurve
Definition be-secure.c:56
char * SSLCipherList
Definition be-secure.c:53
char * ssl_key_file
Definition be-secure.c:39
ssize_t secure_raw_write(Port *port, const void *ptr, size_t len)
Definition be-secure.c:381
char * ssl_crl_file
Definition be-secure.c:41
char * ssl_ca_file
Definition be-secure.c:40
#define Assert(condition)
Definition c.h:945
uint32_t uint32
Definition c.h:618
Datum arg
Definition elog.c:1322
int errcode_for_socket_access(void)
Definition elog.c:976
int errcode_for_file_access(void)
Definition elog.c:897
int errcode(int sqlerrcode)
Definition elog.c:874
#define _(x)
Definition elog.c:95
#define LOG
Definition elog.h:31
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
#define errcontext
Definition elog.h:198
int errhint(const char *fmt,...) pg_attribute_printf(1
#define COMMERROR
Definition elog.h:33
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define FATAL
Definition elog.h:41
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:36
#define DEBUG2
Definition elog.h:29
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
#define DEBUG4
Definition elog.h:27
void err(int eval, const char *fmt,...)
Definition err.c:43
int FreeFile(FILE *file)
Definition fd.c:2827
FILE * AllocateFile(const char *name, const char *mode)
Definition fd.c:2628
#define ERRCODE_PROTOCOL_VIOLATION
Definition fe-connect.c:96
#define palloc0_object(type)
Definition fe_memutils.h:75
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition guc.c:4251
uint32 string_hash(const void *key, Size keysize)
Definition hashfn.c:660
const char * str
@ HOSTSFILE_MISSING
Definition hba.h:180
@ HOSTSFILE_LOAD_OK
Definition hba.h:177
@ HOSTSFILE_EMPTY
Definition hba.h:179
@ HOSTSFILE_DISABLED
Definition hba.h:181
@ HOSTSFILE_LOAD_FAILED
Definition hba.h:178
int b
Definition isn.c:74
int i
Definition isn.c:77
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition latch.c:223
@ PG_TLS1_VERSION
Definition libpq.h:153
@ PG_TLS1_3_VERSION
Definition libpq.h:156
@ PG_TLS1_1_VERSION
Definition libpq.h:154
@ PG_TLS1_2_VERSION
Definition libpq.h:155
@ PG_TLS_ANY
Definition libpq.h:152
List * lappend(List *list, void *datum)
Definition list.c:339
#define PG_UTF8
Definition mbprint.c:43
char * pg_any_to_server(const char *s, int len, int encoding)
Definition mbutils.c:687
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
char * pstrdup(const char *in)
Definition mcxt.c:1781
void MemoryContextRegisterResetCallback(MemoryContext context, MemoryContextCallback *cb)
Definition mcxt.c:582
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc0(Size size)
Definition mcxt.c:1417
MemoryContext TopMemoryContext
Definition mcxt.c:166
void * palloc(Size size)
Definition mcxt.c:1387
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition memutils.h:170
static char * errmsg
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
const void size_t len
static char * filename
Definition pg_dumpall.c:133
#define lfirst(lc)
Definition pg_list.h:172
#define NIL
Definition pg_list.h:68
#define foreach_ptr(type, var, lst)
Definition pg_list.h:469
#define linitial(l)
Definition pg_list.h:178
static int port
Definition pg_regress.c:115
static char * hostname
Definition pg_regress.c:114
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define strerror
Definition port.h:273
#define snprintf
Definition port.h:260
unsigned char pg_tolower(unsigned char ch)
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
#define PG_ALPN_PROTOCOL
Definition pqcomm.h:189
#define PG_ALPN_PROTOCOL_VECTOR
Definition pqcomm.h:190
e
static int fb(int x)
static unsigned hash(unsigned *uv, int n)
Definition rege_dfa.c:715
static void error(void)
char * pg_clean_ascii(const char *str, int alloc_flags)
Definition string.c:85
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
const char * hostname
void * ssl_ctx
Definition hba.h:172
char * ssl_passphrase_cmd
Definition hba.h:168
char * sourcefile
Definition hba.h:158
char * ssl_key
Definition hba.h:163
bool ssl_passphrase_reload
Definition hba.h:169
char * ssl_ca
Definition hba.h:167
List * hostnames
Definition hba.h:162
char * ssl_cert
Definition hba.h:164
int linenumber
Definition hba.h:156
Definition pg_list.h:54
bool last_read_was_eof
Definition libpq-be.h:213
HostsLine * default_host
HostsLine * no_sni
const char * type
const char * name
#define WL_SOCKET_READABLE
#define WL_EXIT_ON_PM_DEATH
#define WL_SOCKET_WRITEABLE
#define EINTR
Definition win32_port.h:361
#define EWOULDBLOCK
Definition win32_port.h:367
#define ECONNRESET
Definition win32_port.h:371
#define EAGAIN
Definition win32_port.h:359