LCOV - differential code coverage report
Current view: top level - src/backend/libpq - be-secure-openssl.c (source / functions) Coverage Total Hit UNC UBC GNC CBC EUB ECB DUB DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 70.4 % 842 593 15 234 28 565 4 6 9 29
Current Date: 2026-11-28 16:48:44 +0900 Functions: 94.7 % 38 36 2 9 27 2
Baseline: lcov-20261128-baseline Branches: 47.7 % 713 340 21 352 13 327 4 2
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
[..1] days: 10.0 % 10 1 9 1
(30,360] days: 84.6 % 267 226 6 35 27 199
(360..) days: 64.8 % 565 366 199 366 4 6
Function coverage date bins:
(30,360] days: 100.0 % 6 6 1 5
(360..) days: 93.8 % 32 30 2 8 22
Branch coverage date bins:
[..1] days: 7.1 % 14 1 13 1
(30,360] days: 66.8 % 268 179 8 81 12 167
(360..) days: 36.6 % 437 160 271 160 4 2

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  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                 :                : #include <openssl/ec.h>
                                 52                 :                : #include <openssl/x509v3.h>
                                 53                 :                : 
                                 54                 :                : /*
                                 55                 :                :  * Simplehash for tracking configured hostnames to guard against duplicate
                                 56                 :                :  * entries.  Each list of hosts is traversed and added to the hash during
                                 57                 :                :  * parsing and if a duplicate error is detected an error will be thrown.
                                 58                 :                :  */
                                 59                 :                : typedef struct
                                 60                 :                : {
                                 61                 :                :     uint32      status;
                                 62                 :                :     const char *hostname;
                                 63                 :                : } HostCacheEntry;
                                 64                 :                : static uint32 host_cache_pointer(const char *key);
                                 65                 :                : #define SH_PREFIX       host_cache
                                 66                 :                : #define SH_ELEMENT_TYPE HostCacheEntry
                                 67                 :                : #define SH_KEY_TYPE     const char *
                                 68                 :                : #define SH_KEY          hostname
                                 69                 :                : #define SH_HASH_KEY(tb, key)    host_cache_pointer(key)
                                 70                 :                : #define SH_EQUAL(tb, a, b)      (pg_strcasecmp(a, b) == 0)
                                 71                 :                : #define SH_SCOPE                static inline
                                 72                 :                : #define SH_DECLARE
                                 73                 :                : #define SH_DEFINE
                                 74                 :                : #include "lib/simplehash.h"
                                 75                 :                : 
                                 76                 :                : /* default init hook can be overridden by a shared library */
                                 77                 :                : static void default_openssl_tls_init(SSL_CTX *context, bool isServerStart);
                                 78                 :                : openssl_tls_init_hook_typ openssl_tls_init_hook = default_openssl_tls_init;
                                 79                 :                : 
                                 80                 :                : static int  port_bio_read(BIO *h, char *buf, int size);
                                 81                 :                : static int  port_bio_write(BIO *h, const char *buf, int size);
                                 82                 :                : static BIO_METHOD *port_bio_method(void);
                                 83                 :                : static int  ssl_set_port_bio(Port *port);
                                 84                 :                : 
                                 85                 :                : static DH  *load_dh_file(char *filename, bool isServerStart);
                                 86                 :                : static int  ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata);
                                 87                 :                : static int  dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
                                 88                 :                : static int  verify_cb(int ok, X509_STORE_CTX *ctx);
                                 89                 :                : static void info_cb(const SSL *ssl, int type, int args);
                                 90                 :                : static int  alpn_cb(SSL *ssl,
                                 91                 :                :                     const unsigned char **out,
                                 92                 :                :                     unsigned char *outlen,
                                 93                 :                :                     const unsigned char *in,
                                 94                 :                :                     unsigned int inlen,
                                 95                 :                :                     void *userdata);
                                 96                 :                : static bool initialize_dh(SSL_CTX *context, bool isServerStart);
                                 97                 :                : static bool initialize_ecdh(SSL_CTX *context, bool isServerStart);
                                 98                 :                : static const char *SSLerrmessageExt(unsigned long ecode, const char *replacement);
                                 99                 :                : static const char *SSLerrmessage(unsigned long ecode);
                                100                 :                : static bool init_host_context(HostsLine *host, bool isServerStart, bool *hasWarned)
                                101                 :                :             pg_attribute_nonnull(3);
                                102                 :                : static void host_context_cleanup_cb(void *arg);
                                103                 :                : #ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
                                104                 :                : static int  sni_clienthello_cb(SSL *ssl, int *al, void *arg);
                                105                 :                : #endif
                                106                 :                : 
                                107                 :                : static char *X509_NAME_to_cstring(const X509_NAME *name);
                                108                 :                : 
                                109                 :                : static SSL_CTX *SSL_context = NULL;
                                110                 :                : static MemoryContext SSL_hosts_memcxt = NULL;
                                111                 :                : static struct hosts
                                112                 :                : {
                                113                 :                :     /*
                                114                 :                :      * List of HostsLine structures containing SSL configurations for
                                115                 :                :      * connections with hostnames defined in the SNI extension.
                                116                 :                :      */
                                117                 :                :     List       *sni;
                                118                 :                : 
                                119                 :                :     /* The SSL configuration to use for connections without SNI */
                                120                 :                :     HostsLine  *no_sni;
                                121                 :                : 
                                122                 :                :     /*
                                123                 :                :      * The default SSL configuration to use as a fallback in case no hostname
                                124                 :                :      * matches the supplied hostname in the SNI extension.
                                125                 :                :      */
                                126                 :                :     HostsLine  *default_host;
                                127                 :                : 
                                128                 :                :     /*
                                129                 :                :      * Whether the configuration was loaded with ssl_sni enabled.
                                130                 :                :      */
                                131                 :                :     bool        sni_enabled;
                                132                 :                : }          *SSL_hosts;
                                133                 :                : 
                                134                 :                : static bool dummy_ssl_passwd_cb_called = false;
                                135                 :                : static bool ssl_is_server_start;
                                136                 :                : 
                                137                 :                : static int  ssl_protocol_version_to_openssl(int v);
                                138                 :                : static const char *ssl_protocol_version_to_string(int v);
                                139                 :                : 
                                140                 :                : struct CallbackErr
                                141                 :                : {
                                142                 :                :     /*
                                143                 :                :      * Storage for passing certificate verification error logging from the
                                144                 :                :      * callback.
                                145                 :                :      */
                                146                 :                :     char       *cert_errdetail;
                                147                 :                : };
                                148                 :                : 
                                149                 :                : /* ------------------------------------------------------------ */
                                150                 :                : /*                       Public interface                       */
                                151                 :                : /* ------------------------------------------------------------ */
                                152                 :                : 
                                153                 :                : int
 3615 tgl@sss.pgh.pa.us         154                 :CBC          71 : be_tls_init(bool isServerStart)
                                155                 :                : {
  255 dgustafsson@postgres      156                 :             71 :     List       *pg_hosts = NIL;
                                157                 :                :     ListCell   *line;
                                158                 :                :     MemoryContext oldcxt;
                                159                 :             71 :     MemoryContext host_memcxt = NULL;
                                160                 :                :     MemoryContextCallback *host_memcxt_cb;
                                161                 :             71 :     char       *err_msg = NULL;
                                162                 :                :     HostsFileLoadResult res;
                                163                 :                :     struct hosts *new_hosts;
                                164                 :             71 :     SSL_CTX    *context = NULL;
 2441 michael@paquier.xyz       165                 :             71 :     int         ssl_ver_min = -1;
                                166                 :             71 :     int         ssl_ver_max = -1;
  255 dgustafsson@postgres      167                 :             71 :     host_cache_hash *host_cache = NULL;
  122 dgustafsson@postgres      168                 :GNC          71 :     bool        hasWarned = false;
   33 dgustafsson@postgres      169                 :CBC          71 :     int         nloaded = 0;
                                170                 :                : 
                                171                 :                :     /*
                                172                 :                :      * Since we don't know which host we're using until the ClientHello is
                                173                 :                :      * sent, ssl_loaded_verify_locations *always* starts out as false. The
                                174                 :                :      * only place it's set to true is in sni_clienthello_cb().
                                175                 :                :      */
  255                           176                 :             71 :     ssl_loaded_verify_locations = false;
                                177                 :                : 
                                178                 :             71 :     host_memcxt = AllocSetContextCreate(CurrentMemoryContext,
                                179                 :                :                                         "hosts file parser context",
                                180                 :                :                                         ALLOCSET_SMALL_SIZES);
                                181                 :             71 :     oldcxt = MemoryContextSwitchTo(host_memcxt);
                                182                 :                : 
                                183                 :                :     /* Allocate a tentative replacement for SSL_hosts. */
                                184                 :             71 :     new_hosts = palloc0_object(struct hosts);
   53                           185                 :             71 :     new_hosts->sni_enabled = ssl_sni;
                                186                 :                : 
                                187                 :                :     /*
                                188                 :                :      * Register a reset callback for the memory context which is responsible
                                189                 :                :      * for freeing OpenSSL managed allocations upon context deletion.  The
                                190                 :                :      * callback is allocated here to make sure it gets cleaned up along with
                                191                 :                :      * the memory context it's registered for.
                                192                 :                :      */
  255                           193                 :             71 :     host_memcxt_cb = palloc0_object(MemoryContextCallback);
                                194                 :             71 :     host_memcxt_cb->func = host_context_cleanup_cb;
                                195                 :             71 :     host_memcxt_cb->arg = new_hosts;
                                196                 :             71 :     MemoryContextRegisterResetCallback(host_memcxt, host_memcxt_cb);
                                197                 :                : 
                                198                 :                :     /*
                                199                 :                :      * If ssl_sni is enabled, attempt to load and parse TLS configuration from
                                200                 :                :      * the pg_hosts.conf file with the set of hosts returned as a list.  If
                                201                 :                :      * there are hosts configured they take precedence over the configuration
                                202                 :                :      * in postgresql.conf.  Make sure to allocate the parsed rows in their own
                                203                 :                :      * memory context so that we can delete them easily in case parsing fails.
                                204                 :                :      * If ssl_sni is disabled then set the state accordingly to make sure we
                                205                 :                :      * instead parse the config from postgresql.conf.
                                206                 :                :      *
                                207                 :                :      * The reason for not doing everything in this if-else conditional is that
                                208                 :                :      * we want to use the same processing of postgresql.conf for when ssl_sni
                                209                 :                :      * is off as well as when it's on but the hosts file is missing etc.  Thus
                                210                 :                :      * we set res to the state and continue with a new conditional instead of
                                211                 :                :      * duplicating logic and risk it diverging over time.
                                212                 :                :      */
                                213         [ +  + ]:             71 :     if (ssl_sni)
                                214                 :                :     {
                                215                 :                :         /*
                                216                 :                :          * The GUC check hook should have already blocked this but to be on
                                217                 :                :          * the safe side we double-check here.
                                218                 :                :          */
                                219                 :                : #ifndef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
                                220                 :                :         ereport(isServerStart ? FATAL : LOG,
                                221                 :                :                 errcode(ERRCODE_CONFIG_FILE_ERROR),
                                222                 :                :                 errmsg("ssl_sni is not supported with LibreSSL"));
                                223                 :                :         goto error;
                                224                 :                : #endif
                                225                 :                : 
                                226                 :                :         /* Attempt to load configuration from pg_hosts.conf */
                                227                 :             29 :         res = load_hosts(&pg_hosts, &err_msg);
                                228                 :                : 
                                229                 :                :         /*
                                230                 :                :          * pg_hosts.conf is not required to contain configuration, but if it
                                231                 :                :          * does we error out in case it fails to load rather than continue to
                                232                 :                :          * try the postgresql.conf configuration to avoid silently falling
                                233                 :                :          * back on an undesired configuration.
                                234                 :                :          */
                                235         [ +  + ]:             29 :         if (res == HOSTSFILE_LOAD_FAILED)
                                236                 :                :         {
                                237   [ +  -  +  -  :              3 :             ereport(isServerStart ? FATAL : LOG,
                                              +  - ]
                                238                 :                :                     errcode(ERRCODE_CONFIG_FILE_ERROR),
                                239                 :                :                     errmsg("could not load file \"%s\": %s", HostsFileName,
                                240                 :                :                            err_msg ? err_msg : "unknown error"));
  255 dgustafsson@postgres      241                 :UBC           0 :             goto error;
                                242                 :                :         }
                                243                 :                :     }
                                244                 :                :     else
  255 dgustafsson@postgres      245                 :CBC          42 :         res = HOSTSFILE_DISABLED;
                                246                 :                : 
                                247                 :                :     /*
                                248                 :                :      * Loading and parsing the hosts file was successful, create configs for
                                249                 :                :      * each host entry and add to the list of hosts to be checked during
                                250                 :                :      * login.
                                251                 :                :      */
                                252         [ +  + ]:             68 :     if (res == HOSTSFILE_LOAD_OK)
                                253                 :                :     {
                                254         [ -  + ]:             25 :         Assert(ssl_sni);
                                255                 :                : 
                                256   [ +  -  +  +  :             58 :         foreach(line, pg_hosts)
                                              +  + ]
                                257                 :                :         {
                                258                 :             40 :             HostsLine  *host = lfirst(line);
                                259                 :                : 
                                260                 :                :             /*
                                261                 :                :              * The hostname in the config will be set to NULL for the default
                                262                 :                :              * host as well as in configs used for non-SNI connections.  Lists
                                263                 :                :              * of hostnames in pg_hosts.conf are not allowed to contain the
                                264                 :                :              * default '*' entry or a '/no_sni/' entry and this is checked
                                265                 :                :              * during parsing.  Thus we can inspect the head of the hostnames
                                266                 :                :              * list for these since they will never be anywhere else.
                                267                 :                :              */
                                268         [ +  + ]:             40 :             if (strcmp(linitial(host->hostnames), "*") == 0)
                                269                 :                :             {
                                270         [ +  + ]:              7 :                 if (new_hosts->default_host)
                                271                 :                :                 {
                                272   [ +  -  +  - ]:              1 :                     ereport(isServerStart ? FATAL : LOG,
                                273                 :                :                             errcode(ERRCODE_CONFIG_FILE_ERROR),
                                274                 :                :                             errmsg("multiple default hosts specified"),
                                275                 :                :                             errcontext("line %d of configuration file \"%s\"",
                                276                 :                :                                        host->linenumber, host->sourcefile));
                                277                 :              2 :                     goto error;
                                278                 :                :                 }
                                279                 :                : 
                                280                 :              6 :                 new_hosts->default_host = host;
                                281                 :                :             }
                                282         [ +  + ]:             33 :             else if (strcmp(linitial(host->hostnames), "/no_sni/") == 0)
                                283                 :                :             {
                                284         [ +  + ]:              3 :                 if (new_hosts->no_sni)
                                285                 :                :                 {
                                286   [ +  -  +  - ]:              1 :                     ereport(isServerStart ? FATAL : LOG,
                                287                 :                :                             errcode(ERRCODE_CONFIG_FILE_ERROR),
                                288                 :                :                             errmsg("multiple no_sni hosts specified"),
                                289                 :                :                             errcontext("line %d of configuration file \"%s\"",
                                290                 :                :                                        host->linenumber, host->sourcefile));
  255 dgustafsson@postgres      291                 :UBC           0 :                     goto error;
                                292                 :                :                 }
                                293                 :                : 
  255 dgustafsson@postgres      294                 :CBC           2 :                 new_hosts->no_sni = host;
                                295                 :                :             }
                                296                 :                :             else
                                297                 :                :             {
                                298                 :                :                 /* Check the hostnames for duplicates */
                                299         [ +  + ]:             30 :                 if (!host_cache)
                                300                 :             21 :                     host_cache = host_cache_create(host_memcxt, 32, NULL);
                                301                 :                : 
                                302   [ +  -  +  +  :             92 :                 foreach_ptr(char, hostname, host->hostnames)
                                              +  + ]
                                303                 :                :                 {
                                304                 :                :                     HostCacheEntry *entry;
                                305                 :                :                     bool        found;
                                306                 :                : 
                                307                 :             36 :                     entry = host_cache_insert(host_cache, hostname, &found);
                                308         [ +  + ]:             36 :                     if (found)
                                309                 :                :                     {
                                310   [ +  -  +  - ]:              2 :                         ereport(isServerStart ? FATAL : LOG,
                                311                 :                :                                 errcode(ERRCODE_CONFIG_FILE_ERROR),
                                312                 :                :                                 errmsg("multiple entries for host \"%s\" specified",
                                313                 :                :                                        hostname),
                                314                 :                :                                 errcontext("line %d of configuration file \"%s\"",
                                315                 :                :                                            host->linenumber, host->sourcefile));
  255 dgustafsson@postgres      316                 :UBC           0 :                         goto error;
                                317                 :                :                     }
                                318                 :                :                     else
  255 dgustafsson@postgres      319                 :CBC          34 :                         entry->hostname = pstrdup(hostname);
                                320                 :                :                 }
                                321                 :                : 
                                322                 :                :                 /*
                                323                 :                :                  * At this point we know we have a configuration with a list
                                324                 :                :                  * of distinct 1..n hostnames for literal string matching with
                                325                 :                :                  * the SNI extension from the user.
                                326                 :                :                  */
                                327                 :             28 :                 new_hosts->sni = lappend(new_hosts->sni, host);
                                328                 :                :             }
                                329                 :                : 
                                330                 :                :             /*
                                331                 :                :              * Create the SSL context only once the entry has been accepted
                                332                 :                :              * and added to new_hosts, as the cleanup callback can only free
                                333                 :                :              * contexts of entries it can reach from there.
                                334                 :                :              *
                                335                 :                :              * An EXEC_BACKEND child has no previous configuration to fall
                                336                 :                :              * back on, so rather than leaving the backend without SSL for all
                                337                 :                :              * hosts we keep a failed entry without a context.  Connections
                                338                 :                :              * selecting it will fail the handshake.
                                339                 :                :              */
   33 dgustafsson@postgres      340         [ +  + ]:GNC          36 :             if (init_host_context(host, isServerStart, &hasWarned))
   33 dgustafsson@postgres      341                 :CBC          33 :                 nloaded++;
                                342         [ +  - ]:              2 :             else if (!IsUnderPostmaster)
   53                           343                 :              2 :                 goto error;
                                344                 :                :         }
                                345                 :                : 
   33                           346         [ -  + ]:             18 :         if (nloaded == 0)
   33 dgustafsson@postgres      347                 :UBC           0 :             goto error;
                                348                 :                :     }
                                349                 :                : 
                                350                 :                :     /*
                                351                 :                :      * If SNI is disabled, then we load configuration from postgresql.conf. If
                                352                 :                :      * SNI is enabled but the pg_hosts.conf file doesn't exist, or is empty,
                                353                 :                :      * then we also load the config from postgresql.conf.
                                354                 :                :      */
  255 dgustafsson@postgres      355   [ +  +  +  -  :CBC          43 :     else if (res == HOSTSFILE_DISABLED || res == HOSTSFILE_EMPTY || res == HOSTSFILE_MISSING)
                                              +  - ]
                                356                 :                :     {
  103 michael@paquier.xyz       357                 :GNC          43 :         HostsLine  *pgconf = palloc0_object(HostsLine);
                                358                 :                : 
                                359                 :                : #ifdef USE_ASSERT_CHECKING
  255 dgustafsson@postgres      360         [ +  + ]:CBC          43 :         if (res == HOSTSFILE_DISABLED)
                                361         [ -  + ]:             42 :             Assert(ssl_sni == false);
                                362                 :                : #endif
                                363                 :                : 
                                364                 :                :         /*
                                365                 :                :          * Copy the configuration from the GUC variables since they aren't
                                366                 :                :          * guaranteed to survive a failed reload.
                                367                 :                :          */
   53                           368                 :             43 :         pgconf->ssl_cert = pstrdup(ssl_cert_file);
                                369                 :             43 :         pgconf->ssl_key = pstrdup(ssl_key_file);
                                370                 :             43 :         pgconf->ssl_ca = pstrdup(ssl_ca_file);
                                371                 :             43 :         pgconf->ssl_passphrase_cmd = pstrdup(ssl_passphrase_command);
  255                           372                 :             43 :         pgconf->ssl_passphrase_reload = ssl_passphrase_command_supports_reload;
                                373                 :                : 
  122 dgustafsson@postgres      374         [ +  + ]:GNC          43 :         if (!init_host_context(pgconf, isServerStart, &hasWarned))
  255 dgustafsson@postgres      375                 :CBC           3 :             goto error;
                                376                 :                : 
                                377                 :                :         /*
                                378                 :                :          * If postgresql.conf is used to configure SSL then by definition it
                                379                 :                :          * will be the default context as we don't have per-host config.
                                380                 :                :          */
                                381                 :             38 :         new_hosts->default_host = pgconf;
                                382                 :                :     }
                                383                 :                : 
                                384                 :                :     /*
                                385                 :                :      * Make sure we have at least one configuration loaded to use, without
                                386                 :                :      * that we cannot drive a connection so exit.
                                387                 :                :      */
                                388   [ +  +  +  +  :             56 :     if (new_hosts->sni == NIL && !new_hosts->default_host && !new_hosts->no_sni)
                                              -  + ]
                                389                 :                :     {
 3615 tgl@sss.pgh.pa.us         390   [ #  #  #  # ]:UBC           0 :         ereport(isServerStart ? FATAL : LOG,
                                391                 :                :                 errcode(ERRCODE_CONFIG_FILE_ERROR),
                                392                 :                :                 errmsg("no SSL configurations loaded"),
                                393                 :                :         /*- translator: The two %s contain filenames */
                                394                 :                :                 errhint("If ssl_sni is enabled then add configuration to file \"%s\", else file \"%s\".",
                                395                 :                :                         HostsFileName, "postgresql.conf"));
 3617                           396                 :              0 :         goto error;
                                397                 :                :     }
                                398                 :                : 
                                399                 :                : #ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
                                400                 :                : 
                                401                 :                :     /*
                                402                 :                :      * Create a new SSL context into which we'll load all the configuration
                                403                 :                :      * settings.  If we fail partway through, we can avoid memory leakage by
                                404                 :                :      * freeing this context; we don't install it as active until the end.
                                405                 :                :      */
  122 dgustafsson@postgres      406                 :GNC          56 :     context = SSL_CTX_new(TLS_method());
  255 dgustafsson@postgres      407         [ -  + ]:CBC          56 :     if (!context)
                                408                 :                :     {
 3615 tgl@sss.pgh.pa.us         409   [ #  #  #  # ]:UBC           0 :         ereport(isServerStart ? FATAL : LOG,
                                410                 :                :                 (errmsg("could not create SSL context: %s",
                                411                 :                :                         SSLerrmessage(ERR_get_error()))));
 3617                           412                 :              0 :         goto error;
                                413                 :                :     }
                                414                 :                : #else
                                415                 :                : 
                                416                 :                :     /*
                                417                 :                :      * If the client hello callback isn't supported we want to use the default
                                418                 :                :      * context as the one to drive the handshake so avoid creating a new one
                                419                 :                :      * and use the already existing default one instead.
                                420                 :                :      */
                                421                 :                :     context = new_hosts->default_host->ssl_ctx;
                                422                 :                : 
                                423                 :                :     /*
                                424                 :                :      * Since we don't allocate a new SSL_CTX here like we do when SNI has been
                                425                 :                :      * enabled we need to bump the reference count on context to avoid double
                                426                 :                :      * free of the context when using the same cleanup logic across the cases.
                                427                 :                :      */
                                428                 :                :     SSL_CTX_up_ref(context);
                                429                 :                : #endif
                                430                 :                : 
                                431                 :                :     /*
                                432                 :                :      * Disable OpenSSL's moving-write-buffer sanity check, because it causes
                                433                 :                :      * unnecessary failures in nonblocking send cases.
                                434                 :                :      */
  255 dgustafsson@postgres      435                 :CBC          56 :     SSL_CTX_set_mode(context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
                                436                 :                : 
 2930 peter_e@gmx.net           437         [ +  - ]:             56 :     if (ssl_min_protocol_version)
                                438                 :                :     {
 2441 michael@paquier.xyz       439                 :             56 :         ssl_ver_min = ssl_protocol_version_to_openssl(ssl_min_protocol_version);
                                440                 :                : 
                                441         [ -  + ]:             56 :         if (ssl_ver_min == -1)
                                442                 :                :         {
 2441 michael@paquier.xyz       443   [ #  #  #  # ]:UBC           0 :             ereport(isServerStart ? FATAL : LOG,
                                444                 :                :             /*- translator: first %s is a GUC option name, second %s is its value */
                                445                 :                :                     (errmsg("\"%s\" setting \"%s\" not supported by this build",
                                446                 :                :                             "ssl_min_protocol_version",
                                447                 :                :                             GetConfigOption("ssl_min_protocol_version",
                                448                 :                :                                             false, false))));
 2850 peter@eisentraut.org      449                 :              0 :             goto error;
                                450                 :                :         }
                                451                 :                : 
 2441 michael@paquier.xyz       452         [ -  + ]:CBC          56 :         if (!SSL_CTX_set_min_proto_version(context, ssl_ver_min))
                                453                 :                :         {
 2618 peter@eisentraut.org      454   [ #  #  #  # ]:UBC           0 :             ereport(isServerStart ? FATAL : LOG,
                                455                 :                :                     (errmsg("could not set minimum SSL protocol version")));
                                456                 :              0 :             goto error;
                                457                 :                :         }
                                458                 :                :     }
                                459                 :                : 
 2930 peter_e@gmx.net           460         [ +  + ]:CBC          56 :     if (ssl_max_protocol_version)
                                461                 :                :     {
 2441 michael@paquier.xyz       462                 :              1 :         ssl_ver_max = ssl_protocol_version_to_openssl(ssl_max_protocol_version);
                                463                 :                : 
                                464         [ -  + ]:              1 :         if (ssl_ver_max == -1)
                                465                 :                :         {
 2441 michael@paquier.xyz       466   [ #  #  #  # ]:UBC           0 :             ereport(isServerStart ? FATAL : LOG,
                                467                 :                :             /*- translator: first %s is a GUC option name, second %s is its value */
                                468                 :                :                     (errmsg("\"%s\" setting \"%s\" not supported by this build",
                                469                 :                :                             "ssl_max_protocol_version",
                                470                 :                :                             GetConfigOption("ssl_max_protocol_version",
                                471                 :                :                                             false, false))));
 2850 peter@eisentraut.org      472                 :              0 :             goto error;
                                473                 :                :         }
                                474                 :                : 
 2441 michael@paquier.xyz       475         [ -  + ]:CBC           1 :         if (!SSL_CTX_set_max_proto_version(context, ssl_ver_max))
                                476                 :                :         {
 2618 peter@eisentraut.org      477   [ #  #  #  # ]:UBC           0 :             ereport(isServerStart ? FATAL : LOG,
                                478                 :                :                     (errmsg("could not set maximum SSL protocol version")));
                                479                 :              0 :             goto error;
                                480                 :                :         }
                                481                 :                :     }
                                482                 :                : 
                                483                 :                :     /* Check compatibility of min/max protocols */
 2441 michael@paquier.xyz       484   [ +  -  +  + ]:CBC          56 :     if (ssl_min_protocol_version &&
                                485                 :                :         ssl_max_protocol_version)
                                486                 :                :     {
                                487                 :                :         /*
                                488                 :                :          * No need to check for invalid values (-1) for each protocol number
                                489                 :                :          * as the code above would have already generated an error.
                                490                 :                :          */
                                491         [ +  - ]:              1 :         if (ssl_ver_min > ssl_ver_max)
                                492                 :                :         {
                                493   [ +  -  +  - ]:              1 :             ereport(isServerStart ? FATAL : LOG,
                                494                 :                :                     (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                495                 :                :                      errmsg("could not set SSL protocol version range"),
                                496                 :                :                      errdetail("\"%s\" cannot be higher than \"%s\".",
                                497                 :                :                                "ssl_min_protocol_version",
                                498                 :                :                                "ssl_max_protocol_version")));
 2403 michael@paquier.xyz       499                 :UBC           0 :             goto error;
                                500                 :                :         }
                                501                 :                :     }
                                502                 :                : 
                                503                 :                :     /*
                                504                 :                :      * Disallow SSL session tickets. OpenSSL use both stateful and stateless
                                505                 :                :      * tickets for TLSv1.3, and stateless ticket for TLSv1.2. SSL_OP_NO_TICKET
                                506                 :                :      * is available since 0.9.8f but only turns off stateless tickets. In
                                507                 :                :      * order to turn off stateful tickets we need SSL_CTX_set_num_tickets,
                                508                 :                :      * which is available since OpenSSL 1.1.1.  LibreSSL 3.5.4 (from OpenBSD
                                509                 :                :      * 7.1) introduced this API for compatibility, but doesn't support session
                                510                 :                :      * tickets at all so it's a no-op there.
                                511                 :                :      */
                                512                 :                : #ifdef HAVE_SSL_CTX_SET_NUM_TICKETS
  855 dgustafsson@postgres      513                 :CBC          55 :     SSL_CTX_set_num_tickets(context, 0);
                                514                 :                : #endif
  831                           515                 :             55 :     SSL_CTX_set_options(context, SSL_OP_NO_TICKET);
                                516                 :                : 
                                517                 :                :     /* disallow SSL session caching, too */
 3403 tgl@sss.pgh.pa.us         518                 :             55 :     SSL_CTX_set_session_cache_mode(context, SSL_SESS_CACHE_OFF);
                                519                 :                : 
                                520                 :                :     /* disallow SSL compression */
 2090 michael@paquier.xyz       521                 :             55 :     SSL_CTX_set_options(context, SSL_OP_NO_COMPRESSION);
                                522                 :                : 
                                523                 :                :     /*
                                524                 :                :      * Disallow SSL renegotiation.  This concerns only TLSv1.2 and older
                                525                 :                :      * protocol versions, as TLSv1.3 has no support for renegotiation.
                                526                 :                :      * SSL_OP_NO_RENEGOTIATION is available in OpenSSL since 1.1.0h (via a
                                527                 :                :      * backport from 1.1.1). SSL_OP_NO_CLIENT_RENEGOTIATION is available in
                                528                 :                :      * LibreSSL since 2.5.1 disallowing all client-initiated renegotiation
                                529                 :                :      * (this is usually on by default).
                                530                 :                :      */
                                531                 :                : #ifdef SSL_OP_NO_RENEGOTIATION
 2013                           532                 :             55 :     SSL_CTX_set_options(context, SSL_OP_NO_RENEGOTIATION);
                                533                 :                : #endif
                                534                 :                : #ifdef SSL_OP_NO_CLIENT_RENEGOTIATION
                                535                 :                :     SSL_CTX_set_options(context, SSL_OP_NO_CLIENT_RENEGOTIATION);
                                536                 :                : #endif
                                537                 :                : 
                                538                 :                :     /* set up ephemeral DH and ECDH keys */
 3407 heikki.linnakangas@i      539         [ -  + ]:             55 :     if (!initialize_dh(context, isServerStart))
 3407 heikki.linnakangas@i      540                 :UBC           0 :         goto error;
 3615 tgl@sss.pgh.pa.us         541         [ -  + ]:CBC          55 :     if (!initialize_ecdh(context, isServerStart))
 3617 tgl@sss.pgh.pa.us         542                 :UBC           0 :         goto error;
                                543                 :                : 
                                544                 :                :     /* set up the allowed cipher list for TLSv1.2 and below */
  765 dgustafsson@postgres      545         [ -  + ]:CBC          53 :     if (SSL_CTX_set_cipher_list(context, SSLCipherList) != 1)
                                546                 :                :     {
 3615 tgl@sss.pgh.pa.us         547   [ #  #  #  # ]:UBC           0 :         ereport(isServerStart ? FATAL : LOG,
                                548                 :                :                 (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                549                 :                :                  errmsg("could not set the TLSv1.2 cipher list (no valid ciphers available)")));
 3617                           550                 :              0 :         goto error;
                                551                 :                :     }
                                552                 :                : 
                                553                 :                :     /*
                                554                 :                :      * Set up the allowed cipher suites for TLSv1.3. If the GUC is an empty
                                555                 :                :      * string we leave the allowed suites to be the OpenSSL default value.
                                556                 :                :      */
  765 dgustafsson@postgres      557         [ +  + ]:CBC          53 :     if (SSLCipherSuites[0])
                                558                 :                :     {
                                559                 :                :         /* set up the allowed cipher suites */
                                560         [ -  + ]:             50 :         if (SSL_CTX_set_ciphersuites(context, SSLCipherSuites) != 1)
                                561                 :                :         {
  765 dgustafsson@postgres      562   [ #  #  #  # ]:UBC           0 :             ereport(isServerStart ? FATAL : LOG,
                                563                 :                :                     (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                564                 :                :                      errmsg("could not set the TLSv1.3 cipher suites (no valid ciphers available)")));
                                565                 :              0 :             goto error;
                                566                 :                :         }
                                567                 :                :     }
                                568                 :                : 
                                569                 :                :     /* Let server choose order */
 4485 heikki.linnakangas@i      570         [ +  - ]:CBC          53 :     if (SSLPreferServerCiphers)
 3617 tgl@sss.pgh.pa.us         571                 :             53 :         SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
                                572                 :                : 
                                573                 :                :     /*
                                574                 :                :      * Success!  Replace any existing SSL_context and host configurations.
                                575                 :                :      */
  255 dgustafsson@postgres      576         [ +  + ]:             53 :     if (SSL_context)
                                577                 :                :     {
                                578                 :             14 :         SSL_CTX_free(SSL_context);
                                579                 :             14 :         SSL_context = NULL;
                                580                 :                :     }
                                581                 :                : 
                                582                 :             53 :     MemoryContextSwitchTo(oldcxt);
                                583                 :                : 
                                584         [ +  + ]:             53 :     if (SSL_hosts_memcxt)
                                585                 :             14 :         MemoryContextDelete(SSL_hosts_memcxt);
                                586                 :                : 
                                587                 :             53 :     SSL_hosts_memcxt = host_memcxt;
                                588                 :             53 :     SSL_hosts = new_hosts;
                                589                 :             53 :     SSL_context = context;
                                590                 :                : 
                                591                 :             53 :     return 0;
                                592                 :                : 
   53                           593                 :              5 : error:
                                594                 :                : 
                                595                 :                :     /*
                                596                 :                :      * Clean up by releasing working SSL contexts as well as allocations
                                597                 :                :      * performed during parsing.  Since all our allocations are done in a
                                598                 :                :      * local memory context all we need to do is delete it.
                                599                 :                :      */
  255                           600         [ -  + ]:              5 :     if (context)
  255 dgustafsson@postgres      601                 :UBC           0 :         SSL_CTX_free(context);
                                602                 :                : 
                                603                 :                :     /*
                                604                 :                :      * If the initialization failed, and the ssl_sni setting was changed, we
                                605                 :                :      * issue a WARNING to indicate that the ssl_sni setting won't match the
                                606                 :                :      * SSL configuration in use.
                                607                 :                :      */
   53 dgustafsson@postgres      608   [ +  -  +  -  :CBC           5 :     if (SSL_context && SSL_hosts && SSL_hosts->sni_enabled != ssl_sni)
                                              +  + ]
                                609                 :                :     {
                                610   [ +  -  +  - ]:              2 :         ereport(WARNING,
                                611                 :                :                 errcode(ERRCODE_CONFIG_FILE_ERROR),
                                612                 :                :                 SSL_hosts->sni_enabled ?
                                613                 :                :                 errmsg("SSL configuration not reloaded, SNI remains on") :
                                614                 :                :                 errmsg("SSL configuration not reloaded, SNI remains off"),
                                615                 :                :                 errdetail("The SSL configuration failed to reload; the previous configuration and SNI state will remain active."));
                                616                 :                :     }
                                617                 :                : 
  255                           618                 :              5 :     MemoryContextSwitchTo(oldcxt);
                                619                 :              5 :     MemoryContextDelete(host_memcxt);
                                620                 :              5 :     return -1;
                                621                 :                : }
                                622                 :                : 
                                623                 :                : /*
                                624                 :                :  * host_context_cleanup_cb
                                625                 :                :  *
                                626                 :                :  * Memory context reset callback for clearing OpenSSL managed resources when
                                627                 :                :  * hosts are reloaded and the previous set of configured hosts are freed. As
                                628                 :                :  * all hosts are allocated in a single context we don't need to free each host
                                629                 :                :  * individually, just resources managed by OpenSSL.
                                630                 :                :  */
                                631                 :                : static void
                                632                 :            421 : host_context_cleanup_cb(void *arg)
                                633                 :                : {
                                634                 :            421 :     struct hosts *hosts = arg;
                                635                 :                : 
                                636   [ +  +  +  +  :            981 :     foreach_ptr(HostsLine, host, hosts->sni)
                                              +  + ]
                                637                 :                :     {
                                638         [ +  + ]:            139 :         if (host->ssl_ctx != NULL)
                                639                 :            137 :             SSL_CTX_free(host->ssl_ctx);
                                640                 :                :     }
                                641                 :                : 
                                642   [ +  +  +  - ]:            421 :     if (hosts->no_sni && hosts->no_sni->ssl_ctx)
                                643                 :              9 :         SSL_CTX_free(hosts->no_sni->ssl_ctx);
                                644                 :                : 
                                645   [ +  +  +  - ]:            421 :     if (hosts->default_host && hosts->default_host->ssl_ctx)
                                646                 :            346 :         SSL_CTX_free(hosts->default_host->ssl_ctx);
                                647                 :            421 : }
                                648                 :                : 
                                649                 :                : 
                                650                 :                : /*
                                651                 :                :  * init_host_context
                                652                 :                :  *
                                653                 :                :  * Creates and initializes an OpenSSL SSL_CTX structure for the host config
                                654                 :                :  * passed in the host parameter.  The SSL_CTX will be initialized with cert,
                                655                 :                :  * key, CA and CRL; the remaining options are copied from the main context
                                656                 :                :  * during connection setup in case this context ends up being used.
                                657                 :                :  *
                                658                 :                :  * If an ssl init hook has been defined, and ssl_sni is enabled, then issue a
                                659                 :                :  * warning since the hook won't be executed.  hasWarned will be is set to true
                                660                 :                :  * to indicate that the warning has been issued, and passing it back as true
                                661                 :                :  * will omit future warning to avoid flooding the logs.
                                662                 :                :  */
                                663                 :                : static bool
  122 dgustafsson@postgres      664                 :GNC          79 : init_host_context(HostsLine *host, bool isServerStart, bool *hasWarned)
                                665                 :                : {
                                666                 :             79 :     SSL_CTX    *ctx = SSL_CTX_new(TLS_method());
                                667                 :                : 
  255 dgustafsson@postgres      668         [ -  + ]:CBC          79 :     if (!ctx)
                                669                 :                :     {
  255 dgustafsson@postgres      670   [ #  #  #  # ]:UBC           0 :         ereport(isServerStart ? FATAL : LOG,
                                671                 :                :                 (errmsg("could not create SSL context: %s",
                                672                 :                :                         SSLerrmessage(ERR_get_error()))));
                                673                 :              0 :         goto error;
                                674                 :                :     }
                                675                 :                : 
                                676                 :                :     /*
                                677                 :                :      * Call init hook (usually to set password callback) in case SNI hasn't
                                678                 :                :      * been enabled. If SNI is enabled the hook won't operate on the actual
                                679                 :                :      * TLS context used so it cannot function properly; we warn if one has
                                680                 :                :      * been installed.
                                681                 :                :      *
                                682                 :                :      * If SNI is enabled, we set password callback based what was configured.
                                683                 :                :      */
  255 dgustafsson@postgres      684         [ +  + ]:CBC          79 :     if (!ssl_sni)
                                685                 :             42 :         (*openssl_tls_init_hook) (ctx, isServerStart);
                                686                 :                :     else
                                687                 :                :     {
  122 dgustafsson@postgres      688   [ +  +  +  + ]:GNC          37 :         if (openssl_tls_init_hook != default_openssl_tls_init && !*hasWarned)
                                689                 :                :         {
  255 dgustafsson@postgres      690         [ +  - ]:CBC           1 :             ereport(WARNING,
                                691                 :                :                     errcode(ERRCODE_CONFIG_FILE_ERROR),
                                692                 :                :                     errmsg("SNI is enabled; installed TLS init hook will be ignored"),
                                693                 :                :             /*- translator: first %s is a GUC, second %s contains a filename */
                                694                 :                :                     errhint("TLS init hooks are incompatible with SNI. "
                                695                 :                :                             "Set \"%s\" to \"off\" to make use of the hook "
                                696                 :                :                             "that is currently installed, or remove the hook "
                                697                 :                :                             "and use per-host passphrase commands in \"%s\".",
                                698                 :                :                             "ssl_sni", HostsFileName));
  122 dgustafsson@postgres      699                 :GNC           1 :             *hasWarned = true;
                                700                 :                :         }
                                701                 :                : 
                                702                 :                :         /*
                                703                 :                :          * Set up the password callback, if configured.
                                704                 :                :          */
  255 dgustafsson@postgres      705         [ +  + ]:CBC          37 :         if (isServerStart)
                                706                 :                :         {
                                707   [ +  +  +  - ]:             22 :             if (host->ssl_passphrase_cmd && host->ssl_passphrase_cmd[0])
                                708                 :                :             {
                                709                 :              6 :                 SSL_CTX_set_default_passwd_cb(ctx, ssl_external_passwd_cb);
                                710                 :              6 :                 SSL_CTX_set_default_passwd_cb_userdata(ctx, host->ssl_passphrase_cmd);
                                711                 :                :             }
                                712                 :                :         }
                                713                 :                :         else
                                714                 :                :         {
                                715                 :                :             /*
                                716                 :                :              * If ssl_passphrase_reload is true then ssl_passphrase_cmd cannot
                                717                 :                :              * be NULL due to their parsing order, but just in case and to
                                718                 :                :              * self-document the code we replicate the nullness checks.
                                719                 :                :              */
                                720         [ +  + ]:             15 :             if (host->ssl_passphrase_reload &&
                                721   [ +  -  +  - ]:              6 :                 (host->ssl_passphrase_cmd && host->ssl_passphrase_cmd[0]))
                                722                 :                :             {
                                723                 :              6 :                 SSL_CTX_set_default_passwd_cb(ctx, ssl_external_passwd_cb);
                                724                 :              6 :                 SSL_CTX_set_default_passwd_cb_userdata(ctx, host->ssl_passphrase_cmd);
                                725                 :                :             }
                                726                 :                :             else
                                727                 :                :             {
                                728                 :                :                 /*
                                729                 :                :                  * If reloading and no external command is configured,
                                730                 :                :                  * override OpenSSL's default handling of passphrase-protected
                                731                 :                :                  * files, because we don't want to prompt for a passphrase in
                                732                 :                :                  * an already-running server.
                                733                 :                :                  */
                                734                 :              9 :                 SSL_CTX_set_default_passwd_cb(ctx, dummy_ssl_passwd_cb);
                                735                 :                :             }
                                736                 :                :         }
                                737                 :                :     }
                                738                 :                : 
                                739                 :                :     /*
                                740                 :                :      * Load and verify server's certificate and private key
                                741                 :                :      */
                                742         [ +  + ]:             79 :     if (SSL_CTX_use_certificate_chain_file(ctx, host->ssl_cert) != 1)
                                743                 :                :     {
                                744   [ -  +  +  - ]:              2 :         ereport(isServerStart ? FATAL : LOG,
                                745                 :                :                 (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                746                 :                :                  errmsg("could not load server certificate file \"%s\": %s",
                                747                 :                :                         host->ssl_cert, SSLerrmessage(ERR_get_error()))));
                                748                 :              2 :         goto error;
                                749                 :                :     }
                                750                 :                : 
                                751         [ -  + ]:             77 :     if (!check_ssl_key_file_permissions(host->ssl_key, isServerStart))
  255 dgustafsson@postgres      752                 :UBC           0 :         goto error;
                                753                 :                : 
                                754                 :                : 
                                755                 :                :     /* used by the callback */
  255 dgustafsson@postgres      756                 :CBC          77 :     ssl_is_server_start = isServerStart;
                                757                 :                : 
                                758                 :                :     /*
                                759                 :                :      * OK, try to load the private key file.
                                760                 :                :      */
                                761                 :             77 :     dummy_ssl_passwd_cb_called = false;
                                762                 :                : 
                                763         [ +  + ]:             77 :     if (SSL_CTX_use_PrivateKey_file(ctx,
                                764                 :             77 :                                     host->ssl_key,
                                765                 :                :                                     SSL_FILETYPE_PEM) != 1)
                                766                 :                :     {
                                767         [ +  + ]:              6 :         if (dummy_ssl_passwd_cb_called)
                                768   [ -  +  +  - ]:              2 :             ereport(isServerStart ? FATAL : LOG,
                                769                 :                :                     (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                770                 :                :                      errmsg("private key file \"%s\" cannot be reloaded because it requires a passphrase",
                                771                 :                :                             host->ssl_key)));
                                772                 :                :         else
                                773   [ +  +  +  - ]:              4 :             ereport(isServerStart ? FATAL : LOG,
                                774                 :                :                     (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                775                 :                :                      errmsg("could not load private key file \"%s\": %s",
                                776                 :                :                             host->ssl_key, SSLerrmessage(ERR_get_error()))));
                                777                 :              3 :         goto error;
                                778                 :                :     }
                                779                 :                : 
                                780         [ -  + ]:             71 :     if (SSL_CTX_check_private_key(ctx) != 1)
                                781                 :                :     {
  255 dgustafsson@postgres      782   [ #  #  #  # ]:UBC           0 :         ereport(isServerStart ? FATAL : LOG,
                                783                 :                :                 (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                784                 :                :                  errmsg("check of private key failed: %s",
                                785                 :                :                         SSLerrmessage(ERR_get_error()))));
                                786                 :              0 :         goto error;
                                787                 :                :     }
                                788                 :                : 
                                789                 :                :     /*
                                790                 :                :      * Load CA store, so we can verify client certificates if needed.
                                791                 :                :      */
  255 dgustafsson@postgres      792   [ +  +  +  + ]:CBC          71 :     if (host->ssl_ca && host->ssl_ca[0])
                                793                 :                :     {
                                794                 :                :         STACK_OF(X509_NAME) * root_cert_list;
                                795                 :                : 
                                796   [ +  -  -  + ]:            106 :         if (SSL_CTX_load_verify_locations(ctx, host->ssl_ca, NULL) != 1 ||
                                797                 :             53 :             (root_cert_list = SSL_load_client_CA_file(host->ssl_ca)) == NULL)
                                798                 :                :         {
 3615 tgl@sss.pgh.pa.us         799   [ #  #  #  # ]:UBC           0 :             ereport(isServerStart ? FATAL : LOG,
                                800                 :                :                     (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                801                 :                :                      errmsg("could not load root certificate file \"%s\": %s",
                                802                 :                :                             host->ssl_ca, SSLerrmessage(ERR_get_error()))));
 3617                           803                 :              0 :             goto error;
                                804                 :                :         }
                                805                 :                : 
                                806                 :                :         /*
                                807                 :                :          * Tell OpenSSL to send the list of root certs we trust to clients in
                                808                 :                :          * CertificateRequests.  This lets a client with a keystore select the
                                809                 :                :          * appropriate client certificate to send to us.  Also, this ensures
                                810                 :                :          * that the SSL context will "own" the root_cert_list and remember to
                                811                 :                :          * free it when no longer needed.
                                812                 :                :          */
  255 dgustafsson@postgres      813                 :CBC          53 :         SSL_CTX_set_client_CA_list(ctx, root_cert_list);
                                814                 :                :     }
                                815                 :                : 
                                816                 :                :     /*----------
                                817                 :                :      * Load the Certificate Revocation List (CRL).
                                818                 :                :      * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
                                819                 :                :      *----------
                                820                 :                :      */
 2109 peter@eisentraut.org      821   [ +  +  -  + ]:             71 :     if (ssl_crl_file[0] || ssl_crl_dir[0])
                                822                 :                :     {
  255 dgustafsson@postgres      823                 :             67 :         X509_STORE *cvstore = SSL_CTX_get_cert_store(ctx);
                                824                 :                : 
 4485 heikki.linnakangas@i      825         [ +  - ]:             67 :         if (cvstore)
                                826                 :                :         {
                                827                 :                :             /* Set the flags to check against the complete CRL chain */
 2109 peter@eisentraut.org      828         [ +  - ]:            134 :             if (X509_STORE_load_locations(cvstore,
                                829         [ +  - ]:             67 :                                           ssl_crl_file[0] ? ssl_crl_file : NULL,
 2083 tgl@sss.pgh.pa.us         830         [ +  + ]:             67 :                                           ssl_crl_dir[0] ? ssl_crl_dir : NULL)
                                831                 :                :                 == 1)
                                832                 :                :             {
 4485 heikki.linnakangas@i      833                 :             67 :                 X509_STORE_set_flags(cvstore,
                                834                 :                :                                      X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
                                835                 :                :             }
 2109 peter@eisentraut.org      836         [ #  # ]:UBC           0 :             else if (ssl_crl_dir[0] == 0)
                                837                 :                :             {
 3615 tgl@sss.pgh.pa.us         838   [ #  #  #  # ]:              0 :                 ereport(isServerStart ? FATAL : LOG,
                                839                 :                :                         (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                840                 :                :                          errmsg("could not load SSL certificate revocation list file \"%s\": %s",
                                841                 :                :                                 ssl_crl_file, SSLerrmessage(ERR_get_error()))));
 3617                           842                 :              0 :                 goto error;
                                843                 :                :             }
 2109 peter@eisentraut.org      844         [ #  # ]:              0 :             else if (ssl_crl_file[0] == 0)
                                845                 :                :             {
                                846   [ #  #  #  # ]:              0 :                 ereport(isServerStart ? FATAL : LOG,
                                847                 :                :                         (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                848                 :                :                          errmsg("could not load SSL certificate revocation list directory \"%s\": %s",
                                849                 :                :                                 ssl_crl_dir, SSLerrmessage(ERR_get_error()))));
                                850                 :              0 :                 goto error;
                                851                 :                :             }
                                852                 :                :             else
                                853                 :                :             {
                                854   [ #  #  #  # ]:              0 :                 ereport(isServerStart ? FATAL : LOG,
                                855                 :                :                         (errcode(ERRCODE_CONFIG_FILE_ERROR),
                                856                 :                :                          errmsg("could not load SSL certificate revocation list file \"%s\" or directory \"%s\": %s",
                                857                 :                :                                 ssl_crl_file, ssl_crl_dir,
                                858                 :                :                                 SSLerrmessage(ERR_get_error()))));
                                859                 :              0 :                 goto error;
                                860                 :                :             }
                                861                 :                :         }
                                862                 :                :     }
                                863                 :                : 
  255 dgustafsson@postgres      864                 :CBC          71 :     host->ssl_ctx = ctx;
                                865                 :             71 :     return true;
                                866                 :                : 
 3617 tgl@sss.pgh.pa.us         867                 :              5 : error:
  255 dgustafsson@postgres      868         [ +  - ]:              5 :     if (ctx)
                                869                 :              5 :         SSL_CTX_free(ctx);
                                870                 :              5 :     return false;
                                871                 :                : }
                                872                 :                : 
                                873                 :                : void
 3617 tgl@sss.pgh.pa.us         874                 :            162 : be_tls_destroy(void)
                                875                 :                : {
                                876         [ -  + ]:            162 :     if (SSL_context)
 3617 tgl@sss.pgh.pa.us         877                 :UBC           0 :         SSL_CTX_free(SSL_context);
 3617 tgl@sss.pgh.pa.us         878                 :CBC         162 :     SSL_context = NULL;
                                879                 :            162 :     ssl_loaded_verify_locations = false;
                                880                 :                : 
   53 dgustafsson@postgres      881         [ -  + ]:            162 :     if (SSL_hosts_memcxt)
                                882                 :                :     {
   53 dgustafsson@postgres      883                 :UBC           0 :         MemoryContextDelete(SSL_hosts_memcxt);
                                884                 :              0 :         SSL_hosts_memcxt = NULL;
                                885                 :              0 :         SSL_hosts = NULL;
                                886                 :                :     }
 4492 heikki.linnakangas@i      887                 :CBC         162 : }
                                888                 :                : 
                                889                 :                : int
 4485                           890                 :            169 : be_tls_open_server(Port *port)
                                891                 :                : {
                                892                 :                :     int         r;
                                893                 :                :     int         err;
                                894                 :                :     int         waitfor;
                                895                 :                :     unsigned long ecode;
                                896                 :                :     bool        give_proto_hint;
                                897                 :                :     static struct CallbackErr err_context;
                                898                 :                : 
                                899         [ -  + ]:            169 :     Assert(!port->ssl);
                                900         [ -  + ]:            169 :     Assert(!port->peer);
                                901                 :                : 
 3617 tgl@sss.pgh.pa.us         902         [ -  + ]:            169 :     if (!SSL_context)
                                903                 :                :     {
 3617 tgl@sss.pgh.pa.us         904         [ #  # ]:UBC           0 :         ereport(COMMERROR,
                                905                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                906                 :                :                  errmsg("could not initialize SSL connection: SSL context not set up")));
                                907                 :              0 :         return -1;
                                908                 :                :     }
                                909                 :                : 
                                910                 :                :     /* set up debugging/info callback */
 2136 michael@paquier.xyz       911                 :CBC         169 :     SSL_CTX_set_info_callback(SSL_context, info_cb);
                                912                 :                : 
                                913                 :                :     /* enable ALPN */
  964 heikki.linnakangas@i      914                 :            169 :     SSL_CTX_set_alpn_select_cb(SSL_context, alpn_cb, port);
                                915                 :                : 
 4485                           916         [ -  + ]:            169 :     if (!(port->ssl = SSL_new(SSL_context)))
                                917                 :                :     {
 4485 heikki.linnakangas@i      918         [ #  # ]:UBC           0 :         ereport(COMMERROR,
                                919                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                920                 :                :                  errmsg("could not initialize SSL connection: %s",
                                921                 :                :                         SSLerrmessage(ERR_get_error()))));
                                922                 :              0 :         return -1;
                                923                 :                :     }
  778 dgustafsson@postgres      924         [ -  + ]:CBC         169 :     if (!ssl_set_port_bio(port))
                                925                 :                :     {
 4485 heikki.linnakangas@i      926         [ #  # ]:UBC           0 :         ereport(COMMERROR,
                                927                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                928                 :                :                  errmsg("could not set SSL socket: %s",
                                929                 :                :                         SSLerrmessage(ERR_get_error()))));
                                930                 :              0 :         return -1;
                                931                 :                :     }
                                932                 :                : 
                                933                 :                :     /*
                                934                 :                :      * If the underlying TLS library supports the client hello callback we use
                                935                 :                :      * that in order to support host based configuration using the SNI TLS
                                936                 :                :      * extension.  If the user has disabled SNI via the ssl_sni GUC we still
                                937                 :                :      * make use of the callback in order to have consistent handling of
                                938                 :                :      * OpenSSL contexts, except in that case the callback will install the
                                939                 :                :      * default configuration regardless of the hostname sent by the user in
                                940                 :                :      * the handshake.
                                941                 :                :      *
                                942                 :                :      * In case the TLS library does not support the client hello callback, as
                                943                 :                :      * of this writing LibreSSL does not, we need to install the client cert
                                944                 :                :      * verification callback here (if the user configured a CA) since we
                                945                 :                :      * cannot use the OpenSSL context update functionality.
                                946                 :                :      */
                                947                 :                : #ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
  255 dgustafsson@postgres      948                 :CBC         169 :     SSL_CTX_set_client_hello_cb(SSL_context, sni_clienthello_cb, NULL);
                                949                 :                : #else
                                950                 :                :     if (SSL_hosts->default_host->ssl_ca && SSL_hosts->default_host->ssl_ca[0])
                                951                 :                :     {
                                952                 :                :         /*
                                953                 :                :          * Always ask for SSL client cert, but don't fail if it's not
                                954                 :                :          * presented.  We might fail such connections later, depending on what
                                955                 :                :          * we find in pg_hba.conf.
                                956                 :                :          */
                                957                 :                :         SSL_set_verify(port->ssl,
                                958                 :                :                        (SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE),
                                959                 :                :                        verify_cb);
                                960                 :                : 
                                961                 :                :         ssl_loaded_verify_locations = true;
                                962                 :                :     }
                                963                 :                : #endif
                                964                 :                : 
  381                           965                 :            169 :     err_context.cert_errdetail = NULL;
                                966                 :            169 :     SSL_set_ex_data(port->ssl, 0, &err_context);
                                967                 :                : 
 4485 heikki.linnakangas@i      968                 :            169 :     port->ssl_in_use = true;
                                969                 :                : 
                                970                 :            605 : aloop:
                                971                 :                : 
                                972                 :                :     /*
                                973                 :                :      * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
                                974                 :                :      * queue.  In general, the current thread's error queue must be empty
                                975                 :                :      * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
                                976                 :                :      * not work reliably.  An extension may have failed to clear the
                                977                 :                :      * per-thread error queue following another call to an OpenSSL I/O
                                978                 :                :      * routine.
                                979                 :                :      */
 1083 tgl@sss.pgh.pa.us         980                 :            605 :     errno = 0;
 3886 peter_e@gmx.net           981                 :            605 :     ERR_clear_error();
 4485 heikki.linnakangas@i      982                 :            605 :     r = SSL_accept(port->ssl);
                                983         [ +  + ]:            605 :     if (r <= 0)
                                984                 :                :     {
                                985                 :            468 :         err = SSL_get_error(port->ssl, r);
                                986                 :                : 
                                987                 :                :         /*
                                988                 :                :          * Other clients of OpenSSL in the backend may fail to call
                                989                 :                :          * ERR_get_error(), but we always do, so as to not cause problems for
                                990                 :                :          * OpenSSL clients that don't call ERR_clear_error() defensively.  Be
                                991                 :                :          * sure that this happens by calling now. SSL_get_error() relies on
                                992                 :                :          * the OpenSSL per-thread error queue being intact, so this is the
                                993                 :                :          * earliest possible point ERR_get_error() may be called.
                                994                 :                :          */
 3886 peter_e@gmx.net           995                 :            468 :         ecode = ERR_get_error();
 4485 heikki.linnakangas@i      996   [ +  -  +  -  :            468 :         switch (err)
                                                 - ]
                                997                 :                :         {
                                998                 :            436 :             case SSL_ERROR_WANT_READ:
                                999                 :                :             case SSL_ERROR_WANT_WRITE:
                               1000                 :                :                 /* not allowed during connection establishment */
 4316 andres@anarazel.de       1001         [ -  + ]:            436 :                 Assert(!port->noblock);
                               1002                 :                : 
                               1003                 :                :                 /*
                               1004                 :                :                  * No need to care about timeouts/interrupts here. At this
                               1005                 :                :                  * point authentication_timeout still employs
                               1006                 :                :                  * StartupPacketTimeoutHandler() which directly exits.
                               1007                 :                :                  */
                               1008         [ +  - ]:            436 :                 if (err == SSL_ERROR_WANT_READ)
 2925 tmunro@postgresql.or     1009                 :            436 :                     waitfor = WL_SOCKET_READABLE | WL_EXIT_ON_PM_DEATH;
                               1010                 :                :                 else
 2925 tmunro@postgresql.or     1011                 :UBC           0 :                     waitfor = WL_SOCKET_WRITEABLE | WL_EXIT_ON_PM_DEATH;
                               1012                 :                : 
  784 heikki.linnakangas@i     1013                 :CBC         436 :                 (void) WaitLatchOrSocket(NULL, waitfor, port->sock, 0,
                               1014                 :                :                                          WAIT_EVENT_SSL_OPEN_SERVER);
 4485                          1015                 :            436 :                 goto aloop;
 4485 heikki.linnakangas@i     1016                 :UBC           0 :             case SSL_ERROR_SYSCALL:
 1083 tgl@sss.pgh.pa.us        1017   [ #  #  #  # ]:              0 :                 if (r < 0 && errno != 0)
 4485 heikki.linnakangas@i     1018         [ #  # ]:              0 :                     ereport(COMMERROR,
                               1019                 :                :                             (errcode_for_socket_access(),
                               1020                 :                :                              errmsg("could not accept SSL connection: %m")));
                               1021                 :                :                 else
                               1022         [ #  # ]:              0 :                     ereport(COMMERROR,
                               1023                 :                :                             (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1024                 :                :                              errmsg("could not accept SSL connection: EOF detected")));
                               1025                 :              0 :                 break;
 4485 heikki.linnakangas@i     1026                 :CBC          32 :             case SSL_ERROR_SSL:
 2345 tgl@sss.pgh.pa.us        1027         [ -  + ]:             32 :                 switch (ERR_GET_REASON(ecode))
                               1028                 :                :                 {
                               1029                 :                :                         /*
                               1030                 :                :                          * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
                               1031                 :                :                          * TLSV1_ALERT_PROTOCOL_VERSION have been observed
                               1032                 :                :                          * when trying to communicate with an old OpenSSL
                               1033                 :                :                          * library, or when the client and server specify
                               1034                 :                :                          * disjoint protocol ranges.  NO_PROTOCOLS_AVAILABLE
                               1035                 :                :                          * occurs if there's a local misconfiguration (which
                               1036                 :                :                          * can happen despite our checks, if openssl.cnf
                               1037                 :                :                          * injects a limit we didn't account for).  It's not
                               1038                 :                :                          * very clear what would make OpenSSL return the other
                               1039                 :                :                          * codes listed here, but a hint about protocol
                               1040                 :                :                          * versions seems like it's appropriate for all.
                               1041                 :                :                          */
 2345 tgl@sss.pgh.pa.us        1042                 :UBC           0 :                     case SSL_R_NO_PROTOCOLS_AVAILABLE:
                               1043                 :                :                     case SSL_R_UNSUPPORTED_PROTOCOL:
                               1044                 :                :                     case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
                               1045                 :                :                     case SSL_R_UNKNOWN_PROTOCOL:
                               1046                 :                :                     case SSL_R_UNKNOWN_SSL_VERSION:
                               1047                 :                :                     case SSL_R_UNSUPPORTED_SSL_VERSION:
                               1048                 :                :                     case SSL_R_WRONG_SSL_VERSION:
                               1049                 :                :                     case SSL_R_WRONG_VERSION_NUMBER:
                               1050                 :                :                     case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
                               1051                 :                : #ifdef SSL_R_VERSION_TOO_HIGH
                               1052                 :                :                     case SSL_R_VERSION_TOO_HIGH:
                               1053                 :                : #endif
                               1054                 :                : #ifdef SSL_R_VERSION_TOO_LOW
                               1055                 :                :                     case SSL_R_VERSION_TOO_LOW:
                               1056                 :                : #endif
                               1057                 :              0 :                         give_proto_hint = true;
                               1058                 :              0 :                         break;
 2345 tgl@sss.pgh.pa.us        1059                 :CBC          32 :                     default:
                               1060                 :             32 :                         give_proto_hint = false;
                               1061                 :             32 :                         break;
                               1062                 :                :                 }
 4485 heikki.linnakangas@i     1063   [ +  -  +  +  :             32 :                 ereport(COMMERROR,
                                     -  +  -  -  -  
                                                 - ]
                               1064                 :                :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1065                 :                :                          errmsg("could not accept SSL connection: %s",
                               1066                 :                :                                 SSLerrmessage(ecode)),
                               1067                 :                :                          err_context.cert_errdetail ? errdetail_internal("%s", err_context.cert_errdetail) : 0,
                               1068                 :                :                          give_proto_hint ?
                               1069                 :                :                          errhint("This may indicate that the client does not support any SSL protocol version between %s and %s.",
                               1070                 :                :                                  ssl_min_protocol_version ?
                               1071                 :                :                                  ssl_protocol_version_to_string(ssl_min_protocol_version) :
                               1072                 :                :                                  MIN_OPENSSL_TLS_VERSION,
                               1073                 :                :                                  ssl_max_protocol_version ?
                               1074                 :                :                                  ssl_protocol_version_to_string(ssl_max_protocol_version) :
                               1075                 :                :                                  MAX_OPENSSL_TLS_VERSION) : 0));
  381 dgustafsson@postgres     1076         [ +  + ]:             32 :                 if (err_context.cert_errdetail)
                               1077                 :              8 :                     pfree(err_context.cert_errdetail);
 4485 heikki.linnakangas@i     1078                 :             32 :                 break;
 4485 heikki.linnakangas@i     1079                 :UBC           0 :             case SSL_ERROR_ZERO_RETURN:
                               1080         [ #  # ]:              0 :                 ereport(COMMERROR,
                               1081                 :                :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1082                 :                :                          errmsg("could not accept SSL connection: EOF detected")));
                               1083                 :              0 :                 break;
                               1084                 :              0 :             default:
                               1085         [ #  # ]:              0 :                 ereport(COMMERROR,
                               1086                 :                :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1087                 :                :                          errmsg("unrecognized SSL error code: %d",
                               1088                 :                :                                 err)));
                               1089                 :              0 :                 break;
                               1090                 :                :         }
 4485 heikki.linnakangas@i     1091                 :CBC          32 :         return -1;
                               1092                 :                :     }
                               1093                 :                : 
                               1094                 :                :     /* Get the protocol selected by ALPN */
  964                          1095                 :            137 :     port->alpn_used = false;
                               1096                 :                :     {
                               1097                 :                :         const unsigned char *selected;
                               1098                 :                :         unsigned int len;
                               1099                 :                : 
                               1100                 :            137 :         SSL_get0_alpn_selected(port->ssl, &selected, &len);
                               1101                 :                : 
                               1102                 :                :         /* If ALPN is used, check that we negotiated the expected protocol */
                               1103         [ +  - ]:            137 :         if (selected != NULL)
                               1104                 :                :         {
                               1105         [ +  - ]:            137 :             if (len == strlen(PG_ALPN_PROTOCOL) &&
                               1106         [ +  - ]:            137 :                 memcmp(selected, PG_ALPN_PROTOCOL, strlen(PG_ALPN_PROTOCOL)) == 0)
                               1107                 :                :             {
                               1108                 :            137 :                 port->alpn_used = true;
                               1109                 :                :             }
                               1110                 :                :             else
                               1111                 :                :             {
                               1112                 :                :                 /* shouldn't happen */
  964 heikki.linnakangas@i     1113         [ #  # ]:UBC           0 :                 ereport(COMMERROR,
                               1114                 :                :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1115                 :                :                          errmsg("received SSL connection request with unexpected ALPN protocol")));
                               1116                 :                :             }
                               1117                 :                :         }
                               1118                 :                :     }
                               1119                 :                : 
                               1120                 :                :     /* Get client certificate, if available. */
 4485 heikki.linnakangas@i     1121                 :CBC         137 :     port->peer = SSL_get_peer_certificate(port->ssl);
                               1122                 :                : 
                               1123                 :                :     /* and extract the Common Name and Distinguished Name from it. */
                               1124                 :            137 :     port->peer_cn = NULL;
 2070 andrew@dunslane.net      1125                 :            137 :     port->peer_dn = NULL;
 4485 heikki.linnakangas@i     1126                 :            137 :     port->peer_cert_valid = false;
                               1127         [ +  + ]:            137 :     if (port->peer != NULL)
                               1128                 :                :     {
                               1129                 :                :         int         len;
  183 dgustafsson@postgres     1130                 :             31 :         const X509_NAME *x509name = X509_get_subject_name(port->peer);
                               1131                 :                :         char       *peer_dn;
 2070 andrew@dunslane.net      1132                 :             31 :         BIO        *bio = NULL;
                               1133                 :             31 :         BUF_MEM    *bio_buf = NULL;
                               1134                 :                :         int         index;
                               1135                 :                : 
  122 dgustafsson@postgres     1136                 :GNC          31 :         index = X509_NAME_get_index_by_NID(unconstify(X509_NAME *, x509name), NID_commonName, -1);
                               1137         [ +  - ]:             31 :         if (index >= 0)
                               1138                 :                :         {
                               1139                 :                :             const X509_NAME_ENTRY *entry;
                               1140                 :                :             const ASN1_STRING *peer_cn_asn1;
                               1141                 :                :             const unsigned char *peer_cn_internal;
                               1142                 :                :             char       *peer_cn;
                               1143                 :                : 
                               1144                 :             31 :             entry = X509_NAME_get_entry(unconstify(X509_NAME *, x509name), index);
                               1145                 :             31 :             peer_cn_asn1 = X509_NAME_ENTRY_get_data(entry);
                               1146                 :             31 :             len = ASN1_STRING_length(peer_cn_asn1);
                               1147                 :             31 :             peer_cn_internal = ASN1_STRING_get0_data(peer_cn_asn1);
                               1148                 :                : 
 4485 heikki.linnakangas@i     1149                 :CBC          31 :             peer_cn = MemoryContextAlloc(TopMemoryContext, len + 1);
  122 dgustafsson@postgres     1150                 :GNC          31 :             memcpy(peer_cn, peer_cn_internal, len);
 4485 heikki.linnakangas@i     1151                 :CBC          31 :             peer_cn[len] = '\0';
                               1152                 :                : 
                               1153                 :                :             /*
                               1154                 :                :              * Reject embedded NULLs in certificate common name to prevent
                               1155                 :                :              * attacks like CVE-2009-4034.
                               1156                 :                :              */
                               1157         [ -  + ]:             31 :             if (len != strlen(peer_cn))
                               1158                 :                :             {
 4485 heikki.linnakangas@i     1159         [ #  # ]:UBC           0 :                 ereport(COMMERROR,
                               1160                 :                :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1161                 :                :                          errmsg("SSL certificate's common name contains embedded null")));
                               1162                 :              0 :                 pfree(peer_cn);
                               1163                 :              0 :                 return -1;
                               1164                 :                :             }
                               1165                 :                : 
 4485 heikki.linnakangas@i     1166                 :CBC          31 :             port->peer_cn = peer_cn;
                               1167                 :                :         }
                               1168                 :                : 
 2070 andrew@dunslane.net      1169                 :             31 :         bio = BIO_new(BIO_s_mem());
                               1170         [ -  + ]:             31 :         if (!bio)
                               1171                 :                :         {
 1163 dgustafsson@postgres     1172         [ #  # ]:UBC           0 :             if (port->peer_cn != NULL)
                               1173                 :                :             {
                               1174                 :              0 :                 pfree(port->peer_cn);
                               1175                 :              0 :                 port->peer_cn = NULL;
                               1176                 :                :             }
 2070 andrew@dunslane.net      1177                 :              0 :             return -1;
                               1178                 :                :         }
                               1179                 :                : 
                               1180                 :                :         /*
                               1181                 :                :          * RFC2253 is the closest thing to an accepted standard format for
                               1182                 :                :          * DNs. We have documented how to produce this format from a
                               1183                 :                :          * certificate. It uses commas instead of slashes for delimiters,
                               1184                 :                :          * which make regular expression matching a bit easier. Also note that
                               1185                 :                :          * it prints the Subject fields in reverse order.
                               1186                 :                :          */
 1163 dgustafsson@postgres     1187   [ +  -  -  + ]:CBC          62 :         if (X509_NAME_print_ex(bio, x509name, 0, XN_FLAG_RFC2253) == -1 ||
                               1188                 :             31 :             BIO_get_mem_ptr(bio, &bio_buf) <= 0)
                               1189                 :                :         {
 2070 andrew@dunslane.net      1190                 :UBC           0 :             BIO_free(bio);
 1163 dgustafsson@postgres     1191         [ #  # ]:              0 :             if (port->peer_cn != NULL)
                               1192                 :                :             {
                               1193                 :              0 :                 pfree(port->peer_cn);
                               1194                 :              0 :                 port->peer_cn = NULL;
                               1195                 :                :             }
 2070 andrew@dunslane.net      1196                 :              0 :             return -1;
                               1197                 :                :         }
 2070 andrew@dunslane.net      1198                 :CBC          31 :         peer_dn = MemoryContextAlloc(TopMemoryContext, bio_buf->length + 1);
                               1199                 :             31 :         memcpy(peer_dn, bio_buf->data, bio_buf->length);
                               1200                 :             31 :         len = bio_buf->length;
                               1201                 :             31 :         BIO_free(bio);
                               1202                 :             31 :         peer_dn[len] = '\0';
                               1203         [ -  + ]:             31 :         if (len != strlen(peer_dn))
                               1204                 :                :         {
 2070 andrew@dunslane.net      1205         [ #  # ]:UBC           0 :             ereport(COMMERROR,
                               1206                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1207                 :                :                      errmsg("SSL certificate's distinguished name contains embedded null")));
                               1208                 :              0 :             pfree(peer_dn);
 1163 dgustafsson@postgres     1209         [ #  # ]:              0 :             if (port->peer_cn != NULL)
                               1210                 :                :             {
                               1211                 :              0 :                 pfree(port->peer_cn);
                               1212                 :              0 :                 port->peer_cn = NULL;
                               1213                 :                :             }
 2070 andrew@dunslane.net      1214                 :              0 :             return -1;
                               1215                 :                :         }
                               1216                 :                : 
 2070 andrew@dunslane.net      1217                 :CBC          31 :         port->peer_dn = peer_dn;
                               1218                 :                : 
 4485 heikki.linnakangas@i     1219                 :             31 :         port->peer_cert_valid = true;
                               1220                 :                :     }
                               1221                 :                : 
                               1222                 :            137 :     return 0;
                               1223                 :                : }
                               1224                 :                : 
                               1225                 :                : void
                               1226                 :            169 : be_tls_close(Port *port)
                               1227                 :                : {
                               1228         [ +  - ]:            169 :     if (port->ssl)
                               1229                 :                :     {
                               1230                 :            169 :         SSL_shutdown(port->ssl);
                               1231                 :            169 :         SSL_free(port->ssl);
                               1232                 :            169 :         port->ssl = NULL;
                               1233                 :            169 :         port->ssl_in_use = false;
                               1234                 :                :     }
                               1235                 :                : 
                               1236         [ +  + ]:            169 :     if (port->peer)
                               1237                 :                :     {
                               1238                 :             31 :         X509_free(port->peer);
                               1239                 :             31 :         port->peer = NULL;
                               1240                 :                :     }
                               1241                 :                : 
                               1242         [ +  + ]:            169 :     if (port->peer_cn)
                               1243                 :                :     {
                               1244                 :             31 :         pfree(port->peer_cn);
                               1245                 :             31 :         port->peer_cn = NULL;
                               1246                 :                :     }
                               1247                 :                : 
 2070 andrew@dunslane.net      1248         [ +  + ]:            169 :     if (port->peer_dn)
                               1249                 :                :     {
                               1250                 :             31 :         pfree(port->peer_dn);
                               1251                 :             31 :         port->peer_dn = NULL;
                               1252                 :                :     }
 4492 heikki.linnakangas@i     1253                 :            169 : }
                               1254                 :                : 
                               1255                 :                : ssize_t
 4306                          1256                 :            635 : be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
                               1257                 :                : {
                               1258                 :                :     ssize_t     n;
                               1259                 :                :     int         err;
                               1260                 :                :     unsigned long ecode;
                               1261                 :                : 
 4485                          1262                 :            635 :     errno = 0;
 3886 peter_e@gmx.net          1263                 :            635 :     ERR_clear_error();
 4485 heikki.linnakangas@i     1264                 :            635 :     n = SSL_read(port->ssl, ptr, len);
                               1265                 :            635 :     err = SSL_get_error(port->ssl, n);
 3886 peter_e@gmx.net          1266   [ +  +  -  + ]:            635 :     ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
 4485 heikki.linnakangas@i     1267   [ +  +  -  -  :            635 :     switch (err)
                                           -  +  - ]
                               1268                 :                :     {
                               1269                 :            354 :         case SSL_ERROR_NONE:
                               1270                 :                :             /* a-ok */
 4492                          1271                 :            354 :             break;
 4485                          1272                 :            263 :         case SSL_ERROR_WANT_READ:
 4306                          1273                 :            263 :             *waitfor = WL_SOCKET_READABLE;
                               1274                 :            263 :             errno = EWOULDBLOCK;
                               1275                 :            263 :             n = -1;
                               1276                 :            263 :             break;
 4485 heikki.linnakangas@i     1277                 :UBC           0 :         case SSL_ERROR_WANT_WRITE:
 4306                          1278                 :              0 :             *waitfor = WL_SOCKET_WRITEABLE;
                               1279                 :              0 :             errno = EWOULDBLOCK;
                               1280                 :              0 :             n = -1;
                               1281                 :              0 :             break;
 4485                          1282                 :              0 :         case SSL_ERROR_SYSCALL:
                               1283                 :                :             /* leave it to caller to ereport the value of errno */
 1083 tgl@sss.pgh.pa.us        1284   [ #  #  #  # ]:              0 :             if (n != -1 || errno == 0)
                               1285                 :                :             {
 4485 heikki.linnakangas@i     1286                 :              0 :                 errno = ECONNRESET;
                               1287                 :              0 :                 n = -1;
                               1288                 :                :             }
 4492                          1289                 :              0 :             break;
 4485                          1290                 :              0 :         case SSL_ERROR_SSL:
                               1291         [ #  # ]:              0 :             ereport(COMMERROR,
                               1292                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1293                 :                :                      errmsg("SSL error: %s", SSLerrmessage(ecode))));
                               1294                 :              0 :             errno = ECONNRESET;
                               1295                 :              0 :             n = -1;
 4492                          1296                 :              0 :             break;
 3435 heikki.linnakangas@i     1297                 :CBC          18 :         case SSL_ERROR_ZERO_RETURN:
                               1298                 :                :             /* connection was cleanly shut down by peer */
                               1299                 :             18 :             n = 0;
                               1300                 :             18 :             break;
 4492 heikki.linnakangas@i     1301                 :UBC           0 :         default:
 4485                          1302         [ #  # ]:              0 :             ereport(COMMERROR,
                               1303                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1304                 :                :                      errmsg("unrecognized SSL error code: %d",
                               1305                 :                :                             err)));
                               1306                 :              0 :             errno = ECONNRESET;
                               1307                 :              0 :             n = -1;
 4492                          1308                 :              0 :             break;
                               1309                 :                :     }
                               1310                 :                : 
 4485 heikki.linnakangas@i     1311                 :CBC         635 :     return n;
                               1312                 :                : }
                               1313                 :                : 
                               1314                 :                : ssize_t
  657 peter@eisentraut.org     1315                 :            246 : be_tls_write(Port *port, const void *ptr, size_t len, int *waitfor)
                               1316                 :                : {
                               1317                 :                :     ssize_t     n;
                               1318                 :                :     int         err;
                               1319                 :                :     unsigned long ecode;
                               1320                 :                : 
 4485 heikki.linnakangas@i     1321                 :            246 :     errno = 0;
 3886 peter_e@gmx.net          1322                 :            246 :     ERR_clear_error();
 4485 heikki.linnakangas@i     1323                 :            246 :     n = SSL_write(port->ssl, ptr, len);
                               1324                 :            246 :     err = SSL_get_error(port->ssl, n);
 3886 peter_e@gmx.net          1325   [ +  -  -  + ]:            246 :     ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
 4485 heikki.linnakangas@i     1326   [ +  -  -  -  :            246 :     switch (err)
                                           -  -  - ]
                               1327                 :                :     {
                               1328                 :            246 :         case SSL_ERROR_NONE:
                               1329                 :                :             /* a-ok */
                               1330                 :            246 :             break;
 4485 heikki.linnakangas@i     1331                 :UBC           0 :         case SSL_ERROR_WANT_READ:
 4306                          1332                 :              0 :             *waitfor = WL_SOCKET_READABLE;
                               1333                 :              0 :             errno = EWOULDBLOCK;
                               1334                 :              0 :             n = -1;
                               1335                 :              0 :             break;
 4485                          1336                 :              0 :         case SSL_ERROR_WANT_WRITE:
 4306                          1337                 :              0 :             *waitfor = WL_SOCKET_WRITEABLE;
                               1338                 :              0 :             errno = EWOULDBLOCK;
                               1339                 :              0 :             n = -1;
                               1340                 :              0 :             break;
 4485                          1341                 :              0 :         case SSL_ERROR_SYSCALL:
                               1342                 :                : 
                               1343                 :                :             /*
                               1344                 :                :              * Leave it to caller to ereport the value of errno.  However, if
                               1345                 :                :              * errno is still zero then assume it's a read EOF situation, and
                               1346                 :                :              * report ECONNRESET.  (This seems possible because SSL_write can
                               1347                 :                :              * also do reads.)
                               1348                 :                :              */
 1083 tgl@sss.pgh.pa.us        1349   [ #  #  #  # ]:              0 :             if (n != -1 || errno == 0)
                               1350                 :                :             {
 4485 heikki.linnakangas@i     1351                 :              0 :                 errno = ECONNRESET;
                               1352                 :              0 :                 n = -1;
                               1353                 :                :             }
                               1354                 :              0 :             break;
                               1355                 :              0 :         case SSL_ERROR_SSL:
                               1356         [ #  # ]:              0 :             ereport(COMMERROR,
                               1357                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1358                 :                :                      errmsg("SSL error: %s", SSLerrmessage(ecode))));
 3435                          1359                 :              0 :             errno = ECONNRESET;
                               1360                 :              0 :             n = -1;
                               1361                 :              0 :             break;
 4485                          1362                 :              0 :         case SSL_ERROR_ZERO_RETURN:
                               1363                 :                : 
                               1364                 :                :             /*
                               1365                 :                :              * the SSL connection was closed, leave it to the caller to
                               1366                 :                :              * ereport it
                               1367                 :                :              */
                               1368                 :              0 :             errno = ECONNRESET;
                               1369                 :              0 :             n = -1;
                               1370                 :              0 :             break;
                               1371                 :              0 :         default:
                               1372         [ #  # ]:              0 :             ereport(COMMERROR,
                               1373                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1374                 :                :                      errmsg("unrecognized SSL error code: %d",
                               1375                 :                :                             err)));
                               1376                 :              0 :             errno = ECONNRESET;
                               1377                 :              0 :             n = -1;
                               1378                 :              0 :             break;
                               1379                 :                :     }
                               1380                 :                : 
 4485 heikki.linnakangas@i     1381                 :CBC         246 :     return n;
                               1382                 :                : }
                               1383                 :                : 
                               1384                 :                : /* ------------------------------------------------------------ */
                               1385                 :                : /*                      Internal functions                      */
                               1386                 :                : /* ------------------------------------------------------------ */
                               1387                 :                : 
                               1388                 :                : /*
                               1389                 :                :  * Private substitute BIO: this does the sending and receiving using send() and
                               1390                 :                :  * recv() instead. This is so that we can enable and disable interrupts
                               1391                 :                :  * just while calling recv(). We cannot have interrupts occurring while
                               1392                 :                :  * the bulk of OpenSSL runs, because it uses malloc() and possibly other
                               1393                 :                :  * non-reentrant libc facilities. We also need to call send() and recv()
                               1394                 :                :  * directly so it gets passed through the socket/signals layer on Win32.
                               1395                 :                :  *
                               1396                 :                :  * These functions are closely modelled on the standard socket BIO in OpenSSL;
                               1397                 :                :  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
                               1398                 :                :  */
                               1399                 :                : 
                               1400                 :                : static BIO_METHOD *port_bio_method_ptr = NULL;
                               1401                 :                : 
                               1402                 :                : static int
  778 dgustafsson@postgres     1403                 :           3038 : port_bio_read(BIO *h, char *buf, int size)
                               1404                 :                : {
 4485 heikki.linnakangas@i     1405                 :           3038 :     int         res = 0;
  778 dgustafsson@postgres     1406                 :           3038 :     Port       *port = (Port *) BIO_get_data(h);
                               1407                 :                : 
 4485 heikki.linnakangas@i     1408         [ +  - ]:           3038 :     if (buf != NULL)
                               1409                 :                :     {
  136 peter@eisentraut.org     1410                 :GNC        3038 :         res = (int) secure_raw_read(port, buf, size);
 4485 heikki.linnakangas@i     1411                 :CBC        3038 :         BIO_clear_retry_flags(h);
  778 dgustafsson@postgres     1412                 :           3038 :         port->last_read_was_eof = res == 0;
 4485 heikki.linnakangas@i     1413         [ +  + ]:           3038 :         if (res <= 0)
                               1414                 :                :         {
                               1415                 :                :             /* If we were interrupted, tell caller to retry */
 4316 andres@anarazel.de       1416   [ +  -  +  +  :            704 :             if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
                                              -  + ]
                               1417                 :                :             {
 4485 heikki.linnakangas@i     1418                 :            699 :                 BIO_set_retry_read(h);
                               1419                 :                :             }
                               1420                 :                :         }
                               1421                 :                :     }
                               1422                 :                : 
                               1423                 :           3038 :     return res;
                               1424                 :                : }
                               1425                 :                : 
                               1426                 :                : static int
  778 dgustafsson@postgres     1427                 :            717 : port_bio_write(BIO *h, const char *buf, int size)
                               1428                 :                : {
 4485 heikki.linnakangas@i     1429                 :            717 :     int         res = 0;
                               1430                 :                : 
  136 peter@eisentraut.org     1431                 :GNC         717 :     res = (int) secure_raw_write(((Port *) BIO_get_data(h)), buf, size);
 4485 heikki.linnakangas@i     1432                 :CBC         717 :     BIO_clear_retry_flags(h);
                               1433         [ -  + ]:            717 :     if (res <= 0)
                               1434                 :                :     {
                               1435                 :                :         /* If we were interrupted, tell caller to retry */
 4316 andres@anarazel.de       1436   [ #  #  #  #  :UBC           0 :         if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
                                              #  # ]
                               1437                 :                :         {
 4485 heikki.linnakangas@i     1438                 :              0 :             BIO_set_retry_write(h);
                               1439                 :                :         }
                               1440                 :                :     }
                               1441                 :                : 
 4485 heikki.linnakangas@i     1442                 :CBC         717 :     return res;
                               1443                 :                : }
                               1444                 :                : 
                               1445                 :                : static long
  778 dgustafsson@postgres     1446                 :            814 : port_bio_ctrl(BIO *h, int cmd, long num, void *ptr)
                               1447                 :                : {
                               1448                 :                :     long        res;
                               1449                 :            814 :     Port       *port = (Port *) BIO_get_data(h);
                               1450                 :                : 
                               1451      [ +  +  + ]:            814 :     switch (cmd)
                               1452                 :                :     {
                               1453                 :              5 :         case BIO_CTRL_EOF:
                               1454                 :                : 
                               1455                 :                :             /*
                               1456                 :                :              * This should not be needed. port_bio_read already has a way to
                               1457                 :                :              * signal EOF to OpenSSL. However, OpenSSL made an undocumented,
                               1458                 :                :              * backwards-incompatible change and now expects EOF via BIO_ctrl.
                               1459                 :                :              * See https://github.com/openssl/openssl/issues/8208
                               1460                 :                :              */
                               1461                 :              5 :             res = port->last_read_was_eof;
                               1462                 :              5 :             break;
                               1463                 :            471 :         case BIO_CTRL_FLUSH:
                               1464                 :                :             /* libssl expects all BIOs to support BIO_flush. */
                               1465                 :            471 :             res = 1;
                               1466                 :            471 :             break;
                               1467                 :            338 :         default:
                               1468                 :            338 :             res = 0;
                               1469                 :            338 :             break;
                               1470                 :                :     }
                               1471                 :                : 
                               1472                 :            814 :     return res;
                               1473                 :                : }
                               1474                 :                : 
                               1475                 :                : static BIO_METHOD *
                               1476                 :            169 : port_bio_method(void)
                               1477                 :                : {
                               1478         [ +  - ]:            169 :     if (!port_bio_method_ptr)
                               1479                 :                :     {
                               1480                 :                :         int         my_bio_index;
                               1481                 :                : 
 3726 heikki.linnakangas@i     1482                 :            169 :         my_bio_index = BIO_get_new_index();
                               1483         [ -  + ]:            169 :         if (my_bio_index == -1)
 3726 heikki.linnakangas@i     1484                 :UBC           0 :             return NULL;
  778 dgustafsson@postgres     1485                 :CBC         169 :         my_bio_index |= BIO_TYPE_SOURCE_SINK;
                               1486                 :            169 :         port_bio_method_ptr = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
                               1487         [ -  + ]:            169 :         if (!port_bio_method_ptr)
 3726 heikki.linnakangas@i     1488                 :UBC           0 :             return NULL;
  778 dgustafsson@postgres     1489   [ +  -  +  - ]:CBC         338 :         if (!BIO_meth_set_write(port_bio_method_ptr, port_bio_write) ||
                               1490         [ -  + ]:            338 :             !BIO_meth_set_read(port_bio_method_ptr, port_bio_read) ||
                               1491                 :            169 :             !BIO_meth_set_ctrl(port_bio_method_ptr, port_bio_ctrl))
                               1492                 :                :         {
  778 dgustafsson@postgres     1493                 :UBC           0 :             BIO_meth_free(port_bio_method_ptr);
                               1494                 :              0 :             port_bio_method_ptr = NULL;
 3726 heikki.linnakangas@i     1495                 :              0 :             return NULL;
                               1496                 :                :         }
                               1497                 :                :     }
  778 dgustafsson@postgres     1498                 :CBC         169 :     return port_bio_method_ptr;
                               1499                 :                : }
                               1500                 :                : 
                               1501                 :                : static int
                               1502                 :            169 : ssl_set_port_bio(Port *port)
                               1503                 :                : {
                               1504                 :                :     BIO        *bio;
                               1505                 :                :     BIO_METHOD *bio_method;
                               1506                 :                : 
                               1507                 :            169 :     bio_method = port_bio_method();
 3726 heikki.linnakangas@i     1508         [ -  + ]:            169 :     if (bio_method == NULL)
  778 dgustafsson@postgres     1509                 :UBC           0 :         return 0;
                               1510                 :                : 
  778 dgustafsson@postgres     1511                 :CBC         169 :     bio = BIO_new(bio_method);
 4485 heikki.linnakangas@i     1512         [ -  + ]:            169 :     if (bio == NULL)
  778 dgustafsson@postgres     1513                 :UBC           0 :         return 0;
                               1514                 :                : 
  778 dgustafsson@postgres     1515                 :CBC         169 :     BIO_set_data(bio, port);
                               1516                 :            169 :     BIO_set_init(bio, 1);
                               1517                 :                : 
 4485 heikki.linnakangas@i     1518                 :            169 :     SSL_set_bio(port->ssl, bio, bio);
  778 dgustafsson@postgres     1519                 :            169 :     return 1;
                               1520                 :                : }
                               1521                 :                : 
                               1522                 :                : /*
                               1523                 :                :  *  Load precomputed DH parameters.
                               1524                 :                :  *
                               1525                 :                :  *  To prevent "downgrade" attacks, we perform a number of checks
                               1526                 :                :  *  to verify that the DBA-generated DH parameters file contains
                               1527                 :                :  *  what we expect it to contain.
                               1528                 :                :  */
                               1529                 :                : static DH  *
 3407 heikki.linnakangas@i     1530                 :UBC           0 : load_dh_file(char *filename, bool isServerStart)
                               1531                 :                : {
                               1532                 :                :     FILE       *fp;
 4485                          1533                 :              0 :     DH         *dh = NULL;
                               1534                 :                :     int         codes;
                               1535                 :                : 
                               1536                 :                :     /* attempt to open file.  It's not an error if it doesn't exist. */
 3407                          1537         [ #  # ]:              0 :     if ((fp = AllocateFile(filename, "r")) == NULL)
                               1538                 :                :     {
                               1539   [ #  #  #  # ]:              0 :         ereport(isServerStart ? FATAL : LOG,
                               1540                 :                :                 (errcode_for_file_access(),
                               1541                 :                :                  errmsg("could not open DH parameters file \"%s\": %m",
                               1542                 :                :                         filename)));
 4485                          1543                 :              0 :         return NULL;
                               1544                 :                :     }
                               1545                 :                : 
                               1546                 :              0 :     dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
 3407                          1547                 :              0 :     FreeFile(fp);
                               1548                 :                : 
                               1549         [ #  # ]:              0 :     if (dh == NULL)
                               1550                 :                :     {
                               1551   [ #  #  #  # ]:              0 :         ereport(isServerStart ? FATAL : LOG,
                               1552                 :                :                 (errcode(ERRCODE_CONFIG_FILE_ERROR),
                               1553                 :                :                  errmsg("could not load DH parameters file: %s",
                               1554                 :                :                         SSLerrmessage(ERR_get_error()))));
                               1555                 :              0 :         return NULL;
                               1556                 :                :     }
                               1557                 :                : 
                               1558                 :                :     /* make sure the DH parameters are usable */
                               1559         [ #  # ]:              0 :     if (DH_check(dh, &codes) == 0)
                               1560                 :                :     {
                               1561   [ #  #  #  # ]:              0 :         ereport(isServerStart ? FATAL : LOG,
                               1562                 :                :                 (errcode(ERRCODE_CONFIG_FILE_ERROR),
                               1563                 :                :                  errmsg("invalid DH parameters: %s",
                               1564                 :                :                         SSLerrmessage(ERR_get_error()))));
 2079 tgl@sss.pgh.pa.us        1565                 :              0 :         DH_free(dh);
 3407 heikki.linnakangas@i     1566                 :              0 :         return NULL;
                               1567                 :                :     }
                               1568         [ #  # ]:              0 :     if (codes & DH_CHECK_P_NOT_PRIME)
                               1569                 :                :     {
                               1570   [ #  #  #  # ]:              0 :         ereport(isServerStart ? FATAL : LOG,
                               1571                 :                :                 (errcode(ERRCODE_CONFIG_FILE_ERROR),
                               1572                 :                :                  errmsg("invalid DH parameters: p is not prime")));
 2079 tgl@sss.pgh.pa.us        1573                 :              0 :         DH_free(dh);
 3407 heikki.linnakangas@i     1574                 :              0 :         return NULL;
                               1575                 :                :     }
                               1576         [ #  # ]:              0 :     if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
                               1577         [ #  # ]:              0 :         (codes & DH_CHECK_P_NOT_SAFE_PRIME))
                               1578                 :                :     {
                               1579   [ #  #  #  # ]:              0 :         ereport(isServerStart ? FATAL : LOG,
                               1580                 :                :                 (errcode(ERRCODE_CONFIG_FILE_ERROR),
                               1581                 :                :                  errmsg("invalid DH parameters: neither suitable generator or safe prime")));
 2079 tgl@sss.pgh.pa.us        1582                 :              0 :         DH_free(dh);
 3407 heikki.linnakangas@i     1583                 :              0 :         return NULL;
                               1584                 :                :     }
                               1585                 :                : 
 4485                          1586                 :              0 :     return dh;
                               1587                 :                : }
                               1588                 :                : 
                               1589                 :                : /*
                               1590                 :                :  *  Passphrase collection callback using ssl_passphrase_command
                               1591                 :                :  */
                               1592                 :                : static int
 3197 peter_e@gmx.net          1593                 :CBC          20 : ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata)
                               1594                 :                : {
                               1595                 :                :     /* same prompt as OpenSSL uses internally */
                               1596                 :             20 :     const char *prompt = "Enter PEM pass phrase:";
  255 dgustafsson@postgres     1597                 :             20 :     const char *cmd = userdata;
                               1598                 :                : 
 3197 peter_e@gmx.net          1599         [ -  + ]:             20 :     Assert(rwflag == 0);
                               1600                 :                : 
  255 dgustafsson@postgres     1601                 :             20 :     return run_ssl_passphrase_command(cmd, prompt, ssl_is_server_start, buf, size);
                               1602                 :                : }
                               1603                 :                : 
                               1604                 :                : /*
                               1605                 :                :  * Dummy passphrase callback
                               1606                 :                :  *
                               1607                 :                :  * If OpenSSL is told to use a passphrase-protected server key, by default
                               1608                 :                :  * it will issue a prompt on /dev/tty and try to read a key from there.
                               1609                 :                :  * That's no good during a postmaster SIGHUP cycle, not to mention SSL context
                               1610                 :                :  * reload in an EXEC_BACKEND postmaster child.  So override it with this dummy
                               1611                 :                :  * function that just returns an empty passphrase, guaranteeing failure.
                               1612                 :                :  */
                               1613                 :                : static int
 3197 peter_e@gmx.net          1614                 :              2 : dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
                               1615                 :                : {
                               1616                 :                :     /* Set flag to change the error message we'll report */
                               1617                 :              2 :     dummy_ssl_passwd_cb_called = true;
                               1618                 :                :     /* And return empty string */
 3616 tgl@sss.pgh.pa.us        1619         [ -  + ]:              2 :     Assert(size > 0);
                               1620                 :              2 :     buf[0] = '\0';
                               1621                 :              2 :     return 0;
                               1622                 :                : }
                               1623                 :                : 
                               1624                 :                : /*
                               1625                 :                :  * Examines the provided certificate name, and if it's too long to log or
                               1626                 :                :  * contains unprintable ASCII, escapes and truncates it. The return value is
                               1627                 :                :  * always a new palloc'd string. (The input string is still modified in place,
                               1628                 :                :  * for ease of implementation.)
                               1629                 :                :  */
                               1630                 :                : static char *
 1537 peter@eisentraut.org     1631                 :             16 : prepare_cert_name(char *name)
                               1632                 :                : {
 1597                          1633                 :             16 :     size_t      namelen = strlen(name);
 1537                          1634                 :             16 :     char       *truncated = name;
                               1635                 :                : 
                               1636                 :                :     /*
                               1637                 :                :      * Common Names are 64 chars max, so for a common case where the CN is the
                               1638                 :                :      * last field, we can still print the longest possible CN with a
                               1639                 :                :      * 7-character prefix (".../CN=[64 chars]"), for a reasonable limit of 71
                               1640                 :                :      * characters.
                               1641                 :                :      */
                               1642                 :                : #define MAXLEN 71
                               1643                 :                : 
                               1644         [ +  + ]:             16 :     if (namelen > MAXLEN)
                               1645                 :                :     {
                               1646                 :                :         /*
                               1647                 :                :          * Keep the end of the name, not the beginning, since the most
                               1648                 :                :          * specific field is likely to give users the most information.
                               1649                 :                :          */
                               1650                 :              1 :         truncated = name + namelen - MAXLEN;
                               1651                 :              1 :         truncated[0] = truncated[1] = truncated[2] = '.';
                               1652                 :              1 :         namelen = MAXLEN;
                               1653                 :                :     }
                               1654                 :                : 
                               1655                 :                : #undef MAXLEN
                               1656                 :                : 
                               1657                 :             16 :     return pg_clean_ascii(truncated, 0);
                               1658                 :                : }
                               1659                 :                : 
                               1660                 :                : /*
                               1661                 :                :  *  Certificate verification callback
                               1662                 :                :  *
                               1663                 :                :  *  This callback allows us to examine intermediate problems during
                               1664                 :                :  *  verification, for later logging.
                               1665                 :                :  *
                               1666                 :                :  *  This callback also allows us to override the default acceptance
                               1667                 :                :  *  criteria (e.g., accepting self-signed or expired certs), but
                               1668                 :                :  *  for now we accept the default checks.
                               1669                 :                :  */
                               1670                 :                : static int
 4485 heikki.linnakangas@i     1671                 :            101 : verify_cb(int ok, X509_STORE_CTX *ctx)
                               1672                 :                : {
                               1673                 :                :     int         depth;
                               1674                 :                :     int         errcode;
                               1675                 :                :     const char *errstring;
                               1676                 :                :     StringInfoData str;
                               1677                 :                :     X509       *cert;
                               1678                 :                :     SSL        *ssl;
                               1679                 :                :     struct CallbackErr *cb_err;
                               1680                 :                : 
 1597 peter@eisentraut.org     1681         [ +  + ]:            101 :     if (ok)
                               1682                 :                :     {
                               1683                 :                :         /* Nothing to do for the successful case. */
                               1684                 :             93 :         return ok;
                               1685                 :                :     }
                               1686                 :                : 
                               1687                 :                :     /* Pull all the information we have on the verification failure. */
                               1688                 :              8 :     depth = X509_STORE_CTX_get_error_depth(ctx);
                               1689                 :              8 :     errcode = X509_STORE_CTX_get_error(ctx);
                               1690                 :              8 :     errstring = X509_verify_cert_error_string(errcode);
                               1691                 :                : 
                               1692                 :                :     /*
                               1693                 :                :      * Extract the current SSL and CallbackErr object to use for passing error
                               1694                 :                :      * detail back from the callback.
                               1695                 :                :      */
  381 dgustafsson@postgres     1696                 :              8 :     ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
                               1697                 :              8 :     cb_err = (struct CallbackErr *) SSL_get_ex_data(ssl, 0);
                               1698                 :                : 
 1597 peter@eisentraut.org     1699                 :              8 :     initStringInfo(&str);
                               1700                 :              8 :     appendStringInfo(&str,
                               1701                 :              8 :                      _("Client certificate verification failed at depth %d: %s."),
                               1702                 :                :                      depth, errstring);
                               1703                 :                : 
                               1704                 :              8 :     cert = X509_STORE_CTX_get_current_cert(ctx);
                               1705         [ +  - ]:              8 :     if (cert)
                               1706                 :                :     {
                               1707                 :                :         char       *subject,
                               1708                 :                :                    *issuer;
                               1709                 :                :         char       *sub_prepared,
                               1710                 :                :                    *iss_prepared;
                               1711                 :                :         char       *serialno;
                               1712                 :                :         ASN1_INTEGER *sn;
                               1713                 :                :         BIGNUM     *b;
                               1714                 :                : 
                               1715                 :                :         /*
                               1716                 :                :          * Get the Subject and Issuer for logging, but don't let maliciously
                               1717                 :                :          * huge certs flood the logs, and don't reflect non-ASCII bytes into
                               1718                 :                :          * it either.
                               1719                 :                :          */
                               1720                 :              8 :         subject = X509_NAME_to_cstring(X509_get_subject_name(cert));
 1537                          1721                 :              8 :         sub_prepared = prepare_cert_name(subject);
                               1722                 :              8 :         pfree(subject);
                               1723                 :                : 
 1597                          1724                 :              8 :         issuer = X509_NAME_to_cstring(X509_get_issuer_name(cert));
 1537                          1725                 :              8 :         iss_prepared = prepare_cert_name(issuer);
                               1726                 :              8 :         pfree(issuer);
                               1727                 :                : 
                               1728                 :                :         /*
                               1729                 :                :          * Pull the serial number, too, in case a Subject is still ambiguous.
                               1730                 :                :          * This mirrors be_tls_get_peer_serial().
                               1731                 :                :          */
 1597                          1732                 :              8 :         sn = X509_get_serialNumber(cert);
                               1733                 :              8 :         b = ASN1_INTEGER_to_BN(sn, NULL);
                               1734                 :              8 :         serialno = BN_bn2dec(b);
                               1735                 :                : 
                               1736                 :              8 :         appendStringInfoChar(&str, '\n');
                               1737         [ -  + ]:              8 :         appendStringInfo(&str,
                               1738                 :              8 :                          _("Failed certificate data (unverified): subject \"%s\", serial number %s, issuer \"%s\"."),
 1537 peter@eisentraut.org     1739                 :UBC           0 :                          sub_prepared, serialno ? serialno : _("unknown"),
                               1740                 :                :                          iss_prepared);
                               1741                 :                : 
 1597 peter@eisentraut.org     1742                 :CBC           8 :         BN_free(b);
                               1743                 :              8 :         OPENSSL_free(serialno);
 1537                          1744                 :              8 :         pfree(iss_prepared);
                               1745                 :              8 :         pfree(sub_prepared);
                               1746                 :                :     }
                               1747                 :                : 
                               1748                 :                :     /* Store our detail message to be logged later. */
  381 dgustafsson@postgres     1749                 :              8 :     cb_err->cert_errdetail = str.data;
                               1750                 :                : 
 4485 heikki.linnakangas@i     1751                 :              8 :     return ok;
                               1752                 :                : }
                               1753                 :                : 
                               1754                 :                : /*
                               1755                 :                :  *  This callback is used to copy SSL information messages
                               1756                 :                :  *  into the PostgreSQL log.
                               1757                 :                :  */
                               1758                 :                : static void
                               1759                 :           3898 : info_cb(const SSL *ssl, int type, int args)
                               1760                 :                : {
                               1761                 :                :     const char *desc;
                               1762                 :                : 
 2136 michael@paquier.xyz      1763                 :           3898 :     desc = SSL_state_string_long(ssl);
                               1764                 :                : 
 4485 heikki.linnakangas@i     1765   [ +  +  +  +  :           3898 :     switch (type)
                                        -  -  +  +  
                                                 - ]
                               1766                 :                :     {
                               1767                 :            169 :         case SSL_CB_HANDSHAKE_START:
                               1768         [ -  + ]:            169 :             ereport(DEBUG4,
                               1769                 :                :                     (errmsg_internal("SSL: handshake start: \"%s\"", desc)));
 4492                          1770                 :            169 :             break;
 4485                          1771                 :            137 :         case SSL_CB_HANDSHAKE_DONE:
                               1772         [ -  + ]:            137 :             ereport(DEBUG4,
                               1773                 :                :                     (errmsg_internal("SSL: handshake done: \"%s\"", desc)));
 4492                          1774                 :            137 :             break;
 4485                          1775                 :           2800 :         case SSL_CB_ACCEPT_LOOP:
                               1776         [ -  + ]:           2800 :             ereport(DEBUG4,
                               1777                 :                :                     (errmsg_internal("SSL: accept loop: \"%s\"", desc)));
 4492                          1778                 :           2800 :             break;
 4485                          1779                 :            605 :         case SSL_CB_ACCEPT_EXIT:
                               1780         [ -  + ]:            605 :             ereport(DEBUG4,
                               1781                 :                :                     (errmsg_internal("SSL: accept exit (%d): \"%s\"", args, desc)));
                               1782                 :            605 :             break;
 4485 heikki.linnakangas@i     1783                 :UBC           0 :         case SSL_CB_CONNECT_LOOP:
                               1784         [ #  # ]:              0 :             ereport(DEBUG4,
                               1785                 :                :                     (errmsg_internal("SSL: connect loop: \"%s\"", desc)));
                               1786                 :              0 :             break;
                               1787                 :              0 :         case SSL_CB_CONNECT_EXIT:
                               1788         [ #  # ]:              0 :             ereport(DEBUG4,
                               1789                 :                :                     (errmsg_internal("SSL: connect exit (%d): \"%s\"", args, desc)));
                               1790                 :              0 :             break;
 4485 heikki.linnakangas@i     1791                 :CBC          30 :         case SSL_CB_READ_ALERT:
                               1792         [ -  + ]:             30 :             ereport(DEBUG4,
                               1793                 :                :                     (errmsg_internal("SSL: read alert (0x%04x): \"%s\"", args, desc)));
                               1794                 :             30 :             break;
                               1795                 :            157 :         case SSL_CB_WRITE_ALERT:
                               1796         [ -  + ]:            157 :             ereport(DEBUG4,
                               1797                 :                :                     (errmsg_internal("SSL: write alert (0x%04x): \"%s\"", args, desc)));
 4492                          1798                 :            157 :             break;
                               1799                 :                :     }
 4485                          1800                 :           3898 : }
                               1801                 :                : 
                               1802                 :                : /* See pqcomm.h comments on OpenSSL implementation of ALPN (RFC 7301) */
                               1803                 :                : static const unsigned char alpn_protos[] = PG_ALPN_PROTOCOL_VECTOR;
                               1804                 :                : 
                               1805                 :                : /*
                               1806                 :                :  * Server callback for ALPN negotiation. We use the standard "helper" function
                               1807                 :                :  * even though currently we only accept one value.
                               1808                 :                :  */
                               1809                 :                : static int
  964                          1810                 :            312 : alpn_cb(SSL *ssl,
                               1811                 :                :         const unsigned char **out,
                               1812                 :                :         unsigned char *outlen,
                               1813                 :                :         const unsigned char *in,
                               1814                 :                :         unsigned int inlen,
                               1815                 :                :         void *userdata)
                               1816                 :                : {
                               1817                 :                :     /*
                               1818                 :                :      * Why does OpenSSL provide a helper function that requires a nonconst
                               1819                 :                :      * vector when the callback is declared to take a const vector? What are
                               1820                 :                :      * we to do with that?
                               1821                 :                :      */
                               1822                 :                :     int         retval;
                               1823                 :                : 
                               1824         [ -  + ]:            312 :     Assert(userdata != NULL);
                               1825         [ -  + ]:            312 :     Assert(out != NULL);
                               1826         [ -  + ]:            312 :     Assert(outlen != NULL);
                               1827         [ -  + ]:            312 :     Assert(in != NULL);
                               1828                 :                : 
   52 peter@eisentraut.org     1829                 :GNC         312 :     retval = SSL_select_next_proto(unconstify(unsigned char **, out), outlen,
                               1830                 :                :                                    alpn_protos, sizeof(alpn_protos),
                               1831                 :                :                                    in, inlen);
  964 heikki.linnakangas@i     1832   [ +  -  +  -  :CBC         312 :     if (*out == NULL || *outlen > sizeof(alpn_protos) || *outlen <= 0)
                                              -  + ]
  964 heikki.linnakangas@i     1833                 :UBC           0 :         return SSL_TLSEXT_ERR_NOACK;    /* can't happen */
                               1834                 :                : 
  964 heikki.linnakangas@i     1835         [ +  - ]:CBC         312 :     if (retval == OPENSSL_NPN_NEGOTIATED)
                               1836                 :            312 :         return SSL_TLSEXT_ERR_OK;
                               1837                 :                :     else
                               1838                 :                :     {
                               1839                 :                :         /*
                               1840                 :                :          * The client doesn't support our protocol.  Reject the connection
                               1841                 :                :          * with TLS "no_application_protocol" alert, per RFC 7301.
                               1842                 :                :          */
  943 heikki.linnakangas@i     1843                 :UBC           0 :         return SSL_TLSEXT_ERR_ALERT_FATAL;
                               1844                 :                :     }
                               1845                 :                : }
                               1846                 :                : 
                               1847                 :                : #ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
                               1848                 :                : /*
                               1849                 :                :  * ssl_update_ssl
                               1850                 :                :  *
                               1851                 :                :  * Replace certificate/key and CA in an SSL object to match the, via the SNI
                               1852                 :                :  * extension, selected host configuration for the connection.  The SSL_CTX
                               1853                 :                :  * object to use should be passed in as ctx.  This function will update the
                               1854                 :                :  * SSL object in-place.
                               1855                 :                :  */
                               1856                 :                : static bool
  255 dgustafsson@postgres     1857                 :CBC         312 : ssl_update_ssl(SSL *ssl, HostsLine *host_config)
                               1858                 :                : {
                               1859                 :            312 :     SSL_CTX    *ctx = host_config->ssl_ctx;
                               1860                 :                : 
                               1861                 :                :     X509       *cert;
                               1862                 :                :     EVP_PKEY   *key;
                               1863                 :                : 
                               1864                 :                :     STACK_OF(X509) * chain;
                               1865                 :                : 
                               1866         [ -  + ]:            312 :     Assert(ctx != NULL);
                               1867                 :                :     /*-
                               1868                 :                :      * Make use of the already-loaded certificate chain and key. At first
                               1869                 :                :      * glance, SSL_set_SSL_CTX() looks like the easiest way to do this, but
                               1870                 :                :      * beware -- it has very odd behavior:
                               1871                 :                :      *
                               1872                 :                :      *     https://github.com/openssl/openssl/issues/6109
                               1873                 :                :      */
                               1874                 :            312 :     cert = SSL_CTX_get0_certificate(ctx);
                               1875                 :            312 :     key = SSL_CTX_get0_privatekey(ctx);
                               1876                 :                : 
                               1877   [ +  -  -  + ]:            312 :     Assert(cert && key);
                               1878                 :                : 
                               1879         [ +  - ]:            312 :     if (!SSL_CTX_get0_chain_certs(ctx, &chain)
                               1880         [ +  - ]:            312 :         || !SSL_use_cert_and_key(ssl, cert, key, chain, 1 /* override */ )
                               1881         [ -  + ]:            312 :         || !SSL_check_private_key(ssl))
                               1882                 :                :     {
                               1883                 :                :         /*
                               1884                 :                :          * This shouldn't really be possible, since the inputs came from a
                               1885                 :                :          * SSL_CTX that was already populated by OpenSSL.
                               1886                 :                :          */
  255 dgustafsson@postgres     1887         [ #  # ]:UBC           0 :         ereport(COMMERROR,
                               1888                 :                :                 errcode(ERRCODE_INTERNAL_ERROR),
                               1889                 :                :                 errmsg_internal("could not update certificate chain: %s",
                               1890                 :                :                                 SSLerrmessage(ERR_get_error())));
                               1891                 :              0 :         return false;
                               1892                 :                :     }
                               1893                 :                : 
  255 dgustafsson@postgres     1894   [ +  +  +  + ]:CBC         312 :     if (host_config->ssl_ca && host_config->ssl_ca[0])
                               1895                 :                :     {
                               1896                 :                :         /*
                               1897                 :                :          * Copy the trust store and list of roots over from the SSL_CTX.
                               1898                 :                :          */
                               1899                 :            292 :         X509_STORE *ca_store = SSL_CTX_get_cert_store(ctx);
                               1900                 :                : 
                               1901                 :                :         STACK_OF(X509_NAME) * roots;
                               1902                 :                : 
                               1903                 :                :         /*
                               1904                 :                :          * The trust store appears to be the only setting that this function
                               1905                 :                :          * can't override via the (SSL *) pointer directly. Instead, share it
                               1906                 :                :          * with the active SSL_CTX (this should always be SSL_context).
                               1907                 :                :          */
                               1908         [ -  + ]:            292 :         Assert(SSL_context == SSL_get_SSL_CTX(ssl));
                               1909                 :            292 :         SSL_CTX_set1_cert_store(SSL_context, ca_store);
                               1910                 :                : 
                               1911                 :                :         /*
                               1912                 :                :          * SSL_set_client_CA_list() will take ownership of its argument, so we
                               1913                 :                :          * need to duplicate it.
                               1914                 :                :          */
                               1915         [ +  - ]:            292 :         if ((roots = SSL_CTX_get_client_CA_list(ctx)) == NULL
                               1916         [ -  + ]:            292 :             || (roots = SSL_dup_CA_list(roots)) == NULL)
                               1917                 :                :         {
  255 dgustafsson@postgres     1918         [ #  # ]:UBC           0 :             ereport(COMMERROR,
                               1919                 :                :                     errcode(ERRCODE_INTERNAL_ERROR),
                               1920                 :                :                     errmsg_internal("could not duplicate SSL_CTX CA list: %s",
                               1921                 :                :                                     SSLerrmessage(ERR_get_error())));
                               1922                 :              0 :             return false;
                               1923                 :                :         }
                               1924                 :                : 
  255 dgustafsson@postgres     1925                 :CBC         292 :         SSL_set_client_CA_list(ssl, roots);
                               1926                 :                : 
                               1927                 :                :         /*
                               1928                 :                :          * Always ask for SSL client cert, but don't fail if it's not
                               1929                 :                :          * presented.  We might fail such connections later, depending on what
                               1930                 :                :          * we find in pg_hba.conf.
                               1931                 :                :          */
                               1932                 :            292 :         SSL_set_verify(ssl,
                               1933                 :                :                        (SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE),
                               1934                 :                :                        verify_cb);
                               1935                 :                : 
                               1936                 :            292 :         ssl_loaded_verify_locations = true;
                               1937                 :                :     }
                               1938                 :                : 
                               1939                 :            312 :     return true;
                               1940                 :                : }
                               1941                 :                : 
                               1942                 :                : /*
                               1943                 :                :  * sni_clienthello_cb
                               1944                 :                :  *
                               1945                 :                :  * Callback for extracting the servername extension from the TLS handshake
                               1946                 :                :  * during ClientHello.  There is a callback in OpenSSL for the servername
                               1947                 :                :  * specifically but OpenSSL themselves advice against using it as it is more
                               1948                 :                :  * dependent on ordering for execution.
                               1949                 :                :  */
                               1950                 :                : static int
                               1951                 :            319 : sni_clienthello_cb(SSL *ssl, int *al, void *arg)
                               1952                 :                : {
                               1953                 :                :     const char *tlsext_hostname;
                               1954                 :                :     const unsigned char *tlsext;
                               1955                 :                :     size_t      left,
                               1956                 :                :                 len;
                               1957                 :            319 :     HostsLine  *install_config = NULL;
                               1958                 :                : 
   53                          1959         [ +  + ]:            319 :     if (!SSL_hosts->sni_enabled)
                               1960                 :                :     {
                               1961                 :                :         /* A configuration loaded without SNI must have a default host */
  255                          1962                 :            248 :         install_config = SSL_hosts->default_host;
   53                          1963         [ -  + ]:            248 :         Assert(install_config != NULL);
  255                          1964                 :            248 :         goto found;
                               1965                 :                :     }
                               1966                 :                : 
                               1967         [ +  + ]:             71 :     if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &tlsext, &left))
                               1968                 :                :     {
                               1969         [ -  + ]:             67 :         if (left <= 2)
                               1970                 :                :         {
  255 dgustafsson@postgres     1971                 :UBC           0 :             *al = SSL_AD_DECODE_ERROR;
                               1972                 :              0 :             return 0;
                               1973                 :                :         }
  255 dgustafsson@postgres     1974                 :CBC          67 :         len = (*(tlsext++) << 8);
                               1975                 :             67 :         len += *(tlsext)++;
                               1976         [ -  + ]:             67 :         if (len + 2 != left)
                               1977                 :                :         {
  255 dgustafsson@postgres     1978                 :UBC           0 :             *al = SSL_AD_DECODE_ERROR;
                               1979                 :              0 :             return 0;
                               1980                 :                :         }
                               1981                 :                : 
  255 dgustafsson@postgres     1982                 :CBC          67 :         left = len;
                               1983                 :                : 
                               1984   [ +  -  -  + ]:             67 :         if (left == 0 || *tlsext++ != TLSEXT_NAMETYPE_host_name)
                               1985                 :                :         {
  255 dgustafsson@postgres     1986                 :UBC           0 :             *al = SSL_AD_DECODE_ERROR;
                               1987                 :              0 :             return 0;
                               1988                 :                :         }
                               1989                 :                : 
  255 dgustafsson@postgres     1990                 :CBC          67 :         left--;
                               1991                 :                : 
                               1992                 :                :         /*
                               1993                 :                :          * Now we can finally pull out the byte array with the actual
                               1994                 :                :          * hostname.
                               1995                 :                :          */
                               1996         [ -  + ]:             67 :         if (left <= 2)
                               1997                 :                :         {
  255 dgustafsson@postgres     1998                 :UBC           0 :             *al = SSL_AD_DECODE_ERROR;
                               1999                 :              0 :             return 0;
                               2000                 :                :         }
  255 dgustafsson@postgres     2001                 :CBC          67 :         len = (*(tlsext++) << 8);
                               2002                 :             67 :         len += *(tlsext++);
                               2003         [ -  + ]:             67 :         if (len + 2 > left)
                               2004                 :                :         {
  255 dgustafsson@postgres     2005                 :UBC           0 :             *al = SSL_AD_DECODE_ERROR;
                               2006                 :              0 :             return 0;
                               2007                 :                :         }
  255 dgustafsson@postgres     2008                 :CBC          67 :         left = len;
                               2009                 :             67 :         tlsext_hostname = (const char *) tlsext;
                               2010                 :                : 
                               2011                 :                :         /*
                               2012                 :                :          * We have a requested hostname from the client, match against all
                               2013                 :                :          * entries in the pg_hosts configuration and attempt to find a match.
                               2014                 :                :          * Matching is done case insensitive as per RFC 952 and RFC 921.
                               2015                 :                :          */
                               2016   [ +  +  +  +  :            106 :         foreach_ptr(HostsLine, host, SSL_hosts->sni)
                                              +  + ]
                               2017                 :                :         {
                               2018   [ +  -  +  +  :            140 :             foreach_ptr(char, hostname, host->hostnames)
                                              +  + ]
                               2019                 :                :             {
                               2020   [ +  +  +  + ]:            171 :                 if (strlen(hostname) == len &&
                               2021                 :             79 :                     pg_strncasecmp(hostname, tlsext_hostname, len) == 0)
                               2022                 :                :                 {
                               2023                 :             52 :                     install_config = host;
                               2024                 :             52 :                     goto found;
                               2025                 :                :                 }
                               2026                 :                :             }
                               2027                 :                :         }
                               2028                 :                : 
                               2029                 :                :         /*
                               2030                 :                :          * If no host specific match was found, and there is a default config,
                               2031                 :                :          * then fall back to using that.
                               2032                 :                :          */
                               2033   [ +  -  +  + ]:             15 :         if (!install_config && SSL_hosts->default_host)
                               2034                 :             10 :             install_config = SSL_hosts->default_host;
                               2035                 :                :     }
                               2036                 :                : 
                               2037                 :                :     /*
                               2038                 :                :      * No hostname TLS extension in the handshake, use the default or no_sni
                               2039                 :                :      * configurations if available.
                               2040                 :                :      */
                               2041                 :                :     else
                               2042                 :                :     {
                               2043                 :              4 :         tlsext_hostname = NULL;
                               2044                 :                : 
                               2045         [ +  + ]:              4 :         if (SSL_hosts->no_sni)
                               2046                 :              2 :             install_config = SSL_hosts->no_sni;
                               2047         [ -  + ]:              2 :         else if (SSL_hosts->default_host)
  255 dgustafsson@postgres     2048                 :UBC           0 :             install_config = SSL_hosts->default_host;
                               2049                 :                :         else
                               2050                 :                :         {
                               2051                 :                :             /*
                               2052                 :                :              * Reaching here means that we didn't get a hostname in the TLS
                               2053                 :                :              * extension and the server has been configured to not allow any
                               2054                 :                :              * connections without a specified hostname.
                               2055                 :                :              *
                               2056                 :                :              * The error message for a missing server_name should, according
                               2057                 :                :              * to RFC 8446, be missing_extension. This isn't entirely ideal
                               2058                 :                :              * since the user won't be able to tell which extension the server
                               2059                 :                :              * considered missing.  Sending unrecognized_name would be a more
                               2060                 :                :              * helpful error, but for now we stick to the RFC.
                               2061                 :                :              */
  255 dgustafsson@postgres     2062                 :CBC           2 :             *al = SSL_AD_MISSING_EXTENSION;
                               2063                 :                : 
                               2064         [ +  - ]:              2 :             ereport(COMMERROR,
                               2065                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               2066                 :                :                      errmsg("no hostname provided in callback, and no fallback configured")));
                               2067                 :              2 :             return SSL_CLIENT_HELLO_ERROR;
                               2068                 :                :         }
                               2069                 :                :     }
                               2070                 :                : 
                               2071                 :                :     /*
                               2072                 :                :      * If we reach here without a context chosen as the session context then
                               2073                 :                :      * fail the handshake and terminate the connection.
                               2074                 :                :      */
                               2075         [ +  + ]:             17 :     if (install_config == NULL)
                               2076                 :                :     {
                               2077         [ +  - ]:              5 :         if (tlsext_hostname)
                               2078                 :              5 :             *al = SSL_AD_UNRECOGNIZED_NAME;
                               2079                 :                :         else
  255 dgustafsson@postgres     2080                 :UBC           0 :             *al = SSL_AD_MISSING_EXTENSION;
  255 dgustafsson@postgres     2081                 :CBC           5 :         return SSL_CLIENT_HELLO_ERROR;
                               2082                 :                :     }
                               2083                 :                : 
                               2084                 :             12 : found:
   33                          2085         [ -  + ]:            312 :     if (install_config->ssl_ctx == NULL)
                               2086                 :                :     {
   33 dgustafsson@postgres     2087                 :UBC           0 :         *al = SSL_AD_INTERNAL_ERROR;
                               2088         [ #  # ]:              0 :         ereport(COMMERROR,
                               2089                 :                :                 errcode(ERRCODE_CONFIG_FILE_ERROR),
                               2090                 :                :                 errmsg("SSL configuration for host could not be loaded, terminating connection"),
                               2091                 :                :                 errcontext("line %d of configuration file \"%s\"",
                               2092                 :                :                            install_config->linenumber, install_config->sourcefile));
                               2093                 :              0 :         return SSL_CLIENT_HELLO_ERROR;
                               2094                 :                :     }
                               2095                 :                : 
  255 dgustafsson@postgres     2096         [ -  + ]:CBC         312 :     if (!ssl_update_ssl(ssl, install_config))
                               2097                 :                :     {
  255 dgustafsson@postgres     2098                 :UBC           0 :         *al = SSL_AD_INTERNAL_ERROR;
                               2099         [ #  # ]:              0 :         ereport(COMMERROR,
                               2100                 :                :                 errcode(ERRCODE_PROTOCOL_VIOLATION),
                               2101                 :                :                 errmsg("failed to switch to SSL configuration for host, terminating connection"));
                               2102                 :              0 :         return SSL_CLIENT_HELLO_ERROR;
                               2103                 :                :     }
                               2104                 :                : 
  255 dgustafsson@postgres     2105                 :CBC         312 :     return SSL_CLIENT_HELLO_SUCCESS;
                               2106                 :                : }
                               2107                 :                : #endif                          /* HAVE_SSL_CTX_SET_CLIENT_HELLO_CB */
                               2108                 :                : 
                               2109                 :                : /*
                               2110                 :                :  * Set DH parameters for generating ephemeral DH keys.
                               2111                 :                :  */
                               2112                 :                : static bool
 3407 heikki.linnakangas@i     2113                 :             55 : initialize_dh(SSL_CTX *context, bool isServerStart)
                               2114                 :                : {
                               2115                 :             55 :     SSL_CTX_set_options(context, SSL_OP_SINGLE_DH_USE);
                               2116                 :                : 
                               2117         [ -  + ]:             55 :     if (ssl_dh_params_file[0])
                               2118                 :                :     {
                               2119                 :                :         DH         *dh;
                               2120                 :                : 
    1 peter@eisentraut.org     2121                 :UNC           0 :         dh = load_dh_file(ssl_dh_params_file, isServerStart);
                               2122                 :                : 
                               2123         [ #  # ]:              0 :         if (!dh)
                               2124                 :              0 :             return false;
                               2125                 :                : 
                               2126         [ #  # ]:              0 :         if (SSL_CTX_set_tmp_dh(context, dh) != 1)
                               2127                 :                :         {
                               2128   [ #  #  #  # ]:              0 :             ereport(isServerStart ? FATAL : LOG,
                               2129                 :                :                     (errcode(ERRCODE_CONFIG_FILE_ERROR),
                               2130                 :                :                      errmsg("DH: could not set DH parameters: %s",
                               2131                 :                :                             SSLerrmessage(ERR_get_error()))));
                               2132                 :              0 :             DH_free(dh);
                               2133                 :              0 :             return false;
                               2134                 :                :         }
                               2135                 :                : 
 2541 michael@paquier.xyz      2136                 :UBC           0 :         DH_free(dh);
                               2137                 :                :     }
                               2138                 :                :     else
                               2139                 :                :     {
                               2140                 :                :         /* If ssl_dh_params_file is not set, let OpenSSL pick a default. */
                               2141                 :                : 
    1 peter@eisentraut.org     2142         [ -  + ]:GNC          55 :         if (SSL_CTX_set_dh_auto(context, 1) != 1)
                               2143                 :                :         {
    1 peter@eisentraut.org     2144   [ #  #  #  # ]:UNC           0 :             ereport(isServerStart ? FATAL : LOG,
                               2145                 :                :                     (errcode(ERRCODE_INTERNAL_ERROR),
                               2146                 :                :                      errmsg("DH: could not set DH parameters: %s",
                               2147                 :                :                             SSLerrmessage(ERR_get_error()))));
                               2148                 :              0 :             return false;
                               2149                 :                :         }
                               2150                 :                :     }
                               2151                 :                : 
 3407 heikki.linnakangas@i     2152                 :CBC          55 :     return true;
                               2153                 :                : }
                               2154                 :                : 
                               2155                 :                : /*
                               2156                 :                :  * Set ECDH parameters for generating ephemeral Elliptic Curve DH
                               2157                 :                :  * keys.  This is much simpler than the DH parameters, as we just
                               2158                 :                :  * need to provide the name of the curve to OpenSSL.
                               2159                 :                :  */
                               2160                 :                : static bool
 3615 tgl@sss.pgh.pa.us        2161                 :             55 : initialize_ecdh(SSL_CTX *context, bool isServerStart)
                               2162                 :                : {
  765 dgustafsson@postgres     2163         [ +  + ]:             55 :     if (SSL_CTX_set1_groups_list(context, SSLECDHCurve) != 1)
                               2164                 :                :     {
                               2165                 :                :         /*
                               2166                 :                :          * OpenSSL 3.3.0 introduced proper error messages for group parsing
                               2167                 :                :          * errors, earlier versions returns "no SSL error reported" which is
                               2168                 :                :          * far from helpful. For older versions, we replace with a better
                               2169                 :                :          * error message. Injecting the error into the OpenSSL error queue
                               2170                 :                :          * need APIs from OpenSSL 3.0.
                               2171                 :                :          */
 3615 tgl@sss.pgh.pa.us        2172   [ +  -  +  - ]:              2 :         ereport(isServerStart ? FATAL : LOG,
                               2173                 :                :                 errcode(ERRCODE_CONFIG_FILE_ERROR),
                               2174                 :                :                 errmsg("could not set group names specified in ssl_groups: %s",
                               2175                 :                :                        SSLerrmessageExt(ERR_get_error(),
                               2176                 :                :                                         _("No valid groups found"))),
                               2177                 :                :                 errhint("Ensure that each group name is spelled correctly and supported by the installed version of OpenSSL."));
 3617 tgl@sss.pgh.pa.us        2178                 :UBC           0 :         return false;
                               2179                 :                :     }
                               2180                 :                : 
 3617 tgl@sss.pgh.pa.us        2181                 :CBC          53 :     return true;
                               2182                 :                : }
                               2183                 :                : 
                               2184                 :                : /*
                               2185                 :                :  * Obtain reason string for passed SSL errcode with replacement
                               2186                 :                :  *
                               2187                 :                :  * The error message supplied in replacement will be used in case the error
                               2188                 :                :  * code from OpenSSL is 0, else the error message from SSLerrmessage() will
                               2189                 :                :  * be returned.
                               2190                 :                :  *
                               2191                 :                :  * Not all versions of OpenSSL place an error on the queue even for failing
                               2192                 :                :  * operations, which will yield "no SSL error reported" by SSLerrmessage. This
                               2193                 :                :  * function can be used to ensure that a proper error message is displayed for
                               2194                 :                :  * versions reporting no error, while using the OpenSSL error via SSLerrmessage
                               2195                 :                :  * for versions where there is one.
                               2196                 :                :  */
                               2197                 :                : static const char *
  765 dgustafsson@postgres     2198                 :              2 : SSLerrmessageExt(unsigned long ecode, const char *replacement)
                               2199                 :                : {
                               2200         [ +  - ]:              2 :     if (ecode == 0)
                               2201                 :              2 :         return replacement;
                               2202                 :                :     else
  765 dgustafsson@postgres     2203                 :UBC           0 :         return SSLerrmessage(ecode);
                               2204                 :                : }
                               2205                 :                : 
                               2206                 :                : /*
                               2207                 :                :  * Obtain reason string for passed SSL errcode
                               2208                 :                :  *
                               2209                 :                :  * ERR_get_error() is used by caller to get errcode to pass here.
                               2210                 :                :  *
                               2211                 :                :  * Some caution is needed here since ERR_reason_error_string will return NULL
                               2212                 :                :  * if it doesn't recognize the error code, or (in OpenSSL >= 3) if the code
                               2213                 :                :  * represents a system errno value.  We don't want to return NULL ever.
                               2214                 :                :  */
                               2215                 :                : static const char *
 3886 peter_e@gmx.net          2216                 :CBC          38 : SSLerrmessage(unsigned long ecode)
                               2217                 :                : {
                               2218                 :                :     const char *errreason;
                               2219                 :                :     static char errbuf[36];
                               2220                 :                : 
                               2221         [ -  + ]:             38 :     if (ecode == 0)
 4492 heikki.linnakangas@i     2222                 :UBC           0 :         return _("no SSL error reported");
 3886 peter_e@gmx.net          2223                 :CBC          38 :     errreason = ERR_reason_error_string(ecode);
 4492 heikki.linnakangas@i     2224         [ +  + ]:             38 :     if (errreason != NULL)
                               2225                 :             36 :         return errreason;
                               2226                 :                : 
                               2227                 :                :     /*
                               2228                 :                :      * In OpenSSL 3.0.0 and later, ERR_reason_error_string does not map system
                               2229                 :                :      * errno values anymore.  (See OpenSSL source code for the explanation.)
                               2230                 :                :      * We can cover that shortcoming with this bit of code.  Older OpenSSL
                               2231                 :                :      * versions don't have the ERR_SYSTEM_ERROR macro, but that's okay because
                               2232                 :                :      * they don't have the shortcoming either.
                               2233                 :                :      */
                               2234                 :                : #ifdef ERR_SYSTEM_ERROR
  996 tgl@sss.pgh.pa.us        2235         [ +  - ]:              2 :     if (ERR_SYSTEM_ERROR(ecode))
                               2236                 :              2 :         return strerror(ERR_GET_REASON(ecode));
                               2237                 :                : #endif
                               2238                 :                : 
                               2239                 :                :     /* No choice but to report the numeric ecode */
 3886 peter_e@gmx.net          2240                 :UBC           0 :     snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), ecode);
 4492 heikki.linnakangas@i     2241                 :              0 :     return errbuf;
                               2242                 :                : }
                               2243                 :                : 
                               2244                 :                : int
 4248 magnus@hagander.net      2245                 :CBC         222 : be_tls_get_cipher_bits(Port *port)
                               2246                 :                : {
                               2247                 :                :     int         bits;
                               2248                 :                : 
                               2249         [ +  - ]:            222 :     if (port->ssl)
                               2250                 :                :     {
                               2251                 :            222 :         SSL_get_cipher_bits(port->ssl, &bits);
                               2252                 :            222 :         return bits;
                               2253                 :                :     }
                               2254                 :                :     else
 4248 magnus@hagander.net      2255                 :UBC           0 :         return 0;
                               2256                 :                : }
                               2257                 :                : 
                               2258                 :                : const char *
 3229 peter_e@gmx.net          2259                 :CBC         223 : be_tls_get_version(Port *port)
                               2260                 :                : {
 4248 magnus@hagander.net      2261         [ +  - ]:            223 :     if (port->ssl)
 3229 peter_e@gmx.net          2262                 :            223 :         return SSL_get_version(port->ssl);
                               2263                 :                :     else
 3229 peter_e@gmx.net          2264                 :UBC           0 :         return NULL;
                               2265                 :                : }
                               2266                 :                : 
                               2267                 :                : const char *
 3229 peter_e@gmx.net          2268                 :CBC         223 : be_tls_get_cipher(Port *port)
                               2269                 :                : {
 4248 magnus@hagander.net      2270         [ +  - ]:            223 :     if (port->ssl)
 3229 peter_e@gmx.net          2271                 :            223 :         return SSL_get_cipher(port->ssl);
                               2272                 :                :     else
 3229 peter_e@gmx.net          2273                 :UBC           0 :         return NULL;
                               2274                 :                : }
                               2275                 :                : 
                               2276                 :                : void
 2857 peter@eisentraut.org     2277                 :CBC         111 : be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len)
                               2278                 :                : {
 4248 magnus@hagander.net      2279         [ +  + ]:            111 :     if (port->peer)
                               2280                 :             29 :         strlcpy(ptr, X509_NAME_to_cstring(X509_get_subject_name(port->peer)), len);
                               2281                 :                :     else
                               2282                 :             82 :         ptr[0] = '\0';
                               2283                 :            111 : }
                               2284                 :                : 
                               2285                 :                : void
 2857 peter@eisentraut.org     2286                 :            112 : be_tls_get_peer_issuer_name(Port *port, char *ptr, size_t len)
                               2287                 :                : {
                               2288         [ +  + ]:            112 :     if (port->peer)
                               2289                 :             30 :         strlcpy(ptr, X509_NAME_to_cstring(X509_get_issuer_name(port->peer)), len);
                               2290                 :                :     else
                               2291                 :             82 :         ptr[0] = '\0';
                               2292                 :            112 : }
                               2293                 :                : 
                               2294                 :                : void
                               2295                 :            112 : be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
                               2296                 :                : {
                               2297         [ +  + ]:            112 :     if (port->peer)
                               2298                 :                :     {
                               2299                 :                :         ASN1_INTEGER *serial;
                               2300                 :                :         BIGNUM     *b;
                               2301                 :                :         char       *decimal;
                               2302                 :                : 
                               2303                 :             30 :         serial = X509_get_serialNumber(port->peer);
                               2304                 :             30 :         b = ASN1_INTEGER_to_BN(serial, NULL);
                               2305                 :             30 :         decimal = BN_bn2dec(b);
                               2306                 :                : 
                               2307                 :             30 :         BN_free(b);
                               2308                 :             30 :         strlcpy(ptr, decimal, len);
                               2309                 :             30 :         OPENSSL_free(decimal);
                               2310                 :                :     }
                               2311                 :                :     else
                               2312                 :             82 :         ptr[0] = '\0';
                               2313                 :            112 : }
                               2314                 :                : 
                               2315                 :                : char *
 3250 peter_e@gmx.net          2316                 :              4 : be_tls_get_certificate_hash(Port *port, size_t *len)
                               2317                 :                : {
                               2318                 :                :     X509       *server_cert;
                               2319                 :                :     char       *cert_hash;
                               2320                 :                : #if OPENSSL_VERSION_NUMBER >= 0x30000000L
                               2321                 :                :     EVP_MD     *algo_type;
                               2322                 :                :     const char *algo_name;
                               2323                 :                : #else
 3250 peter_e@gmx.net          2324                 :ECB         (4) :     const EVP_MD *algo_type = NULL;
                               2325                 :                : #endif
                               2326                 :                :     unsigned char hash[EVP_MAX_MD_SIZE];    /* size for SHA-512 */
                               2327                 :                :     unsigned int hash_size;
                               2328                 :                :     int         algo_nid;
                               2329                 :                : 
 3250 peter_e@gmx.net          2330                 :CBC           4 :     *len = 0;
                               2331                 :              4 :     server_cert = SSL_get_certificate(port->ssl);
                               2332         [ -  + ]:              4 :     if (server_cert == NULL)
 3250 peter_e@gmx.net          2333                 :UBC           0 :         return NULL;
                               2334                 :                : 
                               2335                 :                :     /*
                               2336                 :                :      * Get the signature algorithm of the certificate to determine the hash
                               2337                 :                :      * algorithm to use for the result.  Prefer X509_get_signature_info(),
                               2338                 :                :      * introduced in OpenSSL 1.1.1, which can handle RSA-PSS signatures.
                               2339                 :                :      */
                               2340                 :                : #if HAVE_X509_GET_SIGNATURE_INFO
 1382 michael@paquier.xyz      2341         [ -  + ]:CBC           4 :     if (!X509_get_signature_info(server_cert, &algo_nid, NULL, NULL, NULL))
                               2342                 :                : #else
                               2343                 :                :     if (!OBJ_find_sigid_algs(X509_get_signature_nid(server_cert),
                               2344                 :                :                              &algo_nid, NULL))
                               2345                 :                : #endif
 3250 peter_e@gmx.net          2346         [ #  # ]:UBC           0 :         elog(ERROR, "could not determine server certificate signature algorithm");
                               2347                 :                : 
                               2348                 :                :     /*
                               2349                 :                :      * The TLS server's certificate bytes need to be hashed with SHA-256 if
                               2350                 :                :      * its signature algorithm is MD5 or SHA-1 as per RFC 5929
                               2351                 :                :      * (https://tools.ietf.org/html/rfc5929#section-4.1).  If something else
                               2352                 :                :      * is used, the same hash as the signature algorithm is used.
                               2353                 :                :      */
                               2354                 :                : #if OPENSSL_VERSION_NUMBER >= 0x30000000L
  106 michael@paquier.xyz      2355         [ -  + ]:GNC           4 :     switch (algo_nid)
                               2356                 :                :     {
  106 michael@paquier.xyz      2357                 :UNC           0 :         case NID_md5:
                               2358                 :                :         case NID_sha1:
                               2359                 :              0 :             algo_name = "SHA256";
                               2360                 :              0 :             break;
  106 michael@paquier.xyz      2361                 :GNC           4 :         default:
                               2362                 :              4 :             algo_name = OBJ_nid2sn(algo_nid);
                               2363         [ -  + ]:              4 :             if (algo_name == NULL)
  106 michael@paquier.xyz      2364         [ #  # ]:UNC           0 :                 elog(ERROR, "could not find digest for NID %d",
                               2365                 :                :                      algo_nid);
  106 michael@paquier.xyz      2366                 :GNC           4 :             break;
                               2367                 :                :     }
                               2368                 :                : 
                               2369                 :              4 :     algo_type = EVP_MD_fetch(NULL, algo_name, NULL);
                               2370         [ -  + ]:              4 :     if (algo_type == NULL)
  106 michael@paquier.xyz      2371         [ #  # ]:UNC           0 :         elog(ERROR, "could not fetch digest \"%s\"", algo_name);
                               2372                 :                : #else
 3250 peter_e@gmx.net          2373         [ -  + ]:ECB         (4) :     switch (algo_nid)
                               2374                 :                :     {
 3250 peter_e@gmx.net          2375                 :EUB             :         case NID_md5:
                               2376                 :                :         case NID_sha1:
                               2377                 :                :             algo_type = EVP_sha256();
                               2378                 :                :             break;
 3250 peter_e@gmx.net          2379                 :ECB         (4) :         default:
                               2380                 :            (4) :             algo_type = EVP_get_digestbynid(algo_nid);
                               2381         [ -  + ]:            (4) :             if (algo_type == NULL)
 3250 peter_e@gmx.net          2382         [ #  # ]:EUB             :                 elog(ERROR, "could not find digest for NID %s",
                               2383                 :                :                      OBJ_nid2sn(algo_nid));
 3250 peter_e@gmx.net          2384                 :ECB         (4) :             break;
                               2385                 :                :     }
                               2386                 :                : #endif
                               2387                 :                : 
                               2388                 :                :     /* generate and save the certificate hash */
 3250 peter_e@gmx.net          2389         [ -  + ]:CBC           4 :     if (!X509_digest(server_cert, algo_type, hash, &hash_size))
                               2390                 :                :     {
                               2391                 :                : #if OPENSSL_VERSION_NUMBER >= 0x30000000L
  106 michael@paquier.xyz      2392                 :UNC           0 :         EVP_MD_free(algo_type);
                               2393                 :                : #endif
 3250 peter_e@gmx.net          2394         [ #  # ]:UBC           0 :         elog(ERROR, "could not generate server certificate hash");
                               2395                 :                :     }
                               2396                 :                : 
                               2397                 :                : #if OPENSSL_VERSION_NUMBER >= 0x30000000L
  106 michael@paquier.xyz      2398                 :GNC           4 :     EVP_MD_free(algo_type);
                               2399                 :                : #endif
                               2400                 :                : 
 3250 peter_e@gmx.net          2401                 :CBC           4 :     cert_hash = palloc(hash_size);
                               2402                 :              4 :     memcpy(cert_hash, hash, hash_size);
                               2403                 :              4 :     *len = hash_size;
                               2404                 :                : 
                               2405                 :              4 :     return cert_hash;
                               2406                 :                : }
                               2407                 :                : 
                               2408                 :                : /*
                               2409                 :                :  * Convert an X509 subject name to a cstring.
                               2410                 :                :  *
                               2411                 :                :  */
                               2412                 :                : static char *
  183 dgustafsson@postgres     2413                 :             75 : X509_NAME_to_cstring(const X509_NAME *name)
                               2414                 :                : {
 4248 magnus@hagander.net      2415                 :             75 :     BIO        *membuf = BIO_new(BIO_s_mem());
                               2416                 :                :     int         i,
                               2417                 :                :                 nid,
                               2418                 :             75 :                 count = X509_NAME_entry_count(name);
                               2419                 :                :     const X509_NAME_ENTRY *e;
                               2420                 :                :     const ASN1_STRING *v;
                               2421                 :                :     const char *field_name;
                               2422                 :                :     size_t      size;
                               2423                 :                :     char        nullterm;
                               2424                 :                :     char       *sp;
                               2425                 :                :     char       *dp;
                               2426                 :                :     char       *result;
                               2427                 :                : 
 2216                          2428         [ -  + ]:             75 :     if (membuf == NULL)
 2216 magnus@hagander.net      2429         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2430                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                               2431                 :                :                  errmsg("could not create BIO")));
                               2432                 :                : 
 4248 magnus@hagander.net      2433                 :CBC          75 :     (void) BIO_set_close(membuf, BIO_CLOSE);
                               2434         [ +  + ]:            161 :     for (i = 0; i < count; i++)
                               2435                 :                :     {
                               2436                 :             86 :         e = X509_NAME_get_entry(name, i);
                               2437                 :             86 :         nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(e));
 2216                          2438         [ -  + ]:             86 :         if (nid == NID_undef)
 2216 magnus@hagander.net      2439         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2440                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2441                 :                :                      errmsg("could not get NID for ASN1_OBJECT object")));
 4248 magnus@hagander.net      2442                 :CBC          86 :         v = X509_NAME_ENTRY_get_data(e);
                               2443                 :             86 :         field_name = OBJ_nid2sn(nid);
 2216                          2444         [ -  + ]:             86 :         if (field_name == NULL)
 4248 magnus@hagander.net      2445                 :UBC           0 :             field_name = OBJ_nid2ln(nid);
 2216 magnus@hagander.net      2446         [ -  + ]:CBC          86 :         if (field_name == NULL)
 2216 magnus@hagander.net      2447         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2448                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2449                 :                :                      errmsg("could not convert NID %d to an ASN1_OBJECT structure", nid)));
 4248 magnus@hagander.net      2450                 :CBC          86 :         BIO_printf(membuf, "/%s=", field_name);
                               2451                 :             86 :         ASN1_STRING_print_ex(membuf, v,
                               2452                 :                :                              ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
                               2453                 :                :                               | ASN1_STRFLGS_UTF8_CONVERT));
                               2454                 :                :     }
                               2455                 :                : 
                               2456                 :                :     /* ensure null termination of the BIO's content */
                               2457                 :             75 :     nullterm = '\0';
                               2458                 :             75 :     BIO_write(membuf, &nullterm, 1);
                               2459                 :             75 :     size = BIO_get_mem_data(membuf, &sp);
                               2460                 :             75 :     dp = pg_any_to_server(sp, size - 1, PG_UTF8);
                               2461                 :                : 
                               2462                 :             75 :     result = pstrdup(dp);
                               2463         [ -  + ]:             75 :     if (dp != sp)
 4248 magnus@hagander.net      2464                 :UBC           0 :         pfree(dp);
 2216 magnus@hagander.net      2465         [ -  + ]:CBC          75 :     if (BIO_free(membuf) != 1)
 2216 magnus@hagander.net      2466         [ #  # ]:UBC           0 :         elog(ERROR, "could not free OpenSSL BIO structure");
                               2467                 :                : 
 4248 magnus@hagander.net      2468                 :CBC          75 :     return result;
                               2469                 :                : }
                               2470                 :                : 
                               2471                 :                : /*
                               2472                 :                :  * Convert TLS protocol version GUC enum to OpenSSL values
                               2473                 :                :  *
                               2474                 :                :  * This is a straightforward one-to-one mapping, but doing it this way makes
                               2475                 :                :  * the definitions of ssl_min_protocol_version and ssl_max_protocol_version
                               2476                 :                :  * independent of OpenSSL availability and version.
                               2477                 :                :  *
                               2478                 :                :  * If a version is passed that is not supported by the current OpenSSL
                               2479                 :                :  * version, then we return -1.  If a nonnegative value is returned,
                               2480                 :                :  * subsequent code can assume it's working with a supported version.
                               2481                 :                :  *
                               2482                 :                :  * Note: this is rather similar to libpq's routine in fe-secure-openssl.c,
                               2483                 :                :  * so make sure to update both routines if changing this one.
                               2484                 :                :  */
                               2485                 :                : static int
 2441 michael@paquier.xyz      2486                 :             57 : ssl_protocol_version_to_openssl(int v)
                               2487                 :                : {
 2930 peter_e@gmx.net          2488   [ -  -  +  +  :             57 :     switch (v)
                                              -  - ]
                               2489                 :                :     {
 2930 peter_e@gmx.net          2490                 :UBC           0 :         case PG_TLS_ANY:
                               2491                 :              0 :             return 0;
                               2492                 :              0 :         case PG_TLS1_VERSION:
                               2493                 :                : #ifndef OPENSSL_NO_TLS1
                               2494                 :              0 :             return TLS1_VERSION;
                               2495                 :                : #else
                               2496                 :                :             break;
                               2497                 :                : #endif
 2930 peter_e@gmx.net          2498                 :CBC           1 :         case PG_TLS1_1_VERSION:
                               2499                 :                : #ifndef OPENSSL_NO_TLS1_1
                               2500                 :              1 :             return TLS1_1_VERSION;
                               2501                 :                : #else
                               2502                 :                :             break;
                               2503                 :                : #endif
                               2504                 :             56 :         case PG_TLS1_2_VERSION:
                               2505                 :                : #ifndef OPENSSL_NO_TLS1_2
                               2506                 :             56 :             return TLS1_2_VERSION;
                               2507                 :                : #else
                               2508                 :                :             break;
                               2509                 :                : #endif
 2930 peter_e@gmx.net          2510                 :UBC           0 :         case PG_TLS1_3_VERSION:
                               2511                 :                : #ifndef OPENSSL_NO_TLS1_3
                               2512                 :              0 :             return TLS1_3_VERSION;
                               2513                 :                : #else
                               2514                 :                :             break;
                               2515                 :                : #endif
                               2516                 :                :     }
                               2517                 :                : 
                               2518                 :              0 :     return -1;
                               2519                 :                : }
                               2520                 :                : 
                               2521                 :                : /*
                               2522                 :                :  * Likewise provide a mapping to strings.
                               2523                 :                :  */
                               2524                 :                : static const char *
 2345 tgl@sss.pgh.pa.us        2525                 :              0 : ssl_protocol_version_to_string(int v)
                               2526                 :                : {
                               2527   [ #  #  #  #  :              0 :     switch (v)
                                              #  # ]
                               2528                 :                :     {
                               2529                 :              0 :         case PG_TLS_ANY:
                               2530                 :              0 :             return "any";
                               2531                 :              0 :         case PG_TLS1_VERSION:
                               2532                 :              0 :             return "TLSv1";
                               2533                 :              0 :         case PG_TLS1_1_VERSION:
                               2534                 :              0 :             return "TLSv1.1";
                               2535                 :              0 :         case PG_TLS1_2_VERSION:
                               2536                 :              0 :             return "TLSv1.2";
                               2537                 :              0 :         case PG_TLS1_3_VERSION:
                               2538                 :              0 :             return "TLSv1.3";
                               2539                 :                :     }
                               2540                 :                : 
                               2541                 :              0 :     return "(unrecognized)";
                               2542                 :                : }
                               2543                 :                : 
                               2544                 :                : static uint32
  255 dgustafsson@postgres     2545                 :CBC          36 : host_cache_pointer(const char *key)
                               2546                 :                : {
                               2547                 :                :     uint32      hash;
                               2548                 :             36 :     char       *lkey = pstrdup(key);
                               2549                 :             36 :     int         len = strlen(key);
                               2550                 :                : 
                               2551         [ +  + ]:            444 :     for (int i = 0; i < len; i++)
                               2552                 :            408 :         lkey[i] = pg_tolower(lkey[i]);
                               2553                 :                : 
                               2554                 :             36 :     hash = string_hash((const void *) lkey, len);
                               2555                 :             36 :     pfree(lkey);
                               2556                 :             36 :     return hash;
                               2557                 :                : }
                               2558                 :                : 
                               2559                 :                : static void
 2439 andrew@dunslane.net      2560                 :             39 : default_openssl_tls_init(SSL_CTX *context, bool isServerStart)
                               2561                 :                : {
                               2562         [ +  + ]:             39 :     if (isServerStart)
                               2563                 :                :     {
                               2564         [ +  + ]:             33 :         if (ssl_passphrase_command[0])
                               2565                 :                :         {
                               2566                 :              7 :             SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
  255 dgustafsson@postgres     2567                 :              7 :             SSL_CTX_set_default_passwd_cb_userdata(context, ssl_passphrase_command);
                               2568                 :                :         }
                               2569                 :                :     }
                               2570                 :                :     else
                               2571                 :                :     {
 2439 andrew@dunslane.net      2572   [ +  +  +  + ]:              6 :         if (ssl_passphrase_command[0] && ssl_passphrase_command_supports_reload)
                               2573                 :                :         {
                               2574                 :              1 :             SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
  255 dgustafsson@postgres     2575                 :              1 :             SSL_CTX_set_default_passwd_cb_userdata(context, ssl_passphrase_command);
                               2576                 :                :         }
                               2577                 :                :         else
                               2578                 :                : 
                               2579                 :                :             /*
                               2580                 :                :              * If reloading and no external command is configured, override
                               2581                 :                :              * OpenSSL's default handling of passphrase-protected files,
                               2582                 :                :              * because we don't want to prompt for a passphrase in an
                               2583                 :                :              * already-running server.
                               2584                 :                :              */
 2439 andrew@dunslane.net      2585                 :              5 :             SSL_CTX_set_default_passwd_cb(context, dummy_ssl_passwd_cb);
                               2586                 :                :     }
                               2587                 :             39 : }
        

Generated by: LCOV version 2.0-1