1 /*-------------------------------------------------------------------------
7 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * src/interfaces/libpq/fe-secure-openssl.c
16 * We don't provide informational callbacks here (like
17 * info_cb() in be-secure.c), since there's no good mechanism to
18 * display such information to the user.
20 *-------------------------------------------------------------------------
23 #include "postgres_fe.h"
31 #include "libpq-int.h"
36 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #ifdef HAVE_NETINET_TCP_H
41 #include <netinet/tcp.h>
43 #include <arpa/inet.h>
48 #ifdef ENABLE_THREAD_SAFETY
50 #include "pthread-win32.h"
56 #include <openssl/ssl.h>
57 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L)
58 #include <openssl/conf.h>
61 #include <openssl/engine.h>
63 #include <openssl/x509v3.h>
65 static bool verify_peer_name_matches_certificate(PGconn *);
66 static int verify_cb(int ok, X509_STORE_CTX *ctx);
67 static int verify_peer_name_matches_certificate_name(PGconn *conn,
70 static void destroy_ssl_system(void);
71 static int initialize_SSL(PGconn *conn);
72 static PostgresPollingStatusType open_client_SSL(PGconn *);
73 static char *SSLerrmessage(void);
74 static void SSLerrfree(char *buf);
76 static int my_sock_read(BIO *h, char *buf, int size);
77 static int my_sock_write(BIO *h, const char *buf, int size);
78 static BIO_METHOD *my_BIO_s_socket(void);
79 static int my_SSL_set_fd(PGconn *conn, int fd);
82 static bool pq_init_ssl_lib = true;
83 static bool pq_init_crypto_lib = true;
86 * SSL_context is currently shared between threads and therefore we need to be
87 * careful to lock around any usage of it when providing thread safety.
88 * ssl_config_mutex is the mutex that we use to protect it.
90 static SSL_CTX *SSL_context = NULL;
92 #ifdef ENABLE_THREAD_SAFETY
93 static long ssl_open_connections = 0;
96 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
98 static pthread_mutex_t ssl_config_mutex = NULL;
99 static long win32_ssl_create_mutex = 0;
101 #endif /* ENABLE_THREAD_SAFETY */
104 /* ------------------------------------------------------------ */
105 /* Procedures common to all secure sessions */
106 /* ------------------------------------------------------------ */
109 * Exported function to allow application to tell us it's already
110 * initialized OpenSSL and/or libcrypto.
113 pgtls_init_library(bool do_ssl, int do_crypto)
115 #ifdef ENABLE_THREAD_SAFETY
118 * Disallow changing the flags while we have open connections, else we'd
119 * get completely confused.
121 if (ssl_open_connections != 0)
125 pq_init_ssl_lib = do_ssl;
126 pq_init_crypto_lib = do_crypto;
130 * Begin or continue negotiating a secure session.
132 PostgresPollingStatusType
133 pgtls_open_client(PGconn *conn)
135 /* First time through? */
136 if (conn->ssl == NULL)
138 #ifdef ENABLE_THREAD_SAFETY
142 #ifdef ENABLE_THREAD_SAFETY
143 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
145 printfPQExpBuffer(&conn->errorMessage,
146 libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
147 return PGRES_POLLING_FAILED;
150 /* Create a connection-specific SSL object */
151 if (!(conn->ssl = SSL_new(SSL_context)) ||
152 !SSL_set_app_data(conn->ssl, conn) ||
153 !my_SSL_set_fd(conn, conn->sock))
155 char *err = SSLerrmessage();
157 printfPQExpBuffer(&conn->errorMessage,
158 libpq_gettext("could not establish SSL connection: %s\n"),
161 #ifdef ENABLE_THREAD_SAFETY
162 pthread_mutex_unlock(&ssl_config_mutex);
166 return PGRES_POLLING_FAILED;
168 conn->ssl_in_use = true;
170 #ifdef ENABLE_THREAD_SAFETY
171 pthread_mutex_unlock(&ssl_config_mutex);
175 * Load client certificate, private key, and trusted CA certs.
177 if (initialize_SSL(conn) != 0)
179 /* initialize_SSL already put a message in conn->errorMessage */
181 return PGRES_POLLING_FAILED;
185 /* Begin or continue the actual handshake */
186 return open_client_SSL(conn);
190 * Is there unread data waiting in the SSL read buffer?
193 pgtls_read_pending(PGconn *conn)
195 return SSL_pending(conn->ssl);
199 * Read data from a secure connection.
201 * On failure, this function is responsible for putting a suitable message
202 * into conn->errorMessage. The caller must still inspect errno, but only
203 * to determine whether to continue/retry after error.
206 pgtls_read(PGconn *conn, void *ptr, size_t len)
209 int result_errno = 0;
215 n = SSL_read(conn->ssl, ptr, len);
216 err = SSL_get_error(conn->ssl, n);
222 /* Not supposed to happen, so we don't translate the msg */
223 printfPQExpBuffer(&conn->errorMessage,
224 "SSL_read failed but did not provide error information\n");
225 /* assume the connection is broken */
226 result_errno = ECONNRESET;
229 case SSL_ERROR_WANT_READ:
232 case SSL_ERROR_WANT_WRITE:
235 * Returning 0 here would cause caller to wait for read-ready,
236 * which is not correct since what SSL wants is wait for
237 * write-ready. The former could get us stuck in an infinite
238 * wait, so don't risk it; busy-loop instead.
241 case SSL_ERROR_SYSCALL:
244 result_errno = SOCK_ERRNO;
245 if (result_errno == EPIPE ||
246 result_errno == ECONNRESET)
247 printfPQExpBuffer(&conn->errorMessage,
249 "server closed the connection unexpectedly\n"
250 "\tThis probably means the server terminated abnormally\n"
251 "\tbefore or while processing the request.\n"));
253 printfPQExpBuffer(&conn->errorMessage,
254 libpq_gettext("SSL SYSCALL error: %s\n"),
255 SOCK_STRERROR(result_errno,
256 sebuf, sizeof(sebuf)));
260 printfPQExpBuffer(&conn->errorMessage,
261 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
262 /* assume the connection is broken */
263 result_errno = ECONNRESET;
269 char *errm = SSLerrmessage();
271 printfPQExpBuffer(&conn->errorMessage,
272 libpq_gettext("SSL error: %s\n"), errm);
274 /* assume the connection is broken */
275 result_errno = ECONNRESET;
279 case SSL_ERROR_ZERO_RETURN:
282 * Per OpenSSL documentation, this error code is only returned for
283 * a clean connection closure, so we should not report it as a
286 printfPQExpBuffer(&conn->errorMessage,
287 libpq_gettext("SSL connection has been closed unexpectedly\n"));
288 result_errno = ECONNRESET;
292 printfPQExpBuffer(&conn->errorMessage,
293 libpq_gettext("unrecognized SSL error code: %d\n"),
295 /* assume the connection is broken */
296 result_errno = ECONNRESET;
301 /* ensure we return the intended errno to caller */
302 SOCK_ERRNO_SET(result_errno);
308 * Write data to a secure connection.
310 * On failure, this function is responsible for putting a suitable message
311 * into conn->errorMessage. The caller must still inspect errno, but only
312 * to determine whether to continue/retry after error.
315 pgtls_write(PGconn *conn, const void *ptr, size_t len)
318 int result_errno = 0;
323 n = SSL_write(conn->ssl, ptr, len);
324 err = SSL_get_error(conn->ssl, n);
330 /* Not supposed to happen, so we don't translate the msg */
331 printfPQExpBuffer(&conn->errorMessage,
332 "SSL_write failed but did not provide error information\n");
333 /* assume the connection is broken */
334 result_errno = ECONNRESET;
337 case SSL_ERROR_WANT_READ:
340 * Returning 0 here causes caller to wait for write-ready, which
341 * is not really the right thing, but it's the best we can do.
345 case SSL_ERROR_WANT_WRITE:
348 case SSL_ERROR_SYSCALL:
351 result_errno = SOCK_ERRNO;
352 if (result_errno == EPIPE || result_errno == ECONNRESET)
353 printfPQExpBuffer(&conn->errorMessage,
355 "server closed the connection unexpectedly\n"
356 "\tThis probably means the server terminated abnormally\n"
357 "\tbefore or while processing the request.\n"));
359 printfPQExpBuffer(&conn->errorMessage,
360 libpq_gettext("SSL SYSCALL error: %s\n"),
361 SOCK_STRERROR(result_errno,
362 sebuf, sizeof(sebuf)));
366 printfPQExpBuffer(&conn->errorMessage,
367 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
368 /* assume the connection is broken */
369 result_errno = ECONNRESET;
375 char *errm = SSLerrmessage();
377 printfPQExpBuffer(&conn->errorMessage,
378 libpq_gettext("SSL error: %s\n"), errm);
380 /* assume the connection is broken */
381 result_errno = ECONNRESET;
385 case SSL_ERROR_ZERO_RETURN:
388 * Per OpenSSL documentation, this error code is only returned for
389 * a clean connection closure, so we should not report it as a
392 printfPQExpBuffer(&conn->errorMessage,
393 libpq_gettext("SSL connection has been closed unexpectedly\n"));
394 result_errno = ECONNRESET;
398 printfPQExpBuffer(&conn->errorMessage,
399 libpq_gettext("unrecognized SSL error code: %d\n"),
401 /* assume the connection is broken */
402 result_errno = ECONNRESET;
407 /* ensure we return the intended errno to caller */
408 SOCK_ERRNO_SET(result_errno);
413 /* ------------------------------------------------------------ */
414 /* OpenSSL specific code */
415 /* ------------------------------------------------------------ */
418 * Certificate verification callback
420 * This callback allows us to log intermediate problems during
421 * verification, but there doesn't seem to be a clean way to get
422 * our PGconn * structure. So we can't log anything!
424 * This callback also allows us to override the default acceptance
425 * criteria (e.g., accepting self-signed or expired certs), but
426 * for now we accept the default checks.
429 verify_cb(int ok, X509_STORE_CTX *ctx)
436 * Check if a wildcard certificate matches the server hostname.
438 * The rule for this is:
439 * 1. We only match the '*' character as wildcard
440 * 2. We match only wildcards at the start of the string
441 * 3. The '*' character does *not* match '.', meaning that we match only
442 * a single pathname component.
443 * 4. We don't support more than one '*' in a single pattern.
445 * This is roughly in line with RFC2818, but contrary to what most browsers
446 * appear to be implementing (point 3 being the difference)
448 * Matching is always case-insensitive, since DNS is case insensitive.
451 wildcard_certificate_match(const char *pattern, const char *string)
453 int lenpat = strlen(pattern);
454 int lenstr = strlen(string);
456 /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
463 /* If pattern is longer than the string, we can never match */
466 if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
469 * If string does not end in pattern (minus the wildcard), we don't
474 if (strchr(string, '.') < string + lenstr - lenpat)
477 * If there is a dot left of where the pattern started to match, we
478 * don't match (rule 3)
482 /* String ended with pattern, and didn't have a dot before, so we match */
488 * Check if a name from a server's certificate matches the peer's hostname.
490 * Returns 1 if the name matches, and 0 if it does not. On error, returns
491 * -1, and sets the libpq error message.
493 * The name extracted from the certificate is returned in *store_name. The
494 * caller is responsible for freeing it.
497 verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
502 unsigned char *namedata;
507 /* Should not happen... */
508 if (name_entry == NULL)
510 printfPQExpBuffer(&conn->errorMessage,
511 libpq_gettext("SSL certificate's name entry is missing\n"));
516 * GEN_DNS can be only IA5String, equivalent to US ASCII.
518 * There is no guarantee the string returned from the certificate is
519 * NULL-terminated, so make a copy that is.
521 namedata = ASN1_STRING_data(name_entry);
522 len = ASN1_STRING_length(name_entry);
523 name = malloc(len + 1);
526 printfPQExpBuffer(&conn->errorMessage,
527 libpq_gettext("out of memory\n"));
530 memcpy(name, namedata, len);
534 * Reject embedded NULLs in certificate common or alternative name to
535 * prevent attacks like CVE-2009-4034.
537 if (len != strlen(name))
540 printfPQExpBuffer(&conn->errorMessage,
541 libpq_gettext("SSL certificate's name contains embedded null\n"));
545 if (pg_strcasecmp(name, conn->pghost) == 0)
547 /* Exact name match */
550 else if (wildcard_certificate_match(name, conn->pghost))
552 /* Matched wildcard name */
565 * Verify that the server certificate matches the hostname we connected to.
567 * The certificate's Common Name and Subject Alternative Names are considered.
570 verify_peer_name_matches_certificate(PGconn *conn)
572 int names_examined = 0;
573 bool found_match = false;
574 bool got_error = false;
575 char *first_name = NULL;
577 STACK_OF(GENERAL_NAME) *peer_san;
582 * If told not to verify the peer name, don't do it. Return true
583 * indicating that the verification was successful.
585 if (strcmp(conn->sslmode, "verify-full") != 0)
588 /* Check that we have a hostname to compare with. */
589 if (!(conn->pghost && conn->pghost[0] != '\0'))
591 printfPQExpBuffer(&conn->errorMessage,
592 libpq_gettext("host name must be specified for a verified SSL connection\n"));
597 * First, get the Subject Alternative Names (SANs) from the certificate,
598 * and compare them against the originally given hostname.
600 peer_san = (STACK_OF(GENERAL_NAME) *)
601 X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
605 int san_len = sk_GENERAL_NAME_num(peer_san);
607 for (i = 0; i < san_len; i++)
609 const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
611 if (name->type == GEN_DNS)
616 rc = verify_peer_name_matches_certificate_name(conn,
627 first_name = alt_name;
632 if (found_match || got_error)
635 sk_GENERAL_NAME_free(peer_san);
639 * If there is no subjectAltName extension of type dNSName, check the
642 * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
643 * dNSName is present, the CN must be ignored.)
645 if (names_examined == 0)
647 X509_NAME *subject_name;
649 subject_name = X509_get_subject_name(conn->peer);
650 if (subject_name != NULL)
654 cn_index = X509_NAME_get_index_by_NID(subject_name,
659 rc = verify_peer_name_matches_certificate_name(
661 X509_NAME_ENTRY_get_data(
662 X509_NAME_get_entry(subject_name, cn_index)),
673 if (!found_match && !got_error)
676 * No match. Include the name from the server certificate in the error
677 * message, to aid debugging broken configurations. If there are
678 * multiple names, only print the first one to avoid an overly long
681 if (names_examined > 1)
683 printfPQExpBuffer(&conn->errorMessage,
684 libpq_ngettext("server certificate for \"%s\" (and %d other name) does not match host name \"%s\"\n",
685 "server certificate for \"%s\" (and %d other names) does not match host name \"%s\"\n",
687 first_name, names_examined - 1, conn->pghost);
689 else if (names_examined == 1)
691 printfPQExpBuffer(&conn->errorMessage,
692 libpq_gettext("server certificate for \"%s\" does not match host name \"%s\"\n"),
693 first_name, conn->pghost);
697 printfPQExpBuffer(&conn->errorMessage,
698 libpq_gettext("could not get server's host name from server certificate\n"));
706 return found_match && !got_error;
709 #ifdef ENABLE_THREAD_SAFETY
711 * Callback functions for OpenSSL internal locking
715 pq_threadidcallback(void)
718 * This is not standards-compliant. pthread_self() returns pthread_t, and
719 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
720 * it, so we have to do it.
722 return (unsigned long) pthread_self();
725 static pthread_mutex_t *pq_lockarray;
728 pq_lockingcallback(int mode, int n, const char *file, int line)
730 if (mode & CRYPTO_LOCK)
732 if (pthread_mutex_lock(&pq_lockarray[n]))
733 PGTHREAD_ERROR("failed to lock mutex");
737 if (pthread_mutex_unlock(&pq_lockarray[n]))
738 PGTHREAD_ERROR("failed to unlock mutex");
741 #endif /* ENABLE_THREAD_SAFETY */
744 * Initialize SSL system, in particular creating the SSL_context object
745 * that will be shared by all SSL-using connections in this process.
747 * In threadsafe mode, this includes setting up libcrypto callback functions
748 * to do thread locking.
750 * If the caller has told us (through PQinitOpenSSL) that he's taking care
751 * of libcrypto, we expect that callbacks are already set, and won't try to
754 * The conn parameter is only used to be able to pass back an error
755 * message - no connection-local setup is made here.
757 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
760 pgtls_init(PGconn *conn)
762 #ifdef ENABLE_THREAD_SAFETY
764 /* Also see similar code in fe-connect.c, default_threadlock() */
765 if (ssl_config_mutex == NULL)
767 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
768 /* loop, another thread own the lock */ ;
769 if (ssl_config_mutex == NULL)
771 if (pthread_mutex_init(&ssl_config_mutex, NULL))
774 InterlockedExchange(&win32_ssl_create_mutex, 0);
777 if (pthread_mutex_lock(&ssl_config_mutex))
780 if (pq_init_crypto_lib)
783 * If necessary, set up an array to hold locks for libcrypto.
784 * libcrypto will tell us how big to make this array.
786 if (pq_lockarray == NULL)
790 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
793 pthread_mutex_unlock(&ssl_config_mutex);
796 for (i = 0; i < CRYPTO_num_locks(); i++)
798 if (pthread_mutex_init(&pq_lockarray[i], NULL))
802 pthread_mutex_unlock(&ssl_config_mutex);
808 if (ssl_open_connections++ == 0)
811 * These are only required for threaded libcrypto applications,
812 * but make sure we don't stomp on them if they're already set.
814 if (CRYPTO_get_id_callback() == NULL)
815 CRYPTO_set_id_callback(pq_threadidcallback);
816 if (CRYPTO_get_locking_callback() == NULL)
817 CRYPTO_set_locking_callback(pq_lockingcallback);
820 #endif /* ENABLE_THREAD_SAFETY */
826 #if SSLEAY_VERSION_NUMBER >= 0x00907000L
827 OPENSSL_config(NULL);
830 SSL_load_error_strings();
834 * We use SSLv23_method() because it can negotiate use of the highest
835 * mutually supported protocol version, while alternatives like
836 * TLSv1_2_method() permit only one specific version. Note that we
837 * don't actually allow SSL v2 or v3, only TLS protocols (see below).
839 SSL_context = SSL_CTX_new(SSLv23_method());
842 char *err = SSLerrmessage();
844 printfPQExpBuffer(&conn->errorMessage,
845 libpq_gettext("could not create SSL context: %s\n"),
848 #ifdef ENABLE_THREAD_SAFETY
849 pthread_mutex_unlock(&ssl_config_mutex);
854 /* Disable old protocol versions */
855 SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
858 * Disable OpenSSL's moving-write-buffer sanity check, because it
859 * causes unnecessary failures in nonblocking send cases.
861 SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
864 #ifdef ENABLE_THREAD_SAFETY
865 pthread_mutex_unlock(&ssl_config_mutex);
871 * This function is needed because if the libpq library is unloaded
872 * from the application, the callback functions will no longer exist when
873 * libcrypto is used by other parts of the system. For this reason,
874 * we unregister the callback functions when the last libpq
875 * connection is closed. (The same would apply for OpenSSL callbacks
878 * Callbacks are only set when we're compiled in threadsafe mode, so
879 * we only need to remove them in this case.
882 destroy_ssl_system(void)
884 #ifdef ENABLE_THREAD_SAFETY
885 /* Mutex is created in initialize_ssl_system() */
886 if (pthread_mutex_lock(&ssl_config_mutex))
889 if (pq_init_crypto_lib && ssl_open_connections > 0)
890 --ssl_open_connections;
892 if (pq_init_crypto_lib && ssl_open_connections == 0)
895 * No connections left, unregister libcrypto callbacks, if no one
896 * registered different ones in the meantime.
898 if (CRYPTO_get_locking_callback() == pq_lockingcallback)
899 CRYPTO_set_locking_callback(NULL);
900 if (CRYPTO_get_id_callback() == pq_threadidcallback)
901 CRYPTO_set_id_callback(NULL);
904 * We don't free the lock array or the SSL_context. If we get another
905 * connection in this process, we will just re-use them with the
908 * This means we leak a little memory on repeated load/unload of the
913 pthread_mutex_unlock(&ssl_config_mutex);
918 * Initialize (potentially) per-connection SSL data, namely the
919 * client certificate, private key, and trusted CA certs.
921 * conn->ssl must already be created. It receives the connection's client
922 * certificate and private key. Note however that certificates also get
923 * loaded into the SSL_context object, and are therefore accessible to all
924 * connections in this process. This should be OK as long as there aren't
925 * any hash collisions among the certs.
927 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
930 initialize_SSL(PGconn *conn)
933 char homedir[MAXPGPATH];
934 char fnbuf[MAXPGPATH];
938 EVP_PKEY *pkey = NULL;
941 * We'll need the home directory if any of the relevant parameters are
942 * defaulted. If pqGetHomeDirectory fails, act as though none of the
943 * files could be found.
945 if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
946 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
947 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
948 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
949 have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
950 else /* won't need it */
951 have_homedir = false;
953 /* Read the client certificate file */
954 if (conn->sslcert && strlen(conn->sslcert) > 0)
955 strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
956 else if (have_homedir)
957 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
961 if (fnbuf[0] == '\0')
963 /* no home directory, proceed without a client cert */
966 else if (stat(fnbuf, &buf) != 0)
969 * If file is not present, just go on without a client cert; server
970 * might or might not accept the connection. Any other error,
971 * however, is grounds for complaint.
973 if (errno != ENOENT && errno != ENOTDIR)
975 printfPQExpBuffer(&conn->errorMessage,
976 libpq_gettext("could not open certificate file \"%s\": %s\n"),
977 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
985 * Cert file exists, so load it. Since OpenSSL doesn't provide the
986 * equivalent of "SSL_use_certificate_chain_file", we actually have to
987 * load the file twice. The first call loads any extra certs after
988 * the first one into chain-cert storage associated with the
989 * SSL_context. The second call loads the first cert (only) into the
990 * SSL object, where it will be correctly paired with the private key
991 * we load below. We do it this way so that each connection
992 * understands which subject cert to present, in case different
993 * sslcert settings are used for different connections in the same
996 * NOTE: This function may also modify our SSL_context and therefore
997 * we have to lock around this call and any places where we use the
998 * SSL_context struct.
1000 #ifdef ENABLE_THREAD_SAFETY
1003 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
1005 printfPQExpBuffer(&conn->errorMessage,
1006 libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
1010 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1012 char *err = SSLerrmessage();
1014 printfPQExpBuffer(&conn->errorMessage,
1015 libpq_gettext("could not read certificate file \"%s\": %s\n"),
1019 #ifdef ENABLE_THREAD_SAFETY
1020 pthread_mutex_unlock(&ssl_config_mutex);
1025 if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1027 char *err = SSLerrmessage();
1029 printfPQExpBuffer(&conn->errorMessage,
1030 libpq_gettext("could not read certificate file \"%s\": %s\n"),
1033 #ifdef ENABLE_THREAD_SAFETY
1034 pthread_mutex_unlock(&ssl_config_mutex);
1039 /* need to load the associated private key, too */
1042 #ifdef ENABLE_THREAD_SAFETY
1043 pthread_mutex_unlock(&ssl_config_mutex);
1048 * Read the SSL key. If a key is specified, treat it as an engine:key
1049 * combination if there is colon present - we don't support files with
1050 * colon in the name. The exception is if the second character is a colon,
1051 * in which case it can be a Windows filename with drive specification.
1053 if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1055 #ifdef USE_SSL_ENGINE
1056 if (strchr(conn->sslkey, ':')
1058 && conn->sslkey[1] != ':'
1062 /* Colon, but not in second character, treat as engine:key */
1063 char *engine_str = strdup(conn->sslkey);
1066 if (engine_str == NULL)
1068 printfPQExpBuffer(&conn->errorMessage,
1069 libpq_gettext("out of memory\n"));
1073 /* cannot return NULL because we already checked before strdup */
1074 engine_colon = strchr(engine_str, ':');
1076 *engine_colon = '\0'; /* engine_str now has engine name */
1077 engine_colon++; /* engine_colon now has key name */
1079 conn->engine = ENGINE_by_id(engine_str);
1080 if (conn->engine == NULL)
1082 char *err = SSLerrmessage();
1084 printfPQExpBuffer(&conn->errorMessage,
1085 libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1092 if (ENGINE_init(conn->engine) == 0)
1094 char *err = SSLerrmessage();
1096 printfPQExpBuffer(&conn->errorMessage,
1097 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1100 ENGINE_free(conn->engine);
1101 conn->engine = NULL;
1106 pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1110 char *err = SSLerrmessage();
1112 printfPQExpBuffer(&conn->errorMessage,
1113 libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1114 engine_colon, engine_str, err);
1116 ENGINE_finish(conn->engine);
1117 ENGINE_free(conn->engine);
1118 conn->engine = NULL;
1122 if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1124 char *err = SSLerrmessage();
1126 printfPQExpBuffer(&conn->errorMessage,
1127 libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1128 engine_colon, engine_str, err);
1130 ENGINE_finish(conn->engine);
1131 ENGINE_free(conn->engine);
1132 conn->engine = NULL;
1139 fnbuf[0] = '\0'; /* indicate we're not going to load from a
1143 #endif /* USE_SSL_ENGINE */
1145 /* PGSSLKEY is not an engine, treat it as a filename */
1146 strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1149 else if (have_homedir)
1151 /* No PGSSLKEY specified, load default file */
1152 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1157 if (have_cert && fnbuf[0] != '\0')
1159 /* read the client key from file */
1161 if (stat(fnbuf, &buf) != 0)
1163 printfPQExpBuffer(&conn->errorMessage,
1164 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1169 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1171 printfPQExpBuffer(&conn->errorMessage,
1172 libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1178 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1180 char *err = SSLerrmessage();
1182 printfPQExpBuffer(&conn->errorMessage,
1183 libpq_gettext("could not load private key file \"%s\": %s\n"),
1190 /* verify that the cert and key go together */
1192 SSL_check_private_key(conn->ssl) != 1)
1194 char *err = SSLerrmessage();
1196 printfPQExpBuffer(&conn->errorMessage,
1197 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1204 * If the root cert file exists, load it so we can perform certificate
1205 * verification. If sslmode is "verify-full" we will also do further
1206 * verification after the connection has been completed.
1208 if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1209 strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1210 else if (have_homedir)
1211 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1215 if (fnbuf[0] != '\0' &&
1216 stat(fnbuf, &buf) == 0)
1218 X509_STORE *cvstore;
1220 #ifdef ENABLE_THREAD_SAFETY
1223 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
1225 printfPQExpBuffer(&conn->errorMessage,
1226 libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
1230 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1232 char *err = SSLerrmessage();
1234 printfPQExpBuffer(&conn->errorMessage,
1235 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1238 #ifdef ENABLE_THREAD_SAFETY
1239 pthread_mutex_unlock(&ssl_config_mutex);
1244 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1246 if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1247 strlcpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
1248 else if (have_homedir)
1249 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1253 /* Set the flags to check against the complete CRL chain */
1254 if (fnbuf[0] != '\0' &&
1255 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
1257 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
1258 #ifdef X509_V_FLAG_CRL_CHECK
1259 X509_STORE_set_flags(cvstore,
1260 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1262 char *err = SSLerrmessage();
1264 printfPQExpBuffer(&conn->errorMessage,
1265 libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
1268 #ifdef ENABLE_THREAD_SAFETY
1269 pthread_mutex_unlock(&ssl_config_mutex);
1274 /* if not found, silently ignore; we do not require CRL */
1276 #ifdef ENABLE_THREAD_SAFETY
1277 pthread_mutex_unlock(&ssl_config_mutex);
1280 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1285 * stat() failed; assume root file doesn't exist. If sslmode is
1286 * verify-ca or verify-full, this is an error. Otherwise, continue
1287 * without performing any server cert verification.
1289 if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1292 * The only way to reach here with an empty filename is if
1293 * pqGetHomeDirectory failed. That's a sufficiently unusual case
1294 * that it seems worth having a specialized error message for it.
1296 if (fnbuf[0] == '\0')
1297 printfPQExpBuffer(&conn->errorMessage,
1298 libpq_gettext("could not get home directory to locate root certificate file\n"
1299 "Either provide the file or change sslmode to disable server certificate verification.\n"));
1301 printfPQExpBuffer(&conn->errorMessage,
1302 libpq_gettext("root certificate file \"%s\" does not exist\n"
1303 "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1309 * If the OpenSSL version used supports it (from 1.0.0 on) and the user
1310 * requested it, disable SSL compression.
1312 #ifdef SSL_OP_NO_COMPRESSION
1313 if (conn->sslcompression && conn->sslcompression[0] == '0')
1315 SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1323 * Attempt to negotiate SSL connection.
1325 static PostgresPollingStatusType
1326 open_client_SSL(PGconn *conn)
1330 r = SSL_connect(conn->ssl);
1333 int err = SSL_get_error(conn->ssl, r);
1337 case SSL_ERROR_WANT_READ:
1338 return PGRES_POLLING_READING;
1340 case SSL_ERROR_WANT_WRITE:
1341 return PGRES_POLLING_WRITING;
1343 case SSL_ERROR_SYSCALL:
1348 printfPQExpBuffer(&conn->errorMessage,
1349 libpq_gettext("SSL SYSCALL error: %s\n"),
1350 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1352 printfPQExpBuffer(&conn->errorMessage,
1353 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1355 return PGRES_POLLING_FAILED;
1359 char *err = SSLerrmessage();
1361 printfPQExpBuffer(&conn->errorMessage,
1362 libpq_gettext("SSL error: %s\n"),
1366 return PGRES_POLLING_FAILED;
1370 printfPQExpBuffer(&conn->errorMessage,
1371 libpq_gettext("unrecognized SSL error code: %d\n"),
1374 return PGRES_POLLING_FAILED;
1379 * We already checked the server certificate in initialize_SSL() using
1380 * SSL_CTX_set_verify(), if root.crt exists.
1383 /* get server certificate */
1384 conn->peer = SSL_get_peer_certificate(conn->ssl);
1385 if (conn->peer == NULL)
1387 char *err = SSLerrmessage();
1389 printfPQExpBuffer(&conn->errorMessage,
1390 libpq_gettext("certificate could not be obtained: %s\n"),
1394 return PGRES_POLLING_FAILED;
1397 if (!verify_peer_name_matches_certificate(conn))
1400 return PGRES_POLLING_FAILED;
1403 /* SSL handshake is complete */
1404 return PGRES_POLLING_OK;
1408 * Close SSL connection.
1411 pgtls_close(PGconn *conn)
1413 bool destroy_needed = false;
1418 * We can't destroy everything SSL-related here due to the possible
1419 * later calls to OpenSSL routines which may need our thread
1420 * callbacks, so set a flag here and check at the end.
1422 destroy_needed = true;
1424 SSL_shutdown(conn->ssl);
1425 SSL_free(conn->ssl);
1427 conn->ssl_in_use = false;
1432 X509_free(conn->peer);
1436 #ifdef USE_SSL_ENGINE
1439 ENGINE_finish(conn->engine);
1440 ENGINE_free(conn->engine);
1441 conn->engine = NULL;
1446 * This will remove our SSL locking hooks, if this is the last SSL
1447 * connection, which means we must wait to call it until after all SSL
1448 * calls have been made, otherwise we can end up with a race condition and
1449 * possible deadlocks.
1451 * See comments above destroy_ssl_system().
1454 destroy_ssl_system();
1459 * Obtain reason string for last SSL error
1461 * Some caution is needed here since ERR_reason_error_string will
1462 * return NULL if it doesn't recognize the error code. We don't
1463 * want to return NULL ever.
1465 static char ssl_nomem[] = "out of memory allocating error description";
1467 #define SSL_ERR_LEN 128
1472 unsigned long errcode;
1473 const char *errreason;
1476 errbuf = malloc(SSL_ERR_LEN);
1479 errcode = ERR_get_error();
1482 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1485 errreason = ERR_reason_error_string(errcode);
1486 if (errreason != NULL)
1488 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1491 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
1496 SSLerrfree(char *buf)
1498 if (buf != ssl_nomem)
1502 /* ------------------------------------------------------------ */
1503 /* SSL information functions */
1504 /* ------------------------------------------------------------ */
1507 PQsslInUse(PGconn *conn)
1511 return conn->ssl_in_use;
1515 * Return pointer to OpenSSL object.
1518 PQgetssl(PGconn *conn)
1526 PQsslStruct(PGconn *conn, const char *struct_name)
1530 if (strcmp(struct_name, "OpenSSL") == 0)
1536 PQsslAttributeNames(PGconn *conn)
1538 static const char *const result[] = {
1551 PQsslAttribute(PGconn *conn, const char *attribute_name)
1555 if (conn->ssl == NULL)
1558 if (strcmp(attribute_name, "library") == 0)
1561 if (strcmp(attribute_name, "key_bits") == 0)
1563 static char sslbits_str[10];
1566 SSL_get_cipher_bits(conn->ssl, &sslbits);
1567 snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1571 if (strcmp(attribute_name, "cipher") == 0)
1572 return SSL_get_cipher(conn->ssl);
1574 if (strcmp(attribute_name, "compression") == 0)
1575 return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1577 if (strcmp(attribute_name, "protocol") == 0)
1578 return SSL_get_version(conn->ssl);
1580 return NULL; /* unknown attribute */
1584 * Private substitute BIO: this does the sending and receiving using
1585 * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1586 * functions to disable SIGPIPE and give better error messages on I/O errors.
1588 * These functions are closely modelled on the standard socket BIO in OpenSSL;
1589 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1590 * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1591 * to retry; do we need to adopt their logic for that?
1594 static bool my_bio_initialized = false;
1595 static BIO_METHOD my_bio_methods;
1598 my_sock_read(BIO *h, char *buf, int size)
1602 res = pqsecure_raw_read((PGconn *) h->ptr, buf, size);
1603 BIO_clear_retry_flags(h);
1606 /* If we were interrupted, tell caller to retry */
1612 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1616 BIO_set_retry_read(h);
1628 my_sock_write(BIO *h, const char *buf, int size)
1632 res = pqsecure_raw_write((PGconn *) h->ptr, buf, size);
1633 BIO_clear_retry_flags(h);
1636 /* If we were interrupted, tell caller to retry */
1642 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1646 BIO_set_retry_write(h);
1658 my_BIO_s_socket(void)
1660 if (!my_bio_initialized)
1662 memcpy(&my_bio_methods, BIO_s_socket(), sizeof(BIO_METHOD));
1663 my_bio_methods.bread = my_sock_read;
1664 my_bio_methods.bwrite = my_sock_write;
1665 my_bio_initialized = true;
1667 return &my_bio_methods;
1670 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
1672 my_SSL_set_fd(PGconn *conn, int fd)
1677 bio = BIO_new(my_BIO_s_socket());
1680 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1683 /* Use 'ptr' to store pointer to PGconn */
1686 SSL_set_bio(conn->ssl, bio, bio);
1687 BIO_set_fd(bio, fd, BIO_NOCLOSE);