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 #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 certificate,
133 * 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);
396 /* ------------------------------------------------------------ */
397 /* OpenSSL specific code */
398 /* ------------------------------------------------------------ */
401 * Certificate verification callback
403 * This callback allows us to log intermediate problems during
404 * verification, but there doesn't seem to be a clean way to get
405 * our PGconn * structure. So we can't log anything!
407 * This callback also allows us to override the default acceptance
408 * criteria (e.g., accepting self-signed or expired certs), but
409 * for now we accept the default checks.
412 verify_cb(int ok, X509_STORE_CTX *ctx)
419 * Check if a wildcard certificate matches the server hostname.
421 * The rule for this is:
422 * 1. We only match the '*' character as wildcard
423 * 2. We match only wildcards at the start of the string
424 * 3. The '*' character does *not* match '.', meaning that we match only
425 * a single pathname component.
426 * 4. We don't support more than one '*' in a single pattern.
428 * This is roughly in line with RFC2818, but contrary to what most browsers
429 * appear to be implementing (point 3 being the difference)
431 * Matching is always case-insensitive, since DNS is case insensitive.
434 wildcard_certificate_match(const char *pattern, const char *string)
436 int lenpat = strlen(pattern);
437 int lenstr = strlen(string);
439 /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
446 /* If pattern is longer than the string, we can never match */
449 if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
452 * If string does not end in pattern (minus the wildcard), we don't
457 if (strchr(string, '.') < string + lenstr - lenpat)
460 * If there is a dot left of where the pattern started to match, we
461 * don't match (rule 3)
465 /* String ended with pattern, and didn't have a dot before, so we match */
470 * Check if a name from a server's certificate matches the peer's hostname.
472 * Returns 1 if the name matches, and 0 if it does not. On error, returns
473 * -1, and sets the libpq error message.
475 * The name extracted from the certificate is returned in *store_name. The
476 * caller is responsible for freeing it.
479 verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
484 const unsigned char *namedata;
486 char *host = PQhost(conn);
490 /* Should not happen... */
491 if (name_entry == NULL)
493 printfPQExpBuffer(&conn->errorMessage,
494 libpq_gettext("SSL certificate's name entry is missing\n"));
499 * GEN_DNS can be only IA5String, equivalent to US ASCII.
501 * There is no guarantee the string returned from the certificate is
502 * NULL-terminated, so make a copy that is.
504 #ifdef HAVE_ASN1_STRING_GET0_DATA
505 namedata = ASN1_STRING_get0_data(name_entry);
507 namedata = ASN1_STRING_data(name_entry);
509 len = ASN1_STRING_length(name_entry);
510 name = malloc(len + 1);
513 printfPQExpBuffer(&conn->errorMessage,
514 libpq_gettext("out of memory\n"));
517 memcpy(name, namedata, len);
521 * Reject embedded NULLs in certificate common or alternative name to
522 * prevent attacks like CVE-2009-4034.
524 if (len != strlen(name))
527 printfPQExpBuffer(&conn->errorMessage,
528 libpq_gettext("SSL certificate's name contains embedded null\n"));
532 if (pg_strcasecmp(name, host) == 0)
534 /* Exact name match */
537 else if (wildcard_certificate_match(name, host))
539 /* Matched wildcard name */
552 * Verify that the server certificate matches the hostname we connected to.
554 * The certificate's Common Name and Subject Alternative Names are considered.
557 verify_peer_name_matches_certificate(PGconn *conn)
559 int names_examined = 0;
560 bool found_match = false;
561 bool got_error = false;
562 char *first_name = NULL;
564 STACK_OF(GENERAL_NAME) *peer_san;
567 char *host = PQhost(conn);
570 * If told not to verify the peer name, don't do it. Return true
571 * indicating that the verification was successful.
573 if (strcmp(conn->sslmode, "verify-full") != 0)
576 /* Check that we have a hostname to compare with. */
577 if (!(host && host[0] != '\0'))
579 printfPQExpBuffer(&conn->errorMessage,
580 libpq_gettext("host name must be specified for a verified SSL connection\n"));
585 * First, get the Subject Alternative Names (SANs) from the certificate,
586 * and compare them against the originally given hostname.
588 peer_san = (STACK_OF(GENERAL_NAME) *)
589 X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
593 int san_len = sk_GENERAL_NAME_num(peer_san);
595 for (i = 0; i < san_len; i++)
597 const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
599 if (name->type == GEN_DNS)
604 rc = verify_peer_name_matches_certificate_name(conn,
615 first_name = alt_name;
620 if (found_match || got_error)
623 sk_GENERAL_NAME_free(peer_san);
627 * If there is no subjectAltName extension of type dNSName, check the
630 * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
631 * dNSName is present, the CN must be ignored.)
633 if (names_examined == 0)
635 X509_NAME *subject_name;
637 subject_name = X509_get_subject_name(conn->peer);
638 if (subject_name != NULL)
642 cn_index = X509_NAME_get_index_by_NID(subject_name,
647 rc = verify_peer_name_matches_certificate_name(
649 X509_NAME_ENTRY_get_data(
650 X509_NAME_get_entry(subject_name, cn_index)),
661 if (!found_match && !got_error)
664 * No match. Include the name from the server certificate in the error
665 * message, to aid debugging broken configurations. If there are
666 * multiple names, only print the first one to avoid an overly long
669 if (names_examined > 1)
671 printfPQExpBuffer(&conn->errorMessage,
672 libpq_ngettext("server certificate for \"%s\" (and %d other name) does not match host name \"%s\"\n",
673 "server certificate for \"%s\" (and %d other names) does not match host name \"%s\"\n",
675 first_name, names_examined - 1, host);
677 else if (names_examined == 1)
679 printfPQExpBuffer(&conn->errorMessage,
680 libpq_gettext("server certificate for \"%s\" does not match host name \"%s\"\n"),
685 printfPQExpBuffer(&conn->errorMessage,
686 libpq_gettext("could not get server's host name from server certificate\n"));
694 return found_match && !got_error;
697 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
699 * Callback functions for OpenSSL internal locking. (OpenSSL 1.1.0
700 * does its own locking, and doesn't need these anymore. The
701 * CRYPTO_lock() function was removed in 1.1.0, when the callbacks
702 * were made obsolete, so we assume that if CRYPTO_lock() exists,
703 * the callbacks are still required.)
707 pq_threadidcallback(void)
710 * This is not standards-compliant. pthread_self() returns pthread_t, and
711 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
712 * it, so we have to do it.
714 return (unsigned long) pthread_self();
717 static pthread_mutex_t *pq_lockarray;
720 pq_lockingcallback(int mode, int n, const char *file, int line)
722 if (mode & CRYPTO_LOCK)
724 if (pthread_mutex_lock(&pq_lockarray[n]))
725 PGTHREAD_ERROR("failed to lock mutex");
729 if (pthread_mutex_unlock(&pq_lockarray[n]))
730 PGTHREAD_ERROR("failed to unlock mutex");
733 #endif /* ENABLE_THREAD_SAFETY && HAVE_CRYPTO_LOCK */
736 * Initialize SSL library.
738 * In threadsafe mode, this includes setting up libcrypto callback functions
739 * to do thread locking.
741 * If the caller has told us (through PQinitOpenSSL) that he's taking care
742 * of libcrypto, we expect that callbacks are already set, and won't try to
745 * The conn parameter is only used to be able to pass back an error
746 * message - no connection-local setup is made here.
748 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
751 pgtls_init(PGconn *conn)
753 #ifdef ENABLE_THREAD_SAFETY
755 /* Also see similar code in fe-connect.c, default_threadlock() */
756 if (ssl_config_mutex == NULL)
758 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
759 /* loop, another thread own the lock */ ;
760 if (ssl_config_mutex == NULL)
762 if (pthread_mutex_init(&ssl_config_mutex, NULL))
765 InterlockedExchange(&win32_ssl_create_mutex, 0);
768 if (pthread_mutex_lock(&ssl_config_mutex))
771 #ifdef HAVE_CRYPTO_LOCK
772 if (pq_init_crypto_lib)
775 * If necessary, set up an array to hold locks for libcrypto.
776 * libcrypto will tell us how big to make this array.
778 if (pq_lockarray == NULL)
782 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
785 pthread_mutex_unlock(&ssl_config_mutex);
788 for (i = 0; i < CRYPTO_num_locks(); i++)
790 if (pthread_mutex_init(&pq_lockarray[i], NULL))
794 pthread_mutex_unlock(&ssl_config_mutex);
800 if (ssl_open_connections++ == 0)
803 * These are only required for threaded libcrypto applications,
804 * but make sure we don't stomp on them if they're already set.
806 if (CRYPTO_get_id_callback() == NULL)
807 CRYPTO_set_id_callback(pq_threadidcallback);
808 if (CRYPTO_get_locking_callback() == NULL)
809 CRYPTO_set_locking_callback(pq_lockingcallback);
812 #endif /* HAVE_CRYPTO_LOCK */
813 #endif /* ENABLE_THREAD_SAFETY */
815 if (!ssl_lib_initialized)
819 #ifdef HAVE_OPENSSL_INIT_SSL
820 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
822 OPENSSL_config(NULL);
824 SSL_load_error_strings();
827 ssl_lib_initialized = true;
830 #ifdef ENABLE_THREAD_SAFETY
831 pthread_mutex_unlock(&ssl_config_mutex);
837 * This function is needed because if the libpq library is unloaded
838 * from the application, the callback functions will no longer exist when
839 * libcrypto is used by other parts of the system. For this reason,
840 * we unregister the callback functions when the last libpq
841 * connection is closed. (The same would apply for OpenSSL callbacks
844 * Callbacks are only set when we're compiled in threadsafe mode, so
845 * we only need to remove them in this case. They are also not needed
846 * with OpenSSL 1.1.0 anymore.
849 destroy_ssl_system(void)
851 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
852 /* Mutex is created in initialize_ssl_system() */
853 if (pthread_mutex_lock(&ssl_config_mutex))
856 if (pq_init_crypto_lib && ssl_open_connections > 0)
857 --ssl_open_connections;
859 if (pq_init_crypto_lib && ssl_open_connections == 0)
862 * No connections left, unregister libcrypto callbacks, if no one
863 * registered different ones in the meantime.
865 if (CRYPTO_get_locking_callback() == pq_lockingcallback)
866 CRYPTO_set_locking_callback(NULL);
867 if (CRYPTO_get_id_callback() == pq_threadidcallback)
868 CRYPTO_set_id_callback(NULL);
871 * We don't free the lock array. If we get another connection in
872 * this process, we will just re-use them with the existing mutexes.
874 * This means we leak a little memory on repeated load/unload of the
879 pthread_mutex_unlock(&ssl_config_mutex);
884 * Create per-connection SSL object, and load the client certificate,
885 * private key, and trusted CA certs.
887 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
890 initialize_SSL(PGconn *conn)
892 SSL_CTX *SSL_context;
894 char homedir[MAXPGPATH];
895 char fnbuf[MAXPGPATH];
900 EVP_PKEY *pkey = NULL;
903 * We'll need the home directory if any of the relevant parameters are
904 * defaulted. If pqGetHomeDirectory fails, act as though none of the
905 * files could be found.
907 if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
908 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
909 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
910 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
911 have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
912 else /* won't need it */
913 have_homedir = false;
916 * Create a new SSL_CTX object.
918 * We used to share a single SSL_CTX between all connections, but it was
919 * complicated if connections used different certificates. So now we create
920 * a separate context for each connection, and accept the overhead.
922 SSL_context = SSL_CTX_new(SSLv23_method());
925 char *err = SSLerrmessage(ERR_get_error());
927 printfPQExpBuffer(&conn->errorMessage,
928 libpq_gettext("could not create SSL context: %s\n"),
934 /* Disable old protocol versions */
935 SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
938 * Disable OpenSSL's moving-write-buffer sanity check, because it
939 * causes unnecessary failures in nonblocking send cases.
941 SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
944 * If the root cert file exists, load it so we can perform certificate
945 * verification. If sslmode is "verify-full" we will also do further
946 * verification after the connection has been completed.
948 if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
949 strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
950 else if (have_homedir)
951 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
955 if (fnbuf[0] != '\0' &&
956 stat(fnbuf, &buf) == 0)
960 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
962 char *err = SSLerrmessage(ERR_get_error());
964 printfPQExpBuffer(&conn->errorMessage,
965 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
968 SSL_CTX_free(SSL_context);
972 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
974 if (conn->sslcrl && strlen(conn->sslcrl) > 0)
975 strlcpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
976 else if (have_homedir)
977 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
981 /* Set the flags to check against the complete CRL chain */
982 if (fnbuf[0] != '\0' &&
983 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
985 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
986 #ifdef X509_V_FLAG_CRL_CHECK
987 X509_STORE_set_flags(cvstore,
988 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
990 char *err = SSLerrmessage(ERR_get_error());
992 printfPQExpBuffer(&conn->errorMessage,
993 libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
996 SSL_CTX_free(SSL_context);
1000 /* if not found, silently ignore; we do not require CRL */
1003 have_rootcert = true;
1008 * stat() failed; assume root file doesn't exist. If sslmode is
1009 * verify-ca or verify-full, this is an error. Otherwise, continue
1010 * without performing any server cert verification.
1012 if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1015 * The only way to reach here with an empty filename is if
1016 * pqGetHomeDirectory failed. That's a sufficiently unusual case
1017 * that it seems worth having a specialized error message for it.
1019 if (fnbuf[0] == '\0')
1020 printfPQExpBuffer(&conn->errorMessage,
1021 libpq_gettext("could not get home directory to locate root certificate file\n"
1022 "Either provide the file or change sslmode to disable server certificate verification.\n"));
1024 printfPQExpBuffer(&conn->errorMessage,
1025 libpq_gettext("root certificate file \"%s\" does not exist\n"
1026 "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1027 SSL_CTX_free(SSL_context);
1030 have_rootcert = false;
1033 /* Read the client certificate file */
1034 if (conn->sslcert && strlen(conn->sslcert) > 0)
1035 strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
1036 else if (have_homedir)
1037 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
1041 if (fnbuf[0] == '\0')
1043 /* no home directory, proceed without a client cert */
1046 else if (stat(fnbuf, &buf) != 0)
1049 * If file is not present, just go on without a client cert; server
1050 * might or might not accept the connection. Any other error,
1051 * however, is grounds for complaint.
1053 if (errno != ENOENT && errno != ENOTDIR)
1055 printfPQExpBuffer(&conn->errorMessage,
1056 libpq_gettext("could not open certificate file \"%s\": %s\n"),
1057 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
1058 SSL_CTX_free(SSL_context);
1066 * Cert file exists, so load it. Since OpenSSL doesn't provide the
1067 * equivalent of "SSL_use_certificate_chain_file", we have to load
1068 * it into the SSL context, rather than the SSL object.
1070 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1072 char *err = SSLerrmessage(ERR_get_error());
1074 printfPQExpBuffer(&conn->errorMessage,
1075 libpq_gettext("could not read certificate file \"%s\": %s\n"),
1078 SSL_CTX_free(SSL_context);
1082 /* need to load the associated private key, too */
1087 * The SSL context is now loaded with the correct root and client certificates.
1088 * Create a connection-specific SSL object. The private key is loaded directly
1089 * into the SSL object. (We could load the private key into the context, too, but
1090 * we have done it this way historically, and it doesn't really matter.)
1092 if (!(conn->ssl = SSL_new(SSL_context)) ||
1093 !SSL_set_app_data(conn->ssl, conn) ||
1094 !my_SSL_set_fd(conn, conn->sock))
1096 char *err = SSLerrmessage(ERR_get_error());
1098 printfPQExpBuffer(&conn->errorMessage,
1099 libpq_gettext("could not establish SSL connection: %s\n"),
1102 SSL_CTX_free(SSL_context);
1105 conn->ssl_in_use = true;
1108 * SSL contexts are reference counted by OpenSSL. We can free it as soon as we
1109 * have created the SSL object, and it will stick around for as long as it's
1112 SSL_CTX_free(SSL_context);
1116 * Read the SSL key. If a key is specified, treat it as an engine:key
1117 * combination if there is colon present - we don't support files with
1118 * colon in the name. The exception is if the second character is a colon,
1119 * in which case it can be a Windows filename with drive specification.
1121 if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1123 #ifdef USE_SSL_ENGINE
1124 if (strchr(conn->sslkey, ':')
1126 && conn->sslkey[1] != ':'
1130 /* Colon, but not in second character, treat as engine:key */
1131 char *engine_str = strdup(conn->sslkey);
1134 if (engine_str == NULL)
1136 printfPQExpBuffer(&conn->errorMessage,
1137 libpq_gettext("out of memory\n"));
1141 /* cannot return NULL because we already checked before strdup */
1142 engine_colon = strchr(engine_str, ':');
1144 *engine_colon = '\0'; /* engine_str now has engine name */
1145 engine_colon++; /* engine_colon now has key name */
1147 conn->engine = ENGINE_by_id(engine_str);
1148 if (conn->engine == NULL)
1150 char *err = SSLerrmessage(ERR_get_error());
1152 printfPQExpBuffer(&conn->errorMessage,
1153 libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1160 if (ENGINE_init(conn->engine) == 0)
1162 char *err = SSLerrmessage(ERR_get_error());
1164 printfPQExpBuffer(&conn->errorMessage,
1165 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1168 ENGINE_free(conn->engine);
1169 conn->engine = NULL;
1174 pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1178 char *err = SSLerrmessage(ERR_get_error());
1180 printfPQExpBuffer(&conn->errorMessage,
1181 libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1182 engine_colon, engine_str, err);
1184 ENGINE_finish(conn->engine);
1185 ENGINE_free(conn->engine);
1186 conn->engine = NULL;
1190 if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1192 char *err = SSLerrmessage(ERR_get_error());
1194 printfPQExpBuffer(&conn->errorMessage,
1195 libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1196 engine_colon, engine_str, err);
1198 ENGINE_finish(conn->engine);
1199 ENGINE_free(conn->engine);
1200 conn->engine = NULL;
1207 fnbuf[0] = '\0'; /* indicate we're not going to load from a
1211 #endif /* USE_SSL_ENGINE */
1213 /* PGSSLKEY is not an engine, treat it as a filename */
1214 strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1217 else if (have_homedir)
1219 /* No PGSSLKEY specified, load default file */
1220 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1225 if (have_cert && fnbuf[0] != '\0')
1227 /* read the client key from file */
1229 if (stat(fnbuf, &buf) != 0)
1231 printfPQExpBuffer(&conn->errorMessage,
1232 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1237 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1239 printfPQExpBuffer(&conn->errorMessage,
1240 libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1246 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1248 char *err = SSLerrmessage(ERR_get_error());
1250 printfPQExpBuffer(&conn->errorMessage,
1251 libpq_gettext("could not load private key file \"%s\": %s\n"),
1258 /* verify that the cert and key go together */
1260 SSL_check_private_key(conn->ssl) != 1)
1262 char *err = SSLerrmessage(ERR_get_error());
1264 printfPQExpBuffer(&conn->errorMessage,
1265 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1272 * If a root cert was loaded, also set our certificate verification callback.
1275 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1278 * If the OpenSSL version used supports it (from 1.0.0 on) and the user
1279 * requested it, disable SSL compression.
1281 #ifdef SSL_OP_NO_COMPRESSION
1282 if (conn->sslcompression && conn->sslcompression[0] == '0')
1284 SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1292 * Attempt to negotiate SSL connection.
1294 static PostgresPollingStatusType
1295 open_client_SSL(PGconn *conn)
1300 r = SSL_connect(conn->ssl);
1303 int err = SSL_get_error(conn->ssl, r);
1304 unsigned long ecode;
1306 ecode = ERR_get_error();
1309 case SSL_ERROR_WANT_READ:
1310 return PGRES_POLLING_READING;
1312 case SSL_ERROR_WANT_WRITE:
1313 return PGRES_POLLING_WRITING;
1315 case SSL_ERROR_SYSCALL:
1320 printfPQExpBuffer(&conn->errorMessage,
1321 libpq_gettext("SSL SYSCALL error: %s\n"),
1322 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1324 printfPQExpBuffer(&conn->errorMessage,
1325 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1327 return PGRES_POLLING_FAILED;
1331 char *err = SSLerrmessage(ecode);
1333 printfPQExpBuffer(&conn->errorMessage,
1334 libpq_gettext("SSL error: %s\n"),
1338 return PGRES_POLLING_FAILED;
1342 printfPQExpBuffer(&conn->errorMessage,
1343 libpq_gettext("unrecognized SSL error code: %d\n"),
1346 return PGRES_POLLING_FAILED;
1351 * We already checked the server certificate in initialize_SSL() using
1352 * SSL_CTX_set_verify(), if root.crt exists.
1355 /* get server certificate */
1356 conn->peer = SSL_get_peer_certificate(conn->ssl);
1357 if (conn->peer == NULL)
1361 err = SSLerrmessage(ERR_get_error());
1363 printfPQExpBuffer(&conn->errorMessage,
1364 libpq_gettext("certificate could not be obtained: %s\n"),
1368 return PGRES_POLLING_FAILED;
1371 if (!verify_peer_name_matches_certificate(conn))
1374 return PGRES_POLLING_FAILED;
1377 /* SSL handshake is complete */
1378 return PGRES_POLLING_OK;
1382 * Close SSL connection.
1385 pgtls_close(PGconn *conn)
1387 bool destroy_needed = false;
1392 * We can't destroy everything SSL-related here due to the possible
1393 * later calls to OpenSSL routines which may need our thread
1394 * callbacks, so set a flag here and check at the end.
1396 destroy_needed = true;
1398 SSL_shutdown(conn->ssl);
1399 SSL_free(conn->ssl);
1401 conn->ssl_in_use = false;
1406 X509_free(conn->peer);
1410 #ifdef USE_SSL_ENGINE
1413 ENGINE_finish(conn->engine);
1414 ENGINE_free(conn->engine);
1415 conn->engine = NULL;
1420 * This will remove our SSL locking hooks, if this is the last SSL
1421 * connection, which means we must wait to call it until after all SSL
1422 * calls have been made, otherwise we can end up with a race condition and
1423 * possible deadlocks.
1425 * See comments above destroy_ssl_system().
1428 destroy_ssl_system();
1433 * Obtain reason string for passed SSL errcode
1435 * ERR_get_error() is used by caller to get errcode to pass here.
1437 * Some caution is needed here since ERR_reason_error_string will
1438 * return NULL if it doesn't recognize the error code. We don't
1439 * want to return NULL ever.
1441 static char ssl_nomem[] = "out of memory allocating error description";
1443 #define SSL_ERR_LEN 128
1446 SSLerrmessage(unsigned long ecode)
1448 const char *errreason;
1451 errbuf = malloc(SSL_ERR_LEN);
1456 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1459 errreason = ERR_reason_error_string(ecode);
1460 if (errreason != NULL)
1462 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1465 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1470 SSLerrfree(char *buf)
1472 if (buf != ssl_nomem)
1476 /* ------------------------------------------------------------ */
1477 /* SSL information functions */
1478 /* ------------------------------------------------------------ */
1481 PQsslInUse(PGconn *conn)
1485 return conn->ssl_in_use;
1489 * Return pointer to OpenSSL object.
1492 PQgetssl(PGconn *conn)
1500 PQsslStruct(PGconn *conn, const char *struct_name)
1504 if (strcmp(struct_name, "OpenSSL") == 0)
1510 PQsslAttributeNames(PGconn *conn)
1512 static const char *const result[] = {
1525 PQsslAttribute(PGconn *conn, const char *attribute_name)
1529 if (conn->ssl == NULL)
1532 if (strcmp(attribute_name, "library") == 0)
1535 if (strcmp(attribute_name, "key_bits") == 0)
1537 static char sslbits_str[10];
1540 SSL_get_cipher_bits(conn->ssl, &sslbits);
1541 snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1545 if (strcmp(attribute_name, "cipher") == 0)
1546 return SSL_get_cipher(conn->ssl);
1548 if (strcmp(attribute_name, "compression") == 0)
1549 return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1551 if (strcmp(attribute_name, "protocol") == 0)
1552 return SSL_get_version(conn->ssl);
1554 return NULL; /* unknown attribute */
1558 * Private substitute BIO: this does the sending and receiving using
1559 * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1560 * functions to disable SIGPIPE and give better error messages on I/O errors.
1562 * These functions are closely modelled on the standard socket BIO in OpenSSL;
1563 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1564 * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1565 * to retry; do we need to adopt their logic for that?
1568 #ifndef HAVE_BIO_GET_DATA
1569 #define BIO_get_data(bio) (bio->ptr)
1570 #define BIO_set_data(bio, data) (bio->ptr = data)
1573 static BIO_METHOD *my_bio_methods;
1576 my_sock_read(BIO *h, char *buf, int size)
1580 res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1581 BIO_clear_retry_flags(h);
1584 /* If we were interrupted, tell caller to retry */
1590 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1594 BIO_set_retry_read(h);
1606 my_sock_write(BIO *h, const char *buf, int size)
1610 res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1611 BIO_clear_retry_flags(h);
1614 /* If we were interrupted, tell caller to retry */
1620 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1624 BIO_set_retry_write(h);
1636 my_BIO_s_socket(void)
1638 if (!my_bio_methods)
1640 BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1641 #ifdef HAVE_BIO_METH_NEW
1644 my_bio_index = BIO_get_new_index();
1645 if (my_bio_index == -1)
1647 my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1648 if (!my_bio_methods)
1651 * As of this writing, these functions never fail. But check anyway, like
1652 * OpenSSL's own examples do.
1654 if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1655 !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1656 !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1657 !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1658 !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1659 !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1660 !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1661 !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1663 BIO_meth_free(my_bio_methods);
1664 my_bio_methods = NULL;
1668 my_bio_methods = malloc(sizeof(BIO_METHOD));
1669 if (!my_bio_methods)
1671 memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1672 my_bio_methods->bread = my_sock_read;
1673 my_bio_methods->bwrite = my_sock_write;
1676 return my_bio_methods;
1679 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
1681 my_SSL_set_fd(PGconn *conn, int fd)
1685 BIO_METHOD *bio_method;
1687 bio_method = my_BIO_s_socket();
1688 if (bio_method == NULL)
1690 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1693 bio = BIO_new(bio_method);
1696 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1699 BIO_set_data(bio, conn);
1701 SSL_set_bio(conn->ssl, bio, bio);
1702 BIO_set_fd(bio, fd, BIO_NOCLOSE);