1 /*-------------------------------------------------------------------------
4 * functions related to setting up a secure connection to the backend.
5 * Secure connections are expected to provide confidentiality,
6 * message integrity and endpoint authentication.
9 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
10 * Portions Copyright (c) 1994, Regents of the University of California
14 * src/interfaces/libpq/fe-secure.c
18 * We don't provide informational callbacks here (like
19 * info_cb() in be-secure.c), since there's no good mechanism to
20 * display such information to the user.
22 *-------------------------------------------------------------------------
25 #include "postgres_fe.h"
33 #include "libpq-int.h"
38 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #ifdef HAVE_NETINET_TCP_H
43 #include <netinet/tcp.h>
45 #include <arpa/inet.h>
50 #ifdef ENABLE_THREAD_SAFETY
52 #include "pthread-win32.h"
60 #include <openssl/ssl.h>
61 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L)
62 #include <openssl/conf.h>
65 #include <openssl/engine.h>
70 #define USER_CERT_FILE ".postgresql/postgresql.crt"
71 #define USER_KEY_FILE ".postgresql/postgresql.key"
72 #define ROOT_CERT_FILE ".postgresql/root.crt"
73 #define ROOT_CRL_FILE ".postgresql/root.crl"
75 /* On Windows, the "home" directory is already PostgreSQL-specific */
76 #define USER_CERT_FILE "postgresql.crt"
77 #define USER_KEY_FILE "postgresql.key"
78 #define ROOT_CERT_FILE "root.crt"
79 #define ROOT_CRL_FILE "root.crl"
82 static bool verify_peer_name_matches_certificate(PGconn *);
83 static int verify_cb(int ok, X509_STORE_CTX *ctx);
84 static int init_ssl_system(PGconn *conn);
85 static void destroy_ssl_system(void);
86 static int initialize_SSL(PGconn *conn);
87 static void destroySSL(void);
88 static PostgresPollingStatusType open_client_SSL(PGconn *);
89 static void close_SSL(PGconn *);
90 static char *SSLerrmessage(void);
91 static void SSLerrfree(char *buf);
93 static bool pq_init_ssl_lib = true;
94 static bool pq_init_crypto_lib = true;
97 * SSL_context is currently shared between threads and therefore we need to be
98 * careful to lock around any usage of it when providing thread safety.
99 * ssl_config_mutex is the mutex that we use to protect it.
101 static SSL_CTX *SSL_context = NULL;
103 #ifdef ENABLE_THREAD_SAFETY
104 static long ssl_open_connections = 0;
107 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
109 static pthread_mutex_t ssl_config_mutex = NULL;
110 static long win32_ssl_create_mutex = 0;
112 #endif /* ENABLE_THREAD_SAFETY */
117 * Macros to handle disabling and then restoring the state of SIGPIPE handling.
118 * On Windows, these are all no-ops since there's no SIGPIPEs.
123 #define SIGPIPE_MASKED(conn) ((conn)->sigpipe_so || (conn)->sigpipe_flag)
125 #ifdef ENABLE_THREAD_SAFETY
130 bool sigpipe_pending;
134 #define DECLARE_SIGPIPE_INFO(spinfo) struct sigpipe_info spinfo
136 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
138 (spinfo).got_epipe = false; \
139 if (!SIGPIPE_MASKED(conn)) \
141 if (pq_block_sigpipe(&(spinfo).oldsigmask, \
142 &(spinfo).sigpipe_pending) < 0) \
147 #define REMEMBER_EPIPE(spinfo, cond) \
150 (spinfo).got_epipe = true; \
153 #define RESTORE_SIGPIPE(conn, spinfo) \
155 if (!SIGPIPE_MASKED(conn)) \
156 pq_reset_sigpipe(&(spinfo).oldsigmask, (spinfo).sigpipe_pending, \
157 (spinfo).got_epipe); \
159 #else /* !ENABLE_THREAD_SAFETY */
161 #define DECLARE_SIGPIPE_INFO(spinfo) pqsigfunc spinfo = NULL
163 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
165 if (!SIGPIPE_MASKED(conn)) \
166 spinfo = pqsignal(SIGPIPE, SIG_IGN); \
169 #define REMEMBER_EPIPE(spinfo, cond)
171 #define RESTORE_SIGPIPE(conn, spinfo) \
173 if (!SIGPIPE_MASKED(conn)) \
174 pqsignal(SIGPIPE, spinfo); \
176 #endif /* ENABLE_THREAD_SAFETY */
179 #define DECLARE_SIGPIPE_INFO(spinfo)
180 #define DISABLE_SIGPIPE(conn, spinfo, failaction)
181 #define REMEMBER_EPIPE(spinfo, cond)
182 #define RESTORE_SIGPIPE(conn, spinfo)
185 /* ------------------------------------------------------------ */
186 /* Procedures common to all secure sessions */
187 /* ------------------------------------------------------------ */
191 * Exported function to allow application to tell us it's already
192 * initialized OpenSSL.
195 PQinitSSL(int do_init)
197 PQinitOpenSSL(do_init, do_init);
201 * Exported function to allow application to tell us it's already
202 * initialized OpenSSL and/or libcrypto.
205 PQinitOpenSSL(int do_ssl, int do_crypto)
208 #ifdef ENABLE_THREAD_SAFETY
211 * Disallow changing the flags while we have open connections, else we'd
212 * get completely confused.
214 if (ssl_open_connections != 0)
218 pq_init_ssl_lib = do_ssl;
219 pq_init_crypto_lib = do_crypto;
224 * Initialize global SSL context
227 pqsecure_initialize(PGconn *conn)
232 r = init_ssl_system(conn);
239 * Destroy global context
242 pqsecure_destroy(void)
250 * Begin or continue negotiating a secure session.
252 PostgresPollingStatusType
253 pqsecure_open_client(PGconn *conn)
256 /* First time through? */
257 if (conn->ssl == NULL)
259 #ifdef ENABLE_THREAD_SAFETY
263 /* We cannot use MSG_NOSIGNAL to block SIGPIPE when using SSL */
264 conn->sigpipe_flag = false;
266 #ifdef ENABLE_THREAD_SAFETY
267 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
269 printfPQExpBuffer(&conn->errorMessage,
270 libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
271 return PGRES_POLLING_FAILED;
274 /* Create a connection-specific SSL object */
275 if (!(conn->ssl = SSL_new(SSL_context)) ||
276 !SSL_set_app_data(conn->ssl, conn) ||
277 !SSL_set_fd(conn->ssl, conn->sock))
279 char *err = SSLerrmessage();
281 printfPQExpBuffer(&conn->errorMessage,
282 libpq_gettext("could not establish SSL connection: %s\n"),
285 #ifdef ENABLE_THREAD_SAFETY
286 pthread_mutex_unlock(&ssl_config_mutex);
290 return PGRES_POLLING_FAILED;
292 #ifdef ENABLE_THREAD_SAFETY
293 pthread_mutex_unlock(&ssl_config_mutex);
296 * Load client certificate, private key, and trusted CA certs.
298 if (initialize_SSL(conn) != 0)
300 /* initialize_SSL already put a message in conn->errorMessage */
302 return PGRES_POLLING_FAILED;
306 /* Begin or continue the actual handshake */
307 return open_client_SSL(conn);
309 /* shouldn't get here */
310 return PGRES_POLLING_FAILED;
315 * Close secure session.
318 pqsecure_close(PGconn *conn)
327 * Read data from a secure connection.
329 * On failure, this function is responsible for putting a suitable message
330 * into conn->errorMessage. The caller must still inspect errno, but only
331 * to determine whether to continue/retry after error.
334 pqsecure_read(PGconn *conn, void *ptr, size_t len)
337 int result_errno = 0;
345 DECLARE_SIGPIPE_INFO(spinfo);
347 /* SSL_read can write to the socket, so we need to disable SIGPIPE */
348 DISABLE_SIGPIPE(conn, spinfo, return -1);
352 n = SSL_read(conn->ssl, ptr, len);
353 err = SSL_get_error(conn->ssl, n);
359 /* Not supposed to happen, so we don't translate the msg */
360 printfPQExpBuffer(&conn->errorMessage,
361 "SSL_read failed but did not provide error information\n");
362 /* assume the connection is broken */
363 result_errno = ECONNRESET;
366 case SSL_ERROR_WANT_READ:
369 case SSL_ERROR_WANT_WRITE:
372 * Returning 0 here would cause caller to wait for read-ready,
373 * which is not correct since what SSL wants is wait for
374 * write-ready. The former could get us stuck in an infinite
375 * wait, so don't risk it; busy-loop instead.
378 case SSL_ERROR_SYSCALL:
381 result_errno = SOCK_ERRNO;
382 REMEMBER_EPIPE(spinfo, result_errno == EPIPE);
383 if (result_errno == EPIPE ||
384 result_errno == ECONNRESET)
385 printfPQExpBuffer(&conn->errorMessage,
387 "server closed the connection unexpectedly\n"
388 "\tThis probably means the server terminated abnormally\n"
389 "\tbefore or while processing the request.\n"));
391 printfPQExpBuffer(&conn->errorMessage,
392 libpq_gettext("SSL SYSCALL error: %s\n"),
393 SOCK_STRERROR(result_errno,
394 sebuf, sizeof(sebuf)));
398 printfPQExpBuffer(&conn->errorMessage,
399 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
400 /* assume the connection is broken */
401 result_errno = ECONNRESET;
407 char *errm = SSLerrmessage();
409 printfPQExpBuffer(&conn->errorMessage,
410 libpq_gettext("SSL error: %s\n"), errm);
412 /* assume the connection is broken */
413 result_errno = ECONNRESET;
417 case SSL_ERROR_ZERO_RETURN:
420 * Per OpenSSL documentation, this error code is only returned
421 * for a clean connection closure, so we should not report it
424 printfPQExpBuffer(&conn->errorMessage,
425 libpq_gettext("SSL connection has been closed unexpectedly\n"));
426 result_errno = ECONNRESET;
430 printfPQExpBuffer(&conn->errorMessage,
431 libpq_gettext("unrecognized SSL error code: %d\n"),
433 /* assume the connection is broken */
434 result_errno = ECONNRESET;
439 RESTORE_SIGPIPE(conn, spinfo);
444 n = recv(conn->sock, ptr, len, 0);
448 result_errno = SOCK_ERRNO;
450 /* Set error message if appropriate */
451 switch (result_errno)
456 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
460 /* no error message, caller is expected to retry */
465 printfPQExpBuffer(&conn->errorMessage,
467 "server closed the connection unexpectedly\n"
468 "\tThis probably means the server terminated abnormally\n"
469 "\tbefore or while processing the request.\n"));
474 printfPQExpBuffer(&conn->errorMessage,
475 libpq_gettext("could not receive data from server: %s\n"),
476 SOCK_STRERROR(result_errno,
477 sebuf, sizeof(sebuf)));
483 /* ensure we return the intended errno to caller */
484 SOCK_ERRNO_SET(result_errno);
490 * Write data to a secure connection.
492 * On failure, this function is responsible for putting a suitable message
493 * into conn->errorMessage. The caller must still inspect errno, but only
494 * to determine whether to continue/retry after error.
497 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
500 int result_errno = 0;
503 DECLARE_SIGPIPE_INFO(spinfo);
510 DISABLE_SIGPIPE(conn, spinfo, return -1);
513 n = SSL_write(conn->ssl, ptr, len);
514 err = SSL_get_error(conn->ssl, n);
520 /* Not supposed to happen, so we don't translate the msg */
521 printfPQExpBuffer(&conn->errorMessage,
522 "SSL_write failed but did not provide error information\n");
523 /* assume the connection is broken */
524 result_errno = ECONNRESET;
527 case SSL_ERROR_WANT_READ:
530 * Returning 0 here causes caller to wait for write-ready,
531 * which is not really the right thing, but it's the best we
536 case SSL_ERROR_WANT_WRITE:
539 case SSL_ERROR_SYSCALL:
542 result_errno = SOCK_ERRNO;
543 REMEMBER_EPIPE(spinfo, result_errno == EPIPE);
544 if (result_errno == EPIPE ||
545 result_errno == ECONNRESET)
546 printfPQExpBuffer(&conn->errorMessage,
548 "server closed the connection unexpectedly\n"
549 "\tThis probably means the server terminated abnormally\n"
550 "\tbefore or while processing the request.\n"));
552 printfPQExpBuffer(&conn->errorMessage,
553 libpq_gettext("SSL SYSCALL error: %s\n"),
554 SOCK_STRERROR(result_errno,
555 sebuf, sizeof(sebuf)));
559 printfPQExpBuffer(&conn->errorMessage,
560 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
561 /* assume the connection is broken */
562 result_errno = ECONNRESET;
568 char *errm = SSLerrmessage();
570 printfPQExpBuffer(&conn->errorMessage,
571 libpq_gettext("SSL error: %s\n"), errm);
573 /* assume the connection is broken */
574 result_errno = ECONNRESET;
578 case SSL_ERROR_ZERO_RETURN:
581 * Per OpenSSL documentation, this error code is only returned
582 * for a clean connection closure, so we should not report it
585 printfPQExpBuffer(&conn->errorMessage,
586 libpq_gettext("SSL connection has been closed unexpectedly\n"));
587 result_errno = ECONNRESET;
591 printfPQExpBuffer(&conn->errorMessage,
592 libpq_gettext("unrecognized SSL error code: %d\n"),
594 /* assume the connection is broken */
595 result_errno = ECONNRESET;
606 if (conn->sigpipe_flag)
607 flags |= MSG_NOSIGNAL;
610 #endif /* MSG_NOSIGNAL */
612 DISABLE_SIGPIPE(conn, spinfo, return -1);
614 n = send(conn->sock, ptr, len, flags);
618 result_errno = SOCK_ERRNO;
621 * If we see an EINVAL, it may be because MSG_NOSIGNAL isn't
622 * available on this machine. So, clear sigpipe_flag so we don't
623 * try the flag again, and retry the send().
626 if (flags != 0 && result_errno == EINVAL)
628 conn->sigpipe_flag = false;
632 #endif /* MSG_NOSIGNAL */
634 /* Set error message if appropriate */
635 switch (result_errno)
640 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
644 /* no error message, caller is expected to retry */
648 /* Set flag for EPIPE */
649 REMEMBER_EPIPE(spinfo, true);
655 printfPQExpBuffer(&conn->errorMessage,
657 "server closed the connection unexpectedly\n"
658 "\tThis probably means the server terminated abnormally\n"
659 "\tbefore or while processing the request.\n"));
663 printfPQExpBuffer(&conn->errorMessage,
664 libpq_gettext("could not send data to server: %s\n"),
665 SOCK_STRERROR(result_errno,
666 sebuf, sizeof(sebuf)));
672 RESTORE_SIGPIPE(conn, spinfo);
674 /* ensure we return the intended errno to caller */
675 SOCK_ERRNO_SET(result_errno);
680 /* ------------------------------------------------------------ */
681 /* SSL specific code */
682 /* ------------------------------------------------------------ */
686 * Certificate verification callback
688 * This callback allows us to log intermediate problems during
689 * verification, but there doesn't seem to be a clean way to get
690 * our PGconn * structure. So we can't log anything!
692 * This callback also allows us to override the default acceptance
693 * criteria (e.g., accepting self-signed or expired certs), but
694 * for now we accept the default checks.
697 verify_cb(int ok, X509_STORE_CTX *ctx)
704 * Check if a wildcard certificate matches the server hostname.
706 * The rule for this is:
707 * 1. We only match the '*' character as wildcard
708 * 2. We match only wildcards at the start of the string
709 * 3. The '*' character does *not* match '.', meaning that we match only
710 * a single pathname component.
711 * 4. We don't support more than one '*' in a single pattern.
713 * This is roughly in line with RFC2818, but contrary to what most browsers
714 * appear to be implementing (point 3 being the difference)
716 * Matching is always case-insensitive, since DNS is case insensitive.
719 wildcard_certificate_match(const char *pattern, const char *string)
721 int lenpat = strlen(pattern);
722 int lenstr = strlen(string);
724 /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
731 /* If pattern is longer than the string, we can never match */
734 if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
737 * If string does not end in pattern (minus the wildcard), we don't
742 if (strchr(string, '.') < string + lenstr - lenpat)
745 * If there is a dot left of where the pattern started to match, we
746 * don't match (rule 3)
750 /* String ended with pattern, and didn't have a dot before, so we match */
756 * Verify that common name resolves to peer.
759 verify_peer_name_matches_certificate(PGconn *conn)
767 * If told not to verify the peer name, don't do it. Return true
768 * indicating that the verification was successful.
770 if (strcmp(conn->sslmode, "verify-full") != 0)
774 * Extract the common name from the certificate.
776 * XXX: Should support alternate names here
778 /* First find out the name's length and allocate a buffer for it. */
779 len = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
780 NID_commonName, NULL, 0);
783 printfPQExpBuffer(&conn->errorMessage,
784 libpq_gettext("could not get server common name from server certificate\n"));
787 peer_cn = malloc(len + 1);
790 printfPQExpBuffer(&conn->errorMessage,
791 libpq_gettext("out of memory\n"));
795 r = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
796 NID_commonName, peer_cn, len + 1);
799 /* Got different length than on the first call. Shouldn't happen. */
800 printfPQExpBuffer(&conn->errorMessage,
801 libpq_gettext("could not get server common name from server certificate\n"));
808 * Reject embedded NULLs in certificate common name to prevent attacks
809 * like CVE-2009-4034.
811 if (len != strlen(peer_cn))
813 printfPQExpBuffer(&conn->errorMessage,
814 libpq_gettext("SSL certificate's common name contains embedded null\n"));
820 * We got the peer's common name. Now compare it against the originally
823 if (!(conn->pghost && conn->pghost[0] != '\0'))
825 printfPQExpBuffer(&conn->errorMessage,
826 libpq_gettext("host name must be specified for a verified SSL connection\n"));
831 if (pg_strcasecmp(peer_cn, conn->pghost) == 0)
832 /* Exact name match */
834 else if (wildcard_certificate_match(peer_cn, conn->pghost))
835 /* Matched wildcard certificate */
839 printfPQExpBuffer(&conn->errorMessage,
840 libpq_gettext("server common name \"%s\" does not match host name \"%s\"\n"),
841 peer_cn, conn->pghost);
850 #ifdef ENABLE_THREAD_SAFETY
852 * Callback functions for OpenSSL internal locking
856 pq_threadidcallback(void)
859 * This is not standards-compliant. pthread_self() returns pthread_t, and
860 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
861 * it, so we have to do it.
863 return (unsigned long) pthread_self();
866 static pthread_mutex_t *pq_lockarray;
869 pq_lockingcallback(int mode, int n, const char *file, int line)
871 if (mode & CRYPTO_LOCK)
873 if (pthread_mutex_lock(&pq_lockarray[n]))
874 PGTHREAD_ERROR("failed to lock mutex");
878 if (pthread_mutex_unlock(&pq_lockarray[n]))
879 PGTHREAD_ERROR("failed to unlock mutex");
882 #endif /* ENABLE_THREAD_SAFETY */
885 * Initialize SSL system, in particular creating the SSL_context object
886 * that will be shared by all SSL-using connections in this process.
888 * In threadsafe mode, this includes setting up libcrypto callback functions
889 * to do thread locking.
891 * If the caller has told us (through PQinitOpenSSL) that he's taking care
892 * of libcrypto, we expect that callbacks are already set, and won't try to
895 * The conn parameter is only used to be able to pass back an error
896 * message - no connection-local setup is made here.
898 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
901 init_ssl_system(PGconn *conn)
903 #ifdef ENABLE_THREAD_SAFETY
905 /* Also see similar code in fe-connect.c, default_threadlock() */
906 if (ssl_config_mutex == NULL)
908 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
909 /* loop, another thread own the lock */ ;
910 if (ssl_config_mutex == NULL)
912 if (pthread_mutex_init(&ssl_config_mutex, NULL))
915 InterlockedExchange(&win32_ssl_create_mutex, 0);
918 if (pthread_mutex_lock(&ssl_config_mutex))
921 if (pq_init_crypto_lib)
924 * If necessary, set up an array to hold locks for libcrypto.
925 * libcrypto will tell us how big to make this array.
927 if (pq_lockarray == NULL)
931 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
934 pthread_mutex_unlock(&ssl_config_mutex);
937 for (i = 0; i < CRYPTO_num_locks(); i++)
939 if (pthread_mutex_init(&pq_lockarray[i], NULL))
943 pthread_mutex_unlock(&ssl_config_mutex);
949 if (ssl_open_connections++ == 0)
951 /* These are only required for threaded libcrypto applications */
952 CRYPTO_set_id_callback(pq_threadidcallback);
953 CRYPTO_set_locking_callback(pq_lockingcallback);
956 #endif /* ENABLE_THREAD_SAFETY */
962 #if SSLEAY_VERSION_NUMBER >= 0x00907000L
963 OPENSSL_config(NULL);
966 SSL_load_error_strings();
970 * We use SSLv23_method() because it can negotiate use of the highest
971 * mutually supported protocol version, while alternatives like
972 * TLSv1_2_method() permit only one specific version. Note that we
973 * don't actually allow SSL v2 or v3, only TLS protocols (see below).
975 SSL_context = SSL_CTX_new(SSLv23_method());
978 char *err = SSLerrmessage();
980 printfPQExpBuffer(&conn->errorMessage,
981 libpq_gettext("could not create SSL context: %s\n"),
984 #ifdef ENABLE_THREAD_SAFETY
985 pthread_mutex_unlock(&ssl_config_mutex);
990 /* Disable old protocol versions */
991 SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
994 * Disable OpenSSL's moving-write-buffer sanity check, because it
995 * causes unnecessary failures in nonblocking send cases.
997 SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1000 #ifdef ENABLE_THREAD_SAFETY
1001 pthread_mutex_unlock(&ssl_config_mutex);
1007 * This function is needed because if the libpq library is unloaded
1008 * from the application, the callback functions will no longer exist when
1009 * libcrypto is used by other parts of the system. For this reason,
1010 * we unregister the callback functions when the last libpq
1011 * connection is closed. (The same would apply for OpenSSL callbacks
1014 * Callbacks are only set when we're compiled in threadsafe mode, so
1015 * we only need to remove them in this case.
1018 destroy_ssl_system(void)
1020 #ifdef ENABLE_THREAD_SAFETY
1021 /* Mutex is created in initialize_ssl_system() */
1022 if (pthread_mutex_lock(&ssl_config_mutex))
1025 if (pq_init_crypto_lib && ssl_open_connections > 0)
1026 --ssl_open_connections;
1028 if (pq_init_crypto_lib && ssl_open_connections == 0)
1030 /* No connections left, unregister libcrypto callbacks */
1031 CRYPTO_set_locking_callback(NULL);
1032 CRYPTO_set_id_callback(NULL);
1035 * We don't free the lock array or the SSL_context. If we get another
1036 * connection in this process, we will just re-use them with the
1039 * This means we leak a little memory on repeated load/unload of the
1044 pthread_mutex_unlock(&ssl_config_mutex);
1049 * Initialize (potentially) per-connection SSL data, namely the
1050 * client certificate, private key, and trusted CA certs.
1052 * conn->ssl must already be created. It receives the connection's client
1053 * certificate and private key. Note however that certificates also get
1054 * loaded into the SSL_context object, and are therefore accessible to all
1055 * connections in this process. This should be OK as long as there aren't
1056 * any hash collisions among the certs.
1058 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
1061 initialize_SSL(PGconn *conn)
1064 char homedir[MAXPGPATH];
1065 char fnbuf[MAXPGPATH];
1069 EVP_PKEY *pkey = NULL;
1072 * We'll need the home directory if any of the relevant parameters are
1073 * defaulted. If pqGetHomeDirectory fails, act as though none of the
1074 * files could be found.
1076 if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
1077 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
1078 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
1079 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
1080 have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
1081 else /* won't need it */
1082 have_homedir = false;
1084 /* Read the client certificate file */
1085 if (conn->sslcert && strlen(conn->sslcert) > 0)
1086 strncpy(fnbuf, conn->sslcert, sizeof(fnbuf));
1087 else if (have_homedir)
1088 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
1092 if (fnbuf[0] == '\0')
1094 /* no home directory, proceed without a client cert */
1097 else if (stat(fnbuf, &buf) != 0)
1100 * If file is not present, just go on without a client cert; server
1101 * might or might not accept the connection. Any other error,
1102 * however, is grounds for complaint.
1104 if (errno != ENOENT && errno != ENOTDIR)
1106 printfPQExpBuffer(&conn->errorMessage,
1107 libpq_gettext("could not open certificate file \"%s\": %s\n"),
1108 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
1116 * Cert file exists, so load it. Since OpenSSL doesn't provide the
1117 * equivalent of "SSL_use_certificate_chain_file", we actually have to
1118 * load the file twice. The first call loads any extra certs after
1119 * the first one into chain-cert storage associated with the
1120 * SSL_context. The second call loads the first cert (only) into the
1121 * SSL object, where it will be correctly paired with the private key
1122 * we load below. We do it this way so that each connection
1123 * understands which subject cert to present, in case different
1124 * sslcert settings are used for different connections in the same
1127 * NOTE: This function may also modify our SSL_context and therefore
1128 * we have to lock around this call and any places where we use the
1129 * SSL_context struct.
1131 #ifdef ENABLE_THREAD_SAFETY
1134 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
1136 printfPQExpBuffer(&conn->errorMessage,
1137 libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
1141 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1143 char *err = SSLerrmessage();
1145 printfPQExpBuffer(&conn->errorMessage,
1146 libpq_gettext("could not read certificate file \"%s\": %s\n"),
1150 #ifdef ENABLE_THREAD_SAFETY
1151 pthread_mutex_unlock(&ssl_config_mutex);
1156 if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1158 char *err = SSLerrmessage();
1160 printfPQExpBuffer(&conn->errorMessage,
1161 libpq_gettext("could not read certificate file \"%s\": %s\n"),
1164 #ifdef ENABLE_THREAD_SAFETY
1165 pthread_mutex_unlock(&ssl_config_mutex);
1170 /* need to load the associated private key, too */
1173 #ifdef ENABLE_THREAD_SAFETY
1174 pthread_mutex_unlock(&ssl_config_mutex);
1179 * Read the SSL key. If a key is specified, treat it as an engine:key
1180 * combination if there is colon present - we don't support files with
1181 * colon in the name. The exception is if the second character is a colon,
1182 * in which case it can be a Windows filename with drive specification.
1184 if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1186 #ifdef USE_SSL_ENGINE
1187 if (strchr(conn->sslkey, ':')
1189 && conn->sslkey[1] != ':'
1193 /* Colon, but not in second character, treat as engine:key */
1194 char *engine_str = strdup(conn->sslkey);
1197 if (engine_str == NULL)
1199 printfPQExpBuffer(&conn->errorMessage,
1200 libpq_gettext("out of memory\n"));
1204 /* cannot return NULL because we already checked before strdup */
1205 engine_colon = strchr(engine_str, ':');
1207 *engine_colon = '\0'; /* engine_str now has engine name */
1208 engine_colon++; /* engine_colon now has key name */
1210 conn->engine = ENGINE_by_id(engine_str);
1211 if (conn->engine == NULL)
1213 char *err = SSLerrmessage();
1215 printfPQExpBuffer(&conn->errorMessage,
1216 libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1223 if (ENGINE_init(conn->engine) == 0)
1225 char *err = SSLerrmessage();
1227 printfPQExpBuffer(&conn->errorMessage,
1228 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1231 ENGINE_free(conn->engine);
1232 conn->engine = NULL;
1237 pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1241 char *err = SSLerrmessage();
1243 printfPQExpBuffer(&conn->errorMessage,
1244 libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1245 engine_colon, engine_str, err);
1247 ENGINE_finish(conn->engine);
1248 ENGINE_free(conn->engine);
1249 conn->engine = NULL;
1253 if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1255 char *err = SSLerrmessage();
1257 printfPQExpBuffer(&conn->errorMessage,
1258 libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1259 engine_colon, engine_str, err);
1261 ENGINE_finish(conn->engine);
1262 ENGINE_free(conn->engine);
1263 conn->engine = NULL;
1270 fnbuf[0] = '\0'; /* indicate we're not going to load from a
1274 #endif /* USE_SSL_ENGINE */
1276 /* PGSSLKEY is not an engine, treat it as a filename */
1277 strncpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1280 else if (have_homedir)
1282 /* No PGSSLKEY specified, load default file */
1283 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1288 if (have_cert && fnbuf[0] != '\0')
1290 /* read the client key from file */
1292 if (stat(fnbuf, &buf) != 0)
1294 printfPQExpBuffer(&conn->errorMessage,
1295 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1300 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1302 printfPQExpBuffer(&conn->errorMessage,
1303 libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1309 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1311 char *err = SSLerrmessage();
1313 printfPQExpBuffer(&conn->errorMessage,
1314 libpq_gettext("could not load private key file \"%s\": %s\n"),
1321 /* verify that the cert and key go together */
1323 SSL_check_private_key(conn->ssl) != 1)
1325 char *err = SSLerrmessage();
1327 printfPQExpBuffer(&conn->errorMessage,
1328 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1335 * If the root cert file exists, load it so we can perform certificate
1336 * verification. If sslmode is "verify-full" we will also do further
1337 * verification after the connection has been completed.
1339 if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1340 strncpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1341 else if (have_homedir)
1342 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1346 if (fnbuf[0] != '\0' &&
1347 stat(fnbuf, &buf) == 0)
1349 X509_STORE *cvstore;
1351 #ifdef ENABLE_THREAD_SAFETY
1354 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
1356 printfPQExpBuffer(&conn->errorMessage,
1357 libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
1361 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1363 char *err = SSLerrmessage();
1365 printfPQExpBuffer(&conn->errorMessage,
1366 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1369 #ifdef ENABLE_THREAD_SAFETY
1370 pthread_mutex_unlock(&ssl_config_mutex);
1375 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1377 if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1378 strncpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
1379 else if (have_homedir)
1380 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1384 /* Set the flags to check against the complete CRL chain */
1385 if (fnbuf[0] != '\0' &&
1386 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
1388 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
1389 #ifdef X509_V_FLAG_CRL_CHECK
1390 X509_STORE_set_flags(cvstore,
1391 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1393 char *err = SSLerrmessage();
1395 printfPQExpBuffer(&conn->errorMessage,
1396 libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
1399 #ifdef ENABLE_THREAD_SAFETY
1400 pthread_mutex_unlock(&ssl_config_mutex);
1405 /* if not found, silently ignore; we do not require CRL */
1407 #ifdef ENABLE_THREAD_SAFETY
1408 pthread_mutex_unlock(&ssl_config_mutex);
1411 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1416 * stat() failed; assume root file doesn't exist. If sslmode is
1417 * verify-ca or verify-full, this is an error. Otherwise, continue
1418 * without performing any server cert verification.
1420 if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1423 * The only way to reach here with an empty filename is if
1424 * pqGetHomeDirectory failed. That's a sufficiently unusual case
1425 * that it seems worth having a specialized error message for it.
1427 if (fnbuf[0] == '\0')
1428 printfPQExpBuffer(&conn->errorMessage,
1429 libpq_gettext("could not get home directory to locate root certificate file\n"
1430 "Either provide the file or change sslmode to disable server certificate verification.\n"));
1432 printfPQExpBuffer(&conn->errorMessage,
1433 libpq_gettext("root certificate file \"%s\" does not exist\n"
1434 "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1440 * If the OpenSSL version used supports it (from 1.0.0 on) and the user
1441 * requested it, disable SSL compression.
1443 #ifdef SSL_OP_NO_COMPRESSION
1444 if (conn->sslcompression && conn->sslcompression[0] == '0')
1446 SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1456 destroy_ssl_system();
1460 * Attempt to negotiate SSL connection.
1462 static PostgresPollingStatusType
1463 open_client_SSL(PGconn *conn)
1467 r = SSL_connect(conn->ssl);
1470 int err = SSL_get_error(conn->ssl, r);
1474 case SSL_ERROR_WANT_READ:
1475 return PGRES_POLLING_READING;
1477 case SSL_ERROR_WANT_WRITE:
1478 return PGRES_POLLING_WRITING;
1480 case SSL_ERROR_SYSCALL:
1485 printfPQExpBuffer(&conn->errorMessage,
1486 libpq_gettext("SSL SYSCALL error: %s\n"),
1487 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1489 printfPQExpBuffer(&conn->errorMessage,
1490 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1492 return PGRES_POLLING_FAILED;
1496 char *err = SSLerrmessage();
1498 printfPQExpBuffer(&conn->errorMessage,
1499 libpq_gettext("SSL error: %s\n"),
1503 return PGRES_POLLING_FAILED;
1507 printfPQExpBuffer(&conn->errorMessage,
1508 libpq_gettext("unrecognized SSL error code: %d\n"),
1511 return PGRES_POLLING_FAILED;
1516 * We already checked the server certificate in initialize_SSL() using
1517 * SSL_CTX_set_verify(), if root.crt exists.
1520 /* get server certificate */
1521 conn->peer = SSL_get_peer_certificate(conn->ssl);
1522 if (conn->peer == NULL)
1524 char *err = SSLerrmessage();
1526 printfPQExpBuffer(&conn->errorMessage,
1527 libpq_gettext("certificate could not be obtained: %s\n"),
1531 return PGRES_POLLING_FAILED;
1534 if (!verify_peer_name_matches_certificate(conn))
1537 return PGRES_POLLING_FAILED;
1540 /* SSL handshake is complete */
1541 return PGRES_POLLING_OK;
1545 * Close SSL connection.
1548 close_SSL(PGconn *conn)
1550 bool destroy_needed = false;
1554 DECLARE_SIGPIPE_INFO(spinfo);
1557 * We can't destroy everything SSL-related here due to the possible
1558 * later calls to OpenSSL routines which may need our thread
1559 * callbacks, so set a flag here and check at the end.
1561 destroy_needed = true;
1563 DISABLE_SIGPIPE(conn, spinfo, (void) 0);
1564 SSL_shutdown(conn->ssl);
1565 SSL_free(conn->ssl);
1567 /* We have to assume we got EPIPE */
1568 REMEMBER_EPIPE(spinfo, true);
1569 RESTORE_SIGPIPE(conn, spinfo);
1574 X509_free(conn->peer);
1578 #ifdef USE_SSL_ENGINE
1581 ENGINE_finish(conn->engine);
1582 ENGINE_free(conn->engine);
1583 conn->engine = NULL;
1588 * This will remove our SSL locking hooks, if this is the last SSL
1589 * connection, which means we must wait to call it until after all
1590 * SSL calls have been made, otherwise we can end up with a race
1591 * condition and possible deadlocks.
1593 * See comments above destroy_ssl_system().
1600 * Obtain reason string for last SSL error
1602 * Some caution is needed here since ERR_reason_error_string will
1603 * return NULL if it doesn't recognize the error code. We don't
1604 * want to return NULL ever.
1606 static char ssl_nomem[] = "out of memory allocating error description";
1608 #define SSL_ERR_LEN 128
1613 unsigned long errcode;
1614 const char *errreason;
1617 errbuf = malloc(SSL_ERR_LEN);
1620 errcode = ERR_get_error();
1623 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1626 errreason = ERR_reason_error_string(errcode);
1627 if (errreason != NULL)
1629 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1632 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
1637 SSLerrfree(char *buf)
1639 if (buf != ssl_nomem)
1644 * Return pointer to OpenSSL object.
1647 PQgetssl(PGconn *conn)
1653 #else /* !USE_SSL */
1656 PQgetssl(PGconn *conn)
1660 #endif /* USE_SSL */
1663 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
1666 * Block SIGPIPE for this thread. This prevents send()/write() from exiting
1670 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1672 sigset_t sigpipe_sigset;
1675 sigemptyset(&sigpipe_sigset);
1676 sigaddset(&sigpipe_sigset, SIGPIPE);
1678 /* Block SIGPIPE and save previous mask for later reset */
1679 SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
1683 /* We can have a pending SIGPIPE only if it was blocked before */
1684 if (sigismember(osigset, SIGPIPE))
1686 /* Is there a pending SIGPIPE? */
1687 if (sigpending(&sigset) != 0)
1690 if (sigismember(&sigset, SIGPIPE))
1691 *sigpipe_pending = true;
1693 *sigpipe_pending = false;
1696 *sigpipe_pending = false;
1702 * Discard any pending SIGPIPE and reset the signal mask.
1704 * Note: we are effectively assuming here that the C library doesn't queue
1705 * up multiple SIGPIPE events. If it did, then we'd accidentally leave
1706 * ours in the queue when an event was already pending and we got another.
1707 * As long as it doesn't queue multiple events, we're OK because the caller
1708 * can't tell the difference.
1710 * The caller should say got_epipe = FALSE if it is certain that it
1711 * didn't get an EPIPE error; in that case we'll skip the clear operation
1712 * and things are definitely OK, queuing or no. If it got one or might have
1713 * gotten one, pass got_epipe = TRUE.
1715 * We do not want this to change errno, since if it did that could lose
1716 * the error code from a preceding send(). We essentially assume that if
1717 * we were able to do pq_block_sigpipe(), this can't fail.
1720 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1722 int save_errno = SOCK_ERRNO;
1726 /* Clear SIGPIPE only if none was pending */
1727 if (got_epipe && !sigpipe_pending)
1729 if (sigpending(&sigset) == 0 &&
1730 sigismember(&sigset, SIGPIPE))
1732 sigset_t sigpipe_sigset;
1734 sigemptyset(&sigpipe_sigset);
1735 sigaddset(&sigpipe_sigset, SIGPIPE);
1737 sigwait(&sigpipe_sigset, &signo);
1741 /* Restore saved block mask */
1742 pthread_sigmask(SIG_SETMASK, osigset, NULL);
1744 SOCK_ERRNO_SET(save_errno);
1747 #endif /* ENABLE_THREAD_SAFETY && !WIN32 */