1 /*-------------------------------------------------------------------------
7 * Portions Copyright (c) 1996-2014, 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 * Read data from a secure connection.
192 * On failure, this function is responsible for putting a suitable message
193 * into conn->errorMessage. The caller must still inspect errno, but only
194 * to determine whether to continue/retry after error.
197 pgtls_read(PGconn *conn, void *ptr, size_t len)
200 int result_errno = 0;
206 n = SSL_read(conn->ssl, ptr, len);
207 err = SSL_get_error(conn->ssl, n);
213 /* Not supposed to happen, so we don't translate the msg */
214 printfPQExpBuffer(&conn->errorMessage,
215 "SSL_read failed but did not provide error information\n");
216 /* assume the connection is broken */
217 result_errno = ECONNRESET;
220 case SSL_ERROR_WANT_READ:
223 case SSL_ERROR_WANT_WRITE:
226 * Returning 0 here would cause caller to wait for read-ready,
227 * which is not correct since what SSL wants is wait for
228 * write-ready. The former could get us stuck in an infinite
229 * wait, so don't risk it; busy-loop instead.
232 case SSL_ERROR_SYSCALL:
235 result_errno = SOCK_ERRNO;
236 if (result_errno == EPIPE ||
237 result_errno == ECONNRESET)
238 printfPQExpBuffer(&conn->errorMessage,
240 "server closed the connection unexpectedly\n"
241 "\tThis probably means the server terminated abnormally\n"
242 "\tbefore or while processing the request.\n"));
244 printfPQExpBuffer(&conn->errorMessage,
245 libpq_gettext("SSL SYSCALL error: %s\n"),
246 SOCK_STRERROR(result_errno,
247 sebuf, sizeof(sebuf)));
251 printfPQExpBuffer(&conn->errorMessage,
252 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
253 /* assume the connection is broken */
254 result_errno = ECONNRESET;
260 char *errm = SSLerrmessage();
262 printfPQExpBuffer(&conn->errorMessage,
263 libpq_gettext("SSL error: %s\n"), errm);
265 /* assume the connection is broken */
266 result_errno = ECONNRESET;
270 case SSL_ERROR_ZERO_RETURN:
273 * Per OpenSSL documentation, this error code is only returned
274 * for a clean connection closure, so we should not report it
277 printfPQExpBuffer(&conn->errorMessage,
278 libpq_gettext("SSL connection has been closed unexpectedly\n"));
279 result_errno = ECONNRESET;
283 printfPQExpBuffer(&conn->errorMessage,
284 libpq_gettext("unrecognized SSL error code: %d\n"),
286 /* assume the connection is broken */
287 result_errno = ECONNRESET;
292 /* ensure we return the intended errno to caller */
293 SOCK_ERRNO_SET(result_errno);
299 * Write data to a secure connection.
301 * On failure, this function is responsible for putting a suitable message
302 * into conn->errorMessage. The caller must still inspect errno, but only
303 * to determine whether to continue/retry after error.
306 pgtls_write(PGconn *conn, const void *ptr, size_t len)
309 int result_errno = 0;
314 n = SSL_write(conn->ssl, ptr, len);
315 err = SSL_get_error(conn->ssl, n);
321 /* Not supposed to happen, so we don't translate the msg */
322 printfPQExpBuffer(&conn->errorMessage,
323 "SSL_write failed but did not provide error information\n");
324 /* assume the connection is broken */
325 result_errno = ECONNRESET;
328 case SSL_ERROR_WANT_READ:
331 * Returning 0 here causes caller to wait for write-ready,
332 * which is not really the right thing, but it's the best we
337 case SSL_ERROR_WANT_WRITE:
340 case SSL_ERROR_SYSCALL:
343 result_errno = SOCK_ERRNO;
344 if (result_errno == EPIPE || result_errno == ECONNRESET)
345 printfPQExpBuffer(&conn->errorMessage,
347 "server closed the connection unexpectedly\n"
348 "\tThis probably means the server terminated abnormally\n"
349 "\tbefore or while processing the request.\n"));
351 printfPQExpBuffer(&conn->errorMessage,
352 libpq_gettext("SSL SYSCALL error: %s\n"),
353 SOCK_STRERROR(result_errno,
354 sebuf, sizeof(sebuf)));
358 printfPQExpBuffer(&conn->errorMessage,
359 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
360 /* assume the connection is broken */
361 result_errno = ECONNRESET;
367 char *errm = SSLerrmessage();
369 printfPQExpBuffer(&conn->errorMessage,
370 libpq_gettext("SSL error: %s\n"), errm);
372 /* assume the connection is broken */
373 result_errno = ECONNRESET;
377 case SSL_ERROR_ZERO_RETURN:
380 * Per OpenSSL documentation, this error code is only returned
381 * for a clean connection closure, so we should not report it
384 printfPQExpBuffer(&conn->errorMessage,
385 libpq_gettext("SSL connection has been closed unexpectedly\n"));
386 result_errno = ECONNRESET;
390 printfPQExpBuffer(&conn->errorMessage,
391 libpq_gettext("unrecognized SSL error code: %d\n"),
393 /* assume the connection is broken */
394 result_errno = ECONNRESET;
399 /* ensure we return the intended errno to caller */
400 SOCK_ERRNO_SET(result_errno);
405 /* ------------------------------------------------------------ */
406 /* OpenSSL specific code */
407 /* ------------------------------------------------------------ */
410 * Certificate verification callback
412 * This callback allows us to log intermediate problems during
413 * verification, but there doesn't seem to be a clean way to get
414 * our PGconn * structure. So we can't log anything!
416 * This callback also allows us to override the default acceptance
417 * criteria (e.g., accepting self-signed or expired certs), but
418 * for now we accept the default checks.
421 verify_cb(int ok, X509_STORE_CTX *ctx)
428 * Check if a wildcard certificate matches the server hostname.
430 * The rule for this is:
431 * 1. We only match the '*' character as wildcard
432 * 2. We match only wildcards at the start of the string
433 * 3. The '*' character does *not* match '.', meaning that we match only
434 * a single pathname component.
435 * 4. We don't support more than one '*' in a single pattern.
437 * This is roughly in line with RFC2818, but contrary to what most browsers
438 * appear to be implementing (point 3 being the difference)
440 * Matching is always case-insensitive, since DNS is case insensitive.
443 wildcard_certificate_match(const char *pattern, const char *string)
445 int lenpat = strlen(pattern);
446 int lenstr = strlen(string);
448 /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
455 /* If pattern is longer than the string, we can never match */
458 if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
461 * If string does not end in pattern (minus the wildcard), we don't
466 if (strchr(string, '.') < string + lenstr - lenpat)
469 * If there is a dot left of where the pattern started to match, we
470 * don't match (rule 3)
474 /* String ended with pattern, and didn't have a dot before, so we match */
480 * Check if a name from a server's certificate matches the peer's hostname.
482 * Returns 1 if the name matches, and 0 if it does not. On error, returns
483 * -1, and sets the libpq error message.
485 * The name extracted from the certificate is returned in *store_name. The
486 * caller is responsible for freeing it.
489 verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
494 unsigned char *namedata;
499 /* Should not happen... */
500 if (name_entry == NULL)
502 printfPQExpBuffer(&conn->errorMessage,
503 libpq_gettext("SSL certificate's name entry is missing\n"));
508 * GEN_DNS can be only IA5String, equivalent to US ASCII.
510 * There is no guarantee the string returned from the certificate is
511 * NULL-terminated, so make a copy that is.
513 namedata = ASN1_STRING_data(name_entry);
514 len = ASN1_STRING_length(name_entry);
515 name = malloc(len + 1);
518 printfPQExpBuffer(&conn->errorMessage,
519 libpq_gettext("out of memory\n"));
522 memcpy(name, namedata, len);
526 * Reject embedded NULLs in certificate common or alternative name to
527 * prevent attacks like CVE-2009-4034.
529 if (len != strlen(name))
532 printfPQExpBuffer(&conn->errorMessage,
533 libpq_gettext("SSL certificate's name contains embedded null\n"));
537 if (pg_strcasecmp(name, conn->pghost) == 0)
539 /* Exact name match */
542 else if (wildcard_certificate_match(name, conn->pghost))
544 /* Matched wildcard name */
557 * Verify that the server certificate matches the hostname we connected to.
559 * The certificate's Common Name and Subject Alternative Names are considered.
562 verify_peer_name_matches_certificate(PGconn *conn)
564 int names_examined = 0;
565 bool found_match = false;
566 bool got_error = false;
567 char *first_name = NULL;
568 STACK_OF(GENERAL_NAME) *peer_san;
573 * If told not to verify the peer name, don't do it. Return true
574 * indicating that the verification was successful.
576 if (strcmp(conn->sslmode, "verify-full") != 0)
579 /* Check that we have a hostname to compare with. */
580 if (!(conn->pghost && conn->pghost[0] != '\0'))
582 printfPQExpBuffer(&conn->errorMessage,
583 libpq_gettext("host name must be specified for a verified SSL connection\n"));
588 * First, get the Subject Alternative Names (SANs) from the certificate,
589 * and compare them against the originally given hostname.
591 peer_san = (STACK_OF(GENERAL_NAME) *)
592 X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
596 int san_len = sk_GENERAL_NAME_num(peer_san);
598 for (i = 0; i < san_len; i++)
600 const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
602 if (name->type == GEN_DNS)
607 rc = verify_peer_name_matches_certificate_name(conn,
618 first_name = alt_name;
623 if (found_match || got_error)
626 sk_GENERAL_NAME_free(peer_san);
629 * If there is no subjectAltName extension of type dNSName, check the
632 * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
633 * dNSName is present, the CN must be ignored.)
635 if (names_examined == 0)
637 X509_NAME *subject_name;
639 subject_name = X509_get_subject_name(conn->peer);
640 if (subject_name != NULL)
644 cn_index = X509_NAME_get_index_by_NID(subject_name,
649 rc = verify_peer_name_matches_certificate_name(
651 X509_NAME_ENTRY_get_data(
652 X509_NAME_get_entry(subject_name, cn_index)),
663 if (!found_match && !got_error)
666 * No match. Include the name from the server certificate in the
667 * error message, to aid debugging broken configurations. If there
668 * are multiple names, only print the first one to avoid an overly
669 * long error message.
671 if (names_examined > 1)
673 printfPQExpBuffer(&conn->errorMessage,
674 libpq_ngettext("server certificate for \"%s\" (and %d other name) does not match host name \"%s\"\n",
675 "server certificate for \"%s\" (and %d other names) does not match host name \"%s\"\n",
677 first_name, names_examined - 1, conn->pghost);
679 else if (names_examined == 1)
681 printfPQExpBuffer(&conn->errorMessage,
682 libpq_gettext("server certificate for \"%s\" does not match host name \"%s\"\n"),
683 first_name, conn->pghost);
687 printfPQExpBuffer(&conn->errorMessage,
688 libpq_gettext("could not get server's hostname from server certificate\n"));
696 return found_match && !got_error;
699 #ifdef ENABLE_THREAD_SAFETY
701 * Callback functions for OpenSSL internal locking
705 pq_threadidcallback(void)
708 * This is not standards-compliant. pthread_self() returns pthread_t, and
709 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
710 * it, so we have to do it.
712 return (unsigned long) pthread_self();
715 static pthread_mutex_t *pq_lockarray;
718 pq_lockingcallback(int mode, int n, const char *file, int line)
720 if (mode & CRYPTO_LOCK)
722 if (pthread_mutex_lock(&pq_lockarray[n]))
723 PGTHREAD_ERROR("failed to lock mutex");
727 if (pthread_mutex_unlock(&pq_lockarray[n]))
728 PGTHREAD_ERROR("failed to unlock mutex");
731 #endif /* ENABLE_THREAD_SAFETY */
734 * Initialize SSL system, in particular creating the SSL_context object
735 * that will be shared by all SSL-using connections in this process.
737 * In threadsafe mode, this includes setting up libcrypto callback functions
738 * to do thread locking.
740 * If the caller has told us (through PQinitOpenSSL) that he's taking care
741 * of libcrypto, we expect that callbacks are already set, and won't try to
744 * The conn parameter is only used to be able to pass back an error
745 * message - no connection-local setup is made here.
747 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
750 pgtls_init(PGconn *conn)
752 #ifdef ENABLE_THREAD_SAFETY
754 /* Also see similar code in fe-connect.c, default_threadlock() */
755 if (ssl_config_mutex == NULL)
757 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
758 /* loop, another thread own the lock */ ;
759 if (ssl_config_mutex == NULL)
761 if (pthread_mutex_init(&ssl_config_mutex, NULL))
764 InterlockedExchange(&win32_ssl_create_mutex, 0);
767 if (pthread_mutex_lock(&ssl_config_mutex))
770 if (pq_init_crypto_lib)
773 * If necessary, set up an array to hold locks for libcrypto.
774 * libcrypto will tell us how big to make this array.
776 if (pq_lockarray == NULL)
780 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
783 pthread_mutex_unlock(&ssl_config_mutex);
786 for (i = 0; i < CRYPTO_num_locks(); i++)
788 if (pthread_mutex_init(&pq_lockarray[i], NULL))
792 pthread_mutex_unlock(&ssl_config_mutex);
798 if (ssl_open_connections++ == 0)
800 /* These are only required for threaded libcrypto applications */
801 CRYPTO_set_id_callback(pq_threadidcallback);
802 CRYPTO_set_locking_callback(pq_lockingcallback);
805 #endif /* ENABLE_THREAD_SAFETY */
811 #if SSLEAY_VERSION_NUMBER >= 0x00907000L
812 OPENSSL_config(NULL);
815 SSL_load_error_strings();
819 * We use SSLv23_method() because it can negotiate use of the highest
820 * mutually supported protocol version, while alternatives like
821 * TLSv1_2_method() permit only one specific version. Note that we
822 * don't actually allow SSL v2 or v3, only TLS protocols (see below).
824 SSL_context = SSL_CTX_new(SSLv23_method());
827 char *err = SSLerrmessage();
829 printfPQExpBuffer(&conn->errorMessage,
830 libpq_gettext("could not create SSL context: %s\n"),
833 #ifdef ENABLE_THREAD_SAFETY
834 pthread_mutex_unlock(&ssl_config_mutex);
839 /* Disable old protocol versions */
840 SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
843 * Disable OpenSSL's moving-write-buffer sanity check, because it
844 * causes unnecessary failures in nonblocking send cases.
846 SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
849 #ifdef ENABLE_THREAD_SAFETY
850 pthread_mutex_unlock(&ssl_config_mutex);
856 * This function is needed because if the libpq library is unloaded
857 * from the application, the callback functions will no longer exist when
858 * libcrypto is used by other parts of the system. For this reason,
859 * we unregister the callback functions when the last libpq
860 * connection is closed. (The same would apply for OpenSSL callbacks
863 * Callbacks are only set when we're compiled in threadsafe mode, so
864 * we only need to remove them in this case.
867 destroy_ssl_system(void)
869 #ifdef ENABLE_THREAD_SAFETY
870 /* Mutex is created in initialize_ssl_system() */
871 if (pthread_mutex_lock(&ssl_config_mutex))
874 if (pq_init_crypto_lib && ssl_open_connections > 0)
875 --ssl_open_connections;
877 if (pq_init_crypto_lib && ssl_open_connections == 0)
879 /* No connections left, unregister libcrypto callbacks */
880 CRYPTO_set_locking_callback(NULL);
881 CRYPTO_set_id_callback(NULL);
884 * We don't free the lock array or the SSL_context. If we get another
885 * connection in this process, we will just re-use them with the
888 * This means we leak a little memory on repeated load/unload of the
893 pthread_mutex_unlock(&ssl_config_mutex);
898 * Initialize (potentially) per-connection SSL data, namely the
899 * client certificate, private key, and trusted CA certs.
901 * conn->ssl must already be created. It receives the connection's client
902 * certificate and private key. Note however that certificates also get
903 * loaded into the SSL_context object, and are therefore accessible to all
904 * connections in this process. This should be OK as long as there aren't
905 * any hash collisions among the certs.
907 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
910 initialize_SSL(PGconn *conn)
913 char homedir[MAXPGPATH];
914 char fnbuf[MAXPGPATH];
918 EVP_PKEY *pkey = NULL;
921 * We'll need the home directory if any of the relevant parameters are
922 * defaulted. If pqGetHomeDirectory fails, act as though none of the
923 * files could be found.
925 if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
926 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
927 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
928 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
929 have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
930 else /* won't need it */
931 have_homedir = false;
933 /* Read the client certificate file */
934 if (conn->sslcert && strlen(conn->sslcert) > 0)
935 strncpy(fnbuf, conn->sslcert, sizeof(fnbuf));
936 else if (have_homedir)
937 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
941 if (fnbuf[0] == '\0')
943 /* no home directory, proceed without a client cert */
946 else if (stat(fnbuf, &buf) != 0)
949 * If file is not present, just go on without a client cert; server
950 * might or might not accept the connection. Any other error,
951 * however, is grounds for complaint.
953 if (errno != ENOENT && errno != ENOTDIR)
955 printfPQExpBuffer(&conn->errorMessage,
956 libpq_gettext("could not open certificate file \"%s\": %s\n"),
957 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
965 * Cert file exists, so load it. Since OpenSSL doesn't provide the
966 * equivalent of "SSL_use_certificate_chain_file", we actually have to
967 * load the file twice. The first call loads any extra certs after
968 * the first one into chain-cert storage associated with the
969 * SSL_context. The second call loads the first cert (only) into the
970 * SSL object, where it will be correctly paired with the private key
971 * we load below. We do it this way so that each connection
972 * understands which subject cert to present, in case different
973 * sslcert settings are used for different connections in the same
976 * NOTE: This function may also modify our SSL_context and therefore
977 * we have to lock around this call and any places where we use the
978 * SSL_context struct.
980 #ifdef ENABLE_THREAD_SAFETY
983 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
985 printfPQExpBuffer(&conn->errorMessage,
986 libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
990 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
992 char *err = SSLerrmessage();
994 printfPQExpBuffer(&conn->errorMessage,
995 libpq_gettext("could not read certificate file \"%s\": %s\n"),
999 #ifdef ENABLE_THREAD_SAFETY
1000 pthread_mutex_unlock(&ssl_config_mutex);
1005 if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1007 char *err = SSLerrmessage();
1009 printfPQExpBuffer(&conn->errorMessage,
1010 libpq_gettext("could not read certificate file \"%s\": %s\n"),
1013 #ifdef ENABLE_THREAD_SAFETY
1014 pthread_mutex_unlock(&ssl_config_mutex);
1019 /* need to load the associated private key, too */
1022 #ifdef ENABLE_THREAD_SAFETY
1023 pthread_mutex_unlock(&ssl_config_mutex);
1028 * Read the SSL key. If a key is specified, treat it as an engine:key
1029 * combination if there is colon present - we don't support files with
1030 * colon in the name. The exception is if the second character is a colon,
1031 * in which case it can be a Windows filename with drive specification.
1033 if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1035 #ifdef USE_SSL_ENGINE
1036 if (strchr(conn->sslkey, ':')
1038 && conn->sslkey[1] != ':'
1042 /* Colon, but not in second character, treat as engine:key */
1043 char *engine_str = strdup(conn->sslkey);
1046 if (engine_str == NULL)
1048 printfPQExpBuffer(&conn->errorMessage,
1049 libpq_gettext("out of memory\n"));
1053 /* cannot return NULL because we already checked before strdup */
1054 engine_colon = strchr(engine_str, ':');
1056 *engine_colon = '\0'; /* engine_str now has engine name */
1057 engine_colon++; /* engine_colon now has key name */
1059 conn->engine = ENGINE_by_id(engine_str);
1060 if (conn->engine == NULL)
1062 char *err = SSLerrmessage();
1064 printfPQExpBuffer(&conn->errorMessage,
1065 libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1072 if (ENGINE_init(conn->engine) == 0)
1074 char *err = SSLerrmessage();
1076 printfPQExpBuffer(&conn->errorMessage,
1077 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1080 ENGINE_free(conn->engine);
1081 conn->engine = NULL;
1086 pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1090 char *err = SSLerrmessage();
1092 printfPQExpBuffer(&conn->errorMessage,
1093 libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1094 engine_colon, engine_str, err);
1096 ENGINE_finish(conn->engine);
1097 ENGINE_free(conn->engine);
1098 conn->engine = NULL;
1102 if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1104 char *err = SSLerrmessage();
1106 printfPQExpBuffer(&conn->errorMessage,
1107 libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1108 engine_colon, engine_str, err);
1110 ENGINE_finish(conn->engine);
1111 ENGINE_free(conn->engine);
1112 conn->engine = NULL;
1119 fnbuf[0] = '\0'; /* indicate we're not going to load from a
1123 #endif /* USE_SSL_ENGINE */
1125 /* PGSSLKEY is not an engine, treat it as a filename */
1126 strncpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1129 else if (have_homedir)
1131 /* No PGSSLKEY specified, load default file */
1132 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1137 if (have_cert && fnbuf[0] != '\0')
1139 /* read the client key from file */
1141 if (stat(fnbuf, &buf) != 0)
1143 printfPQExpBuffer(&conn->errorMessage,
1144 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1149 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1151 printfPQExpBuffer(&conn->errorMessage,
1152 libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1158 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1160 char *err = SSLerrmessage();
1162 printfPQExpBuffer(&conn->errorMessage,
1163 libpq_gettext("could not load private key file \"%s\": %s\n"),
1170 /* verify that the cert and key go together */
1172 SSL_check_private_key(conn->ssl) != 1)
1174 char *err = SSLerrmessage();
1176 printfPQExpBuffer(&conn->errorMessage,
1177 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1184 * If the root cert file exists, load it so we can perform certificate
1185 * verification. If sslmode is "verify-full" we will also do further
1186 * verification after the connection has been completed.
1188 if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1189 strncpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1190 else if (have_homedir)
1191 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1195 if (fnbuf[0] != '\0' &&
1196 stat(fnbuf, &buf) == 0)
1198 X509_STORE *cvstore;
1200 #ifdef ENABLE_THREAD_SAFETY
1203 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
1205 printfPQExpBuffer(&conn->errorMessage,
1206 libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
1210 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1212 char *err = SSLerrmessage();
1214 printfPQExpBuffer(&conn->errorMessage,
1215 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1218 #ifdef ENABLE_THREAD_SAFETY
1219 pthread_mutex_unlock(&ssl_config_mutex);
1224 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1226 if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1227 strncpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
1228 else if (have_homedir)
1229 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1233 /* Set the flags to check against the complete CRL chain */
1234 if (fnbuf[0] != '\0' &&
1235 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
1237 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
1238 #ifdef X509_V_FLAG_CRL_CHECK
1239 X509_STORE_set_flags(cvstore,
1240 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1242 char *err = SSLerrmessage();
1244 printfPQExpBuffer(&conn->errorMessage,
1245 libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
1248 #ifdef ENABLE_THREAD_SAFETY
1249 pthread_mutex_unlock(&ssl_config_mutex);
1254 /* if not found, silently ignore; we do not require CRL */
1256 #ifdef ENABLE_THREAD_SAFETY
1257 pthread_mutex_unlock(&ssl_config_mutex);
1260 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1265 * stat() failed; assume root file doesn't exist. If sslmode is
1266 * verify-ca or verify-full, this is an error. Otherwise, continue
1267 * without performing any server cert verification.
1269 if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1272 * The only way to reach here with an empty filename is if
1273 * pqGetHomeDirectory failed. That's a sufficiently unusual case
1274 * that it seems worth having a specialized error message for it.
1276 if (fnbuf[0] == '\0')
1277 printfPQExpBuffer(&conn->errorMessage,
1278 libpq_gettext("could not get home directory to locate root certificate file\n"
1279 "Either provide the file or change sslmode to disable server certificate verification.\n"));
1281 printfPQExpBuffer(&conn->errorMessage,
1282 libpq_gettext("root certificate file \"%s\" does not exist\n"
1283 "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1289 * If the OpenSSL version used supports it (from 1.0.0 on) and the user
1290 * requested it, disable SSL compression.
1292 #ifdef SSL_OP_NO_COMPRESSION
1293 if (conn->sslcompression && conn->sslcompression[0] == '0')
1295 SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1303 * Attempt to negotiate SSL connection.
1305 static PostgresPollingStatusType
1306 open_client_SSL(PGconn *conn)
1310 r = SSL_connect(conn->ssl);
1313 int err = SSL_get_error(conn->ssl, r);
1317 case SSL_ERROR_WANT_READ:
1318 return PGRES_POLLING_READING;
1320 case SSL_ERROR_WANT_WRITE:
1321 return PGRES_POLLING_WRITING;
1323 case SSL_ERROR_SYSCALL:
1328 printfPQExpBuffer(&conn->errorMessage,
1329 libpq_gettext("SSL SYSCALL error: %s\n"),
1330 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1332 printfPQExpBuffer(&conn->errorMessage,
1333 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1335 return PGRES_POLLING_FAILED;
1339 char *err = SSLerrmessage();
1341 printfPQExpBuffer(&conn->errorMessage,
1342 libpq_gettext("SSL error: %s\n"),
1346 return PGRES_POLLING_FAILED;
1350 printfPQExpBuffer(&conn->errorMessage,
1351 libpq_gettext("unrecognized SSL error code: %d\n"),
1354 return PGRES_POLLING_FAILED;
1359 * We already checked the server certificate in initialize_SSL() using
1360 * SSL_CTX_set_verify(), if root.crt exists.
1363 /* get server certificate */
1364 conn->peer = SSL_get_peer_certificate(conn->ssl);
1365 if (conn->peer == NULL)
1367 char *err = SSLerrmessage();
1369 printfPQExpBuffer(&conn->errorMessage,
1370 libpq_gettext("certificate could not be obtained: %s\n"),
1374 return PGRES_POLLING_FAILED;
1377 if (!verify_peer_name_matches_certificate(conn))
1380 return PGRES_POLLING_FAILED;
1383 /* SSL handshake is complete */
1384 return PGRES_POLLING_OK;
1388 * Close SSL connection.
1391 pgtls_close(PGconn *conn)
1393 bool destroy_needed = false;
1398 * We can't destroy everything SSL-related here due to the possible
1399 * later calls to OpenSSL routines which may need our thread
1400 * callbacks, so set a flag here and check at the end.
1402 destroy_needed = true;
1404 SSL_shutdown(conn->ssl);
1405 SSL_free(conn->ssl);
1407 conn->ssl_in_use = false;
1412 X509_free(conn->peer);
1416 #ifdef USE_SSL_ENGINE
1419 ENGINE_finish(conn->engine);
1420 ENGINE_free(conn->engine);
1421 conn->engine = NULL;
1426 * This will remove our SSL locking hooks, if this is the last SSL
1427 * connection, which means we must wait to call it until after all SSL
1428 * calls have been made, otherwise we can end up with a race condition and
1429 * possible deadlocks.
1431 * See comments above destroy_ssl_system().
1434 destroy_ssl_system();
1439 * Obtain reason string for last SSL error
1441 * Some caution is needed here since ERR_reason_error_string will
1442 * return NULL if it doesn't recognize the error code. We don't
1443 * want to return NULL ever.
1445 static char ssl_nomem[] = "out of memory allocating error description";
1447 #define SSL_ERR_LEN 128
1452 unsigned long errcode;
1453 const char *errreason;
1456 errbuf = malloc(SSL_ERR_LEN);
1459 errcode = ERR_get_error();
1462 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1465 errreason = ERR_reason_error_string(errcode);
1466 if (errreason != NULL)
1468 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1471 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
1476 SSLerrfree(char *buf)
1478 if (buf != ssl_nomem)
1483 * Return pointer to OpenSSL object.
1486 PQgetssl(PGconn *conn)
1495 * Private substitute BIO: this does the sending and receiving using send() and
1496 * recv() instead. This is so that we can enable and disable interrupts
1497 * just while calling recv(). We cannot have interrupts occurring while
1498 * the bulk of openssl runs, because it uses malloc() and possibly other
1499 * non-reentrant libc facilities. We also need to call send() and recv()
1500 * directly so it gets passed through the socket/signals layer on Win32.
1502 * These functions are closely modelled on the standard socket BIO in OpenSSL;
1503 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1504 * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1505 * to retry; do we need to adopt their logic for that?
1508 static bool my_bio_initialized = false;
1509 static BIO_METHOD my_bio_methods;
1512 my_sock_read(BIO *h, char *buf, int size)
1517 res = pqsecure_raw_read((PGconn *) h->ptr, buf, size);
1519 BIO_clear_retry_flags(h);
1527 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1531 BIO_set_retry_read(h);
1544 my_sock_write(BIO *h, const char *buf, int size)
1549 res = pqsecure_raw_write((PGconn *) h->ptr, buf, size);
1551 BIO_clear_retry_flags(h);
1554 if (save_errno == EINTR)
1556 BIO_set_retry_write(h);
1564 my_BIO_s_socket(void)
1566 if (!my_bio_initialized)
1568 memcpy(&my_bio_methods, BIO_s_socket(), sizeof(BIO_METHOD));
1569 my_bio_methods.bread = my_sock_read;
1570 my_bio_methods.bwrite = my_sock_write;
1571 my_bio_initialized = true;
1573 return &my_bio_methods;
1576 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
1578 my_SSL_set_fd(PGconn *conn, int fd)
1583 bio = BIO_new(my_BIO_s_socket());
1586 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1589 /* Use 'ptr' to store pointer to PGconn */
1592 SSL_set_bio(conn->ssl, bio, bio);
1593 BIO_set_fd(bio, fd, BIO_NOCLOSE);