1 /*-------------------------------------------------------------------------
7 * Portions Copyright (c) 1996-2018, 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 #include <openssl/conf.h>
59 #include <openssl/engine.h>
61 #include <openssl/x509v3.h>
63 static bool verify_peer_name_matches_certificate(PGconn *);
64 static int verify_cb(int ok, X509_STORE_CTX *ctx);
65 static int verify_peer_name_matches_certificate_name(PGconn *conn,
68 static void destroy_ssl_system(void);
69 static int initialize_SSL(PGconn *conn);
70 static PostgresPollingStatusType open_client_SSL(PGconn *);
71 static char *SSLerrmessage(unsigned long ecode);
72 static void SSLerrfree(char *buf);
74 static int my_sock_read(BIO *h, char *buf, int size);
75 static int my_sock_write(BIO *h, const char *buf, int size);
76 static BIO_METHOD *my_BIO_s_socket(void);
77 static int my_SSL_set_fd(PGconn *conn, int fd);
80 static bool pq_init_ssl_lib = true;
81 static bool pq_init_crypto_lib = true;
83 static bool ssl_lib_initialized = false;
85 #ifdef ENABLE_THREAD_SAFETY
86 static long ssl_open_connections = 0;
89 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
91 static pthread_mutex_t ssl_config_mutex = NULL;
92 static long win32_ssl_create_mutex = 0;
94 #endif /* ENABLE_THREAD_SAFETY */
97 /* ------------------------------------------------------------ */
98 /* Procedures common to all secure sessions */
99 /* ------------------------------------------------------------ */
102 * Exported function to allow application to tell us it's already
103 * initialized OpenSSL and/or libcrypto.
106 pgtls_init_library(bool do_ssl, int do_crypto)
108 #ifdef ENABLE_THREAD_SAFETY
111 * Disallow changing the flags while we have open connections, else we'd
112 * get completely confused.
114 if (ssl_open_connections != 0)
118 pq_init_ssl_lib = do_ssl;
119 pq_init_crypto_lib = do_crypto;
123 * Begin or continue negotiating a secure session.
125 PostgresPollingStatusType
126 pgtls_open_client(PGconn *conn)
128 /* First time through? */
129 if (conn->ssl == NULL)
132 * Create a connection-specific SSL object, and load client
133 * certificate, private key, and trusted CA certs.
135 if (initialize_SSL(conn) != 0)
137 /* initialize_SSL already put a message in conn->errorMessage */
139 return PGRES_POLLING_FAILED;
143 /* Begin or continue the actual handshake */
144 return open_client_SSL(conn);
148 * Is there unread data waiting in the SSL read buffer?
151 pgtls_read_pending(PGconn *conn)
153 return SSL_pending(conn->ssl);
157 * Read data from a secure connection.
159 * On failure, this function is responsible for putting a suitable message
160 * into conn->errorMessage. The caller must still inspect errno, but only
161 * to determine whether to continue/retry after error.
164 pgtls_read(PGconn *conn, void *ptr, size_t len)
167 int result_errno = 0;
175 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
176 * queue. In general, the current thread's error queue must be empty
177 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
178 * not work reliably. Since the possibility exists that other OpenSSL
179 * clients running in the same thread but not under our control will fail
180 * to call ERR_get_error() themselves (after their own I/O operations),
181 * pro-actively clear the per-thread error queue now.
185 n = SSL_read(conn->ssl, ptr, len);
186 err = SSL_get_error(conn->ssl, n);
189 * Other clients of OpenSSL may fail to call ERR_get_error(), but we
190 * always do, so as to not cause problems for OpenSSL clients that don't
191 * call ERR_clear_error() defensively. Be sure that this happens by
192 * calling now. SSL_get_error() relies on the OpenSSL per-thread error
193 * queue being intact, so this is the earliest possible point
194 * ERR_get_error() may be called.
196 ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
202 /* Not supposed to happen, so we don't translate the msg */
203 printfPQExpBuffer(&conn->errorMessage,
204 "SSL_read failed but did not provide error information\n");
205 /* assume the connection is broken */
206 result_errno = ECONNRESET;
209 case SSL_ERROR_WANT_READ:
212 case SSL_ERROR_WANT_WRITE:
215 * Returning 0 here would cause caller to wait for read-ready,
216 * which is not correct since what SSL wants is wait for
217 * write-ready. The former could get us stuck in an infinite
218 * wait, so don't risk it; busy-loop instead.
221 case SSL_ERROR_SYSCALL:
224 result_errno = SOCK_ERRNO;
225 if (result_errno == EPIPE ||
226 result_errno == ECONNRESET)
227 printfPQExpBuffer(&conn->errorMessage,
229 "server closed the connection unexpectedly\n"
230 "\tThis probably means the server terminated abnormally\n"
231 "\tbefore or while processing the request.\n"));
233 printfPQExpBuffer(&conn->errorMessage,
234 libpq_gettext("SSL SYSCALL error: %s\n"),
235 SOCK_STRERROR(result_errno,
236 sebuf, sizeof(sebuf)));
240 printfPQExpBuffer(&conn->errorMessage,
241 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
242 /* assume the connection is broken */
243 result_errno = ECONNRESET;
249 char *errm = SSLerrmessage(ecode);
251 printfPQExpBuffer(&conn->errorMessage,
252 libpq_gettext("SSL error: %s\n"), errm);
254 /* assume the connection is broken */
255 result_errno = ECONNRESET;
259 case SSL_ERROR_ZERO_RETURN:
262 * Per OpenSSL documentation, this error code is only returned for
263 * a clean connection closure, so we should not report it as a
266 printfPQExpBuffer(&conn->errorMessage,
267 libpq_gettext("SSL connection has been closed unexpectedly\n"));
268 result_errno = ECONNRESET;
272 printfPQExpBuffer(&conn->errorMessage,
273 libpq_gettext("unrecognized SSL error code: %d\n"),
275 /* assume the connection is broken */
276 result_errno = ECONNRESET;
281 /* ensure we return the intended errno to caller */
282 SOCK_ERRNO_SET(result_errno);
288 * Write data to a secure connection.
290 * On failure, this function is responsible for putting a suitable message
291 * into conn->errorMessage. The caller must still inspect errno, but only
292 * to determine whether to continue/retry after error.
295 pgtls_write(PGconn *conn, const void *ptr, size_t len)
298 int result_errno = 0;
305 n = SSL_write(conn->ssl, ptr, len);
306 err = SSL_get_error(conn->ssl, n);
307 ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
313 /* Not supposed to happen, so we don't translate the msg */
314 printfPQExpBuffer(&conn->errorMessage,
315 "SSL_write failed but did not provide error information\n");
316 /* assume the connection is broken */
317 result_errno = ECONNRESET;
320 case SSL_ERROR_WANT_READ:
323 * Returning 0 here causes caller to wait for write-ready, which
324 * is not really the right thing, but it's the best we can do.
328 case SSL_ERROR_WANT_WRITE:
331 case SSL_ERROR_SYSCALL:
334 result_errno = SOCK_ERRNO;
335 if (result_errno == EPIPE || result_errno == ECONNRESET)
336 printfPQExpBuffer(&conn->errorMessage,
338 "server closed the connection unexpectedly\n"
339 "\tThis probably means the server terminated abnormally\n"
340 "\tbefore or while processing the request.\n"));
342 printfPQExpBuffer(&conn->errorMessage,
343 libpq_gettext("SSL SYSCALL error: %s\n"),
344 SOCK_STRERROR(result_errno,
345 sebuf, sizeof(sebuf)));
349 printfPQExpBuffer(&conn->errorMessage,
350 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
351 /* assume the connection is broken */
352 result_errno = ECONNRESET;
358 char *errm = SSLerrmessage(ecode);
360 printfPQExpBuffer(&conn->errorMessage,
361 libpq_gettext("SSL error: %s\n"), errm);
363 /* assume the connection is broken */
364 result_errno = ECONNRESET;
368 case SSL_ERROR_ZERO_RETURN:
371 * Per OpenSSL documentation, this error code is only returned for
372 * a clean connection closure, so we should not report it as a
375 printfPQExpBuffer(&conn->errorMessage,
376 libpq_gettext("SSL connection has been closed unexpectedly\n"));
377 result_errno = ECONNRESET;
381 printfPQExpBuffer(&conn->errorMessage,
382 libpq_gettext("unrecognized SSL error code: %d\n"),
384 /* assume the connection is broken */
385 result_errno = ECONNRESET;
390 /* ensure we return the intended errno to caller */
391 SOCK_ERRNO_SET(result_errno);
397 * Get the TLS finish message sent during last handshake
399 * This information is useful for callers doing channel binding during
403 pgtls_get_finished(PGconn *conn, size_t *len)
409 * OpenSSL does not offer an API to get directly the length of the TLS
410 * Finished message sent, so first do a dummy call to grab this
411 * information and then do an allocation with the correct size.
413 *len = SSL_get_finished(conn->ssl, dummy, sizeof(dummy));
414 result = malloc(*len);
417 (void) SSL_get_finished(conn->ssl, result, *len);
423 /* ------------------------------------------------------------ */
424 /* OpenSSL specific code */
425 /* ------------------------------------------------------------ */
428 * Certificate verification callback
430 * This callback allows us to log intermediate problems during
431 * verification, but there doesn't seem to be a clean way to get
432 * our PGconn * structure. So we can't log anything!
434 * This callback also allows us to override the default acceptance
435 * criteria (e.g., accepting self-signed or expired certs), but
436 * for now we accept the default checks.
439 verify_cb(int ok, X509_STORE_CTX *ctx)
446 * Check if a wildcard certificate matches the server hostname.
448 * The rule for this is:
449 * 1. We only match the '*' character as wildcard
450 * 2. We match only wildcards at the start of the string
451 * 3. The '*' character does *not* match '.', meaning that we match only
452 * a single pathname component.
453 * 4. We don't support more than one '*' in a single pattern.
455 * This is roughly in line with RFC2818, but contrary to what most browsers
456 * appear to be implementing (point 3 being the difference)
458 * Matching is always case-insensitive, since DNS is case insensitive.
461 wildcard_certificate_match(const char *pattern, const char *string)
463 int lenpat = strlen(pattern);
464 int lenstr = strlen(string);
466 /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
473 /* If pattern is longer than the string, we can never match */
476 if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
479 * If string does not end in pattern (minus the wildcard), we don't
484 if (strchr(string, '.') < string + lenstr - lenpat)
487 * If there is a dot left of where the pattern started to match, we
488 * don't match (rule 3)
492 /* String ended with pattern, and didn't have a dot before, so we match */
497 * Check if a name from a server's certificate matches the peer's hostname.
499 * Returns 1 if the name matches, and 0 if it does not. On error, returns
500 * -1, and sets the libpq error message.
502 * The name extracted from the certificate is returned in *store_name. The
503 * caller is responsible for freeing it.
506 verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
511 const unsigned char *namedata;
513 char *host = PQhost(conn);
517 /* Should not happen... */
518 if (name_entry == NULL)
520 printfPQExpBuffer(&conn->errorMessage,
521 libpq_gettext("SSL certificate's name entry is missing\n"));
526 * GEN_DNS can be only IA5String, equivalent to US ASCII.
528 * There is no guarantee the string returned from the certificate is
529 * NULL-terminated, so make a copy that is.
531 #ifdef HAVE_ASN1_STRING_GET0_DATA
532 namedata = ASN1_STRING_get0_data(name_entry);
534 namedata = ASN1_STRING_data(name_entry);
536 len = ASN1_STRING_length(name_entry);
537 name = malloc(len + 1);
540 printfPQExpBuffer(&conn->errorMessage,
541 libpq_gettext("out of memory\n"));
544 memcpy(name, namedata, len);
548 * Reject embedded NULLs in certificate common or alternative name to
549 * prevent attacks like CVE-2009-4034.
551 if (len != strlen(name))
554 printfPQExpBuffer(&conn->errorMessage,
555 libpq_gettext("SSL certificate's name contains embedded null\n"));
559 if (pg_strcasecmp(name, host) == 0)
561 /* Exact name match */
564 else if (wildcard_certificate_match(name, host))
566 /* Matched wildcard name */
579 * Verify that the server certificate matches the hostname we connected to.
581 * The certificate's Common Name and Subject Alternative Names are considered.
584 verify_peer_name_matches_certificate(PGconn *conn)
586 int names_examined = 0;
587 bool found_match = false;
588 bool got_error = false;
589 char *first_name = NULL;
591 STACK_OF(GENERAL_NAME) *peer_san;
594 char *host = PQhost(conn);
597 * If told not to verify the peer name, don't do it. Return true
598 * indicating that the verification was successful.
600 if (strcmp(conn->sslmode, "verify-full") != 0)
603 /* Check that we have a hostname to compare with. */
604 if (!(host && host[0] != '\0'))
606 printfPQExpBuffer(&conn->errorMessage,
607 libpq_gettext("host name must be specified for a verified SSL connection\n"));
612 * First, get the Subject Alternative Names (SANs) from the certificate,
613 * and compare them against the originally given hostname.
615 peer_san = (STACK_OF(GENERAL_NAME) *)
616 X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
620 int san_len = sk_GENERAL_NAME_num(peer_san);
622 for (i = 0; i < san_len; i++)
624 const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
626 if (name->type == GEN_DNS)
631 rc = verify_peer_name_matches_certificate_name(conn,
642 first_name = alt_name;
647 if (found_match || got_error)
650 sk_GENERAL_NAME_free(peer_san);
654 * If there is no subjectAltName extension of type dNSName, check the
657 * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
658 * dNSName is present, the CN must be ignored.)
660 if (names_examined == 0)
662 X509_NAME *subject_name;
664 subject_name = X509_get_subject_name(conn->peer);
665 if (subject_name != NULL)
669 cn_index = X509_NAME_get_index_by_NID(subject_name,
674 rc = verify_peer_name_matches_certificate_name(
676 X509_NAME_ENTRY_get_data(
677 X509_NAME_get_entry(subject_name, cn_index)),
688 if (!found_match && !got_error)
691 * No match. Include the name from the server certificate in the error
692 * message, to aid debugging broken configurations. If there are
693 * multiple names, only print the first one to avoid an overly long
696 if (names_examined > 1)
698 printfPQExpBuffer(&conn->errorMessage,
699 libpq_ngettext("server certificate for \"%s\" (and %d other name) does not match host name \"%s\"\n",
700 "server certificate for \"%s\" (and %d other names) does not match host name \"%s\"\n",
702 first_name, names_examined - 1, host);
704 else if (names_examined == 1)
706 printfPQExpBuffer(&conn->errorMessage,
707 libpq_gettext("server certificate for \"%s\" does not match host name \"%s\"\n"),
712 printfPQExpBuffer(&conn->errorMessage,
713 libpq_gettext("could not get server's host name from server certificate\n"));
721 return found_match && !got_error;
724 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
726 * Callback functions for OpenSSL internal locking. (OpenSSL 1.1.0
727 * does its own locking, and doesn't need these anymore. The
728 * CRYPTO_lock() function was removed in 1.1.0, when the callbacks
729 * were made obsolete, so we assume that if CRYPTO_lock() exists,
730 * the callbacks are still required.)
734 pq_threadidcallback(void)
737 * This is not standards-compliant. pthread_self() returns pthread_t, and
738 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
739 * it, so we have to do it.
741 return (unsigned long) pthread_self();
744 static pthread_mutex_t *pq_lockarray;
747 pq_lockingcallback(int mode, int n, const char *file, int line)
749 if (mode & CRYPTO_LOCK)
751 if (pthread_mutex_lock(&pq_lockarray[n]))
752 PGTHREAD_ERROR("failed to lock mutex");
756 if (pthread_mutex_unlock(&pq_lockarray[n]))
757 PGTHREAD_ERROR("failed to unlock mutex");
760 #endif /* ENABLE_THREAD_SAFETY && HAVE_CRYPTO_LOCK */
763 * Initialize SSL library.
765 * In threadsafe mode, this includes setting up libcrypto callback functions
766 * to do thread locking.
768 * If the caller has told us (through PQinitOpenSSL) that he's taking care
769 * of libcrypto, we expect that callbacks are already set, and won't try to
772 * The conn parameter is only used to be able to pass back an error
773 * message - no connection-local setup is made here.
775 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
778 pgtls_init(PGconn *conn)
780 #ifdef ENABLE_THREAD_SAFETY
782 /* Also see similar code in fe-connect.c, default_threadlock() */
783 if (ssl_config_mutex == NULL)
785 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
786 /* loop, another thread own the lock */ ;
787 if (ssl_config_mutex == NULL)
789 if (pthread_mutex_init(&ssl_config_mutex, NULL))
792 InterlockedExchange(&win32_ssl_create_mutex, 0);
795 if (pthread_mutex_lock(&ssl_config_mutex))
798 #ifdef HAVE_CRYPTO_LOCK
799 if (pq_init_crypto_lib)
802 * If necessary, set up an array to hold locks for libcrypto.
803 * libcrypto will tell us how big to make this array.
805 if (pq_lockarray == NULL)
809 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
812 pthread_mutex_unlock(&ssl_config_mutex);
815 for (i = 0; i < CRYPTO_num_locks(); i++)
817 if (pthread_mutex_init(&pq_lockarray[i], NULL))
821 pthread_mutex_unlock(&ssl_config_mutex);
827 if (ssl_open_connections++ == 0)
830 * These are only required for threaded libcrypto applications,
831 * but make sure we don't stomp on them if they're already set.
833 if (CRYPTO_get_id_callback() == NULL)
834 CRYPTO_set_id_callback(pq_threadidcallback);
835 if (CRYPTO_get_locking_callback() == NULL)
836 CRYPTO_set_locking_callback(pq_lockingcallback);
839 #endif /* HAVE_CRYPTO_LOCK */
840 #endif /* ENABLE_THREAD_SAFETY */
842 if (!ssl_lib_initialized)
846 #ifdef HAVE_OPENSSL_INIT_SSL
847 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
849 OPENSSL_config(NULL);
851 SSL_load_error_strings();
854 ssl_lib_initialized = true;
857 #ifdef ENABLE_THREAD_SAFETY
858 pthread_mutex_unlock(&ssl_config_mutex);
864 * This function is needed because if the libpq library is unloaded
865 * from the application, the callback functions will no longer exist when
866 * libcrypto is used by other parts of the system. For this reason,
867 * we unregister the callback functions when the last libpq
868 * connection is closed. (The same would apply for OpenSSL callbacks
871 * Callbacks are only set when we're compiled in threadsafe mode, so
872 * we only need to remove them in this case. They are also not needed
873 * with OpenSSL 1.1.0 anymore.
876 destroy_ssl_system(void)
878 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
879 /* Mutex is created in initialize_ssl_system() */
880 if (pthread_mutex_lock(&ssl_config_mutex))
883 if (pq_init_crypto_lib && ssl_open_connections > 0)
884 --ssl_open_connections;
886 if (pq_init_crypto_lib && ssl_open_connections == 0)
889 * No connections left, unregister libcrypto callbacks, if no one
890 * registered different ones in the meantime.
892 if (CRYPTO_get_locking_callback() == pq_lockingcallback)
893 CRYPTO_set_locking_callback(NULL);
894 if (CRYPTO_get_id_callback() == pq_threadidcallback)
895 CRYPTO_set_id_callback(NULL);
898 * We don't free the lock array. If we get another connection in this
899 * process, we will just re-use them with the existing mutexes.
901 * This means we leak a little memory on repeated load/unload of the
906 pthread_mutex_unlock(&ssl_config_mutex);
911 * Create per-connection SSL object, and load the client certificate,
912 * private key, and trusted CA certs.
914 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
917 initialize_SSL(PGconn *conn)
919 SSL_CTX *SSL_context;
921 char homedir[MAXPGPATH];
922 char fnbuf[MAXPGPATH];
927 EVP_PKEY *pkey = NULL;
930 * We'll need the home directory if any of the relevant parameters are
931 * defaulted. If pqGetHomeDirectory fails, act as though none of the
932 * files could be found.
934 if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
935 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
936 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
937 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
938 have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
939 else /* won't need it */
940 have_homedir = false;
943 * Create a new SSL_CTX object.
945 * We used to share a single SSL_CTX between all connections, but it was
946 * complicated if connections used different certificates. So now we
947 * create a separate context for each connection, and accept the overhead.
949 SSL_context = SSL_CTX_new(SSLv23_method());
952 char *err = SSLerrmessage(ERR_get_error());
954 printfPQExpBuffer(&conn->errorMessage,
955 libpq_gettext("could not create SSL context: %s\n"),
961 /* Disable old protocol versions */
962 SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
965 * Disable OpenSSL's moving-write-buffer sanity check, because it causes
966 * unnecessary failures in nonblocking send cases.
968 SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
971 * If the root cert file exists, load it so we can perform certificate
972 * verification. If sslmode is "verify-full" we will also do further
973 * verification after the connection has been completed.
975 if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
976 strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
977 else if (have_homedir)
978 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
982 if (fnbuf[0] != '\0' &&
983 stat(fnbuf, &buf) == 0)
987 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
989 char *err = SSLerrmessage(ERR_get_error());
991 printfPQExpBuffer(&conn->errorMessage,
992 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
995 SSL_CTX_free(SSL_context);
999 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1001 if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1002 strlcpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
1003 else if (have_homedir)
1004 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1008 /* Set the flags to check against the complete CRL chain */
1009 if (fnbuf[0] != '\0' &&
1010 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
1012 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
1013 #ifdef X509_V_FLAG_CRL_CHECK
1014 X509_STORE_set_flags(cvstore,
1015 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1017 char *err = SSLerrmessage(ERR_get_error());
1019 printfPQExpBuffer(&conn->errorMessage,
1020 libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
1023 SSL_CTX_free(SSL_context);
1027 /* if not found, silently ignore; we do not require CRL */
1030 have_rootcert = true;
1035 * stat() failed; assume root file doesn't exist. If sslmode is
1036 * verify-ca or verify-full, this is an error. Otherwise, continue
1037 * without performing any server cert verification.
1039 if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1042 * The only way to reach here with an empty filename is if
1043 * pqGetHomeDirectory failed. That's a sufficiently unusual case
1044 * that it seems worth having a specialized error message for it.
1046 if (fnbuf[0] == '\0')
1047 printfPQExpBuffer(&conn->errorMessage,
1048 libpq_gettext("could not get home directory to locate root certificate file\n"
1049 "Either provide the file or change sslmode to disable server certificate verification.\n"));
1051 printfPQExpBuffer(&conn->errorMessage,
1052 libpq_gettext("root certificate file \"%s\" does not exist\n"
1053 "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1054 SSL_CTX_free(SSL_context);
1057 have_rootcert = false;
1060 /* Read the client certificate file */
1061 if (conn->sslcert && strlen(conn->sslcert) > 0)
1062 strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
1063 else if (have_homedir)
1064 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
1068 if (fnbuf[0] == '\0')
1070 /* no home directory, proceed without a client cert */
1073 else if (stat(fnbuf, &buf) != 0)
1076 * If file is not present, just go on without a client cert; server
1077 * might or might not accept the connection. Any other error,
1078 * however, is grounds for complaint.
1080 if (errno != ENOENT && errno != ENOTDIR)
1082 printfPQExpBuffer(&conn->errorMessage,
1083 libpq_gettext("could not open certificate file \"%s\": %s\n"),
1084 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
1085 SSL_CTX_free(SSL_context);
1093 * Cert file exists, so load it. Since OpenSSL doesn't provide the
1094 * equivalent of "SSL_use_certificate_chain_file", we have to load it
1095 * into the SSL context, rather than the SSL object.
1097 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1099 char *err = SSLerrmessage(ERR_get_error());
1101 printfPQExpBuffer(&conn->errorMessage,
1102 libpq_gettext("could not read certificate file \"%s\": %s\n"),
1105 SSL_CTX_free(SSL_context);
1109 /* need to load the associated private key, too */
1114 * The SSL context is now loaded with the correct root and client
1115 * certificates. Create a connection-specific SSL object. The private key
1116 * is loaded directly into the SSL object. (We could load the private key
1117 * into the context, too, but we have done it this way historically, and
1118 * it doesn't really matter.)
1120 if (!(conn->ssl = SSL_new(SSL_context)) ||
1121 !SSL_set_app_data(conn->ssl, conn) ||
1122 !my_SSL_set_fd(conn, conn->sock))
1124 char *err = SSLerrmessage(ERR_get_error());
1126 printfPQExpBuffer(&conn->errorMessage,
1127 libpq_gettext("could not establish SSL connection: %s\n"),
1130 SSL_CTX_free(SSL_context);
1133 conn->ssl_in_use = true;
1136 * SSL contexts are reference counted by OpenSSL. We can free it as soon
1137 * as we have created the SSL object, and it will stick around for as long
1138 * as it's actually needed.
1140 SSL_CTX_free(SSL_context);
1144 * Read the SSL key. If a key is specified, treat it as an engine:key
1145 * combination if there is colon present - we don't support files with
1146 * colon in the name. The exception is if the second character is a colon,
1147 * in which case it can be a Windows filename with drive specification.
1149 if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1151 #ifdef USE_SSL_ENGINE
1152 if (strchr(conn->sslkey, ':')
1154 && conn->sslkey[1] != ':'
1158 /* Colon, but not in second character, treat as engine:key */
1159 char *engine_str = strdup(conn->sslkey);
1162 if (engine_str == NULL)
1164 printfPQExpBuffer(&conn->errorMessage,
1165 libpq_gettext("out of memory\n"));
1169 /* cannot return NULL because we already checked before strdup */
1170 engine_colon = strchr(engine_str, ':');
1172 *engine_colon = '\0'; /* engine_str now has engine name */
1173 engine_colon++; /* engine_colon now has key name */
1175 conn->engine = ENGINE_by_id(engine_str);
1176 if (conn->engine == NULL)
1178 char *err = SSLerrmessage(ERR_get_error());
1180 printfPQExpBuffer(&conn->errorMessage,
1181 libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1188 if (ENGINE_init(conn->engine) == 0)
1190 char *err = SSLerrmessage(ERR_get_error());
1192 printfPQExpBuffer(&conn->errorMessage,
1193 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1196 ENGINE_free(conn->engine);
1197 conn->engine = NULL;
1202 pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1206 char *err = SSLerrmessage(ERR_get_error());
1208 printfPQExpBuffer(&conn->errorMessage,
1209 libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1210 engine_colon, engine_str, err);
1212 ENGINE_finish(conn->engine);
1213 ENGINE_free(conn->engine);
1214 conn->engine = NULL;
1218 if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1220 char *err = SSLerrmessage(ERR_get_error());
1222 printfPQExpBuffer(&conn->errorMessage,
1223 libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1224 engine_colon, engine_str, err);
1226 ENGINE_finish(conn->engine);
1227 ENGINE_free(conn->engine);
1228 conn->engine = NULL;
1235 fnbuf[0] = '\0'; /* indicate we're not going to load from a
1239 #endif /* USE_SSL_ENGINE */
1241 /* PGSSLKEY is not an engine, treat it as a filename */
1242 strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1245 else if (have_homedir)
1247 /* No PGSSLKEY specified, load default file */
1248 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1253 if (have_cert && fnbuf[0] != '\0')
1255 /* read the client key from file */
1257 if (stat(fnbuf, &buf) != 0)
1259 printfPQExpBuffer(&conn->errorMessage,
1260 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1265 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1267 printfPQExpBuffer(&conn->errorMessage,
1268 libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1274 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1276 char *err = SSLerrmessage(ERR_get_error());
1278 printfPQExpBuffer(&conn->errorMessage,
1279 libpq_gettext("could not load private key file \"%s\": %s\n"),
1286 /* verify that the cert and key go together */
1288 SSL_check_private_key(conn->ssl) != 1)
1290 char *err = SSLerrmessage(ERR_get_error());
1292 printfPQExpBuffer(&conn->errorMessage,
1293 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1300 * If a root cert was loaded, also set our certificate verification
1304 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1307 * If the OpenSSL version used supports it (from 1.0.0 on) and the user
1308 * requested it, disable SSL compression.
1310 #ifdef SSL_OP_NO_COMPRESSION
1311 if (conn->sslcompression && conn->sslcompression[0] == '0')
1313 SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1321 * Attempt to negotiate SSL connection.
1323 static PostgresPollingStatusType
1324 open_client_SSL(PGconn *conn)
1329 r = SSL_connect(conn->ssl);
1332 int err = SSL_get_error(conn->ssl, r);
1333 unsigned long ecode;
1335 ecode = ERR_get_error();
1338 case SSL_ERROR_WANT_READ:
1339 return PGRES_POLLING_READING;
1341 case SSL_ERROR_WANT_WRITE:
1342 return PGRES_POLLING_WRITING;
1344 case SSL_ERROR_SYSCALL:
1349 printfPQExpBuffer(&conn->errorMessage,
1350 libpq_gettext("SSL SYSCALL error: %s\n"),
1351 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1353 printfPQExpBuffer(&conn->errorMessage,
1354 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1356 return PGRES_POLLING_FAILED;
1360 char *err = SSLerrmessage(ecode);
1362 printfPQExpBuffer(&conn->errorMessage,
1363 libpq_gettext("SSL error: %s\n"),
1367 return PGRES_POLLING_FAILED;
1371 printfPQExpBuffer(&conn->errorMessage,
1372 libpq_gettext("unrecognized SSL error code: %d\n"),
1375 return PGRES_POLLING_FAILED;
1380 * We already checked the server certificate in initialize_SSL() using
1381 * SSL_CTX_set_verify(), if root.crt exists.
1384 /* get server certificate */
1385 conn->peer = SSL_get_peer_certificate(conn->ssl);
1386 if (conn->peer == NULL)
1390 err = SSLerrmessage(ERR_get_error());
1392 printfPQExpBuffer(&conn->errorMessage,
1393 libpq_gettext("certificate could not be obtained: %s\n"),
1397 return PGRES_POLLING_FAILED;
1400 if (!verify_peer_name_matches_certificate(conn))
1403 return PGRES_POLLING_FAILED;
1406 /* SSL handshake is complete */
1407 return PGRES_POLLING_OK;
1411 * Close SSL connection.
1414 pgtls_close(PGconn *conn)
1416 bool destroy_needed = false;
1421 * We can't destroy everything SSL-related here due to the possible
1422 * later calls to OpenSSL routines which may need our thread
1423 * callbacks, so set a flag here and check at the end.
1425 destroy_needed = true;
1427 SSL_shutdown(conn->ssl);
1428 SSL_free(conn->ssl);
1430 conn->ssl_in_use = false;
1435 X509_free(conn->peer);
1439 #ifdef USE_SSL_ENGINE
1442 ENGINE_finish(conn->engine);
1443 ENGINE_free(conn->engine);
1444 conn->engine = NULL;
1449 * This will remove our SSL locking hooks, if this is the last SSL
1450 * connection, which means we must wait to call it until after all SSL
1451 * calls have been made, otherwise we can end up with a race condition and
1452 * possible deadlocks.
1454 * See comments above destroy_ssl_system().
1457 destroy_ssl_system();
1462 * Obtain reason string for passed SSL errcode
1464 * ERR_get_error() is used by caller to get errcode to pass here.
1466 * Some caution is needed here since ERR_reason_error_string will
1467 * return NULL if it doesn't recognize the error code. We don't
1468 * want to return NULL ever.
1470 static char ssl_nomem[] = "out of memory allocating error description";
1472 #define SSL_ERR_LEN 128
1475 SSLerrmessage(unsigned long ecode)
1477 const char *errreason;
1480 errbuf = malloc(SSL_ERR_LEN);
1485 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1488 errreason = ERR_reason_error_string(ecode);
1489 if (errreason != NULL)
1491 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1494 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1499 SSLerrfree(char *buf)
1501 if (buf != ssl_nomem)
1505 /* ------------------------------------------------------------ */
1506 /* SSL information functions */
1507 /* ------------------------------------------------------------ */
1510 PQsslInUse(PGconn *conn)
1514 return conn->ssl_in_use;
1518 * Return pointer to OpenSSL object.
1521 PQgetssl(PGconn *conn)
1529 PQsslStruct(PGconn *conn, const char *struct_name)
1533 if (strcmp(struct_name, "OpenSSL") == 0)
1539 PQsslAttributeNames(PGconn *conn)
1541 static const char *const result[] = {
1554 PQsslAttribute(PGconn *conn, const char *attribute_name)
1558 if (conn->ssl == NULL)
1561 if (strcmp(attribute_name, "library") == 0)
1564 if (strcmp(attribute_name, "key_bits") == 0)
1566 static char sslbits_str[10];
1569 SSL_get_cipher_bits(conn->ssl, &sslbits);
1570 snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1574 if (strcmp(attribute_name, "cipher") == 0)
1575 return SSL_get_cipher(conn->ssl);
1577 if (strcmp(attribute_name, "compression") == 0)
1578 return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1580 if (strcmp(attribute_name, "protocol") == 0)
1581 return SSL_get_version(conn->ssl);
1583 return NULL; /* unknown attribute */
1587 * Private substitute BIO: this does the sending and receiving using
1588 * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1589 * functions to disable SIGPIPE and give better error messages on I/O errors.
1591 * These functions are closely modelled on the standard socket BIO in OpenSSL;
1592 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1593 * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1594 * to retry; do we need to adopt their logic for that?
1597 #ifndef HAVE_BIO_GET_DATA
1598 #define BIO_get_data(bio) (bio->ptr)
1599 #define BIO_set_data(bio, data) (bio->ptr = data)
1602 static BIO_METHOD *my_bio_methods;
1605 my_sock_read(BIO *h, char *buf, int size)
1609 res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1610 BIO_clear_retry_flags(h);
1613 /* If we were interrupted, tell caller to retry */
1619 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1623 BIO_set_retry_read(h);
1635 my_sock_write(BIO *h, const char *buf, int size)
1639 res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1640 BIO_clear_retry_flags(h);
1643 /* If we were interrupted, tell caller to retry */
1649 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1653 BIO_set_retry_write(h);
1665 my_BIO_s_socket(void)
1667 if (!my_bio_methods)
1669 BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1670 #ifdef HAVE_BIO_METH_NEW
1673 my_bio_index = BIO_get_new_index();
1674 if (my_bio_index == -1)
1676 my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1677 if (!my_bio_methods)
1681 * As of this writing, these functions never fail. But check anyway,
1682 * like OpenSSL's own examples do.
1684 if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1685 !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1686 !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1687 !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1688 !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1689 !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1690 !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1691 !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1693 BIO_meth_free(my_bio_methods);
1694 my_bio_methods = NULL;
1698 my_bio_methods = malloc(sizeof(BIO_METHOD));
1699 if (!my_bio_methods)
1701 memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1702 my_bio_methods->bread = my_sock_read;
1703 my_bio_methods->bwrite = my_sock_write;
1706 return my_bio_methods;
1709 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
1711 my_SSL_set_fd(PGconn *conn, int fd)
1715 BIO_METHOD *bio_method;
1717 bio_method = my_BIO_s_socket();
1718 if (bio_method == NULL)
1720 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1723 bio = BIO_new(bio_method);
1726 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1729 BIO_set_data(bio, conn);
1731 SSL_set_bio(conn->ssl, bio, bio);
1732 BIO_set_fd(bio, fd, BIO_NOCLOSE);